ocpp-ws-io 2.2.2 → 2.3.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/README.md +4 -4
- package/dist/adapters/redis.d.mts +2 -2
- package/dist/adapters/redis.d.ts +2 -2
- package/dist/adapters/redis.js +1 -1
- package/dist/adapters/redis.mjs +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/{context-DcTIzhq-.d.ts → context-B4-L-O1-.d.ts} +1 -1
- package/dist/{context-Cy7YIKyU.d.mts → context-BNELI5Ux.d.mts} +1 -1
- package/dist/express.d.mts +1 -1
- package/dist/express.d.ts +1 -1
- package/dist/fastify.d.mts +2 -2
- package/dist/fastify.d.ts +2 -2
- package/dist/hono.d.mts +2 -2
- package/dist/hono.d.ts +2 -2
- package/dist/{index-D5pJ3wS4.d.ts → index-CEMhGOxh.d.ts} +16 -6
- package/dist/{index-B9rTwvbn.d.mts → index-Gz98XqQ7.d.mts} +16 -6
- package/dist/index.d.mts +9 -11
- package/dist/index.d.ts +9 -11
- package/dist/index.js +6 -6
- package/dist/index.mjs +6 -6
- package/dist/nestjs.d.mts +1 -1
- package/dist/nestjs.d.ts +1 -1
- package/dist/nestjs.js +6 -6
- package/dist/nestjs.mjs +6 -6
- package/dist/parse-worker.cjs +91 -0
- package/dist/plugins.d.mts +43 -7
- package/dist/plugins.d.ts +43 -7
- package/dist/plugins.js +1 -1
- package/dist/plugins.mjs +1 -1
- package/dist/{types-xFfIgIuS.d.mts → types-tTYOr5Gm.d.mts} +139 -24
- package/dist/{types-xFfIgIuS.d.ts → types-tTYOr5Gm.d.ts} +139 -24
- package/package.json +2 -2
package/dist/nestjs.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import bt,{resolve}from'path';import {fileURLToPath}from'url';import {Injectable,Inject,Optional,Global,Module,Logger,SetMetadata}from'@nestjs/common';import {HttpAdapterHost,DiscoveryService,MetadataScanner,DiscoveryModule}from'@nestjs/core';import {EventEmitter}from'events';import ei,{createServer as createServer$1}from'http';import {createServer}from'https';import ne,{WebSocketServer}from'ws';import {cpus,totalmem,freemem}from'os';import {TLSSocket}from'tls';import {isIPv4}from'net';import {prettyTransport,consoleTransport,createLogger}from'voltlog-io';import Gt from'ajv';import Jt from'ajv-formats';import {randomUUID}from'crypto';import {Worker}from'worker_threads';var F=(o,e,t,n)=>{for(var i=e,r=o.length-1,a;r>=0;r--)(a=o[r])&&(i=(a(i))||i);return i},G=(o,e)=>(t,n)=>e(t,n,o);var St=()=>fileURLToPath(import.meta.url),It=()=>bt.dirname(St()),T=It();var ee="ocpp:gateway",de="ocpp:message_event",pe="ocpp:wildcard_event",ce="ocpp:auth",le="ocpp:connection_middleware",ue="ocpp:rpc_middleware",me="ocpp:cors",te="ocpp:params_args",U="OCPP_SERVER_OPTIONS",O="OCPP_SERVER_INSTANCE";var Di=o=>SetMetadata(ee,typeof o=="string"?{path:o}:o||{}),xi=o=>SetMetadata(me,o),wi=(...o)=>SetMetadata(ue,o);var ji=(o,e)=>SetMetadata(de,{action:o,protocol:e}),Ri=()=>SetMetadata(pe,true),qi=()=>SetMetadata(ce,true),Oi=()=>SetMetadata(le,true);var Ue=(c=>(c[c.CLIENT=0]="CLIENT",c[c.MESSAGE=1]="MESSAGE",c[c.PARAMS=2]="PARAMS",c[c.CONTEXT=3]="CONTEXT",c[c.IDENTITY=4]="IDENTITY",c[c.PATH=5]="PATH",c[c.SESSION=6]="SESSION",c[c.PATH_PARAMS=7]="PATH_PARAMS",c[c.PROTOCOL=8]="PROTOCOL",c[c.MESSAGE_ID=9]="MESSAGE_ID",c[c.HANDSHAKE=10]="HANDSHAKE",c))(Ue||{});function R(o,e){return ()=>(t,n,i)=>{let r=Reflect.getMetadata(te,t.constructor,n)||{},a={type:o,data:e};Reflect.defineMetadata(te,{...r,[i]:a},t.constructor,n);}}var Wi=R(0),Hi=R(1),zi=R(2),Bi=R(3),Gi=R(4),Ji=R(5),Ki=R(6),Xi=o=>R(7,o)(),Yi=R(8),Qi=R(9),Zi=R(10);var M=class{constructor(e,t,n,i){this.discoveryService=e;this.metadataScanner=t;this.server=n;this.service=i;}discoveryService;metadataScanner;server;service;logger=new Logger(M.name);onModuleInit(){this.explore();}explore(){this.discoveryService.getProviders().filter(n=>n.metatype&&Reflect.hasMetadata(ee,n.metatype)).forEach(n=>{let{instance:i,metatype:r}=n;if(!i||!r)return;let a=Reflect.getMetadata(ee,r),s=Reflect.getMetadata(me,r),p=Reflect.getMetadata(ue,r),d=a?.path;this.service?.registerUpgradePath(d);let l=d?this.server.route(d):this.server.route();s&&l.cors(s);let c={...a};delete c.path,Object.keys(c).length>0&&l.config(c);let u=typeof i.onOcppClientConnected=="function",g=typeof i.onOcppClientDisconnected=="function",P=typeof i.onOcppClientError=="function";(u||g||P||p?.length)&&l.on("client",h=>{if(p?.length)for(let b of p)h.use(b);u&&i.onOcppClientConnected(h),g&&h.on("close",b=>{i.onOcppClientDisconnected(h,b?.code??1e3,b?.reason?b.reason.toString():"");}),P&&h.on("error",b=>{i.onOcppClientError(h,b);});}),this.metadataScanner.scanFromPrototype(i,Object.getPrototypeOf(i),h=>{let b=i[h];if(typeof b!="function")return;Reflect.hasMetadata(le,b)&&(l.use(_=>this.executeWithParams(i,b,_)),this.logger.log(`Mapped Connection Middleware: ${r.name}.${h}`)),Reflect.hasMetadata(ce,b)&&(l.auth(_=>this.executeWithParams(i,b,_)),this.logger.log(`Mapped Auth Handler: ${r.name}.${h}`));let N=Reflect.getMetadata(de,b);if(N){let{action:_,protocol:L}=N,ae=oe=>this.executeWithParams(i,b,oe);L?(l.handle(L,_,ae),this.logger.log(`Mapped RPC Event: ${_} (${L}) -> ${r.name}.${h}`)):(l.handle(_,ae),this.logger.log(`Mapped RPC Event: ${_} -> ${r.name}.${h}`));}Reflect.hasMetadata(pe,b)&&(l.handle((_,L)=>this.executeWithParams(i,b,{...L,method:L?.method??_})),this.logger.log(`Mapped Wildcard Event -> ${r.name}.${h}`));});});}async executeWithParams(e,t,n){let i=Reflect.getMetadata(te,e.constructor,t.name)||{},r=Math.max(-1,...Object.keys(i).map(Number)),a=new Array(r+1).fill(void 0);if(Object.keys(i).length===0)a[0]=n;else for(let[s,p]of Object.entries(i)){let d=Number(s),l=this.normalizeParamMetadata(p),c=n.handshake??n.client?.handshake;switch(l.type){case 0:a[d]=n.client;break;case 1:a[d]=n.message||{messageId:n.messageId,method:n.method,protocol:n.protocol,params:n.params};break;case 2:a[d]=n.params??n.payload;break;case 3:a[d]=n;break;case 4:a[d]=n.client?.identity??c?.identity;break;case 5:a[d]=c?.pathname;break;case 6:a[d]=n.client?.session??n.state;break;case 7:a[d]=l.data?c?.params?.[l.data]:c?.params;break;case 8:a[d]=n.protocol??n.client?.protocol??c?.protocols;break;case 9:a[d]=n.messageId;break;case 10:a[d]=c;break}}return t.apply(e,a)}normalizeParamMetadata(e){return typeof e=="number"?{type:e}:e}};M=F([Injectable()],M);var fe=class{constructor(e){this.ocppService=e;}ocppService;use(e,t,n){e.ocppServer=this.ocppService.server,e.ocpp=this.ocppService,n();}};fe=F([Injectable()],fe);var ge=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),n=e-this._prevTimestamp,i=(t.user+t.system)/1e3/n/cpus().length*100;this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=e;let r=totalmem(),a=freemem(),s=(r-a)/r*100,p=i>this._cpuThreshold,d=s>this._memThreshold,l=this._multiplier;p||d?(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!==l&&this.emit("adapted",{multiplier:this._multiplier,cpuPercent:Math.round(i*100)/100,memPercent:Math.round(s*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};function Ze(o){return o.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}function et(o,e){let t=o;t.startsWith("::ffff:")&&(t=t.substring(7));for(let n of e){if(n===t)return true;if(n.includes("/")){let i=n.split("/"),r=i[0],a=i[1];if(!r||!a)continue;let s=parseInt(a,10);if(isIPv4(t)&&isIPv4(r)){let p=Ze(t),d=Ze(r),l=s===0?0:-1<<32-s>>>0;if((p&l)===(d&l))return true}}}return false}function We(o,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=o.socket.remoteAddress;if(!t||!et(t,e.allowedIPs))return {allowed:false,reason:"IP address not allowed"}}if(e.allowedSchemes&&e.allowedSchemes.length>0){let t=o.socket instanceof TLSSocket?"wss":"ws",n=o.headers["x-forwarded-proto"];if(typeof n=="string"&&(t=n==="https"||n==="wss"?"wss":"ws"),!e.allowedSchemes.includes(t))return {allowed:false,reason:"Protocol scheme not allowed"}}if(e.allowedOrigins&&e.allowedOrigins.length>0){let t=o.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}function Ot(o){return o.showMetadata===false||o.showSourceMeta===false||o.prettifySource===true||o.prettifyMetadata===true}function Mt(o){let e=o.showMetadata??true,t=o.showSourceMeta??true,n=o.prettifySource??false,i=o.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",s="\x1B[36m";return (p,d)=>{if(!t)p.context=void 0;else if(n&&p.context){let c=[];p.context.component&&c.push(String(p.context.component)),p.context.identity&&c.push(String(p.context.identity)),c.length>0&&(p.message=`${r}[${c.join("/")}]${a} ${p.message}`,p.context=void 0);}let l=p.meta;if(!e)p.meta={};else if(i&&l&&Object.keys(l).length>0){let c=Object.entries(l).filter(([,u])=>u!=null).map(([u,g])=>{let P=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?P=`${r}${P}${a}`:P=`${r}${P}${a}`,`${s}${u}${a}=${P}`}).join(" ");c&&(p.message=`${p.message} ${c}`),p.meta={};}d(p);}}function ye(o,e){if(o===false||o?.enabled===false)return null;if(o?.logger)return e&&o.logger.child?o.logger.child(e):o.logger;let t=o?.level??"INFO",i=o?.prettify??false?[prettyTransport({level:t})]:[consoleTransport({level:t})];if(o?.handler){let s=o.handler;i.push({name:"customHandler",write:p=>s(p)});}let r=[];o&&Ot(o)&&r.push(Mt(o));let a=createLogger({level:t,transports:i,middleware:r.length>0?r:void 0});return e&&Object.keys(e).length>0?a.child(e):a}var Te=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 n=this.keys().next().value;n!==void 0&&this.delete(n);}return this}get(e){if(!this.has(e))return;let t=super.get(e);return this.delete(e),super.set(e,t),t}};var J=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function tt(o){return o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var ve=class{root=new J;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let n=tt(e),i=this.root;for(let r of n)if(r==="*"){i.wildcardChild||(i.wildcardChild=new J),i=i.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!i.paramChild)i.paramChild=new J,i.paramChild.paramName=a;else if(i.paramChild.paramName!==a)throw new Error(`Route conflict: param ":${a}" conflicts with existing ":${i.paramChild.paramName}" at the same position in pattern "${e}"`);i=i.paramChild;}else {let a=r.toLowerCase(),s=i.children.get(a);s||(s=new J,i.children.set(a,s)),i=s;}i.routers.push(t),this._size++;}match(e){let t=tt(e),n=[];if(this._matchRecursive(this.root,t,0,{},n),n.length===0)return null;let i=n[0].params,r=[];for(let a of n)r.push(...a.routers);return {routers:r,params:i}}_matchRecursive(e,t,n,i,r){if(n===t.length){e.routers.length>0&&r.push({routers:[...e.routers],params:{...i}});return}let a=t[n],s=a.toLowerCase(),p=e.children.get(s);if(p&&this._matchRecursive(p,t,n+1,i,r),e.paramChild){let d={...i};d[e.paramChild.paramName]=decodeURIComponent(a),this._matchRecursive(e.paramChild,t,n+1,d,r);}e.wildcardChild&&e.wildcardChild.routers.length>0&&r.push({routers:[...e.wildcardChild.routers],params:{...i}});}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}};async function it(o,e){let t=-1,n=async(i,r)=>{if(r&&(e.state={...e.state||{},...r||{}}),i<=t)throw new Error("next() called multiple times in middleware");t=i;let a=o[i];i!==o.length&&a&&(e.next=n.bind(null,i+1),await a(e));};await n(0);}var K=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 n=e[e.length-1],i=[...e];typeof n=="function"&&(i[i.length-1]=(...r)=>{let a=r.length-1,s=r[a];return s&&typeof s=="object"&&Object.defineProperty(s,"client",{value:t,enumerable:true,configurable:true}),n(...r)}),t.handle(...i);}),this}};var ie=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},Ce=class extends Error{statusCode;headers;constructor(e,t,n={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=n;}};var E=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},X=class extends E{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},be=class extends E{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},Pe=class extends E{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";}},Se=class extends E{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},Ie=class extends E{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";}},Ee=class extends E{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";}},De=class extends E{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";}},xe=class extends E{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";}},we=class extends E{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";}},_e=class extends E{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";}},V=class extends E{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";}},Le=class extends E{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function nt(o,e,t={}){let n=typeof t=="object"?t:{},{exchangeLog:i=false,prettify:r=false}=n;return async(a,s)=>{let p=Date.now(),d=a.method,l=i?"info":"debug";switch(a.type){case "incoming_call":i&&r?o[l]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):o[l]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":i&&r?o[l]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):o[l]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let c=await s(),u=Date.now()-p;switch(a.type){case "incoming_call":c!=null&&(i&&r?o[l]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,params:c,direction:"OUT"}):o[l]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:u,params:c,direction:"OUT"}));break;case "outgoing_call":i&&r?o[l]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,payload:c,direction:"IN"}):o[l]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:u,payload:c,direction:"IN"});break}return c}catch(c){let u=c.message,g=Date.now()-p;throw a.type==="incoming_call"?i&&r?o.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"OUT"}):o.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"OUT"}):a.type==="outgoing_call"&&(i&&r?o.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"}):o.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"})),c}}}var Ae=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let n=-1,i=async r=>{if(r<=n)throw new Error("next() called multiple times");n=r;let a=this._stack[r];if(r===this._stack.length)return t(e);if(a)return a(e,()=>i(r+1))};return i(0)}};var $e=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,n)=>{this._queue.push({fn:e,resolve:t,reject:n}),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 rt=[{$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 at=[{$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 Et,{resolve}from'path';import {fileURLToPath}from'url';import {Injectable,Inject,Optional,Global,Module,Logger,SetMetadata}from'@nestjs/common';import {HttpAdapterHost,DiscoveryService,MetadataScanner,DiscoveryModule}from'@nestjs/core';import {EventEmitter}from'events';import ai,{createServer as createServer$1}from'http';import {createServer}from'https';import se,{WebSocketServer}from'ws';import {cpus,totalmem,freemem}from'os';import {TLSSocket}from'tls';import {isIPv4,isIPv6}from'net';import {prettyTransport,consoleTransport,createLogger}from'voltlog-io';import {randomUUID,timingSafeEqual}from'crypto';import Yt from'ajv';import Zt from'ajv-formats';import {existsSync}from'fs';import {Worker}from'worker_threads';var U=(o,e,t,n)=>{for(var i=e,r=o.length-1,a;r>=0;r--)(a=o[r])&&(i=(a(i))||i);return i},X=(o,e)=>(t,n)=>e(t,n,o);var xt=()=>fileURLToPath(import.meta.url),wt=()=>Et.dirname(xt()),C=wt();var ie="ocpp:gateway",ce="ocpp:message_event",le="ocpp:wildcard_event",ue="ocpp:auth",me="ocpp:connection_middleware",he="ocpp:rpc_middleware",fe="ocpp:cors",ne="ocpp:params_args",W="OCPP_SERVER_OPTIONS",V="OCPP_SERVER_INSTANCE";var Ri=o=>SetMetadata(ie,typeof o=="string"?{path:o}:o||{}),ji=o=>SetMetadata(fe,o),qi=(...o)=>SetMetadata(he,o);var ki=(o,e)=>SetMetadata(ce,{action:o,protocol:e}),Fi=()=>SetMetadata(le,true),Ui=()=>SetMetadata(ue,true),Wi=()=>SetMetadata(me,true);var We=(l=>(l[l.CLIENT=0]="CLIENT",l[l.MESSAGE=1]="MESSAGE",l[l.PARAMS=2]="PARAMS",l[l.CONTEXT=3]="CONTEXT",l[l.IDENTITY=4]="IDENTITY",l[l.PATH=5]="PATH",l[l.SESSION=6]="SESSION",l[l.PATH_PARAMS=7]="PATH_PARAMS",l[l.PROTOCOL=8]="PROTOCOL",l[l.MESSAGE_ID=9]="MESSAGE_ID",l[l.HANDSHAKE=10]="HANDSHAKE",l))(We||{});function R(o,e){return ()=>(t,n,i)=>{let r=Reflect.getMetadata(ne,t.constructor,n)||{},a={type:o,data:e};Reflect.defineMetadata(ne,{...r,[i]:a},t.constructor,n);}}var Xi=R(0),Qi=R(1),Yi=R(2),Zi=R(3),en=R(4),tn=R(5),nn=R(6),rn=o=>R(7,o)(),an=R(8),on=R(9),sn=R(10);var N=class{constructor(e,t,n,i){this.discoveryService=e;this.metadataScanner=t;this.server=n;this.service=i;}discoveryService;metadataScanner;server;service;logger=new Logger(N.name);onModuleInit(){this.explore();}explore(){this.discoveryService.getProviders().filter(n=>n.metatype&&Reflect.hasMetadata(ie,n.metatype)).forEach(n=>{let{instance:i,metatype:r}=n;if(!i||!r)return;let a=Reflect.getMetadata(ie,r),s=Reflect.getMetadata(fe,r),p=Reflect.getMetadata(he,r),d=a?.path;this.service?.registerUpgradePath(d);let c=d?this.server.route(d):this.server.route();s&&c.cors(s);let l={...a};delete l.path,Object.keys(l).length>0&&c.config(l);let u=typeof i.onOcppClientConnected=="function",g=typeof i.onOcppClientDisconnected=="function",y=typeof i.onOcppClientError=="function";(u||g||y||p?.length)&&c.on("client",P=>{if(p?.length)for(let h of p)P.use(h);u&&i.onOcppClientConnected(P),g&&P.on("close",h=>{i.onOcppClientDisconnected(P,h?.code??1e3,h?.reason?h.reason.toString():"");}),y&&P.on("error",h=>{i.onOcppClientError(P,h);});}),this.metadataScanner.scanFromPrototype(i,Object.getPrototypeOf(i),P=>{let h=i[P];if(typeof h!="function")return;Reflect.hasMetadata(me,h)&&(c.use(w=>this.executeWithParams(i,h,P,w)),this.logger.log(`Mapped Connection Middleware: ${r.name}.${P}`)),Reflect.hasMetadata(ue,h)&&(c.auth(w=>this.executeWithParams(i,h,P,w)),this.logger.log(`Mapped Auth Handler: ${r.name}.${P}`));let j=Reflect.getMetadata(ce,h);if(j){let{action:w,protocol:M}=j,O=Ne=>this.executeWithParams(i,h,P,Ne);M?(c.handle(M,w,O),this.logger.log(`Mapped RPC Event: ${w} (${M}) -> ${r.name}.${P}`)):(c.handle(w,O),this.logger.log(`Mapped RPC Event: ${w} -> ${r.name}.${P}`));}Reflect.hasMetadata(le,h)&&(c.handle((w,M)=>this.executeWithParams(i,h,P,{...M,method:M?.method??w})),this.logger.log(`Mapped Wildcard Event -> ${r.name}.${P}`));});});}async executeWithParams(e,t,n,i){let r=Reflect.getMetadata(ne,e.constructor,n)||{},a=Math.max(-1,...Object.keys(r).map(Number)),s=new Array(a+1).fill(void 0);if(Object.keys(r).length===0)s[0]=i;else for(let[p,d]of Object.entries(r)){let c=Number(p),l=this.normalizeParamMetadata(d),u=i.handshake??i.client?.handshake;switch(l.type){case 0:s[c]=i.client;break;case 1:s[c]=i.message||{messageId:i.messageId,method:i.method,protocol:i.protocol,params:i.params};break;case 2:s[c]=i.params??i.payload;break;case 3:s[c]=i;break;case 4:s[c]=i.client?.identity??u?.identity;break;case 5:s[c]=u?.pathname;break;case 6:s[c]=i.client?.session??i.state;break;case 7:s[c]=l.data?u?.params?.[l.data]:u?.params;break;case 8:s[c]=i.protocol??i.client?.protocol??u?.protocols;break;case 9:s[c]=i.messageId;break;case 10:s[c]=u;break}}return t.apply(e,s)}normalizeParamMetadata(e){return typeof e=="number"?{type:e}:e}};N=U([Injectable()],N);var ye=class{constructor(e){this.ocppService=e;}ocppService;use(e,t,n){e.ocppServer=this.ocppService.server,e.ocpp=this.ocppService,n();}};ye=U([Injectable()],ye);var re=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),n=e-this._prevTimestamp,i=(t.user+t.system)/1e3/n/cpus().length*100;this._prevCpuUsage=process.cpuUsage(),this._prevTimestamp=e;let r=totalmem(),a=freemem(),s=(r-a)/r*100,p=i>this._cpuThreshold,d=s>this._memThreshold,c=this._multiplier;p||d?(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(i*100)/100,memPercent:Math.round(s*100)/100});}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}};function it(o){return o.split(".").reduce((e,t)=>(e<<8)+parseInt(t,10),0)>>>0}var Mt=(1n<<128n)-1n;function nt(o){o=o.split("%")[0];let e=o.match(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(e){let a=[e[2],e[3],e[4],e[5]].map(d=>parseInt(d,10));if(a.some(d=>d>255))return null;let s=(a[0]<<8|a[1]).toString(16),p=(a[2]<<8|a[3]).toString(16);o=`${e[1]}${s}:${p}`;}let t=o.split("::");if(t.length>2)return null;let n=t[0]?t[0].split(":"):[],i;if(t.length===2){let a=t[1]?t[1].split(":"):[],s=8-n.length-a.length;if(s<0)return null;i=[...n,...Array(s).fill("0"),...a];}else i=n;if(i.length!==8)return null;let r=0n;for(let a of i){if(!/^[0-9a-fA-F]{1,4}$/.test(a))return null;r=r<<16n|BigInt(parseInt(a,16));}return r}function rt(o,e){let t=o;t.startsWith("::ffff:")&&(t=t.substring(7));for(let n of e){if(n===t)return true;if(n.includes("/")){let i=n.split("/"),r=i[0],a=i[1];if(!r||!a)continue;let s=parseInt(a,10);if(isIPv4(t)&&isIPv4(r)){if(s<0||s>32)continue;let p=it(t),d=it(r),c=s===0?0:-1<<32-s>>>0;if((p&c)===(d&c))return true}else if(isIPv6(t)&&isIPv6(r)){if(s<0||s>128)continue;let p=nt(t),d=nt(r);if(p===null||d===null)continue;let c=s===0?0n:~0n<<BigInt(128-s)&Mt;if((p&c)===(d&c))return true}}}return false}function He(o,e){if(e.allowedIPs&&e.allowedIPs.length>0){let t=o.socket.remoteAddress;if(!t||!rt(t,e.allowedIPs))return {allowed:false,reason:"IP address not allowed"}}if(e.allowedSchemes&&e.allowedSchemes.length>0){let t=o.socket instanceof TLSSocket?"wss":"ws";if(e.trustProxy===true){let n=o.headers["x-forwarded-proto"];typeof n=="string"&&(t=n==="https"||n==="wss"?"wss":"ws");}if(!e.allowedSchemes.includes(t))return {allowed:false,reason:"Protocol scheme not allowed"}}if(e.allowedOrigins&&e.allowedOrigins.length>0){let t=o.headers.origin;if(typeof t=="string"&&!e.allowedOrigins.includes(t))return {allowed:false,reason:"Origin not allowed"}}return {allowed:true}}function Ft(o){return o.showMetadata===false||o.showSourceMeta===false||o.prettifySource===true||o.prettifyMetadata===true}function Ut(o){let e=o.showMetadata??true,t=o.showSourceMeta??true,n=o.prettifySource??false,i=o.prettifyMetadata??false,r="\x1B[2;37m",a="\x1B[0m",s="\x1B[36m";return (p,d)=>{if(!t)p.context=void 0;else if(n&&p.context){let l=[];p.context.component&&l.push(String(p.context.component)),p.context.identity&&l.push(String(p.context.identity)),l.length>0&&(p.message=`${r}[${l.join("/")}]${a} ${p.message}`,p.context=void 0);}let c=p.meta;if(!e)p.meta={};else if(i&&c&&Object.keys(c).length>0){let l=Object.entries(c).filter(([,u])=>u!=null).map(([u,g])=>{let y=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?y=`${r}${y}${a}`:y=`${r}${y}${a}`,`${s}${u}${a}=${y}`}).join(" ");l&&(p.message=`${p.message} ${l}`),p.meta={};}d(p);}}function Te(o,e){if(o===false||o?.enabled===false)return null;if(o?.logger)return e&&o.logger.child?o.logger.child(e):o.logger;let t=o?.level??"INFO",i=o?.prettify??false?[prettyTransport({level:t})]:[consoleTransport({level:t})];if(o?.handler){let s=o.handler;i.push({name:"customHandler",write:p=>s(p)});}let r=[];o&&Ft(o)&&r.push(Ut(o));let a=createLogger({level:t,transports:i,middleware:r.length>0?r:void 0});return e&&Object.keys(e).length>0?a.child(e):a}var ve=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 n=this.keys().next().value;n!==void 0&&this.delete(n);}return this}get(e){if(!this.has(e))return;let t=super.get(e);return this.delete(e),super.set(e,t),t}};var G=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},Ce=class extends Error{statusCode;headers;constructor(e,t,n={}){super(e),this.name="UnexpectedHttpResponse",this.statusCode=t,this.headers=n;}};var D=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},Q=class extends D{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},be=class extends D{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},Pe=class extends D{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";}},Se=class extends D{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},Ie=class extends D{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";}},Ee=class extends D{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";}},De=class extends D{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";}},xe=class extends D{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";}},we=class extends D{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";}},_e=class extends D{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";}},k=class extends D{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";}},Le=class extends D{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function ae(){return randomUUID()}function H(o,e,t={}){switch(o){case "GenericError":return new D(e,t);case "RpcFrameworkError":return new Le(e,t);case "MessageTypeNotSupported":return new k(e,t);case "NotImplemented":return new Q(e,t);case "NotSupported":return new be(e,t);case "InternalError":return new Pe(e,t);case "ProtocolError":return new Se(e,t);case "SecurityError":return new Ie(e,t);case "FormatViolation":return new De(e,t);case "FormationViolation":return new Ee(e,t);case "PropertyConstraintViolation":return new xe(e,t);case "OccurrenceConstraintViolation":return new we(e,t);case "TypeConstraintViolation":return new _e(e,t);default:return new D(e,t)}}var zt=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function at(o,e=true){let t={};for(let n of zt){if(n==="stack"&&!e)continue;let i=o[n];if(i!==void 0){if(typeof i=="function"||typeof i=="symbol")continue;if(typeof i=="object"&&i!==null)try{JSON.stringify(i),t[n]=i;}catch{}else t[n]=i;}}return t.name||(t.name=o.name),t.message||(t.message=o.message),t}var Bt="ocpp-ws-io",Gt="2.3.0";function ot(){return `${Bt}/${Gt}`}var J={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>J};function oe(o){try{return decodeURIComponent(o)}catch{return o}}var Y=class{children=new Map;paramChild=null;paramName="";wildcardChild=null;routers=[]};function st(o){return o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"").split("/").filter(Boolean)}var Ae=class{root=new Y;_frozen=false;_size=0;get size(){return this._size}insert(e,t){this._frozen&&(this._frozen=false);let n=st(e),i=this.root;for(let r of n)if(r==="*"){i.wildcardChild||(i.wildcardChild=new Y),i=i.wildcardChild;break}else if(r.startsWith(":")){let a=r.slice(1);if(!i.paramChild)i.paramChild=new Y,i.paramChild.paramName=a;else if(i.paramChild.paramName!==a)throw new Error(`Route conflict: param ":${a}" conflicts with existing ":${i.paramChild.paramName}" at the same position in pattern "${e}"`);i=i.paramChild;}else {let a=r.toLowerCase(),s=i.children.get(a);s||(s=new Y,i.children.set(a,s)),i=s;}i.routers.push(t),this._size++;}match(e){let t=st(e),n=[];if(this._matchRecursive(this.root,t,0,{},n),n.length===0)return null;let i=n[0].params,r=[];for(let a of n)r.push(...a.routers);return {routers:r,params:i}}_matchRecursive(e,t,n,i,r){if(n===t.length){e.routers.length>0&&r.push({routers:[...e.routers],params:{...i}});return}let a=t[n],s=a.toLowerCase(),p=e.children.get(s);if(p&&this._matchRecursive(p,t,n+1,i,r),e.paramChild){let d={...i};d[e.paramChild.paramName]=oe(a),this._matchRecursive(e.paramChild,t,n+1,d,r);}e.wildcardChild&&e.wildcardChild.routers.length>0&&r.push({routers:[...e.wildcardChild.routers],params:{...i}});}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}};async function dt(o,e){let t=-1,n=async(i,r)=>{if(r&&(e.state={...e.state||{},...r||{}}),i<=t)throw new Error("next() called multiple times in middleware");t=i;let a=o[i];i!==o.length&&a&&(e.next=n.bind(null,i+1),await a(e));};await n(0);}var Z=class extends EventEmitter{patterns;middlewares;authCallback=null;_routeCORS;_routeConfig;_regexPatterns=[];_onPatternAdded;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:[]}),this._onPatternAdded?.(t);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 n=e[e.length-1],i=[...e];typeof n=="function"&&(i[i.length-1]=(...r)=>{let a=r.length-1,s=r[a];return s&&typeof s=="object"&&Object.defineProperty(s,"client",{value:t,enumerable:true,configurable:true}),n(...r)}),t.handle(...i);}),this}};function pt(o,e,t={}){let n=typeof t=="object"?t:{},{exchangeLog:i=false,prettify:r=false}=n;return async(a,s)=>{let p=Date.now(),d=a.method,c=i?"info":"debug";switch(a.type){case "incoming_call":i&&r?o[c]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"}):o[c]?.("CALL \u2190",{messageId:a.messageId,method:a.method,protocol:a.protocol,payload:a.params,direction:"IN"});break;case "outgoing_call":i&&r?o[c]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:a.method,params:a.params,direction:"OUT"}):o[c]?.("CALL \u2192",{method:a.method,params:a.params,direction:"OUT"});break}try{let l=await s(),u=Date.now()-p;switch(a.type){case "incoming_call":l!=null&&(i&&r?o[c]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,params:l,direction:"OUT"}):o[c]?.("CALLRESULT \u2192",{messageId:a.messageId,method:a.method,durationMs:u,params:l,direction:"OUT"}));break;case "outgoing_call":i&&r?o[c]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:a.messageId,method:a.method,durationMs:u,payload:l,direction:"IN"}):o[c]?.("CALLRESULT \u2190",{messageId:a.messageId,method:a.method,durationMs:u,payload:l,direction:"IN"});break}return l}catch(l){let u=l.message,g=Date.now()-p;throw a.type==="incoming_call"?i&&r?o.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"OUT"}):o.error?.("CALLERROR \u2192",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"OUT"}):a.type==="outgoing_call"&&(i&&r?o.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"}):o.warn?.("CALLERROR \u2190",{messageId:a.messageId,method:a.method,durationMs:g,error:u,direction:"IN"})),l}}}var $e=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let n=-1,i=async r=>{if(r<=n)throw new Error("next() called multiple times");n=r;let a=this._stack[r];if(r===this._stack.length)return t(e);if(a)return a(e,()=>i(r+1))};return i(0)}};var Re=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,n)=>{this._queue.push({fn:e,resolve:t,reject:n}),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 ct=[{$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 lt=[{$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
|
|
@@ -1716,7 +1716,7 @@ Base64 encoded firmware signature.\r
|
|
|
1716
1716
|
`,type:"string",enum:["Accepted","Rejected","AcceptedCanceled","InvalidCertificate","RevokedCertificate"]},StatusInfoType:{description:`Element providing more information about the status.\r
|
|
1717
1717
|
`,type:"object",additionalProperties:false,properties:{customData:{$ref:"#/definitions/CustomDataType"},reasonCode:{description:`A predefined code for the reason why the status is returned in this response. The string is case-insensitive.\r
|
|
1718
1718
|
`,type:"string",maxLength:20},additionalInfo:{description:`Additional text to provide detailed information.\r
|
|
1719
|
-
`,type:"string",maxLength:512}},required:["reasonCode"]}},properties:{customData:{$ref:"#/definitions/CustomDataType"},status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"},statusInfo:{$ref:"#/definitions/StatusInfoType"}},required:["status"],type:"object"}];var
|
|
1719
|
+
`,type:"string",maxLength:512}},required:["reasonCode"]}},properties:{customData:{$ref:"#/definitions/CustomDataType"},status:{$ref:"#/definitions/UpdateFirmwareStatusEnumType"},statusInfo:{$ref:"#/definitions/StatusInfoType"}},required:["status"],type:"object"}];var ut=[{$schema:"http://json-schema.org/draft-07/schema",$id:"urn:AdjustPeriodicEventStreamRequest",comment:"OCPP 2.1 Edition 1 (c) OCA, Creative Commons Attribution-NoDerivatives 4.0 International Public License",definitions:{PeriodicEventStreamParamsType:{javaType:"PeriodicEventStreamParams",type:"object",additionalProperties:false,properties:{interval:{description:`Time in seconds after which stream data is sent.\r
|
|
1720
1720
|
`,type:"integer",minimum:0},values:{description:`Number of items to be sent together in stream.\r
|
|
1721
1721
|
`,type:"integer",minimum:0},customData:{$ref:"#/definitions/CustomDataType"}}},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.",javaType:"CustomData",type:"object",properties:{vendorId:{type:"string",maxLength:255}},required:["vendorId"]}},type:"object",additionalProperties:false,properties:{id:{type:"integer",minimum:0},params:{$ref:"#/definitions/PeriodicEventStreamParamsType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["id","params"]},{$schema:"http://json-schema.org/draft-07/schema",$id:"urn:AdjustPeriodicEventStreamResponse",comment:"OCPP 2.1 Edition 1 (c) OCA, Creative Commons Attribution-NoDerivatives 4.0 International Public License",definitions:{GenericStatusEnumType:{description:`Status of operation.\r
|
|
1722
1722
|
`,javaType:"GenericStatusEnum",type:"string",additionalProperties:false,enum:["Accepted","Rejected"]},StatusInfoType:{description:`Element providing more information about the status.\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"]}];
|
|
4820
|
+
`,type:"integer",minimum:0},status:{$ref:"#/definitions/GenericStatusEnumType"},customData:{$ref:"#/definitions/CustomDataType"}},required:["vatNumber","status"]}];var ei=new Set(["type"]),ti=new Set(["maximum","minimum","maxLength","minLength","pattern","format","anyOf","oneOf","not","if"]),ii=new Set(["required","maxItems","minItems","maxProperties","minProperties","additionalProperties","additionalItems","exclusiveMaximum","exclusiveMinimum","multipleOf"]),ni=new Set(["enum","const"]);function ri(o){return ei.has(o)?"TypeConstraintViolation":ii.has(o)?"OccurrenceConstraintViolation":ni.has(o)?"PropertyConstraintViolation":(ti.has(o),"FormatViolation")}var ze=class{subprotocol;_ajv;constructor(e,t){this.subprotocol=e,this._ajv=new Yt({allErrors:true,strict:false,multipleOfPrecision:4}),Zt(this._ajv);for(let n of t){let i={...n};if(typeof i.$id=="string"){let r=i.$id.match(/^urn:(.+?)(Request|Response)$/);r&&(i.$id=`urn:${r[1]}.${r[2]==="Request"?"req":"conf"}`),i.$id.startsWith("urn:")&&(i.$id=i.$id.replace("urn:","urn/"));}this._ajv.addSchema(i);}}_normalizeSchemaId(e){return e.startsWith("urn:")?e.replace("urn:","urn/"):e}validate(e,t){let n=this._normalizeSchemaId(e),i=this._ajv.getSchema(n);if(!i)return;if(!i(t)&&i.errors&&i.errors.length>0){let a=i.errors[0],s=ri(a.keyword);s==="FormatViolation"&&this.subprotocol.startsWith("ocpp1.6")&&(s="FormationViolation");let p=this._ajv.errorsText(i.errors);throw H(s,p)}}hasSchema(e){return !!this._ajv.getSchema(this._normalizeSchemaId(e))}};function je(o,e){return new ze(o,e)}var qe=null;function mt(){return qe||(qe=[je("ocpp1.6",ct),je("ocpp2.0.1",lt),je("ocpp2.1",ut)],qe)}var Me={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var _={CALL:2,CALLRESULT:3,CALLERROR:4},ht=Symbol("NOREPLY");function gt(o){if(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57)return true;switch(o){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 yt(o){if(o.length===0)throw new SyntaxError("Unexpected end of input");let e=new Set,t=0;for(;t<o.length;){for(;t<o.length&&(o.charCodeAt(t)===32||o.charCodeAt(t)===9);)t++;let n=t;for(;t<o.length&>(o.charCodeAt(t));)t++;if(t===n)throw new SyntaxError(`Unexpected character at index ${t}`);let i=o.substring(n,t);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);for(e.add(i);t<o.length&&(o.charCodeAt(t)===32||o.charCodeAt(t)===9);)t++;if(t>=o.length)break;if(o.charCodeAt(t)!==44)throw new SyntaxError(`Unexpected character at index ${t}`);t++;let r=t;for(;r<o.length&&(o.charCodeAt(r)===32||o.charCodeAt(r)===9);)r++;if(r>=o.length||!gt(o.charCodeAt(r)))throw new SyntaxError("Unexpected end of input")}if(e.size===0)throw new SyntaxError("Unexpected end of input");return e}var oi=new Set([1004,1005,1006]);function Tt(o){return o>=1e3&&o<=1014&&!oi.has(o)||o>=3e3&&o<=4999}var si=/^ *[Bb][Aa][Ss][Ii][Cc] +([A-Za-z0-9._~+/-]+=*) *$/;function vt(o,e){if(!o)return;let t=si.exec(o);if(t?.[1])try{let n=Buffer.from(t[1],"base64"),i=Buffer.from(`${e}:`);if(n.length>i.length&&timingSafeEqual(n.subarray(0,i.length),i))return n.subarray(i.length);let r=n.indexOf(58);if(r!==-1){let a=n.subarray(0,r),s=Buffer.from(e);if(a.length===s.length&&timingSafeEqual(a,s))return n.subarray(r+1)}}catch{}}function A(o,e,t,n){if(!o.writable)return;let i=ai.STATUS_CODES[e]??"Unknown",r=t??i,s={Connection:"close","Content-Type":"text/plain; charset=utf-8","Content-Length":Buffer.byteLength(r,"utf8"),...n},p=Object.entries(s).map(([d,c])=>`${d}: ${c}`).join(`\r
|
|
4821
4821
|
`);o.end(`HTTP/1.1 ${e} ${i}\r
|
|
4822
4822
|
${p}\r
|
|
4823
4823
|
\r
|
|
4824
|
-
${r}`);}var{CONNECTING:Q,OPEN:z,CLOSING:ze,CLOSED:$}=Oe,Me=class o extends EventEmitter{static CONNECTING=Q;static OPEN=z;static CLOSING=ze;static CLOSED=$;_options;_state=$;_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=H;_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 $e(this._options.callConcurrency),this._middleware=new Ae;let t=this._options.logging,n=ye(t,{component:"OCPPClient",identity:this._identity});this._logger=n||H,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(nt(this._logger,this._identity,this._options.logging)),this._options.strictMode&&this._setupValidators();}_logExchange(e,t,n,i){if(!this._logger)return;let r=e==="OUT"?"\u2192":"\u2190",a=t==="CALLERROR"?"warn":this._exchangeLog?"info":"debug";if(this._exchangeLog&&this._prettify){let s=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",p=n??t,d=`${s} ${this._identity} ${r} ${p} [${e}]`;this._logger?.[a]?.(d,{...i,direction:e});}else this._exchangeLog?this._logger?.[a]?.(`${t} ${r}`,{...i,direction:e}):this._logger?.[a]?.(`${t} ${r}`,i);}get log(){return this._logger||H}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!==$)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=Q,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let n=this._buildEndpoint(),i=this._buildWsOptions();this._logger?.debug?.("Connecting",{url:n}),this.emit("connecting",{url:n});let r=new ne(n,this._options.protocols??[],i);this._ws=r;let a=()=>{if(d(),this._state=z,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 u=this._outboundBuffer;this._outboundBuffer=[];for(let g of u)this._ws?.send(g);}this._logger?.info?.("Connected",{protocol:r.protocol});let c={response:r._req?.res};this.emit("open",c),e(c);},s=l=>{d(),this._state=$,this._logger?.error?.("Connection error",{error:l.message}),this.emit("error",l),t(l);},p=(l,c)=>{d(),this._state=$;let u=new Ce(`Unexpected HTTP response: ${c.statusCode}`,c.statusCode??0,c.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:c.statusCode}),this.emit("error",u),t(u);},d=()=>{r.removeListener("open",a),r.removeListener("error",s),r.removeListener("unexpected-response",p);};r.on("open",a),r.on("error",s),r.on("unexpected-response",p);})}async close(e={}){let{code:t=1e3,reason:n="",awaitPending:i=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===$?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,n,i,r),this._closePromise)}async _closeInternal(e,t,n,i){if(this._state=ze,this._stopPing(),!i&&n){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(s=>{let p=a.resolve,d=a.reject;a.resolve=l=>{p(l),s();},a.reject=l=>{d(l),s();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===ne.CLOSED){this._state=$,this._cleanup();let s={code:e,reason:t};this.emit("close",s),r(s);return}let a=(s,p)=>{this._ws?.removeListener("close",a),this._state=$,this._cleanup();let d={code:s,reason:p.toString()};this.emit("close",d),r(d);};this._ws.on("close",a),i?this._ws.terminate():this._ws.close(ht(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,n,i;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],n=e[2]??{},i=e[3]??{}):(t=e[0],n=e[1]??{},i=e[2]??{}),this._state!==z){if(this._options.offlineQueue&&(this._state===$||this._state===Q))return new Promise((a,s)=>{let p=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=p&&(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:n,options:i,resolve:a,reject:s}),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=i.retries??0;return r>0?this._callWithRetry(t,n,i,r):this._callQueue.push(()=>this._sendCall(t,n,i))}async safeCall(...e){try{return await this.call(...e)}catch(t){if(t.name!=="TimeoutError"){let n={method:e.find(i=>typeof i=="string"&&!i.startsWith("ocpp")),error:t};this._logger?.warn?this._logger.warn("SafeCall failed",n):console.warn("SafeCall failed",n);}return}}async _sendCall(e,t,n){let i=n.idempotencyKey??je(),r=n.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:i,method:e,params:t,options:n},s;return await this._middleware.execute(a,async p=>{let d=p;this._options.strictMode&&this._protocol&&this._validateOutbound(d.method,d.params,"req");let l=[w.CALL,i,d.method,d.params],c=this._invokeBeforeSend(l);if(c instanceof Promise){if(await c===false)return}else if(c===false)return;let u=JSON.stringify(l);return s=await new Promise((g,P)=>{let h=setTimeout(()=>{this._pendingCalls.delete(i),P(new ie(`Call to "${d.method}" timed out after ${r}ms`));},r),b=()=>{clearTimeout(h),this._pendingCalls.delete(i),P(new Error("Aborted"));};n.signal&&n.signal.addEventListener("abort",b),this._pendingCalls.set(i,{resolve:g,reject:P,timeoutHandle:h,abortHandler:n.signal?()=>n.signal?.removeEventListener("abort",b):void 0,method:d.method,sentAt:Date.now()}),this._ws?.readyState===ne.OPEN?this._safeSend(this._ws,u,N=>{N?(clearTimeout(h),this._pendingCalls.delete(i),P(N)):this._emitMessageEvent(l,"OUT",{type:"outgoing_call",messageId:i,method:d.method,params:d.params,options:n});}):this._state===Q?(this._logger?.debug?.("Buffering call",{method:d.method}),this._outboundBuffer.push(u)):(clearTimeout(h),this._pendingCalls.delete(i),P(new Error(`WebSocket is not open (state: ${this._state})`)));}),s}),s}sendRaw(e){if(this._state===z&&this._ws)this._ws.send(e);else if(this._state===Q)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===z&&this._startPing());}_attachWebsocket(e){e.on("message",t=>this._onMessage(t)),e.on("close",(t,n)=>this._onClose(t,n)),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,n,i){let r=this._buildMessageEventContext(n,i),a={message:e,direction:t,ctx:r};this.emit("message",a);}_onMessage(e,t){this._recordActivity();let n;try{if(t!==void 0?n=t:n=JSON.parse(e),!Array.isArray(n))throw new Error("Message is not an array")}catch(p){this._onBadMessage(typeof e=="string"?e:e.toString(),p);return}let i=n[0],r=n[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new V(`Invalid MessageId type: ${typeof r} (expected string)`));return}if(i===w.CALL&&n.length<4||i===w.CALLRESULT&&n.length<3||i===w.CALLERROR&&n.length<5){this._onBadMessage(JSON.stringify(n),new V(`Missing payload elements for message type ${i}`));return}let a=i===w.CALLERROR?4:i===w.CALL?3:2,s=n[a];if(typeof s!="object"||s===null||Array.isArray(s)){this._onBadMessage(JSON.stringify(n),new V(`Payload must be a JSON object, got ${s===null?"null":Array.isArray(s)?"array":typeof s}`));return}switch(i){case w.CALL:this._handleIncomingCall(n);break;case w.CALLRESULT:this._handleCallResult(n);break;case w.CALLERROR:this._handleCallError(n);break;default:this._onBadMessage(JSON.stringify(n),new V(`Unknown message type: ${i}`));}}async _handleIncomingCall(e){let[,t,n,i]=e,r={type:"incoming_call",messageId:t,method:n,params:i,protocol:this._protocol};try{await this._middleware.execute(r,async a=>{let s=a,p=[w.CALL,s.messageId,s.method,s.params];if(this._emitMessageEvent(p,"IN",s),this.emit("call",p),this._state===z)try{if(this._pendingResponses.has(s.messageId))throw Y("RpcFrameworkError",`Already processing call with ID: ${s.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${s.method}`):void 0)??this._handlers.get(s.method);if(!d&&!this._wildcardHandler)throw new X(`Method "${s.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(s.method,s.params,"req"),this._pendingResponses.add(s.messageId);let l=new AbortController,c={messageId:s.messageId,method:s.method,protocol:this._protocol,params:s.params,signal:l.signal},u;if(d?u=await d(c):this._wildcardHandler&&(u=await this._wildcardHandler(s.method,c)),this._pendingResponses.delete(s.messageId),u===lt)return;this._options.strictMode&&this._protocol&&this._validateOutbound(s.method,u,"conf");let g=[w.CALLRESULT,s.messageId,u],P=this._invokeBeforeSend(g);if(P instanceof Promise){if(await P===!1)return u}else if(P===!1)return u;return this._ws?.send(JSON.stringify(g)),this._emitMessageEvent(g,"OUT",{type:"outgoing_result",messageId:s.messageId,method:s.method,payload:u}),this.emit("callResult",g),u}catch(d){this._pendingResponses.delete(s.messageId);let l=d instanceof E||d.rpcErrorCode?d:Y("InternalError",d.message),c=this._options.respondWithDetailedErrors?st(d):{},u=[w.CALLERROR,s.messageId,l.rpcErrorCode,l.rpcErrorMessage||d.message||"",c],g=this._invokeBeforeSend(u);if(g instanceof Promise){if(await g===!1)throw d}else if(g===!1)throw d;throw this._ws?.send(JSON.stringify(u)),this._emitMessageEvent(u,"OUT",{type:"outgoing_error",messageId:s.messageId,method:s.method,errorCode:l.rpcErrorCode,errorDescription:l.rpcErrorMessage||d.message||""}),this.emit("callError",u),this.emit("handlerError",{method:s.method,error:d}),d}});}catch{}}async _handleCallResult(e){let[,t,n]=e;if(!this._pendingCalls.has(t)){this._logger?.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let i=this._pendingCalls.get(t),r={type:"incoming_result",messageId:t,payload:n,method:i.method};await this._middleware.execute(r,async a=>{let s=a,p=this._pendingCalls.get(s.messageId);if(!p)return;let d=Date.now()-p.sentAt;this._emitMessageEvent(e,"IN",s,d),this.emit("callResult",e),clearTimeout(p.timeoutHandle),p.abortHandler,this._pendingCalls.delete(s.messageId),p.resolve(s.payload);});}async _handleCallError(e){let[,t]=e,n=this._pendingCalls.get(t);if(!n){this._logger?.warn?.("Received CallError for unknown messageId",{messageId:t});return}let i={type:"incoming_error",messageId:t,error:e,method:n.method};await this._middleware.execute(i,async r=>{let a=r,s=this._pendingCalls.get(a.messageId);if(!s)return;let p=Date.now()-s.sentAt;this._emitMessageEvent(e,"IN",a,p),this.emit("callError",e);let[,,d,l,c]=a.error;clearTimeout(s.timeoutHandle),this._pendingCalls.delete(a.messageId);let u=Y(d,l,c);s.reject(u);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let n=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(n?.[1]&&this._ws){let i=[w.CALLERROR,n[1],"FormatViolation",t.message||"Invalid message format",{}],r=this._invokeBeforeSend(i);r instanceof Promise?r.then(a=>{a!==false&&(this._ws?.send(JSON.stringify(i)),this.emit("callError",i));}).catch(()=>{}):r!==false&&(this._ws.send(JSON.stringify(i)),this.emit("callError",i));}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 n=t.toString();this._rejectPendingCalls(`Connection closed (${e}: ${n})`),this._state!==ze?(this._logger?.info?.("Disconnected",{code:e,reason:n}),this.emit("disconnect",{code:e,reason:n}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=$,this.emit("close",{code:e,reason:n}))):this._state=$;}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=Q;let e=this._options.backoffMin,t=this._options.backoffMax,n=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(n)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:n}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(i){let r=i instanceof Error?i.message:"";if(o._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=$,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=$,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},n);}_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,n,i){let r=n.retryDelayMs??1e3,a=n.retryMaxDelayMs??3e4;for(let s=0;s<=i;s++)try{return await this._callQueue.push(()=>this._sendCall(e,t,n))}catch(p){if(s===i||!(p instanceof ie))throw p;let d=Math.min(a,r*2**s),l=Math.random()*d;this._logger?.warn?.("Call retry",{method:e,attempt:s+1,maxRetries:i,delayMs:Math.round(l)}),await new Promise(c=>setTimeout(c,l));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_invokeBeforeSend(e){return true}_safeSend(e,t,n){if(!e||e.readyState!==ne.OPEN){n?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>o._BACKPRESSURE_THRESHOLD){this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:o._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount});let i=0,r=setInterval(()=>{if(i+=50,!e||e.readyState!==ne.OPEN){clearInterval(r),n?.(new Error("WebSocket closed during backpressure wait"));return}(e.bufferedAmount<=o._BACKPRESSURE_THRESHOLD||i>=1e4)&&(clearInterval(r),e.send(t,n));},50);}else e.send(t,n);}_startPing(){if(this._options.pingIntervalMs<=0)return;let e=this._options.pongTimeoutMs??this._options.pingIntervalMs+5e3,t=()=>{if(this._state!==z||!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.emit("pongTimeout",{identity:this._identity}),this._ws?.terminate();},e));let i=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,i);},n=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,n);}_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=ct(),Array.isArray(this._options.strictMode)?this._strictProtocols=this._options.strictMode:this._strictProtocols=null;}_validateOutbound(e,t,n){let i=this._findValidator();if(!i||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${n}`;try{i.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_validateInbound(e,t,n){let i=this._findValidator();if(!i||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${n}`;try{i.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":dt()}},t=this._options.securityProfile??0;if((t===1||t===2)&&this._options.password){let i=Buffer.from(`${this._identity}:${this._options.password.toString()}`).toString("base64");e?.headers&&(e.headers.Authorization=`Basic ${i}`);}if(t===2||t===3){let i=this._options.tls??{};i.ca&&(e.ca=i.ca),i.rejectUnauthorized!==void 0&&(e.rejectUnauthorized=i.rejectUnauthorized),t===3&&(i.cert&&(e.cert=i.cert),i.key&&(e.key=i.key),i.passphrase&&(e.passphrase=i.passphrase));}let n=this._options.compression;return n&&(e.perMessageDeflate=n===true?{zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},clientNoContextTakeover:true,serverNoContextTakeover:true}:{zlibDeflateOptions:{level:n.level??6,memLevel:n.memLevel??8},zlibInflateOptions:{},clientNoContextTakeover:n.clientNoContextTakeover??true,serverNoContextTakeover:n.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 Ve=class extends Me{_serverSession;_serverHandshake;_serverPlugins;constructor(e,t){super(e),this._serverSession=t.session,this._serverHandshake=t.handshake,this._adaptiveMultiplier=t.adaptiveMultiplier??null,this._workerPool=t.workerPool??null,this._serverPlugins=t.plugins??[],this._state=Oe.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 n=Date.now(),i=(r,a,s)=>{let p=this._rateLimits[r];if(!p)p={tokens:a,lastRefill:n},this._rateLimits[r]=p;else {let d=n-p.lastRefill,l=this._adaptiveMultiplier?.()??1,c=a/s*l,u=d*c;u>0&&(p.tokens=Math.min(a,p.tokens+u),p.lastRefill=n);}return p.tokens>=1?(p.tokens-=1,true):false};if(!i("global",t.limit,t.windowMs))return false;if(e&&t.methods?.[e]){let r=t.methods[e];if(!i(`method:${e}`,r.limit,r.windowMs))return false}return true}_invokeBeforeSend(e){if(this._serverPlugins.length===0)return true;let t=[];for(let n of this._serverPlugins)if(n.onBeforeSend)try{let i=n.onBeforeSend(this,e);if(i instanceof Promise)t.push(i.then(r=>r!==!1).catch(()=>!0));else if(i===!1)return !1}catch{}return t.length>0?Promise.all(t).then(n=>n.every(i=>i===true)):true}_attachServerWebsocket(e){e.on("message",async t=>{this._recordActivity();for(let i of this._serverPlugins)if(i.onBeforeReceive)try{let r=i.onBeforeReceive(this,t);if(r instanceof Promise){if(await r===!1)return}else if(r===!1)return}catch{}let n=this._options.rateLimit;if(n){let i,r;if(n.methods)try{r=JSON.parse(t),Array.isArray(r)&&r[0]===2&&(i=r[2]);}catch{}if(!this._checkRateLimit(i)){this._handleRateLimitExceeded(r||t.toString());return}if(r!==void 0){this._onMessage(t,r);return}}if(this._workerPool){let i=t;this._workerPool.parse(i).then(r=>{this._onMessage(t,r.message);}).catch(()=>{this._onMessage(t);});return}this._onMessage(t);}),e.on("close",(t,n)=>this._onClose(t,n)),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 n=this._options.rateLimit.onLimitExceeded||"ignore";if(this.emit("rateLimitExceeded",{rawData:e}),n==="disconnect")this._logger?.warn?.("Rate limit exceeded \u2014 disconnecting client",{identity:this.identity}),this._ws?.terminate();else if(typeof n=="function")try{let i=n(this,e);i instanceof Promise&&i.catch(r=>{this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:r});});}catch(i){this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:i});}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 Be=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 n=resolve(T,"parse-worker.js");for(let i=0;i<t;i++){let r=new Worker(n);r.on("message",a=>{let s=this._pending.get(a.id);s&&(this._pending.delete(a.id),a.error?s.reject(new Error(a.error)):s.resolve({message:a.message,validationError:a.validationError}));}),r.on("error",a=>{console.error(`[WorkerPool] Worker ${i} 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((n,i)=>{let r=this._taskId++;this._pending.set(r,{resolve:n,reject:i});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,n]of this._pending)n.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(n=>setTimeout(n,5e3))]);}catch{}});await Promise.allSettled(e),this._workers=[];}};function gt(o={}){try{return new Be(o)}catch{return null}}var re=class extends EventEmitter{_options;_trie=new ve;_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;_telemetryInterval=null;_nodeId=je();_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 Te(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,s]of this._sessions.entries())r-s.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);},60*1e3).unref(),this._logger=ye(this._options.logging,{component:"OCPPServer"});let n=this._options.rateLimit;n?.adaptive&&(this._adaptiveLimiter=new ge({cpuThresholdPercent:n.cpuThresholdPercent,memThresholdPercent:n.memThresholdPercent,cooldownMs:n.cooldownMs}),this._adaptiveLimiter.on("adapted",r=>{this._logger?.info?.("Adaptive rate limit adjusted",r),this.emit("rateLimit:adapted",r);}),this._adaptiveLimiter.start());let i=this._options.workerThreads;if(i){let r=typeof i=="object"?i:{};this._workerPool=gt(r),this._workerPool&&this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size});}}get log(){return this._logger||H}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 K;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 n=t.onInit(this);n instanceof Promise&&n.catch(i=>{this._logger?.error?.("Plugin onInit error",{name:t.name,error:i.message});});}return this._startTelemetryPush(),this}_startTelemetryPush(){if(this._telemetryInterval)return;let e=this._options.telemetry?.pushIntervalMs;!e||e<=0||this._plugins.some(t=>t.onTelemetry)&&(this._telemetryInterval=setInterval(async()=>{try{let t=this.stats(),n=this._adapter?await this.adapterMetrics().catch(()=>null):null;for(let i of this._plugins)try{await i.onTelemetry?.(t,n??void 0);}catch{}}catch{}},e),this._telemetryInterval.unref());}use(...e){let t=new K;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new K;return t.auth(e),this._registerRouter(t),t}_registerRouter(e){let t=e.patterns.filter(i=>typeof i=="string"),n=e._regexPatterns.length>0;if(t.length===0&&!n)this._globalMiddlewareRouters.push(e);else {for(let i of t)this._trie.insert(i,e);n&&this._regexRouters.push(e);}}async listen(e=0,t,n){let i;if(n?.server)i=n.server;else {let a=this._options.securityProfile??0;if(a===2||a===3){let s=this._options.tls??{},p={};s.cert&&(p.cert=s.cert),s.key&&(p.key=s.key),s.ca&&(p.ca=s.ca),s.passphrase&&(p.passphrase=s.passphrase),a===3&&(p.requestCert=true,p.rejectUnauthorized=s.rejectUnauthorized??true),i=createServer(p);}else i=createServer$1();}this._state==="CLOSED"&&(this._state="OPEN");let r=(a,s,p)=>{this._handleUpgrade(a,s,p).catch(d=>{s.destroyed||s.destroy(),this._logger?.error?.("Upgrade error",{error:d.message}),this.emit("upgradeError",{error:d,socket:s});});};if(i.on("upgrade",r),this._httpServers.add(i),this._options.healthEndpoint&&i.on("request",async(a,s)=>{let p=a.url??"";if(p==="/health"){let d=this.stats(),l=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:d.connectedClients,activeSessions:d.activeSessions,uptimeSeconds:Math.round(d.uptimeSeconds),pid:d.pid});s.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),s.end(l);return}if(p==="/metrics"){let d=this.stats(),l=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${d.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${d.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(d.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${d.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 ${d.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 ${d.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${d.webSockets?.bufferedAmount??0}`,""];s.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"});for(let c of this._plugins)if(c.getCustomMetrics)try{let u=await c.getCustomMetrics();u?.length&&(l.push(""),l.push(...u));}catch(u){this._logger?.error?.("Plugin getCustomMetrics error",{name:c.name,error:u.message});}s.end(l.join(`
|
|
4825
|
-
`));return}s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found");}),n?.signal){let a=new AbortController;this._httpServerAbortControllers.add(a),n.signal.addEventListener("abort",()=>{a.abort(),i.close(),this._httpServers.delete(i);},{once:true});}return n?.server||await new Promise((a,s)=>{i.on("error",s),i.listen(e,t,()=>{i.removeListener("error",s);let p=i.address();this._logger?.info?.("Server listening",{port:typeof p=="object"?p?.port:e,host:t??"0.0.0.0"}),a();});}),i}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 n={};e.cert&&(n.cert=e.cert),e.key&&(n.key=e.key),e.ca&&(n.ca=e.ca),e.passphrase&&(n.passphrase=e.passphrase);let i=0;for(let r of this._httpServers)"setSecureContext"in r&&typeof r.setSecureContext=="function"&&(r.setSecureContext(n),i++);this._logger?.info?.(`TLS context hot-reloaded across ${i} active server(s)`);for(let r of this._plugins)try{r.onTLSUpdate?.(e);}catch(a){this._logger?.error?.("Plugin onTLSUpdate error",{name:r.name,error:a.message});}}get handleUpgrade(){return (e,t,n)=>this._handleUpgrade(e,t,n).catch(i=>{t.destroyed||t.destroy(),this._logger?.error?.("Upgrade error",{error:i.message}),this.emit("upgradeError",{error:i,socket:t});})}async _handleUpgrade(e,t,n){if(this._state!=="OPEN"){j(t,503,"Server is shutting down");return}let i=this._options.connectionRateLimit;if(i){let m=e.socket.remoteAddress??"unknown",D=Date.now(),S=this._connectionBuckets.get(m);if(!S)S={tokens:i.limit,lastRefill:D},this._connectionBuckets.set(m,S);else {let f=D-S.lastRefill,x=i.limit/i.windowMs;S.tokens=Math.min(i.limit,S.tokens+f*x),S.lastRefill=D;}if(S.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:m});let f={type:"CONNECTION_RATE_LIMIT",ip:m,timestamp:new Date().toISOString(),details:{tokensRemaining:S.tokens}};this.emit("securityEvent",f);for(let x of this._plugins)try{x.onSecurityEvent?.(f);}catch{}j(t,429,"Too Many Requests");return}S.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"){j(t,400,"Invalid upgrade request");return}if(this._globalCORS){let{allowed:m,reason:D}=We(e,this._globalCORS);if(!m){this._logger?.warn?.("CORS rejected connection",{reason:D,ip:e.socket.remoteAddress}),j(t,403,"Forbidden");return}}let r=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),a,s=[],p=[],d={},l=r.pathname,c=false,u=this._trie.size>0||this._regexRouters.length>0,g;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let m of this._globalMiddlewareRouters)p.push(m),m.middlewares.length>0&&s.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);let P=this._trie.match(l);if(P){Object.assign(d,P.params);for(let m of P.routers)p.push(m),c=true,m._routeConfig&&(g=Object.assign(g||{},m._routeConfig)),m.middlewares.length>0&&s.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);}for(let m of this._regexRouters)for(let D of m._regexPatterns){let S=D.regex.exec(l);if(S){if(p.push(m),c=true,S.groups)for(let[f,x]of Object.entries(S.groups))d[f]=decodeURIComponent(x??"");m._routeConfig&&(g=Object.assign(g||{},m._routeConfig)),m.middlewares.length>0&&s.push(...m.middlewares),m.authCallback&&!a&&(a=m.authCallback);break}}let h=d.identity;if(!h){let m=l.split("/").filter(Boolean);h=decodeURIComponent(m[m.length-1]??"");}if(!h){j(t,400,"Missing identity in URL path");return}for(let m of p)if(m._routeCORS){let{allowed:D,reason:S}=We(e,m._routeCORS);if(!D){this._logger?.warn?.("Route CORS rejected connection",{reason:S,ip:e.socket.remoteAddress}),j(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let b=new Set,N=e.headers["sec-websocket-protocol"];if(N)try{b=mt(N);}catch{j(t,400,"Invalid Sec-WebSocket-Protocol header");return}let _=g?.protocols??this._options.protocols??[],L;if(_.length>0){if(b.size===0){j(t,400,"Missing subprotocol");return}if(L=_.find(m=>b.has(m)),!L){j(t,400,"No matching subprotocol");return}}let ae=ft(e.headers.authorization??"",h),oe,Ke=this._options.securityProfile??0;Ke===3&&"getPeerCertificate"in t&&(oe=t.getPeerCertificate());let Z={identity:h,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:b,pathname:l,params:d,query:r.searchParams,request:e,password:ae,clientCertificate:oe,securityProfile:Ke},Ne,Xe;if(a||s.length>0){let m=new AbortController,D=()=>{m.abort(new Error("Socket closed during handshake"));};t.on("close",D),t.on("error",D),t.on("end",D);let S=this._options.handshakeTimeoutMs??3e4,f;S>0&&(f=setTimeout(()=>{m.abort(new Error("Handshake timeout"));},S));try{Ne={handshake:Z,state:{},reject:(v=401,I="Unauthorized")=>{throw {code:v,message:I,_isMiddlewareReject:!0}},next:async v=>{}};let x=[...s],y=!1;if(x.push(async v=>{y=!0,a?Xe=await new Promise((I,k)=>{let A=!1,se=B=>{A||(A=!0,B?.protocol&&(L=B.protocol),I(B));},ke=(B=401,Ye="Unauthorized")=>{throw A||(A=!0,k({code:B,message:Ye})),{code:B,message:Ye,_isMiddlewareReject:!0}};if(m.signal.aborted){k(m.signal.reason);return}m.signal.addEventListener("abort",()=>{A||(A=!0,k(m.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:h,pathname:l});let Tt={handshake:Z,state:v.state,reject:ke,signal:m.signal,accept:se};a(Tt);}):L=Z.protocols.values().next().value??void 0;}),await it(x,Ne),!y)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(x){if(m.signal.aborted){let A=x instanceof Error?x.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:h,reason:A});let se={type:"UPGRADE_ABORTED",identity:h,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:A}};this.emit("securityEvent",se);for(let ke of this._plugins)try{ke.onSecurityEvent?.(se);}catch{}this.emit("upgradeAborted",{identity:h,reason:A,socket:t,request:e}),t.destroyed||t.destroy();return}let y=x,v=typeof y?.code=="number"?y.code:401,I=typeof y?.message=="string"?y.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:h,code:v});let k={type:"AUTH_FAILED",identity:h,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:v,message:I}};this.emit("securityEvent",k);for(let A of this._plugins){try{A.onSecurityEvent?.(k);}catch{}try{A.onAuthFailed?.(Z,v,I);}catch{}}j(t,v,I);return}finally{f&&clearTimeout(f),t.removeListener("close",D),t.removeListener("error",D),t.removeListener("end",D);}}else if(u&&!c){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:l}),j(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:h}),t.destroyed||t.destroy();return}this._wss||(this._wss=new WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536})),this._wss.handleUpgrade(e,t,n,m=>{let D={identity:h,endpoint:"",callTimeoutMs:g?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:g?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:g?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:g?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:g?.strictMode??this._options.strictMode,strictModeMethods:g?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:g?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},S={...Ne?.state||{},...this._sessions.get(h)?.data||{},...Xe?.session||{}},f=new Ve(D,{ws:m,handshake:Z,session:S,protocol:L,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter.multiplier:void 0,workerPool:this._workerPool??void 0,plugins:this._plugins});this._updateSessionActivity(h,f.session);let x=this._clientsByIdentity.get(h);if(x&&x!==f){this._logger?.warn?.("Evicting stale connection for identity",{identity:h,reason:"Duplicate identity replaced by new connection"});for(let y of this._plugins)try{y.onEviction?.(x,f);}catch{}x.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(x);}this._clients.add(f),this._clientsByIdentity.set(h,f),this._adapter?.setPresence&&this._adapter.setPresence(h,this._nodeId,300).catch(y=>{this._logger?.error?.("Error setting presence",{identity:h,error:y});}),this._logger?.info?.("Client connected",{identity:h,remoteAddress:e.socket.remoteAddress,protocol:L}),f.on("close",({code:y,reason:v})=>{this._clients.delete(f),this._clientsByIdentity.get(h)===f&&this._clientsByIdentity.delete(h),this?._adapter?.removePresence&&this._adapter.removePresence(h).catch(I=>{this._logger?.error?.("Error removing presence",{identity:h,error:I});});for(let I of this._plugins)try{I.onDisconnect?.(f,y,v);}catch(k){this._logger?.error?.("Plugin onDisconnect error",{name:I.name,error:k.message});}this._logger?.info?.("Client disconnected",{identity:h});});for(let y of this._plugins)try{let v=y.onConnection?.(f);v instanceof Promise&&v.catch(I=>{this._logger?.error?.("Plugin onConnection error",{name:y.name,error:I.message});});}catch(v){this._logger?.error?.("Plugin onConnection error",{name:y.name,error:v.message});}f.on("message",y=>{for(let v of this._plugins)try{v.onMessage?.(f,y);}catch{}}),f.on("error",y=>{for(let v of this._plugins)try{v.onError?.(f,y);}catch{}}),f.on("badMessage",({message:y,error:v})=>{for(let I of this._plugins)try{I.onBadMessage?.(f,y,v);}catch{}}),f.on("strictValidationFailure",({message:y,error:v})=>{for(let I of this._plugins)try{I.onValidationFailure?.(f,y,v);}catch{}}),f.on("backpressure",y=>{for(let v of this._plugins)try{v.onBackpressure?.(f,y.bufferedAmount);}catch{}}),f.on("pongTimeout",()=>{for(let y of this._plugins)try{y.onPongTimeout?.(f);}catch{}}),f.on("handlerError",({method:y,error:v})=>{for(let I of this._plugins)try{I.onHandlerError?.(f,y,v);}catch{}}),f.on("rateLimitExceeded",y=>{for(let v of this._plugins)try{v.onRateLimitExceeded?.(f,y.rawData);}catch{}}),this.emit("client",f);for(let y of p)y.emit("client",f);f.on("message",()=>{this._updateSessionActivity(h,f.session);});});}_updateSessionActivity(e,t){this._sessions.set(e,{data:t,lastActive:Date.now()});}async close(e={}){if(this._state!=="OPEN")return;this._state="CLOSING",this.emit("closing"),this._logger?.info?.("Server closing",{clientCount:this._clients.size});for(let i of this._plugins)try{let r=i.onClosing?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClosing error",{name:i.name,error:r.message});}if(this._gcInterval&&(clearInterval(this._gcInterval),this._gcInterval=null),this._telemetryInterval&&(clearInterval(this._telemetryInterval),this._telemetryInterval=null),!e.force){let r=Array.from(this._clients).map(async a=>{let s=a._ws;s&&s.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:s.bufferedAmount}),await new Promise(p=>{let d=0,l=setInterval(()=>{d+=50,(!s||s.bufferedAmount===0||d>=5e3)&&(clearInterval(l),p());},50);}));});await Promise.allSettled(r);}let t=Array.from(this._clients).map(i=>i.close(e).catch(()=>{}));await Promise.allSettled(t);for(let i of this._httpServerAbortControllers)i.abort();this._httpServerAbortControllers.clear(),this._wss&&(this._wss.close(),this._wss=new WebSocketServer({noServer:true}));let n=Array.from(this._httpServers).map(i=>new Promise(r=>{i.close(()=>r());}));await Promise.allSettled(n),this._httpServers.clear(),this._adaptiveLimiter&&this._adaptiveLimiter.stop();for(let i of this._plugins)try{let r=i.onClose?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClose error",{name:i.name,error:r.message});}this._adapter&&await this._adapter.disconnect(),this._state="CLOSED",this.emit("close");}reconfigure(e){let t={...this._options};Object.assign(this._options,e);for(let n of this._plugins)try{n.onReconfigure?.(e,t);}catch(i){this._logger?.error?.("Plugin onReconfigure error",{name:n.name,error:i.message});}}async sendToClient(...e){let t,n,i,r;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],n=e[2],i=e[3],r=e[4]):(t=e[0],n=e[1],i=e[2],r=e[3]);for(let a of this._clients)if(a.identity===t)return await a.call(n,i,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:n,params:i,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 n=this._clientsByIdentity.get(e);if(!n)return this._logger?.warn?.("sendBatch: client not found locally",{identity:e}),t.map(()=>{});let i=n.options.callConcurrency??1;t.length>i&&n.reconfigure({callConcurrency:t.length});try{return (await Promise.allSettled(t.map(a=>n.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>i&&n.reconfigure({callConcurrency:i});}}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 n of this._clients)n.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 n of this._clients)if(n.identity===t.target){n.call(t.method,t.params,t.options).catch(i=>{i.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:t.target,error:i});});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 n=Array.from(this._clients).map(r=>r.call(e,t).catch(()=>{})),i=this._adapter?this._adapter.publish("ocpp:broadcast",{source:this._nodeId,method:e,params:t}):Promise.resolve();await Promise.all([Promise.all(n),i]);}async broadcastBatch(e,t,n,i){let r=new Set,a=[];for(let p of e){let d=this._clientsByIdentity.get(p);d&&(r.add(p),a.push(d.call(t,n,i).catch(()=>{})));}let s=e.filter(p=>!r.has(p));if(s.length>0&&this._adapter){let p=[];this._adapter.getPresenceBatch?p=await this._adapter.getPresenceBatch(s):this._adapter.getPresence&&(p=await Promise.all(s.map(l=>this._adapter.getPresence(l))));let d=[];for(let l=0;l<s.length;l++){let c=p[l];c&&d.push({channel:`ocpp:node:${c}`,data:{source:this._nodeId,target:s[l],method:t,params:n,options:i}});}d.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(d):await Promise.all(d.map(l=>this._adapter.publish(l.channel,l.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}};var q=class{constructor(e,t={},n){this.ocppServer=e;this.options=t;this.httpAdapterHost=n;}ocppServer;options;httpAdapterHost;attachedHttpServer;gatewayPatterns=new Set;acceptAllUpgrades=false;upgradeHandler=(e,t,n)=>this.handleUpgrade(e,t,n);onModuleInit(){if(this.options.autoAttach===false)return;let e=this.httpAdapterHost?.httpAdapter?.getHttpServer();!e||this.attachedHttpServer===e||(e.on("upgrade",this.upgradeHandler),this.attachedHttpServer=e);}async onModuleDestroy(){this.attachedHttpServer&&(this.attachedHttpServer.removeListener("upgrade",this.upgradeHandler),this.attachedHttpServer=void 0),await this.ocppServer.close();}get server(){return this.ocppServer}get clients(){return this.ocppServer.clients}stats(){return this.ocppServer.stats()}getClient(e){return this.ocppServer.getLocalClient(e)}getLocalClient(e){return this.ocppServer.getLocalClient(e)}hasLocalClient(e){return this.ocppServer.hasLocalClient(e)}hasClient(e){return this.ocppServer.isClientConnected(e)}async sendToClient(...e){return this.ocppServer.sendToClient.apply(this.ocppServer,e)}async safeSendToClient(...e){return this.ocppServer.safeSendToClient.apply(this.ocppServer,e)}close(e){return this.ocppServer.close(e)}registerUpgradePath(e){if(!e){this.acceptAllUpgrades=true;return}this.gatewayPatterns.add(e);}handleUpgrade(e,t,n){this.shouldHandleUpgrade(e)&&this.ocppServer.handleUpgrade(e,t,n);}shouldHandleUpgrade(e){if(e.headers.upgrade?.toLowerCase()!=="websocket")return false;let t=this.getPathname(e);if(!t)return false;if(this.options.upgradeFilter)return this.options.upgradeFilter(t,e);let n=this.normalizePrefixes(this.options.upgradePathPrefix);if(n.length>0)return n.some(i=>t.startsWith(i));if(this.acceptAllUpgrades||this.gatewayPatterns.size===0)return true;for(let i of this.gatewayPatterns)if(this.matchesPattern(i,t))return true;return false}getPathname(e){try{return new URL(e.url??"/",`http://${e.headers.host??"localhost"}`).pathname}catch{return}}normalizePrefixes(e){return e?(Array.isArray(e)?e:[e]).filter(Boolean):[]}matchesPattern(e,t){if(e instanceof RegExp)return e.test(t);let n=e.split("/").filter(Boolean),i=t.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let a=n[r],s=i[r];if(a==="*")return true;if(s===void 0)return false;if(!a.startsWith(":")&&a!==s)return false}return n.length===i.length}};q=F([Injectable(),G(0,Inject(O)),G(1,Optional()),G(1,Inject(U)),G(2,Optional()),G(2,Inject(HttpAdapterHost))],q);var W=class{_isModule=true;static forRoot(e={}){let t={provide:U,useValue:e},n={provide:O,useValue:new re(e)};return {module:W,providers:[t,n],exports:[q,O]}}static forRootAsync(e){let i=[W.createAsyncOptionsProvider(e),{provide:O,useFactory:async r=>new re(r),inject:[U]}];return e.useClass&&i.push({provide:e.useClass,useClass:e.useClass}),{module:W,imports:e.imports||[],providers:i,exports:[q,O]}}static createAsyncOptionsProvider(e){if(e.useFactory)return {provide:U,useFactory:e.useFactory,inject:e.inject||[]};let t=e.useExisting||e.useClass;return t?{provide:U,useFactory:async n=>n.createOcppOptions(),inject:[t]}:{provide:U,useValue:{}}}};W=F([Global(),Module({imports:[DiscoveryModule],providers:[q,{provide:M,inject:[DiscoveryService,MetadataScanner,O,q],useFactory:(o,e,t,n)=>new M(o,e,t,n)}],exports:[q,O]})],W);
|
|
4826
|
-
export{
|
|
4824
|
+
${r}`);}var{CONNECTING:ee,OPEN:z,CLOSING:Be,CLOSED:$}=Me,Oe=class o extends EventEmitter{static CONNECTING=ee;static OPEN=z;static CLOSING=Be;static CLOSED=$;_options;_state=$;_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=J;_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 Re(this._options.callConcurrency),this._middleware=new $e;let t=this._options.logging,n=Te(t,{component:"OCPPClient",identity:this._identity});this._logger=n||J,t&&typeof t=="object"&&(this._exchangeLog=t.exchangeLog??false,this._prettify=t.prettify??false),this._options.logging&&this.use(pt(this._logger,this._identity,this._options.logging)),this._options.strictMode&&this._setupValidators();}_logExchange(e,t,n,i){if(!this._logger)return;let r=e==="OUT"?"\u2192":"\u2190",a=t==="CALLERROR"?"warn":this._exchangeLog?"info":"debug";if(this._exchangeLog&&this._prettify){let s=t==="CALLERROR"?"\u{1F6A8}":t==="CALLRESULT"?"\u2705":"\u26A1",p=n??t,d=`${s} ${this._identity} ${r} ${p} [${e}]`;this._logger?.[a]?.(d,{...i,direction:e});}else this._exchangeLog?this._logger?.[a]?.(`${t} ${r}`,{...i,direction:e}):this._logger?.[a]?.(`${t} ${r}`,i);}get log(){return this._logger||J}get identity(){return this._options.identity}get endpoint(){return this._options.endpoint}get bufferedAmount(){return this._ws?.bufferedAmount??0}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!==$)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=ee,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let n=this._buildEndpoint(),i=this._buildWsOptions();this._logger?.debug?.("Connecting",{url:n}),this.emit("connecting",{url:n});let r=new se(n,this._options.protocols??[],i);this._ws=r;let a=()=>{if(d(),this._state=z,this._protocol=r.protocol,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._reconnectAttempt=0,this._attachWebsocket(r),this._startPing(),this._flushOfflineQueue(),this._outboundBuffer.length>0){let u=this._outboundBuffer;this._outboundBuffer=[];for(let g of u)this._ws?.send(g);}this._logger?.info?.("Connected",{protocol:r.protocol});let l={response:r._req?.res};this.emit("open",l),e(l);},s=c=>{d(),this._state=$,this._logger?.error?.("Connection error",{error:c.message}),this.listenerCount("error")>0&&this.emit("error",c),t(c);},p=(c,l)=>{d(),this._state=$;let u=new Ce(`Unexpected HTTP response: ${l.statusCode}`,l.statusCode??0,l.headers);this._logger?.error?.("Unexpected HTTP response",{statusCode:l.statusCode}),this.listenerCount("error")>0&&this.emit("error",u),t(u);},d=()=>{r.removeListener("open",a),r.removeListener("error",s),r.removeListener("unexpected-response",p);};r.on("open",a),r.on("error",s),r.on("unexpected-response",p);})}async close(e={}){let{code:t=1e3,reason:n="",awaitPending:i=true,force:r=false}=e;return this._closePromise?this._closePromise:this._state===$?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,n,i,r),this._closePromise)}async _closeInternal(e,t,n,i){if(this._state=Be,this._stopPing(),!i&&n){let r=Array.from(this._pendingCalls.values()).map(a=>new Promise(s=>{let p=a.resolve,d=a.reject;a.resolve=c=>{p(c),s();},a.reject=c=>{d(c),s();};}));r.length>0&&await Promise.allSettled(r);}return new Promise(r=>{if(!this._ws||this._ws.readyState===se.CLOSED){this._state=$,this._cleanup();let s={code:e,reason:t};this.emit("close",s),r(s);return}let a=(s,p)=>{this._ws?.removeListener("close",a),this._state=$,this._cleanup();let d={code:s,reason:p.toString()};this.emit("close",d),r(d);};this._ws.on("close",a),i?this._ws.terminate():this._ws.close(Tt(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;}hasHandler(e,t){return t?this._handlers.has(`${t}:${e}`):this._handlers.has(e)}removeAllHandlers(){this._handlers.clear(),this._wildcardHandler=null;}use(e){this._middleware.use(e);}async call(...e){let t,n,i;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],n=e[2]??{},i=e[3]??{}):(t=e[0],n=e[1]??{},i=e[2]??{}),this._state!==z){if(this._options.offlineQueue&&(this._state===$||this._state===ee))return new Promise((a,s)=>{let p=this._options.offlineQueueMaxSize??100;this._offlineQueue.length>=p&&(this._offlineQueue.shift()?.reject(new Error("Offline queue overflow \u2014 oldest queued call dropped")),this._logger?.warn?.("Offline queue full \u2014 dropping oldest message",{method:t,queueSize:this._offlineQueue.length})),this._offlineQueue.push({method:t,params:n,options:i,resolve:a,reject:s}),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=i.retries??0;return r>0?this._callWithRetry(t,n,i,r):this._callQueue.push(()=>this._sendCall(t,n,i))}callImmediate(e,t,n){return this._state!==z?Promise.reject(new Error(`Cannot call: client is in state ${this._state}`)):this._sendCall(e,t??{},n??{})}async safeCall(...e){try{return await this.call(...e)}catch(t){if(t.name!=="TimeoutError"){let i={method:e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?e[1]:e[0],error:t};this._logger?.warn?this._logger.warn("SafeCall failed",i):console.warn("SafeCall failed",i);}return}}async _sendCall(e,t,n){let i=n.idempotencyKey??ae(),r=n.timeoutMs??this._options.callTimeoutMs,a={type:"outgoing_call",messageId:i,method:e,params:t,options:n},s;return await this._middleware.execute(a,async p=>{let d=p;this._options.strictMode&&this._protocol&&this._validateOutbound(d.method,d.params,"req");let c=[_.CALL,i,d.method,d.params],l=this._invokeBeforeSend(c);if(l instanceof Promise){if(await l===false)return}else if(l===false)return;let u=JSON.stringify(c);return s=await new Promise((g,y)=>{let P,h=setTimeout(()=>{P?.(),this._pendingCalls.delete(i),y(new G(`Call to "${d.method}" timed out after ${r}ms`));},r),j=()=>{clearTimeout(h),this._pendingCalls.delete(i),y(n.signal?.reason??new Error("Aborted"));};n.signal&&(n.signal.addEventListener("abort",j,{once:true}),P=()=>n.signal?.removeEventListener("abort",j)),this._pendingCalls.set(i,{resolve:g,reject:y,timeoutHandle:h,removeAbortListener:P,method:d.method,sentAt:Date.now()}),this._ws?.readyState===se.OPEN?this._safeSend(this._ws,u,w=>{w?(clearTimeout(h),P?.(),this._pendingCalls.delete(i),y(w)):this._emitMessageEvent(c,"OUT",{type:"outgoing_call",messageId:i,method:d.method,params:d.params,options:n});}):this._state===ee?(this._logger?.debug?.("Buffering call",{method:d.method}),this._outboundBuffer.push(u)):(clearTimeout(h),P?.(),this._pendingCalls.delete(i),y(new Error(`WebSocket is not open (state: ${this._state})`)));}),s}),s}sendRaw(e){if(this._state===z&&this._ws)this._ws.send(e);else if(this._state===ee)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===z&&this._startPing());}_attachWebsocket(e){e.on("message",t=>this._onMessage(t)),e.on("close",(t,n)=>this._onClose(t,n)),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,n,i){let r=this._buildMessageEventContext(n,i),a={message:e,direction:t,ctx:r};this.emit("message",a);}_onMessage(e,t){this._recordActivity();let n;try{if(t!==void 0?n=t:n=JSON.parse(e),!Array.isArray(n))throw new Error("Message is not an array")}catch(p){this._onBadMessage(typeof e=="string"?e:e.toString(),p);return}let i=n[0],r=n[1];if(typeof r!="string"){this._onBadMessage(typeof e=="string"?e:e.toString(),new k(`Invalid MessageId type: ${typeof r} (expected string)`));return}if(i===_.CALL&&n.length<4||i===_.CALLRESULT&&n.length<3||i===_.CALLERROR&&n.length<5){this._onBadMessage(JSON.stringify(n),new k(`Missing payload elements for message type ${i}`));return}let a=i===_.CALLERROR?4:i===_.CALL?3:2,s=n[a];if(typeof s!="object"||s===null||Array.isArray(s)){this._onBadMessage(JSON.stringify(n),new k(`Payload must be a JSON object, got ${s===null?"null":Array.isArray(s)?"array":typeof s}`));return}switch(i){case _.CALL:this._handleIncomingCall(n);break;case _.CALLRESULT:this._handleCallResult(n);break;case _.CALLERROR:this._handleCallError(n);break;default:this._onBadMessage(JSON.stringify(n),new k(`Unknown message type: ${i}`));}}async _handleIncomingCall(e){let[,t,n,i]=e,r={type:"incoming_call",messageId:t,method:n,params:i,protocol:this._protocol};try{await this._middleware.execute(r,async a=>{let s=a,p=[_.CALL,s.messageId,s.method,s.params];if(this._emitMessageEvent(p,"IN",s),this.emit("call",p),this._state===z)try{if(this._pendingResponses.has(s.messageId))throw H("RpcFrameworkError",`Already processing call with ID: ${s.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${s.method}`):void 0)??this._handlers.get(s.method);if(!d&&!this._wildcardHandler)throw new Q(`Method "${s.method}" not implemented`);this._options.strictMode&&this._protocol&&this._validateInbound(s.method,s.params,"req"),this._pendingResponses.add(s.messageId);let c=new AbortController,l={messageId:s.messageId,method:s.method,protocol:this._protocol,params:s.params,signal:c.signal},u;if(d?u=await d(l):this._wildcardHandler&&(u=await this._wildcardHandler(s.method,l)),this._pendingResponses.delete(s.messageId),u===ht)return;this._options.strictMode&&this._protocol&&this._validateOutbound(s.method,u,"conf");let g=[_.CALLRESULT,s.messageId,u],y=this._invokeBeforeSend(g);if(y instanceof Promise){if(await y===!1)return u}else if(y===!1)return u;return this._ws?.send(JSON.stringify(g)),this._emitMessageEvent(g,"OUT",{type:"outgoing_result",messageId:s.messageId,method:s.method,payload:u}),this.emit("callResult",g),u}catch(d){this._pendingResponses.delete(s.messageId);let c=d instanceof D||d.rpcErrorCode?d:H("InternalError",d.message),l=this._options.respondWithDetailedErrors?at(d,!1):{},u=[_.CALLERROR,s.messageId,c.rpcErrorCode,c.rpcErrorMessage||d.message||"",l],g=this._invokeBeforeSend(u);if(g instanceof Promise){if(await g===!1)throw d}else if(g===!1)throw d;throw this._ws?.send(JSON.stringify(u)),this._emitMessageEvent(u,"OUT",{type:"outgoing_error",messageId:s.messageId,method:s.method,errorCode:c.rpcErrorCode,errorDescription:c.rpcErrorMessage||d.message||""}),this.emit("callError",u),this.emit("handlerError",{method:s.method,error:d}),d}});}catch{}}async _handleCallResult(e){let[,t,n]=e;if(!this._pendingCalls.has(t)){this._logger?.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let i=this._pendingCalls.get(t),r={type:"incoming_result",messageId:t,payload:n,method:i.method};await this._middleware.execute(r,async a=>{let s=a,p=this._pendingCalls.get(s.messageId);if(!p)return;let d=Date.now()-p.sentAt;if(this._emitMessageEvent(e,"IN",s,d),this.emit("callResult",e),this._options.strictMode&&this._protocol)try{this._validateInbound(p.method,s.payload,"conf");}catch(c){clearTimeout(p.timeoutHandle),p.removeAbortListener?.(),this._pendingCalls.delete(s.messageId),p.reject(c);return}clearTimeout(p.timeoutHandle),p.removeAbortListener?.(),this._pendingCalls.delete(s.messageId),p.resolve(s.payload);});}async _handleCallError(e){let[,t]=e,n=this._pendingCalls.get(t);if(!n){this._logger?.warn?.("Received CallError for unknown messageId",{messageId:t});return}let i={type:"incoming_error",messageId:t,error:e,method:n.method};await this._middleware.execute(i,async r=>{let a=r,s=this._pendingCalls.get(a.messageId);if(!s)return;let p=Date.now()-s.sentAt;this._emitMessageEvent(e,"IN",a,p),this.emit("callError",e);let[,,d,c,l]=a.error;clearTimeout(s.timeoutHandle),s.removeAbortListener?.(),this._pendingCalls.delete(a.messageId);let u=H(d,c,l);s.reject(u);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let n=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(n?.[1]&&this._ws){let i=this._protocol==="ocpp1.6"?"FormationViolation":"FormatViolation",r=[_.CALLERROR,n[1],i,t.message||"Invalid message format",{}],a=this._invokeBeforeSend(r);a instanceof Promise?a.then(s=>{s!==false&&(this._ws?.send(JSON.stringify(r)),this.emit("callError",r));}).catch(()=>{}):a!==false&&(this._ws.send(JSON.stringify(r)),this.emit("callError",r));}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.removeAbortListener?.(),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._stopPing(),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null);let n=t.toString();this._rejectPendingCalls(`Connection closed (${e}: ${n})`),this._state!==Be?(this._logger?.info?.("Disconnected",{code:e,reason:n}),this.emit("disconnect",{code:e,reason:n}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=$,this.emit("close",{code:e,reason:n}))):this._state=$;}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=ee;let e=this._options.backoffMin,t=this._options.backoffMax,n=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(n)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:n}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(i){let r=i instanceof Error?i.message:"";if(o._INTOLERABLE_ERRORS.has(r)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:r}),this._state=$,this.emit("close",{code:1001,reason:r});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=$,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},n);}_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,n,i){let r=n.retryDelayMs??1e3,a=n.retryMaxDelayMs??3e4;for(let s=0;s<=i;s++)try{return await this._callQueue.push(()=>this._sendCall(e,t,n))}catch(p){if(s===i||!(p instanceof G))throw p;let d=Math.min(a,r*2**s),c=Math.random()*d;this._logger?.warn?.("Call retry",{method:e,attempt:s+1,maxRetries:i,delayMs:Math.round(c)}),await new Promise(l=>setTimeout(l,c));}throw new Error("Retry exhausted")}static _BACKPRESSURE_THRESHOLD=512*1024;_backpressureQueue=[];_backpressureTimer=null;_invokeBeforeSend(e){return true}_safeSend(e,t,n){if(!e||e.readyState!==se.OPEN){n?.(new Error("WebSocket is not open"));return}if(e.bufferedAmount>o._BACKPRESSURE_THRESHOLD||this._backpressureQueue.length>0){this._backpressureQueue.length===0&&(this._logger?.warn?.("Backpressure \u2014 pausing send",{identity:this._identity,bufferedAmount:e.bufferedAmount,threshold:o._BACKPRESSURE_THRESHOLD}),this.emit("backpressure",{identity:this._identity,bufferedAmount:e.bufferedAmount})),this._backpressureQueue.push({data:t,cb:n,enqueuedAt:Date.now()}),this._startBackpressureDrain(e);return}e.send(t,n);}_startBackpressureDrain(e){this._backpressureTimer||(this._backpressureTimer=setInterval(()=>{if(!e||e.readyState!==se.OPEN){this._stopBackpressureDrain();let n=this._backpressureQueue.splice(0);for(let i of n)i.cb?.(new Error("WebSocket closed during backpressure wait"));return}let t=Date.now();for(;this._backpressureQueue.length>0;){let n=this._backpressureQueue[0],i=t-n.enqueuedAt>=1e4;if(e.bufferedAmount<=o._BACKPRESSURE_THRESHOLD||i)this._backpressureQueue.shift(),e.send(n.data,n.cb);else break}this._backpressureQueue.length===0&&this._stopBackpressureDrain();},50));}_stopBackpressureDrain(){this._backpressureTimer&&(clearInterval(this._backpressureTimer),this._backpressureTimer=null);}_startPing(){if(this._options.pingIntervalMs<=0)return;let e=this._options.pongTimeoutMs??this._options.pingIntervalMs+5e3,t=()=>{if(this._state!==z||!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.emit("pongTimeout",{identity:this._identity}),this._ws?.terminate();},e));let i=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,i);},n=this._options.pingIntervalMs*(.75+Math.random()*.5);this._pingTimer=setTimeout(t,n);}_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=mt(),Array.isArray(this._options.strictMode)?this._strictProtocols=this._options.strictMode:this._strictProtocols=null;}_validateOutbound(e,t,n){let i=this._findValidator();if(!i||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${n}`;try{i.validate(r,t);}catch(a){throw this.emit("strictValidationFailure",{message:t,error:a}),a}}_validateInbound(e,t,n){let i=this._findValidator();if(!i||this._options.strictModeMethods&&!this._options.strictModeMethods.includes(e))return;let r=`urn:${e}.${n}`;try{i.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=new URL(this._options.endpoint);if(e.pathname.endsWith("/")||(e.pathname+="/"),e.pathname+=encodeURIComponent(this._identity),this._options.query)for(let[t,n]of new URLSearchParams(this._options.query))e.searchParams.append(t,n);return e.toString()}_buildWsOptions(){let e={headers:{...this._options.headers,"User-Agent":ot()}},t=this._options.securityProfile??0;if((t===1||t===2)&&this._options.password){let i=Buffer.from(`${this._identity}:${this._options.password.toString()}`).toString("base64");e?.headers&&(e.headers.Authorization=`Basic ${i}`);}if(t===2||t===3){let i=this._options.tls??{};i.ca&&(e.ca=i.ca),i.rejectUnauthorized!==void 0&&(e.rejectUnauthorized=i.rejectUnauthorized),t===3&&(i.cert&&(e.cert=i.cert),i.key&&(e.key=i.key),i.passphrase&&(e.passphrase=i.passphrase));}let n=this._options.compression;return n&&(e.perMessageDeflate=n===true?{zlibDeflateOptions:{level:6,memLevel:8},zlibInflateOptions:{},clientNoContextTakeover:true,serverNoContextTakeover:true}:{zlibDeflateOptions:{level:n.level??6,memLevel:n.memLevel??8},zlibInflateOptions:{},clientNoContextTakeover:n.clientNoContextTakeover??true,serverNoContextTakeover:n.serverNoContextTakeover??true}),e}_cleanup(){this._stopPing(),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._stopBackpressureDrain();let e=this._backpressureQueue.splice(0);for(let t of e)t.cb?.(new Error("Connection closed"));this._closePromise=null,this._ws=null;}};var Ve=class extends Oe{_serverSession;_serverHandshake;_serverPlugins;constructor(e,t){super(e),this._serverSession=t.session,this._serverHandshake=t.handshake,this._adaptiveMultiplier=t.adaptiveMultiplier??null,this._workerPool=t.workerPool??null,this._serverPlugins=t.plugins??[],this._state=Me.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;_inboundChain=Promise.resolve();_checkRateLimit(e){let t=this._options.rateLimit;if(!t)return true;let n=Date.now(),i=(r,a,s)=>{let p=this._rateLimits[r];if(!p)p={tokens:a,lastRefill:n},this._rateLimits[r]=p;else {let d=n-p.lastRefill,c=this._adaptiveMultiplier?.()??1,l=a/s*c,u=d*l;u>0&&(p.tokens=Math.min(a,p.tokens+u),p.lastRefill=n);}return p.tokens>=1?(p.tokens-=1,true):false};if(!i("global",t.limit,t.windowMs))return false;if(e&&t.methods?.[e]){let r=t.methods[e];if(!i(`method:${e}`,r.limit,r.windowMs))return false}return true}_invokeBeforeSend(e){if(this._serverPlugins.length===0)return true;let t=[];for(let n of this._serverPlugins)if(n.onBeforeSend)try{let i=n.onBeforeSend(this,e);if(i instanceof Promise)t.push(i.then(r=>r!==!1).catch(()=>!0));else if(i===!1)return !1}catch{}return t.length>0?Promise.all(t).then(n=>n.every(i=>i===true)):true}_attachServerWebsocket(e){e.on("message",t=>{this._recordActivity(),this._inboundChain=this._inboundChain.then(()=>this._processInboundMessage(t)).catch(()=>{});}),e.on("close",(t,n)=>this._onClose(t,n)),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");});}async _processInboundMessage(e){for(let n of this._serverPlugins)if(n.onBeforeReceive)try{let i=n.onBeforeReceive(this,e);if(i instanceof Promise){if(await i===!1)return}else if(i===!1)return}catch{}let t=this._options.rateLimit;if(t){let n,i;if(t.methods)try{i=JSON.parse(e),Array.isArray(i)&&i[0]===2&&(n=i[2]);}catch{}if(!this._checkRateLimit(n)){this._handleRateLimitExceeded(i||e.toString());return}if(i!==void 0){this._onMessage(e,i);return}}if(this._workerPool){let n=e;try{let i=await this._workerPool.parse(n);this._onMessage(e,i.message);}catch{this._onMessage(e);}return}this._onMessage(e);}_handleRateLimitExceeded(e){let n=this._options.rateLimit.onLimitExceeded||"ignore";if(this.emit("rateLimitExceeded",{rawData:e}),n==="disconnect")this._logger?.warn?.("Rate limit exceeded \u2014 disconnecting client",{identity:this.identity}),this._ws?.terminate();else if(typeof n=="function")try{let i=n(this,e);i instanceof Promise&&i.catch(r=>{this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:r});});}catch(i){this._logger?.error?.("Error in custom onLimitExceeded handler",{identity:this.identity,error:i});}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 Ge=class{_workers=[];_nextWorker=0;_taskId=0;_pending=new Map;_maxQueueSize;_terminated=false;_workerPath;constructor(e={}){let t=e.poolSize??Math.max(2,cpus().length-2);if(this._maxQueueSize=e.maxQueueSize??1e4,this._workerPath=e.workerPath??resolve(C,"parse-worker.cjs"),!existsSync(this._workerPath))throw new Error(`WorkerPool: worker entry not found at ${this._workerPath}`);for(let n=0;n<t;n++)this._workers.push(this._createWorker(n));}_createWorker(e){let t=new Worker(this._workerPath);return t.on("message",n=>{let i=this._pending.get(n.id);i&&(this._pending.delete(n.id),n.error?i.reject(new Error(n.error)):i.resolve({message:n.message,validationError:n.validationError}));}),t.on("error",n=>{console.error(`[WorkerPool] Worker ${e} error:`,n.message),this._failWorkerTasks(e,`Worker ${e} crashed: ${n.message}`);}),t.on("exit",n=>{if(!this._terminated&&(this._failWorkerTasks(e,`Worker ${e} exited (code ${n})`),this._workers[e]===t))try{this._workers[e]=this._createWorker(e);}catch{}}),t}_failWorkerTasks(e,t){for(let[n,i]of this._pending)i.workerIndex===e&&(i.reject(new Error(t)),this._pending.delete(n));}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((n,i)=>{let r=this._taskId++,a=this._nextWorker%this._workers.length,s=this._workers[a];this._nextWorker=(this._nextWorker+1)%this._workers.length,this._pending.set(r,{resolve:n,reject:i,workerIndex:a});try{s.postMessage({id:r,buffer:e,schemaInfo:t});}catch(p){this._pending.delete(r),i(p);}})}async shutdown(){if(this._terminated)return;this._terminated=true;for(let[t,n]of this._pending)n.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(n=>setTimeout(n,5e3))]);}catch{}});await Promise.allSettled(e),this._workers=[];}};function Je(o={}){try{return new Ge(o)}catch{return null}}var de=class o extends EventEmitter{_options;_trie=new Ae;_globalMiddlewareRouters=[];_regexRouters=[];_clients=new Set;_clientsByIdentity=new Map;_httpServers=new Set;_ownedHttpServers=new Set;_attachedHttpHandlers=new Map;_wss=null;_state="OPEN";_adapter=null;_httpServerAbortControllers=new Set;_logger=null;_globalCORS;_connectionBuckets=new Map;_adaptiveLimiter=null;_plugins=[];_workerPool=null;_telemetryInterval=null;_presenceInterval=null;_nodeId=ae();_pendingRemoteCalls=new Map;static _REMOTE_RESPONSE_GRACE_MS=1e3;_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 ve(t),this._wss=this._createWss(),this._gcInterval=setInterval(()=>{let r=Date.now();for(let[a,s]of this._sessions.entries())r-s.lastActive>this._sessionTimeoutMs&&this._sessions.delete(a);this._sweepConnectionBuckets(r);},60*1e3).unref(),this._logger=Te(this._options.logging,{component:"OCPPServer"});let n=this._options.rateLimit;n?.adaptive&&(this._adaptiveLimiter=new re({cpuThresholdPercent:n.cpuThresholdPercent,memThresholdPercent:n.memThresholdPercent,cooldownMs:n.cooldownMs}),this._adaptiveLimiter.on("adapted",r=>{this._logger?.info?.("Adaptive rate limit adjusted",r),this.emit("rateLimit:adapted",r);}),this._adaptiveLimiter.start());let i=this._options.workerThreads;if(i){let r=typeof i=="object"?i:{};this._workerPool=Je(r),this._workerPool?this._logger?.info?.("Worker thread pool initialized",{poolSize:this._workerPool.size}):this._logger?.warn?.("workerThreads was requested but the worker pool could not be created \u2014 falling back to main-thread parsing");}}get log(){return this._logger||J}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 Z;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 n=t.onInit(this);n instanceof Promise&&n.catch(i=>{this._logger?.error?.("Plugin onInit error",{name:t.name,error:i.message});});}return this._startTelemetryPush(),this}_startTelemetryPush(){if(this._telemetryInterval)return;let e=this._options.telemetry?.pushIntervalMs;!e||e<=0||this._plugins.some(t=>t.onTelemetry)&&(this._telemetryInterval=setInterval(async()=>{try{let t=this.stats(),n=this._adapter?await this.adapterMetrics().catch(()=>null):null;for(let i of this._plugins)try{await i.onTelemetry?.(t,n??void 0);}catch{}}catch{}},e),this._telemetryInterval.unref());}use(...e){let t=new Z;return t.use(...e),this._registerRouter(t),t}auth(e){let t=new Z;return t.auth(e),this._registerRouter(t),t}_registerRouter(e){let t=e.patterns.filter(i=>typeof i=="string"),n=e._regexPatterns.length>0;if(t.length===0&&!n)this._globalMiddlewareRouters.push(e);else {for(let i of t)this._trie.insert(i,e);n&&this._regexRouters.push(e);}e._onPatternAdded=i=>{let r=this._globalMiddlewareRouters.indexOf(e);r!==-1&&this._globalMiddlewareRouters.splice(r,1),typeof i=="string"?this._trie.insert(i,e):this._regexRouters.includes(e)||this._regexRouters.push(e);};}async listen(e=0,t,n){let i;if(n?.server)i=n.server;else {let p=this._options.securityProfile??0;if(p===2||p===3){let d=this._options.tls??{},c={};d.cert&&(c.cert=d.cert),d.key&&(c.key=d.key),d.ca&&(c.ca=d.ca),d.passphrase&&(c.passphrase=d.passphrase),p===3&&(c.requestCert=true,c.rejectUnauthorized=d.rejectUnauthorized??true),i=createServer(c);}else i=createServer$1();}if(this._state==="CLOSED"&&(this._state="OPEN"),this._options.workerThreads&&!this._workerPool){let p=this._options.workerThreads;this._workerPool=Je(typeof p=="object"?p:{});}let r=(p,d,c)=>{this._handleUpgrade(p,d,c).catch(l=>{d.destroyed||d.destroy(),this._logger?.error?.("Upgrade error",{error:l.message}),this.emit("upgradeError",{error:l,socket:d});});};i.on("upgrade",r),this._httpServers.add(i);let a=!n?.server;a&&this._ownedHttpServers.add(i);let s;if(this._options.healthEndpoint&&(s=async(p,d)=>{if(d.headersSent||d.writableEnded)return;let c=p.url??"";if(c==="/health"){let l=this.stats(),u=JSON.stringify({status:this._state==="OPEN"?"ok":"degraded",state:this._state,connectedClients:l.connectedClients,activeSessions:l.activeSessions,uptimeSeconds:Math.round(l.uptimeSeconds),pid:l.pid});d.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-cache"}),d.end(u);return}if(c==="/metrics"){let l=this.stats(),u=["# HELP ocpp_connected_clients Number of currently connected OCPP clients","# TYPE ocpp_connected_clients gauge",`ocpp_connected_clients ${l.connectedClients}`,"","# HELP ocpp_active_sessions Number of active in-memory sessions","# TYPE ocpp_active_sessions gauge",`ocpp_active_sessions ${l.activeSessions}`,"","# HELP ocpp_uptime_seconds Process uptime in seconds","# TYPE ocpp_uptime_seconds gauge",`ocpp_uptime_seconds ${Math.round(l.uptimeSeconds)}`,"","# HELP ocpp_memory_rss_bytes Resident set size in bytes","# TYPE ocpp_memory_rss_bytes gauge",`ocpp_memory_rss_bytes ${l.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 ${l.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 ${l.memoryUsage.heapTotal}`,"","# HELP ocpp_ws_buffered_bytes Total buffered WebSocket bytes","# TYPE ocpp_ws_buffered_bytes gauge",`ocpp_ws_buffered_bytes ${l.webSockets?.bufferedAmount??0}`,""];d.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8","Cache-Control":"no-cache"});for(let g of this._plugins)if(g.getCustomMetrics)try{let y=await g.getCustomMetrics();y?.length&&(u.push(""),u.push(...y));}catch(y){this._logger?.error?.("Plugin getCustomMetrics error",{name:g.name,error:y.message});}d.end(u.join(`
|
|
4825
|
+
`));return}a&&(d.writeHead(404,{"Content-Type":"text/plain"}),d.end("Not Found"));},i.on("request",s)),this._attachedHttpHandlers.set(i,{upgrade:r,request:s}),n?.signal){let p=new AbortController;this._httpServerAbortControllers.add(p),n.signal.addEventListener("abort",()=>{p.abort();let d=this._attachedHttpHandlers.get(i);d&&(i.removeListener("upgrade",d.upgrade),d.request&&i.removeListener("request",d.request),this._attachedHttpHandlers.delete(i)),this._ownedHttpServers.has(i)&&(i.close(),this._ownedHttpServers.delete(i)),this._httpServers.delete(i);},{once:true});}return n?.server||await new Promise((p,d)=>{i.on("error",d),i.listen(e,t,()=>{i.removeListener("error",d);let c=i.address();this._logger?.info?.("Server listening",{port:typeof c=="object"?c?.port:e,host:t??"0.0.0.0"}),p();});}),i}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 n={};e.cert&&(n.cert=e.cert),e.key&&(n.key=e.key),e.ca&&(n.ca=e.ca),e.passphrase&&(n.passphrase=e.passphrase);let i=0;for(let r of this._httpServers)"setSecureContext"in r&&typeof r.setSecureContext=="function"&&(r.setSecureContext(n),i++);this._logger?.info?.(`TLS context hot-reloaded across ${i} active server(s)`);for(let r of this._plugins)try{r.onTLSUpdate?.(e);}catch(a){this._logger?.error?.("Plugin onTLSUpdate error",{name:r.name,error:a.message});}}get handleUpgrade(){return (e,t,n)=>this._handleUpgrade(e,t,n).catch(i=>{t.destroyed||t.destroy(),this._logger?.error?.("Upgrade error",{error:i.message}),this.emit("upgradeError",{error:i,socket:t});})}async _handleUpgrade(e,t,n){if(this._state!=="OPEN"){A(t,503,"Server is shutting down");return}let i=this._options.maxConnections;if(i!==void 0&&this._clients.size>=i){let m={type:"CONNECTION_LIMIT",ip:e.socket.remoteAddress??"unknown",timestamp:new Date().toISOString(),details:{activeConnections:this._clients.size,maxConnections:i}};this.emit("securityEvent",m);for(let I of this._plugins)try{I.onSecurityEvent?.(m);}catch{}A(t,503,"Connection limit reached");return}let r=this._options.connectionRateLimit;if(r){let m=e.socket.remoteAddress??"unknown",I=Date.now(),S=this._connectionBuckets.get(m);if(!S)S={tokens:r.limit,lastRefill:I},this._connectionBuckets.set(m,S);else {let f=I-S.lastRefill,x=r.limit/r.windowMs;S.tokens=Math.min(r.limit,S.tokens+f*x),S.lastRefill=I;}if(S.tokens<1){this._logger?.warn?.("Connection rate limit exceeded",{ip:m});let f={type:"CONNECTION_RATE_LIMIT",ip:m,timestamp:new Date().toISOString(),details:{tokensRemaining:S.tokens}};this.emit("securityEvent",f);for(let x of this._plugins)try{x.onSecurityEvent?.(f);}catch{}A(t,429,"Too Many Requests");return}S.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"){A(t,400,"Invalid upgrade request");return}if(this._globalCORS){let{allowed:m,reason:I}=He(e,this._globalCORS);if(!m){this._logger?.warn?.("CORS rejected connection",{reason:I,ip:e.socket.remoteAddress}),A(t,403,"Forbidden");return}}let a=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`),s,p=[],d=[],c={},l=a.pathname,u=false,g=this._trie.size>0||this._regexRouters.length>0,y;!this._trie.frozen&&this._trie.size>0&&this._trie.freeze();for(let m of this._globalMiddlewareRouters)d.push(m),m.middlewares.length>0&&p.push(...m.middlewares),m.authCallback&&!s&&(s=m.authCallback);let P=this._trie.match(l);if(P){Object.assign(c,P.params);for(let m of P.routers)d.push(m),u=true,m._routeConfig&&(y=Object.assign(y||{},m._routeConfig)),m.middlewares.length>0&&p.push(...m.middlewares),m.authCallback&&!s&&(s=m.authCallback);}for(let m of this._regexRouters)for(let I of m._regexPatterns){let S=I.regex.exec(l);if(S){if(d.push(m),u=true,S.groups)for(let[f,x]of Object.entries(S.groups))c[f]=oe(x??"");m._routeConfig&&(y=Object.assign(y||{},m._routeConfig)),m.middlewares.length>0&&p.push(...m.middlewares),m.authCallback&&!s&&(s=m.authCallback);break}}let h=c.identity;if(!h){let m=l.split("/").filter(Boolean);h=oe(m[m.length-1]??"");}if(!h){A(t,400,"Missing identity in URL path");return}for(let m of d)if(m._routeCORS){let{allowed:I,reason:S}=He(e,m._routeCORS);if(!I){this._logger?.warn?.("Route CORS rejected connection",{reason:S,ip:e.socket.remoteAddress}),A(t,403,"Forbidden");return}}"setKeepAlive"in t&&t.setKeepAlive(true);let j=new Set,w=e.headers["sec-websocket-protocol"];if(w)try{j=yt(w);}catch{A(t,400,"Invalid Sec-WebSocket-Protocol header");return}let M=y?.protocols??this._options.protocols??[],O;if(M.length>0){if(j.size===0){A(t,400,"Missing subprotocol");return}if(O=M.find(m=>j.has(m)),!O){A(t,400,"No matching subprotocol");return}}let Ne=vt(e.headers.authorization??"",h),Xe,Qe=this._options.securityProfile??0;Qe===3&&"getPeerCertificate"in t&&(Xe=t.getPeerCertificate());let te={identity:h,remoteAddress:e.socket.remoteAddress??"",headers:e.headers,protocols:j,pathname:l,params:c,query:a.searchParams,request:e,password:Ne,clientCertificate:Xe,securityProfile:Qe},ke,Ye;if(s||p.length>0){let m=new AbortController,I=()=>{m.abort(new Error("Socket closed during handshake"));};t.on("close",I),t.on("error",I),t.on("end",I);let S=this._options.handshakeTimeoutMs??3e4,f;S>0&&(f=setTimeout(()=>{m.abort(new Error("Handshake timeout"));},S));try{ke={handshake:te,state:{},reject:(v=401,E="Unauthorized")=>{throw {code:v,message:E,_isMiddlewareReject:!0}},next:async v=>{}};let x=[...p],T=!1;if(x.push(async v=>{T=!0,s?Ye=await new Promise((E,F)=>{let L=!1,pe=K=>{L||(L=!0,K?.protocol&&(O=K.protocol),E(K));},Fe=(K=401,Ze="Unauthorized")=>{throw L||(L=!0,F({code:K,message:Ze})),{code:K,message:Ze,_isMiddlewareReject:!0}};if(m.signal.aborted){F(m.signal.reason);return}m.signal.addEventListener("abort",()=>{L||(L=!0,F(m.signal.reason));},{once:!0}),this._logger?.debug?.("Executing auth callback",{identity:h,pathname:l});let Pt={handshake:te,state:v.state,reject:Fe,signal:m.signal,accept:pe};s(Pt);}):O=te.protocols.values().next().value??void 0;}),await dt(x,ke),!T)throw {code:500,message:"Middleware chain halted unexpectedly without rejecting",_isMiddlewareReject:!0}}catch(x){if(m.signal.aborted){let L=x instanceof Error?x.message:"Unknown abort";this._logger?.warn?.("Handshake aborted",{identity:h,reason:L});let pe={type:"UPGRADE_ABORTED",identity:h,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{reason:L}};this.emit("securityEvent",pe);for(let Fe of this._plugins)try{Fe.onSecurityEvent?.(pe);}catch{}this.emit("upgradeAborted",{identity:h,reason:L,socket:t,request:e}),t.destroyed||t.destroy();return}let T=x,v=typeof T?.code=="number"?T.code:401,E=typeof T?.message=="string"?T.message:"Unauthorized";this._logger?.warn?.("Auth rejected",{identity:h,code:v});let F={type:"AUTH_FAILED",identity:h,ip:e.socket.remoteAddress,timestamp:new Date().toISOString(),details:{code:v,message:E}};this.emit("securityEvent",F);for(let L of this._plugins){try{L.onSecurityEvent?.(F);}catch{}try{L.onAuthFailed?.(te,v,E);}catch{}}A(t,v,E);return}finally{f&&clearTimeout(f),t.removeListener("close",I),t.removeListener("error",I),t.removeListener("end",I);}}else if(g&&!u){this._logger?.warn?.("Connection rejected: No matching route found",{pathname:l}),A(t,404,"Endpoint Not Found");return}if(t.readyState!=="open"){this._logger?.debug?.("Socket closed before upgrade completion",{identity:h}),t.destroyed||t.destroy();return}this._wss||(this._wss=this._createWss()),this._wss.handleUpgrade(e,t,n,m=>{let I={identity:h,endpoint:"",callTimeoutMs:y?.callTimeoutMs??this._options.callTimeoutMs,pingIntervalMs:y?.pingIntervalMs??this._options.pingIntervalMs,deferPingsOnActivity:y?.deferPingsOnActivity??this._options.deferPingsOnActivity,callConcurrency:y?.callConcurrency??this._options.callConcurrency,maxBadMessages:this._options.maxBadMessages,respondWithDetailedErrors:this._options.respondWithDetailedErrors,strictMode:y?.strictMode??this._options.strictMode,strictModeMethods:y?.strictModeMethods??this._options.strictModeMethods,strictModeValidators:this._options.strictModeValidators,rateLimit:y?.rateLimit??this._options.rateLimit,reconnect:false,logging:this._options.logging},S={...ke?.state||{},...this._sessions.get(h)?.data||{},...Ye?.session||{}},f=new Ve(I,{ws:m,handshake:te,session:S,protocol:O,adaptiveMultiplier:this._adaptiveLimiter?()=>this._adaptiveLimiter?.multiplier??1:void 0,workerPool:this._workerPool??void 0,plugins:this._plugins});this._updateSessionActivity(h,f.session);let x=this._clientsByIdentity.get(h);if(x&&x!==f){this._logger?.warn?.("Evicting stale connection for identity",{identity:h,reason:"Duplicate identity replaced by new connection"});for(let T of this._plugins)try{T.onEviction?.(x,f);}catch{}x.close({code:4e3,reason:"Evicted by new connection",force:true}).catch(()=>{}),this._clients.delete(x);}if(this._clients.add(f),this._clientsByIdentity.set(h,f),this._adapter?.setPresence){let T=this._options.presenceTtlSeconds??300;this._adapter.setPresence(h,this._nodeId,T).catch(v=>{this._logger?.error?.("Error setting presence",{identity:h,error:v});});}this._logger?.info?.("Client connected",{identity:h,remoteAddress:e.socket.remoteAddress,protocol:O}),f.on("close",({code:T,reason:v})=>{this._clients.delete(f),this._clientsByIdentity.get(h)===f&&(this._clientsByIdentity.delete(h),this._adapter?.removePresence&&this._adapter.removePresence(h).catch(E=>{this._logger?.error?.("Error removing presence",{identity:h,error:E});}));for(let E of this._plugins)try{E.onDisconnect?.(f,T,v);}catch(F){this._logger?.error?.("Plugin onDisconnect error",{name:E.name,error:F.message});}this._logger?.info?.("Client disconnected",{identity:h});});for(let T of this._plugins)try{let v=T.onConnection?.(f);v instanceof Promise&&v.catch(E=>{this._logger?.error?.("Plugin onConnection error",{name:T.name,error:E.message});});}catch(v){this._logger?.error?.("Plugin onConnection error",{name:T.name,error:v.message});}f.on("message",T=>{for(let v of this._plugins)try{v.onMessage?.(f,T);}catch{}}),f.on("error",T=>{for(let v of this._plugins)try{v.onError?.(f,T);}catch{}}),f.on("badMessage",({message:T,error:v})=>{for(let E of this._plugins)try{E.onBadMessage?.(f,T,v);}catch{}}),f.on("strictValidationFailure",({message:T,error:v})=>{for(let E of this._plugins)try{E.onValidationFailure?.(f,T,v);}catch{}}),f.on("backpressure",T=>{for(let v of this._plugins)try{v.onBackpressure?.(f,T.bufferedAmount);}catch{}}),f.on("pongTimeout",()=>{for(let T of this._plugins)try{T.onPongTimeout?.(f);}catch{}}),f.on("handlerError",({method:T,error:v})=>{for(let E of this._plugins)try{E.onHandlerError?.(f,T,v);}catch{}}),f.on("rateLimitExceeded",T=>{for(let v of this._plugins)try{v.onRateLimitExceeded?.(f,T.rawData);}catch{}}),this.emit("client",f);for(let T of d)T.emit("client",f);f.on("message",()=>{this._updateSessionActivity(h,f.session);});});}_updateSessionActivity(e,t){this._sessions.set(e,{data:t,lastActive:Date.now()});}_sweepConnectionBuckets(e){let t=this._options.connectionRateLimit;if(!t){this._connectionBuckets.clear();return}for(let[n,i]of this._connectionBuckets)e-i.lastRefill>t.windowMs&&this._connectionBuckets.delete(n);}async close(e={}){if(this._state!=="OPEN")return;this._state="CLOSING",this.emit("closing"),this._logger?.info?.("Server closing",{clientCount:this._clients.size});for(let i of this._plugins)try{let r=i.onClosing?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClosing error",{name:i.name,error:r.message});}if(this._gcInterval&&(clearInterval(this._gcInterval),this._gcInterval=null),this._telemetryInterval&&(clearInterval(this._telemetryInterval),this._telemetryInterval=null),this._presenceInterval&&(clearInterval(this._presenceInterval),this._presenceInterval=null),!e.force){let r=Array.from(this._clients).map(async a=>{a.bufferedAmount>0&&(this._logger?.debug?.("Waiting for client buffer to drain",{identity:a.identity,bufferedAmount:a.bufferedAmount}),await new Promise(s=>{let p=0,d=setInterval(()=>{p+=50,(a.bufferedAmount===0||p>=5e3)&&(clearInterval(d),s());},50);}));});await Promise.allSettled(r);}let t=Array.from(this._clients).map(i=>i.close(e).catch(()=>{}));await Promise.allSettled(t);for(let i of this._httpServerAbortControllers)i.abort();this._httpServerAbortControllers.clear(),this._wss&&(this._wss.close(),this._wss=this._createWss());let n=[];for(let i of this._httpServers){let r=this._attachedHttpHandlers.get(i);r&&(i.removeListener("upgrade",r.upgrade),r.request&&i.removeListener("request",r.request)),this._ownedHttpServers.has(i)&&n.push(new Promise(a=>{i.close(()=>a());}));}await Promise.allSettled(n),this._httpServers.clear(),this._ownedHttpServers.clear(),this._attachedHttpHandlers.clear(),this._adaptiveLimiter&&this._adaptiveLimiter.stop(),this._workerPool&&(await this._workerPool.shutdown().catch(()=>{}),this._workerPool=null);for(let i of this._plugins)try{let r=i.onClose?.();r instanceof Promise&&await r;}catch(r){this._logger?.error?.("Plugin onClose error",{name:i.name,error:r.message});}for(let[,i]of this._pendingRemoteCalls)clearTimeout(i.timer),i.reject(new Error("Server closing"));this._pendingRemoteCalls.clear(),this._adapter&&await this._adapter.disconnect(),this._state="CLOSED",this.emit("close");}reconfigure(e){let t={...this._options};if(Object.assign(this._options,e),(e.maxPayloadBytes!==void 0||e.compression!==void 0)&&(this._wss?.close(),this._wss=this._createWss()),e.rateLimit!==void 0){let n=!!e.rateLimit?.adaptive;if(n&&!this._adaptiveLimiter){let i=e.rateLimit;this._adaptiveLimiter=new re({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();}else !n&&this._adaptiveLimiter&&(this._adaptiveLimiter.stop(),this._adaptiveLimiter=null);}e.presenceTtlSeconds!==void 0&&this._presenceInterval&&(clearInterval(this._presenceInterval),this._presenceInterval=null,this._startPresenceRefresh());for(let n of this._plugins)try{n.onReconfigure?.(e,t);}catch(i){this._logger?.error?.("Plugin onReconfigure error",{name:n.name,error:i.message});}}async sendToClient(...e){let t,n,i,r,a;e.length>=4&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?(t=e[0],n=e[1],i=e[2],r=e[3],a=e[4]):(t=e[0],i=e[1],r=e[2],a=e[3]);let s=this._clientsByIdentity.get(t);if(s)return n?await s.call(n,i,r,a):await s.call(i,r,a);if(this._adapter?.getPresence){let p=await this._adapter.getPresence(t);if(p){let d=ae(),c=(a?.timeoutMs??this._options.callTimeoutMs??3e4)+o._REMOTE_RESPONSE_GRACE_MS,l=new Promise((u,g)=>{let y=setTimeout(()=>{this._pendingRemoteCalls.delete(d),g(new G(`Remote call to "${t}" via node ${p} timed out after ${c}ms`));},c);this._pendingRemoteCalls.set(d,{resolve:u,reject:g,timer:y});});try{await this._adapter.publish(`ocpp:node:${p}`,{source:this._nodeId,target:t,version:n,method:i,params:r,options:a,correlationId:d});}catch(u){let g=this._pendingRemoteCalls.get(d);g&&(clearTimeout(g.timer),this._pendingRemoteCalls.delete(d),g.reject(u));}return await l}}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 n=this._clientsByIdentity.get(e);return n?(await Promise.allSettled(t.map(r=>n.callImmediate(r.method,r.params,r.options??{})))).map(r=>{if(r.status==="fulfilled")return r.value;this._logger?.warn?.("sendBatch: individual call failed",{identity:e,error:r.reason?.message});}):(this._logger?.warn?.("sendBatch: client not found locally",{identity:e}),t.map(()=>{}))}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);}),this._startPresenceRefresh();}_startPresenceRefresh(){if(this._presenceInterval||!this._adapter?.setPresence)return;let e=this._options.presenceTtlSeconds??300,t=Math.max(250,e*1e3/2);this._presenceInterval=setInterval(()=>{this._refreshPresence(e).catch(n=>{this._logger?.warn?.("Presence refresh failed",{error:n});});},t),this._presenceInterval.unref();}async _refreshPresence(e){let t=this._adapter;if(!t)return;let n=Array.from(this._clientsByIdentity.keys());n.length!==0&&(t.setPresenceBatch?await t.setPresenceBatch(n.map(i=>({identity:i,nodeId:this._nodeId,ttl:e}))):t.setPresence&&await Promise.all(n.map(i=>t.setPresence(i,this._nodeId,e))));}_onBroadcast(e){try{if(!e||typeof e!="object")return;let t=e;if(t.source===this._nodeId)return;for(let n of this._clients)n.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;if(t.__type==="callResult"&&t.correlationId){let r=this._pendingRemoteCalls.get(t.correlationId);if(!r)return;this._pendingRemoteCalls.delete(t.correlationId),clearTimeout(r.timer),t.ok?r.resolve(t.result):r.reject(H(t.error?.code??"GenericError",t.error?.message,t.error?.details??{}));return}let n=e,i=this._clientsByIdentity.get(n.target);if(i){(n.version?i.call(n.version,n.method,n.params,n.options):i.call(n.method,n.params,n.options)).then(a=>{this._publishRemoteResult(n,{ok:!0,result:a});},a=>{this._publishRemoteResult(n,{ok:!1,error:{code:a?.rpcErrorCode??"GenericError",message:a?.message??"",details:a?.details??{}}}),a.name!=="TimeoutError"&&this._logger?.error?.("Error delivering unicast to client",{identity:n.target,error:a});});return}this._logger?.warn?.("Received unicast for unknown client",{target:n.target}),this._publishRemoteResult(n,{ok:!1,error:{code:"GenericError",message:`Client ${n.target} not found on node ${this._nodeId}`}}),this._adapter?.removePresence&&this._adapter.removePresence(n.target).catch(()=>{});}catch(t){this._logger?.error?.("Error processing unicast",{error:t.message});}}_publishRemoteResult(e,t){!e.correlationId||!e.source||!this._adapter||this._adapter.publish(`ocpp:node:${e.source}`,{__type:"callResult",correlationId:e.correlationId,...t}).catch(n=>{this._logger?.error?.("Failed to publish remote call result",{error:n});});}async publish(e,t){this._adapter&&await this._adapter.publish(e,t);}async broadcast(e,t){let n=Array.from(this._clients).map(r=>r.call(e,t).catch(()=>{})),i=this._adapter?this._adapter.publish("ocpp:broadcast",{source:this._nodeId,method:e,params:t}):Promise.resolve();await Promise.all([Promise.all(n),i]);}async broadcastBatch(e,t,n,i){let r=new Set,a=[];for(let p of e){let d=this._clientsByIdentity.get(p);d&&(r.add(p),a.push(d.call(t,n,i).catch(()=>{})));}let s=e.filter(p=>!r.has(p));if(s.length>0&&this._adapter){let p=[];this._adapter.getPresenceBatch?p=await this._adapter.getPresenceBatch(s):this._adapter.getPresence&&(p=await Promise.all(s.map(c=>this._adapter.getPresence(c))));let d=[];for(let c=0;c<s.length;c++){let l=p[c];l&&d.push({channel:`ocpp:node:${l}`,data:{source:this._nodeId,target:s[c],method:t,params:n,options:i}});}d.length>0&&(this._adapter.publishBatch?await this._adapter.publishBatch(d):await Promise.all(d.map(c=>this._adapter.publish(c.channel,c.data))));}await Promise.all(a);}_createWss(){return new WebSocketServer({noServer:true,maxPayload:this._options.maxPayloadBytes??65536,perMessageDeflate:this._buildCompressionConfig()})}_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}};function Ct(o,e){let t=o.endsWith("/*")?o.slice(0,-2):o;return t===""||t==="/"?true:e===t||e.startsWith(`${t}/`)}var q=class{constructor(e,t={},n){this.ocppServer=e;this.options=t;this.httpAdapterHost=n;}ocppServer;options;httpAdapterHost;attachedHttpServer;gatewayPatterns=new Set;acceptAllUpgrades=false;upgradeHandler=(e,t,n)=>this.handleUpgrade(e,t,n);onModuleInit(){if(this.options.autoAttach===false)return;let e=this.httpAdapterHost?.httpAdapter?.getHttpServer();!e||this.attachedHttpServer===e||(e.on("upgrade",this.upgradeHandler),this.attachedHttpServer=e);}async onModuleDestroy(){this.attachedHttpServer&&(this.attachedHttpServer.removeListener("upgrade",this.upgradeHandler),this.attachedHttpServer=void 0),await this.ocppServer.close();}get server(){return this.ocppServer}get clients(){return this.ocppServer.clients}stats(){return this.ocppServer.stats()}getClient(e){return this.ocppServer.getLocalClient(e)}getLocalClient(e){return this.ocppServer.getLocalClient(e)}hasLocalClient(e){return this.ocppServer.hasLocalClient(e)}hasClient(e){return this.ocppServer.isClientConnected(e)}async sendToClient(...e){return this.ocppServer.sendToClient.apply(this.ocppServer,e)}async safeSendToClient(...e){return this.ocppServer.safeSendToClient.apply(this.ocppServer,e)}close(e){return this.ocppServer.close(e)}registerUpgradePath(e){if(!e){this.acceptAllUpgrades=true;return}this.gatewayPatterns.add(e);}handleUpgrade(e,t,n){this.shouldHandleUpgrade(e)&&this.ocppServer.handleUpgrade(e,t,n);}shouldHandleUpgrade(e){if(e.headers.upgrade?.toLowerCase()!=="websocket")return false;let t=this.getPathname(e);if(!t)return false;if(this.options.upgradeFilter)return this.options.upgradeFilter(t,e);let n=this.normalizePrefixes(this.options.upgradePathPrefix);if(n.length>0)return n.some(i=>Ct(i,t));if(this.acceptAllUpgrades||this.gatewayPatterns.size===0)return true;for(let i of this.gatewayPatterns)if(this.matchesPattern(i,t))return true;return false}getPathname(e){try{return new URL(e.url??"/",`http://${e.headers.host??"localhost"}`).pathname}catch{return}}normalizePrefixes(e){return e?(Array.isArray(e)?e:[e]).filter(Boolean):[]}matchesPattern(e,t){if(e instanceof RegExp)return e.test(t);let n=e.split("/").filter(Boolean),i=t.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let a=n[r],s=i[r];if(a==="*")return true;if(s===void 0)return false;if(!a.startsWith(":")&&a!==s)return false}return n.length===i.length}};q=U([Injectable(),X(0,Inject(V)),X(1,Optional()),X(1,Inject(W)),X(2,Optional()),X(2,Inject(HttpAdapterHost))],q);var B=class{_isModule=true;static forRoot(e={}){let t={provide:W,useValue:e},n={provide:V,useValue:new de(e)};return {module:B,providers:[t,n],exports:[q,V]}}static forRootAsync(e){let i=[B.createAsyncOptionsProvider(e),{provide:V,useFactory:async r=>new de(r),inject:[W]}];return e.useClass&&i.push({provide:e.useClass,useClass:e.useClass}),{module:B,imports:e.imports||[],providers:i,exports:[q,V]}}static createAsyncOptionsProvider(e){if(e.useFactory)return {provide:W,useFactory:e.useFactory,inject:e.inject||[]};let t=e.useExisting||e.useClass;return t?{provide:W,useFactory:async n=>n.createOcppOptions(),inject:[t]}:{provide:W,useValue:{}}}};B=U([Global(),Module({imports:[DiscoveryModule],providers:[q,{provide:N,inject:[DiscoveryService,MetadataScanner,V,q],useFactory:(o,e,t,n)=>new N(o,e,t,n)}],exports:[q,V]})],B);
|
|
4826
|
+
export{Xi as Client,Zi as Context,sn as Handshake,en as Identity,Qi as Message,on as MessageId,ue as OCPP_AUTH_METADATA,me as OCPP_CONNECTION_MIDDLEWARE_METADATA,fe as OCPP_CORS_METADATA,ie as OCPP_GATEWAY_METADATA,ce as OCPP_MESSAGE_EVENT_METADATA,he as OCPP_RPC_MIDDLEWARE_METADATA,V as OCPP_SERVER_INSTANCE,W as OCPP_SERVER_OPTIONS,le as OCPP_WILDCARD_EVENT_METADATA,Ui as OcppAuth,Wi as OcppConnectionMiddleware,ji as OcppCors,N as OcppExplorer,Ri as OcppGateway,ki as OcppMessageEvent,ye as OcppMiddleware,B as OcppModule,We as OcppParamType,q as OcppService,Fi as OcppWildcardEvent,ne as PARAM_ARGS_METADATA,Yi as Params,tn as Path,rn as PathParam,an as Protocol,nn as Session,qi as UseOcppRpcMiddleware};
|