ocpp-ws-io 2.1.15 → 2.2.0

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/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import st,{resolve}from'path';import {fileURLToPath}from'url';import {EventEmitter}from'events';import {cpus,totalmem,freemem}from'os';import re,{WebSocketServer}from'ws';import {prettyTransport,consoleTransport,createLogger}from'voltlog-io';import jt from'ajv';import Rt from'ajv-formats';import {randomUUID}from'crypto';import kt,{createServer as createServer$1}from'http';import {createServer}from'https';import {TLSSocket}from'tls';import {isIPv4}from'net';import {Worker}from'worker_threads';var ot=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ke=()=>fileURLToPath(import.meta.url),pt=()=>st.dirname(ke()),g=pt(),y=ke();var Te=class{_channels=new Map;async publish(e,t){let i=this._channels.get(e);if(i)for(let n of i)try{n(t);}catch{}}async publishBatch(e){for(let t of e)await this.publish(t.channel,t.data);}async subscribe(e,t){this._channels.has(e)||this._channels.set(e,new Set),this._channels.get(e)?.add(t);}async unsubscribe(e){this._channels.delete(e);}async disconnect(){this._channels.clear(),this._presence.clear();}_presence=new Map;async setPresence(e,t,i){this._presence.set(e,t);}async getPresence(e){return this._presence.get(e)||null}async getPresenceBatch(e){return e.map(t=>this._presence.get(t)||null)}async removePresence(e){this._presence.delete(e);}async setPresenceBatch(e){for(let{identity:t,nodeId:i}of e)this._presence.set(t,i);}};function ct(s){return s}var ve=class{_cluster;_subscriber;_handlers=new Map;constructor(e){try{let{createRequire:t}=ot("module"),n=t(y)("ioredis"),r=e.redisOptions??{};e.natMap&&(r.natMap=e.natMap),this._cluster=new n.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber=new n.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber.on("message",(a,o)=>{let d=this._handlers.get(a);d&&d(o);});}catch{throw new Error("ClusterDriver requires 'ioredis' as a peer dependency. Install it with: npm i ioredis")}}async publish(e,t){await this._cluster.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this._subscriber.subscribe(e);}async unsubscribe(e){await this._subscriber.unsubscribe(e),this._handlers.delete(e);}async set(e,t,i){i?await this._cluster.set(e,t,"EX",i):await this._cluster.set(e,t);}async get(e){return await this._cluster.get(e)||null}async mget(e){if(e.length===0)return [];try{return await this._cluster.mget(...e)}catch{return await Promise.all(e.map(t=>this.get(t)))}}async del(e){await this._cluster.del(e);}async xadd(e,t,i){let n=[];i&&n.push("MAXLEN","~",i.toString()),n.push("*");for(let[r,a]of Object.entries(t))n.push(r,a);return await this._cluster.xadd(e,...n)}async xaddBatch(e,t){if(e.length===0)return;let i=this._cluster.pipeline();for(let n of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(n.args))r.push(a,o);i.xadd(n.stream,...r);}await i.exec();}async xread(e,t,i){let n=[];t&&n.push("COUNT",t),typeof i=="number"&&n.push("BLOCK",i),n.push("STREAMS");for(let a of e)n.push(a.key);for(let a of e)n.push(a.id);let r=await this._cluster.xread(...n);return r?r.map(([a,o])=>({stream:a,messages:o.map(([d,p])=>{let c={};for(let l=0;l<p.length;l+=2)c[p[l]]=p[l+1];return {id:d,data:c}})})):null}async xlen(e){return await this._cluster.xlen(e)}async disconnect(){this._handlers.clear(),await Promise.allSettled([this._cluster.quit(),this._subscriber.quit()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this._cluster.pipeline();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,"EX",r);await t.exec();}async expire(e,t){await this._cluster.expire(e,t);}onError(e){return this._cluster.on("error",e),()=>this._cluster.removeListener("error",e)}onReconnect(e){return this._cluster.on("reconnecting",e),()=>this._cluster.removeListener("reconnecting",e)}};var Ce=class{constructor(e,t,i){this.pub=e;this.sub=t;this.blocking=i;this.sub.on&&this.sub.on("message",(n,r)=>{let a=this._handlers.get(n);a&&a(r);});}_handlers=new Map;async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this.sub.subscribe(e);}async unsubscribe(e){await this.sub.unsubscribe(e),this._handlers.delete(e);}async set(e,t,i){i?await this.pub.set(e,t,"EX",i):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mget(...e)}async del(e){await this.pub.del(e);}async xadd(e,t,i){let n=[];i&&n.push("MAXLEN","~",i.toString()),n.push("*");for(let[r,a]of Object.entries(t))n.push(r,a);return await this.pub.xadd(e,...n)}async xaddBatch(e,t){if(e.length===0)return;let i=this.pub.pipeline();for(let n of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(n.args))r.push(a,o);i.xadd(n.stream,...r);}await i.exec();}async xread(e,t,i){let n=[];t&&n.push("COUNT",t),typeof i=="number"&&n.push("BLOCK",i),n.push("STREAMS"),e.forEach(o=>{n.push(o.key);}),e.forEach(o=>{n.push(o.id);});let a=await(i&&this.blocking?this.blocking:this.pub).xread(...n);return a?a.map(([o,d])=>({stream:o,messages:d.map(([p,c])=>{let l={};for(let m=0;m<c.length;m+=2)l[c[m]]=c[m+1];return {id:p,data:l}})})):null}async xlen(e){return await this.pub.xlen(e)}async disconnect(){this._handlers.clear();let e=async t=>{t.quit?await t.quit():t.disconnect&&await t.disconnect();};await Promise.all([e(this.pub),e(this.sub)]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.pipeline();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,"EX",r);await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}},be=class{constructor(e,t,i){this.pub=e;this.sub=t;this.blocking=i;}async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){await this.sub.subscribe(e,t);}async unsubscribe(e){await this.sub.unsubscribe(e);}async set(e,t,i){i?await this.pub.set(e,t,{EX:i}):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mGet(e)}async del(e){await this.pub.del(e);}async xadd(e,t,i){return await this.pub.xAdd(e,"*",t,{TRIM:i?{strategy:"MAXLEN",strategyModifier:"~",threshold:i}:void 0})}async xaddBatch(e,t){if(e.length===0)return;let i=this.pub.multi();for(let n of e)i.xAdd(n.stream,"*",n.args,{TRIM:t?{strategy:"MAXLEN",strategyModifier:"~",threshold:t}:void 0});await i.exec();}async xread(e,t,i){let n={};t&&(n.COUNT=t),typeof i=="number"&&(n.BLOCK=i);let r=e.map(d=>({key:d.key,id:d.id})),o=await(i&&this.blocking?this.blocking:this.pub).xRead(r,n);return !o||o.length===0?null:o.map(d=>({stream:d.name,messages:d.messages.map(p=>({id:p.id,data:p.message}))}))}async xlen(e){return await this.pub.xLen(e)}async disconnect(){await Promise.all([this.pub.disconnect(),this.sub.disconnect()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.multi();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,{EX:r});await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}};function Fe(s,e,t){return e.isOpen!==void 0&&typeof e.subscribe=="function"?new be(s,e,t):new Ce(s,e,t)}var Pe=class{_driver;_prefix;_streamMaxLen;_streamTtlSeconds;_presenceTtlSeconds;_handlers=new Map;_streamOffsets=new Map;_streams=new Set;_polling=false;_closed=false;_sequenceCounters=new Map;_unsubError;_unsubReconnect;_presenceCache=new Map;_driverPool;_nextPoolIndex;constructor(e){this._prefix=e.prefix??"ocpp-ws-io:",this._streamMaxLen=e.streamMaxLen??1e3,this._streamTtlSeconds=e.streamTtlSeconds??300,this._presenceTtlSeconds=e.presenceTtlSeconds??300,this._driver=Fe(e.pubClient,e.subClient,e.blockingClient);let t=e.poolSize??1;if(this._driverPool=[this._driver],this._nextPoolIndex=0,t>1&&e.driverFactory)for(let i=1;i<t;i++)this._driverPool.push(e.driverFactory());this._driver.onError&&(this._unsubError=this._driver.onError(i=>{console.error("[RedisAdapter] Redis error:",i.message);})),this._driver.onReconnect&&(this._unsubReconnect=this._driver.onReconnect(()=>{this._rehydratePresence().catch(()=>{});}));}_getPoolDriver(){if(this._driverPool.length===1)return this._driver;let e=this._driverPool[this._nextPoolIndex];return this._nextPoolIndex=(this._nextPoolIndex+1)%this._driverPool.length,e}async publish(e,t){let i=this._prefix+e,n=t;if(n&&typeof n=="object"&&e.startsWith("ocpp:node:")){let a=(this._sequenceCounters.get(e)??0)+1;this._sequenceCounters.set(e,a),n.__seq=a;}let r=JSON.stringify(t);if(e.startsWith("ocpp:node:")){let a=this._getPoolDriver();await a.xadd(i,{message:r},this._streamMaxLen),await a.expire(i,this._streamTtlSeconds).catch(()=>{});}else await this._getPoolDriver().publish(i,r);}async publishBatch(e){let t=[],i=[];for(let r of e){let a=this._prefix+r.channel,o=JSON.stringify(r.data);r.channel.startsWith("ocpp:node:")?t.push({stream:a,args:{message:o}}):i.push({channel:a,message:o});}let n=[];t.length>0&&n.push(this._getPoolDriver().xaddBatch(t,this._streamMaxLen)),i.length>0&&n.push(Promise.all(i.map(r=>this._getPoolDriver().publish(r.channel,r.message))).then(()=>{})),await Promise.all(n);}async subscribe(e,t){if(!this._handlers.has(e)){this._handlers.set(e,new Set);let i=this._prefix+e;e.startsWith("ocpp:node:")?this._streams.has(i)||(this._streams.add(i),this._streamOffsets.set(i,"0"),this._ensurePolling()):await this._driver.subscribe(i,n=>{this._handleMessage(e,n);});}this._handlers.get(e)?.add(t);}async unsubscribe(e){let t=this._prefix+e;this._streams.has(t)?(this._streams.delete(t),this._streamOffsets.delete(t)):await this._driver.unsubscribe(t),this._handlers.delete(e);}async disconnect(){this._closed=true,this._handlers.clear(),this._streams.clear(),this._presenceCache.clear(),this._sequenceCounters.clear(),this._unsubError&&this._unsubError(),this._unsubReconnect&&this._unsubReconnect(),await Promise.allSettled(this._driverPool.map(e=>e.disconnect()));}_handleMessage(e,t){let i=this._handlers.get(e);if(!i)return;let n;try{n=JSON.parse(t);}catch{n=t;}for(let r of i)try{r(n);}catch{}}_ensurePolling(){this._polling||this._closed||(this._polling=true,this._pollLoop().catch(()=>{this._polling=false;}));}async _pollLoop(){for(;!this._closed;){if(this._streams.size===0){await new Promise(t=>setTimeout(t,1e3));continue}let e=Array.from(this._streams).map(t=>({key:t,id:this._streamOffsets.get(t)||"$"}));try{let t=await this._driver.xread(e,void 0,1e3);if(t)for(let i of t){let n=i.stream.replace(this._prefix,"");for(let r of i.messages){this._streamOffsets.set(i.stream,r.id);let a=r.data.message;a&&this._handleMessage(n,a);}}}catch{await new Promise(i=>setTimeout(i,1e3));}}this._polling=false;}async setPresence(e,t,i){let n=`${this._prefix}presence:${e}`;this._presenceCache.set(e,{nodeId:t,ttl:i}),await this._driver.set(n,t,i);}async getPresence(e){let t=`${this._prefix}presence:${e}`;return await this._driver.get(t)}async getPresenceBatch(e){if(e.length===0)return [];let t=e.map(i=>`${this._prefix}presence:${i}`);return this._driver.mget?await this._driver.mget(t):await Promise.all(t.map(i=>this._driver.get(i)))}async removePresence(e){let t=`${this._prefix}presence:${e}`;await this._driver.del(t);}async metrics(){let e=0,t={};for(let i of this._streams)try{let n=await this._driver.xlen(i);e+=n,t[i]=n;}catch{t[i]=-1;}return {pendingMessages:e,activeStreams:this._streams.size,streamDetails:t}}async setPresenceBatch(e){if(e.length===0)return;let t=e.map(({identity:i,nodeId:n,ttl:r})=>{let a=`${this._prefix}presence:${i}`,o=r??this._presenceTtlSeconds;return this._presenceCache.set(i,{nodeId:n,ttl:o}),{key:a,value:n,ttlSeconds:o}});await this._driver.setPresenceBatch(t);}async _rehydratePresence(){if(this._presenceCache.size===0)return;let e=Array.from(this._presenceCache.entries()).map(([t,{nodeId:i,ttl:n}])=>({key:`${this._prefix}presence:${t}`,value:i,ttlSeconds:n}));await this._driver.setPresenceBatch(e);}};var H=class extends EventEmitter{_cpuThreshold;_memThreshold;_cooldownMs;_sampleInterval;_timer=null;_lastOverloadTime=0;_multiplier=1;_prevCpuUsage=null;_prevTimestamp=0;constructor(e={}){super(),this._cpuThreshold=e.cpuThresholdPercent??70,this._memThreshold=e.memThresholdPercent??85,this._cooldownMs=e.cooldownMs??1e4,this._sampleInterval=e.sampleIntervalMs??2e3;}get multiplier(){return this._multiplier}start(){this._timer||(this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=Date.now(),this._timer=setInterval(()=>this._sample(),this._sampleInterval),this._timer.unref&&this._timer.unref());}stop(){this._timer&&(clearInterval(this._timer),this._timer=null),this._multiplier=1;}_sample(){let e=Date.now(),t=process.cpuUsage(this._prevCpuUsage??void 0),i=e-this._prevTimestamp,n=(t.user+t.system)/1e3/i/cpus().length*100;this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=e;let r=totalmem(),a=freemem(),o=(r-a)/r*100,d=n>this._cpuThreshold,p=o>this._memThreshold,c=this._multiplier;d||p?(this._lastOverloadTime=e,this._multiplier=Math.max(.25,this._multiplier*.5)):e-this._lastOverloadTime>this._cooldownMs&&(this._multiplier=Math.min(1,this._multiplier+.1)),this._multiplier!==c&&this.emit("adapted",{multiplier:this._multiplier,cpuPercent:Math.round(n*100)/100,memPercent:Math.round(o*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};var F=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},z=class extends Error{statusCode;headers;constructor(e,t,i={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=i;}},Se=class extends Error{constructor(e="WebSocket upgrade failed"){super(e),this.name="WebsocketUpgradeError";}},C=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},R=class extends C{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},B=class extends C{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},G=class extends C{rpcErrorCode="InternalError";rpcErrorMessage="An internal error occurred and the receiver was not able to process the requested action successfully";constructor(e,t={}){super(e,t),this.name="RPCInternalError";}},J=class extends C{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},K=class extends C{rpcErrorCode="SecurityError";rpcErrorMessage="During the processing of action a security issue occurred preventing receiver from completing the action successfully";constructor(e,t={}){super(e,t),this.name="RPCSecurityError";}},X=class extends C{rpcErrorCode="FormationViolation";rpcErrorMessage="Payload for action is syntactically incorrect or not conform the PDU structure for action";constructor(e,t={}){super(e,t),this.name="RPCFormationViolationError";}},Q=class extends C{rpcErrorCode="FormatViolation";rpcErrorMessage="Payload is syntactically correct but at least one field contains an invalid value";constructor(e,t={}){super(e,t),this.name="RPCFormatViolationError";}},Y=class extends C{rpcErrorCode="PropertyConstraintViolation";rpcErrorMessage="Payload is syntactically correct but at least one of the fields violates data type constraints";constructor(e,t={}){super(e,t),this.name="RPCPropertyConstraintViolationError";}},Z=class extends C{rpcErrorCode="OccurrenceConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates occurrence constraints";constructor(e,t={}){super(e,t),this.name="RPCOccurrenceConstraintViolationError";}},ee=class extends C{rpcErrorCode="TypeConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates type constraints";constructor(e,t={}){super(e,t),this.name="RPCTypeConstraintViolationError";}},L=class extends C{rpcErrorCode="MessageTypeNotSupported";rpcErrorMessage="A message with a Message Type Number received that is not supported by this implementation";constructor(e,t={}){super(e,t),this.name="RPCMessageTypeNotSupportedError";}},te=class extends C{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function gt(s){return s}function yt(s){return s}function Tt(s){return s}function vt(s){return s}function Ct(...s){return async e=>{let t=false,i=false,n=o=>{t=true,e.accept(o);},r=(o,d)=>(i=true,e.reject(o,d)),a={...e,accept:n,reject:r};try{for(let o of s){if(e.signal.aborted||t||i)break;let d=o(a);if(d instanceof Promise&&await d,t||i)break}!t&&!i&&r(401,"Unauthorized (All composeAuth handlers passed without accepting)");}catch{i||r(500,"Internal Server Error during auth compose execution");}}}function Ie(s,e,t={}){let i=typeof t=="object"?t:{},{exchangeLog:n=false,prettify:r=false}=i;return async(a,o)=>{let d=Date.now(),p=a.method,c=n?"info":"debug";switch(a.type){case "incoming_call":n&&r?s[c]?.(`\u26A1 ${e} \u2190 ${p} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):s[c]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":n&&r?s[c]?.(`\u26A1 ${e} \u2192 ${p} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):s[c]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let l=await o(),m=Date.now()-d;switch(a.type){case "incoming_call":l!=null&&(n&&r?s[c]?.(`\u2705 ${e} \u2192 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:m,params:l,direction:"OUT"}):s[c]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:m,params:l,direction:"OUT"}));break;case "outgoing_call":n&&r?s[c]?.(`\u2705 ${e} \u2190 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:m,payload:l,direction:"IN"}):s[c]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:m,payload:l,direction:"IN"});break}return l}catch(l){let m=l.message,h=Date.now()-d;throw a.type==="incoming_call"?n&&r?s.error?.(`\u{1F6A8} ${e} \u2192 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"OUT"}):a.type==="outgoing_call"&&(n&&r?s.warn?.(`\u{1F6A8} ${e} \u2190 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"IN"})),l}}}function It(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function Et(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,i=s.prettifySource??false,n=s.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",o="\x1B[36m";return (d,p)=>{if(!t)d.context=void 0;else if(i&&d.context){let l=[];d.context.component&&l.push(String(d.context.component)),d.context.identity&&l.push(String(d.context.identity)),l.length>0&&(d.message=`${r}[${l.join("/")}]${a} ${d.message}`,d.context=void 0);}let c=d.meta;if(!e)d.meta={};else if(n&&c&&Object.keys(c).length>0){let l=Object.entries(c).filter(([,m])=>m!=null).map(([m,h])=>{let D=typeof h=="object"?JSON.stringify(h):String(h);return typeof h=="string"?D=`${r}${D}${a}`:D=`${r}${D}${a}`,`${o}${m}${a}=${D}`}).join(" ");l&&(d.message=`${d.message} ${l}`),d.meta={};}p(d);}}function pe(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",n=s?.prettify??false?[prettyTransport({level:t})]:[consoleTransport({level:t})];if(s?.handler){let o=s.handler;n.push({name:"customHandler",write:d=>o(d)});}let r=[];s&&It(s)&&r.push(Et(s));let a=createLogger({level:t,transports:n,middleware:r.length>0?r:void 0});return e&&Object.keys(e).length>0?a.child(e):a}var ce=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let i=-1,n=async r=>{if(r<=i)throw new Error("next() called multiple times");i=r;let a=this._stack[r];if(r===this._stack.length)return t(e);if(a)return a(e,()=>n(r+1))};return n(0)}};var le=class{_concurrency;_running=0;_queue=[];constructor(e=1){this._concurrency=Math.max(1,e);}get concurrency(){return this._concurrency}get pending(){return this._queue.length}get running(){return this._running}get size(){return this._running+this._queue.length}setConcurrency(e){this._concurrency=Math.max(1,e),this._drain();}push(e){return new Promise((t,i)=>{this._queue.push({fn:e,resolve:t,reject:i}),this._drain();})}_drain(){for(;this._running<this._concurrency&&this._queue.length>0;){let e=this._queue.shift();this._running++,e?.fn().then(e.resolve).catch(e.reject).finally(()=>{this._running--,this._drain();});}}};var Ue=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20}},required:["idTag"],type:"object"},{$id:"urn:Authorize.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},required:["idTagInfo"],type:"object"},{$id:"urn:BootNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{chargePointVendor:{type:"string",maxLength:20},chargePointModel:{type:"string",maxLength:20},chargePointSerialNumber:{type:"string",maxLength:25},chargeBoxSerialNumber:{type:"string",maxLength:25},firmwareVersion:{type:"string",maxLength:50},iccid:{type:"string",maxLength:20},imsi:{type:"string",maxLength:20},meterType:{type:"string",maxLength:25},meterSerialNumber:{type:"string",maxLength:25}},required:["chargePointVendor","chargePointModel"],type:"object"},{$id:"urn:BootNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Pending","Rejected"]},currentTime:{type:"string",format:"date-time"},interval:{type:"integer"}},required:["status","currentTime","interval"],type:"object"},{$id:"urn:CancelReservation.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{reservationId:{type:"integer"}},required:["reservationId"],type:"object"},{$id:"urn:CancelReservation.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:CertificateSigned.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{certificateChain:{type:"string",maxLength:1e4}},required:["certificateChain"],type:"object"},{$id:"urn:CertificateSigned.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateSignedStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/CertificateSignedStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:ChangeAvailability.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},type:{type:"string",enum:["Inoperative","Operative"]}},required:["connectorId","type"],type:"object"},{$id:"urn:ChangeAvailability.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","Scheduled"]}},required:["status"],type:"object"},{$id:"urn:ChangeConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"string",maxLength:50},value:{type:"string",maxLength:500}},required:["key","value"],type:"object"},{$id:"urn:ChangeConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","RebootRequired","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:ClearCache.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ClearCache.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ClearChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{id:{type:"integer"},connectorId:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},stackLevel:{type:"integer"}},type:"object"},{$id:"urn:ClearChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Unknown"]}},required:["status"],type:"object"},{$id:"urn:DataTransfer.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{vendorId:{type:"string",maxLength:255},messageId:{type:"string",maxLength:50},data:{type:"string"}},required:["vendorId"],type:"object"},{$id:"urn:DataTransfer.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","UnknownMessageId","UnknownVendorId"]},data:{type:"string"}},required:["status"],type:"object"},{$id:"urn:DeleteCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{$ref:"#/definitions/CertificateHashDataType"}},required:["certificateHashData"],type:"object"},{$id:"urn:DeleteCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{DeleteCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","NotFound"]}},properties:{status:{$ref:"#/definitions/DeleteCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Idle","Uploaded","UploadFailed","Uploading"]}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ExtendedTriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{MessageTriggerEnumType:{type:"string",enum:["BootNotification","LogStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","SignChargePointCertificate","StatusNotification"]}},properties:{requestedMessage:{$ref:"#/definitions/MessageTriggerEnumType"},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:ExtendedTriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{TriggerMessageStatusEnumType:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},properties:{status:{$ref:"#/definitions/TriggerMessageStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","Idle","InstallationFailed","Installing","Installed"]}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetCompositeSchedule.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},duration:{type:"integer"},chargingRateUnit:{type:"string",enum:["A","W"]}},required:["connectorId","duration"],type:"object"},{$id:"urn:GetCompositeSchedule.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]},connectorId:{type:"integer"},scheduleStart:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},required:["status"],type:"object"},{$id:"urn:GetConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{configurationKey:{type:"array",items:{type:"object",properties:{key:{type:"string",maxLength:50},readonly:{type:"boolean"},value:{type:"string",maxLength:500}},additionalProperties:false,required:["key","readonly"]}},unknownKey:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetDiagnostics.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retryInterval:{type:"integer"},startTime:{type:"string",format:"date-time"},stopTime:{type:"string",format:"date-time"}},required:["location"],type:"object"},{$id:"urn:GetDiagnostics.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{fileName:{type:"string",maxLength:255}},type:"object"},{$id:"urn:GetInstalledCertificateIds.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"}},required:["certificateType"],type:"object"},{$id:"urn:GetInstalledCertificateIds.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GetInstalledCertificateStatusEnumType:{type:"string",enum:["Accepted","NotFound"]},HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{type:"array",items:{$ref:"#/definitions/CertificateHashDataType"},minItems:1},status:{$ref:"#/definitions/GetInstalledCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:GetLocalListVersion.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetLocalListVersion.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"}},required:["listVersion"],type:"object"},{$id:"urn:GetLog.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogEnumType:{type:"string",enum:["DiagnosticsLog","SecurityLog"]},LogParametersType:{type:"object",additionalProperties:false,properties:{remoteLocation:{type:"string",maxLength:512},oldestTimestamp:{type:"string",format:"date-time"},latestTimestamp:{type:"string",format:"date-time"}},required:["remoteLocation"]}},properties:{log:{$ref:"#/definitions/LogParametersType"},logType:{$ref:"#/definitions/LogEnumType"},requestId:{type:"integer"},retries:{type:"integer"},retryInterval:{type:"integer"}},required:["logType","requestId","log"],type:"object"},{$id:"urn:GetLog.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled"]}},properties:{status:{$ref:"#/definitions/LogStatusEnumType"},filename:{type:"string",maxLength:255}},required:["status"],type:"object"},{$id:"urn:Heartbeat.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:Heartbeat.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{currentTime:{type:"string",format:"date-time"}},required:["currentTime"],type:"object"},{$id:"urn:InstallCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"},certificate:{type:"string",maxLength:5500}},required:["certificateType","certificate"],type:"object"},{$id:"urn:InstallCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{InstallCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","Rejected"]}},properties:{status:{$ref:"#/definitions/InstallCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UploadLogStatusEnumType:{type:"string",enum:["BadMessage","Idle","NotSupportedOperation","PermissionDenied","Uploaded","UploadFailure","Uploading"]}},properties:{status:{$ref:"#/definitions/UploadLogStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:MeterValues.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},transactionId:{type:"integer"},meterValue:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["connectorId","meterValue"],type:"object"},{$id:"urn:MeterValues.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:RemoteStartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},chargingProfile:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["idTag"],type:"object"},{$id:"urn:RemoteStartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:RemoteStopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{transactionId:{type:"integer"}},required:["transactionId"],type:"object"},{$id:"urn:RemoteStopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ReserveNow.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},expiryDate:{type:"string",format:"date-time"},idTag:{type:"string",maxLength:20},parentIdTag:{type:"string",maxLength:20},reservationId:{type:"integer"}},required:["connectorId","expiryDate","idTag","reservationId"],type:"object"},{$id:"urn:ReserveNow.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Faulted","Occupied","Rejected","Unavailable"]}},required:["status"],type:"object"},{$id:"urn:Reset.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",enum:["Hard","Soft"]}},required:["type"],type:"object"},{$id:"urn:Reset.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:SecurityEventNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",maxLength:50},timestamp:{type:"string",format:"date-time"},techInfo:{type:"string",maxLength:255}},required:["type","timestamp"],type:"object"},{$id:"urn:SecurityEventNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SendLocalList.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"},localAuthorizationList:{type:"array",items:{type:"object",properties:{idTag:{type:"string",maxLength:20},idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},additionalProperties:false,required:["idTag"]}},updateType:{type:"string",enum:["Differential","Full"]}},required:["listVersion","updateType"],type:"object"},{$id:"urn:SendLocalList.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Failed","NotSupported","VersionMismatch"]}},required:["status"],type:"object"},{$id:"urn:SetChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},csChargingProfiles:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["connectorId","csChargingProfiles"],type:"object"},{$id:"urn:SetChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:SignCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{csr:{type:"string",maxLength:5500}},required:["csr"],type:"object"},{$id:"urn:SignCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GenericStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/GenericStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareStatusEnumType:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","DownloadScheduled","DownloadPaused","Idle","InstallationFailed","Installing","Installed","InstallRebooting","InstallScheduled","InstallVerificationFailed","InvalidSignature","SignatureVerified"]}},properties:{status:{$ref:"#/definitions/FirmwareStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SignedUpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareType:{type:"object",additionalProperties:false,properties:{location:{type:"string",maxLength:512},retrieveDateTime:{type:"string",format:"date-time"},installDateTime:{type:"string",format:"date-time"},signingCertificate:{type:"string",maxLength:5500},signature:{type:"string",maxLength:800}},required:["location","retrieveDateTime","signingCertificate","signature"]}},properties:{retries:{type:"integer"},retryInterval:{type:"integer"},requestId:{type:"integer"},firmware:{$ref:"#/definitions/FirmwareType"}},required:["requestId","firmware"],type:"object"},{$id:"urn:SignedUpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UpdateFirmwareStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled","InvalidCertificate","RevokedCertificate"]}},properties:{status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:StartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},meterStart:{type:"integer"},reservationId:{type:"integer"},timestamp:{type:"string",format:"date-time"}},required:["connectorId","idTag","meterStart","timestamp"],type:"object"},{$id:"urn:StartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]},transactionId:{type:"integer"}},required:["idTagInfo","transactionId"],type:"object"},{$id:"urn:StatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},errorCode:{type:"string",enum:["ConnectorLockFailure","EVCommunicationError","GroundFailure","HighTemperature","InternalError","LocalListConflict","NoError","OtherError","OverCurrentFailure","PowerMeterFailure","PowerSwitchFailure","ReaderFailure","ResetFailure","UnderVoltage","OverVoltage","WeakSignal"]},info:{type:"string",maxLength:50},status:{type:"string",enum:["Available","Preparing","Charging","SuspendedEVSE","SuspendedEV","Finishing","Reserved","Unavailable","Faulted"]},timestamp:{type:"string",format:"date-time"},vendorId:{type:"string",maxLength:255},vendorErrorCode:{type:"string",maxLength:50}},required:["connectorId","errorCode","status"],type:"object"},{$id:"urn:StatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:StopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20},meterStop:{type:"integer"},timestamp:{type:"string",format:"date-time"},transactionId:{type:"integer"},reason:{type:"string",enum:["EmergencyStop","EVDisconnected","HardReset","Local","Other","PowerLoss","Reboot","Remote","SoftReset","UnlockCommand","DeAuthorized"]},transactionData:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["transactionId","timestamp","meterStop"],type:"object"},{$id:"urn:StopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},type:"object"},{$id:"urn:TriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{requestedMessage:{type:"string",enum:["BootNotification","DiagnosticsStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","StatusNotification"]},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:TriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},required:["status"],type:"object"},{$id:"urn:UnlockConnector.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"}},required:["connectorId"],type:"object"},{$id:"urn:UnlockConnector.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Unlocked","UnlockFailed","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:UpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retrieveDate:{type:"string",format:"date-time"},retryInterval:{type:"integer"}},required:["location","retrieveDate"],type:"object"},{$id:"urn:UpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"}];var We=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CustomDataType:{description:"This class does not get 'AdditionalProperties = false' in the schema generation, so it can be extended with arbitrary JSON properties to allow adding custom data.",type:"object",properties:{vendorId:{type:"string",maxLength:255}},required:["vendorId"]},HashAlgorithmEnumType:{description:`Used algorithms for the hashes provided.\r
1
+ import st,{resolve}from'path';import {fileURLToPath}from'url';import {EventEmitter}from'events';import {cpus,totalmem,freemem}from'os';import re,{WebSocketServer}from'ws';import {prettyTransport,consoleTransport,createLogger}from'voltlog-io';import jt from'ajv';import Rt from'ajv-formats';import {randomUUID}from'crypto';import kt,{createServer as createServer$1}from'http';import {createServer}from'https';import {TLSSocket}from'tls';import {isIPv4}from'net';import {Worker}from'worker_threads';var ot=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ke=()=>fileURLToPath(import.meta.url),pt=()=>st.dirname(ke()),g=pt(),y=ke();var Te=class{_channels=new Map;async publish(e,t){let i=this._channels.get(e);if(i)for(let n of i)try{n(t);}catch{}}async publishBatch(e){for(let t of e)await this.publish(t.channel,t.data);}async subscribe(e,t){this._channels.has(e)||this._channels.set(e,new Set),this._channels.get(e)?.add(t);}async unsubscribe(e){this._channels.delete(e);}async disconnect(){this._channels.clear(),this._presence.clear();}_presence=new Map;async setPresence(e,t,i){this._presence.set(e,t);}async getPresence(e){return this._presence.get(e)||null}async getPresenceBatch(e){return e.map(t=>this._presence.get(t)||null)}async removePresence(e){this._presence.delete(e);}async setPresenceBatch(e){for(let{identity:t,nodeId:i}of e)this._presence.set(t,i);}};function ct(s){return s}var ve=class{_cluster;_subscriber;_handlers=new Map;constructor(e){try{let{createRequire:t}=ot("module"),n=t(y)("ioredis"),r=e.redisOptions??{};e.natMap&&(r.natMap=e.natMap),this._cluster=new n.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber=new n.Cluster(e.nodes.map(a=>({host:a.host,port:a.port})),{redisOptions:r}),this._subscriber.on("message",(a,o)=>{let d=this._handlers.get(a);d&&d(o);});}catch{throw new Error("ClusterDriver requires 'ioredis' as a peer dependency. Install it with: npm i ioredis")}}async publish(e,t){await this._cluster.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this._subscriber.subscribe(e);}async unsubscribe(e){await this._subscriber.unsubscribe(e),this._handlers.delete(e);}async set(e,t,i){i?await this._cluster.set(e,t,"EX",i):await this._cluster.set(e,t);}async get(e){return await this._cluster.get(e)||null}async mget(e){if(e.length===0)return [];try{return await this._cluster.mget(...e)}catch{return await Promise.all(e.map(t=>this.get(t)))}}async del(e){await this._cluster.del(e);}async xadd(e,t,i){let n=[];i&&n.push("MAXLEN","~",i.toString()),n.push("*");for(let[r,a]of Object.entries(t))n.push(r,a);return await this._cluster.xadd(e,...n)}async xaddBatch(e,t){if(e.length===0)return;let i=this._cluster.pipeline();for(let n of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(n.args))r.push(a,o);i.xadd(n.stream,...r);}await i.exec();}async xread(e,t,i){let n=[];t&&n.push("COUNT",t),typeof i=="number"&&n.push("BLOCK",i),n.push("STREAMS");for(let a of e)n.push(a.key);for(let a of e)n.push(a.id);let r=await this._cluster.xread(...n);return r?r.map(([a,o])=>({stream:a,messages:o.map(([d,p])=>{let c={};for(let l=0;l<p.length;l+=2)c[p[l]]=p[l+1];return {id:d,data:c}})})):null}async xlen(e){return await this._cluster.xlen(e)}async disconnect(){this._handlers.clear(),await Promise.allSettled([this._cluster.quit(),this._subscriber.quit()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this._cluster.pipeline();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,"EX",r);await t.exec();}async expire(e,t){await this._cluster.expire(e,t);}onError(e){return this._cluster.on("error",e),()=>this._cluster.removeListener("error",e)}onReconnect(e){return this._cluster.on("reconnecting",e),()=>this._cluster.removeListener("reconnecting",e)}};var Ce=class{constructor(e,t,i){this.pub=e;this.sub=t;this.blocking=i;this.sub.on&&this.sub.on("message",(n,r)=>{let a=this._handlers.get(n);a&&a(r);});}_handlers=new Map;async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){this._handlers.set(e,t),await this.sub.subscribe(e);}async unsubscribe(e){await this.sub.unsubscribe(e),this._handlers.delete(e);}async set(e,t,i){i?await this.pub.set(e,t,"EX",i):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mget(...e)}async del(e){await this.pub.del(e);}async xadd(e,t,i){let n=[];i&&n.push("MAXLEN","~",i.toString()),n.push("*");for(let[r,a]of Object.entries(t))n.push(r,a);return await this.pub.xadd(e,...n)}async xaddBatch(e,t){if(e.length===0)return;let i=this.pub.pipeline();for(let n of e){let r=[];t&&r.push("MAXLEN","~",t.toString()),r.push("*");for(let[a,o]of Object.entries(n.args))r.push(a,o);i.xadd(n.stream,...r);}await i.exec();}async xread(e,t,i){let n=[];t&&n.push("COUNT",t),typeof i=="number"&&n.push("BLOCK",i),n.push("STREAMS"),e.forEach(o=>{n.push(o.key);}),e.forEach(o=>{n.push(o.id);});let a=await(i&&this.blocking?this.blocking:this.pub).xread(...n);return a?a.map(([o,d])=>({stream:o,messages:d.map(([p,c])=>{let l={};for(let m=0;m<c.length;m+=2)l[c[m]]=c[m+1];return {id:p,data:l}})})):null}async xlen(e){return await this.pub.xlen(e)}async disconnect(){this._handlers.clear();let e=async t=>{t.quit?await t.quit():t.disconnect&&await t.disconnect();};await Promise.all([e(this.pub),e(this.sub)]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.pipeline();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,"EX",r);await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}},be=class{constructor(e,t,i){this.pub=e;this.sub=t;this.blocking=i;}async publish(e,t){await this.pub.publish(e,t);}async subscribe(e,t){await this.sub.subscribe(e,t);}async unsubscribe(e){await this.sub.unsubscribe(e);}async set(e,t,i){i?await this.pub.set(e,t,{EX:i}):await this.pub.set(e,t);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mGet(e)}async del(e){await this.pub.del(e);}async xadd(e,t,i){return await this.pub.xAdd(e,"*",t,{TRIM:i?{strategy:"MAXLEN",strategyModifier:"~",threshold:i}:void 0})}async xaddBatch(e,t){if(e.length===0)return;let i=this.pub.multi();for(let n of e)i.xAdd(n.stream,"*",n.args,{TRIM:t?{strategy:"MAXLEN",strategyModifier:"~",threshold:t}:void 0});await i.exec();}async xread(e,t,i){let n={};t&&(n.COUNT=t),typeof i=="number"&&(n.BLOCK=i);let r=e.map(d=>({key:d.key,id:d.id})),o=await(i&&this.blocking?this.blocking:this.pub).xRead(r,n);return !o||o.length===0?null:o.map(d=>({stream:d.name,messages:d.messages.map(p=>({id:p.id,data:p.message}))}))}async xlen(e){return await this.pub.xLen(e)}async disconnect(){await Promise.all([this.pub.disconnect(),this.sub.disconnect()]);}async setPresenceBatch(e){if(e.length===0)return;let t=this.pub.multi();for(let{key:i,value:n,ttlSeconds:r}of e)t.set(i,n,{EX:r});await t.exec();}async expire(e,t){await this.pub.expire(e,t);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}};function Fe(s,e,t){return e.isOpen!==void 0&&typeof e.subscribe=="function"?new be(s,e,t):new Ce(s,e,t)}var Pe=class{_driver;_prefix;_streamMaxLen;_streamTtlSeconds;_presenceTtlSeconds;_handlers=new Map;_streamOffsets=new Map;_streams=new Set;_polling=false;_closed=false;_sequenceCounters=new Map;_unsubError;_unsubReconnect;_presenceCache=new Map;_driverPool;_nextPoolIndex;constructor(e){this._prefix=e.prefix??"ocpp-ws-io:",this._streamMaxLen=e.streamMaxLen??1e3,this._streamTtlSeconds=e.streamTtlSeconds??300,this._presenceTtlSeconds=e.presenceTtlSeconds??300,this._driver=Fe(e.pubClient,e.subClient,e.blockingClient);let t=e.poolSize??1;if(this._driverPool=[this._driver],this._nextPoolIndex=0,t>1&&e.driverFactory)for(let i=1;i<t;i++)this._driverPool.push(e.driverFactory());this._driver.onError&&(this._unsubError=this._driver.onError(i=>{console.error("[RedisAdapter] Redis error:",i.message);})),this._driver.onReconnect&&(this._unsubReconnect=this._driver.onReconnect(()=>{this._rehydratePresence().catch(()=>{});}));}_getPoolDriver(){if(this._driverPool.length===1)return this._driver;let e=this._driverPool[this._nextPoolIndex];return this._nextPoolIndex=(this._nextPoolIndex+1)%this._driverPool.length,e}async publish(e,t){let i=this._prefix+e,n=t;if(n&&typeof n=="object"&&e.startsWith("ocpp:node:")){let a=(this._sequenceCounters.get(e)??0)+1;this._sequenceCounters.set(e,a),n.__seq=a;}let r=JSON.stringify(t);if(e.startsWith("ocpp:node:")){let a=this._getPoolDriver();await a.xadd(i,{message:r},this._streamMaxLen),await a.expire(i,this._streamTtlSeconds).catch(()=>{});}else await this._getPoolDriver().publish(i,r);}async publishBatch(e){let t=[],i=[];for(let r of e){let a=this._prefix+r.channel,o=JSON.stringify(r.data);r.channel.startsWith("ocpp:node:")?t.push({stream:a,args:{message:o}}):i.push({channel:a,message:o});}let n=[];t.length>0&&n.push(this._getPoolDriver().xaddBatch(t,this._streamMaxLen)),i.length>0&&n.push(Promise.all(i.map(r=>this._getPoolDriver().publish(r.channel,r.message))).then(()=>{})),await Promise.all(n);}async subscribe(e,t){if(!this._handlers.has(e)){this._handlers.set(e,new Set);let i=this._prefix+e;e.startsWith("ocpp:node:")?this._streams.has(i)||(this._streams.add(i),this._streamOffsets.set(i,"0"),this._ensurePolling()):await this._driver.subscribe(i,n=>{this._handleMessage(e,n);});}this._handlers.get(e)?.add(t);}async unsubscribe(e){let t=this._prefix+e;this._streams.has(t)?(this._streams.delete(t),this._streamOffsets.delete(t)):await this._driver.unsubscribe(t),this._handlers.delete(e);}async disconnect(){this._closed=true,this._handlers.clear(),this._streams.clear(),this._presenceCache.clear(),this._sequenceCounters.clear(),this._unsubError&&this._unsubError(),this._unsubReconnect&&this._unsubReconnect(),await Promise.allSettled(this._driverPool.map(e=>e.disconnect()));}_handleMessage(e,t){let i=this._handlers.get(e);if(!i)return;let n;try{n=JSON.parse(t);}catch{n=t;}for(let r of i)try{r(n);}catch{}}_ensurePolling(){this._polling||this._closed||(this._polling=true,this._pollLoop().catch(()=>{this._polling=false;}));}async _pollLoop(){for(;!this._closed;){if(this._streams.size===0){await new Promise(t=>setTimeout(t,1e3));continue}let e=Array.from(this._streams).map(t=>({key:t,id:this._streamOffsets.get(t)||"$"}));try{let t=await this._driver.xread(e,void 0,1e3);if(t)for(let i of t){let n=i.stream.replace(this._prefix,"");for(let r of i.messages){this._streamOffsets.set(i.stream,r.id);let a=r.data.message;a&&this._handleMessage(n,a);}}}catch{await new Promise(i=>setTimeout(i,1e3));}}this._polling=false;}async setPresence(e,t,i){let n=`${this._prefix}presence:${e}`;this._presenceCache.set(e,{nodeId:t,ttl:i}),await this._driver.set(n,t,i);}async getPresence(e){let t=`${this._prefix}presence:${e}`;return await this._driver.get(t)}async getPresenceBatch(e){if(e.length===0)return [];let t=e.map(i=>`${this._prefix}presence:${i}`);return this._driver.mget?await this._driver.mget(t):await Promise.all(t.map(i=>this._driver.get(i)))}async removePresence(e){let t=`${this._prefix}presence:${e}`;await this._driver.del(t);}async metrics(){let e=0,t={};for(let i of this._streams)try{let n=await this._driver.xlen(i);e+=n,t[i]=n;}catch{t[i]=-1;}return {pendingMessages:e,activeStreams:this._streams.size,streamDetails:t}}async setPresenceBatch(e){if(e.length===0)return;let t=e.map(({identity:i,nodeId:n,ttl:r})=>{let a=`${this._prefix}presence:${i}`,o=r??this._presenceTtlSeconds;return this._presenceCache.set(i,{nodeId:n,ttl:o}),{key:a,value:n,ttlSeconds:o}});await this._driver.setPresenceBatch(t);}async _rehydratePresence(){if(this._presenceCache.size===0)return;let e=Array.from(this._presenceCache.entries()).map(([t,{nodeId:i,ttl:n}])=>({key:`${this._prefix}presence:${t}`,value:i,ttlSeconds:n}));await this._driver.setPresenceBatch(e);}};var H=class extends EventEmitter{_cpuThreshold;_memThreshold;_cooldownMs;_sampleInterval;_timer=null;_lastOverloadTime=0;_multiplier=1;_prevCpuUsage=null;_prevTimestamp=0;constructor(e={}){super(),this._cpuThreshold=e.cpuThresholdPercent??70,this._memThreshold=e.memThresholdPercent??85,this._cooldownMs=e.cooldownMs??1e4,this._sampleInterval=e.sampleIntervalMs??2e3;}get multiplier(){return this._multiplier}start(){this._timer||(this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=Date.now(),this._timer=setInterval(()=>this._sample(),this._sampleInterval),this._timer.unref&&this._timer.unref());}stop(){this._timer&&(clearInterval(this._timer),this._timer=null),this._multiplier=1;}_sample(){let e=Date.now(),t=process.cpuUsage(this._prevCpuUsage??void 0),i=e-this._prevTimestamp,n=(t.user+t.system)/1e3/i/cpus().length*100;this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=e;let r=totalmem(),a=freemem(),o=(r-a)/r*100,d=n>this._cpuThreshold,p=o>this._memThreshold,c=this._multiplier;d||p?(this._lastOverloadTime=e,this._multiplier=Math.max(.25,this._multiplier*.5)):e-this._lastOverloadTime>this._cooldownMs&&(this._multiplier=Math.min(1,this._multiplier+.1)),this._multiplier!==c&&this.emit("adapted",{multiplier:this._multiplier,cpuPercent:Math.round(n*100)/100,memPercent:Math.round(o*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};var F=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},z=class extends Error{statusCode;headers;constructor(e,t,i={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=i;}},Se=class extends Error{constructor(e="WebSocket upgrade failed"){super(e),this.name="WebsocketUpgradeError";}},C=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},R=class extends C{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},B=class extends C{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},G=class extends C{rpcErrorCode="InternalError";rpcErrorMessage="An internal error occurred and the receiver was not able to process the requested action successfully";constructor(e,t={}){super(e,t),this.name="RPCInternalError";}},J=class extends C{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},K=class extends C{rpcErrorCode="SecurityError";rpcErrorMessage="During the processing of action a security issue occurred preventing receiver from completing the action successfully";constructor(e,t={}){super(e,t),this.name="RPCSecurityError";}},X=class extends C{rpcErrorCode="FormationViolation";rpcErrorMessage="Payload for action is syntactically incorrect or not conform the PDU structure for action";constructor(e,t={}){super(e,t),this.name="RPCFormationViolationError";}},Q=class extends C{rpcErrorCode="FormatViolation";rpcErrorMessage="Payload is syntactically correct but at least one field contains an invalid value";constructor(e,t={}){super(e,t),this.name="RPCFormatViolationError";}},Y=class extends C{rpcErrorCode="PropertyConstraintViolation";rpcErrorMessage="Payload is syntactically correct but at least one of the fields violates data type constraints";constructor(e,t={}){super(e,t),this.name="RPCPropertyConstraintViolationError";}},Z=class extends C{rpcErrorCode="OccurrenceConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates occurrence constraints";constructor(e,t={}){super(e,t),this.name="RPCOccurrenceConstraintViolationError";}},ee=class extends C{rpcErrorCode="TypeConstraintViolation";rpcErrorMessage="Payload for action is syntactically correct but at least one of the fields violates type constraints";constructor(e,t={}){super(e,t),this.name="RPCTypeConstraintViolationError";}},L=class extends C{rpcErrorCode="MessageTypeNotSupported";rpcErrorMessage="A message with a Message Type Number received that is not supported by this implementation";constructor(e,t={}){super(e,t),this.name="RPCMessageTypeNotSupportedError";}},te=class extends C{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function gt(s){return s}function yt(s){return s}function Tt(s){return s}function vt(s){return s}function Ct(...s){return async e=>{let t=false,i=false,n=o=>{t=true,e.accept(o);},r=(o,d)=>(i=true,e.reject(o,d)),a={...e,accept:n,reject:r};try{for(let o of s){if(e.signal.aborted||t||i)break;let d=o(a);if(d instanceof Promise&&await d,t||i)break}!t&&!i&&r(401,"Unauthorized (All composeAuth handlers passed without accepting)");}catch{i||r(500,"Internal Server Error during auth compose execution");}}}function Ie(s,e,t={}){let i=typeof t=="object"?t:{},{exchangeLog:n=false,prettify:r=false}=i;return async(a,o)=>{let d=Date.now(),p=a.method,c=n?"info":"debug";switch(a.type){case "incoming_call":n&&r?s[c]?.(`\u26A1 ${e} \u2190 ${p} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):s[c]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":n&&r?s[c]?.(`\u26A1 ${e} \u2192 ${p} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):s[c]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let l=await o(),m=Date.now()-d;switch(a.type){case "incoming_call":l!=null&&(n&&r?s[c]?.(`\u2705 ${e} \u2192 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:m,params:l,direction:"OUT"}):s[c]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:m,params:l,direction:"OUT"}));break;case "outgoing_call":n&&r?s[c]?.(`\u2705 ${e} \u2190 ${p} [RES]`,{messageId:a.messageId,method:a.method,durationMs:m,payload:l,direction:"IN"}):s[c]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:m,payload:l,direction:"IN"});break}return l}catch(l){let m=l.message,h=Date.now()-d;throw a.type==="incoming_call"?n&&r?s.error?.(`\u{1F6A8} ${e} \u2192 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"OUT"}):a.type==="outgoing_call"&&(n&&r?s.warn?.(`\u{1F6A8} ${e} \u2190 ${p} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:h,error:m,direction:"IN"})),l}}}function It(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function Et(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,i=s.prettifySource??false,n=s.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",o="\x1B[36m";return (d,p)=>{if(!t)d.context=void 0;else if(i&&d.context){let l=[];d.context.component&&l.push(String(d.context.component)),d.context.identity&&l.push(String(d.context.identity)),l.length>0&&(d.message=`${r}[${l.join("/")}]${a} ${d.message}`,d.context=void 0);}let c=d.meta;if(!e)d.meta={};else if(n&&c&&Object.keys(c).length>0){let l=Object.entries(c).filter(([,m])=>m!=null).map(([m,h])=>{let x=typeof h=="object"?JSON.stringify(h):String(h);return typeof h=="string"?x=`${r}${x}${a}`:x=`${r}${x}${a}`,`${o}${m}${a}=${x}`}).join(" ");l&&(d.message=`${d.message} ${l}`),d.meta={};}p(d);}}function pe(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",n=s?.prettify??false?[prettyTransport({level:t})]:[consoleTransport({level:t})];if(s?.handler){let o=s.handler;n.push({name:"customHandler",write:d=>o(d)});}let r=[];s&&It(s)&&r.push(Et(s));let a=createLogger({level:t,transports:n,middleware:r.length>0?r:void 0});return e&&Object.keys(e).length>0?a.child(e):a}var ce=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let i=-1,n=async r=>{if(r<=i)throw new Error("next() called multiple times");i=r;let a=this._stack[r];if(r===this._stack.length)return t(e);if(a)return a(e,()=>n(r+1))};return n(0)}};var le=class{_concurrency;_running=0;_queue=[];constructor(e=1){this._concurrency=Math.max(1,e);}get concurrency(){return this._concurrency}get pending(){return this._queue.length}get running(){return this._running}get size(){return this._running+this._queue.length}setConcurrency(e){this._concurrency=Math.max(1,e),this._drain();}push(e){return new Promise((t,i)=>{this._queue.push({fn:e,resolve:t,reject:i}),this._drain();})}_drain(){for(;this._running<this._concurrency&&this._queue.length>0;){let e=this._queue.shift();this._running++,e?.fn().then(e.resolve).catch(e.reject).finally(()=>{this._running--,this._drain();});}}};var Ue=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20}},required:["idTag"],type:"object"},{$id:"urn:Authorize.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},required:["idTagInfo"],type:"object"},{$id:"urn:BootNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{chargePointVendor:{type:"string",maxLength:20},chargePointModel:{type:"string",maxLength:20},chargePointSerialNumber:{type:"string",maxLength:25},chargeBoxSerialNumber:{type:"string",maxLength:25},firmwareVersion:{type:"string",maxLength:50},iccid:{type:"string",maxLength:20},imsi:{type:"string",maxLength:20},meterType:{type:"string",maxLength:25},meterSerialNumber:{type:"string",maxLength:25}},required:["chargePointVendor","chargePointModel"],type:"object"},{$id:"urn:BootNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Pending","Rejected"]},currentTime:{type:"string",format:"date-time"},interval:{type:"integer"}},required:["status","currentTime","interval"],type:"object"},{$id:"urn:CancelReservation.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{reservationId:{type:"integer"}},required:["reservationId"],type:"object"},{$id:"urn:CancelReservation.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:CertificateSigned.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{certificateChain:{type:"string",maxLength:1e4}},required:["certificateChain"],type:"object"},{$id:"urn:CertificateSigned.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateSignedStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/CertificateSignedStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:ChangeAvailability.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},type:{type:"string",enum:["Inoperative","Operative"]}},required:["connectorId","type"],type:"object"},{$id:"urn:ChangeAvailability.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","Scheduled"]}},required:["status"],type:"object"},{$id:"urn:ChangeConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"string",maxLength:50},value:{type:"string",maxLength:500}},required:["key","value"],type:"object"},{$id:"urn:ChangeConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","RebootRequired","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:ClearCache.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ClearCache.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ClearChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{id:{type:"integer"},connectorId:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},stackLevel:{type:"integer"}},type:"object"},{$id:"urn:ClearChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Unknown"]}},required:["status"],type:"object"},{$id:"urn:DataTransfer.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{vendorId:{type:"string",maxLength:255},messageId:{type:"string",maxLength:50},data:{type:"string"}},required:["vendorId"],type:"object"},{$id:"urn:DataTransfer.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","UnknownMessageId","UnknownVendorId"]},data:{type:"string"}},required:["status"],type:"object"},{$id:"urn:DeleteCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{$ref:"#/definitions/CertificateHashDataType"}},required:["certificateHashData"],type:"object"},{$id:"urn:DeleteCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{DeleteCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","NotFound"]}},properties:{status:{$ref:"#/definitions/DeleteCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Idle","Uploaded","UploadFailed","Uploading"]}},required:["status"],type:"object"},{$id:"urn:DiagnosticsStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:ExtendedTriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{MessageTriggerEnumType:{type:"string",enum:["BootNotification","LogStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","SignChargePointCertificate","StatusNotification"]}},properties:{requestedMessage:{$ref:"#/definitions/MessageTriggerEnumType"},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:ExtendedTriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{TriggerMessageStatusEnumType:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},properties:{status:{$ref:"#/definitions/TriggerMessageStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","Idle","InstallationFailed","Installing","Installed"]}},required:["status"],type:"object"},{$id:"urn:FirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetCompositeSchedule.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},duration:{type:"integer"},chargingRateUnit:{type:"string",enum:["A","W"]}},required:["connectorId","duration"],type:"object"},{$id:"urn:GetCompositeSchedule.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]},connectorId:{type:"integer"},scheduleStart:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},required:["status"],type:"object"},{$id:"urn:GetConfiguration.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{key:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetConfiguration.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{configurationKey:{type:"array",items:{type:"object",properties:{key:{type:"string",maxLength:50},readonly:{type:"boolean"},value:{type:"string",maxLength:500}},additionalProperties:false,required:["key","readonly"]}},unknownKey:{type:"array",items:{type:"string",maxLength:50}}},type:"object"},{$id:"urn:GetDiagnostics.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retryInterval:{type:"integer"},startTime:{type:"string",format:"date-time"},stopTime:{type:"string",format:"date-time"}},required:["location"],type:"object"},{$id:"urn:GetDiagnostics.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{fileName:{type:"string",maxLength:255}},type:"object"},{$id:"urn:GetInstalledCertificateIds.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"}},required:["certificateType"],type:"object"},{$id:"urn:GetInstalledCertificateIds.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GetInstalledCertificateStatusEnumType:{type:"string",enum:["Accepted","NotFound"]},HashAlgorithmEnumType:{type:"string",enum:["SHA256","SHA384","SHA512"]},CertificateHashDataType:{type:"object",additionalProperties:false,properties:{hashAlgorithm:{$ref:"#/definitions/HashAlgorithmEnumType"},issuerNameHash:{type:"string",maxLength:128},issuerKeyHash:{type:"string",maxLength:128},serialNumber:{type:"string",maxLength:40}},required:["hashAlgorithm","issuerNameHash","issuerKeyHash","serialNumber"]}},properties:{certificateHashData:{type:"array",items:{$ref:"#/definitions/CertificateHashDataType"},minItems:1},status:{$ref:"#/definitions/GetInstalledCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:GetLocalListVersion.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:GetLocalListVersion.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"}},required:["listVersion"],type:"object"},{$id:"urn:GetLog.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogEnumType:{type:"string",enum:["DiagnosticsLog","SecurityLog"]},LogParametersType:{type:"object",additionalProperties:false,properties:{remoteLocation:{type:"string",maxLength:512},oldestTimestamp:{type:"string",format:"date-time"},latestTimestamp:{type:"string",format:"date-time"}},required:["remoteLocation"]}},properties:{log:{$ref:"#/definitions/LogParametersType"},logType:{$ref:"#/definitions/LogEnumType"},requestId:{type:"integer"},retries:{type:"integer"},retryInterval:{type:"integer"}},required:["logType","requestId","log"],type:"object"},{$id:"urn:GetLog.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{LogStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled"]}},properties:{status:{$ref:"#/definitions/LogStatusEnumType"},filename:{type:"string",maxLength:255}},required:["status"],type:"object"},{$id:"urn:Heartbeat.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:Heartbeat.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{currentTime:{type:"string",format:"date-time"}},required:["currentTime"],type:"object"},{$id:"urn:InstallCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CertificateUseEnumType:{type:"string",enum:["CentralSystemRootCertificate","ManufacturerRootCertificate"]}},properties:{certificateType:{$ref:"#/definitions/CertificateUseEnumType"},certificate:{type:"string",maxLength:5500}},required:["certificateType","certificate"],type:"object"},{$id:"urn:InstallCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{InstallCertificateStatusEnumType:{type:"string",enum:["Accepted","Failed","Rejected"]}},properties:{status:{$ref:"#/definitions/InstallCertificateStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UploadLogStatusEnumType:{type:"string",enum:["BadMessage","Idle","NotSupportedOperation","PermissionDenied","Uploaded","UploadFailure","Uploading"]}},properties:{status:{$ref:"#/definitions/UploadLogStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:LogStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:MeterValues.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},transactionId:{type:"integer"},meterValue:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["connectorId","meterValue"],type:"object"},{$id:"urn:MeterValues.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:RemoteStartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},chargingProfile:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["idTag"],type:"object"},{$id:"urn:RemoteStartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:RemoteStopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{transactionId:{type:"integer"}},required:["transactionId"],type:"object"},{$id:"urn:RemoteStopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:ReserveNow.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},expiryDate:{type:"string",format:"date-time"},idTag:{type:"string",maxLength:20},parentIdTag:{type:"string",maxLength:20},reservationId:{type:"integer"}},required:["connectorId","expiryDate","idTag","reservationId"],type:"object"},{$id:"urn:ReserveNow.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Faulted","Occupied","Rejected","Unavailable"]}},required:["status"],type:"object"},{$id:"urn:Reset.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",enum:["Hard","Soft"]}},required:["type"],type:"object"},{$id:"urn:Reset.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected"]}},required:["status"],type:"object"},{$id:"urn:SecurityEventNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{type:{type:"string",maxLength:50},timestamp:{type:"string",format:"date-time"},techInfo:{type:"string",maxLength:255}},required:["type","timestamp"],type:"object"},{$id:"urn:SecurityEventNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SendLocalList.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{listVersion:{type:"integer"},localAuthorizationList:{type:"array",items:{type:"object",properties:{idTag:{type:"string",maxLength:20},idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},additionalProperties:false,required:["idTag"]}},updateType:{type:"string",enum:["Differential","Full"]}},required:["listVersion","updateType"],type:"object"},{$id:"urn:SendLocalList.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Failed","NotSupported","VersionMismatch"]}},required:["status"],type:"object"},{$id:"urn:SetChargingProfile.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},csChargingProfiles:{type:"object",properties:{chargingProfileId:{type:"integer"},transactionId:{type:"integer"},stackLevel:{type:"integer"},chargingProfilePurpose:{type:"string",enum:["ChargePointMaxProfile","TxDefaultProfile","TxProfile"]},chargingProfileKind:{type:"string",enum:["Absolute","Recurring","Relative"]},recurrencyKind:{type:"string",enum:["Daily","Weekly"]},validFrom:{type:"string",format:"date-time"},validTo:{type:"string",format:"date-time"},chargingSchedule:{type:"object",properties:{duration:{type:"integer"},startSchedule:{type:"string",format:"date-time"},chargingRateUnit:{type:"string",enum:["A","W"]},chargingSchedulePeriod:{type:"array",items:{type:"object",properties:{startPeriod:{type:"integer"},limit:{type:"number",multipleOf:.1},numberPhases:{type:"integer"}},additionalProperties:false,required:["startPeriod","limit"]}},minChargingRate:{type:"number",multipleOf:.1}},additionalProperties:false,required:["chargingRateUnit","chargingSchedulePeriod"]}},additionalProperties:false,required:["chargingProfileId","stackLevel","chargingProfilePurpose","chargingProfileKind","chargingSchedule"]}},required:["connectorId","csChargingProfiles"],type:"object"},{$id:"urn:SetChargingProfile.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:SignCertificate.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{csr:{type:"string",maxLength:5500}},required:["csr"],type:"object"},{$id:"urn:SignCertificate.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{GenericStatusEnumType:{type:"string",enum:["Accepted","Rejected"]}},properties:{status:{$ref:"#/definitions/GenericStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareStatusEnumType:{type:"string",enum:["Downloaded","DownloadFailed","Downloading","DownloadScheduled","DownloadPaused","Idle","InstallationFailed","Installing","Installed","InstallRebooting","InstallScheduled","InstallVerificationFailed","InvalidSignature","SignatureVerified"]}},properties:{status:{$ref:"#/definitions/FirmwareStatusEnumType"},requestId:{type:"integer"}},required:["status"],type:"object"},{$id:"urn:SignedFirmwareStatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,type:"object"},{$id:"urn:SignedUpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{FirmwareType:{type:"object",additionalProperties:false,properties:{location:{type:"string",maxLength:512},retrieveDateTime:{type:"string",format:"date-time"},installDateTime:{type:"string",format:"date-time"},signingCertificate:{type:"string",maxLength:5500},signature:{type:"string",maxLength:800}},required:["location","retrieveDateTime","signingCertificate","signature"]}},properties:{retries:{type:"integer"},retryInterval:{type:"integer"},requestId:{type:"integer"},firmware:{$ref:"#/definitions/FirmwareType"}},required:["requestId","firmware"],type:"object"},{$id:"urn:SignedUpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{UpdateFirmwareStatusEnumType:{type:"string",enum:["Accepted","Rejected","AcceptedCanceled","InvalidCertificate","RevokedCertificate"]}},properties:{status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"}},required:["status"],type:"object"},{$id:"urn:StartTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},idTag:{type:"string",maxLength:20},meterStart:{type:"integer"},reservationId:{type:"integer"},timestamp:{type:"string",format:"date-time"}},required:["connectorId","idTag","meterStart","timestamp"],type:"object"},{$id:"urn:StartTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]},transactionId:{type:"integer"}},required:["idTagInfo","transactionId"],type:"object"},{$id:"urn:StatusNotification.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"},errorCode:{type:"string",enum:["ConnectorLockFailure","EVCommunicationError","GroundFailure","HighTemperature","InternalError","LocalListConflict","NoError","OtherError","OverCurrentFailure","PowerMeterFailure","PowerSwitchFailure","ReaderFailure","ResetFailure","UnderVoltage","OverVoltage","WeakSignal"]},info:{type:"string",maxLength:50},status:{type:"string",enum:["Available","Preparing","Charging","SuspendedEVSE","SuspendedEV","Finishing","Reserved","Unavailable","Faulted"]},timestamp:{type:"string",format:"date-time"},vendorId:{type:"string",maxLength:255},vendorErrorCode:{type:"string",maxLength:50}},required:["connectorId","errorCode","status"],type:"object"},{$id:"urn:StatusNotification.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"},{$id:"urn:StopTransaction.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTag:{type:"string",maxLength:20},meterStop:{type:"integer"},timestamp:{type:"string",format:"date-time"},transactionId:{type:"integer"},reason:{type:"string",enum:["EmergencyStop","EVDisconnected","HardReset","Local","Other","PowerLoss","Reboot","Remote","SoftReset","UnlockCommand","DeAuthorized"]},transactionData:{type:"array",items:{type:"object",properties:{timestamp:{type:"string",format:"date-time"},sampledValue:{type:"array",items:{type:"object",properties:{value:{type:"string"},context:{type:"string",enum:["Interruption.Begin","Interruption.End","Sample.Clock","Sample.Periodic","Transaction.Begin","Transaction.End","Trigger","Other"]},format:{type:"string",enum:["Raw","SignedData"]},measurand:{type:"string",enum:["Energy.Active.Export.Register","Energy.Active.Import.Register","Energy.Reactive.Export.Register","Energy.Reactive.Import.Register","Energy.Active.Export.Interval","Energy.Active.Import.Interval","Energy.Reactive.Export.Interval","Energy.Reactive.Import.Interval","Power.Active.Export","Power.Active.Import","Power.Offered","Power.Reactive.Export","Power.Reactive.Import","Power.Factor","Current.Import","Current.Export","Current.Offered","Voltage","Frequency","Temperature","SoC","RPM"]},phase:{type:"string",enum:["L1","L2","L3","N","L1-N","L2-N","L3-N","L1-L2","L2-L3","L3-L1"]},location:{type:"string",enum:["Cable","EV","Inlet","Outlet","Body"]},unit:{type:"string",enum:["Wh","kWh","varh","kvarh","W","kW","VA","kVA","var","kvar","A","V","K","Celcius","Celsius","Fahrenheit","Percent"]}},additionalProperties:false,required:["value"]}}},additionalProperties:false,required:["timestamp","sampledValue"]}}},required:["transactionId","timestamp","meterStop"],type:"object"},{$id:"urn:StopTransaction.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{idTagInfo:{type:"object",properties:{expiryDate:{type:"string",format:"date-time"},parentIdTag:{type:"string",maxLength:20},status:{type:"string",enum:["Accepted","Blocked","Expired","Invalid","ConcurrentTx"]}},additionalProperties:false,required:["status"]}},type:"object"},{$id:"urn:TriggerMessage.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{requestedMessage:{type:"string",enum:["BootNotification","DiagnosticsStatusNotification","FirmwareStatusNotification","Heartbeat","MeterValues","StatusNotification"]},connectorId:{type:"integer"}},required:["requestedMessage"],type:"object"},{$id:"urn:TriggerMessage.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Accepted","Rejected","NotImplemented"]}},required:["status"],type:"object"},{$id:"urn:UnlockConnector.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{connectorId:{type:"integer"}},required:["connectorId"],type:"object"},{$id:"urn:UnlockConnector.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{status:{type:"string",enum:["Unlocked","UnlockFailed","NotSupported"]}},required:["status"],type:"object"},{$id:"urn:UpdateFirmware.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{location:{type:"string",format:"uri"},retries:{type:"integer"},retrieveDate:{type:"string",format:"date-time"},retryInterval:{type:"integer"}},required:["location","retrieveDate"],type:"object"},{$id:"urn:UpdateFirmware.conf",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,properties:{},type:"object"}];var We=[{$id:"urn:Authorize.req",$schema:"http://json-schema.org/draft-07/schema",additionalProperties:false,definitions:{CustomDataType:{description:"This class does not get 'AdditionalProperties = false' in the schema generation, so it can be extended with arbitrary JSON properties to allow adding custom data.",type:"object",properties:{vendorId:{type:"string",maxLength:255}},required:["vendorId"]},HashAlgorithmEnumType:{description:`Used algorithms for the hashes provided.\r
2
2
  `,type:"string",enum:["SHA256","SHA384","SHA512"]},IdTokenEnumType:{description:`Enumeration of possible idToken types.\r
3
3
  `,type:"string",enum:["Central","eMAID","ISO14443","ISO15693","KeyCode","Local","MacAddress","NoAuthorization"]},AdditionalInfoType:{description:`Contains a case insensitive identifier to use for the authorization and the type of authorization to support multiple forms of identifiers.\r
4
4
  `,type:"object",additionalProperties:false,properties:{customData:{$ref:"#/definitions/CustomDataType"},additionalIdToken:{description:`This field specifies the additional IdToken.\r
@@ -4817,10 +4817,10 @@ False to request stopping priority charging.\r
4817
4817
  \r
4818
4818
  `,type:"string",maxLength:20},evseId:{description:`EVSE id for which check was requested. \r
4819
4819
  \r
4820
- `,type:"integer",minimum:0},status:{$ref:"#/definitions/GenericStatusEnumType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["vatNumber","status"]}];function ue(){return randomUUID()}function q(s,e,t={}){switch(s){case "GenericError":return new C(e,t);case "RpcFrameworkError":return new te(e,t);case "MessageTypeNotSupported":return new L(e,t);case "NotImplemented":return new R(e,t);case "NotSupported":return new B(e,t);case "InternalError":return new G(e,t);case "ProtocolError":return new J(e,t);case "SecurityError":return new K(e,t);case "FormatViolation":return new Q(e,t);case "FormationViolation":return new X(e,t);case "PropertyConstraintViolation":return new Y(e,t);case "OccurrenceConstraintViolation":return new Z(e,t);case "TypeConstraintViolation":return new ee(e,t);default:return new C(e,t)}}var Lt=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function Ee(s){let e={};for(let t of Lt){let i=s[t];if(i!==void 0){if(typeof i=="function"||typeof i=="symbol")continue;if(typeof i=="object"&&i!==null)try{JSON.stringify(i),e[t]=i;}catch{}else e[t]=i;}}return e.name||(e.name=s.name),e.message||(e.message=s.message),e}var $t="ocpp-ws-io",At="1.0.1";function De(){return `${$t}/${At}`}var M={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>M};var qt=new Set(["type"]),Mt=new Set(["maximum","minimum","maxLength","minLength","pattern","format","anyOf","oneOf","not","if"]),Ot=new Set(["required","maxItems","minItems","maxProperties","minProperties","additionalProperties","additionalItems","exclusiveMaximum","exclusiveMinimum","multipleOf"]),Vt=new Set(["enum","const"]);function Nt(s){return qt.has(s)?"TypeConstraintViolation":Ot.has(s)?"OccurrenceConstraintViolation":Vt.has(s)?"PropertyConstraintViolation":(Mt.has(s),"FormatViolation")}var me=class{subprotocol;_ajv;constructor(e,t){this.subprotocol=e,this._ajv=new jt({allErrors:true,strict:false,multipleOfPrecision:4}),Rt(this._ajv);for(let i of t){let n={...i};typeof n.$id=="string"&&n.$id.startsWith("urn:")&&(n.$id=n.$id.replace("urn:","urn/")),this._ajv.addSchema(n);}}_normalizeSchemaId(e){return e.startsWith("urn:")?e.replace("urn:","urn/"):e}validate(e,t){let i=this._normalizeSchemaId(e),n=this._ajv.getSchema(i);if(!n)return;if(!n(t)&&n.errors&&n.errors.length>0){let a=n.errors[0],o=Nt(a.keyword),d=this._ajv.errorsText(n.errors);throw q(o,d)}}hasSchema(e){return !!this._ajv.getSchema(this._normalizeSchemaId(e))}},ze=new Map;function ie(s,e){let t=ze.get(s);if(t)return t;let i=new me(s,e);return ze.set(s,i),i}var he=null;function xe(){return he||(he=[ie("ocpp1.6",Ue),ie("ocpp2.0.1",We),ie("ocpp2.1",He)],he)}var ne={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},fe=(n=>(n[n.NONE=0]="NONE",n[n.BASIC_AUTH=1]="BASIC_AUTH",n[n.TLS_BASIC_AUTH=2]="TLS_BASIC_AUTH",n[n.TLS_CLIENT_CERT=3]="TLS_CLIENT_CERT",n))(fe||{}),E={CALL:2,CALLRESULT:3,CALLERROR:4},we=Symbol("NOREPLY");function Be(s){if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57)return true;switch(s){case 33:case 35:case 36:case 37:case 38:case 39:case 42:case 43:case 45:case 46:case 94:case 95:case 96:case 124:case 126:return true}return false}function Ge(s){if(s.length===0)throw new SyntaxError("Unexpected end of input");let e=new Set,t=0;for(;t<s.length;){for(;t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;let i=t;for(;t<s.length&&Be(s.charCodeAt(t));)t++;if(t===i)throw new SyntaxError(`Unexpected character at index ${t}`);let n=s.substring(i,t);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);for(e.add(n);t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;if(t>=s.length)break;if(s.charCodeAt(t)!==44)throw new SyntaxError(`Unexpected character at index ${t}`);t++;let r=t;for(;r<s.length&&(s.charCodeAt(r)===32||s.charCodeAt(r)===9);)r++;if(r>=s.length||!Be(s.charCodeAt(r)))throw new SyntaxError("Unexpected end of input")}if(e.size===0)throw new SyntaxError("Unexpected end of input");return e}var Ft=new Set([1004,1005,1006]);function Je(s){return s>=1e3&&s<=1014&&!Ft.has(s)||s>=3e3&&s<=4999}var Ut=/^ *[Bb][Aa][Ss][Ii][Cc] +([A-Za-z0-9._~+/-]+=*) *$/;function Ke(s,e){if(!s)return;let t=Ut.exec(s);if(t?.[1])try{let i=Buffer.from(t[1],"base64"),n=Buffer.from(`${e}:`);if(i.length>n.length&&i.subarray(0,n.length).equals(n))return i.subarray(n.length);let r=i.indexOf(58);if(r!==-1&&i.subarray(0,r).toString("utf8")===e)return i.subarray(r+1)}catch{}}function _(s,e,t,i){if(!s.writable)return;let n=kt.STATUS_CODES[e]??"Unknown",r=t??n,o={Connection:"close","Content-Type":"text/plain; charset=utf-8","Content-Length":Buffer.byteLength(r,"utf8"),...i},d=Object.entries(o).map(([p,c])=>`${p}: ${c}`).join(`\r
4820
+ `,type:"integer",minimum:0},status:{$ref:"#/definitions/GenericStatusEnumType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["vatNumber","status"]}];function ue(){return randomUUID()}function q(s,e,t={}){switch(s){case "GenericError":return new C(e,t);case "RpcFrameworkError":return new te(e,t);case "MessageTypeNotSupported":return new L(e,t);case "NotImplemented":return new R(e,t);case "NotSupported":return new B(e,t);case "InternalError":return new G(e,t);case "ProtocolError":return new J(e,t);case "SecurityError":return new K(e,t);case "FormatViolation":return new Q(e,t);case "FormationViolation":return new X(e,t);case "PropertyConstraintViolation":return new Y(e,t);case "OccurrenceConstraintViolation":return new Z(e,t);case "TypeConstraintViolation":return new ee(e,t);default:return new C(e,t)}}var Lt=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function Ee(s){let e={};for(let t of Lt){let i=s[t];if(i!==void 0){if(typeof i=="function"||typeof i=="symbol")continue;if(typeof i=="object"&&i!==null)try{JSON.stringify(i),e[t]=i;}catch{}else e[t]=i;}}return e.name||(e.name=s.name),e.message||(e.message=s.message),e}var $t="ocpp-ws-io",At="1.0.1";function xe(){return `${$t}/${At}`}var M={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>M};var qt=new Set(["type"]),Mt=new Set(["maximum","minimum","maxLength","minLength","pattern","format","anyOf","oneOf","not","if"]),Ot=new Set(["required","maxItems","minItems","maxProperties","minProperties","additionalProperties","additionalItems","exclusiveMaximum","exclusiveMinimum","multipleOf"]),Vt=new Set(["enum","const"]);function Nt(s){return qt.has(s)?"TypeConstraintViolation":Ot.has(s)?"OccurrenceConstraintViolation":Vt.has(s)?"PropertyConstraintViolation":(Mt.has(s),"FormatViolation")}var me=class{subprotocol;_ajv;constructor(e,t){this.subprotocol=e,this._ajv=new jt({allErrors:true,strict:false,multipleOfPrecision:4}),Rt(this._ajv);for(let i of t){let n={...i};typeof n.$id=="string"&&n.$id.startsWith("urn:")&&(n.$id=n.$id.replace("urn:","urn/")),this._ajv.addSchema(n);}}_normalizeSchemaId(e){return e.startsWith("urn:")?e.replace("urn:","urn/"):e}validate(e,t){let i=this._normalizeSchemaId(e),n=this._ajv.getSchema(i);if(!n)return;if(!n(t)&&n.errors&&n.errors.length>0){let a=n.errors[0],o=Nt(a.keyword),d=this._ajv.errorsText(n.errors);throw q(o,d)}}hasSchema(e){return !!this._ajv.getSchema(this._normalizeSchemaId(e))}},ze=new Map;function ie(s,e){let t=ze.get(s);if(t)return t;let i=new me(s,e);return ze.set(s,i),i}var he=null;function De(){return he||(he=[ie("ocpp1.6",Ue),ie("ocpp2.0.1",We),ie("ocpp2.1",He)],he)}var ne={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},fe=(n=>(n[n.NONE=0]="NONE",n[n.BASIC_AUTH=1]="BASIC_AUTH",n[n.TLS_BASIC_AUTH=2]="TLS_BASIC_AUTH",n[n.TLS_CLIENT_CERT=3]="TLS_CLIENT_CERT",n))(fe||{}),E={CALL:2,CALLRESULT:3,CALLERROR:4},we=Symbol("NOREPLY");function Be(s){if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57)return true;switch(s){case 33:case 35:case 36:case 37:case 38:case 39:case 42:case 43:case 45:case 46:case 94:case 95:case 96:case 124:case 126:return true}return false}function Ge(s){if(s.length===0)throw new SyntaxError("Unexpected end of input");let e=new Set,t=0;for(;t<s.length;){for(;t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;let i=t;for(;t<s.length&&Be(s.charCodeAt(t));)t++;if(t===i)throw new SyntaxError(`Unexpected character at index ${t}`);let n=s.substring(i,t);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);for(e.add(n);t<s.length&&(s.charCodeAt(t)===32||s.charCodeAt(t)===9);)t++;if(t>=s.length)break;if(s.charCodeAt(t)!==44)throw new SyntaxError(`Unexpected character at index ${t}`);t++;let r=t;for(;r<s.length&&(s.charCodeAt(r)===32||s.charCodeAt(r)===9);)r++;if(r>=s.length||!Be(s.charCodeAt(r)))throw new SyntaxError("Unexpected end of input")}if(e.size===0)throw new SyntaxError("Unexpected end of input");return e}var Ft=new Set([1004,1005,1006]);function Je(s){return s>=1e3&&s<=1014&&!Ft.has(s)||s>=3e3&&s<=4999}var Ut=/^ *[Bb][Aa][Ss][Ii][Cc] +([A-Za-z0-9._~+/-]+=*) *$/;function Ke(s,e){if(!s)return;let t=Ut.exec(s);if(t?.[1])try{let i=Buffer.from(t[1],"base64"),n=Buffer.from(`${e}:`);if(i.length>n.length&&i.subarray(0,n.length).equals(n))return i.subarray(n.length);let r=i.indexOf(58);if(r!==-1&&i.subarray(0,r).toString("utf8")===e)return i.subarray(r+1)}catch{}}function _(s,e,t,i){if(!s.writable)return;let n=kt.STATUS_CODES[e]??"Unknown",r=t??n,o={Connection:"close","Content-Type":"text/plain; charset=utf-8","Content-Length":Buffer.byteLength(r,"utf8"),...i},d=Object.entries(o).map(([p,c])=>`${p}: ${c}`).join(`\r
4821
4821
  `);s.end(`HTTP/1.1 ${e} ${n}\r
4822
4822
  ${d}\r
4823
4823
  \r
4824
- ${r}`);}var {CONNECTING:U,OPEN:O,CLOSING:_e,CLOSED:w}=ne,ae=class s extends EventEmitter{static CONNECTING=U;static OPEN=O;static CLOSING=_e;static CLOSED=w;_options;_state=w;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_pingTimer=null;_pongTimer=null;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_lastActivity=0;_outboundBuffer=[];_offlineQueue=[];_middleware;_validators=[];_strictProtocols=null;_handshake=null;_logger=M;_exchangeLog=false;_prettify=false;constructor(e){if(super(),this.setMaxListeners(0),!e.identity)throw new Error("identity is required");this._identity=e.identity,this._options={reconnect:true,maxReconnects:1/0,backoffMin:1e3,backoffMax:3e4,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,securityProfile:0,...e},this._callQueue=new le(this._options.callConcurrency),this._middleware=new ce;let t=this._options.logging,i=pe(t,{component:"OCPPClient",identity:this._identity});this._logger=i||M,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(Ie(this._logger,this._identity,this._options.logging)),this._options.strictMode&&this._setupValidators();}_logExchange(e,t,i,n){if(!this._logger)return;let r=e==="OUT"?"\u2192":"\u2190",a=t==="CALLERROR"?"warn":this._exchangeLog?"info":"debug";if(this._exchangeLog&&this._prettify){let o=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",d=i??t,p=`${o} ${this._identity} ${r} ${d} [${e}]`;this._logger?.[a]?.(p,{...n,direction:e});}else this._exchangeLog?this._logger?.[a]?.(`${t} ${r}`,{...n,direction:e}):this._logger?.[a]?.(`${t} ${r}`,n);}get log(){return this._logger||M}get identity(){return this._options.identity}get endpoint(){return this._options.endpoint}get options(){return this._options}get protocol(){return this._protocol}get state(){return this._state}get securityProfile(){return this._options.securityProfile??0}async connect(){if(this._state!==w)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=U,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let i=this._buildEndpoint(),n=this._buildWsOptions();this._logger?.debug?.("Connecting",{url:i}),this.emit("connecting",{url:i});let r=new re(i,this._options.protocols??[],n);this._ws=r;let a=()=>{if(p(),this._state=O,this._protocol=r.protocol,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._attachWebsocket(r),this._startPing(),this._flushOfflineQueue(),this._outboundBuffer.length>0){let m=this._outboundBuffer;this._outboundBuffer=[];for(let h of m)this._ws?.send(h);}this._logger?.info?.("Connected",{protocol:r.protocol});let l={response:r._req?.res};this.emit("open",l),e(l);},o=c=>{p(),this._state=w,this._logger?.error?.("Connection error",{error:c.message}),this.emit("error",c),t(c);},d=(c,l)=>{p(),this._state=w;let m=new z(`Unexpected HTTP response: ${l.statusCode}`,l.statusCode??0,l.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:l.statusCode}),this.emit("error",m),t(m);},p=()=>{r.removeListener("open",a),r.removeListener("error",o),r.removeListener("unexpected-response",d);};r.on("open",a),r.on("error",o),r.on("unexpected-response",d);})}async close(e={}){let{code:t=1e3,reason:i="",awaitPending:n=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===w?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,i,n,r),this._closePromise)}async _closeInternal(e,t,i,n){if(this._state=_e,this._stopPing(),!n&&i){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(o=>{let d=a.resolve,p=a.reject;a.resolve=c=>{d(c),o();},a.reject=c=>{p(c),o();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===re.CLOSED){this._state=w,this._cleanup();let o={code:e,reason:t};this.emit("close",o),r(o);return}let a=(o,d)=>{this._ws?.removeListener("close",a),this._state=w,this._cleanup();let p={code:o,reason:d.toString()};this.emit("close",p),r(p);};this._ws.on("close",a),n?this._ws.terminate():this._ws.close(Je(e)?e:1e3,t);})}handle(...e){if(e.length===1&&typeof e[0]=="function"){if(this._wildcardHandler)throw new Error("Wildcard handler is already registered.");this._wildcardHandler=e[0];}else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function"){if(this._handlers.has(e[0]))throw new Error(`Handler for '${e[0]}' is already registered.`);this._handlers.set(e[0],e[1]);}else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function"){let t=`${e[0]}:${e[1]}`;if(this._handlers.has(t))throw new Error(`Handler for '${e[1]}' (protocol: ${e[0]}) is already registered.`);this._handlers.set(t,e[2]);}else throw new Error("Invalid arguments: provide (version, method, handler), (method, handler), or (wildcardHandler)")}removeHandler(e,t){e&&t?this._handlers.delete(`${e}:${t}`):e?this._handlers.delete(e):this._wildcardHandler=null;}removeAllHandlers(){this._handlers.clear(),this._wildcardHandler=null;}use(e){this._middleware.use(e);}async call(...e){let t,i,n;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],i=e[2]??{},n=e[3]??{}):(t=e[0],i=e[1]??{},n=e[2]??{}),this._state!==O){if(this._options.offlineQueue&&(this._state===w||this._state===U))return new Promise((a,o)=>{let d=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=d&&(this._offlineQueue.shift(),this._logger?.warn?.("Offline queue full \u2014 dropping oldest message",{method:t,queueSize:this._offlineQueue.length})),this._offlineQueue.push({method:t,params:i,options:n,resolve:a,reject:o}),this._logger?.debug?.("Call queued offline",{method:t,queueSize:this._offlineQueue.length});});throw new Error(`Cannot call: client is in state ${this._state}`)}let r=n.retries??0;return r>0?this._callWithRetry(t,i,n,r):this._callQueue.push(()=>this._sendCall(t,i,n))}async safeCall(...e){try{return await this.call(...e)}catch(t){if(t.name!=="TimeoutError"){let i={method:e.find(n=>typeof n=="string"&&!n.startsWith("ocpp")),error:t};this._logger?.warn?this._logger.warn("SafeCall failed",i):console.warn("SafeCall failed",i);}return}}async _sendCall(e,t,i){let n=i.idempotencyKey??ue(),r=i.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:n,method:e,params:t,options:i},o;return await this._middleware.execute(a,async d=>{let p=d;this._options.strictMode&&this._protocol&&this._validateOutbound(p.method,p.params,"req");let c=[E.CALL,n,p.method,p.params],l=JSON.stringify(c);return o=await new Promise((m,h)=>{let D=setTimeout(()=>{this._pendingCalls.delete(n),h(new F(`Call to "${p.method}" timed out after ${r}ms`));},r),f=()=>{clearTimeout(D),this._pendingCalls.delete(n),h(new Error("Aborted"));};i.signal&&i.signal.addEventListener("abort",f),this._pendingCalls.set(n,{resolve:m,reject:h,timeoutHandle:D,abortHandler:i.signal?()=>i.signal?.removeEventListener("abort",f):void 0,method:p.method,sentAt:Date.now()}),this._ws?.readyState===re.OPEN?this._safeSend(this._ws,l,j=>{j&&(clearTimeout(D),this._pendingCalls.delete(n),h(j));}):this._state===U?(this._logger?.debug?.("Buffering call",{method:p.method}),this._outboundBuffer.push(l)):(clearTimeout(D),this._pendingCalls.delete(n),h(new Error(`WebSocket is not open (state: ${this._state})`)));}),o}),o}sendRaw(e){if(this._state===O&&this._ws)this._ws.send(e);else if(this._state===U)this._outboundBuffer.push(e);else throw new Error("Cannot send: client is not connected")}reconfigure(e){Object.assign(this._options,e),e.callConcurrency!==void 0&&this._callQueue.setConcurrency(e.callConcurrency),(e.strictMode!==void 0||e.strictModeValidators!==void 0)&&this._setupValidators(),e.pingIntervalMs!==void 0&&(this._stopPing(),this._state===O&&this._startPing());}_attachWebsocket(e){e.on("message",t=>this._onMessage(t)),e.on("close",(t,i)=>this._onClose(t,i)),e.on("error",t=>this.emit("error",t)),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_onMessage(e,t){this._recordActivity();let i;try{if(t!==void 0?i=t:i=JSON.parse(e),!Array.isArray(i))throw new Error("Message is not an array")}catch(d){this._onBadMessage(typeof e=="string"?e:e.toString(),d);return}let n=i[0],r=i[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new L(`Invalid MessageId type: ${typeof r} (expected string)`));return}if(n===E.CALL&&i.length<4||n===E.CALLRESULT&&i.length<3||n===E.CALLERROR&&i.length<5){this._onBadMessage(JSON.stringify(i),new L(`Missing payload elements for message type ${n}`));return}let a=n===E.CALLERROR?4:n===E.CALL?3:2,o=i[a];if(typeof o!="object"||o===null||Array.isArray(o)){this._onBadMessage(JSON.stringify(i),new L(`Payload must be a JSON object, got ${o===null?"null":Array.isArray(o)?"array":typeof o}`));return}switch(n){case E.CALL:this._handleIncomingCall(i);break;case E.CALLRESULT:this._handleCallResult(i);break;case E.CALLERROR:this._handleCallError(i);break;default:this._onBadMessage(JSON.stringify(i),new L(`Unknown message type: ${n}`));}}async _handleIncomingCall(e){let[,t,i,n]=e,r={type:"incoming_call",messageId:t,method:i,params:n,protocol:this._protocol};try{await this._middleware.execute(r,async a=>{let o=a,d=[E.CALL,o.messageId,o.method,o.params];if(this.emit("call",d),this._state===O)try{if(this._pendingResponses.has(o.messageId))throw q("RpcFrameworkError",`Already processing call with ID: ${o.messageId}`);let p=(this._protocol?this._handlers.get(`${this._protocol}:${o.method}`):void 0)??this._handlers.get(o.method);if(!p&&!this._wildcardHandler)throw new R(`Method "${o.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(o.method,o.params,"req"),this._pendingResponses.add(o.messageId);let c=new AbortController,l={messageId:o.messageId,method:o.method,protocol:this._protocol,params:o.params,signal:c.signal},m;if(p?m=await p(l):this._wildcardHandler&&(m=await this._wildcardHandler(o.method,l)),this._pendingResponses.delete(o.messageId),m===we)return;this._options.strictMode&&this._protocol&&this._validateOutbound(o.method,m,"conf");let h=[E.CALLRESULT,o.messageId,m];return this._ws?.send(JSON.stringify(h)),this.emit("callResult",h),m}catch(p){this._pendingResponses.delete(o.messageId);let c=p instanceof C||p.rpcErrorCode?p:q("InternalError",p.message),l=this._options.respondWithDetailedErrors?Ee(p):{},m=[E.CALLERROR,o.messageId,c.rpcErrorCode,c.rpcErrorMessage||p.message||"",l];throw this._ws?.send(JSON.stringify(m)),this.emit("callError",m),p}});}catch{}}async _handleCallResult(e){let[,t,i]=e;if(!this._pendingCalls.has(t)){this._logger?.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let n=this._pendingCalls.get(t),r={type:"incoming_result",messageId:t,payload:i,method:n.method};await this._middleware.execute(r,async a=>{let o=a,d=this._pendingCalls.get(o.messageId);d&&(this.emit("callResult",e),clearTimeout(d.timeoutHandle),d.abortHandler,this._pendingCalls.delete(o.messageId),d.resolve(o.payload));});}async _handleCallError(e){let[,t]=e,i=this._pendingCalls.get(t);if(!i){this._logger?.warn?.("Received CallError for unknown messageId",{messageId:t});return}let n={type:"incoming_error",messageId:t,error:e,method:i.method};await this._middleware.execute(n,async r=>{let a=r,[,,o,d,p]=a.error,c=this._pendingCalls.get(a.messageId);if(!c)return;this.emit("callError",a.error),clearTimeout(c.timeoutHandle),this._pendingCalls.delete(a.messageId);let l=q(o,d,p);c.reject(l);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let i=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(i?.[1]&&this._ws){let n=[E.CALLERROR,i[1],"FormatViolation",t.message||"Invalid message format",{}];this._ws.send(JSON.stringify(n)),this.emit("callError",n);}this._badMessageCount>=this._options.maxBadMessages&&this.close({code:1002,reason:"Too many bad messages"}).catch(()=>{});}_rejectPendingCalls(e){for(let[,t]of this._pendingCalls)clearTimeout(t.timeoutHandle),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._stopPing();let i=t.toString();this._rejectPendingCalls(`Connection closed (${e}: ${i})`),this._state!==_e?(this._logger?.info?.("Disconnected",{code:e,reason:i}),this.emit("disconnect",{code:e,reason:i}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=w,this.emit("close",{code:e,reason:i}))):this._state=w;}static _INTOLERABLE_ERRORS=new Set(["Maximum redirects exceeded","Server sent no subprotocol","Server sent an invalid subprotocol","Server sent a subprotocol but none was requested","Invalid Sec-WebSocket-Accept header"]);_scheduleReconnect(){this._reconnectAttempt++,this._state=U;let e=this._options.backoffMin,t=this._options.backoffMax,i=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(i)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:i}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(n){let r=n instanceof Error?n.message:"";if(s._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=w,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=w,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},i);}_flushOfflineQueue(){if(this._offlineQueue.length===0)return;let e=this._offlineQueue.splice(0,this._offlineQueue.length);this._logger?.info?.("Flushing offline queue",{count:e.length});for(let t of e)this._callQueue.push(()=>this._sendCall(t.method,t.params,t.options)).then(t.resolve).catch(t.reject);}async _callWithRetry(e,t,i,n){let r=i.retryDelayMs??1e3,a=i.retryMaxDelayMs??3e4;for(let o=0;o<=n;o++)try{return await this._callQueue.push(()=>this._sendCall(e,t,i))}catch(d){if(o===n||!(d instanceof F))throw d;let p=Math.min(a,r*2**o),c=Math.random()*p;this._logger?.warn?.("Call retry",{method:e,attempt:o+1,maxRetries:n,delayMs:Math.round(c)}),await new Promise(l=>setTimeout(l,c));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_safeSend(e,t,i){if(!e||e.readyState!==re.OPEN){i?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>s._BACKPRESSURE_THRESHOLD){this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:s._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount});let n=0,r=setInterval(()=>{if(n+=50,!e||e.readyState!==re.OPEN){clearInterval(r),i?.(new Error("WebSocket closed during backpressure wait"));return}(e.bufferedAmount<=s._BACKPRESSURE_THRESHOLD||n>=1e4)&&(clearInterval(r),e.send(t,i));},50);}else e.send(t,i);}_startPing(){if(this._options.pingIntervalMs<=0)return;let e=this._options.pongTimeoutMs??this._options.pingIntervalMs+5e3,t=()=>{if(this._state!==O||!this._ws)return;if(this._options.deferPingsOnActivity){let r=Date.now()-this._lastActivity;if(r<this._options.pingIntervalMs){this._pingTimer=setTimeout(t,this._options.pingIntervalMs-r);return}}this._ws.ping(),e>0&&(this._pongTimer=setTimeout(()=>{this._logger?.warn?.("Pong timeout \u2014 terminating dead connection",{identity:this._identity,timeoutMs:e}),this._ws?.terminate();},e));let n=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,n);},i=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,i);}_stopPing(){this._pingTimer&&(clearTimeout(this._pingTimer),this._pingTimer=null);}_recordActivity(){this._lastActivity=Date.now();}_setupValidators(){this._options.strictModeValidators?this._validators=this._options.strictModeValidators:this._validators=xe(),Array.isArray(this._options.strictMode)?this._strictProtocols=this._options.strictMode:this._strictProtocols=null;}_validateOutbound(e,t,i){let n=this._findValidator();if(!n||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${i}`;try{n.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_validateInbound(e,t,i){let n=this._findValidator();if(!n||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${i}`;try{n.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_findValidator(){return !this._protocol||this._strictProtocols&&!this._strictProtocols.includes(this._protocol)?null:this._validators.find(e=>e.subprotocol===this._protocol)??null}_buildEndpoint(){let e=this._options.endpoint;if(e.endsWith("/")||(e+="/"),e+=encodeURIComponent(this._identity),this._options.query){let t=new URLSearchParams(this._options.query);e+=(e.includes("?")?"&":"?")+t.toString();}return e}_buildWsOptions(){let e={headers:{...this._options.headers,"User-Agent":De()}},t=this._options.securityProfile??0;if((t===1||t===2)&&this._options.password){let n=Buffer.from(`${this._identity}:${this._options.password.toString()}`).toString("base64");e?.headers&&(e.headers.Authorization=`Basic ${n}`);}if(t===2||t===3){let n=this._options.tls??{};n.ca&&(e.ca=n.ca),n.rejectUnauthorized!==void 0&&(e.rejectUnauthorized=n.rejectUnauthorized),t===3&&(n.cert&&(e.cert=n.cert),n.key&&(e.key=n.key),n.passphrase&&(e.passphrase=n.passphrase));}let i=this._options.compression;return i&&(e.perMessageDeflate=i===true?{zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},clientNoContextTakeover:true,serverNoContextTakeover:true}:{zlibDeflateOptions:{level:i.level??6,memLevel:i.memLevel??8},zlibInflateOptions:{},clientNoContextTakeover:i.clientNoContextTakeover??true,serverNoContextTakeover:i.serverNoContextTakeover??true}),e}_cleanup(){this._stopPing(),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=null,this._ws=null;}};var oe=class extends Map{_maxSize;constructor(e){if(super(),e<1)throw new RangeError("LRUMap maxSize must be >= 1");this._maxSize=e;}get maxSize(){return this._maxSize}set(e,t){if(this.has(e)&&this.delete(e),super.set(e,t),this.size>this._maxSize){let i=this.keys().next().value;i!==void 0&&this.delete(i);}return this}get(e){if(!this.has(e))return;let t=super.get(e);return this.delete(e),super.set(e,t),t}};async function Xe(s,e){let t=-1,i=async(n,r)=>{if(r&&(e.state={...e.state||{},...r||{}}),n<=t)throw new Error("next() called multiple times in middleware");t=n;let a=s[n];n!==s.length&&a&&(e.next=i.bind(null,n+1),await a(e));};await i(0);}var A=class extends EventEmitter{patterns;middlewares;authCallback=null;_routeCORS;_routeConfig;_regexPatterns=[];constructor(e,t){super(),this.patterns=[],this.middlewares=t??[],e?.length&&this.route(...e);}route(...e){this.patterns.push(...e);for(let t of e)typeof t!="string"&&this._regexPatterns.push({regex:t,paramNames:[]});return this}use(...e){return this.middlewares.push(...e),this}cors(e){return this._routeCORS=e,this}config(e){return this._routeConfig=e,this}auth(e){return this.authCallback=e,this}handle(...e){return this.on("client",t=>{let i=e[e.length-1],n=[...e];typeof i=="function"&&(n[n.length-1]=(...r)=>{let a=r.length-1,o=r[a];return o&&typeof o=="object"&&Object.defineProperty(o,"client",{value:t,enumerable:true,configurable:true}),i(...r)}),t.handle(...n);}),this}};function zt(...s){return new A(s)}function Ye(s){return s.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}function Ze(s,e){let t=s;t.startsWith("::ffff:")&&(t=t.substring(7));for(let i of e){if(i===t)return true;if(i.includes("/")){let n=i.split("/"),r=n[0],a=n[1];if(!r||!a)continue;let o=parseInt(a,10);if(isIPv4(t)&&isIPv4(r)){let d=Ye(t),p=Ye(r),c=o===0?0:-1<<32-o>>>0;if((d&c)===(p&c))return true}}}return false}function Le(s,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=s.socket.remoteAddress;if(!t||!Ze(t,e.allowedIPs))return {allowed:false,reason:"IP address not allowed"}}if(e.allowedSchemes&&e.allowedSchemes.length>0){let t=s.socket instanceof TLSSocket?"wss":"ws",i=s.headers["x-forwarded-proto"];if(typeof i=="string"&&(t=i==="https"||i==="wss"?"wss":"ws"),!e.allowedSchemes.includes(t))return {allowed:false,reason:"Protocol scheme not allowed"}}if(e.allowedOrigins&&e.allowedOrigins.length>0){let t=s.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}var W=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function et(s){return s.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var ge=class{root=new W;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let i=et(e),n=this.root;for(let r of i)if(r==="*"){n.wildcardChild||(n.wildcardChild=new W),n=n.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!n.paramChild)n.paramChild=new W,n.paramChild.paramName=a;else if(n.paramChild.paramName!==a)throw new Error(`Route conflict: param ":${a}" conflicts with existing ":${n.paramChild.paramName}" at the same position in pattern "${e}"`);n=n.paramChild;}else {let a=r.toLowerCase(),o=n.children.get(a);o||(o=new W,n.children.set(a,o)),n=o;}n.routers.push(t),this._size++;}match(e){let t=et(e),i=[];if(this._matchRecursive(this.root,t,0,{},i),i.length===0)return null;let n=i[0].params,r=[];for(let a of i)r.push(...a.routers);return {routers:r,params:n}}_matchRecursive(e,t,i,n,r){if(i===t.length){e.routers.length>0&&r.push({routers:[...e.routers],params:{...n}});return}let a=t[i],o=a.toLowerCase(),d=e.children.get(o);if(d&&this._matchRecursive(d,t,i+1,n,r),e.paramChild){let p={...n};p[e.paramChild.paramName]=decodeURIComponent(a),this._matchRecursive(e.paramChild,t,i+1,p,r);}e.wildcardChild&&e.wildcardChild.routers.length>0&&r.push({routers:[...e.wildcardChild.routers],params:{...n}});}freeze(){this._frozen||(this._freezeNode(this.root),this._frozen=true);}_freezeNode(e){Object.freeze(e.routers),e.paramChild&&this._freezeNode(e.paramChild),e.wildcardChild&&this._freezeNode(e.wildcardChild);for(let t of e.children.values())this._freezeNode(t);}get frozen(){return this._frozen}};var se=class extends ae{_serverSession;_serverHandshake;constructor(e,t){super(e),this._serverSession=t.session,this._serverHandshake=t.handshake,this._adaptiveMultiplier=t.adaptiveMultiplier??null,this._workerPool=t.workerPool??null,this._state=ne.OPEN,this._identity=this._options.identity,this._ws=t.ws,this._protocol=t.protocol??t.ws.protocol,this._attachServerWebsocket(t.ws),this._startPing();}_rateLimits={};_adaptiveMultiplier=null;_workerPool=null;_checkRateLimit(e){let t=this._options.rateLimit;if(!t)return true;let i=Date.now(),n=(r,a,o)=>{let d=this._rateLimits[r];if(!d)d={tokens:a,lastRefill:i},this._rateLimits[r]=d;else {let p=i-d.lastRefill,c=this._adaptiveMultiplier?.()??1,l=a/o*c,m=p*l;m>0&&(d.tokens=Math.min(a,d.tokens+m),d.lastRefill=i);}return d.tokens>=1?(d.tokens-=1,true):false};if(!n("global",t.limit,t.windowMs))return false;if(e&&t.methods?.[e]){let r=t.methods[e];if(!n(`method:${e}`,r.limit,r.windowMs))return false}return true}_attachServerWebsocket(e){e.on("message",t=>{this._recordActivity();let i=this._options.rateLimit;if(i){let n,r;if(i.methods)try{r=JSON.parse(t),Array.isArray(r)&&r[0]===2&&(n=r[2]);}catch{}if(!this._checkRateLimit(n)){this._handleRateLimitExceeded(r||t.toString());return}if(r!==void 0){this._onMessage(t,r);return}}if(this._workerPool){let n=t;this._workerPool.parse(n).then(r=>{this._onMessage(t,r.message);}).catch(()=>{this._onMessage(t);});return}this._onMessage(t);}),e.on("close",(t,i)=>this._onClose(t,i)),e.on("error",t=>{this.listenerCount("error")>0?this.emit("error",t):this._logger?.debug?.("WebSocket error (unhandled by client listener)",{error:t.message});}),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_handleRateLimitExceeded(e){let i=this._options.rateLimit.onLimitExceeded||"ignore";if(i==="disconnect")this._logger?.warn?.("Rate limit exceeded \u2014 disconnecting client",{identity:this.identity}),this._ws?.terminate();else if(typeof i=="function")try{let n=i(this,e);n instanceof Promise&&n.catch(r=>{this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:r});});}catch(n){this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:n});}else this._logger?.debug?.("Rate limit exceeded \u2014 ignoring message",{identity:this.identity});}get session(){return this._serverSession}get handshake(){return this._serverHandshake}async connect(){throw new Error("Cannot connect from server client \u2014 connection is managed by the server")}close(e={}){return super.close(e)}};var $e=class{_workers=[];_nextWorker=0;_taskId=0;_pending=new Map;_maxQueueSize;_terminated=false;constructor(e={}){let t=e.poolSize??Math.max(2,cpus().length-2);this._maxQueueSize=e.maxQueueSize??1e4;let i=resolve(g,"parse-worker.js");for(let n=0;n<t;n++){let r=new Worker(i);r.on("message",a=>{let o=this._pending.get(a.id);o&&(this._pending.delete(a.id),a.error?o.reject(new Error(a.error)):o.resolve({message:a.message,validationError:a.validationError}));}),r.on("error",a=>{console.error(`[WorkerPool] Worker ${n} error:`,a.message);}),this._workers.push(r);}}get size(){return this._workers.length}get pendingTasks(){return this._pending.size}parse(e,t){return this._terminated?Promise.reject(new Error("WorkerPool has been shut down")):this._pending.size>=this._maxQueueSize?Promise.reject(new Error(`WorkerPool queue full (${this._maxQueueSize} pending tasks)`)):new Promise((i,n)=>{let r=this._taskId++;this._pending.set(r,{resolve:i,reject:n});let a=this._workers[this._nextWorker%this._workers.length];this._nextWorker=(this._nextWorker+1)%this._workers.length,a.postMessage({id:r,buffer:e,schemaInfo:t});})}async shutdown(){if(this._terminated)return;this._terminated=true;for(let[t,i]of this._pending)i.reject(new Error("WorkerPool shutting down")),this._pending.delete(t);let e=this._workers.map(async t=>{try{await Promise.race([t.terminate(),new Promise(i=>setTimeout(i,5e3))]);}catch{}});await Promise.allSettled(e),this._workers=[];}};function tt(s={}){try{return new $e(s)}catch{return null}}var je=class extends EventEmitter{_options;_trie=new ge;_globalMiddlewareRouters=[];_regexRouters=[];_clients=new Set;_clientsByIdentity=new Map;_httpServers=new Set;_wss=null;_state="OPEN";_adapter=null;_httpServerAbortControllers=new Set;_logger=null;_globalCORS;_connectionBuckets=new Map;_adaptiveLimiter=null;_plugins=[];_workerPool=null;_nodeId=ue();_sessions;_gcInterval=null;_sessionTimeoutMs;constructor(e={}){if(super(),this.setMaxListeners(0),e.strictMode&&!e.protocols?.length)throw new Error("strictMode requires protocols to be specified (e.g. protocols: ['ocpp1.6'])");this._options={securityProfile:0,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,handshakeTimeoutMs:3e4,sessionTtlMs:7200*1e3,...e},this._sessionTimeoutMs=this._options.sessionTtlMs;let t=this._options.maxSessions??5e4;this._sessions=new oe(t),this._wss=new WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()}),this._gcInterval=setInterval(()=>{let r=Date.now();for(let[a,o]of this._sessions.entries())r-o.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);},60*1e3).unref(),this._logger=pe(this._options.logging,{component:"OCPPServer"});let i=this._options.rateLimit;i?.adaptive&&(this._adaptiveLimiter=new H({cpuThresholdPercent:i.cpuThresholdPercent,memThresholdPercent:i.memThresholdPercent,cooldownMs:i.cooldownMs}),this._adaptiveLimiter.on("adapted",r=>{this._logger?.info?.("Adaptive rate limit adjusted",r),this.emit("rateLimit:adapted",r);}),this._adaptiveLimiter.start());let n=this._options.workerThreads;if(n){let r=typeof n=="object"?n:{};this._workerPool=tt(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||M}get clients(){return this._clients}get state(){return this._state}stats(){let e=0;if(this._wss)for(let t of this._wss.clients)e+=t.bufferedAmount;return {connectedClients:this._clients.size,activeSessions:this._sessions.size,uptimeSeconds:process.uptime(),pid:process.pid,memoryUsage:process.memoryUsage(),cpuUsage:process.cpuUsage(),webSockets:this._wss?{total:this._wss.clients.size,bufferedAmount:e}:void 0}}async adapterMetrics(){if(!this._adapter||!this._adapter.metrics)return null;try{return await this._adapter.metrics()}catch(e){return this._logger?.warn?.("Failed to fetch adapter metrics",{error:e}),null}}getLocalClient(e){return this._clientsByIdentity.get(e)}hasLocalClient(e){return this.getLocalClient(e)!==void 0}async isClientConnected(e){if(this.hasLocalClient(e))return true;if(this._adapter?.getPresence){let t=await this._adapter.getPresence(e);return t!=null}return false}cors(e){return this._globalCORS=e,this}route(...e){let t=new A;return t.route(...e),this._registerRouter(t),t}attachRouters(...e){for(let t of e)this._registerRouter(t);return this}plugin(...e){for(let t of e)if(this._plugins.push(t),this._logger?.info?.("Plugin registered",{name:t.name}),t.onInit){let i=t.onInit(this);i instanceof Promise&&i.catch(n=>{this._logger?.error?.("Plugin onInit error",{name:t.name,error:n.message});});}return this}use(...e){let t=new A;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new A;return t.auth(e),this._registerRouter(t),t}_registerRouter(e){let t=e.patterns.filter(n=>typeof n=="string"),i=e._regexPatterns.length>0;if(t.length===0&&!i)this._globalMiddlewareRouters.push(e);else {for(let n of t)this._trie.insert(n,e);i&&this._regexRouters.push(e);}}async listen(e=0,t,i){let n;if(i?.server)n=i.server;else {let a=this._options.securityProfile??0;if(a===2||a===3){let o=this._options.tls??{},d={};o.cert&&(d.cert=o.cert),o.key&&(d.key=o.key),o.ca&&(d.ca=o.ca),o.passphrase&&(d.passphrase=o.passphrase),a===3&&(d.requestCert=true,d.rejectUnauthorized=o.rejectUnauthorized??true),n=createServer(d);}else n=createServer$1();}this._state==="CLOSED"&&(this._state="OPEN");let r=(a,o,d)=>{this._handleUpgrade(a,o,d).catch(p=>{o.destroyed||o.destroy(),this._logger?.error?.("Upgrade error",{error:p.message}),this.emit("upgradeError",{error:p,socket:o});});};if(n.on("upgrade",r),this._httpServers.add(n),this._options.healthEndpoint&&n.on("request",(a,o)=>{let d=a.url??"";if(d==="/health"){let p=this.stats(),c=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:p.connectedClients,activeSessions:p.activeSessions,uptimeSeconds:Math.round(p.uptimeSeconds),pid:p.pid});o.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),o.end(c);return}if(d==="/metrics"){let p=this.stats(),c=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${p.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${p.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(p.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${p.memoryUsage.rss}`,"","# HELP ocpp_memory_heap_used_bytes V8 heap used in bytes","# TYPE ocpp_memory_heap_used_bytes gauge",`ocpp_memory_heap_used_bytes ${p.memoryUsage.heapUsed}`,"","# HELP ocpp_memory_heap_total_bytes V8 heap total in bytes","# TYPE ocpp_memory_heap_total_bytes gauge",`ocpp_memory_heap_total_bytes ${p.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${p.webSockets?.bufferedAmount??0}`,""];o.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"}),o.end(c.join(`
4825
- `));return}o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not Found");}),i?.signal){let a=new AbortController;this._httpServerAbortControllers.add(a),i.signal.addEventListener("abort",()=>{a.abort(),n.close(),this._httpServers.delete(n);},{once:true});}return i?.server||await new Promise((a,o)=>{n.on("error",o),n.listen(e,t,()=>{n.removeListener("error",o);let d=n.address();this._logger?.info?.("Server listening",{port:typeof d=="object"?d?.port:e,host:t??"0.0.0.0"}),a();});}),n}updateTLS(e){let t=this._options.securityProfile??0;if(t!==2&&t!==3)throw new Error("updateTLS() requires a TLS Security Profile (TLS_BASIC_AUTH or TLS_CLIENT_CERT)");this._options.tls={...this._options.tls,...e};let i={};e.cert&&(i.cert=e.cert),e.key&&(i.key=e.key),e.ca&&(i.ca=e.ca),e.passphrase&&(i.passphrase=e.passphrase);let n=0;for(let r of this._httpServers)"setSecureContext"in r&&typeof r.setSecureContext=="function"&&(r.setSecureContext(i),n++);this._logger?.info?.(`TLS context hot-reloaded across ${n} active server(s)`);}get handleUpgrade(){return (e,t,i)=>this._handleUpgrade(e,t,i).catch(n=>{t.destroyed||t.destroy(),this._logger?.error?.("Upgrade error",{error:n.message}),this.emit("upgradeError",{error:n,socket:t});})}async _handleUpgrade(e,t,i){if(this._state!=="OPEN"){_(t,503,"Server is shutting down");return}let n=this._options.connectionRateLimit;if(n){let u=e.socket.remoteAddress??"unknown",b=Date.now(),T=this._connectionBuckets.get(u);if(!T)T={tokens:n.limit,lastRefill:b},this._connectionBuckets.set(u,T);else {let v=b-T.lastRefill,S=n.limit/n.windowMs;T.tokens=Math.min(n.limit,T.tokens+v*S),T.lastRefill=b;}if(T.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:u}),this.emit("securityEvent",{type:"CONNECTION_RATE_LIMIT",ip:u,timestamp:new Date().toISOString(),details:{tokensRemaining:T.tokens}}),_(t,429,"Too Many Requests");return}T.tokens-=1;}if(t.readyState!=="open"){this._logger?.debug?.("Socket not open at upgrade start"),t.destroyed||t.destroy();return}if(e.headers.upgrade?.toLowerCase()!=="websocket"){_(t,400,"Invalid upgrade request");return}if(this._globalCORS){let{allowed:u,reason:b}=Le(e,this._globalCORS);if(!u){this._logger?.warn?.("CORS rejected connection",{reason:b,ip:e.socket.remoteAddress}),_(t,403,"Forbidden");return}}let r=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),a,o=[],d=[],p={},c=r.pathname,l=false,m=this._trie.size>0||this._regexRouters.length>0,h;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let u of this._globalMiddlewareRouters)d.push(u),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);let D=this._trie.match(c);if(D){Object.assign(p,D.params);for(let u of D.routers)d.push(u),l=true,u._routeConfig&&(h=Object.assign(h||{},u._routeConfig)),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);}for(let u of this._regexRouters)for(let b of u._regexPatterns){let T=b.regex.exec(c);if(T){if(d.push(u),l=true,T.groups)for(let[v,S]of Object.entries(T.groups))p[v]=decodeURIComponent(S??"");u._routeConfig&&(h=Object.assign(h||{},u._routeConfig)),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);break}}let f=p.identity;if(!f){let u=c.split("/").filter(Boolean);f=decodeURIComponent(u[u.length-1]??"");}if(!f){_(t,400,"Missing identity in URL path");return}for(let u of d)if(u._routeCORS){let{allowed:b,reason:T}=Le(e,u._routeCORS);if(!b){this._logger?.warn?.("Route CORS rejected connection",{reason:T,ip:e.socket.remoteAddress}),_(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let j=new Set,Re=e.headers["sec-websocket-protocol"];if(Re)try{j=Ge(Re);}catch{_(t,400,"Invalid Sec-WebSocket-Protocol header");return}let qe=h?.protocols??this._options.protocols??[],V;if(qe.length>0){if(j.size===0){_(t,400,"Missing subprotocol");return}if(V=qe.find(u=>j.has(u)),!V){_(t,400,"No matching subprotocol");return}}let it=Ke(e.headers.authorization??"",f),Me,Oe=this._options.securityProfile??0;Oe===3&&"getPeerCertificate"in t&&(Me=t.getPeerCertificate());let de={identity:f,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:j,pathname:c,params:p,query:r.searchParams,request:e,password:it,clientCertificate:Me,securityProfile:Oe},ye,Ve;if(a||o.length>0){let u=new AbortController,b=()=>{u.abort(new Error("Socket closed during handshake"));};t.on("close",b),t.on("error",b),t.on("end",b);let T=this._options.handshakeTimeoutMs??3e4,v;T>0&&(v=setTimeout(()=>{u.abort(new Error("Handshake timeout"));},T));try{ye={handshake:de,state:{},reject:(I=401,x="Unauthorized")=>{throw {code:I,message:x,_isMiddlewareReject:!0}},next:async I=>{}};let S=[...o],P=!1;if(S.push(async I=>{P=!0,a?Ve=await new Promise((x,$)=>{let N=!1,nt=k=>{N||(N=!0,k?.protocol&&(V=k.protocol),x(k));},rt=(k=401,Ne="Unauthorized")=>{throw N||(N=!0,$({code:k,message:Ne})),{code:k,message:Ne,_isMiddlewareReject:!0}};if(u.signal.aborted){$(u.signal.reason);return}u.signal.addEventListener("abort",()=>{N||(N=!0,$(u.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:f,pathname:c});let at={handshake:de,state:I.state,reject:rt,signal:u.signal,accept:nt};a(at);}):V=de.protocols.values().next().value??void 0;}),await Xe(S,ye),!P)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(S){if(u.signal.aborted){let $=S instanceof Error?S.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:f,reason:$}),this.emit("securityEvent",{type:"UPGRADE_ABORTED",identity:f,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:$}}),this.emit("upgradeAborted",{identity:f,reason:$,socket:t,request:e}),t.destroyed||t.destroy();return}let P=S,I=typeof P?.code=="number"?P.code:401,x=typeof P?.message=="string"?P.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:f,code:I}),this.emit("securityEvent",{type:"AUTH_FAILED",identity:f,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:I,message:x}}),_(t,I,x);return}finally{v&&clearTimeout(v),t.removeListener("close",b),t.removeListener("error",b),t.removeListener("end",b);}}else if(m&&!l){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:c}),_(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:f}),t.destroyed||t.destroy();return}this._wss||(this._wss=new WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536})),this._wss.handleUpgrade(e,t,i,u=>{let b={identity:f,endpoint:"",callTimeoutMs:h?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:h?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:h?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:h?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:h?.strictMode??this._options.strictMode,strictModeMethods:h?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:h?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},T={...ye?.state||{},...this._sessions.get(f)?.data||{},...Ve?.session||{}},v=new se(b,{ws:u,handshake:de,session:T,protocol:V,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0});this._updateSessionActivity(f,v.session);let S=this._clientsByIdentity.get(f);S&&S!==v&&(this._logger?.warn?.("Evicting stale connection for identity",{identity:f,reason:"Duplicate identity replaced by new connection"}),S.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(S)),this._clients.add(v),this._clientsByIdentity.set(f,v),this._adapter?.setPresence&&this._adapter.setPresence(f,this._nodeId,300).catch(P=>{this._logger?.error?.("Error setting presence",{identity:f,error:P});}),this._logger?.info?.("Client connected",{identity:f,remoteAddress:e.socket.remoteAddress,protocol:V}),v.on("close",({code:P,reason:I})=>{this._clients.delete(v),this._clientsByIdentity.get(f)===v&&this._clientsByIdentity.delete(f),this?._adapter?.removePresence&&this._adapter.removePresence(f).catch(x=>{this._logger?.error?.("Error removing presence",{identity:f,error:x});});for(let x of this._plugins)try{x.onDisconnect?.(v,P,I);}catch($){this._logger?.error?.("Plugin onDisconnect error",{name:x.name,error:$.message});}this._logger?.info?.("Client disconnected",{identity:f});});for(let P of this._plugins)try{let I=P.onConnection?.(v);I instanceof Promise&&I.catch(x=>{this._logger?.error?.("Plugin onConnection error",{name:P.name,error:x.message});});}catch(I){this._logger?.error?.("Plugin onConnection error",{name:P.name,error:I.message});}this.emit("client",v);for(let P of d)P.emit("client",v);v.on("message",()=>{this._updateSessionActivity(f,v.session);});});}_updateSessionActivity(e,t){this._sessions.set(e,{data:t,lastActive:Date.now()});}async close(e={}){if(this._state!=="OPEN")return;if(this._state="CLOSING",this.emit("closing"),this._logger?.info?.("Server closing",{clientCount:this._clients.size}),this._gcInterval&&(clearInterval(this._gcInterval),this._gcInterval=null),!e.force){let r=Array.from(this._clients).map(async a=>{let o=a._ws;o&&o.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:o.bufferedAmount}),await new Promise(d=>{let p=0,c=setInterval(()=>{p+=50,(!o||o.bufferedAmount===0||p>=5e3)&&(clearInterval(c),d());},50);}));});await Promise.allSettled(r);}let t=Array.from(this._clients).map(n=>n.close(e).catch(()=>{}));await Promise.allSettled(t);for(let n of this._httpServerAbortControllers)n.abort();this._httpServerAbortControllers.clear(),this._wss&&(this._wss.close(),this._wss=new WebSocketServer({noServer:true}));let i=Array.from(this._httpServers).map(n=>new Promise(r=>{n.close(()=>r());}));await Promise.allSettled(i),this._httpServers.clear(),this._adaptiveLimiter&&this._adaptiveLimiter.stop();for(let n of this._plugins)try{let r=n.onClose?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClose error",{name:n.name,error:r.message});}this._adapter&&await this._adapter.disconnect(),this._state="CLOSED",this.emit("close");}reconfigure(e){Object.assign(this._options,e);}async sendToClient(...e){let t,i,n,r;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],i=e[2],n=e[3],r=e[4]):(t=e[0],i=e[1],n=e[2],r=e[3]);for(let a of this._clients)if(a.identity===t)return await a.call(i,n,r);if(this._adapter?.getPresence){let a=await this._adapter.getPresence(t);if(a){await this._adapter.publish(`ocpp:node:${a}`,{source:this._nodeId,target:t,method:i,params:n,options:r});return}}throw new Error(`Client ${t} not found`)}async safeSendToClient(...e){try{return await this.sendToClient(...e)}catch(t){this._logger&&typeof this._logger.warn=="function"&&t.name!=="TimeoutError"&&this._logger.warn("SafeSendToClient failed",{identity:e[0],method:e.length>=4&&typeof e[1]=="string"&&typeof e[2]=="string"?e[2]:e.length>=3&&typeof e[1]=="string"?e[1]:"unknown",error:t});return}}async sendBatch(e,t){if(t.length===0)return [];let i=this._clientsByIdentity.get(e);if(!i)return this._logger?.warn?.("sendBatch: client not found locally",{identity:e}),t.map(()=>{});let n=i.options.callConcurrency??1;t.length>n&&i.reconfigure({callConcurrency:t.length});try{return (await Promise.allSettled(t.map(a=>i.call(a.method,a.params,a.options??{})))).map(a=>{if(a.status==="fulfilled")return a.value;this._logger?.warn?.("sendBatch: individual call failed",{identity:e,error:a.reason?.message});})}finally{t.length>n&&i.reconfigure({callConcurrency:n});}}async setAdapter(e){this._adapter=e,await this._adapter.subscribe("ocpp:broadcast",t=>this._onBroadcast(t)),await this._adapter.subscribe(`ocpp:node:${this._nodeId}`,t=>{this._onUnicast(t);});}_onBroadcast(e){try{if(!e||typeof e!="object")return;let t=e;if(t.source===this._nodeId)return;for(let i of this._clients)i.call(t.method,t.params).catch(()=>{});}catch(t){this._logger?.error?.("Error processing broadcast message",{error:t.message});}}_onUnicast(e){try{if(!e||typeof e!="object")return;let t=e;for(let i of this._clients)if(i.identity===t.target){i.call(t.method,t.params,t.options).catch(n=>{n.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:t.target,error:n});});return}this._logger?.warn?.("Received unicast for unknown client",{target:t.target}),this._adapter?.removePresence&&this._adapter.removePresence(t.target).catch(()=>{});}catch(t){this._logger?.error?.("Error processing unicast",{error:t.message});}}async publish(e,t){this._adapter&&await this._adapter.publish(e,t);}async broadcast(e,t){let i=Array.from(this._clients).map(r=>r.call(e,t).catch(()=>{})),n=this._adapter?this._adapter.publish("ocpp:broadcast",{source:this._nodeId,method:e,params:t}):Promise.resolve();await Promise.all([Promise.all(i),n]);}async broadcastBatch(e,t,i,n){let r=new Set,a=[];for(let d of e){let p=this._clientsByIdentity.get(d);p&&(r.add(d),a.push(p.call(t,i,n).catch(()=>{})));}let o=e.filter(d=>!r.has(d));if(o.length>0&&this._adapter){let d=[];this._adapter.getPresenceBatch?d=await this._adapter.getPresenceBatch(o):this._adapter.getPresence&&(d=await Promise.all(o.map(c=>this._adapter.getPresence(c))));let p=[];for(let c=0;c<o.length;c++){let l=d[c];l&&p.push({channel:`ocpp:node:${l}`,data:{source:this._nodeId,target:o[c],method:t,params:i,options:n}});}p.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(p):await Promise.all(p.map(c=>this._adapter.publish(c.channel,c.data))));}await Promise.all(a);}_buildCompressionConfig(){let e=this._options.compression;return e?e===true?{threshold:1024,zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},serverNoContextTakeover:true,clientNoContextTakeover:true}:{threshold:e.threshold??1024,zlibDeflateOptions:{level:e.level??6,memLevel:e.memLevel??8},zlibInflateOptions:{},serverNoContextTakeover:e.serverNoContextTakeover??true,clientNoContextTakeover:e.clientNoContextTakeover??true}:false}};
4826
- export{H as AdaptiveLimiter,ve as ClusterDriver,ne as ConnectionState,Te as InMemoryAdapter,oe as LRUMap,E as MessageType,ce as MiddlewareStack,we as NOREPLY,ae as OCPPClient,A as OCPPRouter,je as OCPPServer,se as OCPPServerClient,Q as RPCFormatViolationError,X as RPCFormationViolationError,te as RPCFrameworkError,C as RPCGenericError,G as RPCInternalError,L as RPCMessageTypeNotSupportedError,R as RPCNotImplementedError,B as RPCNotSupportedError,Z as RPCOccurrenceConstraintViolationError,Y as RPCPropertyConstraintViolationError,J as RPCProtocolError,K as RPCSecurityError,ee as RPCTypeConstraintViolationError,Pe as RedisAdapter,fe as SecurityProfile,F as TimeoutError,z as UnexpectedHttpResponse,me as Validator,Se as WebsocketUpgradeError,Ct as combineAuth,Ie as createLoggingMiddleware,yt as createPlugin,q as createRPCError,zt as createRouter,ie as createValidator,ct as defineAdapter,vt as defineAuth,gt as defineMiddleware,Tt as defineRpcMiddleware,Ee as getErrorPlainObject,De as getPackageIdent,xe as getStandardValidators};
4824
+ ${r}`);}var {CONNECTING:U,OPEN:O,CLOSING:_e,CLOSED:w}=ne,ae=class s extends EventEmitter{static CONNECTING=U;static OPEN=O;static CLOSING=_e;static CLOSED=w;_options;_state=w;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_pingTimer=null;_pongTimer=null;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_lastActivity=0;_outboundBuffer=[];_offlineQueue=[];_middleware;_validators=[];_strictProtocols=null;_handshake=null;_logger=M;_exchangeLog=false;_prettify=false;constructor(e){if(super(),this.setMaxListeners(0),!e.identity)throw new Error("identity is required");this._identity=e.identity,this._options={reconnect:true,maxReconnects:1/0,backoffMin:1e3,backoffMax:3e4,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,securityProfile:0,...e},this._callQueue=new le(this._options.callConcurrency),this._middleware=new ce;let t=this._options.logging,i=pe(t,{component:"OCPPClient",identity:this._identity});this._logger=i||M,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(Ie(this._logger,this._identity,this._options.logging)),this._options.strictMode&&this._setupValidators();}_logExchange(e,t,i,n){if(!this._logger)return;let r=e==="OUT"?"\u2192":"\u2190",a=t==="CALLERROR"?"warn":this._exchangeLog?"info":"debug";if(this._exchangeLog&&this._prettify){let o=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",d=i??t,p=`${o} ${this._identity} ${r} ${d} [${e}]`;this._logger?.[a]?.(p,{...n,direction:e});}else this._exchangeLog?this._logger?.[a]?.(`${t} ${r}`,{...n,direction:e}):this._logger?.[a]?.(`${t} ${r}`,n);}get log(){return this._logger||M}get identity(){return this._options.identity}get endpoint(){return this._options.endpoint}get options(){return this._options}get protocol(){return this._protocol}get state(){return this._state}get securityProfile(){return this._options.securityProfile??0}async connect(){if(this._state!==w)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=U,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let i=this._buildEndpoint(),n=this._buildWsOptions();this._logger?.debug?.("Connecting",{url:i}),this.emit("connecting",{url:i});let r=new re(i,this._options.protocols??[],n);this._ws=r;let a=()=>{if(p(),this._state=O,this._protocol=r.protocol,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._attachWebsocket(r),this._startPing(),this._flushOfflineQueue(),this._outboundBuffer.length>0){let m=this._outboundBuffer;this._outboundBuffer=[];for(let h of m)this._ws?.send(h);}this._logger?.info?.("Connected",{protocol:r.protocol});let l={response:r._req?.res};this.emit("open",l),e(l);},o=c=>{p(),this._state=w,this._logger?.error?.("Connection error",{error:c.message}),this.emit("error",c),t(c);},d=(c,l)=>{p(),this._state=w;let m=new z(`Unexpected HTTP response: ${l.statusCode}`,l.statusCode??0,l.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:l.statusCode}),this.emit("error",m),t(m);},p=()=>{r.removeListener("open",a),r.removeListener("error",o),r.removeListener("unexpected-response",d);};r.on("open",a),r.on("error",o),r.on("unexpected-response",d);})}async close(e={}){let{code:t=1e3,reason:i="",awaitPending:n=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===w?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,i,n,r),this._closePromise)}async _closeInternal(e,t,i,n){if(this._state=_e,this._stopPing(),!n&&i){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(o=>{let d=a.resolve,p=a.reject;a.resolve=c=>{d(c),o();},a.reject=c=>{p(c),o();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===re.CLOSED){this._state=w,this._cleanup();let o={code:e,reason:t};this.emit("close",o),r(o);return}let a=(o,d)=>{this._ws?.removeListener("close",a),this._state=w,this._cleanup();let p={code:o,reason:d.toString()};this.emit("close",p),r(p);};this._ws.on("close",a),n?this._ws.terminate():this._ws.close(Je(e)?e:1e3,t);})}handle(...e){if(e.length===1&&typeof e[0]=="function"){if(this._wildcardHandler)throw new Error("Wildcard handler is already registered.");this._wildcardHandler=e[0];}else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function"){if(this._handlers.has(e[0]))throw new Error(`Handler for '${e[0]}' is already registered.`);this._handlers.set(e[0],e[1]);}else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function"){let t=`${e[0]}:${e[1]}`;if(this._handlers.has(t))throw new Error(`Handler for '${e[1]}' (protocol: ${e[0]}) is already registered.`);this._handlers.set(t,e[2]);}else throw new Error("Invalid arguments: provide (version, method, handler), (method, handler), or (wildcardHandler)")}removeHandler(e,t){e&&t?this._handlers.delete(`${e}:${t}`):e?this._handlers.delete(e):this._wildcardHandler=null;}removeAllHandlers(){this._handlers.clear(),this._wildcardHandler=null;}use(e){this._middleware.use(e);}async call(...e){let t,i,n;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],i=e[2]??{},n=e[3]??{}):(t=e[0],i=e[1]??{},n=e[2]??{}),this._state!==O){if(this._options.offlineQueue&&(this._state===w||this._state===U))return new Promise((a,o)=>{let d=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=d&&(this._offlineQueue.shift(),this._logger?.warn?.("Offline queue full \u2014 dropping oldest message",{method:t,queueSize:this._offlineQueue.length})),this._offlineQueue.push({method:t,params:i,options:n,resolve:a,reject:o}),this._logger?.debug?.("Call queued offline",{method:t,queueSize:this._offlineQueue.length});});throw new Error(`Cannot call: client is in state ${this._state}`)}let r=n.retries??0;return r>0?this._callWithRetry(t,i,n,r):this._callQueue.push(()=>this._sendCall(t,i,n))}async safeCall(...e){try{return await this.call(...e)}catch(t){if(t.name!=="TimeoutError"){let i={method:e.find(n=>typeof n=="string"&&!n.startsWith("ocpp")),error:t};this._logger?.warn?this._logger.warn("SafeCall failed",i):console.warn("SafeCall failed",i);}return}}async _sendCall(e,t,i){let n=i.idempotencyKey??ue(),r=i.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:n,method:e,params:t,options:i},o;return await this._middleware.execute(a,async d=>{let p=d;this._options.strictMode&&this._protocol&&this._validateOutbound(p.method,p.params,"req");let c=[E.CALL,n,p.method,p.params],l=JSON.stringify(c);return o=await new Promise((m,h)=>{let x=setTimeout(()=>{this._pendingCalls.delete(n),h(new F(`Call to "${p.method}" timed out after ${r}ms`));},r),f=()=>{clearTimeout(x),this._pendingCalls.delete(n),h(new Error("Aborted"));};i.signal&&i.signal.addEventListener("abort",f),this._pendingCalls.set(n,{resolve:m,reject:h,timeoutHandle:x,abortHandler:i.signal?()=>i.signal?.removeEventListener("abort",f):void 0,method:p.method,sentAt:Date.now()}),this._ws?.readyState===re.OPEN?this._safeSend(this._ws,l,j=>{j&&(clearTimeout(x),this._pendingCalls.delete(n),h(j));}):this._state===U?(this._logger?.debug?.("Buffering call",{method:p.method}),this._outboundBuffer.push(l)):(clearTimeout(x),this._pendingCalls.delete(n),h(new Error(`WebSocket is not open (state: ${this._state})`)));}),o}),o}sendRaw(e){if(this._state===O&&this._ws)this._ws.send(e);else if(this._state===U)this._outboundBuffer.push(e);else throw new Error("Cannot send: client is not connected")}reconfigure(e){Object.assign(this._options,e),e.callConcurrency!==void 0&&this._callQueue.setConcurrency(e.callConcurrency),(e.strictMode!==void 0||e.strictModeValidators!==void 0)&&this._setupValidators(),e.pingIntervalMs!==void 0&&(this._stopPing(),this._state===O&&this._startPing());}_attachWebsocket(e){e.on("message",t=>this._onMessage(t)),e.on("close",(t,i)=>this._onClose(t,i)),e.on("error",t=>this.emit("error",t)),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_buildMessageEventContext(e,t){return {...e,timestamp:new Date().toISOString(),latencyMs:t}}_emitMessageEvent(e,t,i,n){let r=this._buildMessageEventContext(i,n),a={message:e,direction:t,ctx:r};this.emit("message",a);}_onMessage(e,t){this._recordActivity();let i;try{if(t!==void 0?i=t:i=JSON.parse(e),!Array.isArray(i))throw new Error("Message is not an array")}catch(d){this._onBadMessage(typeof e=="string"?e:e.toString(),d);return}let n=i[0],r=i[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new L(`Invalid MessageId type: ${typeof r} (expected string)`));return}if(n===E.CALL&&i.length<4||n===E.CALLRESULT&&i.length<3||n===E.CALLERROR&&i.length<5){this._onBadMessage(JSON.stringify(i),new L(`Missing payload elements for message type ${n}`));return}let a=n===E.CALLERROR?4:n===E.CALL?3:2,o=i[a];if(typeof o!="object"||o===null||Array.isArray(o)){this._onBadMessage(JSON.stringify(i),new L(`Payload must be a JSON object, got ${o===null?"null":Array.isArray(o)?"array":typeof o}`));return}switch(n){case E.CALL:this._handleIncomingCall(i);break;case E.CALLRESULT:this._handleCallResult(i);break;case E.CALLERROR:this._handleCallError(i);break;default:this._onBadMessage(JSON.stringify(i),new L(`Unknown message type: ${n}`));}}async _handleIncomingCall(e){let[,t,i,n]=e,r={type:"incoming_call",messageId:t,method:i,params:n,protocol:this._protocol};try{await this._middleware.execute(r,async a=>{let o=a,d=[E.CALL,o.messageId,o.method,o.params];if(this._emitMessageEvent(d,"IN",o),this.emit("call",d),this._state===O)try{if(this._pendingResponses.has(o.messageId))throw q("RpcFrameworkError",`Already processing call with ID: ${o.messageId}`);let p=(this._protocol?this._handlers.get(`${this._protocol}:${o.method}`):void 0)??this._handlers.get(o.method);if(!p&&!this._wildcardHandler)throw new R(`Method "${o.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(o.method,o.params,"req"),this._pendingResponses.add(o.messageId);let c=new AbortController,l={messageId:o.messageId,method:o.method,protocol:this._protocol,params:o.params,signal:c.signal},m;if(p?m=await p(l):this._wildcardHandler&&(m=await this._wildcardHandler(o.method,l)),this._pendingResponses.delete(o.messageId),m===we)return;this._options.strictMode&&this._protocol&&this._validateOutbound(o.method,m,"conf");let h=[E.CALLRESULT,o.messageId,m];return this._ws?.send(JSON.stringify(h)),this.emit("callResult",h),m}catch(p){this._pendingResponses.delete(o.messageId);let c=p instanceof C||p.rpcErrorCode?p:q("InternalError",p.message),l=this._options.respondWithDetailedErrors?Ee(p):{},m=[E.CALLERROR,o.messageId,c.rpcErrorCode,c.rpcErrorMessage||p.message||"",l];throw this._ws?.send(JSON.stringify(m)),this.emit("callError",m),p}});}catch{}}async _handleCallResult(e){let[,t,i]=e;if(!this._pendingCalls.has(t)){this._logger?.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let n=this._pendingCalls.get(t),r={type:"incoming_result",messageId:t,payload:i,method:n.method};await this._middleware.execute(r,async a=>{let o=a,d=this._pendingCalls.get(o.messageId);if(!d)return;let p=Date.now()-d.sentAt;this._emitMessageEvent(e,"IN",o,p),this.emit("callResult",e),clearTimeout(d.timeoutHandle),d.abortHandler,this._pendingCalls.delete(o.messageId),d.resolve(o.payload);});}async _handleCallError(e){let[,t]=e,i=this._pendingCalls.get(t);if(!i){this._logger?.warn?.("Received CallError for unknown messageId",{messageId:t});return}let n={type:"incoming_error",messageId:t,error:e,method:i.method};await this._middleware.execute(n,async r=>{let a=r,o=this._pendingCalls.get(a.messageId);if(!o)return;let d=Date.now()-o.sentAt;this._emitMessageEvent(e,"IN",a,d),this.emit("callError",e);let[,,p,c,l]=a.error;clearTimeout(o.timeoutHandle),this._pendingCalls.delete(a.messageId);let m=q(p,c,l);o.reject(m);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let i=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(i?.[1]&&this._ws){let n=[E.CALLERROR,i[1],"FormatViolation",t.message||"Invalid message format",{}];this._ws.send(JSON.stringify(n)),this.emit("callError",n);}this._badMessageCount>=this._options.maxBadMessages&&this.close({code:1002,reason:"Too many bad messages"}).catch(()=>{});}_rejectPendingCalls(e){for(let[,t]of this._pendingCalls)clearTimeout(t.timeoutHandle),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._stopPing();let i=t.toString();this._rejectPendingCalls(`Connection closed (${e}: ${i})`),this._state!==_e?(this._logger?.info?.("Disconnected",{code:e,reason:i}),this.emit("disconnect",{code:e,reason:i}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=w,this.emit("close",{code:e,reason:i}))):this._state=w;}static _INTOLERABLE_ERRORS=new Set(["Maximum redirects exceeded","Server sent no subprotocol","Server sent an invalid subprotocol","Server sent a subprotocol but none was requested","Invalid Sec-WebSocket-Accept header"]);_scheduleReconnect(){this._reconnectAttempt++,this._state=U;let e=this._options.backoffMin,t=this._options.backoffMax,i=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(i)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:i}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(n){let r=n instanceof Error?n.message:"";if(s._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=w,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=w,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},i);}_flushOfflineQueue(){if(this._offlineQueue.length===0)return;let e=this._offlineQueue.splice(0,this._offlineQueue.length);this._logger?.info?.("Flushing offline queue",{count:e.length});for(let t of e)this._callQueue.push(()=>this._sendCall(t.method,t.params,t.options)).then(t.resolve).catch(t.reject);}async _callWithRetry(e,t,i,n){let r=i.retryDelayMs??1e3,a=i.retryMaxDelayMs??3e4;for(let o=0;o<=n;o++)try{return await this._callQueue.push(()=>this._sendCall(e,t,i))}catch(d){if(o===n||!(d instanceof F))throw d;let p=Math.min(a,r*2**o),c=Math.random()*p;this._logger?.warn?.("Call retry",{method:e,attempt:o+1,maxRetries:n,delayMs:Math.round(c)}),await new Promise(l=>setTimeout(l,c));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_safeSend(e,t,i){if(!e||e.readyState!==re.OPEN){i?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>s._BACKPRESSURE_THRESHOLD){this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:s._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount});let n=0,r=setInterval(()=>{if(n+=50,!e||e.readyState!==re.OPEN){clearInterval(r),i?.(new Error("WebSocket closed during backpressure wait"));return}(e.bufferedAmount<=s._BACKPRESSURE_THRESHOLD||n>=1e4)&&(clearInterval(r),e.send(t,i));},50);}else e.send(t,i);}_startPing(){if(this._options.pingIntervalMs<=0)return;let e=this._options.pongTimeoutMs??this._options.pingIntervalMs+5e3,t=()=>{if(this._state!==O||!this._ws)return;if(this._options.deferPingsOnActivity){let r=Date.now()-this._lastActivity;if(r<this._options.pingIntervalMs){this._pingTimer=setTimeout(t,this._options.pingIntervalMs-r);return}}this._ws.ping(),e>0&&(this._pongTimer=setTimeout(()=>{this._logger?.warn?.("Pong timeout \u2014 terminating dead connection",{identity:this._identity,timeoutMs:e}),this._ws?.terminate();},e));let n=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,n);},i=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,i);}_stopPing(){this._pingTimer&&(clearTimeout(this._pingTimer),this._pingTimer=null);}_recordActivity(){this._lastActivity=Date.now();}_setupValidators(){this._options.strictModeValidators?this._validators=this._options.strictModeValidators:this._validators=De(),Array.isArray(this._options.strictMode)?this._strictProtocols=this._options.strictMode:this._strictProtocols=null;}_validateOutbound(e,t,i){let n=this._findValidator();if(!n||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${i}`;try{n.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_validateInbound(e,t,i){let n=this._findValidator();if(!n||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${i}`;try{n.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_findValidator(){return !this._protocol||this._strictProtocols&&!this._strictProtocols.includes(this._protocol)?null:this._validators.find(e=>e.subprotocol===this._protocol)??null}_buildEndpoint(){let e=this._options.endpoint;if(e.endsWith("/")||(e+="/"),e+=encodeURIComponent(this._identity),this._options.query){let t=new URLSearchParams(this._options.query);e+=(e.includes("?")?"&":"?")+t.toString();}return e}_buildWsOptions(){let e={headers:{...this._options.headers,"User-Agent":xe()}},t=this._options.securityProfile??0;if((t===1||t===2)&&this._options.password){let n=Buffer.from(`${this._identity}:${this._options.password.toString()}`).toString("base64");e?.headers&&(e.headers.Authorization=`Basic ${n}`);}if(t===2||t===3){let n=this._options.tls??{};n.ca&&(e.ca=n.ca),n.rejectUnauthorized!==void 0&&(e.rejectUnauthorized=n.rejectUnauthorized),t===3&&(n.cert&&(e.cert=n.cert),n.key&&(e.key=n.key),n.passphrase&&(e.passphrase=n.passphrase));}let i=this._options.compression;return i&&(e.perMessageDeflate=i===true?{zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},clientNoContextTakeover:true,serverNoContextTakeover:true}:{zlibDeflateOptions:{level:i.level??6,memLevel:i.memLevel??8},zlibInflateOptions:{},clientNoContextTakeover:i.clientNoContextTakeover??true,serverNoContextTakeover:i.serverNoContextTakeover??true}),e}_cleanup(){this._stopPing(),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=null,this._ws=null;}};var oe=class extends Map{_maxSize;constructor(e){if(super(),e<1)throw new RangeError("LRUMap maxSize must be >= 1");this._maxSize=e;}get maxSize(){return this._maxSize}set(e,t){if(this.has(e)&&this.delete(e),super.set(e,t),this.size>this._maxSize){let i=this.keys().next().value;i!==void 0&&this.delete(i);}return this}get(e){if(!this.has(e))return;let t=super.get(e);return this.delete(e),super.set(e,t),t}};async function Xe(s,e){let t=-1,i=async(n,r)=>{if(r&&(e.state={...e.state||{},...r||{}}),n<=t)throw new Error("next() called multiple times in middleware");t=n;let a=s[n];n!==s.length&&a&&(e.next=i.bind(null,n+1),await a(e));};await i(0);}var A=class extends EventEmitter{patterns;middlewares;authCallback=null;_routeCORS;_routeConfig;_regexPatterns=[];constructor(e,t){super(),this.patterns=[],this.middlewares=t??[],e?.length&&this.route(...e);}route(...e){this.patterns.push(...e);for(let t of e)typeof t!="string"&&this._regexPatterns.push({regex:t,paramNames:[]});return this}use(...e){return this.middlewares.push(...e),this}cors(e){return this._routeCORS=e,this}config(e){return this._routeConfig=e,this}auth(e){return this.authCallback=e,this}handle(...e){return this.on("client",t=>{let i=e[e.length-1],n=[...e];typeof i=="function"&&(n[n.length-1]=(...r)=>{let a=r.length-1,o=r[a];return o&&typeof o=="object"&&Object.defineProperty(o,"client",{value:t,enumerable:true,configurable:true}),i(...r)}),t.handle(...n);}),this}};function zt(...s){return new A(s)}function Ye(s){return s.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}function Ze(s,e){let t=s;t.startsWith("::ffff:")&&(t=t.substring(7));for(let i of e){if(i===t)return true;if(i.includes("/")){let n=i.split("/"),r=n[0],a=n[1];if(!r||!a)continue;let o=parseInt(a,10);if(isIPv4(t)&&isIPv4(r)){let d=Ye(t),p=Ye(r),c=o===0?0:-1<<32-o>>>0;if((d&c)===(p&c))return true}}}return false}function Le(s,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=s.socket.remoteAddress;if(!t||!Ze(t,e.allowedIPs))return {allowed:false,reason:"IP address not allowed"}}if(e.allowedSchemes&&e.allowedSchemes.length>0){let t=s.socket instanceof TLSSocket?"wss":"ws",i=s.headers["x-forwarded-proto"];if(typeof i=="string"&&(t=i==="https"||i==="wss"?"wss":"ws"),!e.allowedSchemes.includes(t))return {allowed:false,reason:"Protocol scheme not allowed"}}if(e.allowedOrigins&&e.allowedOrigins.length>0){let t=s.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}var W=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function et(s){return s.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var ge=class{root=new W;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let i=et(e),n=this.root;for(let r of i)if(r==="*"){n.wildcardChild||(n.wildcardChild=new W),n=n.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!n.paramChild)n.paramChild=new W,n.paramChild.paramName=a;else if(n.paramChild.paramName!==a)throw new Error(`Route conflict: param ":${a}" conflicts with existing ":${n.paramChild.paramName}" at the same position in pattern "${e}"`);n=n.paramChild;}else {let a=r.toLowerCase(),o=n.children.get(a);o||(o=new W,n.children.set(a,o)),n=o;}n.routers.push(t),this._size++;}match(e){let t=et(e),i=[];if(this._matchRecursive(this.root,t,0,{},i),i.length===0)return null;let n=i[0].params,r=[];for(let a of i)r.push(...a.routers);return {routers:r,params:n}}_matchRecursive(e,t,i,n,r){if(i===t.length){e.routers.length>0&&r.push({routers:[...e.routers],params:{...n}});return}let a=t[i],o=a.toLowerCase(),d=e.children.get(o);if(d&&this._matchRecursive(d,t,i+1,n,r),e.paramChild){let p={...n};p[e.paramChild.paramName]=decodeURIComponent(a),this._matchRecursive(e.paramChild,t,i+1,p,r);}e.wildcardChild&&e.wildcardChild.routers.length>0&&r.push({routers:[...e.wildcardChild.routers],params:{...n}});}freeze(){this._frozen||(this._freezeNode(this.root),this._frozen=true);}_freezeNode(e){Object.freeze(e.routers),e.paramChild&&this._freezeNode(e.paramChild),e.wildcardChild&&this._freezeNode(e.wildcardChild);for(let t of e.children.values())this._freezeNode(t);}get frozen(){return this._frozen}};var se=class extends ae{_serverSession;_serverHandshake;constructor(e,t){super(e),this._serverSession=t.session,this._serverHandshake=t.handshake,this._adaptiveMultiplier=t.adaptiveMultiplier??null,this._workerPool=t.workerPool??null,this._state=ne.OPEN,this._identity=this._options.identity,this._ws=t.ws,this._protocol=t.protocol??t.ws.protocol,this._attachServerWebsocket(t.ws),this._startPing();}_rateLimits={};_adaptiveMultiplier=null;_workerPool=null;_checkRateLimit(e){let t=this._options.rateLimit;if(!t)return true;let i=Date.now(),n=(r,a,o)=>{let d=this._rateLimits[r];if(!d)d={tokens:a,lastRefill:i},this._rateLimits[r]=d;else {let p=i-d.lastRefill,c=this._adaptiveMultiplier?.()??1,l=a/o*c,m=p*l;m>0&&(d.tokens=Math.min(a,d.tokens+m),d.lastRefill=i);}return d.tokens>=1?(d.tokens-=1,true):false};if(!n("global",t.limit,t.windowMs))return false;if(e&&t.methods?.[e]){let r=t.methods[e];if(!n(`method:${e}`,r.limit,r.windowMs))return false}return true}_attachServerWebsocket(e){e.on("message",t=>{this._recordActivity();let i=this._options.rateLimit;if(i){let n,r;if(i.methods)try{r=JSON.parse(t),Array.isArray(r)&&r[0]===2&&(n=r[2]);}catch{}if(!this._checkRateLimit(n)){this._handleRateLimitExceeded(r||t.toString());return}if(r!==void 0){this._onMessage(t,r);return}}if(this._workerPool){let n=t;this._workerPool.parse(n).then(r=>{this._onMessage(t,r.message);}).catch(()=>{this._onMessage(t);});return}this._onMessage(t);}),e.on("close",(t,i)=>this._onClose(t,i)),e.on("error",t=>{this.listenerCount("error")>0?this.emit("error",t):this._logger?.debug?.("WebSocket error (unhandled by client listener)",{error:t.message});}),e.on("ping",()=>{this._recordActivity(),this.emit("ping");}),e.on("pong",()=>{this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._recordActivity(),this.emit("pong");});}_handleRateLimitExceeded(e){let i=this._options.rateLimit.onLimitExceeded||"ignore";if(i==="disconnect")this._logger?.warn?.("Rate limit exceeded \u2014 disconnecting client",{identity:this.identity}),this._ws?.terminate();else if(typeof i=="function")try{let n=i(this,e);n instanceof Promise&&n.catch(r=>{this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:r});});}catch(n){this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:n});}else this._logger?.debug?.("Rate limit exceeded \u2014 ignoring message",{identity:this.identity});}get session(){return this._serverSession}get handshake(){return this._serverHandshake}async connect(){throw new Error("Cannot connect from server client \u2014 connection is managed by the server")}close(e={}){return super.close(e)}};var $e=class{_workers=[];_nextWorker=0;_taskId=0;_pending=new Map;_maxQueueSize;_terminated=false;constructor(e={}){let t=e.poolSize??Math.max(2,cpus().length-2);this._maxQueueSize=e.maxQueueSize??1e4;let i=resolve(g,"parse-worker.js");for(let n=0;n<t;n++){let r=new Worker(i);r.on("message",a=>{let o=this._pending.get(a.id);o&&(this._pending.delete(a.id),a.error?o.reject(new Error(a.error)):o.resolve({message:a.message,validationError:a.validationError}));}),r.on("error",a=>{console.error(`[WorkerPool] Worker ${n} error:`,a.message);}),this._workers.push(r);}}get size(){return this._workers.length}get pendingTasks(){return this._pending.size}parse(e,t){return this._terminated?Promise.reject(new Error("WorkerPool has been shut down")):this._pending.size>=this._maxQueueSize?Promise.reject(new Error(`WorkerPool queue full (${this._maxQueueSize} pending tasks)`)):new Promise((i,n)=>{let r=this._taskId++;this._pending.set(r,{resolve:i,reject:n});let a=this._workers[this._nextWorker%this._workers.length];this._nextWorker=(this._nextWorker+1)%this._workers.length,a.postMessage({id:r,buffer:e,schemaInfo:t});})}async shutdown(){if(this._terminated)return;this._terminated=true;for(let[t,i]of this._pending)i.reject(new Error("WorkerPool shutting down")),this._pending.delete(t);let e=this._workers.map(async t=>{try{await Promise.race([t.terminate(),new Promise(i=>setTimeout(i,5e3))]);}catch{}});await Promise.allSettled(e),this._workers=[];}};function tt(s={}){try{return new $e(s)}catch{return null}}var je=class extends EventEmitter{_options;_trie=new ge;_globalMiddlewareRouters=[];_regexRouters=[];_clients=new Set;_clientsByIdentity=new Map;_httpServers=new Set;_wss=null;_state="OPEN";_adapter=null;_httpServerAbortControllers=new Set;_logger=null;_globalCORS;_connectionBuckets=new Map;_adaptiveLimiter=null;_plugins=[];_workerPool=null;_nodeId=ue();_sessions;_gcInterval=null;_sessionTimeoutMs;constructor(e={}){if(super(),this.setMaxListeners(0),e.strictMode&&!e.protocols?.length)throw new Error("strictMode requires protocols to be specified (e.g. protocols: ['ocpp1.6'])");this._options={securityProfile:0,callTimeoutMs:3e4,pingIntervalMs:3e4,deferPingsOnActivity:false,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,handshakeTimeoutMs:3e4,sessionTtlMs:7200*1e3,...e},this._sessionTimeoutMs=this._options.sessionTtlMs;let t=this._options.maxSessions??5e4;this._sessions=new oe(t),this._wss=new WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()}),this._gcInterval=setInterval(()=>{let r=Date.now();for(let[a,o]of this._sessions.entries())r-o.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);},60*1e3).unref(),this._logger=pe(this._options.logging,{component:"OCPPServer"});let i=this._options.rateLimit;i?.adaptive&&(this._adaptiveLimiter=new H({cpuThresholdPercent:i.cpuThresholdPercent,memThresholdPercent:i.memThresholdPercent,cooldownMs:i.cooldownMs}),this._adaptiveLimiter.on("adapted",r=>{this._logger?.info?.("Adaptive rate limit adjusted",r),this.emit("rateLimit:adapted",r);}),this._adaptiveLimiter.start());let n=this._options.workerThreads;if(n){let r=typeof n=="object"?n:{};this._workerPool=tt(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||M}get clients(){return this._clients}get state(){return this._state}stats(){let e=0;if(this._wss)for(let t of this._wss.clients)e+=t.bufferedAmount;return {connectedClients:this._clients.size,activeSessions:this._sessions.size,uptimeSeconds:process.uptime(),pid:process.pid,memoryUsage:process.memoryUsage(),cpuUsage:process.cpuUsage(),webSockets:this._wss?{total:this._wss.clients.size,bufferedAmount:e}:void 0}}async adapterMetrics(){if(!this._adapter?.metrics)return null;try{return await this._adapter.metrics()}catch(e){return this._logger?.warn?.("Failed to fetch adapter metrics",{error:e}),null}}getLocalClient(e){return this._clientsByIdentity.get(e)}hasLocalClient(e){return this.getLocalClient(e)!==void 0}async isClientConnected(e){if(this.hasLocalClient(e))return true;if(this._adapter?.getPresence){let t=await this._adapter.getPresence(e);return t!=null}return false}cors(e){return this._globalCORS=e,this}route(...e){let t=new A;return t.route(...e),this._registerRouter(t),t}attachRouters(...e){for(let t of e)this._registerRouter(t);return this}plugin(...e){for(let t of e)if(this._plugins.push(t),this._logger?.info?.("Plugin registered",{name:t.name}),t.onInit){let i=t.onInit(this);i instanceof Promise&&i.catch(n=>{this._logger?.error?.("Plugin onInit error",{name:t.name,error:n.message});});}return this}use(...e){let t=new A;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new A;return t.auth(e),this._registerRouter(t),t}_registerRouter(e){let t=e.patterns.filter(n=>typeof n=="string"),i=e._regexPatterns.length>0;if(t.length===0&&!i)this._globalMiddlewareRouters.push(e);else {for(let n of t)this._trie.insert(n,e);i&&this._regexRouters.push(e);}}async listen(e=0,t,i){let n;if(i?.server)n=i.server;else {let a=this._options.securityProfile??0;if(a===2||a===3){let o=this._options.tls??{},d={};o.cert&&(d.cert=o.cert),o.key&&(d.key=o.key),o.ca&&(d.ca=o.ca),o.passphrase&&(d.passphrase=o.passphrase),a===3&&(d.requestCert=true,d.rejectUnauthorized=o.rejectUnauthorized??true),n=createServer(d);}else n=createServer$1();}this._state==="CLOSED"&&(this._state="OPEN");let r=(a,o,d)=>{this._handleUpgrade(a,o,d).catch(p=>{o.destroyed||o.destroy(),this._logger?.error?.("Upgrade error",{error:p.message}),this.emit("upgradeError",{error:p,socket:o});});};if(n.on("upgrade",r),this._httpServers.add(n),this._options.healthEndpoint&&n.on("request",(a,o)=>{let d=a.url??"";if(d==="/health"){let p=this.stats(),c=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:p.connectedClients,activeSessions:p.activeSessions,uptimeSeconds:Math.round(p.uptimeSeconds),pid:p.pid});o.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),o.end(c);return}if(d==="/metrics"){let p=this.stats(),c=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${p.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${p.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(p.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${p.memoryUsage.rss}`,"","# HELP ocpp_memory_heap_used_bytes V8 heap used in bytes","# TYPE ocpp_memory_heap_used_bytes gauge",`ocpp_memory_heap_used_bytes ${p.memoryUsage.heapUsed}`,"","# HELP ocpp_memory_heap_total_bytes V8 heap total in bytes","# TYPE ocpp_memory_heap_total_bytes gauge",`ocpp_memory_heap_total_bytes ${p.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${p.webSockets?.bufferedAmount??0}`,""];o.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"}),o.end(c.join(`
4825
+ `));return}o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not Found");}),i?.signal){let a=new AbortController;this._httpServerAbortControllers.add(a),i.signal.addEventListener("abort",()=>{a.abort(),n.close(),this._httpServers.delete(n);},{once:true});}return i?.server||await new Promise((a,o)=>{n.on("error",o),n.listen(e,t,()=>{n.removeListener("error",o);let d=n.address();this._logger?.info?.("Server listening",{port:typeof d=="object"?d?.port:e,host:t??"0.0.0.0"}),a();});}),n}updateTLS(e){let t=this._options.securityProfile??0;if(t!==2&&t!==3)throw new Error("updateTLS() requires a TLS Security Profile (TLS_BASIC_AUTH or TLS_CLIENT_CERT)");this._options.tls={...this._options.tls,...e};let i={};e.cert&&(i.cert=e.cert),e.key&&(i.key=e.key),e.ca&&(i.ca=e.ca),e.passphrase&&(i.passphrase=e.passphrase);let n=0;for(let r of this._httpServers)"setSecureContext"in r&&typeof r.setSecureContext=="function"&&(r.setSecureContext(i),n++);this._logger?.info?.(`TLS context hot-reloaded across ${n} active server(s)`);}get handleUpgrade(){return (e,t,i)=>this._handleUpgrade(e,t,i).catch(n=>{t.destroyed||t.destroy(),this._logger?.error?.("Upgrade error",{error:n.message}),this.emit("upgradeError",{error:n,socket:t});})}async _handleUpgrade(e,t,i){if(this._state!=="OPEN"){_(t,503,"Server is shutting down");return}let n=this._options.connectionRateLimit;if(n){let u=e.socket.remoteAddress??"unknown",b=Date.now(),T=this._connectionBuckets.get(u);if(!T)T={tokens:n.limit,lastRefill:b},this._connectionBuckets.set(u,T);else {let v=b-T.lastRefill,S=n.limit/n.windowMs;T.tokens=Math.min(n.limit,T.tokens+v*S),T.lastRefill=b;}if(T.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:u}),this.emit("securityEvent",{type:"CONNECTION_RATE_LIMIT",ip:u,timestamp:new Date().toISOString(),details:{tokensRemaining:T.tokens}}),_(t,429,"Too Many Requests");return}T.tokens-=1;}if(t.readyState!=="open"){this._logger?.debug?.("Socket not open at upgrade start"),t.destroyed||t.destroy();return}if(e.headers.upgrade?.toLowerCase()!=="websocket"){_(t,400,"Invalid upgrade request");return}if(this._globalCORS){let{allowed:u,reason:b}=Le(e,this._globalCORS);if(!u){this._logger?.warn?.("CORS rejected connection",{reason:b,ip:e.socket.remoteAddress}),_(t,403,"Forbidden");return}}let r=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),a,o=[],d=[],p={},c=r.pathname,l=false,m=this._trie.size>0||this._regexRouters.length>0,h;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let u of this._globalMiddlewareRouters)d.push(u),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);let x=this._trie.match(c);if(x){Object.assign(p,x.params);for(let u of x.routers)d.push(u),l=true,u._routeConfig&&(h=Object.assign(h||{},u._routeConfig)),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);}for(let u of this._regexRouters)for(let b of u._regexPatterns){let T=b.regex.exec(c);if(T){if(d.push(u),l=true,T.groups)for(let[v,S]of Object.entries(T.groups))p[v]=decodeURIComponent(S??"");u._routeConfig&&(h=Object.assign(h||{},u._routeConfig)),u.middlewares.length>0&&o.push(...u.middlewares),u.authCallback&&!a&&(a=u.authCallback);break}}let f=p.identity;if(!f){let u=c.split("/").filter(Boolean);f=decodeURIComponent(u[u.length-1]??"");}if(!f){_(t,400,"Missing identity in URL path");return}for(let u of d)if(u._routeCORS){let{allowed:b,reason:T}=Le(e,u._routeCORS);if(!b){this._logger?.warn?.("Route CORS rejected connection",{reason:T,ip:e.socket.remoteAddress}),_(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let j=new Set,Re=e.headers["sec-websocket-protocol"];if(Re)try{j=Ge(Re);}catch{_(t,400,"Invalid Sec-WebSocket-Protocol header");return}let qe=h?.protocols??this._options.protocols??[],V;if(qe.length>0){if(j.size===0){_(t,400,"Missing subprotocol");return}if(V=qe.find(u=>j.has(u)),!V){_(t,400,"No matching subprotocol");return}}let it=Ke(e.headers.authorization??"",f),Me,Oe=this._options.securityProfile??0;Oe===3&&"getPeerCertificate"in t&&(Me=t.getPeerCertificate());let de={identity:f,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:j,pathname:c,params:p,query:r.searchParams,request:e,password:it,clientCertificate:Me,securityProfile:Oe},ye,Ve;if(a||o.length>0){let u=new AbortController,b=()=>{u.abort(new Error("Socket closed during handshake"));};t.on("close",b),t.on("error",b),t.on("end",b);let T=this._options.handshakeTimeoutMs??3e4,v;T>0&&(v=setTimeout(()=>{u.abort(new Error("Handshake timeout"));},T));try{ye={handshake:de,state:{},reject:(I=401,D="Unauthorized")=>{throw {code:I,message:D,_isMiddlewareReject:!0}},next:async I=>{}};let S=[...o],P=!1;if(S.push(async I=>{P=!0,a?Ve=await new Promise((D,$)=>{let N=!1,nt=k=>{N||(N=!0,k?.protocol&&(V=k.protocol),D(k));},rt=(k=401,Ne="Unauthorized")=>{throw N||(N=!0,$({code:k,message:Ne})),{code:k,message:Ne,_isMiddlewareReject:!0}};if(u.signal.aborted){$(u.signal.reason);return}u.signal.addEventListener("abort",()=>{N||(N=!0,$(u.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:f,pathname:c});let at={handshake:de,state:I.state,reject:rt,signal:u.signal,accept:nt};a(at);}):V=de.protocols.values().next().value??void 0;}),await Xe(S,ye),!P)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(S){if(u.signal.aborted){let $=S instanceof Error?S.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:f,reason:$}),this.emit("securityEvent",{type:"UPGRADE_ABORTED",identity:f,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:$}}),this.emit("upgradeAborted",{identity:f,reason:$,socket:t,request:e}),t.destroyed||t.destroy();return}let P=S,I=typeof P?.code=="number"?P.code:401,D=typeof P?.message=="string"?P.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:f,code:I}),this.emit("securityEvent",{type:"AUTH_FAILED",identity:f,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:I,message:D}}),_(t,I,D);return}finally{v&&clearTimeout(v),t.removeListener("close",b),t.removeListener("error",b),t.removeListener("end",b);}}else if(m&&!l){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:c}),_(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:f}),t.destroyed||t.destroy();return}this._wss||(this._wss=new WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536})),this._wss.handleUpgrade(e,t,i,u=>{let b={identity:f,endpoint:"",callTimeoutMs:h?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:h?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:h?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:h?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:h?.strictMode??this._options.strictMode,strictModeMethods:h?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:h?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},T={...ye?.state||{},...this._sessions.get(f)?.data||{},...Ve?.session||{}},v=new se(b,{ws:u,handshake:de,session:T,protocol:V,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0});this._updateSessionActivity(f,v.session);let S=this._clientsByIdentity.get(f);S&&S!==v&&(this._logger?.warn?.("Evicting stale connection for identity",{identity:f,reason:"Duplicate identity replaced by new connection"}),S.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(S)),this._clients.add(v),this._clientsByIdentity.set(f,v),this._adapter?.setPresence&&this._adapter.setPresence(f,this._nodeId,300).catch(P=>{this._logger?.error?.("Error setting presence",{identity:f,error:P});}),this._logger?.info?.("Client connected",{identity:f,remoteAddress:e.socket.remoteAddress,protocol:V}),v.on("close",({code:P,reason:I})=>{this._clients.delete(v),this._clientsByIdentity.get(f)===v&&this._clientsByIdentity.delete(f),this?._adapter?.removePresence&&this._adapter.removePresence(f).catch(D=>{this._logger?.error?.("Error removing presence",{identity:f,error:D});});for(let D of this._plugins)try{D.onDisconnect?.(v,P,I);}catch($){this._logger?.error?.("Plugin onDisconnect error",{name:D.name,error:$.message});}this._logger?.info?.("Client disconnected",{identity:f});});for(let P of this._plugins)try{let I=P.onConnection?.(v);I instanceof Promise&&I.catch(D=>{this._logger?.error?.("Plugin onConnection error",{name:P.name,error:D.message});});}catch(I){this._logger?.error?.("Plugin onConnection error",{name:P.name,error:I.message});}this.emit("client",v);for(let P of d)P.emit("client",v);v.on("message",()=>{this._updateSessionActivity(f,v.session);});});}_updateSessionActivity(e,t){this._sessions.set(e,{data:t,lastActive:Date.now()});}async close(e={}){if(this._state!=="OPEN")return;if(this._state="CLOSING",this.emit("closing"),this._logger?.info?.("Server closing",{clientCount:this._clients.size}),this._gcInterval&&(clearInterval(this._gcInterval),this._gcInterval=null),!e.force){let r=Array.from(this._clients).map(async a=>{let o=a._ws;o&&o.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:o.bufferedAmount}),await new Promise(d=>{let p=0,c=setInterval(()=>{p+=50,(!o||o.bufferedAmount===0||p>=5e3)&&(clearInterval(c),d());},50);}));});await Promise.allSettled(r);}let t=Array.from(this._clients).map(n=>n.close(e).catch(()=>{}));await Promise.allSettled(t);for(let n of this._httpServerAbortControllers)n.abort();this._httpServerAbortControllers.clear(),this._wss&&(this._wss.close(),this._wss=new WebSocketServer({noServer:true}));let i=Array.from(this._httpServers).map(n=>new Promise(r=>{n.close(()=>r());}));await Promise.allSettled(i),this._httpServers.clear(),this._adaptiveLimiter&&this._adaptiveLimiter.stop();for(let n of this._plugins)try{let r=n.onClose?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClose error",{name:n.name,error:r.message});}this._adapter&&await this._adapter.disconnect(),this._state="CLOSED",this.emit("close");}reconfigure(e){Object.assign(this._options,e);}async sendToClient(...e){let t,i,n,r;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],i=e[2],n=e[3],r=e[4]):(t=e[0],i=e[1],n=e[2],r=e[3]);for(let a of this._clients)if(a.identity===t)return await a.call(i,n,r);if(this._adapter?.getPresence){let a=await this._adapter.getPresence(t);if(a){await this._adapter.publish(`ocpp:node:${a}`,{source:this._nodeId,target:t,method:i,params:n,options:r});return}}throw new Error(`Client ${t} not found`)}async safeSendToClient(...e){try{return await this.sendToClient(...e)}catch(t){this._logger&&typeof this._logger.warn=="function"&&t.name!=="TimeoutError"&&this._logger.warn("SafeSendToClient failed",{identity:e[0],method:e.length>=4&&typeof e[1]=="string"&&typeof e[2]=="string"?e[2]:e.length>=3&&typeof e[1]=="string"?e[1]:"unknown",error:t});return}}async sendBatch(e,t){if(t.length===0)return [];let i=this._clientsByIdentity.get(e);if(!i)return this._logger?.warn?.("sendBatch: client not found locally",{identity:e}),t.map(()=>{});let n=i.options.callConcurrency??1;t.length>n&&i.reconfigure({callConcurrency:t.length});try{return (await Promise.allSettled(t.map(a=>i.call(a.method,a.params,a.options??{})))).map(a=>{if(a.status==="fulfilled")return a.value;this._logger?.warn?.("sendBatch: individual call failed",{identity:e,error:a.reason?.message});})}finally{t.length>n&&i.reconfigure({callConcurrency:n});}}async setAdapter(e){this._adapter=e,await this._adapter.subscribe("ocpp:broadcast",t=>this._onBroadcast(t)),await this._adapter.subscribe(`ocpp:node:${this._nodeId}`,t=>{this._onUnicast(t);});}_onBroadcast(e){try{if(!e||typeof e!="object")return;let t=e;if(t.source===this._nodeId)return;for(let i of this._clients)i.call(t.method,t.params).catch(()=>{});}catch(t){this._logger?.error?.("Error processing broadcast message",{error:t.message});}}_onUnicast(e){try{if(!e||typeof e!="object")return;let t=e;for(let i of this._clients)if(i.identity===t.target){i.call(t.method,t.params,t.options).catch(n=>{n.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:t.target,error:n});});return}this._logger?.warn?.("Received unicast for unknown client",{target:t.target}),this._adapter?.removePresence&&this._adapter.removePresence(t.target).catch(()=>{});}catch(t){this._logger?.error?.("Error processing unicast",{error:t.message});}}async publish(e,t){this._adapter&&await this._adapter.publish(e,t);}async broadcast(e,t){let i=Array.from(this._clients).map(r=>r.call(e,t).catch(()=>{})),n=this._adapter?this._adapter.publish("ocpp:broadcast",{source:this._nodeId,method:e,params:t}):Promise.resolve();await Promise.all([Promise.all(i),n]);}async broadcastBatch(e,t,i,n){let r=new Set,a=[];for(let d of e){let p=this._clientsByIdentity.get(d);p&&(r.add(d),a.push(p.call(t,i,n).catch(()=>{})));}let o=e.filter(d=>!r.has(d));if(o.length>0&&this._adapter){let d=[];this._adapter.getPresenceBatch?d=await this._adapter.getPresenceBatch(o):this._adapter.getPresence&&(d=await Promise.all(o.map(c=>this._adapter.getPresence(c))));let p=[];for(let c=0;c<o.length;c++){let l=d[c];l&&p.push({channel:`ocpp:node:${l}`,data:{source:this._nodeId,target:o[c],method:t,params:i,options:n}});}p.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(p):await Promise.all(p.map(c=>this._adapter.publish(c.channel,c.data))));}await Promise.all(a);}_buildCompressionConfig(){let e=this._options.compression;return e?e===true?{threshold:1024,zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},serverNoContextTakeover:true,clientNoContextTakeover:true}:{threshold:e.threshold??1024,zlibDeflateOptions:{level:e.level??6,memLevel:e.memLevel??8},zlibInflateOptions:{},serverNoContextTakeover:e.serverNoContextTakeover??true,clientNoContextTakeover:e.clientNoContextTakeover??true}:false}};
4826
+ export{H as AdaptiveLimiter,ve as ClusterDriver,ne as ConnectionState,Te as InMemoryAdapter,oe as LRUMap,E as MessageType,ce as MiddlewareStack,we as NOREPLY,ae as OCPPClient,A as OCPPRouter,je as OCPPServer,se as OCPPServerClient,Q as RPCFormatViolationError,X as RPCFormationViolationError,te as RPCFrameworkError,C as RPCGenericError,G as RPCInternalError,L as RPCMessageTypeNotSupportedError,R as RPCNotImplementedError,B as RPCNotSupportedError,Z as RPCOccurrenceConstraintViolationError,Y as RPCPropertyConstraintViolationError,J as RPCProtocolError,K as RPCSecurityError,ee as RPCTypeConstraintViolationError,Pe as RedisAdapter,fe as SecurityProfile,F as TimeoutError,z as UnexpectedHttpResponse,me as Validator,Se as WebsocketUpgradeError,Ct as combineAuth,Ie as createLoggingMiddleware,yt as createPlugin,q as createRPCError,zt as createRouter,ie as createValidator,ct as defineAdapter,vt as defineAuth,gt as defineMiddleware,Tt as defineRpcMiddleware,Ee as getErrorPlainObject,xe as getPackageIdent,De as getStandardValidators};
@@ -1,4 +1,4 @@
1
- import { O as OCPPPlugin } from './types-BZXEmDQ1.mjs';
1
+ import { O as OCPPPlugin } from './types-BunMs45p.mjs';
2
2
  import 'ws';
3
3
  import 'node:https';
4
4
  import 'node:http';