@tomtom-org/maps-sdk 0.57.0 → 0.58.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +124 -0
- package/README.md +5 -5
- package/THIRD_PARTY.txt +39 -3
- package/core/dist/core.es.js +1 -1
- package/core/dist/core.es.js.map +1 -1
- package/core/dist/index.d.ts +140 -160
- package/map/dist/THIRD_PARTY.txt +36 -1
- package/map/dist/index.d.ts +437 -353
- package/map/dist/map.es.js +1 -1
- package/map/dist/map.es.js.map +1 -1
- package/map/dist/third-party.json +11 -1
- package/map/package.json +2 -0
- package/package.json +7 -6
- package/services/dist/THIRD_PARTY.txt +36 -1
- package/services/dist/index.d.ts +1797 -2820
- package/services/dist/services.es.js +1 -1
- package/services/dist/services.es.js.map +1 -1
- package/services/dist/third-party.json +12 -1
- package/services/package.json +1 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{TomTomConfig as e,areaAnalyticsMetricKeys as t,avoidableTypes as n,bboxFromCoordsArray as r,bboxFromGeoJSON as o,bboxOnlyIfWithArea as a,currentTypes as i,generateId as s,generateTomTomHeaders as c,geographyTypes as l,getPosition as u,getPositionStrict as d,getRoutePlanningLocationType as p,iconToTrafficIncidentCategory as m,indexedMagnitudes as g,inputSectionTypesWithGuidance as h,isProxyCredentialsMode as y,mergeFromGlobal as f,plugTypes as T,poiCategories as R,poiCategoriesToID as I,poiIDsToCategories as S,toPointGeometry as b,trafficIncidentRequestCategories as C,trafficIncidentToIconCategory as v,views as A}from"@tomtom-org/maps-sdk/core";import{z as L}from"zod";import{isNil as P,omit as E}from"lodash-es";var M=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),D=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},N={[M.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[M.FORBIDDEN]:"Request failed with status code 403"},w=class extends D{constructor(e,t,n){super(e,t),this.status=n,this.status&&N[this.status]&&(this.message=N[this.status])}},O=class extends D{constructor(e,t){super("The operation was aborted.",e),this.name="AbortError",this.cause=t}},x=(e,t)=>{const{data:n,message:r,status:o}=e;return new w(n?.error||n?.errorText||r,t,o)},_=(e,t,n,r)=>{if(r?.aborted&&e===r.reason)return new O(t,r.reason);if(r?.aborted&&"AbortError"===e?.name)return new O(t,r.reason);if(e.status){const r=e;return n?n(r,t):x(r,t)}return new D(e.message,t)},G=(e,t)=>new D(e.message,t,e.issues),B=L.object({apiKey:L.string().optional(),commonBaseURL:L.string().optional(),customServiceBaseURL:L.string().optional(),language:L.string().optional()}),H=(e,t=0)=>{const n=e.path.length>0?`${e.path.join(".")}: `:"";if("invalid_union"===e.code){const r=e.unionErrors;if(r?.length)return`${n}no matching union member (${r.map((e,n)=>`option[${n}]: { ${e.issues.map(e=>H(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},F=class extends Error{constructor(e){super(`${e.issues.map(e=>H(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},U=async(e,t,n)=>{if(e.signal?.aborted)throw new O(n,e.signal.reason);const r=t.getAPIVersion?.(e),o=f({...e,...r&&{apiVersion:r}});if(void 0===e.validateRequest||e.validateRequest)try{((e,t)=>{const n=(t?.schema?B.extend(t.schema.shape):B).superRefine((e,n)=>{if("commonBaseURL"in e||"customServiceBaseURL"in e||n.addIssue({code:"custom",message:"commonBaseURL or customServiceBaseURL is required"}),t?.refinements?.length)for(const r of t.refinements)r.check(e)||n.addIssue({code:"custom",message:r.message})}).safeParse(e);if(!n.success)throw new F(n.error)})(o,t.requestValidation)}catch(s){throw G(s,n)}const a=t.buildRequest(o),i=c(o);e.onAPIRequest?.(a);try{const n=await t.sendRequest(a,i,{signal:e.signal});return e.onAPIResponse?.(a,n),t.parseResponse(await n.data,o)}catch(s){throw e.onAPIResponse?.(a,s),_(s,n,t.parseResponseError,e.signal)}},k=class e extends Error{constructor(t,n,r){super(n??`HTTP Error ${t}`),this.name="FetchError",this.status=t,this.data=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},W=async e=>{if(e.ok)return{data:await e.json(),status:e.status};let t,n;const r=e.headers.get("content-type");throw e.bodyUsed?t=e.statusText:r?.includes("application/json")?(n=await e.json(),t=n?.errorText??n?.message??n?.detailedError?.message):r?.includes("text/xml")&&(n=await e.text(),t=e.statusText),new k(e.status,t,n)},K=(e,t)=>new Promise((n,r)=>{if(t?.aborted)return void r(t.reason);const o=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})}),V=async(t,n)=>{const r=e.instance.get().retry;if(!r)return t();const{initialWaitMs:o,backoffFactor:a,timeoutMs:i}=r,s=Date.now();let c=o,l=await t();for(;429===l.status;){const e=Number.parseInt(l.headers.get("retry-after")??"",10),r=Number.isFinite(e)?1e3*e:c;if(Date.now()-s+r>i)break;await l.text().catch(()=>{}),await K(r,n),c*=a,l=await t()}return l},j=()=>y()?"include":void 0,q=async(e,t,n)=>W(await V(()=>{const r=j(),{url:o,headers:a}=e instanceof URL?{url:e,headers:void 0}:e,i={headers:{...t,...a}};return r&&(i.credentials=r),n?.signal&&(i.signal=n.signal),fetch(o,i)},n?.signal)),Y=async(e,t,n)=>W(await V(()=>{const r=j(),o={method:"POST",body:JSON.stringify(e.data),headers:{...t,...e.headers,"Content-Type":"application/json"}};return r&&(o.credentials=r),n?.signal&&(o.signal=n.signal),fetch(e.url,o)},n?.signal)),$=async(e,t,n)=>{if("GET"===e.method)return q(e,t,n);if("POST"===e.method)return Y(e,t,n);throw new Error(`Unsupported HTTP method received: ${e.method}`)},Z=L.array(L.array(L.number())),J=L.object({type:L.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:L.union([L.array(L.number()),Z,L.array(L.array(L.array(L.number()))),L.array(L.array(L.array(L.array(L.number()))))]),radius:L.optional(L.number()),radiusMeters:L.optional(L.number()),bbox:L.optional(L.array(L.number()))}).check(L.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),z=L.object({type:L.literal("Feature"),geometry:J,id:L.optional(L.union([L.string(),L.number()])),properties:L.unknown().optional(),bbox:L.optional(L.array(L.number()))}),Q=L.object({type:L.literal("FeatureCollection"),features:L.array(z),id:L.optional(L.union([L.string(),L.number()])),properties:L.unknown().optional(),bbox:L.optional(L.array(L.number()))}),X=L.union([L.tuple([L.number().min(-180).max(180),L.number().min(-90).max(90)]),L.tuple([L.number().min(-180).max(180),L.number().min(-90).max(90),L.number()]),L.object({type:L.literal("Point"),coordinates:L.array(L.number())}),z]),ee=L.union([L.array(L.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),L.array(L.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),te=L.union([J,z,Q]),ne=L.union([ee,te,L.array(te)]),re=L.object({query:L.string().optional(),position:X.optional(),limit:L.number().max(100).optional(),extendedPostalCodesFor:L.array(L.string()).optional(),mapcodes:L.array(L.string()).optional(),view:L.enum(A).optional(),geographyTypes:L.array(L.string()).optional()}),oe=L.object({indexes:L.array(L.string()).optional(),poiCategories:L.array(L.enum(R)).optional(),poiBrands:L.array(L.string()).optional(),connectors:L.array(L.string()).optional(),fuelTypes:L.array(L.string()).optional(),openingHours:L.string().optional(),timeZone:L.string().optional(),relatedPois:L.string().optional(),minPowerKW:L.number().optional(),maxPowerKW:L.number().optional(),minFuzzyLevel:L.number().optional(),maxFuzzyLevel:L.number().optional()}),ae=re.extend(oe.shape),ie=L.object({type:L.literal("LineString"),coordinates:Z}),se=L.object({type:L.literal("Feature"),geometry:ie}),ce=Z,le=L.union([ie,se,ce]),ue=L.object({route:le,maxDetourTimeSeconds:L.number().int().positive()}),de=L.object({sortBy:L.enum(["detourTime","detourOffset"]).optional()}),pe=ae.extend({...ue.shape,...de.shape}),me=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",ge=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let o;const a=Math.ceil(n/t);for(o=0;o<n;o+=a)r.push(e[o]);return t>1&&o>=n-a&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},he=e=>({...e.apiKey&&{"TomTom-Api-Key":e.apiKey},...!P(e.apiVersion)&&{"TomTom-Api-Version":String(e.apiVersion)}}),ye=e=>({...he(e),...e.language&&{"Accept-Language":e.language}}),fe=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),t.apiKey&&e.append("key",t.apiKey),t.language&&e.append("language",t.language)},Te=e=>he(e),Re=(e,t)=>{t.language&&e.append("language",t.language)},Ie=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},Se=(e,t,n)=>{!P(n)&&e.append(t,String(n))},be=(e,t)=>{if(!t)return;if(void 0!==t.position)return((e,t)=>{const n=u(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))})(e,t.position),void Se(e,"radius",t.radiusMeters);const n=o(t.boundingBox);n&&(e.append("topLeft",me([n[3],n[0]])),e.append("btmRight",me([n[1],n[2]])))},Ce=(e,t)=>{const n=e.searchParams;Re(n,t),Se(n,"limit",t.limit),Ie(n,"fuelSet",t.fuelTypes),Ie(n,"idxSet",t.indexes),Ie(n,"brandSet",t.poiBrands),t.poiCategories&&Ie(n,"categorySet",t.poiCategories.map(e=>I[e])),Ie(n,"connectorSet",t.connectors),Ie(n,"mapcodes",t.mapcodes),Ie(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),Se(n,"minPowerKW",t.minPowerKW),Se(n,"maxPowerKW",t.maxPowerKW),Se(n,"view",t.view),Se(n,"openingHours",t.openingHours),Se(n,"timeZone",t.timeZone),Se(n,"relatedPois",t.relatedPois),Ie(n,"entityTypeSet",t.geographyTypes)},ve=(e,t)=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/${t}`,Ae=e=>{const t=new URL((e=>ve(e,`searchAlongRoute/${e.query??""}.json`))(e));Ce(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),Se(n,"sortBy",e.sortBy),Se(n,"spreadingMode","plan"),{url:t,headers:Te(e),data:{route:{points:(r=e.route,Array.isArray(r)?{type:"LineString",coordinates:r}:"Feature"===r.type?r.geometry:r).coordinates.map(e=>({lat:e[1],lon:e[0]}))}}};var r},Le=e=>{const t={count:0,statusCounts:{}};for(const n of e)for(const e of n.chargingPoints)t.count++,t.statusCounts[e.status]=(t.statusCounts[e.status]||0)+1;return t},Pe=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,Ee=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>Pe(r,e.connector));if(e){if(e.count++,t){const n=e.statusCounts;e.statusCounts[t]=(n[t]||0)+1}}else n.push({connector:r,count:1,statusCounts:t?{[t]:1}:{}})}},Me=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>Pe(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},De=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)Ee(e.connectors,e.status,t);return t},Ne=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",we=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},Oe=e=>`${e[1]},${e[0]}`,xe=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=we(e.southWest),n=we(e.northEast)),[t[0],t[1],n[0],n[1]]},_e=e=>[e.lon,e.lat],Ge=e=>{const{year:t,month:n,day:r}=(e=>{const t=e.split("-");return{year:Number.parseInt(t[0]),month:Number.parseInt(t[1]),day:Number.parseInt(t[2])}})(e.date);return{dateYYYYMMDD:e.date,year:t,month:n,day:r,hour:e.hour,minute:e.minute,date:new Date(t,n-1,r,e.hour,e.minute)}},Be=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,He=e=>{const t=e.timeRanges.map(e=>({start:Ge(e.startTime),end:Ge(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:Be(t)}},Fe=e=>{const{position:t,entryPoints:n,poi:r,id:o,dist:a,boundingBox:i,chargingPark:s,...c}=e,l=s?.connectors?.map(e=>({...E(e,"connectorType"),type:e.connectorType,chargingSpeed:Ne(e.ratedPowerKW)}));return{type:"Feature",geometry:b(_e(t)),...i&&{bbox:xe(i)},id:o,properties:{...E(c,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:_e(e.position)}))},...l?.length&&{chargingPark:{...s,connectors:Me(l)}},...r&&{poi:{name:r.name,categories:(r.categorySet?.map(e=>S[e.id])??[]).filter(e=>!!e),localizedCategories:r.categories??[],...r.phone&&{phone:r.phone},...r.brands&&{brands:r.brands.map(e=>e.name)},...r.url&&{url:r.url},...r.openingHours&&{openingHours:He(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},Ue=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:_e(t)},...n}},ke=e=>{const t=e.results.map(Fe),n=a(o(t));return{type:"FeatureCollection",properties:{...Ue(e.summary)},features:t,...n&&{bbox:n}}},We={requestValidation:{schema:pe},buildRequest:Ae,sendRequest:Y,parseResponse:ke},Ke=async(e,t)=>U(e,{...We,...t},"AlongRouteSearch"),Ve=L.object({position:X,radiusMeters:L.number().optional()}),je=L.union([Ve,L.object({boundingBox:ne})]),qe=L.object({query:L.string()}),Ye=L.object({geoBias:Ve.optional(),limit:L.number().max(100).optional(),countries:L.array(L.string()).optional(),resultType:L.array(L.string()).optional()}),$e=qe.extend(Ye.shape),Ze=e=>{const t=new URL(`${n=e,ve(n,`autocomplete/${n.query}.json`)}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",Re(r,e),Se(r,"limit",e.limit),be(r,e.geoBias),Ie(r,"countrySet",e.countries),Ie(r,"resultSet",e.resultType),{url:t,headers:Te(e)}},Je=e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:_e(t)},radiusMeters:n.radius}},results:(r=e.results,r.map(e=>({segments:e.segments.map(e=>{if((e=>"category"===e.type)(e)){const{id:t,...n}=e;return{...n,category:S[Number(t)]}}return e})})))};var r},ze={requestValidation:{schema:$e},buildRequest:Ze,sendRequest:q,parseResponse:Je},Qe=async(e,t)=>U(e,{...ze,...t},"Autocomplete"),Xe={alongRouteSearch:Ke,buildAlongRouteSearchRequest:Ae,parseAlongRouteSearchResponse:ke,alongRouteSearchTemplate:We},et={autocompleteSearch:Qe,buildAutocompleteSearchRequest:Ze,parseAutocompleteSearchResponse:Je,autocompleteSearchTemplate:ze},tt=B.extend({id:L.string()}),nt=["fast","short","efficient","thrilling"],rt=["all","unknown","none"],ot=e=>{const t=new URL((e=>ve(e,"ev/id"))(e)),n=t.searchParams;return fe(n,e),n.append("id",e.id),t},at=e=>{const t=e.results?.[0];return t?{id:t.id,accessType:t.accessType,chargingStations:(n=t.chargingStations,n.map(e=>({...e,chargingPoints:e.chargingPoints.map(e=>({...e,connectors:e.connectors?.map(e=>({...e,chargingSpeed:Ne(e.ratedPowerKW)}))}))}))),chargingPointAvailability:Le(t.chargingStations),connectorAvailabilities:De(t.chargingStations),...t.openingHours&&{openingHours:He(t.openingHours)}}:void 0;var n},it={requestValidation:{schema:tt},buildRequest:ot,sendRequest:q,parseResponse:at,parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new w(n,t,e.status)}},st={buildEVChargingStationsAvailabilityRequest:ot,parseEVChargingStationsAvailabilityResponse:at,evChargingStationsAvailabilityTemplate:it},ct=L.object({typeahead:L.boolean().optional(),offset:L.number().max(1900).optional(),geoBias:je.optional(),countries:L.array(L.string()).optional()}),lt=B.extend(re.shape).extend(ct.shape).extend({query:L.string()}),ut=e=>{const t=new URL(`${(e=>ve(e,"geocode"))(e)}/${e.query}.json`),n=t.searchParams;return Re(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!P(e.limit)&&n.append("limit",String(e.limit)),!P(e.offset)&&n.append("ofs",String(e.offset)),be(n,e.geoBias),e.countries&&n.append("countrySet",me(e.countries)),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",me(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",me(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",me(e.geographyTypes)),{url:t,headers:Te(e)}},dt=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:b(_e(t)),...n&&{bbox:xe(n)},id:s,properties:{...E(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...o&&{entryPoints:o.map(e=>({...e,position:_e(e.position)}))},...a&&{addressRanges:{...a,from:_e(a.from),to:_e(a.to)}}}}},pt=e=>{const t=e.results.map(dt),n=a(o(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}},mt={requestValidation:{schema:lt},buildRequest:ut,sendRequest:q,parseResponse:pt},gt={buildGeocodingRequest:ut,parseGeocodingResponse:pt,geocodingTemplate:mt},ht=L.object({geometries:L.union([Q,L.array(L.union([L.string(),z])).min(1).max(20)])}),yt=L.object({zoom:L.number().min(0).max(22).optional()}),ft=ht.extend(yt.shape),Tt=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),Rt=e=>{const t=new URL((e=>ve(e,"additionalData.json"))(e)),n=t.searchParams;return((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:Tt(t):Tt(t.features),e.append("geometries",me(n))})(n,e.geometries),Se(n,"geometriesZoom",e.zoom),{url:t,headers:Te(e)}},It=e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??s(),bbox:o(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:o(t),features:t}},St={requestValidation:{schema:ft},buildRequest:Rt,sendRequest:q,parseResponse:It},bt={buildGeometryDataRequest:Rt,parseGeometryDataResponse:It,geometryDataTemplate:St},Ct=L.object({geometries:L.array(L.union([Q,J]))}),vt=ae.extend(Ct.shape),At=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:Oe(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:ge(e.coordinates[0],50).map(e=>Oe(e))}];case"MultiPolygon":return e.coordinates.length>50?(e=>{let t=/* @__PURE__ */new Map;return e.coordinates.forEach(e=>{const n=r(e[0]);if(n){const r=Math.abs((n[2]-n[0])*(n[3]-n[1]));t.set(e,r)}}),t=new Map([...t.entries()].sort((e,t)=>t[1]-e[1]).splice(0,50)),[...t.keys()]})(e).flatMap(e=>At({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>At({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>At(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},Lt=e=>{const t=new URL(`${n=e,ve(n,`geometrySearch/${n.query??""}.json`)}`);var n;return Ce(t,e),{url:t,headers:Te(e),data:{geometryList:e.geometries.flatMap(At)}}},Pt=e=>{const t=e.results.map(Fe),n=a(o(t));return{type:"FeatureCollection",properties:{...Ue(e.summary)},features:t,...n&&{bbox:n}}},Et={requestValidation:{schema:vt},buildRequest:Lt,sendRequest:Y,parseResponse:Pt},Mt=async(e,t)=>U(e,{...Et,...t},"GeometrySearch"),Dt={geometrySearch:Mt,buildGeometrySearchRequest:Lt,parseGeometrySearchResponse:Pt,geometrySearchTemplate:Et},Nt=L.object({entityId:L.string()}),wt=L.object({mapcodes:L.array(L.string()).optional(),view:L.enum(A).optional(),openingHours:L.string().optional(),timeZone:L.string().optional(),relatedPois:L.string().optional()}),Ot=Nt.extend(wt.shape),xt=e=>{const t=new URL(`${(e=>ve(e,"place.json"))(e)}`),n=t.searchParams;return Re(n,e),Se(n,"entityId",e.entityId),Ie(n,"mapcodes",e.mapcodes),Se(n,"view",e.view),Se(n,"openingHours",e.openingHours),Se(n,"timeZone",e.timeZone),Se(n,"relatedPois",e.relatedPois),{url:t,headers:Te(e)}},_t=e=>e.results?.length?Fe(e.results[0]):void 0,Gt={requestValidation:{schema:Ot},buildRequest:xt,sendRequest:q,parseResponse:_t},Bt={buildPlaceByIdRequest:xt,parsePlaceByIdResponse:_t,placeByIdTemplate:Gt},Ht=(e,t)=>{const{data:n,message:r,status:o}=e;return new w(n?.error?.description??n?.detailedError?.message??r,t,o)},Ft=L.number().positive(),Ut=L.number().min(0),kt=L.number().min(0).max(100),Wt=Ft.optional(),Kt=Ut.optional(),Vt=L.number().min(0).max(1).optional(),jt=L.object({speedKMH:L.number(),consumptionUnitsPer100KM:L.number()}),qt={efficiency:L.object({acceleration:Vt,deceleration:Vt,uphill:Vt,downhill:Vt}).optional()},Yt=L.array(jt).min(1).max(25),$t=L.object({...qt,speedsToConsumptionsLiters:Yt,auxiliaryPowerInLitersPerHour:Kt,fuelEnergyDensityInMJoulesPerLiter:L.number().min(1).optional()}),Zt=L.object({...qt,speedsToConsumptionsKWH:Yt,auxiliaryPowerInkW:Kt,consumptionInKWHPerKMAltitudeGain:L.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Kt}),Jt=L.object({currentType:L.enum(i),plugTypes:L.array(L.enum(T)).min(1),efficiency:Vt,baseLoadInkW:Kt,maxPowerInkW:Kt,maxVoltageInV:Kt,maxCurrentInA:Kt,voltageRange:L.object({minVoltageInV:Kt,maxVoltageInV:L.number().optional()}).optional()}),zt=L.object({stateOfChargeInkWh:Ut,maxPowerInkW:Ft}),Qt=L.object({maxChargeKWH:Ft,batteryCurve:L.array(zt).max(20).optional(),chargingConnectors:L.array(Jt).min(1).optional(),chargingTimeOffsetInSec:Kt}),Xt=L.object({consumption:$t}),en=L.object({consumption:Zt,charging:Qt.optional()}),tn=L.object({weightKG:Wt}).optional(),nn=L.object({variantId:L.string()}),rn=L.object({dimensions:tn,engine:L.union([Xt,en]).optional()}),on=L.union([nn,rn]).optional(),an=L.object({heading:L.number().min(0).max(360).optional()}),sn=an.extend({currentFuelInLiters:Ut}),cn=an.extend({currentChargePCT:kt}),ln=an.extend({currentChargeInkWh:Ut}),un=L.union([cn,ln]),dn=L.object({minChargeAtDestinationPCT:kt,minChargeAtChargingStopsPCT:L.number().min(0).max(50)}),pn=L.object({minChargeAtDestinationInkWh:Ut,minChargeAtChargingStopsInkWh:Ut}),mn=L.union([dn,pn]),gn=L.object({chargingPreferences:mn.optional()}),hn={model:on,restrictions:L.object({maxSpeedKMH:L.number().min(0).max(250).optional(),tollTransponder:L.enum(rt).optional()}).optional()},yn=L.object({...hn,engineType:L.undefined().optional(),state:an.optional(),preferences:L.object({}).optional()}),fn=L.object({...hn,engineType:L.literal("combustion"),state:sn.optional(),preferences:L.object({}).optional()}),Tn=L.object({...hn,engineType:L.literal("electric"),state:un.optional(),preferences:gn.optional()}),Rn=L.union([L.discriminatedUnion("engineType",[fn,Tn]),yn]),In=L.object({costModel:L.object({avoid:L.array(L.enum(n)).optional(),traffic:L.enum(["live","historical"]).optional(),routeType:L.enum(nt).optional(),avoidAreas:L.array(ne).max(10).optional()}).optional(),travelMode:L.string().optional(),vehicle:Rn.optional(),when:L.object({option:L.enum(["departAt","arriveBy"]),date:L.date()}).optional()}),Sn=["timeMinutes","remainingChargeCPT","spentChargePCT","spentFuelLiters","distanceKM"],bn=L.object({origin:X,budget:L.object({type:L.enum(Sn),value:L.number().min(0)})}),Cn=L.enum(n).exclude(["alreadyUsedRoads"]),vn=Rn.check(L.refine(e=>!(e.state&&"heading"in e.state),"vehicle.state.heading: calculateReachableRange has no vehicle heading parameter"),L.refine(e=>!(e.preferences&&"chargingPreferences"in e.preferences),"vehicle.preferences.chargingPreferences: calculateReachableRange plans no charging stops")),An=L.object({vehicle:vn.optional(),costModel:L.object({avoid:L.array(Cn).optional(),traffic:L.enum(["live","historical"]).optional(),routeType:L.enum(nt).optional()}).optional(),maxFerryLengthMeters:L.number().min(0).optional(),smoothing:L.enum(["none","weak","strong"]).optional()}),Ln=In.extend(bn.extend(An.shape).shape),Pn=(e,t,n)=>{P(n)||(e[t]=String(n))},En=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),Mn=e=>{const t={};return e?(Pn(t,"accelerationEfficiency",e.acceleration),Pn(t,"decelerationEfficiency",e.deceleration),Pn(t,"uphillEfficiency",e.uphill),Pn(t,"downhillEfficiency",e.downhill),t):t},Dn=e=>{const t={};return e.speedsToConsumptionsKWH?.length&&(t.constantSpeedConsumptionInkWhPerHundredkm=En(e.speedsToConsumptionsKWH)),Pn(t,"auxiliaryPowerInkW",e.auxiliaryPowerInkW),Pn(t,"consumptionInkWhPerkmAltitudeGain",e.consumptionInKWHPerKMAltitudeGain),Pn(t,"recuperationInkWhPerkmAltitudeLoss",e.recuperationInKWHPerKMAltitudeLoss),{...t,...Mn(e.efficiency)}},Nn=e=>{const t=e.consumption,n={};return t.speedsToConsumptionsLiters?.length&&(n.constantSpeedConsumptionInLitersPerHundredkm=En(t.speedsToConsumptionsLiters)),Pn(n,"auxiliaryPowerInLitersPerHour",t.auxiliaryPowerInLitersPerHour),Pn(n,"fuelEnergyDensityInMJoulesPerLiter",t.fuelEnergyDensityInMJoulesPerLiter),{...n,...Mn(t.efficiency)}},wn=e=>{if(e.model&&!("variantId"in e.model))return e.model.engine?.charging?.maxChargeKWH},On=e=>{const t={};return e.charging?.maxChargeKWH&&(t.maxChargeInkWh=String(e.charging.maxChargeKWH)),t},xn=e=>{const t={},n=e.state;if(n?.currentChargeInkWh)return t.currentChargeInkWh=String(n.currentChargeInkWh),t;const r=e.state?.currentChargePCT,o=wn(e);return r&&o&&(t.currentChargeInkWh=String(o*r/100)),t},_n=e=>{const t={};return Pn(t,"currentFuelInLiters",e.state?.currentFuelInLiters),t},Gn=e=>{const t=e.preferences?.chargingPreferences,n={};if(!t)return n;const r=t;if(!P(r.minChargeAtDestinationInkWh)||!P(r.minChargeAtChargingStopsInkWh))return Pn(n,"minChargeAtDestinationInkWh",r.minChargeAtDestinationInkWh),Pn(n,"minChargeAtChargingStopsInkWh",r.minChargeAtChargingStopsInkWh),n;const o=wn(e);if(!o)return n;const a=t;return P(a.minChargeAtDestinationPCT)||(n.minChargeAtDestinationInkWh=String(o*a.minChargeAtDestinationPCT/100)),P(a.minChargeAtChargingStopsPCT)||(n.minChargeAtChargingStopsInkWh=String(o*a.minChargeAtChargingStopsPCT/100)),n},Bn=(e,t)=>{for(const[n,r]of Object.entries(t))e.append(n,r)},Hn=(e,t)=>{for(const[n,r]of Object.entries(t))e.set(n,r)},Fn=(e,t)=>{t.model&&("variantId"in t.model?e.append("vehicleModelId",t.model.variantId):(((e,t)=>{t?.weightKG&&e.append("vehicleWeight",String(t.weightKG))})(e,t.model.dimensions),t.model.engine&&((e,t,n)=>{if("electric"===t){const t=n;return void Bn(e,{...Dn(t.consumption),...On(t)})}Bn(e,Nn(n))})(e,"engineType"in t?t.engineType:void 0,t.model.engine)))},Un=(e,t)=>{t&&("electric"===t.engineType&&e.append("vehicleEngineType","electric"),Fn(e,t),((e,t)=>{if(!t.state||!("engineType"in t))return;const n="electric"===t.engineType?xn:_n;Bn(e,n(t))})(e,t),((e,t)=>{const n=t.restrictions?.maxSpeedKMH;n&&e.append("vehicleMaxSpeed",String(n));const r=t.restrictions?.tollTransponder;r&&e.append("vehicleHasElectricTollCollectionTransponder",r)})(e,t))},kn=e=>e.vehicle&&wn(e.vehicle),Wn=(e,t)=>{const n=t.budget;switch(n.type){case"timeMinutes":e.append("timeBudgetInSec",(60*n.value).toString());break;case"distanceKM":e.append("distanceBudgetInMeters",(1e3*n.value).toString());break;case"spentFuelLiters":e.append("fuelBudgetInLiters",n.value.toString());break;case"spentChargePCT":{const r=kn(t);null!=r&&e.append("energyBudgetInkWh",(r*n.value/100).toString());break}case"remainingChargeCPT":{const r=(e=>{if(!e.vehicle)return;const t=xn(e.vehicle).currentChargeInkWh;return void 0===t?void 0:Number(t)})(t),o=kn(t);if(null!=o&&null!=r){const t=o*n.value/100;e.append("energyBudgetInkWh",Math.max(0,r-t).toString())}break}default:e.append(n.type,n.value.toString())}},Kn=e=>{const t=Oe(d(e.origin)),n=new URL(((e,t)=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange/${t}/json`)(e,t)),r=n.searchParams;return fe(r,e),r.delete("language"),((e,t)=>{const n=t.costModel;((e,t,n)=>{for(const r of n||[])e.append(t,r)})(e,"avoid",n?.avoid),Se(e,"traffic",n?.traffic),((e,t)=>{if(t?.date){const n=t.date.toISOString();"departAt"===t.option?e.append("departAt",n):"arriveBy"===t.option&&e.append("arriveAt",n)}})(e,t.when),Se(e,"routeType",n?.routeType),Se(e,"travelMode",t.travelMode),Un(e,t.vehicle)})(r,e),Wn(r,e),Se(r,"maxFerryLengthInMeters",e.maxFerryLengthMeters),Se(r,"smoothing",e.smoothing??"strong"),{method:"GET",url:n}},Vn=(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:o(n),properties:t}},jn={requestValidation:{schema:Ln},buildRequest:Kn,sendRequest:$,parseResponse:Vn,parseResponseError:Ht,getAPIVersion:()=>2},qn={buildReachableRangeRequest:Kn,parseReachableRangeResponse:Vn,reachableRangeTemplate:jn},Yn={Country:"country",CountrySubdivision:"countrySubdivision",CountrySecondarySubdivision:"countrySecondarySubdivision",CountryTertiarySubdivision:"countryTertiarySubdivision",Municipality:"municipality",MunicipalitySubdivision:"municipalitySubdivision",MunicipalitySecondarySubdivision:"municipalitySecondarySubdivision",Neighbourhood:"neighborhood",PostalCodeArea:"postalCode"},$n=e=>{const[t,n]=d(e.position),r=new URL((e=>ve(e,"reverseGeocode"))(e)),o=r.searchParams;return o.append("position",`${t},${n}`),!P(e.radiusMeters)&&o.append("radiusInMeters",String(e.radiusMeters)),e.geographyType&&o.append("areaTypes",e.geographyType.map(e=>Yn[e]).join(",")),!P(e.heading)&&o.append("vehicleHeadingInDegrees",String(e.heading)),e.view&&o.append("geopoliticalView",e.view),{url:r,headers:{...ye(e),Attributes:"results(*)"}}},Zn={AF:"AFG",AX:"ALA",AL:"ALB",DZ:"DZA",AS:"ASM",AD:"AND",AO:"AGO",AI:"AIA",AQ:"ATA",AG:"ATG",AR:"ARG",AM:"ARM",AW:"ABW",AU:"AUS",AT:"AUT",AZ:"AZE",BS:"BHS",BH:"BHR",BD:"BGD",BB:"BRB",BY:"BLR",BE:"BEL",BZ:"BLZ",BJ:"BEN",BM:"BMU",BT:"BTN",BO:"BOL",BQ:"BES",BA:"BIH",BW:"BWA",BV:"BVT",BR:"BRA",IO:"IOT",BN:"BRN",BG:"BGR",BF:"BFA",BI:"BDI",CV:"CPV",KH:"KHM",CM:"CMR",CA:"CAN",KY:"CYM",CF:"CAF",TD:"TCD",CL:"CHL",CN:"CHN",CX:"CXR",CC:"CCK",CO:"COL",KM:"COM",CG:"COG",CD:"COD",CK:"COK",CR:"CRI",CI:"CIV",HR:"HRV",CU:"CUB",CW:"CUW",CY:"CYP",CZ:"CZE",DK:"DNK",DJ:"DJI",DM:"DMA",DO:"DOM",EC:"ECU",EG:"EGY",SV:"SLV",GQ:"GNQ",ER:"ERI",EE:"EST",SZ:"SWZ",ET:"ETH",FK:"FLK",FO:"FRO",FJ:"FJI",FI:"FIN",FR:"FRA",GF:"GUF",PF:"PYF",TF:"ATF",GA:"GAB",GM:"GMB",GE:"GEO",DE:"DEU",GH:"GHA",GI:"GIB",GR:"GRC",GL:"GRL",GD:"GRD",GP:"GLP",GU:"GUM",GT:"GTM",GG:"GGY",GN:"GIN",GW:"GNB",GY:"GUY",HT:"HTI",HM:"HMD",VA:"VAT",HN:"HND",HK:"HKG",HU:"HUN",IS:"ISL",IN:"IND",ID:"IDN",IR:"IRN",IQ:"IRQ",IE:"IRL",IM:"IMN",IL:"ISR",IT:"ITA",JM:"JAM",JP:"JPN",JE:"JEY",JO:"JOR",KZ:"KAZ",KE:"KEN",KI:"KIR",KP:"PRK",KR:"KOR",KW:"KWT",KG:"KGZ",LA:"LAO",LV:"LVA",LB:"LBN",LS:"LSO",LR:"LBR",LY:"LBY",LI:"LIE",LT:"LTU",LU:"LUX",MO:"MAC",MG:"MDG",MW:"MWI",MY:"MYS",MV:"MDV",ML:"MLI",MT:"MLT",MH:"MHL",MQ:"MTQ",MR:"MRT",MU:"MUS",YT:"MYT",MX:"MEX",FM:"FSM",MD:"MDA",MC:"MCO",MN:"MNG",ME:"MNE",MS:"MSR",MA:"MAR",MZ:"MOZ",MM:"MMR",NA:"NAM",NR:"NRU",NP:"NPL",NL:"NLD",NC:"NCL",NZ:"NZL",NI:"NIC",NE:"NER",NG:"NGA",NU:"NIU",NF:"NFK",MK:"MKD",MP:"MNP",NO:"NOR",OM:"OMN",PK:"PAK",PW:"PLW",PS:"PSE",PA:"PAN",PG:"PNG",PY:"PRY",PE:"PER",PH:"PHL",PN:"PCN",PL:"POL",PT:"PRT",PR:"PRI",QA:"QAT",RE:"REU",RO:"ROU",RU:"RUS",RW:"RWA",BL:"BLM",SH:"SHN",KN:"KNA",LC:"LCA",MF:"MAF",PM:"SPM",VC:"VCT",WS:"WSM",SM:"SMR",ST:"STP",SA:"SAU",SN:"SEN",RS:"SRB",SC:"SYC",SL:"SLE",SG:"SGP",SX:"SXM",SK:"SVK",SI:"SVN",SB:"SLB",SO:"SOM",ZA:"ZAF",GS:"SGS",SS:"SSD",ES:"ESP",LK:"LKA",SD:"SDN",SR:"SUR",SJ:"SJM",SE:"SWE",CH:"CHE",SY:"SYR",TW:"TWN",TJ:"TJK",TZ:"TZA",TH:"THA",TL:"TLS",TG:"TGO",TK:"TKL",TO:"TON",TT:"TTO",TN:"TUN",TR:"TUR",TM:"TKM",TC:"TCA",TV:"TUV",UG:"UGA",UA:"UKR",AE:"ARE",GB:"GBR",US:"USA",UM:"UMI",UY:"URY",UZ:"UZB",VU:"VUT",VE:"VEN",VN:"VNM",VG:"VGB",VI:"VIR",WF:"WLF",EH:"ESH",YE:"YEM",ZM:"ZMB",ZW:"ZWE"},Jn=e=>Zn[e]??e,zn={street:"Street",area:"Geography",address:"Point Address"},Qn=Object.fromEntries(Object.entries(Yn).map(([e,t])=>[t,e])),Xn=e=>{const{street:t,houseNumber:n,countryCodeIso2:r,...o}=e;return{...o,...t&&{streetName:t},...n&&{streetNumber:n},...r&&{countryCode:r,countryCodeISO3:Jn(r)}}},er=(e,t)=>{const n=e.results[0];return{type:"Feature",geometry:b(d(t.position)),id:n?.id??s(),...n&&{properties:{type:zn[n.type],address:{freeformAddress:n.title,...Xn(n.address)},...n.areaType&&{geographyType:[Qn[n.areaType]],dataSources:{geometry:{id:n.id}}},...n.accessPoints?.length&&{entryPoints:n.accessPoints.map(e=>({position:e.position.coordinates}))},originalPosition:n.position.coordinates}}}},tr=L.object({position:X}),nr=L.object({geographyType:L.array(L.enum(l)).optional(),heading:L.number().min(-360).max(360).optional(),radiusMeters:L.number().positive().max(5e6).optional(),view:L.enum(A).optional()}),rr={requestValidation:{schema:tr.extend(nr.shape)},buildRequest:$n,getAPIVersion:()=>2,sendRequest:q,parseResponse:er},or={buildRevGeoRequest:$n,parseRevGeoResponse:er,reverseGeocodingTemplate:rr},ar=["tollVignette","tollRoad","roadShields","importantRoadStretch"],ir=e=>{const t=["summary","legs(summary,path)"],n=e.sectionTypes;if(!n||n.length>0){t.push("sections");const r=!n;for(const e of ar)(r||n.includes(e))&&t.push(`sections.${e}`);e.guidance&&(r||n.includes("lanes"))&&t.push("sections.lanes")}0!==e.extendedRouteRepresentations?.length&&t.push("progressPoints"),e.guidance&&t.push("instructions(*,nextRoadInformation.roadShields.iconReference,previousRoadInformation.roadShields.iconReference,signpost.exitIconReference,distanceToPreviousTrafficLightInMeters)");const r=`routes(${t.join(",")})`;return e.guidance?`roadShieldAtlasReference,${r}`:r},sr=e=>{const t={};if("electric"===e.engineType&&(t.vehicleEngineType="electric"),e.model&&!("variantId"in e.model)){const n=e.model;n.dimensions?.weightKG&&(t.vehicleWeightInKilograms=n.dimensions.weightKG)}return e.state?.heading&&(t.vehicleHeadingInDegrees=e.state.heading),e.restrictions?.maxSpeedKMH&&(t.vehicleMaxSpeedInKilometersPerHour=e.restrictions.maxSpeedKMH),e.restrictions?.tollTransponder&&(t.vehicleHasElectronicTollCollectionTransponder=e.restrictions.tollTransponder),t},cr=e=>({...Dn(e.consumption),...On(e)}),lr=e=>{if(e.model&&!("variantId"in e.model))return e.model.engine},ur=e=>!!e.vehicle?.preferences?.chargingPreferences,dr=e=>{const t=(e=>Array.isArray(e)?e:e.geometry.coordinates)(e),n=(e=>{if(!Array.isArray(e))return e.properties?.sections?.leg})(e);if(n&&n.length>1&&n.every(e=>null!=e.startPointIndex&&null!=e.endPointIndex)){const e=n.map(e=>{const n=e.startPointIndex??0,r=e.endPointIndex??0;return{coordinate:t[n],legToNext:{path:{type:"LineString",coordinates:t.slice(n,r+1)}}}});return e.push({coordinate:t[n.at(-1)?.endPointIndex??t.length-1]}),e}return[{coordinate:t[0],legToNext:{path:{type:"LineString",coordinates:t}}},{coordinate:t.at(-1)??t[0]}]},pr=e=>{if(!Array.isArray(e)&&"properties"in e)return e.properties??void 0},mr=e=>{const t=e.options;if(!t)return{};const n={...t.pauseDurationSeconds&&{pauseDurationInSeconds:t.pauseDurationSeconds},...t.candidateEntryPoints?.length&&{entryPoints:(r=t.candidateEntryPoints,{type:"MultiPoint",coordinates:r.map(e=>d(e))}),...!P(t.preferredEntryPointIndex)&&{preferredEntryPointIndex:t.preferredEntryPointIndex}}};var r;return{...t.legCostModel?.routeType&&{routeType:t.legCostModel.routeType},...t.legCostModel?.avoid?.length&&{avoids:t.legCostModel.avoid.map(e=>({name:e}))},...Object.keys(n).length>0&&{routeStop:n}}},gr=(e,t)=>{t.computeTravelTimeFor&&e.searchParams.set("computeTravelTimeFor",t.computeTravelTimeFor)},hr=(e,t,n)=>{const r=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateLongDistanceEVRoute`,o=new URL(r);((e,t)=>{if(t?.model){if("variantId"in t.model)e.searchParams.set("vehicleModelId",t.model.variantId);else{const n=lr(t);n&&Hn(e.searchParams,cr(n))}Hn(e.searchParams,{...t.state&&xn(t),...Gn(t)})}})(o,e.vehicle),e.chargingStopsStrategy&&o.searchParams.set("chargingStopsStrategy",e.chargingStopsStrategy);const a=(e=>e.vehicle?.model&&!("variantId"in e.vehicle.model)?e.vehicle.model.engine?.charging:void 0)(e);if(!(e.vehicle?.model&&"variantId"in e.vehicle.model||a?.chargingConnectors?.length))throw new Error("Charging preferences require a charging model: set vehicle.model.engine.charging.chargingConnectors (or a predefined vehicle.model.variantId) to plan charging stops.");return{method:"POST",url:o,data:{...t,...a&&{chargingParameters:{...a.batteryCurve?.length&&{batteryCurve:a.batteryCurve},...a.chargingConnectors?.length&&{chargingConnectors:[...a.chargingConnectors]},...!P(a.chargingTimeOffsetInSec)&&{chargingTimeOffsetInSec:a.chargingTimeOffsetInSec}}},vehicleEngineType:"electric"},headers:n}},yr=e=>{const t=e.locations.map(p).includes("path"),n=((e,t)=>{const n=[];for(const r of e)if("waypoint"===p(r)){const e=pr(r),o=e?.candidateEntryPoints?.length?"ignore":t,[a,i]=d(r,{useEntryPoint:o});n.push({coordinate:[a,i],...e&&{options:e}})}else n.push(...dr(r));return n})(e.locations,e.useEntryPoints),r=(e=>{const t={type:"Point",coordinates:e[0].coordinate},n={type:"Point",coordinates:(e.at(-1)??e[0]).coordinate},r=e.slice(1,-1);return{origin:t,destination:n,...r.length&&{waypoints:{type:"MultiPoint",coordinates:r.map(e=>e.coordinate)}}}})(n),a=(e=>{return{...e.costModel?.routeType&&{routeType:e.costModel.routeType},...e.costModel?.traffic&&{traffic:e.costModel.traffic},...e.costModel?.avoid?.length&&{avoids:e.costModel.avoid},...e.travelMode&&{travelMode:e.travelMode},...e.maxAlternatives&&{maxPathAlternativeRoutes:e.maxAlternatives},..."departAt"===e.when?.option&&e.when.date&&{departureDateTime:e.when.date.toISOString()},..."arriveBy"===e.when?.option&&e.when.date&&{arrivalDateTime:e.when.date.toISOString()},...e.guidance&&(n=e.guidance,{guidance:"instructions",instructionPhonetics:n.phonetics?n.phonetics.toLowerCase():"ipa"}),...e.costModel?.avoidAreas?.length&&{avoidAreas:(t=e.costModel.avoidAreas,{rectangles:t.map(e=>{const t=o(e);if(!t)throw new Error("Could not derive a bounding box from an avoidAreas rectangle");const[n,r,a,i]=t;return{type:"Feature",bbox:[n,r,a,i],geometry:null}})})},...e.arrivalSide&&{arrivalSidePreference:"curb"===e.arrivalSide?"curbSide":"anySide"}};var t,n})(e),i=(e=>({...ye(e),Attributes:ir(e)}))(e),s=((e,t)=>{const n=e.slice(1).map((t,n)=>({...e[n].legToNext,...mr(t)}));if(t||!n.every(e=>0===Object.keys(e).length))return n})(n,t),c={routePlanningLocations:r,...a,...s&&{legs:s},...e.vehicle&&sr(e.vehicle)};if(ur(e)){const t=hr(e,c,i);return gr(t.url,e),t}if(e.vehicle?.model&&"variantId"in e.vehicle.model)throw new Error("vehicle.model.variantId is only supported for EV routes with charging stops: set vehicle.preferences.chargingPreferences, or describe the vehicle with vehicle.model.dimensions and vehicle.model.engine instead.");const l=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/routes/calculate`,u=new URL(l);return e.vehicle&&((e,t)=>{const n=lr(t);if(!n)return;const r="electric"===t.engineType;Hn(e.searchParams,{...r?{...cr(n),...xn(t)}:{...Nn(n),..._n(t)}})})(u,e.vehicle),gr(u,e),{method:"POST",url:u,data:c,headers:i}},fr=L.union([X,J]),Tr=L.union([Z,z]),Rr=L.object({locations:L.array(L.union([fr,Tr])).min(1)}),Ir=L.object({arrivalSide:L.enum(["any","curb"]).optional(),chargingStopsStrategy:L.enum(["automaticFastest","manualFastest","automaticFastestWithFallbackToManual"]).optional(),computeTravelTimeFor:L.enum(["none","all"]).optional(),maxAlternatives:L.number().min(0).max(5).optional(),sectionTypes:L.array(L.enum(h)).optional()}),Sr=In.extend(Rr.extend(Ir.shape).shape),br=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},Cr=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,o=[r.coordinate.longitude,r.coordinate.latitude],a=[r.street,r.houseNumber].filter(Boolean),i=a.length>0?a.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:o},properties:{...E(e,["chargingConnectionInfo","chargingParkLocation"]),type:"POI",address:{freeformAddress:i,...r.street&&{streetName:r.street},...r.houseNumber&&{streetNumber:r.houseNumber},...r.city&&{municipality:r.city},...r.region&&{countrySubdivision:r.region},...r.postalCode&&{postalCode:r.postalCode},...r.country&&{country:r.country}},...n&&{chargingConnectionInfo:{plugType:n.chargingPlugType,currentInA:n.chargingCurrentInA,voltageInV:n.chargingVoltageInV,chargingPowerInkW:n.chargingPowerInkW,currentType:br(n.chargingCurrentType),chargingSpeed:Ne(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:Ne(e.chargingParkPowerInkW)}}}},vr=(e,t)=>{const n=(t?.vehicle?.model)?.engine?.charging?.maxChargeKWH;return{lengthInMeters:e.lengthInMeters,travelTimeInSeconds:e.travelDurationInSeconds,trafficDelayInSeconds:e.trafficDelayDurationInSeconds??0,trafficLengthInMeters:e.trafficLengthInMeters??0,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,departureTime:new Date(e.departureDateTime),arrivalTime:new Date(e.arrivalDateTime),deviationDistanceInMeters:e.deviationDistanceInMeters,deviationTimeInSeconds:e.deviationDurationInSeconds,...e.deviationPoint&&{deviationPoint:e.deviationPoint.coordinates},fuelConsumptionInLiters:e.fuelConsumptionInLiters,totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh,...n&&(()=>{const t=e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh;return t?{batteryConsumptionInPCT:100*t/n}:void 0})(),remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:Cr(e.chargingInformationAtEndOfLeg,n)}}},Ar=(e,t)=>e.reduce((n,r,o)=>{const a=r.path.coordinates.length,i=0===o?0:n[o-1]?.endPointIndex;let c;P(i)||(c=0===i?Math.max(a-1,0):i+a);const l=((e,t)=>{if(!t)return;const n=new Date(e.summary.arrivalDateTime).getTime(),r=new Date(t.summary.departureDateTime).getTime();if(Number.isNaN(n)||Number.isNaN(r))return;const o=Math.round((r-n)/1e3);return o>0?o:void 0})(r,e[o+1]),{originalWaypointIndexAtEndOfLeg:u}=r.summary;return n.push({...!P(i)&&{startPointIndex:i},...void 0!==c&&{endPointIndex:c},...!P(u)&&{originalWaypointIndex:u},summary:{...vr(r.summary,t),...void 0!==l&&{stopTimeInSeconds:l}},id:s()}),n},[]),Lr=e=>({id:s(),startPointIndex:e.startPathIndex,endPointIndex:e.endPathIndex}),Pr=e=>{if(e.tec?.causes?.length)return e.tec.causes.map(e=>{switch(e.mainCauseCode){case 1:return"jam";case 2:return"accident";case 3:return"roadworks";case 4:return"narrow-lanes";case 5:return"road-closed";case 9:return"danger";case 11:return"animals-on-road";case 13:return"broken-down-vehicle";case 16:return"lane-closed";case 17:return"wind";case 18:return"fog";case 19:return"rain";case 22:return"frost";case 23:return"flooding";default:return"other"}});switch(e.iconCategory){case"jam":return["jam"];case"accident":return["accident"];case"brokenDownVehicle":return["broken-down-vehicle"];case"dangerousConditions":return["danger"];case"flooding":return["flooding"];case"fog":return["fog"];case"ice":return["frost"];case"laneClosed":return["lane-closed"];case"rain":return["rain"];case"roadClosed":return["road-closed"];case"roadWorks":return["roadworks"];case"wind":return["wind"];default:return["other"]}},Er=(e,t)=>{const n={leg:Ar(e.legs,t)},r=e.sections;if(!r)return n;const o=(e,t)=>{t?.length&&(n[e]=t.map(Lr))};return o("carTrain",r.carTrain),o("ferry",r.ferry),o("tunnel",r.tunnel),o("motorway",r.motorway),o("pedestrian",r.pedestrian),o("toll",r.toll),o("tollRoad",r.tollRoad),o("carpool",r.carpool),o("urban",r.urban),o("unpaved",r.unpaved),o("lowEmissionZone",r.lowEmissionZone),r.country?.length&&(n.country=r.country.map(e=>({...Lr(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:Jn(e.countryCodeIso2??"")}))),r.travelMode?.length&&(n.vehicleRestricted=r.travelMode.filter(e=>"other"===e.travelMode).map(Lr)),r.traffic?.length&&(n.traffic=r.traffic.map(e=>({...Lr(e),delayInSeconds:e.delayDurationInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKilometersPerHour,categories:Pr(e),magnitudeOfDelay:"undefined"===e.delayMagnitude?"indefinite":e.delayMagnitude,tec:e.tec,...e.eventId&&{eventId:e.eventId}}))),r.speedLimit?.length&&(n.speedLimit=r.speedLimit.map(e=>{const t=e.speedRestrictions?.find(e=>"maximum"===e.type)?.inKilometersPerHour;return P(t)?void 0:{...Lr(e),maxSpeedLimitInKmh:t}}).filter(e=>!!e)),r.lanes?.length&&(n.lanes=r.lanes.map(e=>({...Lr(e),lanes:(e.lanes??[]).map(e=>({directions:e.directions.map(e=>_r[e]??e),...e.follow&&{follow:_r[e.follow]??e.follow}})),laneSeparators:(e.laneSeparators??[]).map(e=>Gr[e]??e),properties:e.properties}))),r.roadShields?.length&&(n.roadShields=r.roadShields.map(e=>({...Lr(e),roadShieldReferences:e.roadShieldReferences}))),r.tollVignette?.length&&(n.tollVignette=r.tollVignette.map(e=>({...Lr(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:Jn(e.countryCodeIso2??"")}))),r.importantRoadStretch?.length&&(n.importantRoadStretch=r.importantRoadStretch.map(e=>({...Lr(e),index:e.importantRoadStretchIndex,...e.streetName&&{streetName:e.streetName.text},...e.roadNumbers?.length&&{roadNumbers:e.roadNumbers.map(e=>e.text)}}))),((e,t)=>{if(!t)return;const n=new Set(t);for(const r of Object.keys(e))"leg"===r||n.has(r)||delete e[r]})(n,t.sectionTypes),n},Mr=1e-4,Dr=(e,t)=>Math.abs(e[0]-t[0])<Mr&&Math.abs(e[1]-t[1])<Mr,Nr={depart:"DEPART",waypointLeft:"WAYPOINT_LEFT",waypointRight:"WAYPOINT_RIGHT",waypointReached:"WAYPOINT_REACHED",waypointAhead:"WAYPOINT_AHEAD",arrive:"ARRIVE",arriveLeft:"ARRIVE_LEFT",arriveRight:"ARRIVE_RIGHT",arriveAhead:"ARRIVE_AHEAD",continueStraight:"STRAIGHT",keepLeft:"KEEP_LEFT",keepRight:"KEEP_RIGHT",turnSlightRight:"SLIGHT_RIGHT",turnRight:"TURN_RIGHT",turnSharpRight:"SHARP_RIGHT",turnSlightLeft:"SLIGHT_LEFT",turnLeft:"TURN_LEFT",turnSharpLeft:"SHARP_LEFT",makeUTurn:"MAKE_UTURN",roundaboutStraight:"ROUNDABOUT_STRAIGHT",roundaboutSharpRight:"ROUNDABOUT_SHARP_RIGHT",roundaboutRight:"ROUNDABOUT_RIGHT",roundaboutSlightRight:"ROUNDABOUT_SLIGHT_RIGHT",roundaboutSlightLeft:"ROUNDABOUT_SLIGHT_LEFT",roundaboutLeft:"ROUNDABOUT_LEFT",roundaboutSharpLeft:"ROUNDABOUT_SHARP_LEFT",roundaboutBack:"ROUNDABOUT_BACK",exitRoundabout:"EXIT_ROUNDABOUT",exitMotorwayLeft:"EXIT_MOTORWAY_LEFT",exitMotorwayRight:"EXIT_MOTORWAY_RIGHT",switchMotorwayLeft:"SWITCH_MOTORWAY_LEFT",switchMotorwayRight:"SWITCH_MOTORWAY_RIGHT",enterCarpoolLaneLeft:"ENTER_CARPOOL_LANE_LEFT",enterCarpoolLaneRight:"ENTER_CARPOOL_LANE_RIGHT",exitCarpoolLaneLeft:"EXIT_CARPOOL_LANE_LEFT",exitCarpoolLaneRight:"EXIT_CARPOOL_LANE_RIGHT",mergeLeftLane:"MERGE_LEFT_LANE",mergeRightLane:"MERGE_RIGHT_LANE",takeShipFerry:"TAKE_SHIP_FERRY",takeCarTrain:"TAKE_CAR_TRAIN",leaveShipFerry:"LEAVE_SHIP_FERRY",leaveCarTrain:"LEAVE_CAR_TRAIN",crossBorder:"CROSS_BORDER",passTollgate:"TOLLGATE"},wr={urban:"URBAN",motorway:"MOTORWAY",controlledAccess:"CONTROLLED_ACCESS"},Or={endOfRoad:"END_OF_ROAD",atTrafficLight:"AT_TRAFFIC_LIGHT",onToBridge:"ON_TO_BRIDGE",onBridge:"ON_BRIDGE",afterBridge:"AFTER_BRIDGE",intoTunnel:"INTO_TUNNEL",insideTunnel:"INSIDE_TUNNEL",afterTunnel:"AFTER_TUNNEL"},xr={cashCoinsAndBills:"CASH_COINS_AND_BILLS",cashBillsOnly:"CASH_BILLS_ONLY",cashCoinsOnly:"CASH_COINS_ONLY",cashExactChange:"CASH_EXACT_CHANGE",creditCard:"CREDIT_CARD",debitCard:"DEBIT_CARD",travelCard:"TRAVEL_CARD",etc:"ETC",etcTransponder:"ETC_TRANSPONDER",etcVideoCamera:"ETC_VIDEO_CAMERA",subscription:"SUBSCRIPTION"},_r={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",rightUTurn:"RIGHT_U_TURN",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",leftUTurn:"LEFT_U_TURN"},Gr={unknown:"UNKNOWN",noMarking:"NO_MARKING",longDashed:"LONG_DASHED",doubleSolid:"DOUBLE_SOLID",singleSolid:"SINGLE_SOLID",solidDashed:"SOLID_DASHED",dashedSolid:"DASHED_SOLID",shortDashed:"SHORT_DASHED",shadedAreaMarking:"SHADED_AREA_MARKING",dashedBlocks:"DASHED_BLOCKS",doubleDashed:"DOUBLE_DASHED",crossingAlert:"CROSSING_ALERT",physicalDivider:"PHYSICAL_DIVIDER",physicalDividerLessThan3m:"PHYSICAL_DIVIDER_LESS_THAN_3M",physicalDividerGuardrail:"PHYSICAL_DIVIDER_GUARDRAIL",curb:"CURB"},Br={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",back:"BACK"},Hr={regular:"REGULAR",small:"SMALL"},Fr={left:"LEFT",right:"RIGHT",leftAndRight:"LEFT_AND_RIGHT"},Ur={properties:[]},kr=e=>{const t=e.phonetic;return{text:e.text,...t&&{phonetic:t},...e.phoneticLanguageCode&&{phoneticLanguageCode:e.phoneticLanguageCode}}},Wr=e=>({properties:(e.properties??[]).map(e=>wr[e]??e.toUpperCase()),...e.roadNames?.length&&{streetName:kr(e.roadNames[0].identifier)},...e.countryCodeIso2&&{countryCode:Jn(e.countryCodeIso2)},...e.roadShields?.length&&{roadShields:e.roadShields.map(e=>({roadNumber:e.roadNumber?kr(e.roadNumber):{text:""},countryCode:Jn(e.countryCodeIso2??""),...e.countrySubdivisionCodeIso&&{stateCode:e.countrySubdivisionCodeIso},...e.iconReference&&{roadShieldReference:e.iconReference}}))}}),Kr=e=>({...e.tollgateName&&{tollgateName:kr(e.tollgateName)},...e.tollPaymentTypes?.length&&{tollPaymentTypes:e.tollPaymentTypes.map(e=>xr[e]??e)},...e.countryCrossingFromName&&{countryCrossingFromName:kr(e.countryCrossingFromName)},...e.countryCrossingFromCodeIso2&&{countryCrossingFromCode:Jn(e.countryCrossingFromCodeIso2)},...e.countryCrossingToName&&{countryCrossingToName:kr(e.countryCrossingToName)},...e.countryCrossingToCodeIso2&&{countryCrossingToCode:Jn(e.countryCrossingToCodeIso2)}}),Vr=e=>Br[e]??e,jr=e=>{return{...e.message&&{message:e.message},...e.intersectionName&&{intersectionName:kr(e.intersectionName)},...e.drivingSide&&{drivingSide:e.drivingSide.toUpperCase()},...e.landmark&&{landmark:Or[e.landmark]??e.landmark},...!P(e.distanceToPreviousTrafficLightInMeters)&&{trafficLightOffsetInMeters:e.distanceToPreviousTrafficLightInMeters},...e.sideRoads&&{sideRoads:(n=e.sideRoads,n.map(e=>({side:Fr[e.side]??e.side,offsetFromManeuverInMeters:e.offsetFromManeuverInMeters,...!P(e.isDrivable)&&{isDrivable:e.isDrivable}})))},...e.maneuverView&&{maneuverView:(t=e.maneuverView,{...t.onRouteAngle&&{onRouteAngle:Vr(t.onRouteAngle)},offRouteAngles:(t.offRouteAngles??[]).map(Vr)})},...e.roundaboutType&&{roundaboutType:Hr[e.roundaboutType]??e.roundaboutType},...!P(e.isManeuverObligatory)&&{isManeuverObligatory:e.isManeuverObligatory},...!P(e.changeOfAngleInDegrees)&&{changeOfAngleInDegrees:e.changeOfAngleInDegrees},...!P(e.ambiguousExitOffsetFromManeuverInMeters)&&{offsetOfAmbiguousExitFromManeuverInMeters:e.ambiguousExitOffsetFromManeuverInMeters},...!P(e.roundaboutExitNumber)&&{roundaboutExitNumber:e.roundaboutExitNumber}};var t,n},qr=(e,t)=>{const n=e.signpost?(e=>{if(e.exitName||e.exitNumber||e.towardName)return{...e.exitName&&{exitName:kr(e.exitName)},...e.exitNumber&&{exitNumber:kr(e.exitNumber)},towardName:e.towardName?kr(e.towardName):{text:""}}})(e.signpost):void 0,r=(e.nextRoadInformation?.roadShields??[]).map(e=>e.iconReference).filter(e=>!!e);return{...n&&{signpost:n},...t&&{roadShieldAtlasReference:t},...r.length&&{roadShieldReferences:r},...e.signpost?.exitIconReference&&{signpostRoadShieldReferences:[e.signpost.exitIconReference]}}},Yr=(e,t,n,r)=>({maneuverPoint:t,pathPointIndex:n,routeOffsetInMeters:e.routeOffsetInMeters,maneuver:e.maneuver?Nr[e.maneuver]??e.maneuver:e.maneuver,routePath:(e.routePath??[]).map(e=>({point:e.point.coordinates,distanceInMeters:e.distanceFromRouteStartInMeters,travelTimeInSeconds:e.travelTimeFromRouteStartInSeconds})),nextRoadInfo:e.nextRoadInformation?Wr(e.nextRoadInformation):Ur,previousRoadInfo:e.previousRoadInformation?Wr(e.previousRoadInformation):Ur,...jr(e),...qr(e,r),...Kr(e)}),$r=(e,t,n)=>{const r=[];let o=0;for(const a of e){const e=a.maneuverPoint.coordinates;for(let n=o;n<t.length;n++)if(Dr(t[n],e)){o=n;break}r.push(Yr(a,e,o,n))}return{instructions:r}},Zr=(e,t)=>{const n=e.routes.map((n,r)=>((e,t,n,r)=>{const a={type:"LineString",coordinates:e.legs.flatMap(e=>e.path.coordinates)};return{type:"Feature",geometry:a,id:s(),bbox:o(a),properties:{index:t,summary:vr(e.summary,n),sections:Er(e,n),...e.instructions?.length&&{guidance:$r(e.instructions,a.coordinates,r)},...e.progressPoints&&{progress:e.progressPoints.map(e=>({pointIndex:e.pathIndex,distanceInMeters:e.distanceInMeters,travelTimeInSeconds:e.travelDurationInSeconds}))}}}})(n,r,t,e.roadShieldAtlasReference)),r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},Jr={requestValidation:{schema:Sr,refinements:[{check:e=>{const t=e.locations.map(p),n=t.filter(e=>"waypoint"===e).length,r=t.filter(e=>"path"===e).length;return n>=2||r>=1},message:"At least 2 waypoints or 1 path (route reconstruction) is required."},{check:e=>!e.chargingStopsStrategy||ur(e),message:"chargingStopsStrategy: set vehicle.preferences.chargingPreferences as well — an EV route needs a minimum charge at the destination, which only the charging preferences provide."},{check:e=>!(e.vehicle?.model&&"variantId"in e.vehicle.model)||ur(e),message:"vehicle.model.variantId is only supported for EV routes with charging stops: set vehicle.preferences.chargingPreferences, or describe the vehicle with vehicle.model.dimensions and vehicle.model.engine instead."},{check:e=>{const t=e.locations.at(-1);return!t||"waypoint"!==p(t)||!t.properties?.pauseDurationSeconds},message:"pauseDurationSeconds is not supported on the destination: the routing API requires the wait on the last leg to be 0."}]},buildRequest:yr,sendRequest:$,parseResponse:Zr,parseResponseError:Ht,getAPIVersion:()=>3},zr={buildCalculateRouteRequest:yr,parseCalculateRouteResponse:Zr,calculateRouteTemplate:Jr},Qr=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],Xr={speed:"SPEED",freeFlowSpeed:"FREE_FLOW_SPEED",congestionLevel:"CONGESTION_LEVEL",travelTime:"TRAVEL_TIME",networkLength:"NETWORK_LENGTH"},eo=e=>e instanceof Date?e.toISOString().slice(0,10):e,to=Array.from({length:24},(e,t)=>t),no=e=>Qr.indexOf(e),ro=e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));fe(n.searchParams,e);const r=e=>{const t=/* @__PURE__ */new Date;return t.setDate(t.getDate()-e),t},o=Array.isArray(e.days)?{days:e.days.map(eo)}:{startDate:eo(e.startDate??r(3)),endDate:eo(e.endDate??r(2))};return{method:"POST",url:n,data:{name:e.name??`Maps SDK JS Area Analytics Report ${/* @__PURE__ */(new Date).toISOString()}`,...o,dataTypes:"all"===e.metrics?t.map(e=>Xr[e]):e.metrics.map(e=>Xr[e]),frcs:"all"===e.functionalRoadClasses?Qr.map((e,t)=>t):e.functionalRoadClasses.map(no),hours:"all"===e.hours?to:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},oo=e=>({...void 0!==e.v&&{speed:e.v},...void 0!==e.fv&&{freeFlowSpeed:e.fv},...void 0!==e.c&&{congestionLevel:e.c},...void 0!==e.t&&{travelTime:e.t},...void 0!==e.l&&{networkLength:e.l}}),ao=e=>({...void 0!==e.date&&{date:new Date(e.date)},...void 0!==e.year&&{year:e.year},...void 0!==e.month&&{month:e.month},...void 0!==e.week&&{week:e.week},...void 0!==e.hour&&{hour:e.hour},...void 0!==e.day&&{day:e.day},...oo(e)}),io=(e,t)=>{const n=new Date(e);return n.setDate(n.getDate()+t),n},so=(e,t)=>e.map((e,n)=>{const r=ao(e);return void 0===r.date&&(r.date=io(t,Math.floor(n/24))),void 0===r.hour&&(r.hour=n%24),r}),co=(e,t)=>e.map((e,n)=>{const r=ao(e);return void 0===r.date&&(r.date=io(t,n)),r}),lo=e=>({tileCentre:[e.lon,e.lat],...oo(e)}),uo=e=>({startDate:new Date(e.startDate),endDate:new Date(e.endDate),labels:e.labels}),po=(e,t)=>{return{...e.yearly&&{yearly:e.yearly.map(ao)},...e.monthly&&{monthly:e.monthly.map(ao)},...e.weekly&&{weekly:e.weekly.map(ao)},...e.daily&&{daily:co(e.daily,t)},...e.hourly&&{hourly:so(e.hourly,t)},...e.average&&{average:(n=e.average,n.map((e,t)=>{const n=ao(e);return void 0===n.day&&(n.day=Math.floor(t/24)+1),void 0===n.hour&&(n.hour=t%24),n}))}};var n},mo={SPEED:"speed",FREE_FLOW_SPEED:"freeFlowSpeed",CONGESTION_LEVEL:"congestionLevel",TRAVEL_TIME:"travelTime",NETWORK_LENGTH:"networkLength"},go=e=>{const t={};for(const[n,r]of Object.entries(e)){const e=mo[n];e&&(t[e]=r.map(uo))}return t},ho=(e,t)=>({name:e.name,timezone:e.timezone,level:e.level,baseData:oo(e.baseData),timedData:po(e.timedData,t),...e.tiledData&&{tiledData:{tiles:e.tiledData.tiles.map(lo)}},...e.anomalies&&{anomalies:go(e.anomalies)}}),yo=e=>{const n=e.flatMap(e=>e.properties.tiledData?.tiles??[]),r={};for(const o of t){const e=n.map(e=>e[o]).filter(e=>null!=e);e.length>0&&(r[o]={min:Math.min(...e),max:Math.max(...e)})}return r},fo=e=>{const t=new Date(e.properties.startDate),n=e.features.map(e=>((e,t)=>({type:e.type,id:e.id,geometry:e.geometry,properties:ho(e.properties,t),bbox:o(e.geometry)}))(e,t));return{type:"FeatureCollection",properties:{startDate:t,endDate:new Date(e.properties.endDate),metrics:e.properties.dataTypes.map(e=>mo[e]).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:yo(n)},features:n}},To=L.union([L.date(),L.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),Ro=L.union([L.object({type:L.literal("Polygon"),coordinates:L.array(L.array(L.array(L.number()))).min(1)}),L.object({type:L.literal("MultiPolygon"),coordinates:L.array(L.array(L.array(L.array(L.number())))).min(1)})]),Io=e=>e instanceof Date?e:new Date(e),So=e=>{const t=/* @__PURE__ */new Date,n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return(e=>{const t=Io(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())})(e)<=n-1728e5},bo={requestValidation:{schema:B.extend({name:L.string().optional(),startDate:To.optional(),endDate:To.optional(),days:L.array(To).min(1).optional(),metrics:L.union([L.array(L.enum(t)).min(1),L.literal("all")]),functionalRoadClasses:L.union([L.array(L.enum(Qr)).min(1),L.literal("all")]),hours:L.union([L.array(L.number().int().min(0).max(23)).min(1),L.literal("all")]),geometry:Ro}).refine(e=>{const t=void 0!==e.days,n=void 0!==e.startDate;if(t&&n)return!1;if(!t&&!n)return!1;if(void 0!==e.startDate){const t=((void 0!==e.endDate?Io(e.endDate):/* @__PURE__ */new Date).getTime()-Io(e.startDate).getTime())/864e5;return t>=1&&t<=31}return!0},{message:"Provide either startDate (with optional endDate, at least 1 day apart and within 31 days) or days — but not both"}).refine(e=>{if(void 0!==e.days)return e.days.every(So);const t=e.endDate??/* @__PURE__ */new Date;return So(t)},{message:"Dates must be at least 2 days before today"})},buildRequest:ro,sendRequest:$,parseResponse:fo},Co={buildTrafficAreaAnalyticsRequest:ro,parseTrafficAreaAnalyticsResponse:fo,trafficAreaAnalyticsTemplate:bo},vo=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidentDetails`)(e)),n=t.searchParams;if(fe(n,e),((e,t)=>{Se(e,"fields","{incidents{type,geometry{type,coordinates},properties{id,iconCategory,magnitudeOfDelay,events{description,code,iconCategory},startTime,endTime,from,to,length,delay,roadNumbers,timeValidity,probabilityOfOccurrence,numberOfReports,lastReportTime,tmc{countryCode,tableNumber,tableVersion,direction,points{location,offset}}}}}"),Se(e,"t",t.trafficModelId),Ie(e,"categoryFilter",t.categoryFilter?.map(v)),Ie(e,"timeValidityFilter",t.timeValidityFilter)})(n,e),"bbox"in e&&e.bbox){const r=o(e.bbox);return r&&n.append("bbox",r.join(",")),{method:"GET",url:t}}const{ids:r}=e;return r.length>5?{method:"POST",url:t,data:{ids:r}}:(n.append("ids",r.join(",")),{method:"GET",url:t})},Ao=e=>({description:e.description,code:e.code,category:m(e.iconCategory)}),Lo=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:m(t.iconCategory),magnitudeOfDelay:g[t.magnitudeOfDelay]??"unknown",events:(t.events??[]).map(Ao),...t.startTime&&{startTime:new Date(t.startTime)},...t.endTime&&{endTime:new Date(t.endTime)},...t.from&&{from:t.from},...t.to&&{to:t.to},...null!=t.length&&{lengthInMeters:t.length},...null!=t.delay&&{delayInSeconds:t.delay},...t.roadNumbers&&{roadNumbers:t.roadNumbers},timeValidity:t.timeValidity,...t.probabilityOfOccurrence&&{probabilityOfOccurrence:t.probabilityOfOccurrence},...null!=t.numberOfReports&&{numberOfReports:t.numberOfReports},...t.lastReportTime&&{lastReportTime:new Date(t.lastReportTime)},...t.tmc&&{tmc:(n=t.tmc,{countryCode:n.countryCode,tableNumber:n.tableNumber,tableVersion:n.tableVersion,direction:n.direction,points:(n.points??[]).map(e=>({location:e.location,...null!=e.offset&&{offset:e.offset}}))})}}};var n},Po=e=>({type:"FeatureCollection",features:(e.incidents??[]).filter(e=>null!==e).map(Lo)}),Eo={requestValidation:{schema:B.extend({bbox:ne.optional(),ids:L.array(L.string()).optional(),trafficModelId:L.string().optional(),categoryFilter:L.array(L.enum(C)).optional(),timeValidityFilter:L.array(L.enum(["present","future"])).optional()}).refine(e=>!(e.bbox&&e.ids),{message:"Provide either bbox or ids, not both"})},buildRequest:vo,sendRequest:$,parseResponse:Po},Mo={alongRouteSearch:Xe,reverseGeocode:or,geocode:gt,geometryData:bt,geometrySearch:Dt,calculateRoute:zr,reachableRange:qn,evChargingStationsAvailability:st,trafficAreaAnalytics:Co,trafficIncidentDetails:{buildTrafficIncidentDetailsRequest:vo,parseTrafficIncidentDetailsResponse:Po,trafficIncidentDetailsTemplate:Eo},placeByID:Bt,autocompleteSearch:et},Do=async(e,t)=>U(e,{...it,...t},"EVChargingStationsAvailability"),No=async(e,t)=>{const n=e.properties.dataSources?.chargingAvailability?.id;if(n)try{const r=await Do({...t,id:n}),o=e.properties.poi;return r?{...e,properties:{...e.properties,...o&&{poi:{...o,openingHours:r.openingHours}},chargingPark:{...e.properties.chargingPark,availability:r}}}:void 0}catch(r){return void console.error(r)}};async function wo(e,t){const{excludeIfAvailabilityUnknown:n,...r}=t??{},a=[];for(const o of e.features){const e=await No(o,r);e?a.push(e):n||a.push(o)}return{...e,features:a,bbox:o(a)}}var Oo=e=>Boolean(e&&"availability"in e&&e.availability),xo=async(e,t)=>U(e,{...mt,...t},"Geocode"),_o=async e=>{const t=await xo({query:e,limit:1});if(!t.features[0])throw new Error(`geocodeOne: no results found for "${e}"`);return t.features[0]};async function Go(e,t){const n=await U(e,{...St,...t},"GeometryData");return Array.isArray(e.geometries)||"FeatureCollection"!==e.geometries.type?n:((e,t)=>{const n=e.features.reduce((e,t)=>{const n=t.properties.dataSources?.geometry?.id;return n&&(e[n]={...t.properties,placeCoordinates:t.geometry.coordinates}),e},{}),r=t.features.map(e=>e.id&&n[e.id]?{...e,properties:n[e.id]}:e);return{type:"FeatureCollection",bbox:t.bbox,features:r}})(e.geometries,n)}var Bo=async(e,t)=>U(e,{...Gt,...t},"PlaceById"),Ho=/* @__PURE__ */new Map,Fo=/* @__PURE__ */new Map,Uo="en-GB",ko=e=>e??Uo,Wo=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),Ko=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(Wo);for(const r of e)t[r]=n}return t},Vo=B.extend({filters:L.array(L.string()).optional()}),jo=e=>{const t=S[e.id];return t?{code:t,name:e.name,childCategoryCodes:e.childCategoryIds.map(e=>S[e]).filter(e=>!!e),synonyms:e.synonyms}:(console.error(`Received unknown POI category ID ${e.id} (${e.name}). This category will be skipped and unavailable for filtering.`),null)},qo={requestValidation:{schema:Vo},buildRequest:e=>{const t=ve(e,"poiCategories.json"),n=new URL(t);return Re(n.searchParams,e),{url:n,headers:Te(e)}},getAPIVersion:()=>1,sendRequest:q,parseResponse:e=>({poiCategories:e.poiCategories.map(jo).filter(e=>null!==e)})},Yo=(e,t)=>{const n=(e=>Fo.get(e??Uo)??{})(e),r=/* @__PURE__ */new Map;for(const o of t){const e=Wo(o);for(const[t,o]of Object.entries(n))t.includes(e)&&o&&r.set(o.code,o)}for(const o of r.values())for(const e of o.childCategoryCodes)r.delete(e);return[...r.values()]},$o=async(e={})=>{const{language:t}=f(e);let n=(e=>Ho.get(ko(e)))(t);return n||(n=(await U(e,qo,"POICategories")).poiCategories,((e,t)=>{const n=ko(e);Ho.set(n,t),Fo.set(n,Ko(t))})(t,n)),e.filters?.length?{poiCategories:Yo(t,e.filters)}:{poiCategories:n}},Zo=async(e={})=>{const{poiCategories:t}=await $o(e);return t.map(e=>e.code)},Jo=async(e,t)=>U(e,{...jn,...t},"Reachable Range"),zo=(...e)=>{const t=e.filter(e=>!!e);return t.length<2?t[0]:AbortSignal.any(t)},Qo=async(e,t,n)=>{const r=[];for(const o of e){const e=zo(o.signal,t?.signal);try{r.push(await Jo({...o,...e&&{signal:e}},n))}catch(i){if(!(i instanceof w)||403===i.status||429===i.status)throw i}}const a=o(r);return{type:"FeatureCollection",...a&&{bbox:a},features:r}},Xo=async(e,t)=>U(e,{...rr,...t},"ReverseGeocode"),ea=async(e,t)=>U(e,{...Jr,...t},"Routing"),ta=L.object({minFuzzyLevel:L.number().min(1).max(4).optional(),maxFuzzyLevel:L.number().min(1).max(4).optional()}),na=ae.extend(ct.extend(ta.shape).shape),ra=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:_e(e.details)}};break;case"NEARBY":t={...e,details:{position:_e({lon:e.details.lon,lat:e.details.lat}),text:e.details.text,query:e.details.query}};break;case"BOOKMARK":case"W3W":t=e}return t},oa={requestValidation:{schema:na},buildRequest:e=>{const t=new URL(`${(e=>ve(e,`search/${e.query??""}.json`))(e)}`);Ce(t,e);const n=t.searchParams;return Se(n,"typeahead",e.typeahead),Se(n,"ofs",e.offset),Ie(n,"countrySet",e.countries),be(n,e.geoBias),Se(n,"minFuzzyLevel",e.minFuzzyLevel),Se(n,"maxFuzzyLevel",e.maxFuzzyLevel),{url:t,headers:Te(e)}},sendRequest:q,parseResponse:e=>{const t=e.results.map(Fe),n=a(o(t)),r=e.summary.queryIntent?.map(ra);return{type:"FeatureCollection",properties:{...Ue(e.summary),...r&&{queryIntent:r}},features:t,...n&&{bbox:n}}}},aa=async(e,t)=>"route"in e?Ke(e,t):"geometries"in e?Mt(e,t):(async(e,t)=>U(e,{...oa,...t},"FuzzySearch"))(e,t),ia=async e=>{const t=await aa({query:e,limit:1});if(!t.features[0])throw new Error(`searchOne: no results found for "${e}"`);return t.features[0]},sa=async(e,t)=>U(e,{...bo,...t},"TrafficAreaAnalytics"),ca=async(e,t)=>U(e,{...Eo,...t},"TrafficIncidentDetails");export{N as APIErrorCode,O as SDKAbortError,D as SDKError,w as SDKServiceError,Ke as alongRouteSearch,Qe as autocompleteSearch,Sn as budgetTypes,_ as buildResponseError,G as buildValidationError,Jo as calculateReachableRange,Qo as calculateReachableRanges,ea as calculateRoute,Mo as customizeService,Do as evChargingStationsAvailability,xo as geocode,_o as geocodeOne,Go as geometryData,$o as getPOICategories,Zo as getPOICategoryCodes,No as getPlaceWithEVAvailability,wo as getPlacesWithEVAvailability,Oo as hasChargingAvailability,x as parseDefaultResponseError,Bo as placeById,Xo as reverseGeocode,nt as routeTypes,aa as search,ia as searchOne,rt as tollTransponderOptions,sa as trafficAreaAnalytics,ca as trafficIncidentDetails};
|
|
1
|
+
import{TomTomConfig as e,areaAnalyticsMetricKeys as t,avoidableTypes as n,bboxFromCoordsArray as r,bboxFromGeoJSON as o,bboxOnlyIfWithArea as a,currentTypes as i,generateId as s,generateTomTomHeaders as c,geographyTypes as l,getPosition as u,getPositionStrict as d,getRoutePlanningLocationType as p,inputSectionTypesWithGuidance as m,isProxyCredentialsMode as g,mergeFromGlobal as h,plugTypes as y,poiCategories as f,poiCategoriesToID as T,poiIDsToCategories as R,toPointGeometry as b,trafficIncidentRequestCategories as I,views as S}from"@tomtom-org/maps-sdk/core";import{z as C}from"zod";import{countBy as v,isNil as A,maxBy as P,minBy as L,omit as M,partition as E,pick as w,uniqBy as D}from"lodash-es";import{bbox as x,booleanIntersects as O}from"@turf/turf";var N=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),B=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},H={[N.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[N.FORBIDDEN]:"Request failed with status code 403"},_=class extends B{constructor(e,t,n){super(e,t),this.status=n,this.status&&H[this.status]&&(this.message=H[this.status])}},F=class extends B{constructor(e,t){super("The operation was aborted.",e),this.name="AbortError",this.cause=t}},U=(e,t)=>{const{data:n,message:r,status:o}=e;return new _(n?.error||n?.errorText||r,t,o)},G=(e,t,n,r)=>{if(r?.aborted&&e===r.reason)return new F(t,r.reason);if(r?.aborted&&"AbortError"===e?.name)return new F(t,r.reason);if(e.status){const r=e;return n?n(r,t):U(r,t)}return new B(e.message,t)},k=(e,t)=>new B(e.message,t,e.issues),K=C.object({apiKey:C.string().optional(),commonBaseURL:C.string().optional(),customServiceBaseURL:C.string().optional(),language:C.string().optional()}),W=(e,t=0)=>{const n=e.path.length>0?`${e.path.join(".")}: `:"";if("invalid_union"===e.code){const r=e.unionErrors;if(r?.length)return`${n}no matching union member (${r.map((e,n)=>`option[${n}]: { ${e.issues.map(e=>W(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},j=class extends Error{constructor(e){super(`${e.issues.map(e=>W(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},V=async(e,t,n)=>{if(e.signal?.aborted)throw new F(n,e.signal.reason);const r=t.getAPIVersion?.(e),o=h({...e,...r&&{apiVersion:r}});if(void 0===e.validateRequest||e.validateRequest)try{((e,t)=>{const n=(t?.schema?K.extend(t.schema.shape):K).superRefine((e,n)=>{if("commonBaseURL"in e||"customServiceBaseURL"in e||n.addIssue({code:"custom",message:"commonBaseURL or customServiceBaseURL is required"}),t?.refinements?.length)for(const r of t.refinements)r.check(e)||n.addIssue({code:"custom",message:r.message})}).safeParse(e);if(!n.success)throw new j(n.error)})(o,t.requestValidation)}catch(s){throw k(s,n)}const a=t.buildRequest(o),i=c(o);e.onAPIRequest?.(a);try{const n=await t.sendRequest(a,i,{signal:e.signal});return e.onAPIResponse?.(a,n),t.parseResponse(await n.data,o)}catch(s){throw e.onAPIResponse?.(a,s),G(s,n,t.parseResponseError,e.signal)}},q=class e extends Error{constructor(t,n,r){super(n??`HTTP Error ${t}`),this.name="FetchError",this.status=t,this.data=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},Y=async e=>{if(e.ok)return{data:await e.json(),status:e.status};let t,n;const r=e.headers.get("content-type");throw e.bodyUsed?t=e.statusText:r?.includes("application/json")?(n=await e.json(),t=n?.errorText??n?.message??n?.detailedError?.message):r?.includes("text/xml")&&(n=await e.text(),t=e.statusText),new q(e.status,t,n)},$=(e,t)=>new Promise((n,r)=>{if(t?.aborted)return void r(t.reason);const o=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})}),Z=async(t,n)=>{const r=e.instance.get().retry;if(!r)return t();const{initialWaitMs:o,backoffFactor:a,timeoutMs:i}=r,s=Date.now();let c=o,l=await t();for(;429===l.status;){const e=Number.parseInt(l.headers.get("retry-after")??"",10),r=Number.isFinite(e)?1e3*e:c;if(Date.now()-s+r>i)break;await l.text().catch(()=>{}),await $(r,n),c*=a,l=await t()}return l},z=()=>g()?"include":void 0,J=async(e,t,n)=>Y(await Z(()=>{const r=z(),{url:o,headers:a}=e instanceof URL?{url:e,headers:void 0}:e,i={headers:{...t,...a}};return r&&(i.credentials=r),n?.signal&&(i.signal=n.signal),fetch(o,i)},n?.signal)),Q=async(e,t,n)=>Y(await Z(()=>{const r=z(),o={method:"POST",body:JSON.stringify(e.data),headers:{...t,...e.headers,"Content-Type":"application/json"}};return r&&(o.credentials=r),n?.signal&&(o.signal=n.signal),fetch(e.url,o)},n?.signal)),X=async(e,t,n)=>{if("GET"===e.method)return J(e,t,n);if("POST"===e.method)return Q(e,t,n);throw new Error(`Unsupported HTTP method received: ${e.method}`)},ee=C.array(C.array(C.number())),te=C.object({type:C.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:C.union([C.array(C.number()),ee,C.array(C.array(C.array(C.number()))),C.array(C.array(C.array(C.array(C.number()))))]),radius:C.optional(C.number()),radiusMeters:C.optional(C.number()),bbox:C.optional(C.array(C.number()))}).check(C.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),ne=C.object({type:C.literal("Feature"),geometry:te,id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),re=C.object({type:C.literal("FeatureCollection"),features:C.array(ne),id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),oe=C.union([C.tuple([C.number().min(-180).max(180),C.number().min(-90).max(90)]),C.tuple([C.number().min(-180).max(180),C.number().min(-90).max(90),C.number()]),C.object({type:C.literal("Point"),coordinates:C.array(C.number())}),ne]),ae=C.union([C.array(C.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),C.array(C.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),ie=C.union([te,ne,re]),se=C.union([ae,ie,C.array(ie)]),ce=C.object({query:C.string().optional(),position:oe.optional(),limit:C.number().max(100).optional(),extendedPostalCodesFor:C.array(C.string()).optional(),mapcodes:C.array(C.string()).optional(),view:C.enum(S).optional(),geographyTypes:C.array(C.string()).optional()}),le=C.object({indexes:C.array(C.string()).optional(),poiCategories:C.array(C.enum(f)).optional(),poiBrands:C.array(C.string()).optional(),connectors:C.array(C.string()).optional(),fuelTypes:C.array(C.string()).optional(),openingHours:C.string().optional(),timeZone:C.string().optional(),relatedPois:C.string().optional(),minPowerKW:C.number().optional(),maxPowerKW:C.number().optional(),minFuzzyLevel:C.number().optional(),maxFuzzyLevel:C.number().optional()}),ue=ce.extend(le.shape),de=C.object({type:C.literal("LineString"),coordinates:ee}),pe=C.object({type:C.literal("Feature"),geometry:de}),me=ee,ge=C.union([de,pe,me]),he=C.object({route:ge,maxDetourTimeSeconds:C.number().int().positive()}),ye=C.object({sortBy:C.enum(["detourTime","detourOffset"]).optional()}),fe=ue.extend({...he.shape,...ye.shape}),Te=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",Re=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let o;const a=Math.ceil(n/t);for(o=0;o<n;o+=a)r.push(e[o]);return t>1&&o>=n-a&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},be=e=>({...e.apiKey&&{"TomTom-Api-Key":e.apiKey},...!A(e.apiVersion)&&{"TomTom-Api-Version":String(e.apiVersion)}}),Ie=e=>({...be(e),...e.language&&{"Accept-Language":e.language}}),Se=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),t.apiKey&&e.append("key",t.apiKey),t.language&&e.append("language",t.language)},Ce=e=>be(e),ve=(e,t)=>{t.language&&e.append("language",t.language)},Ae=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},Pe=(e,t,n)=>{!A(n)&&e.append(t,String(n))},Le=(e,t)=>{if(!t)return;if(void 0!==t.position)return((e,t)=>{const n=u(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))})(e,t.position),void Pe(e,"radius",t.radiusMeters);const n=o(t.boundingBox);n&&(e.append("topLeft",Te([n[3],n[0]])),e.append("btmRight",Te([n[1],n[2]])))},Me=(e,t)=>{const n=e.searchParams;ve(n,t),Pe(n,"limit",t.limit),Ae(n,"fuelSet",t.fuelTypes),Ae(n,"idxSet",t.indexes),Ae(n,"brandSet",t.poiBrands),t.poiCategories&&Ae(n,"categorySet",t.poiCategories.map(e=>T[e])),Ae(n,"connectorSet",t.connectors),Ae(n,"mapcodes",t.mapcodes),Ae(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),Pe(n,"minPowerKW",t.minPowerKW),Pe(n,"maxPowerKW",t.maxPowerKW),Pe(n,"view",t.view),Pe(n,"openingHours",t.openingHours),Pe(n,"timeZone",t.timeZone),Pe(n,"relatedPois",t.relatedPois),Ae(n,"entityTypeSet",t.geographyTypes)},Ee=(e,t)=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/${t}`,we=e=>{const t={count:0,statusCounts:{}};for(const n of e)for(const e of n.chargingPoints)t.count++,t.statusCounts[e.status]=(t.statusCounts[e.status]||0)+1;return t},De=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,xe=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>De(r,e.connector));if(e){if(e.count++,t){const n=e.statusCounts;e.statusCounts[t]=(n[t]||0)+1}}else n.push({connector:r,count:1,statusCounts:t?{[t]:1}:{}})}},Oe=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>De(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Ne=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)xe(e.connectors,e.status,t);return t},Be=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",He=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},_e=e=>`${e[1]},${e[0]}`,Fe=e=>{let t,n;return(e=>void 0!==e.topLeftPoint)(e)?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=He(e.southWest),n=He(e.northEast)),[t[0],t[1],n[0],n[1]]},Ue=e=>[e.lon,e.lat],Ge=e=>{const{year:t,month:n,day:r}=(e=>{const t=e.split("-");return{year:Number.parseInt(t[0]),month:Number.parseInt(t[1]),day:Number.parseInt(t[2])}})(e.date);return{dateYYYYMMDD:e.date,year:t,month:n,day:r,hour:e.hour,minute:e.minute,date:new Date(t,n-1,r,e.hour,e.minute)}},ke=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,Ke=e=>{const t=e.timeRanges.map(e=>({start:Ge(e.startTime),end:Ge(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:ke(t)}},We=e=>{const{position:t,entryPoints:n,poi:r,id:o,dist:a,boundingBox:i,chargingPark:s,...c}=e,l=s?.connectors?.map(e=>({...M(e,"connectorType"),type:e.connectorType,chargingSpeed:Be(e.ratedPowerKW)}));return{type:"Feature",geometry:b(Ue(t)),...i&&{bbox:Fe(i)},id:o,properties:{...M(c,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:Ue(e.position)}))},...l?.length&&{chargingPark:{...s,connectors:Oe(l)}},...r&&{poi:{name:r.name,categories:(r.categorySet?.map(e=>R[e.id])??[]).filter(e=>!!e),localizedCategories:r.categories??[],...r.phone&&{phone:r.phone},...r.brands&&{brands:r.brands.map(e=>e.name)},...r.url&&{url:r.url},...r.openingHours&&{openingHours:Ke(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},je=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:Ue(t)},...n}},Ve={requestValidation:{schema:fe},buildRequest:e=>{const t=new URL((e=>Ee(e,`searchAlongRoute/${encodeURIComponent(e.query??"")}.json`))(e));Me(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),Pe(n,"sortBy",e.sortBy),Pe(n,"spreadingMode","plan"),{url:t,headers:Ce(e),data:{route:{points:(r=e.route,Array.isArray(r)?{type:"LineString",coordinates:r}:"Feature"===r.type?r.geometry:r).coordinates.map(e=>({lat:e[1],lon:e[0]}))}}};var r},sendRequest:Q,parseResponse:e=>{const t=e.results.map(We),n=a(o(t));return{type:"FeatureCollection",properties:{...je(e.summary)},features:t,...n&&{bbox:n}}}},qe=async e=>V(e,Ve,"AlongRouteSearch"),Ye=K.extend({id:C.string()}),$e=["fast","short","efficient","thrilling"],Ze=["all","unknown","none"],ze={requestValidation:{schema:Ye},buildRequest:e=>{const t=new URL((e=>Ee(e,"ev/id"))(e)),n=t.searchParams;return Se(n,e),n.append("id",e.id),t},sendRequest:J,parseResponse:e=>{const t=e.results?.[0];return t?{id:t.id,accessType:t.accessType,chargingStations:(n=t.chargingStations,n.map(e=>({...e,chargingPoints:e.chargingPoints.map(e=>({...e,connectors:e.connectors?.map(e=>({...e,chargingSpeed:Be(e.ratedPowerKW)}))}))}))),chargingPointAvailability:we(t.chargingStations),connectorAvailabilities:Ne(t.chargingStations),...t.openingHours&&{openingHours:Ke(t.openingHours)}}:void 0;var n},parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new _(n,t,e.status)}},Je=async e=>V(e,ze,"EVChargingStationsAvailability"),Qe=async(e,t)=>{const n=e.properties.dataSources?.chargingAvailability?.id;if(n)try{const r=await Je({...t,id:n}),o=e.properties.poi;return r?{...e,properties:{...e.properties,...o&&{poi:{...o,openingHours:r.openingHours}},chargingPark:{...e.properties.chargingPark,availability:r}}}:void 0}catch(r){return void console.error(r)}};async function Xe(e,t){const{excludeIfAvailabilityUnknown:n,...r}=t??{},a=[];for(const o of e.features){const e=await Qe(o,r);e?a.push(e):n||a.push(o)}return{...e,features:a,bbox:o(a)}}var et=e=>Boolean(e&&"availability"in e&&e.availability),tt=async(e,t,n)=>{const r="string"==typeof t?{query:t}:t,[o]=(await n({...r,limit:1})).features;if(!o)throw new Error(`${e}: no results found for "${r.query}"`);return o},nt=C.object({position:oe,radiusMeters:C.number().optional()}),rt=C.union([nt,C.object({boundingBox:se})]),ot=C.object({typeahead:C.boolean().optional(),offset:C.number().max(1900).optional(),geoBias:rt.optional(),countries:C.array(C.string()).optional()}),at=K.extend(ce.shape).extend(ot.shape).extend({query:C.string()}),it=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:b(Ue(t)),...n&&{bbox:Fe(n)},id:s,properties:{...M(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...o&&{entryPoints:o.map(e=>({...e,position:Ue(e.position)}))},...a&&{addressRanges:{...a,from:Ue(a.from),to:Ue(a.to)}}}}},st={requestValidation:{schema:at},buildRequest:e=>{const t=new URL(`${(e=>Ee(e,"geocode"))(e)}/${encodeURIComponent(e.query)}.json`),n=t.searchParams;return ve(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!A(e.limit)&&n.append("limit",String(e.limit)),!A(e.offset)&&n.append("ofs",String(e.offset)),Le(n,e.geoBias),e.countries&&n.append("countrySet",Te(e.countries)),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",Te(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",Te(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",Te(e.geographyTypes)),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const t=e.results.map(it),n=a(o(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}}},ct=async e=>V(e,st,"Geocode"),lt=async e=>tt("geocodeOne",e,ct),ut=C.object({geometries:C.union([re,C.array(C.union([C.string(),ne])).min(1).max(20)])}),dt=C.object({zoom:C.number().min(0).max(22).optional()}),pt=ut.extend(dt.shape),mt=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),gt={requestValidation:{schema:pt},buildRequest:e=>{const t=new URL((e=>Ee(e,"additionalData.json"))(e)),n=t.searchParams;return((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:mt(t):mt(t.features),e.append("geometries",Te(n))})(n,e.geometries),Pe(n,"geometriesZoom",e.zoom),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??s(),bbox:o(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:o(t),features:t}}};async function ht(e){const t=await V(e,gt,"GeometryData");return Array.isArray(e.geometries)||"FeatureCollection"!==e.geometries.type?t:((e,t)=>{const n=e.features.reduce((e,t)=>{const n=t.properties.dataSources?.geometry?.id;return n&&(e[n]={...t.properties,placeCoordinates:t.geometry.coordinates}),e},{}),r=t.features.map(e=>e.id&&n[e.id]?{...e,properties:n[e.id]}:e);return{type:"FeatureCollection",bbox:t.bbox,features:r}})(e.geometries,t)}var yt=C.object({entityId:C.string()}),ft=C.object({mapcodes:C.array(C.string()).optional(),view:C.enum(S).optional(),openingHours:C.string().optional(),timeZone:C.string().optional(),relatedPois:C.string().optional()}),Tt=yt.extend(ft.shape),Rt={requestValidation:{schema:Tt},buildRequest:e=>{const t=new URL(`${(e=>Ee(e,"place.json"))(e)}`),n=t.searchParams;return ve(n,e),Pe(n,"entityId",e.entityId),Ae(n,"mapcodes",e.mapcodes),Pe(n,"view",e.view),Pe(n,"openingHours",e.openingHours),Pe(n,"timeZone",e.timeZone),Pe(n,"relatedPois",e.relatedPois),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>e.results?.length?We(e.results[0]):void 0},bt=async e=>V(e,Rt,"PlaceDetails"),It=/* @__PURE__ */new Map,St=/* @__PURE__ */new Map,Ct="en-GB",vt=e=>e??Ct,At=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),Pt=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(At);for(const r of e)t[r]=n}return t},Lt=K.extend({filters:C.array(C.string()).optional()}),Mt=e=>{const t=R[e.id];return t?{code:t,name:e.name,childCategoryCodes:e.childCategoryIds.map(e=>R[e]).filter(e=>!!e),synonyms:e.synonyms}:(console.error(`Received unknown POI category ID ${e.id} (${e.name}). This category will be skipped and unavailable for filtering.`),null)},Et={requestValidation:{schema:Lt},buildRequest:e=>{const t=Ee(e,"poiCategories.json"),n=new URL(t);return ve(n.searchParams,e),{url:n,headers:Ce(e)}},getAPIVersion:()=>1,sendRequest:J,parseResponse:e=>({poiCategories:e.poiCategories.map(Mt).filter(e=>null!==e)})},wt=(e,t)=>{const n=(e=>St.get(e??Ct)??{})(e),r=/* @__PURE__ */new Map;for(const o of t){const e=At(o);for(const[t,o]of Object.entries(n))t.includes(e)&&o&&r.set(o.code,o)}for(const o of r.values())for(const e of o.childCategoryCodes)r.delete(e);return[...r.values()]},Dt=async(e={})=>{const{language:t}=h(e);let n=(e=>It.get(vt(e)))(t);return n||(n=(await V(e,Et,"POICategories")).poiCategories,((e,t)=>{const n=vt(e);It.set(n,t),St.set(n,Pt(t))})(t,n)),e.filters?.length?{poiCategories:wt(t,e.filters)}:{poiCategories:n}},xt=async(e={})=>{const{poiCategories:t}=await Dt(e);return t.map(e=>e.code)},Ot=(e,t)=>{const{data:n,message:r,status:o}=e;return new _(n?.error?.description??n?.detailedError?.message??r,t,o)},Nt=(e,t)=>e*t/100,Bt=e=>"engineType"in e&&"electric"===e.engineType,Ht=e=>{if(Bt(e)&&e.model&&!("variantId"in e.model))return e.model.engine},_t=(e,t,n)=>{A(n)||(e[t]=String(n))},Ft=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),Ut=e=>{const t={};return e?(_t(t,"accelerationEfficiency",e.acceleration),_t(t,"decelerationEfficiency",e.deceleration),_t(t,"uphillEfficiency",e.uphill),_t(t,"downhillEfficiency",e.downhill),t):t},Gt=e=>{const t={};return e.speedsToConsumptionsKWH?.length&&(t.constantSpeedConsumptionInkWhPerHundredkm=Ft(e.speedsToConsumptionsKWH)),_t(t,"auxiliaryPowerInkW",e.auxiliaryPowerInkW),_t(t,"consumptionInkWhPerkmAltitudeGain",e.consumptionInKWHPerKMAltitudeGain),_t(t,"recuperationInkWhPerkmAltitudeLoss",e.recuperationInKWHPerKMAltitudeLoss),{...t,...Ut(e.efficiency)}},kt=e=>{const t=e.consumption,n={};return t.speedsToConsumptionsLiters?.length&&(n.constantSpeedConsumptionInLitersPerHundredkm=Ft(t.speedsToConsumptionsLiters)),_t(n,"auxiliaryPowerInLitersPerHour",t.auxiliaryPowerInLitersPerHour),_t(n,"fuelEnergyDensityInMJoulesPerLiter",t.fuelEnergyDensityInMJoulesPerLiter),{...n,...Ut(t.efficiency)}},Kt=e=>Ht(e)?.charging?.maxChargeKWH,Wt=e=>{const t={};return e.charging?.maxChargeKWH&&(t.maxChargeInkWh=String(e.charging.maxChargeKWH)),t},jt=e=>{const t=e.state?.currentChargeInkWh;if(!A(t))return t;const n=e.state?.currentChargePCT,r=Kt(e);return!A(n)&&r?Nt(r,n):void 0},Vt=e=>{const t={};return _t(t,"currentChargeInkWh",jt(e)),t},qt=e=>{const t={};return _t(t,"currentFuelInLiters",e.state?.currentFuelInLiters),t},Yt=e=>Bt(e)?e.preferences?.chargingPreferences:void 0,$t=(e,t)=>{for(const[n,r]of Object.entries(t))e.set(n,r)},Zt=C.number().positive(),zt=C.number().min(0),Jt=C.number().min(0).max(100),Qt=Zt.optional(),Xt=zt.optional(),en=C.number().min(0).max(1).optional(),tn=C.object({speedKMH:C.number(),consumptionUnitsPer100KM:C.number()}),nn={efficiency:C.object({acceleration:en,deceleration:en,uphill:en,downhill:en}).optional()},rn=C.array(tn).min(1).max(25),on=C.object({...nn,speedsToConsumptionsLiters:rn,auxiliaryPowerInLitersPerHour:Xt,fuelEnergyDensityInMJoulesPerLiter:C.number().min(1).optional()}),an=C.object({...nn,speedsToConsumptionsKWH:rn,auxiliaryPowerInkW:Xt,consumptionInKWHPerKMAltitudeGain:C.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Xt}),sn=C.object({currentType:C.enum(i),plugTypes:C.array(C.enum(y)).min(1),efficiency:en,baseLoadInkW:Xt,maxPowerInkW:Xt,maxVoltageInV:Xt,maxCurrentInA:Xt,voltageRange:C.object({minVoltageInV:Xt,maxVoltageInV:C.number().optional()}).optional()}),cn=C.object({stateOfChargeInkWh:zt,maxPowerInkW:Zt}),ln=C.object({maxChargeKWH:Zt,batteryCurve:C.array(cn).max(20).optional(),chargingConnectors:C.array(sn).min(1).optional(),chargingTimeOffsetInSec:Xt}),un=C.object({consumption:on}),dn=C.object({consumption:an,charging:ln.optional()}),pn=C.object({weightKG:Qt}).optional(),mn=C.object({variantId:C.string()}),gn=C.object({dimensions:pn,engine:C.union([un,dn]).optional()}),hn=C.union([mn,gn]).optional(),yn=C.object({heading:C.number().min(0).max(360).optional()}),fn=yn.extend({currentFuelInLiters:zt}),Tn=yn.extend({currentChargePCT:Jt}),Rn=yn.extend({currentChargeInkWh:zt}),bn=C.union([Tn,Rn]),In=C.object({minChargeAtDestinationPCT:Jt,minChargeAtChargingStopsPCT:C.number().min(0).max(50)}),Sn=C.object({minChargeAtDestinationInkWh:zt,minChargeAtChargingStopsInkWh:zt}),Cn=C.union([In,Sn]),vn=C.object({chargingPreferences:Cn.optional()}),An={model:hn,restrictions:C.object({maxSpeedKMH:C.number().min(0).max(250).optional(),tollTransponder:C.enum(Ze).optional()}).optional()},Pn=C.object({...An,engineType:C.undefined().optional(),state:yn.optional()}),Ln=C.object({...An,engineType:C.literal("combustion"),state:fn.optional()}),Mn=C.object({...An,engineType:C.literal("electric"),state:bn.optional(),preferences:vn.optional()}),En=C.union([C.discriminatedUnion("engineType",[Ln,Mn]),Pn]),wn=C.object({avoid:C.array(C.enum(n)).optional(),traffic:C.enum(["live","historical"]).optional(),routeType:C.enum($e).optional(),avoidAreas:C.array(se).max(10).optional()}),Dn=C.object({option:C.enum(["departAt","arriveBy"]),date:C.date()}),xn=C.object({costModel:wn.optional(),travelMode:C.string().optional(),vehicle:En.optional(),when:Dn.optional()}),On=["timeMinutes","remainingChargePCT","spentChargePCT","spentFuelLiters","distanceKM"],Nn=C.object({origin:oe,budget:C.object({type:C.enum(On),value:C.number().min(0)})}),Bn=C.enum(n).exclude(["alreadyUsedRoads"]),Hn=En.check(C.refine(e=>!(e.state&&"heading"in e.state),"vehicle.state.heading: calculateReachableRange has no vehicle heading parameter. Remove it, or use calculateRoute, which accepts it."),C.refine(e=>!("electric"===e.engineType&&e.preferences&&"chargingPreferences"in e.preferences),"vehicle.preferences.chargingPreferences: calculateReachableRange plans no charging stops. Remove them, or use calculateRoute, which plans stops for them.")),_n=Dn.check(C.refine(e=>"arriveBy"!==e.option,"when.arriveBy: calculateReachableRange has no arrival-time parameter. Use when.departAt instead, or omit when entirely.")),Fn=wn.extend({avoid:C.array(Bn).optional(),avoidAreas:C.unknown().optional()}).check(C.refine(e=>void 0===e.avoidAreas,"costModel.avoidAreas: calculateReachableRange has no avoid-areas parameter. Remove it — the other cost-model options are accepted.")),Un=C.object({when:_n.optional(),vehicle:Hn.optional(),costModel:Fn.optional(),maxFerryLengthMeters:C.number().min(0).optional(),smoothing:C.enum(["none","weak","strong"]).optional()}),Gn=xn.extend(Nn.extend(Un.shape).shape),kn=/* @__PURE__ */new Set(["spentChargePCT","remainingChargePCT"]),Kn={check:e=>!kn.has(e.budget.type)||!!e.vehicle&&void 0!==Kt(e.vehicle),message:"budget: a charge budget is a percentage of the battery, so it needs a capacity to convert against. Set vehicle.engineType to 'electric' and vehicle.model.engine.charging.maxChargeKWH, or budget by time or distance instead."},Wn={check:e=>"remainingChargePCT"!==e.budget.type||!!e.vehicle&&void 0!==jt(e.vehicle),message:"budget.remainingChargePCT: a range down to a remaining charge is measured from the charge the vehicle sets off with. Set vehicle.state.currentChargeInkWh or vehicle.state.currentChargePCT, or use spentChargePCT to budget a share of the battery instead."},jn={schema:Gn,refinements:[Kn,Wn]},Vn=e=>({...e.costModel?.routeType&&{routeType:e.costModel.routeType},...e.costModel?.traffic&&{traffic:e.costModel.traffic},...e.costModel?.avoid?.length&&{avoids:e.costModel.avoid},...e.travelMode&&{travelMode:e.travelMode},..."departAt"===e.when?.option&&e.when.date&&{departureDateTime:e.when.date.toISOString()}}),qn=e=>e.model&&"variantId"in e.model?e.model.variantId:void 0,Yn=e=>{const t={};return Bt(e)&&(t.vehicleEngineType="electric"),e.model&&!("variantId"in e.model)&&e.model.dimensions?.weightKG&&(t.vehicleWeightInKilograms=e.model.dimensions.weightKG),e.restrictions?.maxSpeedKMH&&(t.vehicleMaxSpeedInKilometersPerHour=e.restrictions.maxSpeedKMH),e.restrictions?.tollTransponder&&(t.vehicleHasElectronicTollCollectionTransponder=e.restrictions.tollTransponder),t},$n=(e,t)=>{const n=Ht(t),r=(e=>"engineType"in e&&"combustion"===e.engineType?e.model?.engine:void 0)(t);var o;$t(e.searchParams,Bt(t)?{...n&&(o=n,{...Gt(o.consumption),...Wt(o)}),...Vt(t)}:{...r&&kt(r),...qt(t)})},Zn=(e,t)=>{const n=qn(t);n&&e.searchParams.set("vehicleModelId",n),$n(e,t)},zn=e=>({origin:{type:"Point",coordinates:d(e.origin)},...Vn(e),...e.vehicle&&Yn(e.vehicle)}),Jn=e=>({...Ie(e),Attributes:"reachableRange(boundary)"}),Qn=Object.keys({origin:!0,budget:!0,costModel:!0,vehicle:!0,travelMode:!0,when:!0,maxFerryLengthMeters:!0,smoothing:!0}),Xn={requestValidation:jn,buildRequest:e=>{const t=(e=>new URL(e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange`))(e);return((e,t)=>{const n=t.budget,r=t.vehicle&&Kt(t.vehicle);switch(n.type){case"timeMinutes":e.append("timeBudgetInSec",(60*n.value).toString());break;case"distanceKM":e.append("distanceBudgetInMeters",(1e3*n.value).toString());break;case"spentFuelLiters":e.append("fuelBudgetInLiters",n.value.toString());break;case"spentChargePCT":r&&e.append("energyBudgetInkWh",Nt(r,n.value).toString());break;case"remainingChargePCT":{const o=t.vehicle&&jt(t.vehicle);if(r&&void 0!==o){const t=Nt(r,n.value);e.append("energyBudgetInkWh",Math.max(0,o-t).toString())}break}}})(t.searchParams,e),Pe(t.searchParams,"maxFerryLengthInMeters",e.maxFerryLengthMeters),Pe(t.searchParams,"smoothing",e.smoothing??"strong"),e.vehicle&&Zn(t,e.vehicle),{method:"POST",url:t,data:zn(e),headers:Jn(e)}},sendRequest:X,parseResponse:(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:o(n),properties:w(t,Qn)}},parseResponseError:Ot,getAPIVersion:()=>3},er=async e=>V(e,Xn,"Reachable Range"),tr=(...e)=>{const t=e.filter(e=>!!e);return t.length<2?t[0]:AbortSignal.any(t)},nr=async(e,t)=>{const n=[];for(const o of e){const e=tr(o.signal,t?.signal);try{n.push(await er({...o,...e&&{signal:e}}))}catch(a){if(!(a instanceof _)||403===a.status||429===a.status)throw a}}const r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},rr={Country:"country",CountrySubdivision:"countrySubdivision",CountrySecondarySubdivision:"countrySecondarySubdivision",CountryTertiarySubdivision:"countryTertiarySubdivision",Municipality:"municipality",MunicipalitySubdivision:"municipalitySubdivision",MunicipalitySecondarySubdivision:"municipalitySecondarySubdivision",Neighbourhood:"neighborhood",PostalCodeArea:"postalCode"},or={AF:"AFG",AX:"ALA",AL:"ALB",DZ:"DZA",AS:"ASM",AD:"AND",AO:"AGO",AI:"AIA",AQ:"ATA",AG:"ATG",AR:"ARG",AM:"ARM",AW:"ABW",AU:"AUS",AT:"AUT",AZ:"AZE",BS:"BHS",BH:"BHR",BD:"BGD",BB:"BRB",BY:"BLR",BE:"BEL",BZ:"BLZ",BJ:"BEN",BM:"BMU",BT:"BTN",BO:"BOL",BQ:"BES",BA:"BIH",BW:"BWA",BV:"BVT",BR:"BRA",IO:"IOT",BN:"BRN",BG:"BGR",BF:"BFA",BI:"BDI",CV:"CPV",KH:"KHM",CM:"CMR",CA:"CAN",KY:"CYM",CF:"CAF",TD:"TCD",CL:"CHL",CN:"CHN",CX:"CXR",CC:"CCK",CO:"COL",KM:"COM",CG:"COG",CD:"COD",CK:"COK",CR:"CRI",CI:"CIV",HR:"HRV",CU:"CUB",CW:"CUW",CY:"CYP",CZ:"CZE",DK:"DNK",DJ:"DJI",DM:"DMA",DO:"DOM",EC:"ECU",EG:"EGY",SV:"SLV",GQ:"GNQ",ER:"ERI",EE:"EST",SZ:"SWZ",ET:"ETH",FK:"FLK",FO:"FRO",FJ:"FJI",FI:"FIN",FR:"FRA",GF:"GUF",PF:"PYF",TF:"ATF",GA:"GAB",GM:"GMB",GE:"GEO",DE:"DEU",GH:"GHA",GI:"GIB",GR:"GRC",GL:"GRL",GD:"GRD",GP:"GLP",GU:"GUM",GT:"GTM",GG:"GGY",GN:"GIN",GW:"GNB",GY:"GUY",HT:"HTI",HM:"HMD",VA:"VAT",HN:"HND",HK:"HKG",HU:"HUN",IS:"ISL",IN:"IND",ID:"IDN",IR:"IRN",IQ:"IRQ",IE:"IRL",IM:"IMN",IL:"ISR",IT:"ITA",JM:"JAM",JP:"JPN",JE:"JEY",JO:"JOR",KZ:"KAZ",KE:"KEN",KI:"KIR",KP:"PRK",KR:"KOR",KW:"KWT",KG:"KGZ",LA:"LAO",LV:"LVA",LB:"LBN",LS:"LSO",LR:"LBR",LY:"LBY",LI:"LIE",LT:"LTU",LU:"LUX",MO:"MAC",MG:"MDG",MW:"MWI",MY:"MYS",MV:"MDV",ML:"MLI",MT:"MLT",MH:"MHL",MQ:"MTQ",MR:"MRT",MU:"MUS",YT:"MYT",MX:"MEX",FM:"FSM",MD:"MDA",MC:"MCO",MN:"MNG",ME:"MNE",MS:"MSR",MA:"MAR",MZ:"MOZ",MM:"MMR",NA:"NAM",NR:"NRU",NP:"NPL",NL:"NLD",NC:"NCL",NZ:"NZL",NI:"NIC",NE:"NER",NG:"NGA",NU:"NIU",NF:"NFK",MK:"MKD",MP:"MNP",NO:"NOR",OM:"OMN",PK:"PAK",PW:"PLW",PS:"PSE",PA:"PAN",PG:"PNG",PY:"PRY",PE:"PER",PH:"PHL",PN:"PCN",PL:"POL",PT:"PRT",PR:"PRI",QA:"QAT",RE:"REU",RO:"ROU",RU:"RUS",RW:"RWA",BL:"BLM",SH:"SHN",KN:"KNA",LC:"LCA",MF:"MAF",PM:"SPM",VC:"VCT",WS:"WSM",SM:"SMR",ST:"STP",SA:"SAU",SN:"SEN",RS:"SRB",SC:"SYC",SL:"SLE",SG:"SGP",SX:"SXM",SK:"SVK",SI:"SVN",SB:"SLB",SO:"SOM",ZA:"ZAF",GS:"SGS",SS:"SSD",ES:"ESP",LK:"LKA",SD:"SDN",SR:"SUR",SJ:"SJM",SE:"SWE",CH:"CHE",SY:"SYR",TW:"TWN",TJ:"TJK",TZ:"TZA",TH:"THA",TL:"TLS",TG:"TGO",TK:"TKL",TO:"TON",TT:"TTO",TN:"TUN",TR:"TUR",TM:"TKM",TC:"TCA",TV:"TUV",UG:"UGA",UA:"UKR",AE:"ARE",GB:"GBR",US:"USA",UM:"UMI",UY:"URY",UZ:"UZB",VU:"VUT",VE:"VEN",VN:"VNM",VG:"VGB",VI:"VIR",WF:"WLF",EH:"ESH",YE:"YEM",ZM:"ZMB",ZW:"ZWE"},ar=e=>or[e]??e,ir={street:"Street",area:"Geography",address:"Point Address"},sr=Object.fromEntries(Object.entries(rr).map(([e,t])=>[t,e])),cr=e=>{const{street:t,houseNumber:n,countryCodeIso2:r,...o}=e;return{...o,...t&&{streetName:t},...n&&{streetNumber:n},...r&&{countryCode:r,countryCodeISO3:ar(r)}}},lr=C.object({position:oe}),ur=C.object({geographyTypes:C.array(C.enum(l)).optional(),heading:C.number().min(-360).max(360).optional(),radiusMeters:C.number().positive().max(5e6).optional(),view:C.enum(S).optional()}),dr=lr.extend(ur.shape),pr={requestValidation:{schema:dr},buildRequest:e=>{const[t,n]=d(e.position),r=new URL((e=>Ee(e,"reverseGeocode"))(e)),o=r.searchParams;return o.append("position",`${t},${n}`),!A(e.radiusMeters)&&o.append("radiusInMeters",String(e.radiusMeters)),e.geographyTypes&&o.append("areaTypes",e.geographyTypes.map(e=>rr[e]).join(",")),!A(e.heading)&&o.append("vehicleHeadingInDegrees",String(e.heading)),e.view&&o.append("geopoliticalView",e.view),{url:r,headers:{...Ie(e),Attributes:"results(*)"}}},getAPIVersion:()=>2,sendRequest:J,parseResponse:(e,t)=>{const n=e.results[0];return{type:"Feature",geometry:b(d(t.position)),id:n?.id??s(),...n&&{properties:{type:ir[n.type],address:{freeformAddress:n.title,...cr(n.address)},...n.areaType&&{geographyType:[sr[n.areaType]],dataSources:{geometry:{id:n.id}}},...n.accessPoints?.length&&{entryPoints:n.accessPoints.map(e=>({position:e.position.coordinates}))},originalPosition:n.position.coordinates}}}}},mr=async e=>V(e,pr,"ReverseGeocode"),gr=["tollVignette","tollRoad","roadShields","importantRoadStretch"],hr=e=>{const t=["summary","legs(summary,path)"],n=e.sectionTypes;if(!n||n.length>0){t.push("sections");const r=!n;for(const e of gr)(r||n.includes(e))&&t.push(`sections.${e}`);e.guidance&&(r||n.includes("lanes"))&&t.push("sections.lanes")}0!==e.extendedRouteRepresentations?.length&&t.push("progressPoints"),e.guidance&&t.push("instructions(*,nextRoadInformation.roadShields.iconReference,previousRoadInformation.roadShields.iconReference,signpost.exitIconReference,distanceToPreviousTrafficLightInMeters)");const r=`routes(${t.join(",")})`;return e.guidance?`roadShieldAtlasReference,${r}`:r},yr=e=>{const t=e.state?.heading;return{...Yn(e),...!A(t)&&{vehicleHeadingInDegrees:t}}},fr=(e,t)=>{Zn(e,t),$t(e.searchParams,(e=>{const t=Yt(e),n={};if(!t)return n;const r=t;if(!A(r.minChargeAtDestinationInkWh)||!A(r.minChargeAtChargingStopsInkWh))return _t(n,"minChargeAtDestinationInkWh",r.minChargeAtDestinationInkWh),_t(n,"minChargeAtChargingStopsInkWh",r.minChargeAtChargingStopsInkWh),n;const o=Kt(e);if(!o)return n;const a=t;return A(a.minChargeAtDestinationPCT)||(n.minChargeAtDestinationInkWh=String(Nt(o,a.minChargeAtDestinationPCT))),A(a.minChargeAtChargingStopsPCT)||(n.minChargeAtChargingStopsInkWh=String(Nt(o,a.minChargeAtChargingStopsPCT))),n})(t))},Tr=e=>!!e.vehicle&&!!Yt(e.vehicle),Rr="vehicle.model.variantId is only supported for EV routes with charging stops: set vehicle.preferences.chargingPreferences, or describe the vehicle with vehicle.model.dimensions and vehicle.model.engine instead.",br=e=>{const t=(e=>Array.isArray(e)?e:e.geometry.coordinates)(e),n=(e=>{if(!Array.isArray(e))return e.properties?.sections?.leg})(e);if(n&&n.length>1&&n.every(e=>null!=e.startPointIndex&&null!=e.endPointIndex)){const e=n.map(e=>{const n=e.startPointIndex??0,r=e.endPointIndex??0;return{coordinate:t[n],legToNext:{path:{type:"LineString",coordinates:t.slice(n,r+1)}}}});return e.push({coordinate:t[n.at(-1)?.endPointIndex??t.length-1]}),e}return[{coordinate:t[0],legToNext:{path:{type:"LineString",coordinates:t}}},{coordinate:t.at(-1)??t[0]}]},Ir=e=>{if(!Array.isArray(e)&&"properties"in e)return e.properties??void 0},Sr=e=>{const t=e.options;if(!t)return{};const n={...t.pauseDurationSeconds&&{pauseDurationInSeconds:t.pauseDurationSeconds},...t.candidateEntryPoints?.length&&{entryPoints:(r=t.candidateEntryPoints,{type:"MultiPoint",coordinates:r.map(e=>d(e))}),...!A(t.preferredEntryPointIndex)&&{preferredEntryPointIndex:t.preferredEntryPointIndex}}};var r;return{...t.legCostModel?.routeType&&{routeType:t.legCostModel.routeType},...t.legCostModel?.avoid?.length&&{avoids:t.legCostModel.avoid.map(e=>({name:e}))},...Object.keys(n).length>0&&{routeStop:n}}},Cr=(e,t)=>{t.computeTravelTimeFor&&e.searchParams.set("computeTravelTimeFor",t.computeTravelTimeFor)},vr=C.union([oe,te]),Ar=C.union([ee,ne]),Pr=C.object({locations:C.array(C.union([vr,Ar])).min(1)}),Lr=C.object({arrivalSide:C.enum(["any","curb"]).optional(),chargingStopsStrategy:C.enum(["automaticFastest","manualFastest","automaticFastestWithFallbackToManual"]).optional(),computeTravelTimeFor:C.enum(["none","all"]).optional(),maxAlternatives:C.number().min(0).max(5).optional(),sectionTypes:C.array(C.enum(m)).optional()}),Mr={schema:xn.extend(Pr.extend(Lr.shape).shape),refinements:[{check:e=>{const t=e.locations.map(p),n=t.filter(e=>"waypoint"===e).length,r=t.filter(e=>"path"===e).length;return n>=2||r>=1},message:"At least 2 waypoints or 1 path (route reconstruction) is required."},{check:e=>!e.chargingStopsStrategy||Tr(e),message:"chargingStopsStrategy: set vehicle.preferences.chargingPreferences as well — an EV route needs a minimum charge at the destination, which only the charging preferences provide."},{check:e=>!(e.vehicle&&qn(e.vehicle))||Tr(e),message:Rr},{check:e=>{const t=e.locations.at(-1);return!t||"waypoint"!==p(t)||!t.properties?.pauseDurationSeconds},message:"pauseDurationSeconds is not supported on the destination: the routing API requires the wait on the last leg to be 0."}]},Er={other:"unknown",accident:"accident",fog:"fog",danger:"dangerousConditions",rain:"rain",frost:"ice",jam:"jam","lane-closed":"laneClosed","road-closed":"roadClosed",roadworks:"roadWorks",wind:"wind",flooding:"flooding","broken-down-vehicle":"brokenDownVehicle"},wr=new Map(Object.entries(Er)),Dr=new Map(I.map(e=>[Er[e],e])),xr=new Map(Object.entries({unknown:"unknown",minor:"minor",moderate:"moderate",major:"major",undefined:"indefinite"})),Or=e=>wr.get(e)??e,Nr=e=>Dr.get(e)??"other",Br=e=>xr.get(e)??"unknown",Hr=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},_r=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,o=[r.coordinate.longitude,r.coordinate.latitude],a=[r.street,r.houseNumber].filter(Boolean),i=a.length>0?a.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:o},properties:{...M(e,["chargingConnectionInfo","chargingParkLocation"]),type:"POI",address:{freeformAddress:i,...r.street&&{streetName:r.street},...r.houseNumber&&{streetNumber:r.houseNumber},...r.city&&{municipality:r.city},...r.region&&{countrySubdivision:r.region},...r.postalCode&&{postalCode:r.postalCode},...r.country&&{country:r.country}},...n&&{chargingConnectionInfo:{plugType:n.chargingPlugType,currentInA:n.chargingCurrentInA,voltageInV:n.chargingVoltageInV,chargingPowerInkW:n.chargingPowerInkW,currentType:Hr(n.chargingCurrentType),chargingSpeed:Be(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:Be(e.chargingParkPowerInkW)}}}},Fr=(e,t)=>{const n=t?.vehicle&&Kt(t.vehicle);return{lengthInMeters:e.lengthInMeters,travelTimeInSeconds:e.travelDurationInSeconds,trafficDelayInSeconds:e.trafficDelayDurationInSeconds??0,trafficLengthInMeters:e.trafficLengthInMeters??0,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,departureTime:new Date(e.departureDateTime),arrivalTime:new Date(e.arrivalDateTime),deviationDistanceInMeters:e.deviationDistanceInMeters,deviationTimeInSeconds:e.deviationDurationInSeconds,...e.deviationPoint&&{deviationPoint:e.deviationPoint.coordinates},fuelConsumptionInLiters:e.fuelConsumptionInLiters,totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh,...n&&(()=>{const t=e.batteryConsumptionInKilowattHours??e.batteryConsumptionInkWh;return t?{batteryConsumptionInPCT:100*t/n}:void 0})(),remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:_r(e.chargingInformationAtEndOfLeg,n)}}},Ur=(e,t)=>e.reduce((n,r,o)=>{const a=r.path.coordinates.length,i=0===o?0:n[o-1]?.endPointIndex;let c;A(i)||(c=0===i?Math.max(a-1,0):i+a);const l=((e,t)=>{if(!t)return;const n=new Date(e.summary.arrivalDateTime).getTime(),r=new Date(t.summary.departureDateTime).getTime();if(Number.isNaN(n)||Number.isNaN(r))return;const o=Math.round((r-n)/1e3);return o>0?o:void 0})(r,e[o+1]),{originalWaypointIndexAtEndOfLeg:u}=r.summary;return n.push({...!A(i)&&{startPointIndex:i},...void 0!==c&&{endPointIndex:c},...!A(u)&&{originalWaypointIndex:u},summary:{...Fr(r.summary,t),...void 0!==l&&{stopTimeInSeconds:l}},id:s()}),n},[]),Gr=e=>({id:s(),startPointIndex:e.startPathIndex,endPointIndex:e.endPathIndex}),kr=(e,t)=>{const n={leg:Ur(e.legs,t)},r=e.sections;if(!r)return n;const o=(e,t)=>{t?.length&&(n[e]=t.map(Gr))};return o("carTrain",r.carTrain),o("ferry",r.ferry),o("tunnel",r.tunnel),o("motorway",r.motorway),o("pedestrian",r.pedestrian),o("toll",r.toll),o("tollRoad",r.tollRoad),o("carpool",r.carpool),o("urban",r.urban),o("unpaved",r.unpaved),o("lowEmissionZone",r.lowEmissionZone),r.country?.length&&(n.country=r.country.map(e=>({...Gr(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:ar(e.countryCodeIso2??"")}))),r.travelMode?.length&&(n.vehicleRestricted=r.travelMode.filter(e=>"other"===e.travelMode).map(Gr)),r.traffic?.length&&(n.traffic=r.traffic.map(e=>{return{...Gr(e),delayInSeconds:e.delayDurationInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKilometersPerHour,categories:(t=e,t.tec?.causes?.length?t.tec.causes.map(e=>{switch(e.mainCauseCode){case 1:return"jam";case 2:return"accident";case 3:return"roadworks";case 4:return"narrow-lanes";case 5:return"road-closed";case 9:return"danger";case 11:return"animals-on-road";case 13:return"broken-down-vehicle";case 16:return"lane-closed";case 17:return"wind";case 18:return"fog";case 19:return"rain";case 22:return"frost";case 23:return"flooding";default:return"other"}}):[Nr(t.iconCategory)]),magnitudeOfDelay:Br(e.delayMagnitude),tec:e.tec,...e.eventId&&{eventId:e.eventId}};var t})),r.speedLimit?.length&&(n.speedLimit=r.speedLimit.map(e=>{const t=e.speedRestrictions?.find(e=>"maximum"===e.type)?.inKilometersPerHour;return A(t)?void 0:{...Gr(e),maxSpeedLimitInKmh:t}}).filter(e=>!!e)),r.lanes?.length&&(n.lanes=r.lanes.map(e=>({...Gr(e),lanes:(e.lanes??[]).map(e=>({directions:e.directions.map(e=>$r[e]??e),...e.follow&&{follow:$r[e.follow]??e.follow}})),laneSeparators:(e.laneSeparators??[]).map(e=>Zr[e]??e),properties:e.properties}))),r.roadShields?.length&&(n.roadShields=r.roadShields.map(e=>({...Gr(e),roadShieldReferences:e.roadShieldReferences}))),r.tollVignette?.length&&(n.tollVignette=r.tollVignette.map(e=>({...Gr(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:ar(e.countryCodeIso2??"")}))),r.importantRoadStretch?.length&&(n.importantRoadStretch=r.importantRoadStretch.map(e=>({...Gr(e),index:e.importantRoadStretchIndex,...e.streetName&&{streetName:e.streetName.text},...e.roadNumbers?.length&&{roadNumbers:e.roadNumbers.map(e=>e.text)}}))),((e,t)=>{if(!t)return;const n=new Set(t);for(const r of Object.keys(e))"leg"===r||n.has(r)||delete e[r]})(n,t.sectionTypes),n},Kr=1e-4,Wr=(e,t)=>Math.abs(e[0]-t[0])<Kr&&Math.abs(e[1]-t[1])<Kr,jr={depart:"DEPART",waypointLeft:"WAYPOINT_LEFT",waypointRight:"WAYPOINT_RIGHT",waypointReached:"WAYPOINT_REACHED",waypointAhead:"WAYPOINT_AHEAD",arrive:"ARRIVE",arriveLeft:"ARRIVE_LEFT",arriveRight:"ARRIVE_RIGHT",arriveAhead:"ARRIVE_AHEAD",continueStraight:"STRAIGHT",keepLeft:"KEEP_LEFT",keepRight:"KEEP_RIGHT",turnSlightRight:"SLIGHT_RIGHT",turnRight:"TURN_RIGHT",turnSharpRight:"SHARP_RIGHT",turnSlightLeft:"SLIGHT_LEFT",turnLeft:"TURN_LEFT",turnSharpLeft:"SHARP_LEFT",makeUTurn:"MAKE_UTURN",roundaboutStraight:"ROUNDABOUT_STRAIGHT",roundaboutSharpRight:"ROUNDABOUT_SHARP_RIGHT",roundaboutRight:"ROUNDABOUT_RIGHT",roundaboutSlightRight:"ROUNDABOUT_SLIGHT_RIGHT",roundaboutSlightLeft:"ROUNDABOUT_SLIGHT_LEFT",roundaboutLeft:"ROUNDABOUT_LEFT",roundaboutSharpLeft:"ROUNDABOUT_SHARP_LEFT",roundaboutBack:"ROUNDABOUT_BACK",exitRoundabout:"EXIT_ROUNDABOUT",exitMotorwayLeft:"EXIT_MOTORWAY_LEFT",exitMotorwayRight:"EXIT_MOTORWAY_RIGHT",switchMotorwayLeft:"SWITCH_MOTORWAY_LEFT",switchMotorwayRight:"SWITCH_MOTORWAY_RIGHT",enterCarpoolLaneLeft:"ENTER_CARPOOL_LANE_LEFT",enterCarpoolLaneRight:"ENTER_CARPOOL_LANE_RIGHT",exitCarpoolLaneLeft:"EXIT_CARPOOL_LANE_LEFT",exitCarpoolLaneRight:"EXIT_CARPOOL_LANE_RIGHT",mergeLeftLane:"MERGE_LEFT_LANE",mergeRightLane:"MERGE_RIGHT_LANE",takeShipFerry:"TAKE_SHIP_FERRY",takeCarTrain:"TAKE_CAR_TRAIN",leaveShipFerry:"LEAVE_SHIP_FERRY",leaveCarTrain:"LEAVE_CAR_TRAIN",crossBorder:"CROSS_BORDER",passTollgate:"TOLLGATE"},Vr={urban:"URBAN",motorway:"MOTORWAY",controlledAccess:"CONTROLLED_ACCESS"},qr={endOfRoad:"END_OF_ROAD",atTrafficLight:"AT_TRAFFIC_LIGHT",onToBridge:"ON_TO_BRIDGE",onBridge:"ON_BRIDGE",afterBridge:"AFTER_BRIDGE",intoTunnel:"INTO_TUNNEL",insideTunnel:"INSIDE_TUNNEL",afterTunnel:"AFTER_TUNNEL"},Yr={cashCoinsAndBills:"CASH_COINS_AND_BILLS",cashBillsOnly:"CASH_BILLS_ONLY",cashCoinsOnly:"CASH_COINS_ONLY",cashExactChange:"CASH_EXACT_CHANGE",creditCard:"CREDIT_CARD",debitCard:"DEBIT_CARD",travelCard:"TRAVEL_CARD",etc:"ETC",etcTransponder:"ETC_TRANSPONDER",etcVideoCamera:"ETC_VIDEO_CAMERA",subscription:"SUBSCRIPTION"},$r={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",rightUTurn:"RIGHT_U_TURN",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",leftUTurn:"LEFT_U_TURN"},Zr={unknown:"UNKNOWN",noMarking:"NO_MARKING",longDashed:"LONG_DASHED",doubleSolid:"DOUBLE_SOLID",singleSolid:"SINGLE_SOLID",solidDashed:"SOLID_DASHED",dashedSolid:"DASHED_SOLID",shortDashed:"SHORT_DASHED",shadedAreaMarking:"SHADED_AREA_MARKING",dashedBlocks:"DASHED_BLOCKS",doubleDashed:"DOUBLE_DASHED",crossingAlert:"CROSSING_ALERT",physicalDivider:"PHYSICAL_DIVIDER",physicalDividerLessThan3m:"PHYSICAL_DIVIDER_LESS_THAN_3M",physicalDividerGuardrail:"PHYSICAL_DIVIDER_GUARDRAIL",curb:"CURB"},zr={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",back:"BACK"},Jr={regular:"REGULAR",small:"SMALL"},Qr={left:"LEFT",right:"RIGHT",leftAndRight:"LEFT_AND_RIGHT"},Xr={properties:[]},eo=e=>({text:e.text}),to=e=>({properties:(e.properties??[]).map(e=>Vr[e]??e.toUpperCase()),...e.roadNames?.length&&{streetName:eo(e.roadNames[0].identifier)},...e.countryCodeIso2&&{countryCode:ar(e.countryCodeIso2)},...e.roadShields?.length&&{roadShields:e.roadShields.map(e=>({roadNumber:e.roadNumber?eo(e.roadNumber):{text:""},countryCode:ar(e.countryCodeIso2??""),...e.countrySubdivisionCodeIso&&{stateCode:e.countrySubdivisionCodeIso},...e.iconReference&&{roadShieldReference:e.iconReference}}))}}),no=e=>({...e.tollgateName&&{tollgateName:eo(e.tollgateName)},...e.tollPaymentTypes?.length&&{tollPaymentTypes:e.tollPaymentTypes.map(e=>Yr[e]??e)},...e.countryCrossingFromName&&{countryCrossingFromName:eo(e.countryCrossingFromName)},...e.countryCrossingFromCodeIso2&&{countryCrossingFromCode:ar(e.countryCrossingFromCodeIso2)},...e.countryCrossingToName&&{countryCrossingToName:eo(e.countryCrossingToName)},...e.countryCrossingToCodeIso2&&{countryCrossingToCode:ar(e.countryCrossingToCodeIso2)}}),ro=e=>zr[e]??e,oo=e=>{return{...e.message&&{message:e.message},...e.intersectionName&&{intersectionName:eo(e.intersectionName)},...e.drivingSide&&{drivingSide:e.drivingSide.toUpperCase()},...e.landmark&&{landmark:qr[e.landmark]??e.landmark},...!A(e.distanceToPreviousTrafficLightInMeters)&&{trafficLightOffsetInMeters:e.distanceToPreviousTrafficLightInMeters},...e.sideRoads&&{sideRoads:(n=e.sideRoads,n.map(e=>({side:Qr[e.side]??e.side,offsetFromManeuverInMeters:e.offsetFromManeuverInMeters,...!A(e.isDrivable)&&{isDrivable:e.isDrivable}})))},...e.maneuverView&&{maneuverView:(t=e.maneuverView,{...t.onRouteAngle&&{onRouteAngle:ro(t.onRouteAngle)},offRouteAngles:(t.offRouteAngles??[]).map(ro)})},...e.roundaboutType&&{roundaboutType:Jr[e.roundaboutType]??e.roundaboutType},...!A(e.isManeuverObligatory)&&{isManeuverObligatory:e.isManeuverObligatory},...!A(e.changeOfAngleInDegrees)&&{changeOfAngleInDegrees:e.changeOfAngleInDegrees},...!A(e.ambiguousExitOffsetFromManeuverInMeters)&&{offsetOfAmbiguousExitFromManeuverInMeters:e.ambiguousExitOffsetFromManeuverInMeters},...!A(e.roundaboutExitNumber)&&{roundaboutExitNumber:e.roundaboutExitNumber}};var t,n},ao=(e,t)=>{const n=e.signpost?(e=>{if(e.exitName||e.exitNumber||e.towardName)return{...e.exitName&&{exitName:eo(e.exitName)},...e.exitNumber&&{exitNumber:eo(e.exitNumber)},towardName:e.towardName?eo(e.towardName):{text:""}}})(e.signpost):void 0,r=(e.nextRoadInformation?.roadShields??[]).map(e=>e.iconReference).filter(e=>!!e);return{...n&&{signpost:n},...t&&{roadShieldAtlasReference:t},...r.length&&{roadShieldReferences:r},...e.signpost?.exitIconReference&&{signpostRoadShieldReferences:[e.signpost.exitIconReference]}}},io=(e,t,n,r)=>({maneuverPoint:t,pathPointIndex:n,routeOffsetInMeters:e.routeOffsetInMeters,maneuver:e.maneuver?jr[e.maneuver]??e.maneuver:e.maneuver,routePath:(e.routePath??[]).map(e=>({point:e.point.coordinates,distanceInMeters:e.distanceFromRouteStartInMeters,travelTimeInSeconds:e.travelTimeFromRouteStartInSeconds})),nextRoadInfo:e.nextRoadInformation?to(e.nextRoadInformation):Xr,previousRoadInfo:e.previousRoadInformation?to(e.previousRoadInformation):Xr,...oo(e),...ao(e,r),...no(e)}),so=(e,t,n)=>{const r=[];let o=0;for(const a of e){const e=a.maneuverPoint.coordinates;for(let n=o;n<t.length;n++)if(Wr(t[n],e)){o=n;break}r.push(io(a,e,o,n))}return{instructions:r}},co={requestValidation:Mr,buildRequest:e=>{const t=e.locations.map(p).includes("path"),n=((e,t)=>{const n=[];for(const r of e)if("waypoint"===p(r)){const e=Ir(r),o=e?.candidateEntryPoints?.length?"ignore":t,[a,i]=d(r,{useEntryPoint:o});n.push({coordinate:[a,i],...e&&{options:e}})}else n.push(...br(r));return n})(e.locations,e.useEntryPoints),r=(e=>{const t={type:"Point",coordinates:e[0].coordinate},n={type:"Point",coordinates:(e.at(-1)??e[0]).coordinate},r=e.slice(1,-1);return{origin:t,destination:n,...r.length&&{waypoints:{type:"MultiPoint",coordinates:r.map(e=>e.coordinate)}}}})(n),a=(e=>{return{...Vn(e),...e.maxAlternatives&&{maxPathAlternativeRoutes:e.maxAlternatives},..."arriveBy"===e.when?.option&&e.when.date&&{arrivalDateTime:e.when.date.toISOString()},...e.guidance&&{guidance:"instructions",instructionPhonetics:"ipa"},...e.costModel?.avoidAreas?.length&&{avoidAreas:(t=e.costModel.avoidAreas,{rectangles:t.map(e=>{const t=o(e);if(!t)throw new Error("Could not derive a bounding box from an avoidAreas rectangle");const[n,r,a,i]=t;return{type:"Feature",bbox:[n,r,a,i],geometry:null}})})},...e.arrivalSide&&{arrivalSidePreference:"curb"===e.arrivalSide?"curbSide":"anySide"}};var t})(e),i=(e=>({...Ie(e),Attributes:hr(e)}))(e),s=((e,t)=>{const n=e.slice(1).map((t,n)=>({...e[n].legToNext,...Sr(t)}));if(t||!n.every(e=>0===Object.keys(e).length))return n})(n,t),c={routePlanningLocations:r,...a,...s&&{legs:s},...e.vehicle&&yr(e.vehicle)};if(Tr(e)){const t=((e,t,n)=>{const r=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateLongDistanceEVRoute`,o=new URL(r);fr(o,e.vehicle),e.chargingStopsStrategy&&o.searchParams.set("chargingStopsStrategy",e.chargingStopsStrategy);const a=Ht(e.vehicle)?.charging;if(!qn(e.vehicle)&&!a?.chargingConnectors?.length)throw new Error("Charging preferences require a charging model: set vehicle.model.engine.charging.chargingConnectors (or a predefined vehicle.model.variantId) to plan charging stops.");return{method:"POST",url:o,data:{...t,...a&&{chargingParameters:{...a.batteryCurve?.length&&{batteryCurve:a.batteryCurve},...a.chargingConnectors?.length&&{chargingConnectors:[...a.chargingConnectors]},...!A(a.chargingTimeOffsetInSec)&&{chargingTimeOffsetInSec:a.chargingTimeOffsetInSec}}},vehicleEngineType:"electric"},headers:n}})(e,c,i);return Cr(t.url,e),t}if(e.vehicle&&qn(e.vehicle))throw new Error(Rr);const l=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/routes/calculate`,u=new URL(l);return e.vehicle&&$n(u,e.vehicle),Cr(u,e),{method:"POST",url:u,data:c,headers:i}},sendRequest:X,parseResponse:(e,t)=>{const n=e.routes.map((n,r)=>((e,t,n,r)=>{const a={type:"LineString",coordinates:e.legs.flatMap(e=>e.path.coordinates)};return{type:"Feature",geometry:a,id:s(),bbox:o(a),properties:{index:t,summary:Fr(e.summary,n),sections:kr(e,n),...e.instructions?.length&&{guidance:so(e.instructions,a.coordinates,r)},...e.progressPoints&&{progress:e.progressPoints.map(e=>({pointIndex:e.pathIndex,distanceInMeters:e.distanceInMeters,travelTimeInSeconds:e.travelDurationInSeconds}))}}}})(n,r,t,e.roadShieldAtlasReference)),r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},parseResponseError:Ot,getAPIVersion:()=>3},lo=async e=>V(e,co,"Routing"),uo=C.object({minFuzzyLevel:C.number().min(1).max(4).optional(),maxFuzzyLevel:C.number().min(1).max(4).optional()}),po=ue.extend(ot.extend(uo.shape).shape),mo=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:Ue(e.details)}};break;case"NEARBY":t={...e,details:{position:Ue({lon:e.details.lon,lat:e.details.lat}),text:e.details.text,query:e.details.query}};break;case"BOOKMARK":case"W3W":t=e}return t},go={requestValidation:{schema:po},buildRequest:e=>{const t=new URL(`${(e=>Ee(e,`search/${encodeURIComponent(e.query??"")}.json`))(e)}`);Me(t,e);const n=t.searchParams;return Pe(n,"typeahead",e.typeahead),Pe(n,"ofs",e.offset),Ae(n,"countrySet",e.countries),Le(n,e.geoBias),Pe(n,"minFuzzyLevel",e.minFuzzyLevel),Pe(n,"maxFuzzyLevel",e.maxFuzzyLevel),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const t=e.results.map(We),n=a(o(t)),r=e.summary.queryIntent?.map(mo);return{type:"FeatureCollection",properties:{...je(e.summary),...r&&{queryIntent:r}},features:t,...n&&{bbox:n}}}},ho=C.object({geometries:C.array(C.union([re,te]))}),yo=ue.extend(ho.shape),fo=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:_e(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:Re(e.coordinates[0],50).map(e=>_e(e))}];case"MultiPolygon":return e.coordinates.length>50?(e=>{let t=/* @__PURE__ */new Map;return e.coordinates.forEach(e=>{const n=r(e[0]);if(n){const r=Math.abs((n[2]-n[0])*(n[3]-n[1]));t.set(e,r)}}),t=new Map([...t.entries()].sort((e,t)=>t[1]-e[1]).splice(0,50)),[...t.keys()]})(e).flatMap(e=>fo({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>fo({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>fo(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},To={requestValidation:{schema:yo},buildRequest:e=>{const t=new URL(`${n=e,Ee(n,`geometrySearch/${encodeURIComponent(n.query??"")}.json`)}`);var n;return Me(t,e),{url:t,headers:Ce(e),data:{geometryList:e.geometries.flatMap(fo)}}},sendRequest:Q,parseResponse:e=>{const t=e.results.map(We),n=a(o(t));return{type:"FeatureCollection",properties:{...je(e.summary)},features:t,...n&&{bbox:n}}}},Ro=async e=>"route"in e?qe(e):"geometries"in e?(async e=>V(e,To,"GeometrySearch"))(e):(async e=>V(e,go,"FuzzySearch"))(e),bo=async e=>tt("discoverOnePlace",e,Ro),Io=C.object({query:C.string()}),So=C.object({geoBias:nt.optional(),limit:C.number().max(100).optional(),countries:C.array(C.string()).optional(),resultTypes:C.array(C.string()).optional()}),Co=Io.extend(So.shape),vo={requestValidation:{schema:Co},buildRequest:e=>{const t=new URL(`${n=e,Ee(n,`autocomplete/${encodeURIComponent(n.query)}.json`)}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",ve(r,e),Pe(r,"limit",e.limit),Le(r,e.geoBias),Ae(r,"countrySet",e.countries),Ae(r,"resultSet",e.resultTypes),{url:t,headers:Ce(e)}},sendRequest:J,parseResponse:e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:Ue(t)},radiusMeters:n.radius}},results:(r=e.results,r.map(e=>({segments:e.segments.map(e=>{if((e=>"category"===e.type)(e)){const{id:t,...n}=e;return{...n,category:R[Number(t)]}}return e})})))};var r}},Ao=async e=>V(e,vo,"Autocomplete"),Po=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean),Lo=e=>"category"===e.type&&e.matchedAlternativeName?[e.value,e.matchedAlternativeName]:[e.value],Mo=(e,t)=>{const n=t.flatMap(({segments:t})=>{const[n]=t;return 1===t.length&&"plaintext"!==n.type&&Lo(n).some(t=>((e,t)=>{const n=Po(t).join(""),r=Po(e);return""!==n&&r.some((e,t)=>r.slice(t).join("").startsWith(n))})(t,e))?[n]:[]});return n.find(t=>Lo(t).some(t=>((e,t)=>{const[n,...r]=Po(t);return 0===r.length&&Po(e).some(e=>e.startsWith(n)&&2*n.length>=e.length)})(t,e)))??n[0]},Eo=({query:e,concept:t,places:n,maxResults:r})=>{const o=D(n,e=>e.id),a="none"===t.status?o:E(o,t=>((e,t)=>{const n=Po(e);return Po(t).every(e=>n.some(t=>t.startsWith(e)))})(t.title,e)).flat();return[..."shown"===t.status?[t.suggestion]:[],...a].slice(0,r)},wo="SearchSuggestions",Do={brand:!0,category:!0},xo=e=>e in Do,Oo={place:["POI"],address:["PAD","Addr","XStr"],street:["Str"],area:["Geo"]},No={POI:"place",Street:"street",Geography:"area","Point Address":"address","Address Range":"address","Cross Street":"address"},Bo=e=>e*Math.PI/180,Ho=(e,t)=>e.properties.distance??(t&&(([e,t],[n,r])=>{const o=Math.sin(Bo(r-t)/2)**2+Math.cos(Bo(t))*Math.cos(Bo(r))*Math.sin(Bo(n-e)/2)**2;return 12742017.6*Math.asin(Math.sqrt(o))})(t,e.geometry.coordinates)),_o=(e,t)=>{const n=u(t)??void 0,r=((e,t)=>{if(t)return L(e,e=>Ho(e,t))?.properties.address.countryCode;const n=v(e,e=>e.properties.address.countryCode);return P(Object.keys(n),e=>n[e])})(e,n);return e.map(e=>((e,t,n)=>{const{type:r,address:o,poi:a}=e.properties,i=o.freeformAddress.split(", ").filter(Boolean),[s="",...c]=a?.name?[a.name,...i]:i,l=o.countryCode!==t?o.country:void 0;return{kind:No[r],id:String(e.id),title:s,subtitles:l?[...c,l]:c,distanceInMeters:Ho(e,n),resolve:async()=>({...e,properties:M(e.properties,["distance","score"])})}})(e,r,n))},Fo=e=>{if(e instanceof F)throw new F(wo,e.cause);if(e instanceof _)throw new _(e.message,wo,e.status);if(e instanceof B)throw new B(e.message,wo,e.issues);throw e},Uo=(e,t)=>{const n={...t,..."brand"===e.type?{poiBrands:[e.value]}:{poiCategories:[e.category]}},r={title:e.value,refineParams:n,refine:e=>Ro({...n,...e&&{signal:e}})};return"brand"===e.type?{...r,kind:"brand"}:{...r,kind:"category",category:e.category}},Go=(e,t)=>D(e.flatMap(e=>e.segments.flatMap(e=>"plaintext"===e.type?[]:[Uo(e,t)])),e=>`${e.kind}:${e.title}`),ko=(e,t,n,r)=>{const o=Mo(e,t);return o?"brand"!==o.type||((e,t)=>{const n=Po(e).join("");return t.slice(0,5).some(e=>e.properties.poi?.brands?.some(e=>Po(e).join("")===n))})(o.value,n)?{status:"shown",suggestion:Uo(o,r)}:{status:"withheld"}:{status:"none"}},Ko=async e=>{const{query:t,maxResults:n,filters:r,origin:o,view:a,signal:i,...s}=e,c=r?.countries,l=Math.max(1,Math.min(n??5,10)),{placeKinds:u,refinementKinds:d,wantsPlaces:p,wantsRefinements:m}=(e=>{const t=e?.filter(e=>!xo(e)),n=e?.filter(xo);return{placeKinds:t,refinementKinds:n,wantsPlaces:!e||Boolean(t?.length),wantsRefinements:!e||Boolean(n?.length)}})(r?.kinds),g=o&&{position:o},h=(r?.boundingBox&&{boundingBox:r.boundingBox})??g,y={...M(s,["onAPIRequest","onAPIResponse","apiVersion"]),query:"",countries:c,geoBias:h,view:a},f={...s,signal:i,query:t,limit:10,countries:c,view:a,typeahead:!0,geoBias:h,indexes:u?.flatMap(e=>Oo[e]),poiCategories:r?.poiTypes,geographyTypes:r?.areaTypes},[T,R]=await Promise.all([p?Ro(f):void 0,m?Ao({...s,signal:i,query:t,limit:l,countries:c,geoBias:g,resultTypes:d??["brand","category"]}):void 0]).catch(Fo),b=R?.results??[];if(!p)return{suggestions:Go(b,y).slice(0,l)};const I=(T?.features??[]).filter(e=>!u||u.includes(No[e.properties.type]));return{suggestions:Eo({query:t,concept:ko(t,b,I,y),places:_o(I,o),maxResults:l})}},Wo=864e5,jo=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n},Vo=e=>jo(/* @__PURE__ */new Date,-e),qo=e=>e instanceof Date?e.toISOString().slice(0,10):e,Yo=e=>Date.parse(qo(e)),$o=/(?:Z|[+-]\d{2}:\d{2})$/,Zo=e=>new Date($o.test(e)?e:`${e}Z`),zo=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],Jo={speed:{dataType:"SPEED",field:"v"},freeFlowSpeed:{dataType:"FREE_FLOW_SPEED",field:"fv"},congestionLevel:{dataType:"CONGESTION_LEVEL",field:"c"},travelTime:{dataType:"TRAVEL_TIME",field:"t"},networkLength:{dataType:"NETWORK_LENGTH",field:"l"}},Qo=Array.from({length:24},(e,t)=>t),Xo=e=>zo.indexOf(e),ea=(e,n)=>{const r={};for(const o of t){const t=e[Jo[o].field];void 0!==t&&(r[o]=n(t))}return r},ta=e=>ea(e,e=>e),na=e=>t.find(t=>Jo[t].dataType===e),ra=e=>{const t=Zo(e);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,date:new Date(Yo(t)),hour:t.getUTCHours()}},oa={yearly:({year:e})=>({year:e}),monthly:({year:e,month:t})=>({year:e,month:t}),weekly:({date:e})=>(e=>{const t=jo(e,4-(e.getUTCDay()||7)),n=t.getUTCFullYear(),r=(t.getTime()-Date.UTC(n,0,1))/Wo;return{year:n,week:Math.floor(r/7)+1}})(e),daily:({date:e})=>({date:e}),hourly:({date:e,hour:t})=>({date:e,hour:t})},aa=(e,t)=>e.map(e=>({...oa[t](ra(e.time)),...ta(e)})),ia={MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,SUNDAY:7},sa=e=>{const[t,n]=e.time.split("-"),r=Object.hasOwn(ia,t)?ia[t]:void 0;return void 0===r?void 0:{day:r,hour:Number(n),...ta(e)}},ca=({day:e,hour:t})=>24*(e-1)+t,la=e=>({tileCentre:[e.lon,e.lat],...ta(e)}),ua=e=>({startDate:Zo(e.startDate),endDate:Zo(e.endDate),labels:e.labels.map(({name:e})=>e)}),da=e=>{return{...e.yearly&&{yearly:aa(e.yearly,"yearly")},...e.monthly&&{monthly:aa(e.monthly,"monthly")},...e.weekly&&{weekly:aa(e.weekly,"weekly")},...e.daily&&{daily:aa(e.daily,"daily")},...e.hourly&&{hourly:aa(e.hourly,"hourly")},...e.average&&{average:(t=e.average,t.map(sa).filter(e=>void 0!==e).sort((e,t)=>ca(e)-ca(t)))}};var t},pa=e=>ea(e,e=>e.map(ua)),ma=e=>{return{type:e.type,id:e.id,geometry:e.geometry,properties:(t=e.properties,{name:t.name,...void 0!==t.timezone&&{timezone:t.timezone},level:t.level,baseData:ta(t.baseData),timedData:da(t.timedData),...t.tiledData&&{tiledData:{tiles:t.tiledData.tiles.map(la)}},...t.anomalies&&{anomalies:pa(t.anomalies)}}),bbox:o(e.geometry)};var t},ga=e=>{const n=e.flatMap(e=>e.properties.tiledData?.tiles??[]),r={};for(const o of t){const e=n.map(e=>e[o]).filter(e=>null!=e);e.length>0&&(r[o]={min:Math.min(...e),max:Math.max(...e)})}return r},ha=e=>{const t=e.map(Yo);return{startDate:new Date(Math.min(...t)),endDate:new Date(Math.max(...t))}},ya=C.union([C.date(),C.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),fa=C.union([C.object({type:C.literal("Polygon"),coordinates:C.array(C.array(C.array(C.number()))).min(1)}),C.object({type:C.literal("MultiPolygon"),coordinates:C.array(C.array(C.array(C.array(C.number())))).min(1)})]),Ta=e=>Yo(e)<=Yo(Vo(2)),Ra={requestValidation:{schema:K.extend({name:C.string().optional(),startDate:ya.optional(),endDate:ya.optional(),days:C.array(ya).min(1).optional(),metrics:C.union([C.array(C.enum(t)).min(1),C.literal("all")]),functionalRoadClasses:C.union([C.array(C.enum(zo)).min(1),C.literal("all")]),hours:C.union([C.array(C.number().int().min(0).max(23)).min(1),C.literal("all")]),geometry:fa}).refine(e=>{const t=void 0!==e.days,n=void 0!==e.startDate;if(t&&n)return!1;if(!t&&!n)return!1;if(void 0!==e.startDate){const t=e.endDate??Vo(3),n=(Yo(t)-Yo(e.startDate))/Wo;return n>=1&&n<=31}return!0},{message:"Provide either startDate (with optional endDate, at least 1 day apart and within 31 days) or days — but not both"}).refine(e=>void 0!==e.days?e.days.every(Ta):void 0===e.endDate||Ta(e.endDate),{message:"Dates must be at least 2 days before today"})},buildRequest:e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));Se(n.searchParams,e);const r=Array.isArray(e.days)?{days:e.days.map(qo)}:{startDate:qo(e.startDate??Vo(4)),endDate:qo(e.endDate??Vo(3))};return{method:"POST",url:n,data:{name:e.name??`Maps SDK JS Area Analytics Report ${/* @__PURE__ */(new Date).toISOString()}`,...r,dataTypes:("all"===e.metrics?t:e.metrics).map(e=>Jo[e].dataType),frcs:"all"===e.functionalRoadClasses?zo.map((e,t)=>t):e.functionalRoadClasses.map(Xo),hours:"all"===e.hours?Qo:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},sendRequest:X,parseResponse:e=>{const t=e.features.map(ma);return{type:"FeatureCollection",properties:{...ha(e.properties.days),metrics:e.properties.dataTypes.map(na).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:ga(t)},features:t}}},ba=async e=>V(e,Ra,"TrafficAreaAnalytics"),Ia=["incidents.type","incidents.geometry.type","incidents.geometry.coordinates",...Object.keys({id:!0,iconCategory:!0,magnitudeOfDelay:!0,"events.description":!0,"events.code":!0,"events.iconCategory":!0,startTime:!0,endTime:!0,from:!0,to:!0,lengthInMeters:!0,delayInSeconds:!0,roadNumbers:!0,timeValidity:!0,probabilityOfOccurrence:!0,numberOfReports:!0,lastReportTime:!0}).map(e=>`incidents.properties.${e}`)].join(","),Sa=e=>({description:e.description,code:e.code,category:Nr(e.iconCategory)}),Ca=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:Nr(t.iconCategory),magnitudeOfDelay:Br(t.magnitudeOfDelay),events:(t.events??[]).map(Sa),...t.startTime&&{startTime:new Date(t.startTime)},...t.endTime&&{endTime:new Date(t.endTime)},...t.from&&{from:t.from},...t.to&&{to:t.to},...null!=t.lengthInMeters&&{lengthInMeters:t.lengthInMeters},...null!=t.delayInSeconds&&{delayInSeconds:t.delayInSeconds},...t.roadNumbers&&{roadNumbers:t.roadNumbers},timeValidity:t.timeValidity,...t.probabilityOfOccurrence&&{probabilityOfOccurrence:t.probabilityOfOccurrence},...null!=t.numberOfReports&&{numberOfReports:t.numberOfReports},...t.lastReportTime&&{lastReportTime:new Date(t.lastReportTime)}}}},va=e=>"Polygon"===e.type?{type:"Polygon",coordinates:e.coordinates}:{type:"MultiPolygon",coordinates:e.coordinates},Aa=(e,t)=>{const n=(e=>"FeatureCollection"===e.type?e.features.map(e=>e.geometry):["Feature"===e.type?e.geometry:e])(t).map(va).map(e=>({geometry:e,bbox:x(e)}));return e.filter(e=>{const t=x(e.geometry);return n.some(n=>{return r=t,o=n.bbox,r[0]<=o[2]&&o[0]<=r[2]&&r[1]<=o[3]&&o[1]<=r[3]&&O(e.geometry,n.geometry);var r,o})})},Pa=C.array(C.number()).min(2,"a position needs at least two coordinates"),La=C.array(Pa).min(4,"a linear ring needs at least four positions"),Ma=C.array(La).min(1,"a Polygon needs at least one ring"),Ea=C.discriminatedUnion("type",[C.object({type:C.literal("Polygon"),coordinates:Ma}),C.object({type:C.literal("MultiPolygon"),coordinates:C.array(Ma).min(1,"a MultiPolygon needs at least one polygon")})]),wa=C.object({type:C.literal("Feature"),geometry:Ea,id:C.union([C.string(),C.number()]).optional(),properties:C.unknown().optional()}),Da=C.union([Ea,wa,C.object({type:C.literal("FeatureCollection"),features:C.array(wa).min(1,"a FeatureCollection polygon needs at least one feature")})]),xa={requestValidation:{schema:K.extend({bbox:se.optional(),polygon:Da.optional(),ids:C.array(C.string()).min(1,"ids must contain at least one id").optional(),categoryFilter:C.array(C.enum(I)).optional(),timeValidityFilter:C.array(C.enum(["present","future"])).optional()}),refinements:[{check:e=>1===[e.bbox,e.polygon,e.ids].filter(Boolean).length,message:"Provide exactly one of bbox, polygon or ids"}]},getAPIVersion:()=>2,buildRequest:e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidents/details`)(e)),n=t.searchParams;((e,t)=>{Ae(e,"iconCategories",t.categoryFilter?.map(Or)),Ae(e,"timeValidity",t.timeValidityFilter)})(n,e);const r=(e=>({...Ie(e),Attributes:Ia}))(e);if(e.ids){const{ids:o}=e;return o.length>5?{method:"POST",url:t,headers:r,data:{ids:o}}:(n.append("ids",o.join(",")),{method:"GET",url:t,headers:r})}const a=e.polygon?x(e.polygon,{recompute:!0}):o(e.bbox);return a&&n.append("bbox",a.join(",")),{method:"GET",url:t,headers:r}},sendRequest:X,parseResponse:(e,t)=>{const n=(e.incidents??[]).filter(e=>null!==e).map(Ca);return{type:"FeatureCollection",features:t?.polygon?Aa(n,t.polygon):n}}},Oa=async e=>V(e,xa,"TrafficIncidentDetails");export{H as APIErrorCode,F as SDKAbortError,B as SDKError,_ as SDKServiceError,qe as alongRouteSearch,On as budgetTypes,G as buildResponseError,k as buildValidationError,er as calculateReachableRange,nr as calculateReachableRanges,lo as calculateRoute,bo as discoverOnePlace,Ro as discoverPlaces,Je as evChargingStationsAvailability,ct as geocode,lt as geocodeOne,ht as geometryData,Dt as getPOICategories,xt as getPOICategoryCodes,bt as getPlaceDetails,Qe as getPlaceWithEVAvailability,Xe as getPlacesWithEVAvailability,Ko as getSearchSuggestions,et as hasChargingAvailability,U as parseDefaultResponseError,mr as reverseGeocode,$e as routeTypes,Ze as tollTransponderOptions,ba as trafficAreaAnalytics,Oa as trafficIncidentDetails};
|
|
2
2
|
//# sourceMappingURL=services.es.js.map
|