@idm-plugin/vessel 3.4.1 → 3.4.3

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.
@@ -1 +1 @@
1
- (function(q,A){typeof exports=="object"&&typeof module<"u"?A(exports,require("got"),require("@log4js-node/log4js-api"),require("moment"),require("@idm-plugin/geo2"),require("@idm-plugin/meteo2"),require("@idm-plugin/meteo")):typeof define=="function"&&define.amd?define(["exports","got","@log4js-node/log4js-api","moment","@idm-plugin/geo2","@idm-plugin/meteo2","@idm-plugin/meteo"],A):(q=typeof globalThis<"u"?globalThis:q||self,A(q["idm-plugin-vessel"]={},q.got,q["@log4js-node/log4js-api"],q.moment,q["@idm-plugin/geo2"],q["@idm-plugin/meteo2"],q["@idm-plugin/meteo"]))})(this,function(q,A,U,w,N,ft,nt){"use strict";var It=Object.defineProperty;var St=(q,A,U)=>A in q?It(q,A,{enumerable:!0,configurable:!0,writable:!0,value:U}):q[A]=U;var K=(q,A,U)=>(St(q,typeof A!="symbol"?A+"":A,U),U);let m;try{m=U.getLogger("vessel")}catch{}finally{}class G{parseStatus(s){let t,a;switch(s){case 0:t="在航(主机推动)",a="Underway Using Engine";break;case 1:t="锚泊",a="Anchored";break;case 2:t="失控",a="Not under command";break;case 3:t="操纵受限",a="Limited airworthiness";break;case 4:t="吃水受限",a="Limited by ship's draft";break;case 5:t="靠泊",a="Mooring";break;case 6:t="搁浅",a="Stranded";break;case 7:t="捕捞作业",a="Engaged in fishing";break;case 8:t="靠帆船提供动力",a="Sailing";break;default:t="未定义",a="Undefined"}return{labelCn:t,labelEn:a}}}class mt extends G{constructor(t,a){super();K(this,"clientId");K(this,"clientSecret");K(this,"token");this.clientId=t,this.clientSecret=a}async authToken(t={}){const a="https://svc.data.myvessel.cn/ada/oauth/token",i={searchParams:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials"}},n=await A.post(a,i).json();m==null||m.info("[%s] fetch access token from: %s - %j",t.requestId,a,n),n.error||(this.token={accessToken:n.access_token,tokenType:n.token_type,expiresIn:n.expires_in,scope:n.scope,jti:n.jti,issuedAt:w().utc().format()})}async checkToken(t={}){var a;return(!this.token||w().diff(w(this.token.issuedAt),"seconds")>(((a=this.token)==null?void 0:a.expiresIn)||0)-300)&&await this.authToken(t),this.token}async suggest(t,a={}){var e,r;await this.checkToken(a);const i="https://market.myvessel.cn/sdc/v1/mkt/vessels/fuzzy",n={headers:{Authorization:`${(e=this.token)==null?void 0:e.tokenType} ${(r=this.token)==null?void 0:r.accessToken}`},json:{kw:t,recordNum:a.ps||10}};m==null||m.info("[%s] fetch suggest vessels from: %s - %j",a.requestId,i,n);const o=await A.post(i,n).json();return o.status!==200?(m==null||m.warn("[%s] fetch suggest vessels failed: %j",a.requestId,{message:o.message,status:o.status,code:o.code}),[]):(o.data||[]).map(l=>({mmsi:l.mmsi,name:l.nameEn,nameCn:l.nameCn,imo:Number.isNaN(l.imo)?null:Number(l.imo),callSign:l.callsign,type:l.vesselTypeNameEn,flagName:l.flagCtry,vendor:"myvessel",raw:l}))}async search(t,a={}){var u,l;await this.checkToken(a);const i=/^\d{7}$/.test(t.toString()),n=i?"https://market.myvessel.cn/sdc/v1/mkt/vessels/detail/imo":"https://market.myvessel.cn/sdc/v1/mkt/vessels/detail/mmsi",o=i?{imo:t}:{mmsi:t},e={headers:{Authorization:`${(u=this.token)==null?void 0:u.tokenType} ${(l=this.token)==null?void 0:l.accessToken}`},searchParams:o};m==null||m.info("[%s] fetch vessel from: %s - %j",a.requestId,n,e);const r=await A.get(n,e).json();if(r.status!==200)return m==null||m.warn("[%s] fetch suggest vessels failed: %j",a.requestId,{message:r.message,status:r.status,code:r.code}),{};{const d=r.data;if(d)return{mmsi:d.mmsi,imo:Number.isNaN(d.imo)?null:Number(d.imo),callSign:d.callsign,name:d.nameEn,nameCn:d.nameCn,type:d.vesselTypeNameEn,flagName:d.flagCtry,clasz:d.classSociety,dateOfBuild:d.buildYearMonth,deadweight:d.dwt,grossTonnage:d.grt,netTonnage:d.net,teu:d.teu,length:d.length,breadth:d.width,height:d.height,draught:d.draught,speed:d.speed,passengerCapacity:d.passengercapacity,vendor:"myvessel",raw:d}}return{}}async archives(t,a={}){var e,r;await this.checkToken(a);const i="https://svc.data.myvessel.cn/sdc/v1/ship/info/batch",n={headers:{Authorization:`${(e=this.token)==null?void 0:e.tokenType} ${(r=this.token)==null?void 0:r.accessToken}`},json:{mmsiList:typeof t=="number"?[t]:t}};m==null||m.info("[%s] fetch vessel archive from: %s - %j",a.requestId,i,n);const o=await A.post(i,n).json();return o.status!==200?(m==null||m.warn("[%s] fetch vessel archive failed: %j",a.requestId,{message:o.message,status:o.status,code:o.code}),{}):o.data}async realTimePosition(t,a={}){var r,u;await this.checkToken(a);const i="https://svc.data.myvessel.cn/sdc/v1/vessels/status/location/unit",n={headers:{Authorization:`${(r=this.token)==null?void 0:r.tokenType} ${(u=this.token)==null?void 0:u.accessToken}`},searchParams:{mmsi:t}};m==null||m.info("[%s] fetch realtime position from: %s - %j",a.requestId,i,n);const o=await A.get(i,n).json();if(o.code)return m==null||m.warn("[%s] fetch realtime position failed: %j",a.requestId,{message:o.message,status:o.status,code:o.code}),o;const e=o.data;for(const l in e)!isNaN(e[l])&&Number(e[l])!==1/0&&(e[l]=Number(e[l]));if(e){const l=w(`${e.postime} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");return{mmsi:e.mmsi,name:e.vesselName||e.aisVesselName,imo:e.imo,callSign:e.callsign||e.aisCallSign,lat:e.lat,lng:e.lon,length:e.length,width:e.width,draught:e.currDraught,sog:e.sog,cog:e.cog,hdg:e.hdg,rot:e.rot,eta:/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e.eta)?w.utc(e.eta).format():void 0,destination:e.dest,positionTime:l.unix(),status:e.status,labelCn:e.statusNameCn,labelEn:e.statusNameEn,vesselType:e.vesselTypeNameEn,flag:e.flagCtryNameEn,clasz:e.classSociety,build:e.buildYear,dwt:e.dwt,grt:e.grt,net:e.net,method:"position",vendor:"myVessel",utc:l.utc().format()}}else return{}}async calculateRoute(t,a,i={}){var r,u;await this.checkToken(i);const n="https://svc.data.myvessel.cn/sdc/v1/routes/routing/nodes",o={headers:{Authorization:`${(r=this.token)==null?void 0:r.tokenType} ${(u=this.token)==null?void 0:u.accessToken}`},json:{startPoint:{lon:t.lng,lat:t.lat},endPoint:{lon:a.lng,lat:a.lat},maxDraught:i.maxDraught||10,useAIModel:i.useAIModel||!1,withECA:i.withECA||!1}};m==null||m.info("[%s] fetch route from: %s - %j",i.requestId,n,o);const e=await A.post(n,o).json();return e.status!==200?(m==null||m.warn("[%s] fetch route failed: %j",i.requestId,{message:e.message,status:e.status,code:e.code}),{}):e.data}async trajectory(t,a,i,n,o=!0,e={}){await this.checkToken(e);const r=await this.realTimePosition(t,e),u=w(a),l=w(i),d=[];for(;l.diff(u,"day",!0)>30;)await this.trajectoryIn30Day(t,u,u.clone().add(30,"day"),r,n,d,e),u.add(30,"day");return await this.trajectoryIn30Day(t,u,l,r,n,d,e),d}async trajectoryIn30Day(t,a,i,n,o,e,r={}){var M,C,S,g,b;const u="https://svc.data.myvessel.cn/sdc/v1/vessels/status/track",l={headers:{Authorization:`${(M=this.token)==null?void 0:M.tokenType} ${(C=this.token)==null?void 0:C.accessToken}`},json:{mmsi:t,startTime:a.utcOffset(8).format("YYYY-MM-DD HH:mm:ss"),endTime:i.utcOffset(8).format("YYYY-MM-DD HH:mm:ss")}};m==null||m.info("[%s] fetch trajectory from: %s - %j",r.requestId,u,l);const d=await A.post(u,l).json();if(d.code)return m==null||m.warn("[%s] fetch trajectory failed: %j",r.requestId,u,{message:d.message,status:d.status,code:d.code}),d;let y=-1;const v=w(`${(g=(S=d.data)==null?void 0:S[0])==null?void 0:g.postime} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");return(b=d.data)==null||b.forEach(c=>{for(const Y in c)!isNaN(c[Y])&&Number(c[Y])!==1/0&&(c[Y]=Number(c[Y]));const p=w(`${c.postime} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00"),f=c.status,{labelCn:h,labelEn:k}=this.parseStatus(f),j={mmsi:c.mmsi,imo:n==null?void 0:n.imo,lat:c.lat,lng:c.lon,sog:c.sog,cog:c.cog,hdg:c.hdg,draught:c.draught,status:f,eta:/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(c.eta)?w(`${c.eta} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00").utc().format():void 0,destination:c.dest,positionTime:p.unix(),labelCn:h,labelEn:k,method:"trajectory",vendor:"myVessel",utc:p.utc().format()},x=Math.floor(p.diff(v,"minute",!0)/(o||1));x!==y&&(y=x,e.push(j))}),e}}class yt extends G{constructor(t){super();K(this,"token");this.token=t}async realTimePosition(t,a={}){const i="https://api.hifleet.com/position/position/get/token",n={searchParams:{mmsi:t,usertoken:this.token}},o=await A.post(i,n).json();m==null||m.info("[%s] fetch realtime position from: %s - %j",a.requestId,i,n);const e=o==null?void 0:o.list;if(!e)return m==null||m.warn("[%s] fetch realtime position failed: %j",a.requestId,i,o),o;for(const v in e)!isNaN(e[v])&&Number(e[v])!==1/0&&(e[v]=Number(e[v]));e.status=e.sp>3?0:1;const r=e.status,{labelCn:u,labelEn:l}=this.parseStatus(r),d=w(`${e.ti} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");return{mmsi:e.m,name:e.n,imo:e.imonumber,callSign:e.callsign,lat:Math.round(e.la/60*1e5)/1e5,lng:Math.round(e.lo/60*1e5)/1e5,length:e.l,width:e.w,draught:e.draught,sog:e.sp,cog:e.co,hdg:e.h,rot:isNaN(e.rot)?0:e.rot,eta:/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e.eta)?w.utc(e.eta).format():void 0,destination:e.destination,vesselType:e.type,dwt:e.dwt,build:e.buildyear,flag:e.fn,positionTime:d.unix(),utc:d.utc().format(),status:r,labelCn:u,labelEn:l,method:"position",vendor:"hifleet"}}async search(t,a={}){let i="https://www.hifleet.com/hifleetapi/searchVesselOL.do";const n={searchParams:{keyword:t},headers:{Referer:"https://www.hifleet.com",Origin:"https://www.hifleet.com",Host:"www.hifleet.com"}};let o=await A.post(i,n).json();m==null||m.info("[%s] fetch vessel props from: %s - %j",a.requestId,i,n),o instanceof Array&&(o=o[0]);for(const r in o)!isNaN(o[r])&&Number(o[r])!==1/0&&(o[r]=Number(o[r]));const e={mmsi:o.m,name:o.n,imo:o.i,callSign:o.c,length:o.l,breadth:o.b,draught:o.dr,type:o.t};return i="https://www.hifleet.com/hifleetapi/sameShipSearch.do",o=await A.post(i,n).json(),m==null||m.info("[%s] search vessel dead weight from: %s - %j",a.requestId,i,n),o instanceof Array&&(o=o[0]),o&&(e.deadweight=Number(o.dwt)),e}async suggest(t,a={}){const i="https://www.hifleet.com/hifleetapi/getShipSuggest.do",n={searchParams:{q:t},headers:{Referer:"https://www.hifleet.com",Origin:"https://www.hifleet.com",Host:"www.hifleet.com"}},o=await A.post(i,n).json();m==null||m.info("[%s] suggest vessel props from: %s - %j",a.requestId,i,n);const e=[];for(const r of o)e.push({mmsi:!r.mmsi||isNaN(r.mmsi)?null:Number(r.mmsi),name:r.name,callSign:r.callsign,imo:!r.imo||isNaN(r.imo)?null:Number(r.imo),score:r._score});return e.sort((r,u)=>u.score-r.score),e}async trajectory(t,a,i,n,o=!0,e={}){var c,p,f;const r=await this.realTimePosition(t,e);let u=w(a);const l=w(i),d=w();if(o){let h=l.diff(u,"d",!0);h<0?u=l.clone().subtract(40,"d"):h<30?u.subtract(10,"d"):h<60?u.subtract(5,"d"):u=l.clone().subtract(80,"d"),h=d.diff(l,"d",!0),l.add(h>10?240:h*24,"h")}const y={searchParams:{endtime:l.utcOffset("+8:00").format("YYYY-MM-DD HH:mm:ss"),starttime:u.utcOffset("+8:00").format("YYYY-MM-DD HH:mm:ss"),mmsi:t,usertoken:this.token}},v="https://api.hifleet.com/position/trajectory/nocompressed/withstatic/token",M=await A.get(v,y).json();m==null||m.info("[%s] fetch trajectory from: %s - %j",e.requestId,v,y);let C;M&&(C=((p=(c=M.ships)==null?void 0:c.offors)==null?void 0:p.ship)||[],C.length||m==null||m.warn("[%s] fetch trajectory failed: %j",e.requestId,M));const S=[];let g=-1;const b=w(`${(f=C==null?void 0:C[0])==null?void 0:f.ti} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");for(const h of C){for(const L in h)!isNaN(h[L])&&Number(h[L])!==1/0&&(h[L]=Number(h[L]));const k=w(`${h.ti} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");h.status=h.sp>4?0:1;const{labelEn:j,labelCn:x}=this.parseStatus(h.status),Y={mmsi:h.m,name:h.n,imo:r==null?void 0:r.imo,lat:h.la,lng:h.lo,draught:h.draught,sog:h.sp,cog:h.co,hdg:h.hdg,positionTime:k.unix(),utc:k.utc().format(),status:h.status,labelCn:x,labelEn:j,method:"trajectory",vendor:"hifleet"},F=Math.floor(k.diff(b,"minute",!0)/(n||1));F!==g&&(g=F,S.push(Y))}return S}}class Mt extends G{constructor(t){super();K(this,"token");this.token=t}async realTimePosition(t,a={}){const i={searchParams:{id:t,k:this.token,enc:1}},n="https://api.shipxy.com/apicall/GetSingleShip",o=await A.get(n,i).json();if(m==null||m.info("[%s] fetch realtime position from: %s - %j",a.requestId,n,i),(o==null?void 0:o.status)!==0)return o;const e=o.data[0];for(const y in e)!isNaN(e[y])&&Number(e[y])!==1/0&&(e[y]=Number(e[y]));const{labelCn:r,labelEn:u}=await this.parseStatus(e.navistat),l=w.unix(e.lasttime);return{mmsi:e.ShipID,name:e.name,imo:e.imo,callSign:e.callsign,lat:Math.round(e.lat/1e6*1e5)/1e5,lng:Math.round(e.lon/1e6*1e5)/1e5,length:Math.round(e.length/10*100)/100,width:Math.round(e.width/10*100)/100,draught:Math.round(e.draught/1e3*100)/100,sog:Math.round(e.sog*3600/1e3/1852*100)/100,cog:Math.round(e.cog/100*100)/100,hdg:Math.round(e.hdg/100*100)/100,rot:Math.round(e.rot/100*100)/100,positionTime:e.lasttime,utc:l.utc().format(),status:e.navistat,labelEn:u,labelCn:r,method:"position",vendor:"shipxy"}}async trajectory(t,a,i,n,o=!0,e={}){var b;const r=await this.realTimePosition(t,e),u=w(a),l=w(i),d="https://api.shipxy.com/apicall/GetShipTrack",y={searchParams:{id:t,k:this.token,enc:1,cut:0,btm:u.unix(),etm:l.unix()}},v=await A.get(d,y).json();if(m==null||m.info("[%s] fetch trajectory from: %s - %j",e.requestId,d,y),(v==null?void 0:v.status)!==0)return v;const M=v==null?void 0:v.points,C=[],S=w.unix((b=M[0])==null?void 0:b.utc);let g=-1;for(const c of M){const p=w.unix(c.utc),f={imo:r==null?void 0:r.imo,mmsi:t,sog:Math.round(c.sog*3600/1e3/1852*100)/100,cog:Math.round(c.cog/100*100)/100,lat:Math.round(c.lat/1e6*1e5)/1e5,lng:Math.round(c.lon/1e6*1e5)/1e5,positionTime:p.unix(),utc:p.utc().format(),method:"trajectory",vendor:"shipxy"},h=Math.floor(p.diff(S,"minute",!0)/(n||1));h!==g&&(g=h,C.push(f))}return C}}class pt extends G{constructor(t){super();K(this,"token");this.token=t}async getShipId(t,a={}){const i={headers:{appKey:this.token},json:{mmsiList:t}},n="https://api3.myships.com/sp/ships/getShipIdByMMSI",o=await A.post(n,i).json();return m==null||m.info("[%s] fetch ship id from: %s - %j",a.requestId,n,i),o.code!=="0"?o:o.data[0].shipId}async getShipInfo(t,a={}){const i={headers:{appKey:this.token},json:{shipId:t}},n="https://api3.myships.com/sp/ships/aissta",o=await A.post(n,i).json();if(m==null||m.info("[%s] fetch ship info from: %s - %j",a.requestId,n,i),o.code!=="0")return o;const e=o.data;let r=e.imo;return t==="407170"&&(r="9198379",m==null||m.warn("[%s] ship(%s) imo error: %s, should be %s",a.requestId,t,e.imo,r)),{mmsi:e.mmsi,name:e.shipnameEn,imo:r,callSign:e.callSign,length:e.length,width:e.breadth,draught:(e.draught||100)/10}}async realTimePosition(t,a={}){const i=await this.getShipId(t,a),n=await this.getShipInfo(i,a),o={headers:{appKey:this.token},json:{shipId:i}},e="https://api3.myships.com/sp/ships/position/latest",r=await A.post(e,o).json();m==null||m.info("[%s] fetch realtime position from: %s - %j",a.requestId,e,o);const u=r.data[0];for(const M in u)!isNaN(u[M])&&Number(u[M])!==1/0&&(u[M]=Number(u[M]));const{labelCn:l,labelEn:d}=await this.parseStatus(u.aisNavStatus),y=w.unix(u.posTime);return{...n,mmsi:t,lat:Math.round(u.lat/1e4/60*1e5)/1e5,lng:Math.round(u.lon/1e4/60*1e5)/1e5,sog:Math.round(u.sog/10*100)/100,cog:Math.round(u.cog/10*100)/100,hdg:Math.round(u.heading*100)/100,rot:Math.round(u.rot*100)/100,positionTime:u.posTime,utc:y.utc().format(),status:u.aisNavStatus,labelEn:d,labelCn:l,method:"position",vendor:"myship"}}async trajectory(t,a,i,n,o=!0,e={}){const r=w(a),u=w(i),l=await this.getShipId(t),d=await this.getShipInfo(l),y=[];for(;u.diff(r,"day",!0)>30;)await this.trajectoryIn30Day(l,r.unix(),r.add(30,"day").unix(),d,t,n,y);return await this.trajectoryIn30Day(l,r.unix(),u.unix(),d,t,n,y),y}async trajectoryIn30Day(t,a,i,n,o,e,r,u={}){var S;const l={headers:{appKey:this.token},json:{shipId:t,startTime:a,endTime:i}},d="https://api3.myships.com/sp/ships/position/history",y=await A.post(d,l).json();if(m==null||m.info("[%s] fetch trajectory from: %s - %j",u.requestId,d,l),y.code!=="0")return m==null||m.warn("[%s] invoke myship trajectory failed: %j",u.requestId,y),y;const v=y.data;for(const g in v)!isNaN(v[g])&&Number(v[g])!==1/0&&(v[g]=Number(v[g]));const M=w.unix((S=v[0])==null?void 0:S.posTime);let C=-1;for(const g of v){const b=w.unix(g.posTime),c={imo:n==null?void 0:n.imo,mmsi:o,lat:Math.round(g.lat/1e4/60*1e5)/1e5,lng:Math.round(g.lon/1e4/60*1e5)/1e5,sog:Math.round(g.sog/10*100)/100,cog:Math.round(g.cog/10*100)/100,hdg:Math.round(g.heading*100)/100,rot:Math.round(g.rot*100)/100,positionTime:b.unix(),utc:b.utc().format(),method:"trajectory",vendor:"myship"},p=Math.floor(b.diff(M,"minute",!0)/(e||1));p!==C&&(C=p,r.push(c))}return r}}let _;try{_=U.getLogger("vessel")}catch{}finally{}var ct=(D=>(D.NOTICE="NOTICE",D.WARN="WARN",D.HEAVY="HEAVY",D.SEVERE="SEVERE",D.ERROR="ERROR",D.FATAL="FATAL",D))(ct||{});class dt{parsePrinciple(s,t={}){var e,r,u;_==null||_.debug("[%s] parse rule: %s",t.requestId,s);const a=new RegExp("(?<=\\[)(.+)(?=])","g"),i=s.match(a)?(e=s.match(a))==null?void 0:e[0]:void 0,n=i==null?void 0:i.split(";");if(!n)return;const o={};for(let l=0;l<(n==null?void 0:n.length);l++){const d=(u=(r=n[l].match(a))==null?void 0:r[0])==null?void 0:u.split("],");if(l===0&&!d)o.scope=n[0];else if(d)for(let y=0,v=d.length;y<v;y++){const M=this.parseRule(d[y]);M&&(o[M.level]?M.key?o[M.level][M==null?void 0:M.key]=M:o[M.level]=M:M.key?o[M.level]={[M==null?void 0:M.key]:M}:o[M.level]=M)}}return o}parseRule(s,t={}){var o;_==null||_.debug("[%s] parse rule: %s",t.requestId,s),s=s.startsWith("[")?s:`[${s}`,s=s.endsWith("]")?s:`${s}]`;const a=new RegExp("(?<=\\[)(.+?)(?=])","g"),i=(o=s==null?void 0:s.match(a))==null?void 0:o[0],n=i==null?void 0:i.split(",");if(n){let e=n[3]==="Number.MAX_VALUE"?100:Number(n[3]);return e=isNaN(e)?1:e,{operator:n[0],number:Number.isNaN(Number(n[1]))?n[1]:Number(n[1]),level:n[2],time:e,key:n[4]}}}checkWeather(s,t,a={}){var M,C,S,g,b,c,p,f,h,k,j,x,Y,F,L;let i=0,n=0,o=0,e=0;const r=Math.round(((C=(M=t==null?void 0:t.SEVERE)==null?void 0:M.sigWave)==null?void 0:C.number)*1.6*100)/100,u=(g=(S=t==null?void 0:t.SEVERE)==null?void 0:S.sigWave)==null?void 0:g.number,l=(c=(b=t==null?void 0:t.HEAVY)==null?void 0:b.sigWave)==null?void 0:c.number,d=Math.round((((f=(p=t==null?void 0:t.SEVERE)==null?void 0:p.wind)==null?void 0:f.number)+2)*100)/100,y=(k=(h=t==null?void 0:t.SEVERE)==null?void 0:h.wind)==null?void 0:k.number,v=(x=(j=t==null?void 0:t.HEAVY)==null?void 0:j.wind)==null?void 0:x.number;for(let H=0;H<(s==null?void 0:s.length);H++){const E=s[H],P=(F=(Y=E==null?void 0:E.meteo)==null?void 0:Y.wave)==null?void 0:F.sig,V=(L=E==null?void 0:E.meteo)==null?void 0:L.wind,J=H?w(E.eta).diff(w(s[H-1].eta),"hour",!0):0;e=J>e?J:e,_==null||_.debug("[%s] check sig.wave: %j",a.requestId,{...P,dgThd4Wv:r,svThd4Wv:u,hvThd4Wv:l}),(P==null?void 0:P.height)>=r?E.isDangerous=!0:(P==null?void 0:P.height)>=u?E.isSevere=!0:(P==null?void 0:P.height)>=l&&(E.isHeavy=!0),_==null||_.debug("[%s] check wind: %j",a.requestId,{...V,dgThd4Wd:d,svThd4Wd:y,hvThd4Wd:v}),(V==null?void 0:V.scale)>=d?(E.isDangerous=!0,delete E.isSevere,delete E.isHeavy):(V==null?void 0:V.scale)>y?(E.isDangerous||(E.isSevere=!0),delete E.isHeavy):(V==null?void 0:V.scale)===v&&!E.isDangerous&&!E.isSevere&&(E.isHeavy=!0),i+=E.isDangerous?J:0,n+=E.isSevere?J:0,o+=E.isHeavy?J:0}return i=Math.round(i*100)/100,n=Math.round(n*100)/100,o=Math.round(o*100)/100,e=Math.round(e),{sample:s,dangerous:i,severe:n,heavy:o,step:e<3?3:e,wind:{dgThd4Wd:d,svThd4Wd:y,hvThd4Wd:v},sig:{dgThd4Wv:r,svThd4Wv:u,hvThd4Wv:l}}}}const bt=new dt;let I;try{I=U.getLogger("vessel")}catch{}finally{}const vt=new ft.MeteoHelper2("",!0);var ut=(D=>(D.common="common",D.container="container",D.tugs="tugs",D))(ut||{}),lt=(D=>(D.Ballast="Ballast",D.Laden="Laden",D))(lt||{}),ht=(D=>(D.Cp="CP",D.Perf="Basis",D.Instruct="Other",D))(ht||{});class W{static blockCoefficient(s,t,a,i){let n=Math.round(s/(t*a*i)*100)/100;n=n<.55?.55:n>.85?.85:n;const o=[.55,.6,.65,.7,.75,.8,.85],e=o.map(r=>Math.abs(r-n));return o[e.indexOf(Math.min(...e))]}static froudeNumber(s,t,a=9.8){let i=Math.round(Math.sqrt(s*s/(a*t))*100)/100;return i=i<.05?.05:i>.3?.3:i,i}static amendFactor(s,t,a){const i={.55:[1.7,-1.4,-7.4],.6:[2.2,-2.5,-9.7],.65:[2.6,-3.7,-11.6],.7:[3.1,-5.3,-12.4],.75:[2.4,-10.6,-9.5],.8:[2.6,-13.1,-15.1],.85:[3.1,-18.7,28]};let o={.55:[1.7,-1.4,-7.4],.6:[2.2,-2.5,-9.7],.65:[2.6,-3.7,-11.6],.7:[3.1,-5.3,-12.4],.75:[2.6,-12.5,-13.5],.8:[3,-16.3,-21.6],.85:[3.4,-20.9,31.8]}[s];return a==="Laden"&&(o=i[s]),o[0]+o[1]*t+o[2]*Math.pow(t,2)}static directionFactor(s,t=0){let a;return s>30&&s<=60?a=(1.7-.03*Math.pow(t-4,2))/2:s>60&&s<=150?a=(.9-.06*Math.pow(t-6,2))/2:s>150&&s<=180?a=(.4-.03*Math.pow(t-8,2))/2:a=1,Math.round(a*1e5)/1e5}static vesselTagFactor(s,t,a,i){let n;return a==="container"?n=.7*i/2+Math.pow(i,3)/(22*Math.pow(s,2/3)):t==="Ballast"?n=.7*i/2+Math.pow(i,3)/(2.7*Math.pow(s,2/3)):n=.5*i/2+Math.pow(i,3)/(2.7*Math.pow(s,2/3)),n}static waveHeightFactor(s,t){s=s<3?s*.7:s,s=s<0?.2:s,s=s>6?s-.9*(s-6):s,s=s>9?9:s;let a;return t>30&&t<=60?a=-.6:t>60&&t<=90?a=-.4:t>90&&t<=120?a=s<3?.4:-.3:t>120&&t<=150?a=s<3?.6:-.5:t>150&&t<=180?a=s<3?.7:-.6:a=-.7,Math.round(a*(.144*Math.pow(s,2)+.278*s)*1e4)/1e4}static assembleProperties(s,t,a,i){var y;const n=s.lbp??s.length??s.lengthOverall??198.9642,o=s.draught??8,e=s.breadthMoulded??s.breadth??s.breadthExtreme??32.4572,r=s.deadweight??67035.7773,u=((y=s==null?void 0:s.type)==null?void 0:y.toLowerCase())||"common";return{tag:u.indexOf("container")>-1?"container":u.indexOf("tugs")>-1?"tugs":"common",lbp:n,loadCondition:t,draught:o,breadthMoulded:e,displacement:Math.round((r/1.025+o*e*n*.7)*1e4)/1e4,speed:Math.round((a??14.1382)*1852/3600*1e4)/1e4,bearing:i||90}}static async speedLoseAt(s,t,a,i="",n=2,o=!0,e=!1,r={}){let u;if(t.velocity&&e&&(s.speed=N.LngLatHelper.roundPrecision(t.velocity*1852/3600,6)),o){let l;try{i=(i==null?void 0:i.toUpperCase())==="CMEMS"?"ECMWF":i,i=(i==null?void 0:i.toUpperCase())==="METEO2"?"best_match":i;const{weatherModels:M,marineModels:C}=await nt.Meteo2Assist.autoPickMeteoModel(i),S=await vt.spotForecast(t.lat,t.lng,a.utc().format(),!1,!1,!0,{...r,pastDays:1,forecastDays:1,weatherModels:M,marineModels:C}),[g]=nt.Meteo2Assist.pickHourly(S,a);l=nt.Meteo2Assist.toLegacy(g)}catch(M){I.warn("[%s] meteo2 spot(%j) forecast failed: %s",r.requestId,{...t,eta:a.utc().format(),source:i},M)}const d=W.currentFactor(s.bearing,l==null?void 0:l.current,n),y=W.weatherFactor(s,l,d),v=Math.round((s.speed*1.943844+y+d)*100)/100;u={meteo:{...l},wxFactor:y,cFactor:d,speed:t.velocity&&e?t.velocity:v<0?1:v,eta:a.utc().format(),etd:a.utc().format()}}else u={wxFactor:0,cFactor:0,speed:t.velocity&&e?t.velocity:Math.round(s.speed*1.943844*100)/100,eta:a.utc().format(),etd:a.utc().format()};return delete t.meteo,delete t.wxFactor,delete t.cFactor,delete t.speed,delete t.etd,{...u,...t}}static async speedLoseInHoursStep(s,t,a,i,n,o,e="",r=!0,u=!1,l={}){t.utc();const d=t.clone().add(14,"days"),y=[],v=[];let M=0,C=0,S,g;for(let b=0;b<o.length-1;b++){let c=o[b];c.distanceFromStart=Math.round((n+C)*1e3)/1e3;const p=o[b+1];if(s.bearing=N.LaneHelper.calculateBearing(c,p,!p.gcToPrevious),c.bearing=s.bearing,c.suspend&&u){c.eta=c.eta||t.utc().format(),c.elapsed=c.elapsed??0;const k=c.suspend-c.elapsed;if(i-M>k)i=i-M-k,t.add(k,"hour"),c.elapsed=c.suspend;else{const j=i-M;c.elapsed+=j,t.add(j,"hour"),i=0}if(I==null||I.info(`[%s] suspend ${c.elapsed} hours at %j, and remain ${i} hours need to go...`,l.requestId,c),i===0)return c.distanceFromPrevious=C,{etd:t,from:g||c,to:c,next:o.filter(j=>j),wps:y,days:v}}else c.suspend=0;r=t.isAfter(d)?!1:r,c=await W.speedLoseAt(s,c,t,e,0,r,u,l),g=g||c,c.important&&y.push(c),t.isSameOrAfter(a)&&(v.push(c),a.add(24,"hour"));const f=N.LaneHelper.calculateDistance(c,p,!p.gcToPrevious);let h=Math.round(f/g.speed*1e5)/1e5;if(M+h<i){if(M+=h,t.add(h,"hour"),delete o[b],I==null||I.debug(`[%s] go to %j from %j with ${f}nm, and cost ${h} hours`,l.requestId,{lat:p.lat,lng:p.lng},{lat:g.lat,lng:g.lng,etd:g.etd}),C+=f,o.filter(k=>k).length<=1){S=p,S.eta=t.utc().format(),S.distanceFromPrevious=f,S.distanceFromStart=Math.round((n+C)*1e4)/1e4,y.push(S),delete o[b+1];break}}else{h=i-M,t.add(h,"hour");const k=N.LngLatHelper.roundPrecision(g.speed*h,5);S=N.LaneHelper.calculateCoordinate(c,s.bearing,k,"nauticalmiles",!p.gcToPrevious),S.eta=t.utc().format(),o[b]=S,I==null||I.debug(`[%s] go to %j from %j with ${k}nm, and cost ${h} hours`,l.requestId,{lat:S.lat,lng:S.lng},{lat:c.lat,lng:c.lng,etd:c.etd}),C+=k,S.distanceFromPrevious=Math.round(C*1e4)/1e4,S.distanceFromStart=Math.round((n+C)*1e4)/1e4;break}}return{etd:t,from:g,to:S,next:o.filter(b=>b),wps:y,days:v}}static currentFactor(s,t,a=0){const i=(s-(t==null?void 0:t.degree)||0)/180*Math.PI;if(Math.abs(i)===Math.PI/2)return 0;let n=((t==null?void 0:t.kts)||0)*Math.cos(i);return a&2?n=Math.ceil(n*100)/100:a&1?n=Math.floor(n*100)/100:n=Math.round(n*100)/100,Math.abs(n)>5?0:n}static weatherFactor(s,t,a=0){var v,M,C,S,g,b,c;I==null||I.debug("calculate weather factor via: %j",{...s,...t});const i=W.blockCoefficient(s.displacement,s.lbp,s.breadthMoulded,s.draught),n=N.LngLatHelper.roundPrecision(a*1852/3600,6),o=W.froudeNumber(s.speed-n,s.lbp),e=W.amendFactor(i,o,s.loadCondition);let r=Math.abs(s.bearing%360-(((v=t==null?void 0:t.wind)==null?void 0:v.degree)%360||0));r=r>180?360-r:r;const u=W.directionFactor(r,(M=t==null?void 0:t.wind)==null?void 0:M.scale),l=W.vesselTagFactor(s.displacement,s.loadCondition,s.tag,(C=t==null?void 0:t.wind)==null?void 0:C.kts);let d=u*e*l/100*(s.speed-n);d=Math.round(d*1.943844*1e4)/1e4*-1,s.tag==="tugs"&&Math.abs(d)>1&&(d=d/(Math.abs(Math.round(d))+1)),I==null||I.debug("wind wx factor = %d",d),r=Math.abs(s.bearing%360-(((g=(S=t==null?void 0:t.wave)==null?void 0:S.sig)==null?void 0:g.degree)%360||0)),r=r>180?360-r:r;const y=W.waveHeightFactor(((c=(b=t==null?void 0:t.wave)==null?void 0:b.sig)==null?void 0:c.height)??1,r);return I==null||I.debug("wave wx factor = %d",y),d=Math.abs(d)>Math.abs(y)?d:d*.3+y*.7,I==null||I.debug("weather factor = %d",d),d=Math.abs(d)>3?3*(Math.abs(d)/d)+Math.abs(d)/d*(Math.abs(d)-2)*.1:d,Math.round((d||0)*100)/100}static async analyseInstant(s,t,a,i,n,o="",e=0,r=!0,u=!1,l={}){var X,Q,Z,$,tt,et;const d=w().valueOf();s.lng=N.LngLatHelper.convertToStdLng(s.lng);const{route:y,waypoints:v}=n.points,M=N.LaneHelper.calculateSubRoute(s,y);if(((X=M[0])==null?void 0:X.length)<=1)return;const{v0:C,label:S}=s.sog?{v0:s.sog,label:s.label||"Other"}:{v0:i.speed,label:"CP"},g=W.assembleProperties(a,i.loadCondition,C,0),b=v.length?N.LaneHelper.calculateSubWaypoints(s,v):[];b.forEach(O=>O.important=!0);const c={from:{...s},route:M,waypoints:b,v0:C,label:S},p={hours:[],days:[],wps:[]};e||(N.LaneHelper.calculateRouteDistance(M)/i.speed<=72?e=3:e=6);let f=N.LaneHelper.simplifyRouteToCoordinates(M,b,0),h=0,k=0,j=0,x=0;t=w(t).utc();const Y=t.clone();for(;f.length>0;){const O=e-t.hour()%e,z=Math.ceil(t.clone().add(O,"h").set({minute:0,second:0,millisecond:0}).diff(t,"h",!0)*1e4)/1e4,T=await W.speedLoseInHoursStep(g,t,Y,z,h,f,o,r,u,l);if((Q=T.from)!=null&&Q.speed&&(p.hours.push(T.from),p.wps.push(...T.wps),p.days.push(...T.days)),f=T==null?void 0:T.next,!f.length){const B=await W.speedLoseAt(g,T.to,w(T.to.eta),o,0,r,u,l);B.bearing=g.bearing,p.hours.push(B)}h+=Math.round((((Z=T==null?void 0:T.to)==null?void 0:Z.distanceFromPrevious)??0)*1e4)/1e4}const F=p.hours;for(let O=0;O<F.length-1;O++){const z=w(F[O+1].eta).diff(F[O].etd,"hour",!0)||1;k+=(F[O].wxFactor||0)*z,j+=(F[O].cFactor||0)*z,x+=z}($=p.wps)==null||$.forEach((O,z)=>{O.positionTime=w.utc(O.etd||O.eta).unix();const T=p.wps[z-1];if(T){const B=O.distanceFromStart-T.distanceFromStart,R=w(O.eta||O.etd).diff(w(T.etd||T.eta),"h",!0);O.avgSpd=Math.round(B/R*100)/100,T.bearing=N.LaneHelper.calculateBearing(T,O)}}),p.wps=(tt=p.wps)==null?void 0:tt.reduce((O,z)=>(O.some(T=>Math.round(T.positionTime/60)===Math.round(z.positionTime/60))||O.push(z),O),[]),c.sample=p;const L=p.hours.at(0),H=p.hours.at(-1);c.distance=Math.round(H.distanceFromStart*1e3)/1e3,c.etd=w(L.eta).utc().format(),c.eta=w(H.eta).utc().format(),c.wxFactor=Math.round(k/x*1e3)/1e3,c.cFactor=Math.round(j/x*1e3)/1e3,c.avgSpeed=Math.round(H.distanceFromStart/x*1e3)/1e3,c.totalHrs=Math.round(x*1e3)/1e3;const{distanceInECA:E,hoursInECA:P,totalDgoConsInECA:V,eca:J}=await this.calculateECA(c,i,l),st=N.LngLatHelper.roundPrecision(i.fo/24*(x-P),3),ot=N.LngLatHelper.roundPrecision(i.dgo/24*x,3);c.extend={eca:J,distanceInECA:E,hoursInECA:P,totalDgoConsInECA:V},c.totalFoCons=st<0?0:st,c.totalDgoCons=ot;const at=w().valueOf()-d,rt=((et=p==null?void 0:p.hours)==null?void 0:et.length)||1;return I==null||I.info("[%s] each hour-sample speed analyse cost: (%d / %d = %d) ms",l==null?void 0:l.requestId,at,rt,Math.round(at/rt*1e3)/1e3),c}static async analyseInstantWithThreshed(s,t,a,i,n,o,e,r="",u=3,l=!0,d=!1,y={}){var Z,$,tt,et,O,z;const v=w().valueOf();s.lng=N.LngLatHelper.convertToStdLng(s.lng);const{v0:M,label:C}=s.sog?{v0:s.sog,label:s.label||"Other"}:{v0:n.speed,label:"CP"},S=W.assembleProperties(i,n.loadCondition,M,0),g=N.LaneHelper.calculateSubRoute(s,o);if(((Z=g[0])==null?void 0:Z.length)<=1)return;const b=e.length?N.LaneHelper.calculateSubWaypoints(s,e):[];b.forEach(T=>T.important=!0);let c=N.LaneHelper.simplifyRouteToCoordinates(g,b,0),p=0,f=0,h=0,k=0;const j={hours:[],wps:[],days:[]};t=w(t).utc();const x=t.clone();for(;c.length>0;){const T=u-t.hour()%u;let B=Math.ceil(t.clone().add(T,"h").set({minute:0,second:0,millisecond:0}).diff(t,"h",!0)*1e4)/1e4;B=t.clone().add(B,"h").isSameOrAfter(a)?a.diff(t,"h",!0)*1e4/1e4:B;const R=await W.speedLoseInHoursStep(S,t,x,B,p,c,r,l,d,y);if(($=R.from)!=null&&$.speed&&(j.hours.push(R.from),R!=null&&R.wps&&j.wps.push(...R.wps),j.days.push(...R.days)),c=R==null?void 0:R.next,c.length||j.hours.push(R==null?void 0:R.to),p+=Math.round((((tt=R==null?void 0:R.to)==null?void 0:tt.distanceFromPrevious)??0)*1e4)/1e4,!B)break}j.wps=(et=j.wps)==null?void 0:et.reduce((T,B)=>(T.some(R=>Math.round(w(R.etd).unix()/60)===Math.round(w(B.etd).unix()/60))||T.push(B),T),[]),(O=j.wps)==null||O.forEach((T,B)=>{const R=j.wps[B-1];if(R){const gt=T.distanceFromStart-R.distanceFromStart,wt=w(T.eta||T.etd).diff(w(R.etd||R.eta),"h",!0);T.avgSpd=Math.round(gt/wt*100)/100;const kt=N.LaneHelper.calculateBearing(R,T);R.bearing=kt}});const Y=j.hours;for(let T=0;T<Y.length-1;T++){const B=w(Y[T+1].eta).diff(Y[T].etd,"hour",!0);f+=Y[T].wxFactor*B,h+=Y[T].cFactor*B,k+=B}const F=j.hours.at(0),L=j.hours.at(-1),H=await N.LaneHelper.calculateRangeRoute(F,L,g),E=await N.LaneHelper.calculateRangeWaypoints(F,L,g,b),P={sample:j,distance:Math.round(((L==null?void 0:L.distanceFromStart)||0)*1e4)/1e4,etd:w(F.eta).utc().format(),eta:w(L==null?void 0:L.eta).utc().format(),wxFactor:Math.round(f/k*1e3)/1e3,cFactor:Math.round(h/k*1e3)/1e3,avgSpeed:Math.round(((L==null?void 0:L.distanceFromStart)||0)/k*1e3)/1e3,totalHrs:Math.round(k*1e3)/1e3,from:F,to:L,route:H,waypoints:E,v0:M,label:C},{distanceInECA:V,hoursInECA:J,totalDgoConsInECA:st,eca:ot}=await this.calculateECA(P,n,y),it=N.LngLatHelper.roundPrecision(n.fo/24*(k-J),3),at=N.LngLatHelper.roundPrecision(n.dgo/24*k,3);P.extend={eca:ot,distanceInECA:V,hoursInECA:J,totalDgoConsInECA:st},P.totalDgoCons=at,P.totalFoCons=it<0?0:it;const X=w().valueOf()-v,Q=((z=j==null?void 0:j.hours)==null?void 0:z.length)||1;return I==null||I.debug("[%s] each hour-sample speed analyse cost: (%d / %d = %d) ms",y==null?void 0:y.requestId,X,Q,Math.round(X/Q*1e3)/1e3),P}static async analyseCost(s,t,a,i,n={}){var g,b;const o=w().valueOf(),e=[];s.speedStep=s.speedStep||3,s.alterStep=s.alterStep??1;const r=N.LaneHelper.calculateRouteDistance(i.route);let u=0;a.forEach(c=>{const p=Math.ceil(r/c.speed/24);u=u<p?p:u}),u=u*1.3;const l=w.utc(s.etd).add(u??14,"day");let d=1;for(const c of a){const p=JSON.parse(JSON.stringify(i.route)),f=JSON.parse(JSON.stringify(i.waypoints)),h=await W.analyseInstantWithThreshed({lat:s.lat,lng:s.lng},s.etd,l,t,c,p,f,s.meteoVendor,s.speedStep,s.useMeteo,s.useRouteParam,n);h&&(await W.calculateCost(h,c,s,n),e.push(h),I==null||I.info("[%s][L%d-%d] analyse from %s to %s cost: %j",n.requestId,1,d,s.etd,l.format(),{cost:h.cost.total,hire:h.cost.hire,bunker:h.cost.bunker,distance:h.distance,hours:h.totalHrs,cp:`${c.speed}/${c.fo}/${c.dgo}`})),d++}e.sort((c,p)=>c.cost.total-p.cost.total);const y=e.at(0),v=e.at(1),M=[];if(M.push({combined:!1,speeds:[y],cost:(g=y.cost)==null?void 0:g.total}),v){const c=y.cost.cp,p=v.cost.cp,f=w(y.eta),h=w(y.etd),k=f.diff(h,"days",!0);let j=Math.ceil(k/2);j=j>7?7:j<s.alterStep?s.alterStep:j;let x=2,Y={combined:!1,speeds:[v],cost:(b=v.cost)==null?void 0:b.total},F;for(;j>=s.alterStep;){const L=await W.combinedAnalyse(s,t,l,[c,p],i,j,{...n,level:x});if(Y.cost>L.cost?F?(F==null?void 0:F.cost)>L.cost&&(F=L):(F=Y,Y=L):(!F||(F==null?void 0:F.cost)>L.cost)&&(F=L),j<=s.alterStep)break;j=Math.ceil(j/2),x+=1}M.push(Y),F&&M.push(F)}const S=w().valueOf()-o;return I==null||I.info("[%s] analyse elapsed: %d ms",n==null?void 0:n.requestId,S),M.sort((c,p)=>c.cost-p.cost)}static async combinedAnalyse(s,t,a,i,n,o,e={}){e.counter=1,I==null||I.info("[%s][L%d] analyse with alternate cp in every %d days",e.requestId,e.level,o);const r=await W.alternateAnalyse(s,t,a,i,0,n,o,e),u=r.reduce((p,f)=>p+f.cost.total,0),l=r.reduce((p,f)=>p+f.cost.hire,0),d=r.reduce((p,f)=>p+f.cost.bunker,0),y=r.reduce((p,f)=>p+f.distance,0),v=r.reduce((p,f)=>p+f.totalHrs,0);I==null||I.info("[%s][L%d] cost with cpa/cpb turn: %j",e.requestId,e.level,{cost:u,hire:l,bunker:d,distance:y,hours:v});const M=await W.alternateAnalyse(s,t,a,i,1,n,o,e),C=M.reduce((p,f)=>p+f.cost.total,0),S=M.reduce((p,f)=>p+f.cost.hire,0),g=M.reduce((p,f)=>p+f.cost.bunker,0),b=M.reduce((p,f)=>p+f.distance,0),c=M.reduce((p,f)=>p+f.totalHrs,0);return I==null||I.info("[%s][L%d] cost with cpb/cpa turn: %j",e.requestId,e.level,{cost:C,hire:S,bunker:g,distance:b,hours:c}),u<C?{combined:!0,cost:Math.round(u*1e3)/1e3,speeds:r,step:o}:{combined:!0,cost:Math.round(C*1e3)/1e3,speeds:M,step:o}}static async alternateAnalyse(s,t,a,i,n,o,e,r={}){var y,v;let u=w.utc(s.etd);const l={lat:s.lat,lng:s.lng},d=[];for(;u.isBefore(a);){const M=u.clone().utc().add(e,"day"),C=JSON.parse(JSON.stringify(o.route)),S=JSON.parse(JSON.stringify(o.waypoints)),g=i[n],b=await W.analyseInstantWithThreshed(l,u.utc().format(),M,t,g,C,S,s.meteoVendor,s.speedStep,s.useMeteo,s.useRouteParam,r);b&&(await W.calculateCost(b,g,s,r),I==null||I.info("[%s][L%d-%d] analyse from %s to %s cost: %j",r.requestId,r.level,r.counter,u.utc().format(),M.utc().format(),{cost:b.cost.total,hire:b.cost.hire,bunker:b.cost.bunker,distance:b.distance,hours:b.totalHrs,cp:`${g.speed}/${g.fo}/${g.dgo}`})),r.counter=r.counter+1;const c=(v=(y=b==null?void 0:b.sample)==null?void 0:y.hours)==null?void 0:v.at(-1);if(c)l.lat=c.lat,l.lng=c.lng,u=w(c.eta),d.push(b),n=n?0:1;else break}return d}static async calculateCost(s,t,a,i={}){var n;if(s){const o=(a.addComm||0)>=1?(a.addComm||0)/100:a.addComm||0,e=Math.round(s.totalHrs/24*(a.dailyHire||0)*(1-o)*1e3)/1e3,r=Math.round(s.totalFoCons*(a.priceFO||0)*1e3)/1e3,u=Math.round((s.totalDgoCons+(((n=s.extend)==null?void 0:n.totalDgoConsInECA)||0))*(a.priceDGO||0)*1e3)/1e3;s.cost={total:Math.round((e+r+u)*1e3)/1e3,hire:e,bunker:Math.round((r+u)*1e3)/1e3,cp:t}}return s}static async calculateECA(s,t,a={}){var r,u,l,d;const i=await N.LaneHelper.intersectInECA((s==null?void 0:s.route)||[]);let n=0,o=0,e=0;(u=(r=s==null?void 0:s.sample)==null?void 0:r.wps)==null||u.forEach(y=>{y.positionTime=w.utc(y.etd||y.eta).unix()});for(const y of i){n+=y.distance;const v=await N.LaneHelper.deadReckoningTime((l=y.waypoints)==null?void 0:l.at(0),s.sample.wps),M=await N.LaneHelper.deadReckoningTime((d=y.waypoints)==null?void 0:d.at(-1),s.sample.wps);y.in=v,y.out=M,y.totalHrs=N.LngLatHelper.roundPrecision((M.positionTime-v.positionTime)/3600,3),y.totalDgoCons=N.LngLatHelper.roundPrecision(t.fo/24*y.totalHrs,3),o+=y.totalHrs,e+=y.totalDgoCons}return n=N.LngLatHelper.roundPrecision(n,3),o=N.LngLatHelper.roundPrecision(o,3),e=N.LngLatHelper.roundPrecision(e,3),{distanceInECA:n,hoursInECA:o,totalDgoConsInECA:e,eca:i}}static async mergeSpeeds(s,t={}){var c,p;const a={hours:[],wps:[],days:[]},i=s.reduce((f,h)=>f+h.distance,0),n=s.reduce((f,h)=>{var k;return f+(((k=h.extend)==null?void 0:k.distanceInECA)||0)},0),o=s.reduce((f,h)=>f+h.totalHrs,0),e=s.reduce((f,h)=>{var k;return f+(((k=h.extend)==null?void 0:k.hoursInECA)||0)},0),r=s.reduce((f,h)=>{var k;return f+(((k=h.extend)==null?void 0:k.totalDgoConsInECA)||0)},0),u=s.reduce((f,h)=>f+h.wxFactor*h.totalHrs/o,0),l=s.reduce((f,h)=>f+h.cFactor*h.totalHrs/o,0),d=s.reduce((f,h)=>f+h.totalFoCons,0),y=s.reduce((f,h)=>f+h.totalDgoCons,0),v=s.reduce((f,h)=>f+h.cost.total,0),M=s.reduce((f,h)=>f+h.cost.hire,0),C=s.reduce((f,h)=>f+h.cost.bunker,0),S=[],g=[];let b;for(const f of s){g.push(...((c=f.extend)==null?void 0:c.eca)||[]);const h=f.sample.hours,k=f.sample.wps,j=f.sample.days,x=h.at(0);b&&(x.distanceFromPrevious=b.distanceFromPrevious,x.distanceFromStart=b.distanceFromStart,h.forEach((H,E)=>{E&&(H.distanceFromStart=H.distanceFromStart+b.distanceFromStart)}),k.at(0).distanceFromPrevious=b.distanceFromPrevious,k.at(0).distanceFromStart=b.distanceFromStart,k.forEach((H,E)=>{E&&(H.distanceFromStart=H.distanceFromStart+b.distanceFromStart)}),j.at(0).distanceFromPrevious=b.distanceFromPrevious,j.at(0).distanceFromStart=b.distanceFromStart,j.forEach((H,E)=>{E&&(H.distanceFromStart=H.distanceFromStart+b.distanceFromStart)})),x.cp=f.cost.cp;const Y=[f.etd,f.eta],F=S.findIndex(H=>H.id===x.cp.id);F===-1?(x.cp.segment=[Y],S.push(x.cp)):S[F].segment.push(Y),h.forEach(H=>{var P;((P=a.hours)==null?void 0:P.findIndex(V=>V.eta===H.eta))===-1&&a.hours.push(H)}),k.forEach(H=>{var P;((P=a.wps)==null?void 0:P.findIndex(V=>V.eta===H.eta))===-1&&a.wps.push(H)}),j.forEach(H=>{var P;((P=a==null?void 0:a.days)==null?void 0:P.findIndex(V=>V.eta===H.eta))===-1&&a.days.push(H)});const L=(p=a.wps)==null?void 0:p.findIndex(H=>H.eta===x.eta);L===-1?a.wps.push(x):a.wps[L]=x,b=h.at(-1)}return a.wps.sort((f,h)=>{w(f.etd).unix()-w(h.etd).unix()}),a.wps.forEach((f,h)=>{const k=a.wps[h-1];if(k){const j=f.distanceFromStart-(k.distanceFromStart||0),x=w(f.eta||f.etd).diff(w(k.etd||k.eta),"hour",!0),Y=Math.round(j/x*100)/100;f.avgSpd=Y;const F=N.LaneHelper.calculateBearing(k,f);k.bearing=F}}),{sample:a,etd:s.at(0).etd,eta:s.at(-1).eta,from:s.at(0).from,to:s.at(-1).to,v0:s.at(0).v0,label:"Combined",distance:Math.round(i*1e3)/1e3,totalHrs:Math.round(o*1e3)/1e3,avgSpeed:Math.round(i/o*1e3)/1e3,wxFactor:Math.round(u*1e3)/1e3,cFactor:Math.round(l*1e3)/1e3,totalFoCons:Math.round(d*1e3)/1e3,totalDgoCons:Math.round(y*1e3)/1e3,cost:{total:Math.round(v*1e3)/1e3,hire:Math.round(M*1e3)/1e3,bunker:Math.round(C*1e3)/1e3},extend:{cps:S,eca:g,distanceInECA:Math.round(n*1e3)/1e3,hoursInECA:Math.round(e*1e3)/1e3,totalDgoConsInECA:Math.round(r*1e3)/1e3,speeds:s}}}}q.AISImpl=G,q.AlertHelper=dt,q.AlertLevel=ct,q.HifleetImpl=yt,q.LoadCondition=lt,q.MyShipImpl=pt,q.MyVesselImpl=mt,q.ShipxyImpl=Mt,q.SpeedHelper=W,q.SpeedLabel=ht,q.VesselTag=ut,q.alertHelper=bt,Object.defineProperty(q,Symbol.toStringTag,{value:"Module"})});
1
+ (function(P,D){typeof exports=="object"&&typeof module<"u"?D(exports,require("got"),require("@log4js-node/log4js-api"),require("moment"),require("@idm-plugin/geo2"),require("@idm-plugin/meteo2"),require("@idm-plugin/meteo")):typeof define=="function"&&define.amd?define(["exports","got","@log4js-node/log4js-api","moment","@idm-plugin/geo2","@idm-plugin/meteo2","@idm-plugin/meteo"],D):(P=typeof globalThis<"u"?globalThis:P||self,D(P["idm-plugin-vessel"]={},P.got,P["@log4js-node/log4js-api"],P.moment,P["@idm-plugin/geo2"],P["@idm-plugin/meteo2"],P["@idm-plugin/meteo"]))})(this,function(P,D,U,v,H,pt,it){"use strict";var Ct=Object.defineProperty;var jt=(P,D,U)=>D in P?Ct(P,D,{enumerable:!0,configurable:!0,writable:!0,value:U}):P[D]=U;var K=(P,D,U)=>(jt(P,typeof D!="symbol"?D+"":D,U),U);let y;try{y=U.getLogger("vessel")}catch{}finally{}class G{parseStatus(s){let t,a;switch(s){case 0:t="在航(主机推动)",a="Underway Using Engine";break;case 1:t="锚泊",a="Anchored";break;case 2:t="失控",a="Not under command";break;case 3:t="操纵受限",a="Limited airworthiness";break;case 4:t="吃水受限",a="Limited by ship's draft";break;case 5:t="靠泊",a="Mooring";break;case 6:t="搁浅",a="Stranded";break;case 7:t="捕捞作业",a="Engaged in fishing";break;case 8:t="靠帆船提供动力",a="Sailing";break;default:t="未定义",a="Undefined"}return{labelCn:t,labelEn:a}}}class Mt extends G{constructor(t,a){super();K(this,"clientId");K(this,"clientSecret");K(this,"token");this.clientId=t,this.clientSecret=a}async authToken(t={}){const a="https://svc.data.myvessel.cn/ada/oauth/token",i={searchParams:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials"}},n=await D.post(a,i).json();y==null||y.info("[%s] fetch access token from: %s - %j",t.requestId,a,n),n.error||(this.token={accessToken:n.access_token,tokenType:n.token_type,expiresIn:n.expires_in,scope:n.scope,jti:n.jti,issuedAt:v().utc().format()})}async checkToken(t={}){var a;return(!this.token||v().diff(v(this.token.issuedAt),"seconds")>(((a=this.token)==null?void 0:a.expiresIn)||0)-300)&&await this.authToken(t),this.token}async suggest(t,a={}){var e,r;await this.checkToken(a);const i="https://market.myvessel.cn/sdc/v1/mkt/vessels/fuzzy",n={headers:{Authorization:`${(e=this.token)==null?void 0:e.tokenType} ${(r=this.token)==null?void 0:r.accessToken}`},json:{kw:t,recordNum:a.ps||10}};y==null||y.info("[%s] fetch suggest vessels from: %s - %j",a.requestId,i,n);const o=await D.post(i,n).json();return o.status!==200?(y==null||y.warn("[%s] fetch suggest vessels failed: %j",a.requestId,{message:o.message,status:o.status,code:o.code}),[]):(o.data||[]).map(l=>({mmsi:l.mmsi,name:l.nameEn,nameCn:l.nameCn,imo:Number.isNaN(l.imo)?null:Number(l.imo),callSign:l.callsign,type:l.vesselTypeNameEn,flagName:l.flagCtry,vendor:"myvessel",raw:l}))}async search(t,a={}){var d,l;await this.checkToken(a);const i=/^\d{7}$/.test(t.toString()),n=i?"https://market.myvessel.cn/sdc/v1/mkt/vessels/detail/imo":"https://market.myvessel.cn/sdc/v1/mkt/vessels/detail/mmsi",o=i?{imo:t}:{mmsi:t},e={headers:{Authorization:`${(d=this.token)==null?void 0:d.tokenType} ${(l=this.token)==null?void 0:l.accessToken}`},searchParams:o};y==null||y.info("[%s] fetch vessel from: %s - %j",a.requestId,n,e);const r=await D.get(n,e).json();if(r.status!==200)return y==null||y.warn("[%s] fetch suggest vessels failed: %j",a.requestId,{message:r.message,status:r.status,code:r.code}),{};{const c=r.data;if(c)return{mmsi:c.mmsi,imo:Number.isNaN(c.imo)?null:Number(c.imo),callSign:c.callsign,name:c.nameEn,nameCn:c.nameCn,type:c.vesselTypeNameEn,flagName:c.flagCtry,clasz:c.classSociety,dateOfBuild:c.buildYearMonth,deadweight:c.dwt,grossTonnage:c.grt,netTonnage:c.net,teu:c.teu,length:c.length,breadth:c.width,height:c.height,draught:c.draught,speed:c.speed,passengerCapacity:c.passengercapacity,vendor:"myvessel",raw:c}}return{}}async archives(t,a={}){var e,r;await this.checkToken(a);const i="https://svc.data.myvessel.cn/sdc/v1/ship/info/batch",n={headers:{Authorization:`${(e=this.token)==null?void 0:e.tokenType} ${(r=this.token)==null?void 0:r.accessToken}`},json:{mmsiList:typeof t=="number"?[t]:t}};y==null||y.info("[%s] fetch vessel archive from: %s - %j",a.requestId,i,n);const o=await D.post(i,n).json();return o.status!==200?(y==null||y.warn("[%s] fetch vessel archive failed: %j",a.requestId,{message:o.message,status:o.status,code:o.code}),{}):o.data}async realTimePosition(t,a={}){var r,d;await this.checkToken(a);const i="https://svc.data.myvessel.cn/sdc/v1/vessels/status/location/unit",n={headers:{Authorization:`${(r=this.token)==null?void 0:r.tokenType} ${(d=this.token)==null?void 0:d.accessToken}`},searchParams:{mmsi:t}};y==null||y.info("[%s] fetch realtime position from: %s - %j",a.requestId,i,n);const o=await D.get(i,n).json();if(o.code)return y==null||y.warn("[%s] fetch realtime position failed: %j",a.requestId,{message:o.message,status:o.status,code:o.code}),o;const e=o.data;for(const l in e)!isNaN(e[l])&&Number(e[l])!==1/0&&(e[l]=Number(e[l]));if(e){const l=v(`${e.postime} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");return{mmsi:e.mmsi,name:e.vesselName||e.aisVesselName,imo:e.imo,callSign:e.callsign||e.aisCallSign,lat:e.lat,lng:e.lon,length:e.length,width:e.width,draught:e.currDraught,sog:e.sog,cog:e.cog,hdg:e.hdg,rot:e.rot,eta:/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e.eta)?v.utc(e.eta).format():void 0,destination:e.dest,positionTime:l.unix(),status:e.status,labelCn:e.statusNameCn,labelEn:e.statusNameEn,vesselType:e.vesselTypeNameEn,flag:e.flagCtryNameEn,clasz:e.classSociety,build:e.buildYear,dwt:e.dwt,grt:e.grt,net:e.net,method:"position",vendor:"myVessel",utc:l.utc().format()}}else return{}}async calculateRoute(t,a,i={}){var r,d;await this.checkToken(i);const n="https://svc.data.myvessel.cn/sdc/v1/routes/routing/nodes",o={headers:{Authorization:`${(r=this.token)==null?void 0:r.tokenType} ${(d=this.token)==null?void 0:d.accessToken}`},json:{startPoint:{lon:t.lng,lat:t.lat},endPoint:{lon:a.lng,lat:a.lat},maxDraught:i.maxDraught||10,useAIModel:i.useAIModel||!1,withECA:i.withECA||!1}};y==null||y.info("[%s] fetch route from: %s - %j",i.requestId,n,o);const e=await D.post(n,o).json();return e.status!==200?(y==null||y.warn("[%s] fetch route failed: %j",i.requestId,{message:e.message,status:e.status,code:e.code}),{}):e.data}async trajectory(t,a,i,n,o=!0,e={}){await this.checkToken(e);const r=await this.realTimePosition(t,e),d=v(a),l=v(i),c=[];for(;l.diff(d,"day",!0)>30;)await this.trajectoryIn30Day(t,d,d.clone().add(30,"day"),r,n,c,e),d.add(30,"day");return await this.trajectoryIn30Day(t,d,l,r,n,c,e),c}async trajectoryIn30Day(t,a,i,n,o,e,r={}){var M,j,F,b,g;const d="https://svc.data.myvessel.cn/sdc/v1/vessels/status/track",l={headers:{Authorization:`${(M=this.token)==null?void 0:M.tokenType} ${(j=this.token)==null?void 0:j.accessToken}`},json:{mmsi:t,startTime:a.utcOffset(8).format("YYYY-MM-DD HH:mm:ss"),endTime:i.utcOffset(8).format("YYYY-MM-DD HH:mm:ss")}};y==null||y.info("[%s] fetch trajectory from: %s - %j",r.requestId,d,l);const c=await D.post(d,l).json();if(c.code)return y==null||y.warn("[%s] fetch trajectory failed: %j",r.requestId,d,{message:c.message,status:c.status,code:c.code}),c;let p=-1;const w=v(`${(b=(F=c.data)==null?void 0:F[0])==null?void 0:b.postime} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");return(g=c.data)==null||g.forEach(m=>{for(const Y in m)!isNaN(m[Y])&&Number(m[Y])!==1/0&&(m[Y]=Number(m[Y]));const u=v(`${m.postime} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00"),h=m.status,{labelCn:f,labelEn:k}=this.parseStatus(h),I={mmsi:m.mmsi,imo:n==null?void 0:n.imo,lat:m.lat,lng:m.lon,sog:m.sog,cog:m.cog,hdg:m.hdg,draught:m.draught,status:h,eta:/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(m.eta)?v(`${m.eta} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00").utc().format():void 0,destination:m.dest,positionTime:u.unix(),labelCn:f,labelEn:k,method:"trajectory",vendor:"myVessel",utc:u.utc().format()},E=Math.floor(u.diff(w,"minute",!0)/(o||1));E!==p&&(p=E,e.push(I))}),e}}class bt extends G{constructor(t){super();K(this,"token");this.token=t}async realTimePosition(t,a={}){const i="https://api.hifleet.com/position/position/get/token",n={searchParams:{mmsi:t,usertoken:this.token}},o=await D.post(i,n).json();y==null||y.info("[%s] fetch realtime position from: %s - %j",a.requestId,i,n);const e=o==null?void 0:o.list;if(!e)return y==null||y.warn("[%s] fetch realtime position failed: %j",a.requestId,i,o),o;for(const w in e)!isNaN(e[w])&&Number(e[w])!==1/0&&(e[w]=Number(e[w]));e.status=e.sp>3?0:1;const r=e.status,{labelCn:d,labelEn:l}=this.parseStatus(r),c=v(`${e.ti} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");return{mmsi:e.m,name:e.n,imo:e.imonumber,callSign:e.callsign,lat:Math.round(e.la/60*1e5)/1e5,lng:Math.round(e.lo/60*1e5)/1e5,length:e.l,width:e.w,draught:e.draught,sog:e.sp,cog:e.co,hdg:e.h,rot:isNaN(e.rot)?0:e.rot,eta:/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e.eta)?v.utc(e.eta).format():void 0,destination:e.destination,vesselType:e.type,dwt:e.dwt,build:e.buildyear,flag:e.fn,positionTime:c.unix(),utc:c.utc().format(),status:r,labelCn:d,labelEn:l,method:"position",vendor:"hifleet"}}async search(t,a={}){let i="https://www.hifleet.com/hifleetapi/searchVesselOL.do";const n={searchParams:{keyword:t},headers:{Referer:"https://www.hifleet.com",Origin:"https://www.hifleet.com",Host:"www.hifleet.com"}};let o=await D.post(i,n).json();y==null||y.info("[%s] fetch vessel props from: %s - %j",a.requestId,i,n),o instanceof Array&&(o=o[0]);for(const r in o)!isNaN(o[r])&&Number(o[r])!==1/0&&(o[r]=Number(o[r]));const e={mmsi:o.m,name:o.n,imo:o.i,callSign:o.c,length:o.l,breadth:o.b,draught:o.dr,type:o.t};return i="https://www.hifleet.com/hifleetapi/sameShipSearch.do",o=await D.post(i,n).json(),y==null||y.info("[%s] search vessel dead weight from: %s - %j",a.requestId,i,n),o instanceof Array&&(o=o[0]),o&&(e.deadweight=Number(o.dwt)),e}async suggest(t,a={}){const i="https://www.hifleet.com/hifleetapi/getShipSuggest.do",n={searchParams:{q:t},headers:{Referer:"https://www.hifleet.com",Origin:"https://www.hifleet.com",Host:"www.hifleet.com"}},o=await D.post(i,n).json();y==null||y.info("[%s] suggest vessel props from: %s - %j",a.requestId,i,n);const e=[];for(const r of o)e.push({mmsi:!r.mmsi||isNaN(r.mmsi)?null:Number(r.mmsi),name:r.name,callSign:r.callsign,imo:!r.imo||isNaN(r.imo)?null:Number(r.imo),score:r._score});return e.sort((r,d)=>d.score-r.score),e}async trajectory(t,a,i,n,o=!0,e={}){var m,u,h;const r=await this.realTimePosition(t,e);let d=v(a);const l=v(i),c=v();if(o){let f=l.diff(d,"d",!0);f<0?d=l.clone().subtract(40,"d"):f<30?d.subtract(10,"d"):f<60?d.subtract(5,"d"):d=l.clone().subtract(80,"d"),f=c.diff(l,"d",!0),l.add(f>10?240:f*24,"h")}const p={searchParams:{endtime:l.utcOffset("+8:00").format("YYYY-MM-DD HH:mm:ss"),starttime:d.utcOffset("+8:00").format("YYYY-MM-DD HH:mm:ss"),mmsi:t,usertoken:this.token}},w="https://api.hifleet.com/position/trajectory/nocompressed/withstatic/token",M=await D.get(w,p).json();y==null||y.info("[%s] fetch trajectory from: %s - %j",e.requestId,w,p);let j;M&&(j=((u=(m=M.ships)==null?void 0:m.offors)==null?void 0:u.ship)||[],j.length||y==null||y.warn("[%s] fetch trajectory failed: %j",e.requestId,M));const F=[];let b=-1;const g=v(`${(h=j==null?void 0:j[0])==null?void 0:h.ti} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");for(const f of j){for(const R in f)!isNaN(f[R])&&Number(f[R])!==1/0&&(f[R]=Number(f[R]));const k=v(`${f.ti} +08:00`,"YYYY-MM-DD HH:mm:ss +08:00");f.status=f.sp>4?0:1;const{labelEn:I,labelCn:E}=this.parseStatus(f.status),Y={mmsi:f.m,name:f.n,imo:r==null?void 0:r.imo,lat:f.la,lng:f.lo,draught:f.draught,sog:f.sp,cog:f.co,hdg:f.hdg,positionTime:k.unix(),utc:k.utc().format(),status:f.status,labelCn:E,labelEn:I,method:"trajectory",vendor:"hifleet"},x=Math.floor(k.diff(g,"minute",!0)/(n||1));x!==b&&(b=x,F.push(Y))}return F}}class vt extends G{constructor(t){super();K(this,"token");this.token=t}async realTimePosition(t,a={}){const i={searchParams:{id:t,k:this.token,enc:1}},n="https://api.shipxy.com/apicall/GetSingleShip",o=await D.get(n,i).json();if(y==null||y.info("[%s] fetch realtime position from: %s - %j",a.requestId,n,i),(o==null?void 0:o.status)!==0)return o;const e=o.data[0];for(const p in e)!isNaN(e[p])&&Number(e[p])!==1/0&&(e[p]=Number(e[p]));const{labelCn:r,labelEn:d}=await this.parseStatus(e.navistat),l=v.unix(e.lasttime);return{mmsi:e.ShipID,name:e.name,imo:e.imo,callSign:e.callsign,lat:Math.round(e.lat/1e6*1e5)/1e5,lng:Math.round(e.lon/1e6*1e5)/1e5,length:Math.round(e.length/10*100)/100,width:Math.round(e.width/10*100)/100,draught:Math.round(e.draught/1e3*100)/100,sog:Math.round(e.sog*3600/1e3/1852*100)/100,cog:Math.round(e.cog/100*100)/100,hdg:Math.round(e.hdg/100*100)/100,rot:Math.round(e.rot/100*100)/100,positionTime:e.lasttime,utc:l.utc().format(),status:e.navistat,labelEn:d,labelCn:r,method:"position",vendor:"shipxy"}}async trajectory(t,a,i,n,o=!0,e={}){var g;const r=await this.realTimePosition(t,e),d=v(a),l=v(i),c="https://api.shipxy.com/apicall/GetShipTrack",p={searchParams:{id:t,k:this.token,enc:1,cut:0,btm:d.unix(),etm:l.unix()}},w=await D.get(c,p).json();if(y==null||y.info("[%s] fetch trajectory from: %s - %j",e.requestId,c,p),(w==null?void 0:w.status)!==0)return w;const M=w==null?void 0:w.points,j=[],F=v.unix((g=M[0])==null?void 0:g.utc);let b=-1;for(const m of M){const u=v.unix(m.utc),h={imo:r==null?void 0:r.imo,mmsi:t,sog:Math.round(m.sog*3600/1e3/1852*100)/100,cog:Math.round(m.cog/100*100)/100,lat:Math.round(m.lat/1e6*1e5)/1e5,lng:Math.round(m.lon/1e6*1e5)/1e5,positionTime:u.unix(),utc:u.utc().format(),method:"trajectory",vendor:"shipxy"},f=Math.floor(u.diff(F,"minute",!0)/(n||1));f!==b&&(b=f,j.push(h))}return j}}class gt extends G{constructor(t){super();K(this,"token");this.token=t}async getShipId(t,a={}){const i={headers:{appKey:this.token},json:{mmsiList:t}},n="https://api3.myships.com/sp/ships/getShipIdByMMSI",o=await D.post(n,i).json();return y==null||y.info("[%s] fetch ship id from: %s - %j",a.requestId,n,i),o.code!=="0"?o:o.data[0].shipId}async getShipInfo(t,a={}){const i={headers:{appKey:this.token},json:{shipId:t}},n="https://api3.myships.com/sp/ships/aissta",o=await D.post(n,i).json();if(y==null||y.info("[%s] fetch ship info from: %s - %j",a.requestId,n,i),o.code!=="0")return o;const e=o.data;let r=e.imo;return t==="407170"&&(r="9198379",y==null||y.warn("[%s] ship(%s) imo error: %s, should be %s",a.requestId,t,e.imo,r)),{mmsi:e.mmsi,name:e.shipnameEn,imo:r,callSign:e.callSign,length:e.length,width:e.breadth,draught:(e.draught||100)/10}}async realTimePosition(t,a={}){const i=await this.getShipId(t,a),n=await this.getShipInfo(i,a),o={headers:{appKey:this.token},json:{shipId:i}},e="https://api3.myships.com/sp/ships/position/latest",r=await D.post(e,o).json();y==null||y.info("[%s] fetch realtime position from: %s - %j",a.requestId,e,o);const d=r.data[0];for(const M in d)!isNaN(d[M])&&Number(d[M])!==1/0&&(d[M]=Number(d[M]));const{labelCn:l,labelEn:c}=await this.parseStatus(d.aisNavStatus),p=v.unix(d.posTime);return{...n,mmsi:t,lat:Math.round(d.lat/1e4/60*1e5)/1e5,lng:Math.round(d.lon/1e4/60*1e5)/1e5,sog:Math.round(d.sog/10*100)/100,cog:Math.round(d.cog/10*100)/100,hdg:Math.round(d.heading*100)/100,rot:Math.round(d.rot*100)/100,positionTime:d.posTime,utc:p.utc().format(),status:d.aisNavStatus,labelEn:c,labelCn:l,method:"position",vendor:"myship"}}async trajectory(t,a,i,n,o=!0,e={}){const r=v(a),d=v(i),l=await this.getShipId(t),c=await this.getShipInfo(l),p=[];for(;d.diff(r,"day",!0)>30;)await this.trajectoryIn30Day(l,r.unix(),r.add(30,"day").unix(),c,t,n,p);return await this.trajectoryIn30Day(l,r.unix(),d.unix(),c,t,n,p),p}async trajectoryIn30Day(t,a,i,n,o,e,r,d={}){var F;const l={headers:{appKey:this.token},json:{shipId:t,startTime:a,endTime:i}},c="https://api3.myships.com/sp/ships/position/history",p=await D.post(c,l).json();if(y==null||y.info("[%s] fetch trajectory from: %s - %j",d.requestId,c,l),p.code!=="0")return y==null||y.warn("[%s] invoke myship trajectory failed: %j",d.requestId,p),p;const w=p.data;for(const b in w)!isNaN(w[b])&&Number(w[b])!==1/0&&(w[b]=Number(w[b]));const M=v.unix((F=w[0])==null?void 0:F.posTime);let j=-1;for(const b of w){const g=v.unix(b.posTime),m={imo:n==null?void 0:n.imo,mmsi:o,lat:Math.round(b.lat/1e4/60*1e5)/1e5,lng:Math.round(b.lon/1e4/60*1e5)/1e5,sog:Math.round(b.sog/10*100)/100,cog:Math.round(b.cog/10*100)/100,hdg:Math.round(b.heading*100)/100,rot:Math.round(b.rot*100)/100,positionTime:g.unix(),utc:g.utc().format(),method:"trajectory",vendor:"myship"},u=Math.floor(g.diff(M,"minute",!0)/(e||1));u!==j&&(j=u,r.push(m))}return r}}let _;try{_=U.getLogger("vessel")}catch{}finally{}var lt=(A=>(A.NOTICE="NOTICE",A.WARN="WARN",A.HEAVY="HEAVY",A.SEVERE="SEVERE",A.ERROR="ERROR",A.FATAL="FATAL",A))(lt||{});class ht{parsePrinciple(s,t={}){var e,r,d;_==null||_.debug("[%s] parse rule: %s",t.requestId,s);const a=new RegExp("(?<=\\[)(.+)(?=])","g"),i=s.match(a)?(e=s.match(a))==null?void 0:e[0]:void 0,n=i==null?void 0:i.split(";");if(!n)return;const o={};for(let l=0;l<(n==null?void 0:n.length);l++){const c=(d=(r=n[l].match(a))==null?void 0:r[0])==null?void 0:d.split("],");if(l===0&&!c)o.scope=n[0];else if(c)for(let p=0,w=c.length;p<w;p++){const M=this.parseRule(c[p]);M&&(o[M.level]?M.key?o[M.level][M==null?void 0:M.key]=M:o[M.level]=M:M.key?o[M.level]={[M==null?void 0:M.key]:M}:o[M.level]=M)}}return o}parseRule(s,t={}){var o;_==null||_.debug("[%s] parse rule: %s",t.requestId,s),s=s.startsWith("[")?s:`[${s}`,s=s.endsWith("]")?s:`${s}]`;const a=new RegExp("(?<=\\[)(.+?)(?=])","g"),i=(o=s==null?void 0:s.match(a))==null?void 0:o[0],n=i==null?void 0:i.split(",");if(n){let e=n[3]==="Number.MAX_VALUE"?100:Number(n[3]);return e=isNaN(e)?1:e,{operator:n[0],number:Number.isNaN(Number(n[1]))?n[1]:Number(n[1]),level:n[2],time:e,key:n[4]}}}checkWeather(s,t,a={}){var M,j,F,b,g,m,u,h,f,k,I,E,Y,x,R;let i=0,n=0,o=0,e=0;const r=Math.round(((j=(M=t==null?void 0:t.SEVERE)==null?void 0:M.sigWave)==null?void 0:j.number)*1.6*100)/100,d=(b=(F=t==null?void 0:t.SEVERE)==null?void 0:F.sigWave)==null?void 0:b.number,l=(m=(g=t==null?void 0:t.HEAVY)==null?void 0:g.sigWave)==null?void 0:m.number,c=Math.round((((h=(u=t==null?void 0:t.SEVERE)==null?void 0:u.wind)==null?void 0:h.number)+2)*100)/100,p=(k=(f=t==null?void 0:t.SEVERE)==null?void 0:f.wind)==null?void 0:k.number,w=(E=(I=t==null?void 0:t.HEAVY)==null?void 0:I.wind)==null?void 0:E.number;for(let T=0;T<(s==null?void 0:s.length);T++){const N=s[T],W=(x=(Y=N==null?void 0:N.meteo)==null?void 0:Y.wave)==null?void 0:x.sig,V=(R=N==null?void 0:N.meteo)==null?void 0:R.wind,J=T?v(N.eta).diff(v(s[T-1].eta),"hour",!0):0;e=J>e?J:e,_==null||_.debug("[%s] check sig.wave: %j",a.requestId,{...W,dgThd4Wv:r,svThd4Wv:d,hvThd4Wv:l}),(W==null?void 0:W.height)>=r?N.isDangerous=!0:(W==null?void 0:W.height)>=d?N.isSevere=!0:(W==null?void 0:W.height)>=l&&(N.isHeavy=!0),_==null||_.debug("[%s] check wind: %j",a.requestId,{...V,dgThd4Wd:c,svThd4Wd:p,hvThd4Wd:w}),(V==null?void 0:V.scale)>=c?(N.isDangerous=!0,delete N.isSevere,delete N.isHeavy):(V==null?void 0:V.scale)>p?(N.isDangerous||(N.isSevere=!0),delete N.isHeavy):(V==null?void 0:V.scale)===w&&!N.isDangerous&&!N.isSevere&&(N.isHeavy=!0),i+=N.isDangerous?J:0,n+=N.isSevere?J:0,o+=N.isHeavy?J:0}return i=Math.round(i*100)/100,n=Math.round(n*100)/100,o=Math.round(o*100)/100,e=Math.round(e),{sample:s,dangerous:i,severe:n,heavy:o,step:e<3?3:e,wind:{dgThd4Wd:c,svThd4Wd:p,hvThd4Wd:w},sig:{dgThd4Wv:r,svThd4Wv:d,hvThd4Wv:l}}}}const wt=new ht;let C;try{C=U.getLogger("vessel")}catch{}finally{}const It=new pt.MeteoHelper2("",!0);var ft=(A=>(A.common="common",A.container="container",A.tugs="tugs",A))(ft||{}),mt=(A=>(A.Ballast="Ballast",A.Laden="Laden",A))(mt||{}),yt=(A=>(A.Cp="CP",A.Perf="Basis",A.Instruct="Other",A))(yt||{});class B{static blockCoefficient(s,t,a,i){let n=Math.round(s/(t*a*i)*100)/100;n=n<.55?.55:n>.85?.85:n;const o=[.55,.6,.65,.7,.75,.8,.85],e=o.map(r=>Math.abs(r-n));return o[e.indexOf(Math.min(...e))]}static froudeNumber(s,t,a=9.8){let i=Math.round(Math.sqrt(s*s/(a*t))*100)/100;return i=i<.05?.05:i>.3?.3:i,i}static amendFactor(s,t,a){const i={.55:[1.7,-1.4,-7.4],.6:[2.2,-2.5,-9.7],.65:[2.6,-3.7,-11.6],.7:[3.1,-5.3,-12.4],.75:[2.4,-10.6,-9.5],.8:[2.6,-13.1,-15.1],.85:[3.1,-18.7,28]};let o={.55:[1.7,-1.4,-7.4],.6:[2.2,-2.5,-9.7],.65:[2.6,-3.7,-11.6],.7:[3.1,-5.3,-12.4],.75:[2.6,-12.5,-13.5],.8:[3,-16.3,-21.6],.85:[3.4,-20.9,31.8]}[s];return a==="Laden"&&(o=i[s]),o[0]+o[1]*t+o[2]*Math.pow(t,2)}static directionFactor(s,t=0){let a;return s>30&&s<=60?a=(1.7-.03*Math.pow(t-4,2))/2:s>60&&s<=150?a=(.9-.06*Math.pow(t-6,2))/2:s>150&&s<=180?a=(.4-.03*Math.pow(t-8,2))/2:a=1,Math.round(a*1e5)/1e5}static vesselTagFactor(s,t,a,i){let n;return a==="container"?n=.7*i/2+Math.pow(i,3)/(22*Math.pow(s,2/3)):t==="Ballast"?n=.7*i/2+Math.pow(i,3)/(2.7*Math.pow(s,2/3)):n=.5*i/2+Math.pow(i,3)/(2.7*Math.pow(s,2/3)),n}static waveHeightFactor(s,t){s=s<3?s*.7:s,s=s<0?.2:s,s=s>6?s-.9*(s-6):s,s=s>9?9:s;let a;return t>30&&t<=60?a=-.6:t>60&&t<=90?a=-.4:t>90&&t<=120?a=s<3?.4:-.3:t>120&&t<=150?a=s<3?.6:-.5:t>150&&t<=180?a=s<3?.7:-.6:a=-.7,Math.round(a*(.144*Math.pow(s,2)+.278*s)*1e4)/1e4}static assembleProperties(s,t,a,i){var p;const n=s.lbp??s.length??s.lengthOverall??198.9642,o=s.draught??8,e=s.breadthMoulded??s.breadth??s.breadthExtreme??32.4572,r=s.deadweight??67035.7773,d=((p=s==null?void 0:s.type)==null?void 0:p.toLowerCase())||"common";return{tag:d.indexOf("container")>-1?"container":d.indexOf("tugs")>-1?"tugs":"common",lbp:n,loadCondition:t,draught:o,breadthMoulded:e,displacement:Math.round((r/1.025+o*e*n*.7)*1e4)/1e4,speed:Math.round((a??14.1382)*1852/3600*1e4)/1e4,bearing:i||90}}static async speedLoseAt(s,t,a,i="",n=2,o=!0,e=!1,r={}){let d;if(t.velocity&&e&&(s.speed=H.LngLatHelper.roundPrecision(t.velocity*1852/3600,6)),o){let l;try{i=(i==null?void 0:i.toUpperCase())==="CMEMS"?"ECMWF":i,i=(i==null?void 0:i.toUpperCase())==="METEO2"?"best_match":i;const{weatherModels:M,marineModels:j}=await it.Meteo2Assist.autoPickMeteoModel(i),F=await It.spotForecast(t.lat,t.lng,a.utc().format(),!1,!1,!0,{...r,pastDays:1,forecastDays:1,weatherModels:M,marineModels:j}),[b]=it.Meteo2Assist.pickHourly(F,a);l=it.Meteo2Assist.toLegacy(b)}catch(M){C.warn("[%s] meteo2 spot(%j) forecast failed: %s",r.requestId,{...t,eta:a.utc().format(),source:i},M)}const c=B.currentFactor(s.bearing,l==null?void 0:l.current,n),p=B.weatherFactor(s,l,c),w=Math.round((s.speed*1.943844+p+c)*100)/100;d={meteo:{...l},wxFactor:p,cFactor:c,speed:t.velocity&&e?t.velocity:w<0?1:w,eta:a.utc().format(),etd:a.utc().format()}}else d={wxFactor:0,cFactor:0,speed:t.velocity&&e?t.velocity:Math.round(s.speed*1.943844*100)/100,eta:a.utc().format(),etd:a.utc().format()};return delete t.meteo,delete t.wxFactor,delete t.cFactor,delete t.speed,delete t.etd,{...d,...t}}static async speedLoseInHoursStep(s,t,a,i,n,o,e="",r=!0,d=!1,l={}){t.utc();const c=t.clone().add(14,"days"),p=[],w=[],M=[];let j=0,F=0,b,g;for(let m=0;m<o.length-1;m++){let u=o[m];u.distanceFromStart=Math.round((n+F)*1e3)/1e3;const h=o[m+1];if(s.bearing=H.LaneHelper.calculateBearing(u,h,!h.gcToPrevious),u.bearing=s.bearing,u.suspend&&d){u.eta=u.eta||t.utc().format(),u.elapsed=u.elapsed??0;const I=u.suspend-u.elapsed;if(i-j>I)i=i-j-I,t.add(I,"hour"),u.elapsed=u.suspend;else{const E=i-j;u.elapsed+=E,t.add(E,"hour"),i=0}if(C==null||C.info(`[%s] suspend ${u.elapsed} hours at %j, and remain ${i} hours need to go...`,l.requestId,u),i===0)return u.distanceFromPrevious=F,{etd:t,from:g||u,to:u,next:o.filter(E=>E),wps:p,days:w,all:M}}else u.suspend=0;r=t.isAfter(c)?!1:r,u=await B.speedLoseAt(s,u,t,e,0,r,d,l),M.push(u),g=g||u,u.important&&p.push(u),t.isSameOrAfter(a)&&(w.push(u),a.add(24,"hour"));const f=H.LaneHelper.calculateDistance(u,h,!h.gcToPrevious);let k=Math.round(f/g.speed*1e5)/1e5;if(j+k<i){if(j+=k,t.add(k,"hour"),delete o[m],C==null||C.debug(`[%s] go to %j from %j with ${f}nm, and cost ${k} hours`,l.requestId,{lat:h.lat,lng:h.lng},{lat:g.lat,lng:g.lng,etd:g.etd}),F+=f,o.filter(I=>I).length<=1){b=h,b.eta=t.utc().format(),b.distanceFromPrevious=f,b.distanceFromStart=Math.round((n+F)*1e4)/1e4,p.push(b),M.push(b),delete o[m+1];break}}else{k=i-j,t.add(k,"hour");const I=H.LngLatHelper.roundPrecision(g.speed*k,5);b=H.LaneHelper.calculateCoordinate(u,s.bearing,I,"nauticalmiles",!h.gcToPrevious),b.eta=t.utc().format(),o[m]=b,C==null||C.debug(`[%s] go to %j from %j with ${I}nm, and cost ${k} hours`,l.requestId,{lat:b.lat,lng:b.lng},{lat:u.lat,lng:u.lng,etd:u.etd}),F+=I,b.distanceFromPrevious=Math.round(F*1e4)/1e4,b.distanceFromStart=Math.round((n+F)*1e4)/1e4;break}}return{etd:t,from:g,to:b,next:o.filter(m=>m),wps:p,days:w,all:M}}static currentFactor(s,t,a=0){const i=(s-(t==null?void 0:t.degree)||0)/180*Math.PI;if(Math.abs(i)===Math.PI/2)return 0;let n=((t==null?void 0:t.kts)||0)*Math.cos(i);return a&2?n=Math.ceil(n*100)/100:a&1?n=Math.floor(n*100)/100:n=Math.round(n*100)/100,Math.abs(n)>5?0:n}static weatherFactor(s,t,a=0){var w,M,j,F,b,g,m;C==null||C.debug("calculate weather factor via: %j",{...s,...t});const i=B.blockCoefficient(s.displacement,s.lbp,s.breadthMoulded,s.draught),n=H.LngLatHelper.roundPrecision(a*1852/3600,6),o=B.froudeNumber(s.speed-n,s.lbp),e=B.amendFactor(i,o,s.loadCondition);let r=Math.abs(s.bearing%360-(((w=t==null?void 0:t.wind)==null?void 0:w.degree)%360||0));r=r>180?360-r:r;const d=B.directionFactor(r,(M=t==null?void 0:t.wind)==null?void 0:M.scale),l=B.vesselTagFactor(s.displacement,s.loadCondition,s.tag,(j=t==null?void 0:t.wind)==null?void 0:j.kts);let c=d*e*l/100*(s.speed-n);c=Math.round(c*1.943844*1e4)/1e4*-1,s.tag==="tugs"&&Math.abs(c)>1&&(c=c/(Math.abs(Math.round(c))+1)),C==null||C.debug("wind wx factor = %d",c),r=Math.abs(s.bearing%360-(((b=(F=t==null?void 0:t.wave)==null?void 0:F.sig)==null?void 0:b.degree)%360||0)),r=r>180?360-r:r;const p=B.waveHeightFactor(((m=(g=t==null?void 0:t.wave)==null?void 0:g.sig)==null?void 0:m.height)??1,r);return C==null||C.debug("wave wx factor = %d",p),c=Math.abs(c)>Math.abs(p)?c:c*.3+p*.7,C==null||C.debug("weather factor = %d",c),c=Math.abs(c)>3?3*(Math.abs(c)/c)+Math.abs(c)/c*(Math.abs(c)-2)*.1:c,Math.round((c||0)*100)/100}static async analyseInstant(s,t,a,i,n,o="",e=0,r=!0,d=!1,l={}){var X,Q,Z,$,tt,et,st;const c=v().valueOf();s.lng=H.LngLatHelper.convertToStdLng(s.lng);const{route:p,waypoints:w}=n.points,M=H.LaneHelper.calculateSubRoute(s,p);if(((X=M[0])==null?void 0:X.length)<=1)return;const{v0:j,label:F}=s.sog?{v0:s.sog,label:s.label||"Other"}:{v0:i.speed,label:"CP"},b=B.assembleProperties(a,i.loadCondition,j,0),g=w.length?H.LaneHelper.calculateSubWaypoints(s,w):[];g.forEach(L=>L.important=!0);const m={from:{...s},route:M,waypoints:g,v0:j,label:F},u={hours:[],days:[],wps:[],all:[]};e||(H.LaneHelper.calculateRouteDistance(M)/i.speed<=72?e=3:e=6);let h=H.LaneHelper.simplifyRouteToCoordinates(M,g,0),f=0,k=0,I=0,E=0;t=v(t).utc();const Y=t.clone();for(;h.length>0;){const L=e-t.hour()%e,z=Math.ceil(t.clone().add(L,"h").set({minute:0,second:0,millisecond:0}).diff(t,"h",!0)*1e4)/1e4,S=await B.speedLoseInHoursStep(b,t,Y,z,f,h,o,r,d,l);if(u.all.push(...S.all),(Q=S.from)!=null&&Q.speed&&(u.hours.push(S.from),u.wps.push(...S.wps),u.days.push(...S.days)),h=S==null?void 0:S.next,!h.length){const O=await B.speedLoseAt(b,S.to,v(S.to.eta),o,0,r,d,l);O.bearing=b.bearing,u.hours.push(O),u.all.push(O)}f+=Math.round((((Z=S==null?void 0:S.to)==null?void 0:Z.distanceFromPrevious)??0)*1e4)/1e4}const x=u.hours;for(let L=0;L<x.length-1;L++){const z=v(x[L+1].eta).diff(x[L].etd,"hour",!0)||1;k+=(x[L].wxFactor||0)*z,I+=(x[L].cFactor||0)*z,E+=z}const R=x.reduce((L,z)=>L+(z.suspend||0),0);($=u.wps)==null||$.forEach((L,z)=>{L.positionTime=v.utc(L.etd||L.eta).unix();const S=u.wps[z-1];if(S){const O=L.distanceFromStart-S.distanceFromStart,q=v(L.eta||L.etd).diff(v(S.etd||S.eta),"h",!0);L.avgSpd=Math.round(O/q*100)/100,S.bearing=H.LaneHelper.calculateBearing(S,L)}}),u.wps=(tt=u.wps)==null?void 0:tt.reduce((L,z)=>(L.some(S=>Math.round(S.positionTime/60)===Math.round(z.positionTime/60))||L.push(z),L),[]),u.all=(et=u.all)==null?void 0:et.reduce((L,z)=>(z.positionTime=v.utc(z.etd||z.eta).unix(),L.some(S=>Math.round(S.positionTime/60)===Math.round(z.positionTime/60))||L.push(z),L),[]),m.sample=u;const T=u.hours.at(0),N=u.hours.at(-1);m.distance=Math.round(N.distanceFromStart*1e3)/1e3,m.etd=v(T.eta).utc().format(),m.eta=v(N.eta).utc().format(),m.wxFactor=Math.round(k/E*1e3)/1e3,m.cFactor=Math.round(I/E*1e3)/1e3,m.avgSpeed=Math.round(N.distanceFromStart/E*1e3)/1e3,m.totalHrs=Math.round(E*1e3)/1e3,m.suspend=Math.round(R*1e3)/1e3;const W=H.LngLatHelper.roundPrecision(i.dgo/24*R,3),{distanceInECA:V,hoursInECA:J,totalDgoConsInECA:rt,eca:at}=await this.calculateECA(m,i,l),nt=H.LngLatHelper.roundPrecision(i.fo/24*(E-J),3),ct=H.LngLatHelper.roundPrecision(i.dgo/24*E+W,3);m.extend={eca:at,distanceInECA:V,hoursInECA:J,totalDgoConsInECA:rt,totalDgoConsInSuspend:W},m.totalFoCons=nt<0?0:nt,m.totalDgoCons=ct;const ot=v().valueOf()-c,ut=((st=u==null?void 0:u.hours)==null?void 0:st.length)||1;return C==null||C.info("[%s] each hour-sample speed analyse cost: (%d / %d = %d) ms",l==null?void 0:l.requestId,ot,ut,Math.round(ot/ut*1e3)/1e3),m}static async analyseInstantWithThreshed(s,t,a,i,n,o,e,r="",d=3,l=!0,c=!1,p={}){var Z,$,tt,et,st,L,z;const w=v().valueOf();s.lng=H.LngLatHelper.convertToStdLng(s.lng);const{v0:M,label:j}=s.sog?{v0:s.sog,label:s.label||"Other"}:{v0:n.speed,label:"CP"},F=B.assembleProperties(i,n.loadCondition,M,0),b=H.LaneHelper.calculateSubRoute(s,o);if(((Z=b[0])==null?void 0:Z.length)<=1)return;const g=e.length?H.LaneHelper.calculateSubWaypoints(s,e):[];g.forEach(S=>S.important=!0);let m=H.LaneHelper.simplifyRouteToCoordinates(b,g,0),u=0,h=0,f=0,k=0;const I={hours:[],wps:[],days:[],all:[]};t=v(t).utc();const E=t.clone();for(;m.length>0;){const S=d-t.hour()%d;let O=Math.ceil(t.clone().add(S,"h").set({minute:0,second:0,millisecond:0}).diff(t,"h",!0)*1e4)/1e4;O=t.clone().add(O,"h").isSameOrAfter(a)?a.diff(t,"h",!0)*1e4/1e4:O;const q=await B.speedLoseInHoursStep(F,t,E,O,u,m,r,l,c,p);if(I.all.push(...q.all),($=q.from)!=null&&$.speed&&(I.hours.push(q.from),q!=null&&q.wps&&I.wps.push(...q.wps),I.days.push(...q.days)),m=q==null?void 0:q.next,m.length||I.hours.push(q==null?void 0:q.to),u+=Math.round((((tt=q==null?void 0:q.to)==null?void 0:tt.distanceFromPrevious)??0)*1e4)/1e4,!O)break}I.wps=(et=I.wps)==null?void 0:et.reduce((S,O)=>(S.some(q=>Math.round(v(q.etd).unix()/60)===Math.round(v(O.etd).unix()/60))||S.push(O),S),[]),I.all=(st=I.all)==null?void 0:st.reduce((S,O)=>(O.positionTime=v.utc(O.etd||O.eta).unix(),S.some(q=>Math.round(v(q.etd).unix()/60)===Math.round(v(O.etd).unix()/60))||S.push(O),S),[]),(L=I.wps)==null||L.forEach((S,O)=>{const q=I.wps[O-1];if(q){const kt=S.distanceFromStart-q.distanceFromStart,St=v(S.eta||S.etd).diff(v(q.etd||q.eta),"h",!0);S.avgSpd=Math.round(kt/St*100)/100,q.bearing=H.LaneHelper.calculateBearing(q,S)}});const Y=I.hours;for(let S=0;S<Y.length-1;S++){const O=v(Y[S+1].eta).diff(Y[S].etd,"hour",!0);h+=Y[S].wxFactor*O,f+=Y[S].cFactor*O,k+=O}const x=Y.reduce((S,O)=>S+(O.suspend||0),0),R=I.hours.at(0),T=I.hours.at(-1),N=await H.LaneHelper.calculateRangeRoute(R,T,b),W=await H.LaneHelper.calculateRangeWaypoints(R,T,b,g),V={sample:I,distance:Math.round(((T==null?void 0:T.distanceFromStart)||0)*1e4)/1e4,etd:v(R.eta).utc().format(),eta:v(T==null?void 0:T.eta).utc().format(),wxFactor:Math.round(h/k*1e3)/1e3,cFactor:Math.round(f/k*1e3)/1e3,avgSpeed:Math.round(((T==null?void 0:T.distanceFromStart)||0)/k*1e3)/1e3,totalHrs:Math.round(k*1e3)/1e3,suspend:Math.round(x*1e3)/1e3,from:R,to:T,route:N,waypoints:W,v0:M,label:j},J=H.LngLatHelper.roundPrecision(n.dgo/24*x,3),{distanceInECA:rt,hoursInECA:at,totalDgoConsInECA:nt,eca:ct}=await this.calculateECA(V,n,p),dt=H.LngLatHelper.roundPrecision(n.fo/24*(k-at),3),ot=H.LngLatHelper.roundPrecision(n.dgo/24*k+J,3);V.extend={eca:ct,distanceInECA:rt,hoursInECA:at,totalDgoConsInECA:nt,totalDgoConsInSuspend:J},V.totalDgoCons=ot,V.totalFoCons=dt<0?0:dt;const X=v().valueOf()-w,Q=((z=I==null?void 0:I.hours)==null?void 0:z.length)||1;return C==null||C.debug("[%s] each hour-sample speed analyse cost: (%d / %d = %d) ms",p==null?void 0:p.requestId,X,Q,Math.round(X/Q*1e3)/1e3),V}static async analyseCost(s,t,a,i,n={}){var b,g;const o=v().valueOf(),e=[];s.speedStep=s.speedStep||3,s.alterStep=s.alterStep??1;const r=H.LaneHelper.calculateRouteDistance(i.route);let d=0;a.forEach(m=>{const u=Math.ceil(r/m.speed/24);d=d<u?u:d}),d=d*1.3;const l=v.utc(s.etd).add(d??14,"day");let c=1;for(const m of a){const u=JSON.parse(JSON.stringify(i.route)),h=JSON.parse(JSON.stringify(i.waypoints)),f=await B.analyseInstantWithThreshed({lat:s.lat,lng:s.lng},s.etd,l,t,m,u,h,s.meteoVendor,s.speedStep,s.useMeteo,s.useRouteParam,n);f&&(await B.calculateCost(f,m,s,n),e.push(f),C==null||C.info("[%s][L%d-%d] analyse from %s to %s cost: %j",n.requestId,1,c,s.etd,l.format(),{cost:f.cost.total,hire:f.cost.hire,bunker:f.cost.bunker,distance:f.distance,hours:f.totalHrs,cp:`${m.speed}/${m.fo}/${m.dgo}`})),c++}e.sort((m,u)=>m.cost.total-u.cost.total);const p=e.at(0),w=e.at(1),M=[];if(M.push({combined:!1,speeds:[p],cost:(b=p.cost)==null?void 0:b.total}),w){const m=p.cost.cp,u=w.cost.cp,h=v(p.eta),f=v(p.etd),k=h.diff(f,"days",!0);let I=Math.ceil(k/2);I=I>7?7:I<s.alterStep?s.alterStep:I;let E=2,Y={combined:!1,speeds:[w],cost:(g=w.cost)==null?void 0:g.total},x;for(;I>=s.alterStep;){const R=await B.combinedAnalyse(s,t,l,[m,u],i,I,{...n,level:E});if(Y.cost>R.cost?x?(x==null?void 0:x.cost)>R.cost&&(x=R):(x=Y,Y=R):(!x||(x==null?void 0:x.cost)>R.cost)&&(x=R),I<=s.alterStep)break;I=Math.ceil(I/2),E+=1}M.push(Y),x&&M.push(x)}const F=v().valueOf()-o;return C==null||C.info("[%s] analyse elapsed: %d ms",n==null?void 0:n.requestId,F),M.sort((m,u)=>m.cost-u.cost)}static async combinedAnalyse(s,t,a,i,n,o,e={}){e.counter=1,C==null||C.info("[%s][L%d] analyse with alternate cp in every %d days",e.requestId,e.level,o);const r=await B.alternateAnalyse(s,t,a,i,0,n,o,e),d=r.reduce((u,h)=>u+h.cost.total,0),l=r.reduce((u,h)=>u+h.cost.hire,0),c=r.reduce((u,h)=>u+h.cost.bunker,0),p=r.reduce((u,h)=>u+h.distance,0),w=r.reduce((u,h)=>u+h.totalHrs,0);C==null||C.info("[%s][L%d] cost with cpa/cpb turn: %j",e.requestId,e.level,{cost:d,hire:l,bunker:c,distance:p,hours:w});const M=await B.alternateAnalyse(s,t,a,i,1,n,o,e),j=M.reduce((u,h)=>u+h.cost.total,0),F=M.reduce((u,h)=>u+h.cost.hire,0),b=M.reduce((u,h)=>u+h.cost.bunker,0),g=M.reduce((u,h)=>u+h.distance,0),m=M.reduce((u,h)=>u+h.totalHrs,0);return C==null||C.info("[%s][L%d] cost with cpb/cpa turn: %j",e.requestId,e.level,{cost:j,hire:F,bunker:b,distance:g,hours:m}),d<j?{combined:!0,cost:Math.round(d*1e3)/1e3,speeds:r,step:o}:{combined:!0,cost:Math.round(j*1e3)/1e3,speeds:M,step:o}}static async alternateAnalyse(s,t,a,i,n,o,e,r={}){var p,w;let d=v.utc(s.etd);const l={lat:s.lat,lng:s.lng},c=[];for(;d.isBefore(a);){const M=d.clone().utc().add(e,"day"),j=JSON.parse(JSON.stringify(o.route)),F=JSON.parse(JSON.stringify(o.waypoints)),b=i[n],g=await B.analyseInstantWithThreshed(l,d.utc().format(),M,t,b,j,F,s.meteoVendor,s.speedStep,s.useMeteo,s.useRouteParam,r);g&&(await B.calculateCost(g,b,s,r),C==null||C.info("[%s][L%d-%d] analyse from %s to %s cost: %j",r.requestId,r.level,r.counter,d.utc().format(),M.utc().format(),{cost:g.cost.total,hire:g.cost.hire,bunker:g.cost.bunker,distance:g.distance,hours:g.totalHrs,cp:`${b.speed}/${b.fo}/${b.dgo}`})),r.counter=r.counter+1;const m=(w=(p=g==null?void 0:g.sample)==null?void 0:p.hours)==null?void 0:w.at(-1);if(m)l.lat=m.lat,l.lng=m.lng,d=v(m.eta),c.push(g),n=n?0:1;else break}return c}static async calculateCost(s,t,a,i={}){var n;if(s){const o=(a.addComm||0)>=1?(a.addComm||0)/100:a.addComm||0,e=(a.dailyHire||0)*s.suspend/24,r=Math.round(e+s.totalHrs/24*(a.dailyHire||0)*(1-o)*1e3)/1e3,d=Math.round(s.totalFoCons*(a.priceFO||0)*1e3)/1e3,l=Math.round((s.totalDgoCons+(((n=s.extend)==null?void 0:n.totalDgoConsInECA)||0))*(a.priceDGO||0)*1e3)/1e3;s.cost={total:Math.round((r+d+l)*1e3)/1e3,hire:r,bunker:Math.round((d+l)*1e3)/1e3,cp:t}}return s}static async calculateECA(s,t,a={}){var r,d,l,c;const i=await H.LaneHelper.intersectInECA((s==null?void 0:s.route)||[]);let n=0,o=0,e=0;(d=(r=s==null?void 0:s.sample)==null?void 0:r.wps)==null||d.forEach(p=>{p.positionTime=v.utc(p.etd||p.eta).unix()});for(const p of i){n+=p.distance;const w=await H.LaneHelper.deadReckoningTime((l=p.waypoints)==null?void 0:l.at(0),s.sample.all||s.sample.wps),M=await H.LaneHelper.deadReckoningTime((c=p.waypoints)==null?void 0:c.at(-1),s.sample.all||s.sample.wps);p.in=w,p.out=M,p.totalHrs=H.LngLatHelper.roundPrecision((M.positionTime-w.positionTime)/3600,3),p.totalDgoCons=H.LngLatHelper.roundPrecision(t.fo/24*p.totalHrs,3),o+=p.totalHrs,e+=p.totalDgoCons}return n=H.LngLatHelper.roundPrecision(n,3),o=H.LngLatHelper.roundPrecision(o,3),e=H.LngLatHelper.roundPrecision(e,3),{distanceInECA:n,hoursInECA:o,totalDgoConsInECA:e,eca:i}}static async mergeSpeeds(s,t={}){var m,u;const a={hours:[],wps:[],days:[]},i=s.reduce((h,f)=>h+f.distance,0),n=s.reduce((h,f)=>{var k;return h+(((k=f.extend)==null?void 0:k.distanceInECA)||0)},0),o=s.reduce((h,f)=>h+f.totalHrs,0),e=s.reduce((h,f)=>{var k;return h+(((k=f.extend)==null?void 0:k.hoursInECA)||0)},0),r=s.reduce((h,f)=>{var k;return h+(((k=f.extend)==null?void 0:k.totalDgoConsInECA)||0)},0),d=s.reduce((h,f)=>h+f.wxFactor*f.totalHrs/o,0),l=s.reduce((h,f)=>h+f.cFactor*f.totalHrs/o,0),c=s.reduce((h,f)=>h+f.totalFoCons,0),p=s.reduce((h,f)=>h+f.totalDgoCons,0),w=s.reduce((h,f)=>h+f.cost.total,0),M=s.reduce((h,f)=>h+f.cost.hire,0),j=s.reduce((h,f)=>h+f.cost.bunker,0),F=[],b=[];let g;for(const h of s){b.push(...((m=h.extend)==null?void 0:m.eca)||[]);const f=h.sample.hours,k=h.sample.wps,I=h.sample.days,E=f.at(0);g&&(E.distanceFromPrevious=g.distanceFromPrevious,E.distanceFromStart=g.distanceFromStart,f.forEach((T,N)=>{N&&(T.distanceFromStart=T.distanceFromStart+g.distanceFromStart)}),k.at(0).distanceFromPrevious=g.distanceFromPrevious,k.at(0).distanceFromStart=g.distanceFromStart,k.forEach((T,N)=>{N&&(T.distanceFromStart=T.distanceFromStart+g.distanceFromStart)}),I.at(0).distanceFromPrevious=g.distanceFromPrevious,I.at(0).distanceFromStart=g.distanceFromStart,I.forEach((T,N)=>{N&&(T.distanceFromStart=T.distanceFromStart+g.distanceFromStart)})),E.cp=h.cost.cp;const Y=[h.etd,h.eta],x=F.findIndex(T=>T.id===E.cp.id);x===-1?(E.cp.segment=[Y],F.push(E.cp)):F[x].segment.push(Y),f.forEach(T=>{var W;((W=a.hours)==null?void 0:W.findIndex(V=>V.eta===T.eta))===-1&&a.hours.push(T)}),k.forEach(T=>{var W;((W=a.wps)==null?void 0:W.findIndex(V=>V.eta===T.eta))===-1&&a.wps.push(T)}),I.forEach(T=>{var W;((W=a==null?void 0:a.days)==null?void 0:W.findIndex(V=>V.eta===T.eta))===-1&&a.days.push(T)});const R=(u=a.wps)==null?void 0:u.findIndex(T=>T.eta===E.eta);R===-1?a.wps.push(E):a.wps[R]=E,g=f.at(-1)}return a.wps.sort((h,f)=>{v(h.etd).unix()-v(f.etd).unix()}),a.wps.forEach((h,f)=>{const k=a.wps[f-1];if(k){const I=h.distanceFromStart-(k.distanceFromStart||0),E=v(h.eta||h.etd).diff(v(k.etd||k.eta),"hour",!0),Y=Math.round(I/E*100)/100;h.avgSpd=Y;const x=H.LaneHelper.calculateBearing(k,h);k.bearing=x}}),{sample:a,etd:s.at(0).etd,eta:s.at(-1).eta,from:s.at(0).from,to:s.at(-1).to,v0:s.at(0).v0,label:"Combined",distance:Math.round(i*1e3)/1e3,totalHrs:Math.round(o*1e3)/1e3,avgSpeed:Math.round(i/o*1e3)/1e3,wxFactor:Math.round(d*1e3)/1e3,cFactor:Math.round(l*1e3)/1e3,totalFoCons:Math.round(c*1e3)/1e3,totalDgoCons:Math.round(p*1e3)/1e3,cost:{total:Math.round(w*1e3)/1e3,hire:Math.round(M*1e3)/1e3,bunker:Math.round(j*1e3)/1e3},extend:{cps:F,eca:b,distanceInECA:Math.round(n*1e3)/1e3,hoursInECA:Math.round(e*1e3)/1e3,totalDgoConsInECA:Math.round(r*1e3)/1e3,speeds:s}}}}P.AISImpl=G,P.AlertHelper=ht,P.AlertLevel=lt,P.HifleetImpl=bt,P.LoadCondition=mt,P.MyShipImpl=gt,P.MyVesselImpl=Mt,P.ShipxyImpl=vt,P.SpeedHelper=B,P.SpeedLabel=yt,P.VesselTag=ft,P.alertHelper=wt,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@idm-plugin/vessel",
3
3
  "private": false,
4
- "version": "3.4.1",
4
+ "version": "3.4.3",
5
5
  "description": "idm plugin for vessel",
6
6
  "type": "module",
7
7
  "keywords": [
@@ -38,7 +38,7 @@
38
38
  "@idm-plugin/tag": "^0.2.3"
39
39
  },
40
40
  "devDependencies": {
41
- "@idm-plugin/geo2": "^1.5.9",
41
+ "@idm-plugin/geo2": "^1.6.6",
42
42
  "@idm-plugin/meteo": "^0.5.4",
43
43
  "@idm-plugin/meteo2": "^0.8.2",
44
44
  "@idm-plugin/tag": "^0.3.0",