ocpp-ws-io 2.2.4 → 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 +3 -3
- 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-B_y56LLS.d.ts → context-B4-L-O1-.d.ts} +1 -1
- package/dist/{context-BVYqFvfw.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-DrWsObRI.d.ts → index-CEMhGOxh.d.ts} +16 -6
- package/dist/{index-Dr8uXTWu.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 +7 -7
- package/dist/index.mjs +7 -7
- package/dist/nestjs.d.mts +1 -1
- package/dist/nestjs.d.ts +1 -1
- package/dist/nestjs.js +8 -8
- package/dist/nestjs.mjs +8 -8
- package/dist/parse-worker.cjs +91 -0
- package/dist/plugins.d.mts +12 -2
- package/dist/plugins.d.ts +12 -2
- package/dist/plugins.js +1 -1
- package/dist/plugins.mjs +1 -1
- package/dist/{types-BsoUgWtt.d.mts → types-tTYOr5Gm.d.mts} +110 -22
- package/dist/{types-BsoUgWtt.d.ts → types-tTYOr5Gm.d.ts} +110 -22
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
The **production-ready OCPP RPC implementation** for building type-safe EV charging platforms, CSMS backends, charge points, and simulators. Supports OCPP 1.6J, 2.0.1, and 2.1 with full protocol compliance, all security profiles, Redis clustering, strict JSON schema validation, and structured logging.
|
|
8
8
|
|
|
9
|
-
> **Built with TypeScript** for EV charging, CSMS, CPO/EMSP platforms.
|
|
9
|
+
> **Built with TypeScript** for EV charging, CSMS, CPO/EMSP platforms. Lightweight WebSocket RPC framework (runtime deps: ws, ajv, ajv-formats, voltlog-io) supporting OCPP versions 1.6, 2.0.1, and 2.1 with optional JSON schema validation, bidirectional messaging, all security profiles (0–3), Redis pub/sub clustering, and structured logging powered by [voltlog-io](https://ocpp-ws-io.rohittiwari.me/docs/voltlog-io).
|
|
10
10
|
|
|
11
11
|
[](https://www.npmjs.com/package/ocpp-ws-io)
|
|
12
12
|
[](https://github.com/rohittiwari-dev/ocpp-ws-io/blob/main/LICENSE)
|
|
@@ -163,7 +163,7 @@ await client.call("ocpp1.6", "BootNotification", { ... }, { idempotencyKey: "uni
|
|
|
163
163
|
| `rateLimit` | `RateLimitOptions` | — | Token bucket socket & method rate-limiter |
|
|
164
164
|
| `healthEndpoint` | `boolean` | `false` | Expose HTTP `/health` and `/metrics` APIs |
|
|
165
165
|
|
|
166
|
-
## � Message Observability & Event Handling (
|
|
166
|
+
## � Message Observability & Event Handling (v2.2+)
|
|
167
167
|
|
|
168
168
|
Unified message event API with direction tracking and rich contextual metadata for complete visibility into OCPP message flow.
|
|
169
169
|
|
|
@@ -448,7 +448,7 @@ client.use(async (ctx, next) => {
|
|
|
448
448
|
|
|
449
449
|
## 📡 Redis Clustering & Distributed CSMS Architecture
|
|
450
450
|
|
|
451
|
-
Scale OCPP RPC servers across multiple nodes with Redis pub/sub, Streams, and presence tracking for enterprise CSMS deployments.
|
|
451
|
+
Scale OCPP RPC servers across multiple nodes with Redis pub/sub, Streams, and presence tracking for enterprise CSMS deployments. Cross-node `sendToClient` returns the remote client's response (correlated over the adapter); sessions remain node-local.
|
|
452
452
|
|
|
453
453
|
### Set Up Redis Clustering
|
|
454
454
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import '../types-
|
|
2
|
-
export { a as RedisAdapter, b as RedisAdapterOptions } from '../index-
|
|
1
|
+
import '../types-tTYOr5Gm.mjs';
|
|
2
|
+
export { a as RedisAdapter, b as RedisAdapterOptions } from '../index-Gz98XqQ7.mjs';
|
|
3
3
|
import 'ws';
|
|
4
4
|
import 'node:https';
|
|
5
5
|
import 'node:http';
|
package/dist/adapters/redis.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import '../types-
|
|
2
|
-
export { a as RedisAdapter, b as RedisAdapterOptions } from '../index-
|
|
1
|
+
import '../types-tTYOr5Gm.js';
|
|
2
|
+
export { a as RedisAdapter, b as RedisAdapterOptions } from '../index-CEMhGOxh.js';
|
|
3
3
|
import 'ws';
|
|
4
4
|
import 'node:https';
|
|
5
5
|
import 'node:http';
|
package/dist/adapters/redis.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var l=class{constructor(e,s,
|
|
1
|
+
'use strict';var l=class{constructor(e,s,r){this.pub=e;this.sub=s;this.blocking=r;this.sub.on&&this.sub.on("message",(t,i)=>{let a=this._handlers.get(t);a&&a(i);});}pub;sub;blocking;_handlers=new Map;get hasBlockingClient(){return !!this.blocking}async publish(e,s){await this.pub.publish(e,s);}async subscribe(e,s){this._handlers.set(e,s),await this.sub.subscribe(e);}async unsubscribe(e){await this.sub.unsubscribe(e),this._handlers.delete(e);}async set(e,s,r){r?await this.pub.set(e,s,"EX",r):await this.pub.set(e,s);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mget(...e)}async del(e){await this.pub.del(e);}async xadd(e,s,r){let t=[];r&&t.push("MAXLEN","~",r.toString()),t.push("*");for(let[i,a]of Object.entries(s))t.push(i,a);return await this.pub.xadd(e,...t)}async xaddBatch(e,s){if(e.length===0)return;let r=this.pub.pipeline();for(let t of e){let i=[];s&&i.push("MAXLEN","~",s.toString()),i.push("*");for(let[a,n]of Object.entries(t.args))i.push(a,n);r.xadd(t.stream,...i);}await r.exec();}async xread(e,s,r){let t=[];s&&t.push("COUNT",s),typeof r=="number"&&t.push("BLOCK",r),t.push("STREAMS"),e.forEach(n=>{t.push(n.key);}),e.forEach(n=>{t.push(n.id);});let a=await(r&&this.blocking?this.blocking:this.pub).xread(...t);return a?a.map(([n,o])=>({stream:n,messages:o.map(([u,h])=>{let m={};for(let d=0;d<h.length;d+=2)m[h[d]]=h[d+1];return {id:u,data:m}})})):null}async xlen(e){return await this.pub.xlen(e)}async disconnect(){this._handlers.clear();let e=async s=>{s.quit?await s.quit():s.disconnect&&await s.disconnect();};await Promise.all([e(this.pub),e(this.sub)]);}async setPresenceBatch(e){if(e.length===0)return;let s=this.pub.pipeline();for(let{key:r,value:t,ttlSeconds:i}of e)s.set(r,t,"EX",i);await s.exec();}async expire(e,s){await this.pub.expire(e,s);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}},g=class{constructor(e,s,r){this.pub=e;this.sub=s;this.blocking=r;}pub;sub;blocking;get hasBlockingClient(){return !!this.blocking}async publish(e,s){await this.pub.publish(e,s);}async subscribe(e,s){await this.sub.subscribe(e,s);}async unsubscribe(e){await this.sub.unsubscribe(e);}async set(e,s,r){r?await this.pub.set(e,s,{EX:r}):await this.pub.set(e,s);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mGet(e)}async del(e){await this.pub.del(e);}async xadd(e,s,r){return await this.pub.xAdd(e,"*",s,{TRIM:r?{strategy:"MAXLEN",strategyModifier:"~",threshold:r}:void 0})}async xaddBatch(e,s){if(e.length===0)return;let r=this.pub.multi();for(let t of e)r.xAdd(t.stream,"*",t.args,{TRIM:s?{strategy:"MAXLEN",strategyModifier:"~",threshold:s}:void 0});await r.exec();}async xread(e,s,r){let t={};s&&(t.COUNT=s),typeof r=="number"&&(t.BLOCK=r);let i=e.map(o=>({key:o.key,id:o.id})),n=await(r&&this.blocking?this.blocking:this.pub).xRead(i,t);return !n||n.length===0?null:n.map(o=>({stream:o.name,messages:o.messages.map(u=>({id:u.id,data:u.message}))}))}async xlen(e){return await this.pub.xLen(e)}async disconnect(){await Promise.all([this.pub.disconnect(),this.sub.disconnect()]);}async setPresenceBatch(e){if(e.length===0)return;let s=this.pub.multi();for(let{key:r,value:t,ttlSeconds:i}of e)s.set(r,t,{EX:i});await s.exec();}async expire(e,s){await this.pub.expire(e,s);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}};function p(c,e,s){return e.isOpen!==void 0&&typeof e.subscribe=="function"?new g(c,e,s):new l(c,e,s)}var b=class{_driver;_prefix;_streamMaxLen;_streamTtlSeconds;_presenceTtlSeconds;_handlers=new Map;_streamOffsets=new Map;_streams=new Set;_polling=false;_closed=false;_unsubError;_unsubReconnect;_presenceCache=new Map;_driverPool;_nextPoolIndex;constructor(e){if(this._prefix=e.prefix??"ocpp-ws-io:",this._streamMaxLen=e.streamMaxLen??1e3,this._streamTtlSeconds=e.streamTtlSeconds??300,this._presenceTtlSeconds=e.presenceTtlSeconds??300,e.driver)this._driver=e.driver;else if(e.pubClient&&e.subClient)this._driver=p(e.pubClient,e.subClient,e.blockingClient);else throw new Error("RedisAdapter requires either `driver` or both `pubClient` and `subClient`");let s=e.poolSize??1;if(this._driverPool=[this._driver],this._nextPoolIndex=0,s>1&&e.driverFactory)for(let r=1;r<s;r++)this._driverPool.push(e.driverFactory());this._driver.onError&&(this._unsubError=this._driver.onError(r=>{console.error("[RedisAdapter] Redis error:",r.message);})),this._driver.onReconnect&&(this._unsubReconnect=this._driver.onReconnect(()=>{this._rehydratePresence().catch(()=>{});}));}_getPoolDriver(){if(this._driverPool.length===1)return this._driver;let e=this._driverPool[this._nextPoolIndex];return this._nextPoolIndex=(this._nextPoolIndex+1)%this._driverPool.length,e}async publish(e,s){let r=this._prefix+e,t=JSON.stringify(s);if(e.startsWith("ocpp:node:")){let i=this._getPoolDriver();await i.xadd(r,{message:t},this._streamMaxLen),await i.expire(r,this._streamTtlSeconds).catch(()=>{});}else await this._getPoolDriver().publish(r,t);}async publishBatch(e){let s=[],r=[];for(let i of e){let a=this._prefix+i.channel,n=JSON.stringify(i.data);i.channel.startsWith("ocpp:node:")?s.push({stream:a,args:{message:n}}):r.push({channel:a,message:n});}let t=[];s.length>0&&t.push(this._getPoolDriver().xaddBatch(s,this._streamMaxLen)),r.length>0&&t.push(Promise.all(r.map(i=>this._getPoolDriver().publish(i.channel,i.message))).then(()=>{})),await Promise.all(t);}async subscribe(e,s){if(!this._handlers.has(e)){this._handlers.set(e,new Set);let r=this._prefix+e;e.startsWith("ocpp:node:")?this._streams.has(r)||(this._streams.add(r),this._streamOffsets.has(r)||this._streamOffsets.set(r,"0"),this._ensurePolling()):await this._driver.subscribe(r,t=>{this._handleMessage(e,t);});}this._handlers.get(e)?.add(s);}async unsubscribe(e){let s=this._prefix+e;this._streams.has(s)?this._streams.delete(s):await this._driver.unsubscribe(s),this._handlers.delete(e);}async disconnect(){this._closed=true,this._handlers.clear(),this._streams.clear(),this._presenceCache.clear(),this._unsubError&&this._unsubError(),this._unsubReconnect&&this._unsubReconnect(),await Promise.allSettled(this._driverPool.map(e=>e.disconnect()));}_handleMessage(e,s){let r=this._handlers.get(e);if(!r)return;let t;try{t=JSON.parse(s);}catch{t=s;}for(let i of r)try{i(t);}catch{}}_ensurePolling(){this._polling||this._closed||(this._polling=true,this._pollLoop().catch(()=>{this._polling=false;}));}async _pollLoop(){for(;!this._closed;){if(this._streams.size===0){await new Promise(r=>setTimeout(r,1e3));continue}let e=Array.from(this._streams).map(r=>({key:r,id:this._streamOffsets.get(r)||"$"})),s=this._driver.hasBlockingClient===true;try{let r=await this._driver.xread(e,void 0,s?1e3:void 0);if(r)for(let t of r){let i=t.stream.replace(this._prefix,"");for(let a of t.messages){this._streamOffsets.set(t.stream,a.id);let n=a.data.message;n&&this._handleMessage(i,n);}}else s||await new Promise(t=>setTimeout(t,1e3));}catch{await new Promise(t=>setTimeout(t,1e3));}}this._polling=false;}async setPresence(e,s,r){let t=`${this._prefix}presence:${e}`;this._presenceCache.set(e,{nodeId:s,ttl:r}),await this._driver.set(t,s,r);}async getPresence(e){let s=`${this._prefix}presence:${e}`;return await this._driver.get(s)}async getPresenceBatch(e){if(e.length===0)return [];let s=e.map(r=>`${this._prefix}presence:${r}`);return this._driver.mget?await this._driver.mget(s):await Promise.all(s.map(r=>this._driver.get(r)))}async removePresence(e){let s=`${this._prefix}presence:${e}`;this._presenceCache.delete(e),await this._driver.del(s);}async metrics(){let e=0,s={};for(let r of this._streams)try{let t=await this._driver.xlen(r);e+=t,s[r]=t;}catch{s[r]=-1;}return {pendingMessages:e,activeStreams:this._streams.size,streamDetails:s}}async setPresenceBatch(e){if(e.length===0)return;let s=e.map(({identity:r,nodeId:t,ttl:i})=>{let a=`${this._prefix}presence:${r}`,n=i??this._presenceTtlSeconds;return this._presenceCache.set(r,{nodeId:t,ttl:n}),{key:a,value:t,ttlSeconds:n}});await this._driver.setPresenceBatch(s);}async _rehydratePresence(){if(this._presenceCache.size===0)return;let e=Array.from(this._presenceCache.entries()).map(([s,{nodeId:r,ttl:t}])=>({key:`${this._prefix}presence:${s}`,value:r,ttlSeconds:t}));await this._driver.setPresenceBatch(e);}};exports.RedisAdapter=b;
|
package/dist/adapters/redis.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var l=class{constructor(e,s,
|
|
1
|
+
var l=class{constructor(e,s,r){this.pub=e;this.sub=s;this.blocking=r;this.sub.on&&this.sub.on("message",(t,i)=>{let a=this._handlers.get(t);a&&a(i);});}pub;sub;blocking;_handlers=new Map;get hasBlockingClient(){return !!this.blocking}async publish(e,s){await this.pub.publish(e,s);}async subscribe(e,s){this._handlers.set(e,s),await this.sub.subscribe(e);}async unsubscribe(e){await this.sub.unsubscribe(e),this._handlers.delete(e);}async set(e,s,r){r?await this.pub.set(e,s,"EX",r):await this.pub.set(e,s);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mget(...e)}async del(e){await this.pub.del(e);}async xadd(e,s,r){let t=[];r&&t.push("MAXLEN","~",r.toString()),t.push("*");for(let[i,a]of Object.entries(s))t.push(i,a);return await this.pub.xadd(e,...t)}async xaddBatch(e,s){if(e.length===0)return;let r=this.pub.pipeline();for(let t of e){let i=[];s&&i.push("MAXLEN","~",s.toString()),i.push("*");for(let[a,n]of Object.entries(t.args))i.push(a,n);r.xadd(t.stream,...i);}await r.exec();}async xread(e,s,r){let t=[];s&&t.push("COUNT",s),typeof r=="number"&&t.push("BLOCK",r),t.push("STREAMS"),e.forEach(n=>{t.push(n.key);}),e.forEach(n=>{t.push(n.id);});let a=await(r&&this.blocking?this.blocking:this.pub).xread(...t);return a?a.map(([n,o])=>({stream:n,messages:o.map(([u,h])=>{let m={};for(let d=0;d<h.length;d+=2)m[h[d]]=h[d+1];return {id:u,data:m}})})):null}async xlen(e){return await this.pub.xlen(e)}async disconnect(){this._handlers.clear();let e=async s=>{s.quit?await s.quit():s.disconnect&&await s.disconnect();};await Promise.all([e(this.pub),e(this.sub)]);}async setPresenceBatch(e){if(e.length===0)return;let s=this.pub.pipeline();for(let{key:r,value:t,ttlSeconds:i}of e)s.set(r,t,"EX",i);await s.exec();}async expire(e,s){await this.pub.expire(e,s);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}},g=class{constructor(e,s,r){this.pub=e;this.sub=s;this.blocking=r;}pub;sub;blocking;get hasBlockingClient(){return !!this.blocking}async publish(e,s){await this.pub.publish(e,s);}async subscribe(e,s){await this.sub.subscribe(e,s);}async unsubscribe(e){await this.sub.unsubscribe(e);}async set(e,s,r){r?await this.pub.set(e,s,{EX:r}):await this.pub.set(e,s);}async get(e){return await this.pub.get(e)||null}async mget(e){return e.length===0?[]:await this.pub.mGet(e)}async del(e){await this.pub.del(e);}async xadd(e,s,r){return await this.pub.xAdd(e,"*",s,{TRIM:r?{strategy:"MAXLEN",strategyModifier:"~",threshold:r}:void 0})}async xaddBatch(e,s){if(e.length===0)return;let r=this.pub.multi();for(let t of e)r.xAdd(t.stream,"*",t.args,{TRIM:s?{strategy:"MAXLEN",strategyModifier:"~",threshold:s}:void 0});await r.exec();}async xread(e,s,r){let t={};s&&(t.COUNT=s),typeof r=="number"&&(t.BLOCK=r);let i=e.map(o=>({key:o.key,id:o.id})),n=await(r&&this.blocking?this.blocking:this.pub).xRead(i,t);return !n||n.length===0?null:n.map(o=>({stream:o.name,messages:o.messages.map(u=>({id:u.id,data:u.message}))}))}async xlen(e){return await this.pub.xLen(e)}async disconnect(){await Promise.all([this.pub.disconnect(),this.sub.disconnect()]);}async setPresenceBatch(e){if(e.length===0)return;let s=this.pub.multi();for(let{key:r,value:t,ttlSeconds:i}of e)s.set(r,t,{EX:i});await s.exec();}async expire(e,s){await this.pub.expire(e,s);}onError(e){return this.pub.on("error",e),()=>this.pub.removeListener("error",e)}onReconnect(e){return this.pub.on("connect",e),()=>this.pub.removeListener("connect",e)}};function p(c,e,s){return e.isOpen!==void 0&&typeof e.subscribe=="function"?new g(c,e,s):new l(c,e,s)}var b=class{_driver;_prefix;_streamMaxLen;_streamTtlSeconds;_presenceTtlSeconds;_handlers=new Map;_streamOffsets=new Map;_streams=new Set;_polling=false;_closed=false;_unsubError;_unsubReconnect;_presenceCache=new Map;_driverPool;_nextPoolIndex;constructor(e){if(this._prefix=e.prefix??"ocpp-ws-io:",this._streamMaxLen=e.streamMaxLen??1e3,this._streamTtlSeconds=e.streamTtlSeconds??300,this._presenceTtlSeconds=e.presenceTtlSeconds??300,e.driver)this._driver=e.driver;else if(e.pubClient&&e.subClient)this._driver=p(e.pubClient,e.subClient,e.blockingClient);else throw new Error("RedisAdapter requires either `driver` or both `pubClient` and `subClient`");let s=e.poolSize??1;if(this._driverPool=[this._driver],this._nextPoolIndex=0,s>1&&e.driverFactory)for(let r=1;r<s;r++)this._driverPool.push(e.driverFactory());this._driver.onError&&(this._unsubError=this._driver.onError(r=>{console.error("[RedisAdapter] Redis error:",r.message);})),this._driver.onReconnect&&(this._unsubReconnect=this._driver.onReconnect(()=>{this._rehydratePresence().catch(()=>{});}));}_getPoolDriver(){if(this._driverPool.length===1)return this._driver;let e=this._driverPool[this._nextPoolIndex];return this._nextPoolIndex=(this._nextPoolIndex+1)%this._driverPool.length,e}async publish(e,s){let r=this._prefix+e,t=JSON.stringify(s);if(e.startsWith("ocpp:node:")){let i=this._getPoolDriver();await i.xadd(r,{message:t},this._streamMaxLen),await i.expire(r,this._streamTtlSeconds).catch(()=>{});}else await this._getPoolDriver().publish(r,t);}async publishBatch(e){let s=[],r=[];for(let i of e){let a=this._prefix+i.channel,n=JSON.stringify(i.data);i.channel.startsWith("ocpp:node:")?s.push({stream:a,args:{message:n}}):r.push({channel:a,message:n});}let t=[];s.length>0&&t.push(this._getPoolDriver().xaddBatch(s,this._streamMaxLen)),r.length>0&&t.push(Promise.all(r.map(i=>this._getPoolDriver().publish(i.channel,i.message))).then(()=>{})),await Promise.all(t);}async subscribe(e,s){if(!this._handlers.has(e)){this._handlers.set(e,new Set);let r=this._prefix+e;e.startsWith("ocpp:node:")?this._streams.has(r)||(this._streams.add(r),this._streamOffsets.has(r)||this._streamOffsets.set(r,"0"),this._ensurePolling()):await this._driver.subscribe(r,t=>{this._handleMessage(e,t);});}this._handlers.get(e)?.add(s);}async unsubscribe(e){let s=this._prefix+e;this._streams.has(s)?this._streams.delete(s):await this._driver.unsubscribe(s),this._handlers.delete(e);}async disconnect(){this._closed=true,this._handlers.clear(),this._streams.clear(),this._presenceCache.clear(),this._unsubError&&this._unsubError(),this._unsubReconnect&&this._unsubReconnect(),await Promise.allSettled(this._driverPool.map(e=>e.disconnect()));}_handleMessage(e,s){let r=this._handlers.get(e);if(!r)return;let t;try{t=JSON.parse(s);}catch{t=s;}for(let i of r)try{i(t);}catch{}}_ensurePolling(){this._polling||this._closed||(this._polling=true,this._pollLoop().catch(()=>{this._polling=false;}));}async _pollLoop(){for(;!this._closed;){if(this._streams.size===0){await new Promise(r=>setTimeout(r,1e3));continue}let e=Array.from(this._streams).map(r=>({key:r,id:this._streamOffsets.get(r)||"$"})),s=this._driver.hasBlockingClient===true;try{let r=await this._driver.xread(e,void 0,s?1e3:void 0);if(r)for(let t of r){let i=t.stream.replace(this._prefix,"");for(let a of t.messages){this._streamOffsets.set(t.stream,a.id);let n=a.data.message;n&&this._handleMessage(i,n);}}else s||await new Promise(t=>setTimeout(t,1e3));}catch{await new Promise(t=>setTimeout(t,1e3));}}this._polling=false;}async setPresence(e,s,r){let t=`${this._prefix}presence:${e}`;this._presenceCache.set(e,{nodeId:s,ttl:r}),await this._driver.set(t,s,r);}async getPresence(e){let s=`${this._prefix}presence:${e}`;return await this._driver.get(s)}async getPresenceBatch(e){if(e.length===0)return [];let s=e.map(r=>`${this._prefix}presence:${r}`);return this._driver.mget?await this._driver.mget(s):await Promise.all(s.map(r=>this._driver.get(r)))}async removePresence(e){let s=`${this._prefix}presence:${e}`;this._presenceCache.delete(e),await this._driver.del(s);}async metrics(){let e=0,s={};for(let r of this._streams)try{let t=await this._driver.xlen(r);e+=t,s[r]=t;}catch{s[r]=-1;}return {pendingMessages:e,activeStreams:this._streams.size,streamDetails:s}}async setPresenceBatch(e){if(e.length===0)return;let s=e.map(({identity:r,nodeId:t,ttl:i})=>{let a=`${this._prefix}presence:${r}`,n=i??this._presenceTtlSeconds;return this._presenceCache.set(r,{nodeId:t,ttl:n}),{key:a,value:t,ttlSeconds:n}});await this._driver.setPresenceBatch(s);}async _rehydratePresence(){if(this._presenceCache.size===0)return;let e=Array.from(this._presenceCache.entries()).map(([s,{nodeId:r,ttl:t}])=>({key:`${this._prefix}presence:${s}`,value:r,ttlSeconds:t}));await this._driver.setPresenceBatch(e);}};export{b as RedisAdapter};
|
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var client=require('voltlog-io/client');function G(s){return s}function Y(s,e,t={}){let r=typeof t=="object"?t:{},{exchangeLog:n=false,prettify:i=false}=r;return async(o,a)=>{let l=Date.now(),d=o.method,p=n?"info":"debug";switch(o.type){case "incoming_call":n&&i?s[p]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"}):s[p]?.("CALL \u2190",{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"});break;case "outgoing_call":n&&i?s[p]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:o.method,params:o.params,direction:"OUT"}):s[p]?.("CALL \u2192",{method:o.method,params:o.params,direction:"OUT"});break}try{let c=await a(),u=Date.now()-l;switch(o.type){case "incoming_call":c!=null&&(n&&i?s[p]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}):s[p]?.("CALLRESULT \u2192",{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}));break;case "outgoing_call":n&&i?s[p]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"}):s[p]?.("CALLRESULT \u2190",{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"});break}return c}catch(c){let u=c.message,g=Date.now()-l;throw o.type==="incoming_call"?n&&i?s.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):o.type==="outgoing_call"&&(n&&i?s.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"})),c}}}var N=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let r=-1,n=async i=>{if(i<=r)throw new Error("next() called multiple times");r=i;let o=this._stack[i];if(i===this._stack.length)return t(e);if(o)return o(e,()=>n(i+1))};return n(0)}};var H=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);return r?r.push(t):this._listeners.set(e,[t]),this}once(e,t){let r=(...n)=>{this.off(e,r),t(...n);};return r.__wrapped=t,this.on(e,r)}off(e,t){let r=this._listeners.get(e);if(!r)return this;let n=r.findIndex(i=>i===t||i.__wrapped===t);return n!==-1&&r.splice(n,1),r.length===0&&this._listeners.delete(e),this}emit(e,...t){let r=this._listeners.get(e);if(!r||r.length===0)return false;for(let n of [...r])n(...t);return true}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}listenerCount(e){return this._listeners.get(e)?.length??0}};var w=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},m=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},E=class extends m{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},_=class extends m{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},x=class extends m{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";}},O=class extends m{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},R=class extends m{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";}},M=class extends m{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";}},b=class extends m{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";}},T=class extends m{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";}},k=class extends m{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";}},L=class extends m{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";}},f=class extends m{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";}},S=class extends m{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function X(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function ee(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,r=s.prettifySource??false,n=s.prettifyMetadata??false,i="\x1B[2;37m",o="\x1B[0m",a="\x1B[36m";return (l,d)=>{if(!t)l.context=void 0;else if(r&&l.context){let c=[];l.context.component&&c.push(String(l.context.component)),l.context.identity&&c.push(String(l.context.identity)),c.length>0&&(l.message=`${i}[${c.join("/")}]${o} ${l.message}`,l.context=void 0);}let p=l.meta;if(!e)l.meta={};else if(n&&p&&Object.keys(p).length>0){let c=Object.entries(p).filter(([,u])=>u!=null).map(([u,g])=>{let y=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?y=`${i}${y}${o}`:y=`${i}${y}${o}`,`${a}${u}${o}=${y}`}).join(" ");c&&(l.message=`${l.message} ${c}`),l.meta={};}d(l);}}function W(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",n=s?.prettify??false?[client.prettyTransport({level:t})]:[client.consoleTransport({level:t})];if(s?.handler){let a=s.handler;n.push({name:"customHandler",write:l=>a(l)});}let i=[];s&&X(s)&&i.push(ee(s));let o=client.createLogger({level:t,transports:n,middleware:i.length>0?i:void 0});return e&&Object.keys(e).length>0?o.child(e):o}var j=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,r)=>{this._queue.push({fn:e,resolve:t,reject:r}),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 B={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var h={CALL:2,CALLRESULT:3,CALLERROR:4},V=Symbol("NOREPLY");var D={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>D};function v(s,e,t={}){switch(s){case "GenericError":return new m(e,t);case "RpcFrameworkError":return new S(e,t);case "MessageTypeNotSupported":return new f(e,t);case "NotImplemented":return new E(e,t);case "NotSupported":return new _(e,t);case "InternalError":return new x(e,t);case "ProtocolError":return new O(e,t);case "SecurityError":return new R(e,t);case "FormatViolation":return new b(e,t);case "FormationViolation":return new M(e,t);case "PropertyConstraintViolation":return new T(e,t);case "OccurrenceConstraintViolation":return new k(e,t);case "TypeConstraintViolation":return new L(e,t);default:return new m(e,t)}}var te=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function $(s){let e={};for(let t of te){let r=s[t];if(r!==void 0){if(typeof r=="function"||typeof r=="symbol")continue;if(typeof r=="object"&&r!==null)try{JSON.stringify(r),e[t]=r;}catch{}else e[t]=r;}}return e.name||(e.name=s.name),e.message||(e.message=s.message),e}var {CONNECTING:A,OPEN:I,CLOSING:U,CLOSED:C}=B,q=class s extends H{static CONNECTING=A;static OPEN=I;static CLOSING=U;static CLOSED=C;_options;_state=C;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_outboundBuffer=[];_logger;_middleware;constructor(e){if(super(),!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,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,...e},this._callQueue=new j(this._options.callConcurrency),this._middleware=new N;let t=W(this._options.logging,{component:"BrowserOCPPClient",identity:this._identity});this._logger=t||D;}get log(){return this._logger}get identity(){return this._identity}get protocol(){return this._protocol}get state(){return this._state}async connect(){if(this._state!==C)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=A,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let r=this._buildEndpoint();this._logger.debug?.("Connecting",{url:r}),this.emit("connecting",{url:r});let n;try{n=this._options.protocols?.length?new WebSocket(r,this._options.protocols):new WebSocket(r);}catch(d){this._state=C,t(d);return}this._ws=n;let i=d=>{if(l(),this._state=I,this._protocol=n.protocol||void 0,this._badMessageCount=0,n.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[n.protocol]),this._reconnectAttempt=0,this._attachWebsocket(n),this._outboundBuffer.length>0){let p=this._outboundBuffer;this._outboundBuffer=[];for(let c of p)this._ws?.send(c);}this._logger.info?.("Connected",{protocol:n.protocol||void 0}),this.emit("open",d),e();},o=d=>{l(),this._state=C,this._logger.error?.("Connection error"),this.emit("error",d),t(d);},a=()=>{l(),this._state===A&&(this._state=C,t(new Error("WebSocket closed during connection")));},l=()=>{n.removeEventListener("open",i),n.removeEventListener("error",o),n.removeEventListener("close",a);};n.addEventListener("open",i),n.addEventListener("error",o),n.addEventListener("close",a);})}async close(e={}){let{code:t=1e3,reason:r="",awaitPending:n=true,force:i=false}=e;return this._closePromise?this._closePromise:this._state===C?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,r,n,i),this._closePromise)}async _closeInternal(e,t,r,n){if(this._state=U,!n&&r){let i=Array.from(this._pendingCalls.values()).map(o=>new Promise(a=>{let l=o.resolve,d=o.reject;o.resolve=p=>{l(p),a();},o.reject=p=>{d(p),a();};}));i.length>0&&await Promise.allSettled(i);}return new Promise(i=>{if(!this._ws||this._ws.readyState===WebSocket.CLOSED){this._state=C,this._cleanup();let a={code:e,reason:t};this.emit("close",a),i(a);return}let o=a=>{this._ws?.removeEventListener("close",o),this._state=C,this._cleanup();let l={code:a.code,reason:a.reason};this.emit("close",l),i(l);};if(this._ws.addEventListener("close",o),n)this._ws.close();else {let a=e>=1e3&&e<=4999&&![1004,1005,1006].includes(e);this._ws.close(a?e:1e3,t);}})}handle(...e){if(e.length===1&&typeof e[0]=="function")this._wildcardHandler=e[0];else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function")this._handlers.set(e[0],e[1]);else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function")this._handlers.set(`${e[0]}:${e[1]}`,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,r,n;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],r=e[2]??{},n=e[3]??{}):(t=e[0],r=e[1]??{},n=e[2]??{}),this._state!==I)throw new Error(`Cannot call: client is in state ${this._state}`);return this._callQueue.push(()=>this._sendCall(t,r,n))}async _sendCall(e,t,r){let n=this._generateMessageId(),i=r.timeoutMs??this._options.callTimeoutMs,o={type:"outgoing_call",messageId:n,method:e,params:t,options:r},a;return await this._middleware.execute(o,async l=>{let d=l,p=[h.CALL,n,d.method,d.params],c=JSON.stringify(p);a=await new Promise((u,g)=>{let y=setTimeout(()=>{this._pendingCalls.delete(n),this._logger.warn?.("Call timed out",{messageId:n,method:d.method,timeoutMs:i}),g(new w(`Call to "${d.method}" timed out after ${i}ms`));},i),F={resolve:u,reject:g,timeoutHandle:y,method:d.method,sentAt:Date.now()};if(r.signal){if(r.signal.aborted){clearTimeout(y),g(r.signal.reason??new Error("Aborted"));return}let K=()=>{clearTimeout(y),this._pendingCalls.delete(n),g(r.signal?.reason??new Error("Aborted"));};r.signal.addEventListener("abort",K,{once:true}),F.abortHandler=K;}this._pendingCalls.set(n,F),this._ws?.send(c),this.emit("message",p),this.emit("call",p);});}),a}sendRaw(e){if(this._state===I&&this._ws)this._ws.send(e);else if(this._state===A)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);}_attachWebsocket(e){e.addEventListener("message",t=>this._onMessage(t.data)),e.addEventListener("close",t=>this._onClose(t.code,t.reason)),e.addEventListener("error",t=>this.emit("error",t));}_onMessage(e){let t=typeof e=="string"?e:String(e),r;try{if(r=JSON.parse(t),!Array.isArray(r))throw new Error("Message is not an array")}catch(i){this._onBadMessage(t,i);return}let n=r[0];switch(n){case h.CALL:this._handleIncomingCall(r);break;case h.CALLRESULT:this._handleCallResult(r);break;case h.CALLERROR:this._handleCallError(r);break;default:this._onBadMessage(JSON.stringify(r),new f(`Unknown message type: ${n}`));}}async _handleIncomingCall(e){let[,t,r,n]=e,i={type:"incoming_call",messageId:t,method:r,params:n,protocol:this._protocol};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALL,a.messageId,a.method,a.params];if(this.emit("call",l),this._state===I)try{if(this._pendingResponses.has(a.messageId))throw v("RpcFrameworkError",`Already processing call with ID: ${a.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${a.method}`):void 0)??this._handlers.get(a.method);if(!d&&!this._wildcardHandler)throw v("NotImplemented",`No handler for method: ${a.method}`);this._pendingResponses.add(a.messageId);let p=new AbortController,c={messageId:a.messageId,method:a.method,protocol:this._protocol,params:a.params,signal:p.signal},u;if(d?u=await d(c):this._wildcardHandler&&(u=await this._wildcardHandler(a.method,c)),this._pendingResponses.delete(a.messageId),u===V)return;let g=[h.CALLRESULT,a.messageId,u];this._ws?.send(JSON.stringify(g)),this.emit("callResult",g);}catch(d){this._pendingResponses.delete(a.messageId),this._logger.error?.("Handler error",{messageId:a.messageId,method:a.method,error:d.message});let p=d instanceof m||d.rpcErrorCode?d:v("InternalError",d.message),c=this._options.respondWithDetailedErrors?$(d):{},u=[h.CALLERROR,a.messageId,p.rpcErrorCode,p.rpcErrorMessage||d.message||"",c];this._ws?.send(JSON.stringify(u)),this.emit("callError",u);}});}async _handleCallResult(e){let[,t,r]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let n=this._pendingCalls.get(t),i={type:"incoming_result",messageId:t,method:n.method,payload:r};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALLRESULT,t,a.payload];this.emit("callResult",l),clearTimeout(n.timeoutHandle),this._pendingCalls.delete(t),n.resolve(a.payload);});}async _handleCallError(e){let[,t,r,n,i]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallError for unknown messageId",{messageId:t});return}let o=this._pendingCalls.get(t),a=v(r,n,i),l={type:"incoming_error",messageId:t,method:o.method,error:a};await this._middleware.execute(l,async d=>{let c=d.error,u=[h.CALLERROR,t,c.rpcErrorCode,c.message,c.rpcErrorDetails??{}];this.emit("callError",u),clearTimeout(o.timeoutHandle),this._pendingCalls.delete(t),o.reject(c);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let r=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(r?.[1]&&this._ws){let n=[h.CALLERROR,r[1],"FormatViolation",t.message||"Invalid message format",{}];this._ws.send(JSON.stringify(n)),this.emit("callError",n);}this._badMessageCount>=this._options.maxBadMessages&&this.close({code:1002,reason:"Too many bad messages"}).catch(()=>{});}_rejectPendingCalls(e){for(let[,t]of this._pendingCalls)clearTimeout(t.timeoutHandle),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._rejectPendingCalls(`Connection closed (${e}: ${t})`),this._state!==U?(this._logger?.info?.("Disconnected",{code:e,reason:t}),this.emit("disconnect",{code:e,reason:t}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=C,this.emit("close",{code:e,reason:t}))):this._state=C;}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=A;let e=this._options.backoffMin,t=this._options.backoffMax,r=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(r)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:r}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(n){let i=n instanceof Error?n.message:"";if(s._INTOLERABLE_ERRORS.has(i)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:i}),this._state=C,this.emit("close",{code:1001,reason:i});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=C,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},r);}_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}_cleanup(){this._closePromise=null,this._ws=null;}_generateMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}};exports.BrowserOCPPClient=q;exports.ConnectionState=B;exports.MessageType=h;exports.MiddlewareStack=N;exports.NOREPLY=V;exports.RPCFormatViolationError=b;exports.RPCFormationViolationError=M;exports.RPCFrameworkError=S;exports.RPCGenericError=m;exports.RPCInternalError=x;exports.RPCMessageTypeNotSupportedError=f;exports.RPCNotImplementedError=E;exports.RPCNotSupportedError=_;exports.RPCOccurrenceConstraintViolationError=k;exports.RPCPropertyConstraintViolationError=T;exports.RPCProtocolError=O;exports.RPCSecurityError=R;exports.RPCTypeConstraintViolationError=L;exports.TimeoutError=w;exports.createLoggingMiddleware=Y;exports.createRPCError=v;exports.defineRpcMiddleware=G;exports.getErrorPlainObject=$;
|
|
1
|
+
'use strict';var client=require('voltlog-io/client');function G(s){return s}function Y(s,e,t={}){let n=typeof t=="object"?t:{},{exchangeLog:r=false,prettify:i=false}=n;return async(o,a)=>{let l=Date.now(),d=o.method,p=r?"info":"debug";switch(o.type){case "incoming_call":r&&i?s[p]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"}):s[p]?.("CALL \u2190",{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"});break;case "outgoing_call":r&&i?s[p]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:o.method,params:o.params,direction:"OUT"}):s[p]?.("CALL \u2192",{method:o.method,params:o.params,direction:"OUT"});break}try{let c=await a(),u=Date.now()-l;switch(o.type){case "incoming_call":c!=null&&(r&&i?s[p]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}):s[p]?.("CALLRESULT \u2192",{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}));break;case "outgoing_call":r&&i?s[p]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"}):s[p]?.("CALLRESULT \u2190",{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"});break}return c}catch(c){let u=c.message,g=Date.now()-l;throw o.type==="incoming_call"?r&&i?s.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):o.type==="outgoing_call"&&(r&&i?s.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"})),c}}}var N=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let n=-1,r=async i=>{if(i<=n)throw new Error("next() called multiple times");n=i;let o=this._stack[i];if(i===this._stack.length)return t(e);if(o)return o(e,()=>r(i+1))};return r(0)}};var H=class{_listeners=new Map;on(e,t){let n=this._listeners.get(e);return n?n.push(t):this._listeners.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r);};return n.__wrapped=t,this.on(e,n)}off(e,t){let n=this._listeners.get(e);if(!n)return this;let r=n.findIndex(i=>i===t||i.__wrapped===t);return r!==-1&&n.splice(r,1),n.length===0&&this._listeners.delete(e),this}emit(e,...t){let n=this._listeners.get(e);if(!n||n.length===0)return false;for(let r of [...n])r(...t);return true}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}listenerCount(e){return this._listeners.get(e)?.length??0}};var w=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},m=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},E=class extends m{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},_=class extends m{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},x=class extends m{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";}},O=class extends m{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},R=class extends m{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";}},M=class extends m{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";}},b=class extends m{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";}},T=class extends m{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";}},k=class extends m{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";}},L=class extends m{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";}},f=class extends m{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";}},S=class extends m{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function X(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function ee(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,n=s.prettifySource??false,r=s.prettifyMetadata??false,i="\x1B[2;37m",o="\x1B[0m",a="\x1B[36m";return (l,d)=>{if(!t)l.context=void 0;else if(n&&l.context){let c=[];l.context.component&&c.push(String(l.context.component)),l.context.identity&&c.push(String(l.context.identity)),c.length>0&&(l.message=`${i}[${c.join("/")}]${o} ${l.message}`,l.context=void 0);}let p=l.meta;if(!e)l.meta={};else if(r&&p&&Object.keys(p).length>0){let c=Object.entries(p).filter(([,u])=>u!=null).map(([u,g])=>{let y=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?y=`${i}${y}${o}`:y=`${i}${y}${o}`,`${a}${u}${o}=${y}`}).join(" ");c&&(l.message=`${l.message} ${c}`),l.meta={};}d(l);}}function W(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",r=s?.prettify??false?[client.prettyTransport({level:t})]:[client.consoleTransport({level:t})];if(s?.handler){let a=s.handler;r.push({name:"customHandler",write:l=>a(l)});}let i=[];s&&X(s)&&i.push(ee(s));let o=client.createLogger({level:t,transports:r,middleware:i.length>0?i:void 0});return e&&Object.keys(e).length>0?o.child(e):o}var j=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 B={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var h={CALL:2,CALLRESULT:3,CALLERROR:4},V=Symbol("NOREPLY");var D={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>D};function v(s,e,t={}){switch(s){case "GenericError":return new m(e,t);case "RpcFrameworkError":return new S(e,t);case "MessageTypeNotSupported":return new f(e,t);case "NotImplemented":return new E(e,t);case "NotSupported":return new _(e,t);case "InternalError":return new x(e,t);case "ProtocolError":return new O(e,t);case "SecurityError":return new R(e,t);case "FormatViolation":return new b(e,t);case "FormationViolation":return new M(e,t);case "PropertyConstraintViolation":return new T(e,t);case "OccurrenceConstraintViolation":return new k(e,t);case "TypeConstraintViolation":return new L(e,t);default:return new m(e,t)}}var te=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function $(s,e=true){let t={};for(let n of te){if(n==="stack"&&!e)continue;let r=s[n];if(r!==void 0){if(typeof r=="function"||typeof r=="symbol")continue;if(typeof r=="object"&&r!==null)try{JSON.stringify(r),t[n]=r;}catch{}else t[n]=r;}}return t.name||(t.name=s.name),t.message||(t.message=s.message),t}var {CONNECTING:A,OPEN:I,CLOSING:U,CLOSED:C}=B,q=class s extends H{static CONNECTING=A;static OPEN=I;static CLOSING=U;static CLOSED=C;_options;_state=C;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_outboundBuffer=[];_logger;_middleware;constructor(e){if(super(),!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,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,...e},this._callQueue=new j(this._options.callConcurrency),this._middleware=new N;let t=W(this._options.logging,{component:"BrowserOCPPClient",identity:this._identity});this._logger=t||D;}get log(){return this._logger}get identity(){return this._identity}get protocol(){return this._protocol}get state(){return this._state}async connect(){if(this._state!==C)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=A,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let n=this._buildEndpoint();this._logger.debug?.("Connecting",{url:n}),this.emit("connecting",{url:n});let r;try{r=this._options.protocols?.length?new WebSocket(n,this._options.protocols):new WebSocket(n);}catch(d){this._state=C,t(d);return}this._ws=r;let i=d=>{if(l(),this._state=I,this._protocol=r.protocol||void 0,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._reconnectAttempt=0,this._attachWebsocket(r),this._outboundBuffer.length>0){let p=this._outboundBuffer;this._outboundBuffer=[];for(let c of p)this._ws?.send(c);}this._logger.info?.("Connected",{protocol:r.protocol||void 0}),this.emit("open",d),e();},o=d=>{l(),this._state=C,this._logger.error?.("Connection error"),this.emit("error",d),t(d);},a=()=>{l(),this._state===A&&(this._state=C,t(new Error("WebSocket closed during connection")));},l=()=>{r.removeEventListener("open",i),r.removeEventListener("error",o),r.removeEventListener("close",a);};r.addEventListener("open",i),r.addEventListener("error",o),r.addEventListener("close",a);})}async close(e={}){let{code:t=1e3,reason:n="",awaitPending:r=true,force:i=false}=e;return this._closePromise?this._closePromise:this._state===C?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,n,r,i),this._closePromise)}async _closeInternal(e,t,n,r){if(this._state=U,!r&&n){let i=Array.from(this._pendingCalls.values()).map(o=>new Promise(a=>{let l=o.resolve,d=o.reject;o.resolve=p=>{l(p),a();},o.reject=p=>{d(p),a();};}));i.length>0&&await Promise.allSettled(i);}return new Promise(i=>{if(!this._ws||this._ws.readyState===WebSocket.CLOSED){this._state=C,this._cleanup();let a={code:e,reason:t};this.emit("close",a),i(a);return}let o=a=>{this._ws?.removeEventListener("close",o),this._state=C,this._cleanup();let l={code:a.code,reason:a.reason};this.emit("close",l),i(l);};if(this._ws.addEventListener("close",o),r)this._ws.close();else {let a=e>=1e3&&e<=4999&&![1004,1005,1006].includes(e);this._ws.close(a?e:1e3,t);}})}handle(...e){if(e.length===1&&typeof e[0]=="function")this._wildcardHandler=e[0];else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function")this._handlers.set(e[0],e[1]);else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function")this._handlers.set(`${e[0]}:${e[1]}`,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,r;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],n=e[2]??{},r=e[3]??{}):(t=e[0],n=e[1]??{},r=e[2]??{}),this._state!==I)throw new Error(`Cannot call: client is in state ${this._state}`);return this._callQueue.push(()=>this._sendCall(t,n,r))}async _sendCall(e,t,n){let r=this._generateMessageId(),i=n.timeoutMs??this._options.callTimeoutMs,o={type:"outgoing_call",messageId:r,method:e,params:t,options:n},a;return await this._middleware.execute(o,async l=>{let d=l,p=[h.CALL,r,d.method,d.params],c=JSON.stringify(p);a=await new Promise((u,g)=>{let y=setTimeout(()=>{this._pendingCalls.get(r)?.removeAbortListener?.(),this._pendingCalls.delete(r),this._logger.warn?.("Call timed out",{messageId:r,method:d.method,timeoutMs:i}),g(new w(`Call to "${d.method}" timed out after ${i}ms`));},i),F={resolve:u,reject:g,timeoutHandle:y,method:d.method,sentAt:Date.now()};if(n.signal){if(n.signal.aborted){clearTimeout(y),g(n.signal.reason??new Error("Aborted"));return}let K=()=>{clearTimeout(y),this._pendingCalls.delete(r),g(n.signal?.reason??new Error("Aborted"));};n.signal.addEventListener("abort",K,{once:true}),F.removeAbortListener=()=>n.signal?.removeEventListener("abort",K);}this._pendingCalls.set(r,F),this._ws?.send(c),this.emit("message",p),this.emit("call",p);});}),a}sendRaw(e){if(this._state===I&&this._ws)this._ws.send(e);else if(this._state===A)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);}_attachWebsocket(e){e.addEventListener("message",t=>this._onMessage(t.data)),e.addEventListener("close",t=>this._onClose(t.code,t.reason)),e.addEventListener("error",t=>this.emit("error",t));}_onMessage(e){let t=typeof e=="string"?e:String(e),n;try{if(n=JSON.parse(t),!Array.isArray(n))throw new Error("Message is not an array")}catch(i){this._onBadMessage(t,i);return}let r=n[0];switch(r){case h.CALL:this._handleIncomingCall(n);break;case h.CALLRESULT:this._handleCallResult(n);break;case h.CALLERROR:this._handleCallError(n);break;default:this._onBadMessage(JSON.stringify(n),new f(`Unknown message type: ${r}`));}}async _handleIncomingCall(e){let[,t,n,r]=e,i={type:"incoming_call",messageId:t,method:n,params:r,protocol:this._protocol};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALL,a.messageId,a.method,a.params];if(this.emit("call",l),this._state===I)try{if(this._pendingResponses.has(a.messageId))throw v("RpcFrameworkError",`Already processing call with ID: ${a.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${a.method}`):void 0)??this._handlers.get(a.method);if(!d&&!this._wildcardHandler)throw v("NotImplemented",`No handler for method: ${a.method}`);this._pendingResponses.add(a.messageId);let p=new AbortController,c={messageId:a.messageId,method:a.method,protocol:this._protocol,params:a.params,signal:p.signal},u;if(d?u=await d(c):this._wildcardHandler&&(u=await this._wildcardHandler(a.method,c)),this._pendingResponses.delete(a.messageId),u===V)return;let g=[h.CALLRESULT,a.messageId,u];this._ws?.send(JSON.stringify(g)),this.emit("callResult",g);}catch(d){this._pendingResponses.delete(a.messageId),this._logger.error?.("Handler error",{messageId:a.messageId,method:a.method,error:d.message});let p=d instanceof m||d.rpcErrorCode?d:v("InternalError",d.message),c=this._options.respondWithDetailedErrors?$(d,false):{},u=[h.CALLERROR,a.messageId,p.rpcErrorCode,p.rpcErrorMessage||d.message||"",c];this._ws?.send(JSON.stringify(u)),this.emit("callError",u);}});}async _handleCallResult(e){let[,t,n]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let r=this._pendingCalls.get(t),i={type:"incoming_result",messageId:t,method:r.method,payload:n};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALLRESULT,t,a.payload];this.emit("callResult",l),clearTimeout(r.timeoutHandle),r.removeAbortListener?.(),this._pendingCalls.delete(t),r.resolve(a.payload);});}async _handleCallError(e){let[,t,n,r,i]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallError for unknown messageId",{messageId:t});return}let o=this._pendingCalls.get(t),a=v(n,r,i),l={type:"incoming_error",messageId:t,method:o.method,error:a};await this._middleware.execute(l,async d=>{let c=d.error,u=[h.CALLERROR,t,c.rpcErrorCode,c.message,c.rpcErrorDetails??{}];this.emit("callError",u),clearTimeout(o.timeoutHandle),o.removeAbortListener?.(),this._pendingCalls.delete(t),o.reject(c);});}_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 r=this._protocol==="ocpp1.6"?"FormationViolation":"FormatViolation",i=[h.CALLERROR,n[1],r,t.message||"Invalid message format",{}];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.removeAbortListener?.(),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._rejectPendingCalls(`Connection closed (${e}: ${t})`),this._state!==U?(this._logger?.info?.("Disconnected",{code:e,reason:t}),this.emit("disconnect",{code:e,reason:t}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=C,this.emit("close",{code:e,reason:t}))):this._state=C;}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=A;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(r){let i=r instanceof Error?r.message:"";if(s._INTOLERABLE_ERRORS.has(i)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:i}),this._state=C,this.emit("close",{code:1001,reason:i});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=C,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},n);}_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()}_cleanup(){this._closePromise=null,this._ws=null;}_generateMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}};exports.BrowserOCPPClient=q;exports.ConnectionState=B;exports.MessageType=h;exports.MiddlewareStack=N;exports.NOREPLY=V;exports.RPCFormatViolationError=b;exports.RPCFormationViolationError=M;exports.RPCFrameworkError=S;exports.RPCGenericError=m;exports.RPCInternalError=x;exports.RPCMessageTypeNotSupportedError=f;exports.RPCNotImplementedError=E;exports.RPCNotSupportedError=_;exports.RPCOccurrenceConstraintViolationError=k;exports.RPCPropertyConstraintViolationError=T;exports.RPCProtocolError=O;exports.RPCSecurityError=R;exports.RPCTypeConstraintViolationError=L;exports.TimeoutError=w;exports.createLoggingMiddleware=Y;exports.createRPCError=v;exports.defineRpcMiddleware=G;exports.getErrorPlainObject=$;
|
package/dist/browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {prettyTransport,consoleTransport,createLogger}from'voltlog-io/client';function W(s){return s}function G(s,e,t={}){let r=typeof t=="object"?t:{},{exchangeLog:n=false,prettify:i=false}=r;return async(o,a)=>{let l=Date.now(),d=o.method,p=n?"info":"debug";switch(o.type){case "incoming_call":n&&i?s[p]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"}):s[p]?.("CALL \u2190",{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"});break;case "outgoing_call":n&&i?s[p]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:o.method,params:o.params,direction:"OUT"}):s[p]?.("CALL \u2192",{method:o.method,params:o.params,direction:"OUT"});break}try{let c=await a(),u=Date.now()-l;switch(o.type){case "incoming_call":c!=null&&(n&&i?s[p]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}):s[p]?.("CALLRESULT \u2192",{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}));break;case "outgoing_call":n&&i?s[p]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"}):s[p]?.("CALLRESULT \u2190",{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"});break}return c}catch(c){let u=c.message,g=Date.now()-l;throw o.type==="incoming_call"?n&&i?s.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):o.type==="outgoing_call"&&(n&&i?s.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"})),c}}}var I=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let r=-1,n=async i=>{if(i<=r)throw new Error("next() called multiple times");r=i;let o=this._stack[i];if(i===this._stack.length)return t(e);if(o)return o(e,()=>n(i+1))};return n(0)}};var N=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);return r?r.push(t):this._listeners.set(e,[t]),this}once(e,t){let r=(...n)=>{this.off(e,r),t(...n);};return r.__wrapped=t,this.on(e,r)}off(e,t){let r=this._listeners.get(e);if(!r)return this;let n=r.findIndex(i=>i===t||i.__wrapped===t);return n!==-1&&r.splice(n,1),r.length===0&&this._listeners.delete(e),this}emit(e,...t){let r=this._listeners.get(e);if(!r||r.length===0)return false;for(let n of [...r])n(...t);return true}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}listenerCount(e){return this._listeners.get(e)?.length??0}};var v=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},m=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},w=class extends m{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},E=class extends m{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},_=class extends m{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";}},x=class extends m{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},O=class extends m{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";}},R=class extends m{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";}},M=class extends m{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";}},b=class extends m{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";}},T=class extends m{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";}},k=class extends m{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";}},y=class extends m{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";}},L=class extends m{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function Z(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function X(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,r=s.prettifySource??false,n=s.prettifyMetadata??false,i="\x1B[2;37m",o="\x1B[0m",a="\x1B[36m";return (l,d)=>{if(!t)l.context=void 0;else if(r&&l.context){let c=[];l.context.component&&c.push(String(l.context.component)),l.context.identity&&c.push(String(l.context.identity)),c.length>0&&(l.message=`${i}[${c.join("/")}]${o} ${l.message}`,l.context=void 0);}let p=l.meta;if(!e)l.meta={};else if(n&&p&&Object.keys(p).length>0){let c=Object.entries(p).filter(([,u])=>u!=null).map(([u,g])=>{let P=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?P=`${i}${P}${o}`:P=`${i}${P}${o}`,`${a}${u}${o}=${P}`}).join(" ");c&&(l.message=`${l.message} ${c}`),l.meta={};}d(l);}}function K(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",n=s?.prettify??false?[prettyTransport({level:t})]:[consoleTransport({level:t})];if(s?.handler){let a=s.handler;n.push({name:"customHandler",write:l=>a(l)});}let i=[];s&&Z(s)&&i.push(X(s));let o=createLogger({level:t,transports:n,middleware:i.length>0?i:void 0});return e&&Object.keys(e).length>0?o.child(e):o}var H=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,r)=>{this._queue.push({fn:e,resolve:t,reject:r}),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 j={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var h={CALL:2,CALLRESULT:3,CALLERROR:4},B=Symbol("NOREPLY");var V={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>V};function f(s,e,t={}){switch(s){case "GenericError":return new m(e,t);case "RpcFrameworkError":return new L(e,t);case "MessageTypeNotSupported":return new y(e,t);case "NotImplemented":return new w(e,t);case "NotSupported":return new E(e,t);case "InternalError":return new _(e,t);case "ProtocolError":return new x(e,t);case "SecurityError":return new O(e,t);case "FormatViolation":return new M(e,t);case "FormationViolation":return new R(e,t);case "PropertyConstraintViolation":return new b(e,t);case "OccurrenceConstraintViolation":return new T(e,t);case "TypeConstraintViolation":return new k(e,t);default:return new m(e,t)}}var ee=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function D(s){let e={};for(let t of ee){let r=s[t];if(r!==void 0){if(typeof r=="function"||typeof r=="symbol")continue;if(typeof r=="object"&&r!==null)try{JSON.stringify(r),e[t]=r;}catch{}else e[t]=r;}}return e.name||(e.name=s.name),e.message||(e.message=s.message),e}var {CONNECTING:S,OPEN:A,CLOSING:$,CLOSED:C}=j,U=class s extends N{static CONNECTING=S;static OPEN=A;static CLOSING=$;static CLOSED=C;_options;_state=C;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_outboundBuffer=[];_logger;_middleware;constructor(e){if(super(),!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,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,...e},this._callQueue=new H(this._options.callConcurrency),this._middleware=new I;let t=K(this._options.logging,{component:"BrowserOCPPClient",identity:this._identity});this._logger=t||V;}get log(){return this._logger}get identity(){return this._identity}get protocol(){return this._protocol}get state(){return this._state}async connect(){if(this._state!==C)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=S,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let r=this._buildEndpoint();this._logger.debug?.("Connecting",{url:r}),this.emit("connecting",{url:r});let n;try{n=this._options.protocols?.length?new WebSocket(r,this._options.protocols):new WebSocket(r);}catch(d){this._state=C,t(d);return}this._ws=n;let i=d=>{if(l(),this._state=A,this._protocol=n.protocol||void 0,this._badMessageCount=0,n.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[n.protocol]),this._reconnectAttempt=0,this._attachWebsocket(n),this._outboundBuffer.length>0){let p=this._outboundBuffer;this._outboundBuffer=[];for(let c of p)this._ws?.send(c);}this._logger.info?.("Connected",{protocol:n.protocol||void 0}),this.emit("open",d),e();},o=d=>{l(),this._state=C,this._logger.error?.("Connection error"),this.emit("error",d),t(d);},a=()=>{l(),this._state===S&&(this._state=C,t(new Error("WebSocket closed during connection")));},l=()=>{n.removeEventListener("open",i),n.removeEventListener("error",o),n.removeEventListener("close",a);};n.addEventListener("open",i),n.addEventListener("error",o),n.addEventListener("close",a);})}async close(e={}){let{code:t=1e3,reason:r="",awaitPending:n=true,force:i=false}=e;return this._closePromise?this._closePromise:this._state===C?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,r,n,i),this._closePromise)}async _closeInternal(e,t,r,n){if(this._state=$,!n&&r){let i=Array.from(this._pendingCalls.values()).map(o=>new Promise(a=>{let l=o.resolve,d=o.reject;o.resolve=p=>{l(p),a();},o.reject=p=>{d(p),a();};}));i.length>0&&await Promise.allSettled(i);}return new Promise(i=>{if(!this._ws||this._ws.readyState===WebSocket.CLOSED){this._state=C,this._cleanup();let a={code:e,reason:t};this.emit("close",a),i(a);return}let o=a=>{this._ws?.removeEventListener("close",o),this._state=C,this._cleanup();let l={code:a.code,reason:a.reason};this.emit("close",l),i(l);};if(this._ws.addEventListener("close",o),n)this._ws.close();else {let a=e>=1e3&&e<=4999&&![1004,1005,1006].includes(e);this._ws.close(a?e:1e3,t);}})}handle(...e){if(e.length===1&&typeof e[0]=="function")this._wildcardHandler=e[0];else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function")this._handlers.set(e[0],e[1]);else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function")this._handlers.set(`${e[0]}:${e[1]}`,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,r,n;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],r=e[2]??{},n=e[3]??{}):(t=e[0],r=e[1]??{},n=e[2]??{}),this._state!==A)throw new Error(`Cannot call: client is in state ${this._state}`);return this._callQueue.push(()=>this._sendCall(t,r,n))}async _sendCall(e,t,r){let n=this._generateMessageId(),i=r.timeoutMs??this._options.callTimeoutMs,o={type:"outgoing_call",messageId:n,method:e,params:t,options:r},a;return await this._middleware.execute(o,async l=>{let d=l,p=[h.CALL,n,d.method,d.params],c=JSON.stringify(p);a=await new Promise((u,g)=>{let P=setTimeout(()=>{this._pendingCalls.delete(n),this._logger.warn?.("Call timed out",{messageId:n,method:d.method,timeoutMs:i}),g(new v(`Call to "${d.method}" timed out after ${i}ms`));},i),q={resolve:u,reject:g,timeoutHandle:P,method:d.method,sentAt:Date.now()};if(r.signal){if(r.signal.aborted){clearTimeout(P),g(r.signal.reason??new Error("Aborted"));return}let F=()=>{clearTimeout(P),this._pendingCalls.delete(n),g(r.signal?.reason??new Error("Aborted"));};r.signal.addEventListener("abort",F,{once:true}),q.abortHandler=F;}this._pendingCalls.set(n,q),this._ws?.send(c),this.emit("message",p),this.emit("call",p);});}),a}sendRaw(e){if(this._state===A&&this._ws)this._ws.send(e);else if(this._state===S)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);}_attachWebsocket(e){e.addEventListener("message",t=>this._onMessage(t.data)),e.addEventListener("close",t=>this._onClose(t.code,t.reason)),e.addEventListener("error",t=>this.emit("error",t));}_onMessage(e){let t=typeof e=="string"?e:String(e),r;try{if(r=JSON.parse(t),!Array.isArray(r))throw new Error("Message is not an array")}catch(i){this._onBadMessage(t,i);return}let n=r[0];switch(n){case h.CALL:this._handleIncomingCall(r);break;case h.CALLRESULT:this._handleCallResult(r);break;case h.CALLERROR:this._handleCallError(r);break;default:this._onBadMessage(JSON.stringify(r),new y(`Unknown message type: ${n}`));}}async _handleIncomingCall(e){let[,t,r,n]=e,i={type:"incoming_call",messageId:t,method:r,params:n,protocol:this._protocol};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALL,a.messageId,a.method,a.params];if(this.emit("call",l),this._state===A)try{if(this._pendingResponses.has(a.messageId))throw f("RpcFrameworkError",`Already processing call with ID: ${a.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${a.method}`):void 0)??this._handlers.get(a.method);if(!d&&!this._wildcardHandler)throw f("NotImplemented",`No handler for method: ${a.method}`);this._pendingResponses.add(a.messageId);let p=new AbortController,c={messageId:a.messageId,method:a.method,protocol:this._protocol,params:a.params,signal:p.signal},u;if(d?u=await d(c):this._wildcardHandler&&(u=await this._wildcardHandler(a.method,c)),this._pendingResponses.delete(a.messageId),u===B)return;let g=[h.CALLRESULT,a.messageId,u];this._ws?.send(JSON.stringify(g)),this.emit("callResult",g);}catch(d){this._pendingResponses.delete(a.messageId),this._logger.error?.("Handler error",{messageId:a.messageId,method:a.method,error:d.message});let p=d instanceof m||d.rpcErrorCode?d:f("InternalError",d.message),c=this._options.respondWithDetailedErrors?D(d):{},u=[h.CALLERROR,a.messageId,p.rpcErrorCode,p.rpcErrorMessage||d.message||"",c];this._ws?.send(JSON.stringify(u)),this.emit("callError",u);}});}async _handleCallResult(e){let[,t,r]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let n=this._pendingCalls.get(t),i={type:"incoming_result",messageId:t,method:n.method,payload:r};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALLRESULT,t,a.payload];this.emit("callResult",l),clearTimeout(n.timeoutHandle),this._pendingCalls.delete(t),n.resolve(a.payload);});}async _handleCallError(e){let[,t,r,n,i]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallError for unknown messageId",{messageId:t});return}let o=this._pendingCalls.get(t),a=f(r,n,i),l={type:"incoming_error",messageId:t,method:o.method,error:a};await this._middleware.execute(l,async d=>{let c=d.error,u=[h.CALLERROR,t,c.rpcErrorCode,c.message,c.rpcErrorDetails??{}];this.emit("callError",u),clearTimeout(o.timeoutHandle),this._pendingCalls.delete(t),o.reject(c);});}_onBadMessage(e,t){this._badMessageCount++,this._logger?.warn?.("Bad message",{error:t.message,count:this._badMessageCount}),this.emit("badMessage",{message:e,error:t});let r=e.match(/^\s*\[\s*2\s*,\s*"([^"]+)"/);if(r?.[1]&&this._ws){let n=[h.CALLERROR,r[1],"FormatViolation",t.message||"Invalid message format",{}];this._ws.send(JSON.stringify(n)),this.emit("callError",n);}this._badMessageCount>=this._options.maxBadMessages&&this.close({code:1002,reason:"Too many bad messages"}).catch(()=>{});}_rejectPendingCalls(e){for(let[,t]of this._pendingCalls)clearTimeout(t.timeoutHandle),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._rejectPendingCalls(`Connection closed (${e}: ${t})`),this._state!==$?(this._logger?.info?.("Disconnected",{code:e,reason:t}),this.emit("disconnect",{code:e,reason:t}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=C,this.emit("close",{code:e,reason:t}))):this._state=C;}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=S;let e=this._options.backoffMin,t=this._options.backoffMax,r=Math.min(t,e*2**(this._reconnectAttempt-1)*(.5+Math.random()*.5));this._logger?.warn?.("Reconnecting",{attempt:this._reconnectAttempt,delayMs:Math.round(r)}),this.emit("reconnect",{attempt:this._reconnectAttempt,delay:r}),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null;try{await this._connectInternal();}catch(n){let i=n instanceof Error?n.message:"";if(s._INTOLERABLE_ERRORS.has(i)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:i}),this._state=C,this.emit("close",{code:1001,reason:i});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=C,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},r);}_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}_cleanup(){this._closePromise=null,this._ws=null;}_generateMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}};export{U as BrowserOCPPClient,j as ConnectionState,h as MessageType,I as MiddlewareStack,B as NOREPLY,M as RPCFormatViolationError,R as RPCFormationViolationError,L as RPCFrameworkError,m as RPCGenericError,_ as RPCInternalError,y as RPCMessageTypeNotSupportedError,w as RPCNotImplementedError,E as RPCNotSupportedError,T as RPCOccurrenceConstraintViolationError,b as RPCPropertyConstraintViolationError,x as RPCProtocolError,O as RPCSecurityError,k as RPCTypeConstraintViolationError,v as TimeoutError,G as createLoggingMiddleware,f as createRPCError,W as defineRpcMiddleware,D as getErrorPlainObject};
|
|
1
|
+
import {prettyTransport,consoleTransport,createLogger}from'voltlog-io/client';function W(s){return s}function G(s,e,t={}){let n=typeof t=="object"?t:{},{exchangeLog:r=false,prettify:i=false}=n;return async(o,a)=>{let l=Date.now(),d=o.method,p=r?"info":"debug";switch(o.type){case "incoming_call":r&&i?s[p]?.(`\u26A1 ${e} \u2190 ${d} [IN]`,{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"}):s[p]?.("CALL \u2190",{messageId:o.messageId,method:o.method,protocol:o.protocol,payload:o.params,direction:"IN"});break;case "outgoing_call":r&&i?s[p]?.(`\u26A1 ${e} \u2192 ${d} [OUT]`,{method:o.method,params:o.params,direction:"OUT"}):s[p]?.("CALL \u2192",{method:o.method,params:o.params,direction:"OUT"});break}try{let c=await a(),u=Date.now()-l;switch(o.type){case "incoming_call":c!=null&&(r&&i?s[p]?.(`\u2705 ${e} \u2192 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}):s[p]?.("CALLRESULT \u2192",{messageId:o.messageId,method:o.method,durationMs:u,params:c,direction:"OUT"}));break;case "outgoing_call":r&&i?s[p]?.(`\u2705 ${e} \u2190 ${d} [RES]`,{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"}):s[p]?.("CALLRESULT \u2190",{messageId:o.messageId,method:o.method,durationMs:u,payload:c,direction:"IN"});break}return c}catch(c){let u=c.message,g=Date.now()-l;throw o.type==="incoming_call"?r&&i?s.error?.(`\u{1F6A8} ${e} \u2192 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):s.error?.("CALLERROR \u2192",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"OUT"}):o.type==="outgoing_call"&&(r&&i?s.warn?.(`\u{1F6A8} ${e} \u2190 ${d} [ERR]`,{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"}):s.warn?.("CALLERROR \u2190",{messageId:o.messageId,method:o.method,durationMs:g,error:u,direction:"IN"})),c}}}var I=class{_stack=[];use(e){this._stack.push(e);}async execute(e,t){let n=-1,r=async i=>{if(i<=n)throw new Error("next() called multiple times");n=i;let o=this._stack[i];if(i===this._stack.length)return t(e);if(o)return o(e,()=>r(i+1))};return r(0)}};var N=class{_listeners=new Map;on(e,t){let n=this._listeners.get(e);return n?n.push(t):this._listeners.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r);};return n.__wrapped=t,this.on(e,n)}off(e,t){let n=this._listeners.get(e);if(!n)return this;let r=n.findIndex(i=>i===t||i.__wrapped===t);return r!==-1&&n.splice(r,1),n.length===0&&this._listeners.delete(e),this}emit(e,...t){let n=this._listeners.get(e);if(!n||n.length===0)return false;for(let r of [...n])r(...t);return true}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}removeAllListeners(e){return e?this._listeners.delete(e):this._listeners.clear(),this}listenerCount(e){return this._listeners.get(e)?.length??0}};var v=class extends Error{constructor(e="Operation timed out"){super(e),this.name="TimeoutError";}},m=class extends Error{rpcErrorCode="GenericError";rpcErrorMessage="";details;constructor(e,t={}){super(e),this.name="RPCGenericError",this.details=t;}},w=class extends m{rpcErrorCode="NotImplemented";rpcErrorMessage="Requested method is not known";constructor(e,t={}){super(e,t),this.name="RPCNotImplementedError";}},E=class extends m{rpcErrorCode="NotSupported";rpcErrorMessage="Requested method is recognised but not supported";constructor(e,t={}){super(e,t),this.name="RPCNotSupportedError";}},_=class extends m{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";}},x=class extends m{rpcErrorCode="ProtocolError";rpcErrorMessage="Payload for action is incomplete";constructor(e,t={}){super(e,t),this.name="RPCProtocolError";}},O=class extends m{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";}},R=class extends m{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";}},M=class extends m{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";}},b=class extends m{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";}},T=class extends m{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";}},k=class extends m{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";}},y=class extends m{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";}},L=class extends m{rpcErrorCode="RpcFrameworkError";rpcErrorMessage="Content of the call is not a valid RPC request";constructor(e,t={}){super(e,t),this.name="RPCFrameworkError";}};function Z(s){return s.showMetadata===false||s.showSourceMeta===false||s.prettifySource===true||s.prettifyMetadata===true}function X(s){let e=s.showMetadata??true,t=s.showSourceMeta??true,n=s.prettifySource??false,r=s.prettifyMetadata??false,i="\x1B[2;37m",o="\x1B[0m",a="\x1B[36m";return (l,d)=>{if(!t)l.context=void 0;else if(n&&l.context){let c=[];l.context.component&&c.push(String(l.context.component)),l.context.identity&&c.push(String(l.context.identity)),c.length>0&&(l.message=`${i}[${c.join("/")}]${o} ${l.message}`,l.context=void 0);}let p=l.meta;if(!e)l.meta={};else if(r&&p&&Object.keys(p).length>0){let c=Object.entries(p).filter(([,u])=>u!=null).map(([u,g])=>{let P=typeof g=="object"?JSON.stringify(g):String(g);return typeof g=="string"?P=`${i}${P}${o}`:P=`${i}${P}${o}`,`${a}${u}${o}=${P}`}).join(" ");c&&(l.message=`${l.message} ${c}`),l.meta={};}d(l);}}function K(s,e){if(s===false||s?.enabled===false)return null;if(s?.logger)return e&&s.logger.child?s.logger.child(e):s.logger;let t=s?.level??"INFO",r=s?.prettify??false?[prettyTransport({level:t})]:[consoleTransport({level:t})];if(s?.handler){let a=s.handler;r.push({name:"customHandler",write:l=>a(l)});}let i=[];s&&Z(s)&&i.push(X(s));let o=createLogger({level:t,transports:r,middleware:i.length>0?i:void 0});return e&&Object.keys(e).length>0?o.child(e):o}var H=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 j={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var h={CALL:2,CALLRESULT:3,CALLERROR:4},B=Symbol("NOREPLY");var V={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>V};function f(s,e,t={}){switch(s){case "GenericError":return new m(e,t);case "RpcFrameworkError":return new L(e,t);case "MessageTypeNotSupported":return new y(e,t);case "NotImplemented":return new w(e,t);case "NotSupported":return new E(e,t);case "InternalError":return new _(e,t);case "ProtocolError":return new x(e,t);case "SecurityError":return new O(e,t);case "FormatViolation":return new M(e,t);case "FormationViolation":return new R(e,t);case "PropertyConstraintViolation":return new b(e,t);case "OccurrenceConstraintViolation":return new T(e,t);case "TypeConstraintViolation":return new k(e,t);default:return new m(e,t)}}var ee=["name","message","stack","code","rpcErrorCode","rpcErrorMessage","details"];function D(s,e=true){let t={};for(let n of ee){if(n==="stack"&&!e)continue;let r=s[n];if(r!==void 0){if(typeof r=="function"||typeof r=="symbol")continue;if(typeof r=="object"&&r!==null)try{JSON.stringify(r),t[n]=r;}catch{}else t[n]=r;}}return t.name||(t.name=s.name),t.message||(t.message=s.message),t}var {CONNECTING:S,OPEN:A,CLOSING:$,CLOSED:C}=j,U=class s extends N{static CONNECTING=S;static OPEN=A;static CLOSING=$;static CLOSED=C;_options;_state=C;_ws=null;_protocol;_identity;_handlers=new Map;_wildcardHandler=null;_pendingCalls=new Map;_pendingResponses=new Set;_callQueue;_closePromise=null;_reconnectAttempt=0;_reconnectTimer=null;_badMessageCount=0;_outboundBuffer=[];_logger;_middleware;constructor(e){if(super(),!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,callConcurrency:1,maxBadMessages:1/0,respondWithDetailedErrors:false,...e},this._callQueue=new H(this._options.callConcurrency),this._middleware=new I;let t=K(this._options.logging,{component:"BrowserOCPPClient",identity:this._identity});this._logger=t||V;}get log(){return this._logger}get identity(){return this._identity}get protocol(){return this._protocol}get state(){return this._state}async connect(){if(this._state!==C)throw new Error(`Cannot connect: client is in state ${this._state}`);return this._state=S,this._reconnectAttempt=0,this._connectInternal()}async _connectInternal(){return new Promise((e,t)=>{let n=this._buildEndpoint();this._logger.debug?.("Connecting",{url:n}),this.emit("connecting",{url:n});let r;try{r=this._options.protocols?.length?new WebSocket(n,this._options.protocols):new WebSocket(n);}catch(d){this._state=C,t(d);return}this._ws=r;let i=d=>{if(l(),this._state=A,this._protocol=r.protocol||void 0,this._badMessageCount=0,r.protocol&&this._reconnectAttempt===0&&(this._options.protocols=[r.protocol]),this._reconnectAttempt=0,this._attachWebsocket(r),this._outboundBuffer.length>0){let p=this._outboundBuffer;this._outboundBuffer=[];for(let c of p)this._ws?.send(c);}this._logger.info?.("Connected",{protocol:r.protocol||void 0}),this.emit("open",d),e();},o=d=>{l(),this._state=C,this._logger.error?.("Connection error"),this.emit("error",d),t(d);},a=()=>{l(),this._state===S&&(this._state=C,t(new Error("WebSocket closed during connection")));},l=()=>{r.removeEventListener("open",i),r.removeEventListener("error",o),r.removeEventListener("close",a);};r.addEventListener("open",i),r.addEventListener("error",o),r.addEventListener("close",a);})}async close(e={}){let{code:t=1e3,reason:n="",awaitPending:r=true,force:i=false}=e;return this._closePromise?this._closePromise:this._state===C?{code:1e3,reason:""}:(this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closePromise=this._closeInternal(t,n,r,i),this._closePromise)}async _closeInternal(e,t,n,r){if(this._state=$,!r&&n){let i=Array.from(this._pendingCalls.values()).map(o=>new Promise(a=>{let l=o.resolve,d=o.reject;o.resolve=p=>{l(p),a();},o.reject=p=>{d(p),a();};}));i.length>0&&await Promise.allSettled(i);}return new Promise(i=>{if(!this._ws||this._ws.readyState===WebSocket.CLOSED){this._state=C,this._cleanup();let a={code:e,reason:t};this.emit("close",a),i(a);return}let o=a=>{this._ws?.removeEventListener("close",o),this._state=C,this._cleanup();let l={code:a.code,reason:a.reason};this.emit("close",l),i(l);};if(this._ws.addEventListener("close",o),r)this._ws.close();else {let a=e>=1e3&&e<=4999&&![1004,1005,1006].includes(e);this._ws.close(a?e:1e3,t);}})}handle(...e){if(e.length===1&&typeof e[0]=="function")this._wildcardHandler=e[0];else if(e.length===2&&typeof e[0]=="string"&&typeof e[1]=="function")this._handlers.set(e[0],e[1]);else if(e.length===3&&typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="function")this._handlers.set(`${e[0]}:${e[1]}`,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,r;if(e.length>=3&&typeof e[0]=="string"&&typeof e[1]=="string"?(t=e[1],n=e[2]??{},r=e[3]??{}):(t=e[0],n=e[1]??{},r=e[2]??{}),this._state!==A)throw new Error(`Cannot call: client is in state ${this._state}`);return this._callQueue.push(()=>this._sendCall(t,n,r))}async _sendCall(e,t,n){let r=this._generateMessageId(),i=n.timeoutMs??this._options.callTimeoutMs,o={type:"outgoing_call",messageId:r,method:e,params:t,options:n},a;return await this._middleware.execute(o,async l=>{let d=l,p=[h.CALL,r,d.method,d.params],c=JSON.stringify(p);a=await new Promise((u,g)=>{let P=setTimeout(()=>{this._pendingCalls.get(r)?.removeAbortListener?.(),this._pendingCalls.delete(r),this._logger.warn?.("Call timed out",{messageId:r,method:d.method,timeoutMs:i}),g(new v(`Call to "${d.method}" timed out after ${i}ms`));},i),q={resolve:u,reject:g,timeoutHandle:P,method:d.method,sentAt:Date.now()};if(n.signal){if(n.signal.aborted){clearTimeout(P),g(n.signal.reason??new Error("Aborted"));return}let F=()=>{clearTimeout(P),this._pendingCalls.delete(r),g(n.signal?.reason??new Error("Aborted"));};n.signal.addEventListener("abort",F,{once:true}),q.removeAbortListener=()=>n.signal?.removeEventListener("abort",F);}this._pendingCalls.set(r,q),this._ws?.send(c),this.emit("message",p),this.emit("call",p);});}),a}sendRaw(e){if(this._state===A&&this._ws)this._ws.send(e);else if(this._state===S)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);}_attachWebsocket(e){e.addEventListener("message",t=>this._onMessage(t.data)),e.addEventListener("close",t=>this._onClose(t.code,t.reason)),e.addEventListener("error",t=>this.emit("error",t));}_onMessage(e){let t=typeof e=="string"?e:String(e),n;try{if(n=JSON.parse(t),!Array.isArray(n))throw new Error("Message is not an array")}catch(i){this._onBadMessage(t,i);return}let r=n[0];switch(r){case h.CALL:this._handleIncomingCall(n);break;case h.CALLRESULT:this._handleCallResult(n);break;case h.CALLERROR:this._handleCallError(n);break;default:this._onBadMessage(JSON.stringify(n),new y(`Unknown message type: ${r}`));}}async _handleIncomingCall(e){let[,t,n,r]=e,i={type:"incoming_call",messageId:t,method:n,params:r,protocol:this._protocol};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALL,a.messageId,a.method,a.params];if(this.emit("call",l),this._state===A)try{if(this._pendingResponses.has(a.messageId))throw f("RpcFrameworkError",`Already processing call with ID: ${a.messageId}`);let d=(this._protocol?this._handlers.get(`${this._protocol}:${a.method}`):void 0)??this._handlers.get(a.method);if(!d&&!this._wildcardHandler)throw f("NotImplemented",`No handler for method: ${a.method}`);this._pendingResponses.add(a.messageId);let p=new AbortController,c={messageId:a.messageId,method:a.method,protocol:this._protocol,params:a.params,signal:p.signal},u;if(d?u=await d(c):this._wildcardHandler&&(u=await this._wildcardHandler(a.method,c)),this._pendingResponses.delete(a.messageId),u===B)return;let g=[h.CALLRESULT,a.messageId,u];this._ws?.send(JSON.stringify(g)),this.emit("callResult",g);}catch(d){this._pendingResponses.delete(a.messageId),this._logger.error?.("Handler error",{messageId:a.messageId,method:a.method,error:d.message});let p=d instanceof m||d.rpcErrorCode?d:f("InternalError",d.message),c=this._options.respondWithDetailedErrors?D(d,false):{},u=[h.CALLERROR,a.messageId,p.rpcErrorCode,p.rpcErrorMessage||d.message||"",c];this._ws?.send(JSON.stringify(u)),this.emit("callError",u);}});}async _handleCallResult(e){let[,t,n]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallResult for unknown messageId",{messageId:t});return}let r=this._pendingCalls.get(t),i={type:"incoming_result",messageId:t,method:r.method,payload:n};await this._middleware.execute(i,async o=>{let a=o,l=[h.CALLRESULT,t,a.payload];this.emit("callResult",l),clearTimeout(r.timeoutHandle),r.removeAbortListener?.(),this._pendingCalls.delete(t),r.resolve(a.payload);});}async _handleCallError(e){let[,t,n,r,i]=e;if(!this._pendingCalls.has(t)){this._logger.warn?.("Received CallError for unknown messageId",{messageId:t});return}let o=this._pendingCalls.get(t),a=f(n,r,i),l={type:"incoming_error",messageId:t,method:o.method,error:a};await this._middleware.execute(l,async d=>{let c=d.error,u=[h.CALLERROR,t,c.rpcErrorCode,c.message,c.rpcErrorDetails??{}];this.emit("callError",u),clearTimeout(o.timeoutHandle),o.removeAbortListener?.(),this._pendingCalls.delete(t),o.reject(c);});}_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 r=this._protocol==="ocpp1.6"?"FormationViolation":"FormatViolation",i=[h.CALLERROR,n[1],r,t.message||"Invalid message format",{}];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.removeAbortListener?.(),t.reject(new Error(e));this._pendingCalls.clear(),this._pendingResponses.clear();}_onClose(e,t){this._rejectPendingCalls(`Connection closed (${e}: ${t})`),this._state!==$?(this._logger?.info?.("Disconnected",{code:e,reason:t}),this.emit("disconnect",{code:e,reason:t}),this._options.reconnect&&this._reconnectAttempt<this._options.maxReconnects?this._scheduleReconnect():(this._state=C,this.emit("close",{code:e,reason:t}))):this._state=C;}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=S;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(r){let i=r instanceof Error?r.message:"";if(s._INTOLERABLE_ERRORS.has(i)){this._logger?.error?.("Intolerable error \u2014 stopping reconnection",{error:i}),this._state=C,this.emit("close",{code:1001,reason:i});return}this._reconnectAttempt<this._options.maxReconnects&&this._options.reconnect?this._scheduleReconnect():(this._state=C,this.emit("close",{code:1001,reason:"Max reconnection attempts exhausted"}));}},n);}_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()}_cleanup(){this._closePromise=null,this._ws=null;}_generateMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return (e==="x"?t:t&3|8).toString(16)})}};export{U as BrowserOCPPClient,j as ConnectionState,h as MessageType,I as MiddlewareStack,B as NOREPLY,M as RPCFormatViolationError,R as RPCFormationViolationError,L as RPCFrameworkError,m as RPCGenericError,_ as RPCInternalError,y as RPCMessageTypeNotSupportedError,w as RPCNotImplementedError,E as RPCNotSupportedError,T as RPCOccurrenceConstraintViolationError,b as RPCPropertyConstraintViolationError,x as RPCProtocolError,O as RPCSecurityError,k as RPCTypeConstraintViolationError,v as TimeoutError,G as createLoggingMiddleware,f as createRPCError,W as defineRpcMiddleware,D as getErrorPlainObject};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-
|
|
1
|
+
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-tTYOr5Gm.js';
|
|
2
2
|
|
|
3
3
|
declare abstract class BaseOcppContext {
|
|
4
4
|
readonly server: OCPPServer;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-
|
|
1
|
+
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-tTYOr5Gm.mjs';
|
|
2
2
|
|
|
3
3
|
declare abstract class BaseOcppContext {
|
|
4
4
|
readonly server: OCPPServer;
|
package/dist/express.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { IncomingMessage, Server } from 'node:http';
|
|
2
|
-
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-
|
|
2
|
+
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-tTYOr5Gm.mjs';
|
|
3
3
|
import 'ws';
|
|
4
4
|
import 'node:https';
|
|
5
5
|
import 'node:events';
|
package/dist/express.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { IncomingMessage, Server } from 'node:http';
|
|
2
|
-
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-
|
|
2
|
+
import { O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, c as OCPPProtocol, A as AllMethodNames, d as OCPPRequestType, C as CallOptions, e as OCPPResponseType, f as CloseOptions } from './types-tTYOr5Gm.js';
|
|
3
3
|
import 'ws';
|
|
4
4
|
import 'node:https';
|
|
5
5
|
import 'node:events';
|
package/dist/fastify.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { FastifyPluginAsync } from 'fastify';
|
|
2
|
-
import { O as OCPPServer } from './types-
|
|
2
|
+
import { O as OCPPServer } from './types-tTYOr5Gm.mjs';
|
|
3
3
|
import { IncomingMessage } from 'node:http';
|
|
4
|
-
import { B as BaseOcppContext } from './context-
|
|
4
|
+
import { B as BaseOcppContext } from './context-BNELI5Ux.mjs';
|
|
5
5
|
import 'ws';
|
|
6
6
|
import 'node:https';
|
|
7
7
|
import 'node:events';
|
package/dist/fastify.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { FastifyPluginAsync } from 'fastify';
|
|
2
|
-
import { O as OCPPServer } from './types-
|
|
2
|
+
import { O as OCPPServer } from './types-tTYOr5Gm.js';
|
|
3
3
|
import { IncomingMessage } from 'node:http';
|
|
4
|
-
import { B as BaseOcppContext } from './context-
|
|
4
|
+
import { B as BaseOcppContext } from './context-B4-L-O1-.js';
|
|
5
5
|
import 'ws';
|
|
6
6
|
import 'node:https';
|
|
7
7
|
import 'node:events';
|
package/dist/hono.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IncomingMessage, Server } from 'node:http';
|
|
2
2
|
import { MiddlewareHandler } from 'hono';
|
|
3
|
-
import { O as OCPPServer } from './types-
|
|
4
|
-
import { B as BaseOcppContext } from './context-
|
|
3
|
+
import { O as OCPPServer } from './types-tTYOr5Gm.mjs';
|
|
4
|
+
import { B as BaseOcppContext } from './context-BNELI5Ux.mjs';
|
|
5
5
|
import 'ws';
|
|
6
6
|
import 'node:https';
|
|
7
7
|
import 'node:events';
|
package/dist/hono.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IncomingMessage, Server } from 'node:http';
|
|
2
2
|
import { MiddlewareHandler } from 'hono';
|
|
3
|
-
import { O as OCPPServer } from './types-
|
|
4
|
-
import { B as BaseOcppContext } from './context-
|
|
3
|
+
import { O as OCPPServer } from './types-tTYOr5Gm.js';
|
|
4
|
+
import { B as BaseOcppContext } from './context-B4-L-O1-.js';
|
|
5
5
|
import 'ws';
|
|
6
6
|
import 'node:https';
|
|
7
7
|
import 'node:events';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as EventAdapterInterface } from './types-
|
|
1
|
+
import { E as EventAdapterInterface } from './types-tTYOr5Gm.js';
|
|
2
2
|
|
|
3
3
|
interface RedisLikeClient {
|
|
4
4
|
publish(channel: string, message: string): Promise<number | unknown | undefined>;
|
|
@@ -59,15 +59,26 @@ interface RedisPubSubDriver {
|
|
|
59
59
|
id: string;
|
|
60
60
|
}[], count?: number, block?: number): Promise<StreamEntry[] | null>;
|
|
61
61
|
xlen(stream: string): Promise<number>;
|
|
62
|
+
/**
|
|
63
|
+
* True when the driver has a dedicated connection for blocking XREAD.
|
|
64
|
+
* Without it, BLOCK would head-of-line-block every other command on the
|
|
65
|
+
* shared connection, so the adapter falls back to non-blocking polls.
|
|
66
|
+
*/
|
|
67
|
+
readonly hasBlockingClient?: boolean;
|
|
62
68
|
}
|
|
63
69
|
|
|
64
70
|
interface RedisAdapterOptions {
|
|
65
|
-
/** Redis client for publishing */
|
|
66
|
-
pubClient
|
|
67
|
-
/** Redis client for subscribing
|
|
68
|
-
subClient
|
|
71
|
+
/** Redis client for publishing (required unless `driver` is provided) */
|
|
72
|
+
pubClient?: RedisLikeClient;
|
|
73
|
+
/** Redis client for subscribing — must be a separate connection (required unless `driver` is provided) */
|
|
74
|
+
subClient?: RedisLikeClient;
|
|
69
75
|
/** Redis client for blocking stream operations (recommended for reliability) */
|
|
70
76
|
blockingClient?: RedisLikeClient;
|
|
77
|
+
/**
|
|
78
|
+
* Pre-built driver (e.g. a ClusterDriver) used directly as the primary
|
|
79
|
+
* driver. When set, pubClient/subClient/blockingClient are ignored.
|
|
80
|
+
*/
|
|
81
|
+
driver?: RedisPubSubDriver;
|
|
71
82
|
/** Optional key prefix for channels (default: 'ocpp-ws-io:') */
|
|
72
83
|
prefix?: string;
|
|
73
84
|
/** StreamMaxLen for trimming (default: 1000) */
|
|
@@ -117,7 +128,6 @@ declare class RedisAdapter implements EventAdapterInterface {
|
|
|
117
128
|
private _streams;
|
|
118
129
|
private _polling;
|
|
119
130
|
private _closed;
|
|
120
|
-
private _sequenceCounters;
|
|
121
131
|
private _unsubError?;
|
|
122
132
|
private _unsubReconnect?;
|
|
123
133
|
private _presenceCache;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as EventAdapterInterface } from './types-
|
|
1
|
+
import { E as EventAdapterInterface } from './types-tTYOr5Gm.mjs';
|
|
2
2
|
|
|
3
3
|
interface RedisLikeClient {
|
|
4
4
|
publish(channel: string, message: string): Promise<number | unknown | undefined>;
|
|
@@ -59,15 +59,26 @@ interface RedisPubSubDriver {
|
|
|
59
59
|
id: string;
|
|
60
60
|
}[], count?: number, block?: number): Promise<StreamEntry[] | null>;
|
|
61
61
|
xlen(stream: string): Promise<number>;
|
|
62
|
+
/**
|
|
63
|
+
* True when the driver has a dedicated connection for blocking XREAD.
|
|
64
|
+
* Without it, BLOCK would head-of-line-block every other command on the
|
|
65
|
+
* shared connection, so the adapter falls back to non-blocking polls.
|
|
66
|
+
*/
|
|
67
|
+
readonly hasBlockingClient?: boolean;
|
|
62
68
|
}
|
|
63
69
|
|
|
64
70
|
interface RedisAdapterOptions {
|
|
65
|
-
/** Redis client for publishing */
|
|
66
|
-
pubClient
|
|
67
|
-
/** Redis client for subscribing
|
|
68
|
-
subClient
|
|
71
|
+
/** Redis client for publishing (required unless `driver` is provided) */
|
|
72
|
+
pubClient?: RedisLikeClient;
|
|
73
|
+
/** Redis client for subscribing — must be a separate connection (required unless `driver` is provided) */
|
|
74
|
+
subClient?: RedisLikeClient;
|
|
69
75
|
/** Redis client for blocking stream operations (recommended for reliability) */
|
|
70
76
|
blockingClient?: RedisLikeClient;
|
|
77
|
+
/**
|
|
78
|
+
* Pre-built driver (e.g. a ClusterDriver) used directly as the primary
|
|
79
|
+
* driver. When set, pubClient/subClient/blockingClient are ignored.
|
|
80
|
+
*/
|
|
81
|
+
driver?: RedisPubSubDriver;
|
|
71
82
|
/** Optional key prefix for channels (default: 'ocpp-ws-io:') */
|
|
72
83
|
prefix?: string;
|
|
73
84
|
/** StreamMaxLen for trimming (default: 1000) */
|
|
@@ -117,7 +128,6 @@ declare class RedisAdapter implements EventAdapterInterface {
|
|
|
117
128
|
private _streams;
|
|
118
129
|
private _polling;
|
|
119
130
|
private _closed;
|
|
120
|
-
private _sequenceCounters;
|
|
121
131
|
private _unsubError?;
|
|
122
132
|
private _unsubReconnect?;
|
|
123
133
|
private _presenceCache;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { E as EventAdapterInterface, g as AuthCallback, L as LoggerLike, h as LoggingConfig, M as MiddlewareFunction, i as MiddlewareContext, j as OCPPPlugin, k as ConnectionMiddleware, V as Validator } from './types-
|
|
2
|
-
export { A as AllMethodNames, l as AnyOCPPProtocol, m as AuthAccept, n as AuthContext, o as CORSOptions, p as CallHandler, C as CallOptions, q as ClientEvents, r as ClientOptions, f as CloseOptions, s as CompressionOptions, t as ConnectionContext, u as ConnectionState, H as HandlerContext, v as HandshakeInfo, w as ListenOptions, x as MessageDirection, y as MessageEventContext, z as MessageEventPayload, B as MessageType, D as MiddlewareNext, F as MiddlewareStack, N as NOREPLY, G as OCPP16Methods, I as OCPP201Methods, J as OCPP21Methods, K as OCPPCall, P as OCPPCallError, Q as OCPPCallResult, R as OCPPClient, S as OCPPMessage, T as OCPPMethodMap, c as OCPPProtocol, U as OCPPProtocolKey, d as OCPPRequestType, e as OCPPResponseType, W as OCPPRouter, O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, X as RateLimitOptions, Y as RouterConfig, Z as SecurityEvent, _ as SecurityProfile, $ as ServerEvents, a0 as ServerOptions, a1 as SessionData, a2 as TLSOptions, a3 as TelemetryConfig, a4 as TypedEventEmitter, a5 as WildcardHandler, a6 as createRouter, a7 as createValidator } from './types-
|
|
3
|
-
import { R as RedisPubSubDriver, S as StreamEntry } from './index-
|
|
4
|
-
export { a as RedisAdapter } from './index-
|
|
1
|
+
import { E as EventAdapterInterface, g as AuthCallback, L as LoggerLike, h as LoggingConfig, M as MiddlewareFunction, i as MiddlewareContext, j as OCPPPlugin, k as ConnectionMiddleware, V as Validator } from './types-tTYOr5Gm.mjs';
|
|
2
|
+
export { A as AllMethodNames, l as AnyOCPPProtocol, m as AuthAccept, n as AuthContext, o as CORSOptions, p as CallHandler, C as CallOptions, q as ClientEvents, r as ClientOptions, f as CloseOptions, s as CompressionOptions, t as ConnectionContext, u as ConnectionState, H as HandlerContext, v as HandshakeInfo, w as ListenOptions, x as MessageDirection, y as MessageEventContext, z as MessageEventPayload, B as MessageType, D as MiddlewareNext, F as MiddlewareStack, N as NOREPLY, G as OCPP16Methods, I as OCPP201Methods, J as OCPP21Methods, K as OCPPCall, P as OCPPCallError, Q as OCPPCallResult, R as OCPPClient, S as OCPPMessage, T as OCPPMethodMap, c as OCPPProtocol, U as OCPPProtocolKey, d as OCPPRequestType, e as OCPPResponseType, W as OCPPRouter, O as OCPPServer, a as OCPPServerClient, b as OCPPServerStats, X as RateLimitOptions, Y as RouterConfig, Z as SecurityEvent, _ as SecurityProfile, $ as ServerEvents, a0 as ServerOptions, a1 as SessionData, a2 as TLSOptions, a3 as TelemetryConfig, a4 as TypedEventEmitter, a5 as WildcardHandler, a6 as createRouter, a7 as createValidator } from './types-tTYOr5Gm.mjs';
|
|
3
|
+
import { R as RedisPubSubDriver, S as StreamEntry } from './index-Gz98XqQ7.mjs';
|
|
4
|
+
export { a as RedisAdapter } from './index-Gz98XqQ7.mjs';
|
|
5
5
|
import { EventEmitter } from 'node:events';
|
|
6
6
|
import 'ws';
|
|
7
7
|
import 'node:https';
|
|
@@ -74,22 +74,20 @@ interface ClusterDriverOptions {
|
|
|
74
74
|
* Redis Cluster driver that implements `RedisPubSubDriver`.
|
|
75
75
|
* Requires `ioredis` as a peer dependency.
|
|
76
76
|
*
|
|
77
|
-
* Hash-tag strategy:
|
|
78
|
-
* - Presence keys: `{identity}` → sharded by station identity
|
|
79
|
-
* - Stream keys: `{nodeId}` → sharded by server node ID
|
|
80
|
-
*
|
|
81
77
|
* @example
|
|
82
78
|
* ```ts
|
|
83
|
-
* const driver =
|
|
79
|
+
* const driver = new ClusterDriver({
|
|
84
80
|
* nodes: [{ host: '10.0.0.1', port: 6379 }, { host: '10.0.0.2', port: 6379 }],
|
|
85
81
|
* });
|
|
86
|
-
* const adapter = new RedisAdapter({
|
|
82
|
+
* const adapter = new RedisAdapter({ driver });
|
|
87
83
|
* ```
|
|
88
84
|
*/
|
|
89
85
|
declare class ClusterDriver implements RedisPubSubDriver {
|
|
90
86
|
private _cluster;
|
|
91
87
|
private _subscriber;
|
|
92
88
|
private _handlers;
|
|
89
|
+
/** Cluster connections share command pipelines — never issue blocking reads. */
|
|
90
|
+
readonly hasBlockingClient = false;
|
|
93
91
|
constructor(_options: ClusterDriverOptions);
|
|
94
92
|
publish(channel: string, message: string): Promise<void>;
|
|
95
93
|
subscribe(channel: string, handler: (message: string) => void): Promise<void>;
|
|
@@ -335,7 +333,7 @@ declare function createRPCError(code: string, message?: string, details?: Record
|
|
|
335
333
|
* If a property holds a non-serializable value (functions, symbols,
|
|
336
334
|
* circular references), it is silently skipped.
|
|
337
335
|
*/
|
|
338
|
-
declare function getErrorPlainObject(err: Error): Record<string, unknown>;
|
|
336
|
+
declare function getErrorPlainObject(err: Error, includeStack?: boolean): Record<string, unknown>;
|
|
339
337
|
/**
|
|
340
338
|
* Get the package identifier string used in HTTP headers and logging.
|
|
341
339
|
* Format: `ocpp-ws-io/1.0.0`
|