@tomtom-org/maps-sdk 0.45.4 → 0.45.6
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 +24 -0
- package/core/dist/core.es.js +1 -1
- package/core/dist/core.es.js.map +1 -1
- package/core/dist/index.d.ts +361 -32
- package/core/package.json +1 -0
- package/map/dist/THIRD_PARTY.txt +1 -107
- package/map/dist/index.d.ts +208 -14
- package/map/dist/map.es.js +1 -1
- package/map/dist/map.es.js.map +1 -1
- package/map/package.json +3 -2
- package/package.json +3 -2
- package/services/dist/index.d.ts +3 -3
- package/services/dist/services.es.js +1 -1
- package/services/dist/services.es.js.map +1 -1
package/map/package.json
CHANGED
|
@@ -37,8 +37,9 @@
|
|
|
37
37
|
"entryPoint": "./index.ts"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"
|
|
41
|
-
"lodash-es": "catalog:"
|
|
40
|
+
"@turf/turf": "catalog:",
|
|
41
|
+
"lodash-es": "catalog:",
|
|
42
|
+
"maplibre-gl": "catalog:"
|
|
42
43
|
},
|
|
43
44
|
"dependencies": {
|
|
44
45
|
"@turf/bearing": "^7.3.4",
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@tomtom-org/maps-sdk",
|
|
3
3
|
"author": "TomTom International B.V.",
|
|
4
4
|
"license": "See in LICENSE.txt",
|
|
5
|
-
"version": "0.45.
|
|
5
|
+
"version": "0.45.6",
|
|
6
6
|
"description": "TomTom Maps for JavaScript",
|
|
7
7
|
"keywords": [
|
|
8
8
|
"tomtom",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"nodejs"
|
|
19
19
|
],
|
|
20
20
|
"devDependencies": {
|
|
21
|
-
"@biomejs/biome": "^2.4.
|
|
21
|
+
"@biomejs/biome": "^2.4.3",
|
|
22
22
|
"@size-limit/file": "^11.2.0",
|
|
23
23
|
"@size-limit/preset-app": "^11.2.0",
|
|
24
24
|
"size-limit": "^11.2.0",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"yaml": "^2.8.2"
|
|
27
27
|
},
|
|
28
28
|
"peerDependencies": {
|
|
29
|
+
"@turf/turf": "^7.3.4",
|
|
29
30
|
"lodash-es": "^4.17.23",
|
|
30
31
|
"maplibre-gl": "^5.18.0",
|
|
31
32
|
"zod": "^4.3.6"
|
package/services/dist/index.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ import { RevGeoAddressProps } from '@tomtom-org/maps-sdk/core';
|
|
|
48
48
|
import { RoadShieldReference } from '@tomtom-org/maps-sdk/core';
|
|
49
49
|
import { RoutePathPoint } from '@tomtom-org/maps-sdk/core';
|
|
50
50
|
import { RoutePlanningLocation } from '@tomtom-org/maps-sdk/core';
|
|
51
|
-
import {
|
|
51
|
+
import { RouteProgressPoint } from '@tomtom-org/maps-sdk/core';
|
|
52
52
|
import { Routes } from '@tomtom-org/maps-sdk/core';
|
|
53
53
|
import { RouteSummary } from '@tomtom-org/maps-sdk/core';
|
|
54
54
|
import { SearchPlaceProps } from '@tomtom-org/maps-sdk/core';
|
|
@@ -3658,7 +3658,7 @@ declare type FuzzySearchFeatureCollectionProps = SearchSummary & {
|
|
|
3658
3658
|
* const params: FuzzySearchParams = {
|
|
3659
3659
|
* key: 'your-api-key',
|
|
3660
3660
|
* query: 'pizz', // Will find "pizza" restaurants
|
|
3661
|
-
*
|
|
3661
|
+
* position: [4.9041, 52.3676]
|
|
3662
3662
|
* };
|
|
3663
3663
|
*
|
|
3664
3664
|
* // Fuzzy search with custom fuzziness
|
|
@@ -6031,7 +6031,7 @@ declare type RouteAPI = {
|
|
|
6031
6031
|
sections: SectionAPI[];
|
|
6032
6032
|
summary: SummaryAPI_2;
|
|
6033
6033
|
guidance?: GuidanceAPI;
|
|
6034
|
-
progress?:
|
|
6034
|
+
progress?: RouteProgressPoint[];
|
|
6035
6035
|
};
|
|
6036
6036
|
|
|
6037
6037
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{mergeFromGlobal as e,generateTomTomHeaders as t,getPosition as n,poiCategoriesToID as r,toPointGeometry as o,views as a,bboxFromGeoJSON as i,bboxOnlyIfWithArea as s,generateId as p,bboxFromCoordsArray as c,plugTypes as u,currentTypes as l,avoidableTypes as d,getPositionStrict as m,getRoutePlanningLocationType as g,inputSectionTypesWithGuidance as h,inputSectionTypes as y,indexedMagnitudes as f}from"@tomtom-org/maps-sdk/core";import{z as b}from"zod";import{isNil as S,omit as T}from"lodash-es";var P=/* @__PURE__ */(e=>(e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e))(P||{});class R extends Error{constructor(e,t,n){super(e),this.service=t,this.issues=n,Error.captureStackTrace&&Error.captureStackTrace(this,R)}}const I={[P.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[P.FORBIDDEN]:"Request failed with status code 403"};class C extends R{constructor(e,t,n){super(e,t),this.status=n,this.status&&I[this.status]&&(this.message=I[this.status])}}const x=(e,t)=>{const{data:n,message:r,status:o}=e;return new C(n?.error||n?.errorText||r,t,o)},v=(e,t,n)=>{if(e.status){const r=e;return n?n(r,t):x(r,t)}return new R(e.message,t)},w=(e,t)=>new R(e.message,t,e.issues),A=b.object({apiKey:b.string().optional(),commonBaseURL:b.string().optional(),customServiceBaseURL:b.string().optional(),language:b.string().optional()});class L extends Error{constructor(e){super(e.issues.map(e=>`${e.path.length>0?`${e.path.join(".")}: `:""}${e.message}`).join("; ")),this.issues=e.issues}}const M=async(n,r,o)=>{const a=r.getAPIVersion?.(n),i=e({...n,...a&&{apiVersion:a}});if(void 0===n.validateRequest||n.validateRequest)try{((e,t)=>{const n=(t?.schema?A.extend(t.schema.shape):A).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 L(n.error)})(i,r.requestValidation)}catch(c){return Promise.reject(w(c,o))}const s=r.buildRequest(i),p=t(i);n.onAPIRequest?.(s);try{const e=await r.sendRequest(s,p);return n.onAPIResponse?.(s,e),r.parseResponse(await e.data,i)}catch(c){return n.onAPIResponse?.(s,c),Promise.reject(v(c,o,r.parseResponseError))}};class E extends Error{constructor(e,t,n){super(t??`HTTP Error ${e}`),this.name="FetchError",this.status=e,this.data=n,Error.captureStackTrace&&Error.captureStackTrace(this,E)}}const 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 E(e.status,t,n)},j=async(e,t)=>W(await fetch(e,{headers:t})),k=async(e,t)=>W(await fetch(e.url,{method:"POST",body:JSON.stringify(e.data),headers:{...t,"Content-Type":"application/json"}})),F=b.array(b.array(b.number())),U=b.object({type:b.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:b.union([b.array(b.number()),F,b.array(b.array(b.array(b.number()))),b.array(b.array(b.array(b.array(b.number()))))]),radius:b.optional(b.number()),radiusMeters:b.optional(b.number()),bbox:b.optional(b.array(b.number()))}).check(b.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),B=b.object({type:b.literal("Feature"),geometry:U,id:b.optional(b.union([b.string(),b.number()])),properties:b.any(),bbox:b.optional(b.array(b.number()))}),H=b.object({type:b.literal("FeatureCollection"),features:b.array(B),id:b.optional(b.union([b.string(),b.number()])),properties:b.any(),bbox:b.optional(b.array(b.number()))}),q=b.union([b.tuple([b.number().min(-180).max(180),b.number().min(-90).max(90)]),b.tuple([b.number().min(-180).max(180),b.number().min(-90).max(90),b.number()]),b.object({type:b.literal("Point"),coordinates:b.array(b.number())}),B]),D=b.union([b.array(b.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),b.array(b.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),K=b.union([U,B,H]),O=b.union([D,K,b.array(K)]),$=b.object({query:b.string()}),N=b.object({position:q.optional(),limit:b.number().max(100).optional(),radiusMeters:b.number().optional(),countries:b.array(b.string()).optional(),resultType:b.array(b.string()).optional()}),V=$.extend(N.shape),G=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),e.append("key",t.apiKey),t.language&&e.append("language",t.language)},z=(e,t,n)=>{for(const r of n||[])e.append(t,r)},_=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},Y=(e,t,n)=>{!S(n)&&e.append(t,String(n))},Z=(e,t)=>{const r=n(t);r&&(e.append("lat",String(r[1])),e.append("lon",String(r[0])))},J="/maps/orbis/places",Q=(e,t)=>{const n=e.searchParams;G(n,t),Y(n,"limit",t.limit),Z(n,t.position),_(n,"fuelSet",t.fuelTypes),_(n,"idxSet",t.indexes),_(n,"brandSet",t.poiBrands),t.poiCategories&&_(n,"categorySet",t.poiCategories.map(e=>"number"!=typeof e?r[e]:e)),_(n,"connectorSet",t.connectors),_(n,"mapcodes",t.mapcodes),_(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),Y(n,"minPowerKW",t.minPowerKW),Y(n,"maxPowerKW",t.maxPowerKW),Y(n,"view",t.view),Y(n,"openingHours",t.openingHours),Y(n,"timeZone",t.timeZone),Y(n,"relatedPois",t.relatedPois),_(n,"entityTypeSet",t.geographyTypes)},X=e=>{const t=new URL(`${n=e,n.customServiceBaseURL||`${n.commonBaseURL}${J}/autocomplete/${n.query}.json`}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",G(r,e),Y(r,"limit",e.limit),Z(r,e.position),_(r,"countrySet",e.countries),Y(r,"radius",e.radiusMeters),_(r,"resultSet",e.resultType),t},ee=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},te=e=>`${e[1]},${e[0]}`,ne=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=ee(e.southWest),n=ee(e.northEast)),[t[0],t[1],n[0],n[1]]},re=e=>[e.lon,e.lat],oe=e=>{const{position:t,...n}=e.context.geoBias||{};return{...e,context:{...e.context,geoBias:{...t&&{position:re(t)},radiusMeters:n.radius}}}},ae={requestValidation:{schema:V},buildRequest:X,sendRequest:j,parseResponse:oe},ie=async(e,t)=>M(e,{...ae,...t},"Autocomplete"),se={autocompleteSearch:ie,buildAutocompleteSearchRequest:X,parseAutocompleteSearchResponse:oe,autocompleteSearchTemplate:ae},pe=A.extend({id:b.string()}),ce=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}${J}/ev/id`)(e)),n=t.searchParams;return G(n,e),n.append("id",e.id),t},ue=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",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},de=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,me=(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}:{}})}},ge=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},he=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)me(e.connectors,e.status,t);return t},ye=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)}},fe=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,be=e=>{const t=e.timeRanges.map(e=>({start:ye(e.startTime),end:ye(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:fe(t)}},Se=e=>{const{position:t,entryPoints:n,poi:r,id:a,dist:i,boundingBox:s,chargingPark:p,...c}=e,u=p?.connectors?.map(e=>({...T(e,"connectorType"),type:e.connectorType,chargingSpeed:ue(e.ratedPowerKW)}));return{type:"Feature",geometry:o(re(t)),...s&&{bbox:ne(s)},id:a,properties:{...T(c,"viewport"),...i&&{distance:i},...n?.length&&{entryPoints:n.map(e=>({...e,position:re(e.position)}))},...u?.length&&{chargingPark:{...p,connectors:ge(u)}},...r&&{poi:{...T(r,"categorySet","openingHours"),brands:r?.brands?.map(e=>e.name)??[],categoryIds:r?.categorySet?.map(e=>e.id)??[],...r?.openingHours&&{openingHours:be(r?.openingHours)}}}}}},Te=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:re(t)},...n}},Pe=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:ue(e.ratedPowerKW)}))}))}))),chargingPointAvailability:le(t.chargingStations),connectorAvailabilities:he(t.chargingStations),...t.openingHours&&{openingHours:be(t.openingHours)}}:void 0;var n},Re={requestValidation:{schema:pe},buildRequest:ce,sendRequest:j,parseResponse:Pe,parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new C(n,t,e.status)}},Ie={buildEVChargingStationsAvailabilityRequest:ce,parseEVChargingStationsAvailabilityResponse:Pe,evChargingStationsAvailabilityTemplate:Re},Ce=b.object({typeahead:b.boolean().optional(),offset:b.number().max(1900).optional(),radiusMeters:b.number().optional(),boundingBox:O.optional(),countries:b.array(b.string()).optional()}),xe=b.object({query:b.string()}),ve=b.object({position:q.optional(),limit:b.number().max(100).optional(),extendedPostalCodesFor:b.array(b.string()).optional(),mapcodes:b.array(b.string()).optional(),view:b.enum(a).optional(),geographyTypes:b.array(b.string()).optional()}),we=xe.extend(ve.shape),Ae=A.extend(we.shape).extend(Ce.shape),Le=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",Me=(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 o>=n-a&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},Ee=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}${J}/geocode`)(e)}/${e.query}.json`),n=t.searchParams;G(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!S(e.limit)&&n.append("limit",String(e.limit)),!S(e.offset)&&n.append("ofs",String(e.offset)),Z(n,e.position),e.countries&&n.append("countrySet",Le(e.countries)),!S(e.radiusMeters)&&n.append("radius",String(e.radiusMeters));const r=e.boundingBox&&i(e.boundingBox);return r&&(n.append("topLeft",Le([r[3],r[0]])),n.append("btmRight",Le([r[1],r[2]]))),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",Le(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",Le(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",Le(e.geographyTypes)),t},We=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:a,addressRanges:i,entityType:s,id:p,...c}=e;return{type:"Feature",geometry:o(re(t)),...n&&{bbox:ne(n)},id:p,properties:{...T(c,"viewport"),...r&&{distance:r},...s&&{geographyType:s.split(",")},...a&&{entryPoints:a.map(e=>({...e,position:re(e.position)}))},...i&&{addressRanges:{...i,from:re(i.from),to:re(i.to)}}}}},je=e=>{const t=e.results.map(We),n=s(i(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}},ke={requestValidation:{schema:Ae},buildRequest:Ee,sendRequest:j,parseResponse:je},Fe={buildGeocodingRequest:Ee,parseGeocodingResponse:je,geocodingTemplate:ke},Ue=b.object({geometries:b.union([H,b.array(b.union([b.string(),B])).min(1).max(20)])}),Be=b.object({zoom:b.number().min(0).max(22).optional()}),He=Ue.extend(Be.shape),qe=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),De=e=>{const t=new URL((e=>e.customServiceBaseURL||`${e.commonBaseURL}${J}/additionalData.json`)(e)),n=t.searchParams;return n.append("apiVersion",String(e.apiVersion)),n.append("key",e.apiKey),((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:qe(t):qe(t.features),e.append("geometries",Le(n))})(n,e.geometries),Y(n,"geometriesZoom",e.zoom),t},Ke=e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??p(),bbox:i(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:i(t),features:t}},Oe={requestValidation:{schema:He},buildRequest:De,sendRequest:j,parseResponse:Ke},$e={buildGeometryDataRequest:De,parseGeometryDataResponse:Ke,geometryDataTemplate:Oe},Ne=b.object(r),Ve=b.object({indexes:b.array(b.string()).optional(),poiCategories:b.array(b.union([b.number(),b.keyof(Ne)])).optional(),poiBrands:b.array(b.string()).optional(),connectors:b.array(b.string()).optional(),fuelTypes:b.array(b.string()).optional(),openingHours:b.string().optional(),timeZone:b.string().optional(),relatedPois:b.string().optional(),minPowerKW:b.number().optional(),maxPowerKW:b.number().optional(),minFuzzyLevel:b.number().optional(),mixFuzzyLevel:b.number().optional()}),Ge=we.extend(Ve.shape),ze=b.object({geometries:b.array(b.union([H,U]))}),_e=Ge.extend(ze.shape),Ye=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:te(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:Me(e.coordinates[0],50).map(e=>te(e))}];case"MultiPolygon":return e.coordinates.length>50?(e=>{let t=/* @__PURE__ */new Map;return e.coordinates.forEach(e=>{const n=c(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=>Ye({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>Ye({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>Ye(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},Ze=e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}${J}/geometrySearch/${n.query}.json`}`);var n;return Q(t,e),{url:t,data:{geometryList:e.geometries.flatMap(Ye)}}},Je=e=>{const t=e.results.map(Se),n=s(i(t));return{type:"FeatureCollection",properties:{...Te(e.summary)},features:t,...n&&{bbox:n}}},Qe={requestValidation:{schema:_e},buildRequest:Ze,sendRequest:k,parseResponse:Je},Xe=async(e,t)=>M(e,{...Qe,...t},"GeometrySearch"),et={geometrySearch:Xe,buildGeometrySearchRequest:Ze,parseGeometrySearchResponse:Je,geometrySearchTemplate:Qe},tt=b.object({entityId:b.string()}),nt=b.object({mapcodes:b.array(b.string()).optional(),view:b.enum(a).optional(),openingHours:b.string().optional(),timeZone:b.string().optional(),relatedPois:b.string().optional()}),rt=tt.extend(nt.shape),ot=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}${J}/place.json`)(e)}`),n=t.searchParams;return G(n,e),Y(n,"entityId",e.entityId),_(n,"mapcodes",e.mapcodes),Y(n,"view",e.view),Y(n,"openingHours",e.openingHours),Y(n,"timeZone",e.timeZone),Y(n,"relatedPois",e.relatedPois),t},at=e=>e.results?.length?Se(e.results[0]):void 0,it={requestValidation:{schema:rt},buildRequest:ot,sendRequest:j,parseResponse:at},st={buildPlaceByIdRequest:ot,parsePlaceByIdResponse:at,placeByIdTemplate:it},pt=b.number().positive(),ct=b.number().min(0),ut=b.number().min(0).max(100),lt=pt.optional(),dt=ct.optional(),mt=b.number().min(0).max(1).optional(),gt=b.object({speedKMH:b.number(),consumptionUnitsPer100KM:b.number()}),ht={efficiency:b.object({acceleration:mt,deceleration:mt,uphill:mt,downhill:mt}).optional()},yt=b.array(gt).min(1).max(25),ft=b.object({...ht,speedsToConsumptionsLiters:yt,auxiliaryPowerInLitersPerHour:dt,fuelEnergyDensityInMJoulesPerLiter:b.number().min(1).optional()}),bt=b.object({...ht,speedsToConsumptionsKWH:yt,auxiliaryPowerInkW:dt,consumptionInKWHPerKMAltitudeGain:b.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:dt}),St=b.object({currentType:b.enum(l),plugTypes:b.array(b.enum(u)).min(1),efficiency:mt,baseLoadInkW:dt,maxPowerInkW:dt,maxVoltageInV:dt,maxCurrentInA:dt,voltageRange:b.object({minVoltageInV:dt,maxVoltageInV:b.number().optional()}).optional()}),Tt=b.object({stateOfChargeInkWh:ct,maxPowerInkW:pt}),Pt=b.object({maxChargeKWH:pt,batteryCurve:b.array(Tt).max(20).optional(),chargingConnectors:b.array(St).min(1).optional(),chargingTimeOffsetInSec:dt}),Rt=b.object({consumption:ft}),It=b.object({consumption:bt,charging:Pt.optional()}),Ct=b.object({lengthMeters:lt,widthMeters:lt,heightMeters:lt,weightKG:lt,axleWeightKG:lt}).optional(),xt=b.object({variantId:b.string()}),vt=b.object({dimensions:Ct,engine:b.union([Rt,It]).optional()}),wt=b.union([xt,vt]).optional(),At=b.object({heading:b.number().min(0).max(360).optional()}),Lt=At.extend({currentFuelInLiters:ct}),Mt=At.extend({currentChargePCT:ut}),Et=At.extend({currentChargeInkWh:ct}),Wt=b.union([Mt,Et]),jt=b.object({minChargeAtDestinationPCT:ut,minChargeAtChargingStopsPCT:b.number().min(0).max(50)}),kt=b.object({minChargeAtDestinationInkWh:ct,minChargeAtChargingStopsInkWh:ct}),Ft=b.union([jt,kt]),Ut=b.object({chargingPreferences:Ft.optional()}),Bt={model:wt,restrictions:b.object({loadTypes:b.array(b.enum(["USHazmatClass1","USHazmatClass2","USHazmatClass3","USHazmatClass4","USHazmatClass5","USHazmatClass6","USHazmatClass7","USHazmatClass8","USHazmatClass9","otherHazmatExplosive","otherHazmatGeneral","otherHazmatHarmfulToWater"])).optional(),maxSpeedKMH:b.number().min(0).max(250).optional(),adrCode:b.enum(["B","C","D","E"]).optional(),commercial:b.boolean().optional()}).optional()},Ht=b.object({...Bt,engineType:b.undefined(),state:At.optional(),preferences:b.object({}).optional()}),qt=b.object({...Bt,engineType:b.literal("combustion"),state:Lt.optional(),preferences:b.object({}).optional()}),Dt=b.object({...Bt,engineType:b.literal("electric"),state:Wt.optional(),preferences:Ut.optional()}),Kt=b.union([b.discriminatedUnion("engineType",[qt,Dt]),Ht]),Ot=b.object({costModel:b.object({avoid:b.array(b.enum(d)).optional(),traffic:b.enum(["live","historical"]).optional(),routeType:b.enum(["fast","short","efficient","thrilling"]).optional(),thrillingParams:b.object({hilliness:b.enum(["low","normal","high"]).optional(),windingness:b.enum(["low","normal","high"]).optional()}).optional()}).optional(),travelMode:b.string().optional(),vehicle:Kt.optional(),when:b.object({option:b.enum(["departAt","arriveBy"]),date:b.date()}).optional()}),$t=b.object({origin:q,budget:b.object({type:b.enum(["timeMinutes","remainingChargeCPT","spentChargePCT","spentFuelLiters","distanceKM"]),value:b.number().min(0)})}),Nt=b.object({maxFerryLengthMeters:b.number().min(0).optional()}),Vt=Ot.extend($t.extend(Nt.shape).shape),Gt=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),zt=(e,t,n)=>{((e,t)=>{t&&(!S(t.acceleration)&&e.append("accelerationEfficiency",String(t.acceleration)),!S(t.deceleration)&&e.append("decelerationEfficiency",String(t.deceleration)),!S(t.uphill)&&e.append("uphillEfficiency",String(t.uphill)),!S(t.downhill)&&e.append("downhillEfficiency",String(t.downhill)))})(e,n.consumption.efficiency),"electric"===t?(((e,t)=>{t.speedsToConsumptionsKWH&&e.append("constantSpeedConsumptionInkWhPerHundredkm",Gt(t.speedsToConsumptionsKWH)),!S(t.auxiliaryPowerInkW)&&e.append("auxiliaryPowerInkW",String(t.auxiliaryPowerInkW)),!S(t.consumptionInKWHPerKMAltitudeGain)&&e.append("consumptionInkWhPerkmAltitudeGain",String(t.consumptionInKWHPerKMAltitudeGain)),!S(t.recuperationInKWHPerKMAltitudeLoss)&&e.append("recuperationInkWhPerkmAltitudeLoss",String(t.recuperationInKWHPerKMAltitudeLoss))})(e,n.consumption),((e,t)=>{const n=t.charging;n?.maxChargeKWH&&e.append("maxChargeInkWh",String(n.maxChargeKWH))})(e,n)):((e,t)=>{const n=t.consumption;n.speedsToConsumptionsLiters&&e.append("constantSpeedConsumptionInLitersPerHundredkm",Gt(n.speedsToConsumptionsLiters)),!S(n.auxiliaryPowerInLitersPerHour)&&e.append("auxiliaryPowerInLitersPerHour",String(n.auxiliaryPowerInLitersPerHour)),!S(n.fuelEnergyDensityInMJoulesPerLiter)&&e.append("fuelEnergyDensityInMJoulesPerLiter",String(n.fuelEnergyDensityInMJoulesPerLiter))})(e,n)},_t=(e,t)=>{t.model&&("variantId"in t.model?e.append("vehicleModelId",t.model.variantId):(((e,t)=>{t&&(t.lengthMeters&&e.append("vehicleLength",String(t.lengthMeters)),t.heightMeters&&e.append("vehicleHeight",String(t.heightMeters)),t.widthMeters&&e.append("vehicleWidth",String(t.widthMeters)),t.weightKG&&e.append("vehicleWeight",String(t.weightKG)),t.axleWeightKG&&e.append("vehicleAxleWeight",String(t.axleWeightKG)))})(e,t.model.dimensions),t.model.engine&&zt(e,"engineType"in t?t.engineType:void 0,t.model.engine)))},Yt=(e,t)=>{t&&("electric"===t.engineType&&e.append("vehicleEngineType","electric"),_t(e,t),((e,t)=>{if(t.state&&(t.state.heading&&e.append("vehicleHeading",String(t.state.heading)),"engineType"in t))if("combustion"===t.engineType){const n=t.state;n.currentFuelInLiters&&e.append("currentFuelInLiters",String(n.currentFuelInLiters))}else if("electric"===t.engineType){const n=t.state,r=n,o=n;if(r.currentChargeInkWh)e.append("currentChargeInkWh",String(r.currentChargeInkWh));else if(o.currentChargePCT&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine,r=n.charging?.maxChargeKWH;r&&e.append("currentChargeInkWh",String(r*o.currentChargePCT/100))}}})(e,t),((e,t)=>{if(t.preferences&&"engineType"in t&&"electric"===t.engineType){const n=t.preferences;if(n.chargingPreferences){const r=n.chargingPreferences,o=r,a=r;if(o.minChargeAtChargingStopsInkWh||o.minChargeAtDestinationInkWh)e.append("minChargeAtDestinationInkWh",String(o.minChargeAtDestinationInkWh)),e.append("minChargeAtChargingStopsInkWh",String(o.minChargeAtChargingStopsInkWh));else if((a.minChargeAtChargingStopsPCT||a.minChargeAtDestinationPCT)&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine,r=n.charging?.maxChargeKWH;r&&(e.append("minChargeAtDestinationInkWh",String(r*a.minChargeAtDestinationPCT/100)),e.append("minChargeAtChargingStopsInkWh",String(r*a.minChargeAtChargingStopsPCT/100)))}}}})(e,t),((e,t)=>{const n=t.restrictions;n&&(z(e,"vehicleLoadType",n.loadTypes),n.adrCode&&e.append("vehicleAdrTunnelRestrictionCode",n.adrCode),n.commercial&&e.append("vehicleCommercial",String(n.commercial)),n.maxSpeedKMH&&e.append("vehicleMaxSpeed",String(n.maxSpeedKMH)))})(e,t))},Zt=(e,t)=>{const n=t.costModel;z(e,"avoid",n?.avoid),Y(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),Y(e,"routeType",n?.routeType),Y(e,"travelMode",t.travelMode),Yt(e,t.vehicle)},Jt=e=>{const t=new URL((e=>e.customServiceBaseURL||`${e.commonBaseURL}/routing/1/calculateReachableRange/${te(m(e.origin))}/json`)(e)),n=t.searchParams;return G(n,e),Zt(n,e),Y(n,"maxFerryLengthInMeters",e.maxFerryLengthMeters),t},Qt=(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:i(n),properties:t}},Xt={buildReachableRangeRequest:Jt,parseReachableRangeResponse:Qt,reachableRangeTemplate:{requestValidation:{schema:Vt},buildRequest:Jt,sendRequest:j,parseResponse:Qt}},en=e=>{const t=m(e.position),n=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}${J}/reverseGeocode`)(e)}/${t[1]},${t[0]}.json`),r=n.searchParams;return G(r,e),e.allowFreeformNewline&&r.append("allowFreeformNewline",String(e.allowFreeformNewline)),e.geographyType&&r.append("entityType",Le(e.geographyType)),!S(e.heading)&&r.append("heading",String(e.heading)),e.mapcodes&&r.append("mapcodes",Le(e.mapcodes)),e.number&&r.append("number",e.number),!S(e.radiusMeters)&&r.append("radius",String(e.radiusMeters)),e.returnSpeedLimit&&r.append("returnSpeedLimit",String(e.returnSpeedLimit)),e.returnRoadUse&&r.append("returnRoadUse",String(e.returnRoadUse)),e.roadUses&&r.append("roadUse",JSON.stringify(e.roadUses)),n},tn=(e,t)=>{const n=e.addresses[0],{boundingBox:r,sideOfStreet:a,offsetPosition:i,...s}=n?.address||{};return{type:"Feature",geometry:o(m(t.position)),...r&&{bbox:ne(r)},id:p(),...n&&{properties:{type:n?.entityType?"Geography":s.streetNumber?"Point Address":"Street",address:s,...n.dataSources&&{dataSources:n.dataSources},...n.mapcodes&&{mapcodes:n.mapcodes},...a&&{sideOfStreet:a},...i&&{offsetPosition:ee(i)},originalPosition:ee(n.position)}}}},nn=b.object({position:q}),rn=b.object({allowFreeformNewline:b.boolean().optional(),geographyType:b.array(b.string()).optional(),heading:b.number().min(-360).max(360).optional(),mapcodes:b.array(b.string()).optional(),number:b.string().optional(),radiusMeters:b.number().optional(),returnMatchType:b.boolean().optional(),returnRoadUse:b.boolean().optional(),returnSpeedLimit:b.boolean().optional(),roadUses:b.array(b.string()).optional(),view:b.enum(a).optional()}),on={requestValidation:{schema:nn.extend(rn.shape)},buildRequest:en,sendRequest:j,parseResponse:tn},an={buildRevGeoRequest:en,parseRevGeoResponse:tn,reverseGeocodingTemplate:on},sn=b.union([q,U]),pn=b.union([F,B]),cn=b.object({locations:b.array(b.union([sn,pn])).min(1)}),un=b.object({computeAdditionalTravelTimeFor:b.enum(["none","all"]).optional(),vehicleHeading:b.number().min(0).max(359.5).optional(),maxAlternatives:b.number().min(0).max(5).optional(),sectionTypes:b.array(b.enum(h)).optional()}),ln=Ot.extend(cn.extend(un.shape).shape),dn=e=>e.vehicle?.preferences?.chargingPreferences,mn=e=>Array.isArray(e)?e:e.geometry.coordinates,gn=(e,t,n)=>((e,t)=>e.map(e=>{const n=te(m(e,{useEntryPoint:t})),r=(e=>e.properties||null)(e)?.radiusMeters;return r?`circle(${n},${r})`:n}).join(":"))(t.includes("path")?((e,t,n)=>{let r;const o=e[0];r="path"===t[0]?mn(o)[0]:m(o,{useEntryPoint:n});const a=e[e.length-1];let i;if("path"===t[t.length-1]){const e=mn(a);i=e[e.length-1]}else i=m(a,{useEntryPoint:n});return[r,i]})(e,t,n):e,n),hn=e=>({latitude:e[1],longitude:e[0]}),yn=(e,t,n)=>{const r=[],o=[];return e.forEach((a,i)=>{"path"===t[i]?((e,t,n,r,o)=>{const a=r.length;for(const i of mn(e))r.push(hn(i));Array.isArray(e)||(e.properties.sections.leg.forEach((e,n)=>{(t>0||n>0)&&o.push({supportingPointIndex:a+e.startPointIndex,waypointSourceType:"USER_DEFINED"})}),t<n.length-1&&o.push({supportingPointIndex:a+e.geometry.coordinates.length-1,waypointSourceType:"USER_DEFINED"}))})(a,i,e,r,o):((e,t,n,r,o,a)=>{r.push(hn(m(e,{useEntryPoint:a}))),t>0&&t<n.length-1&&o.push({supportingPointIndex:r.length-1,waypointSourceType:"USER_DEFINED"})})(a,i,e,r,o,n)}),{supportingPoints:r,...o.length&&{pointWaypoints:o}}},fn=e=>{const t=e.locations.map(g),n=e.useEntryPoints??"main-when-available",r=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/routing/${dn(e)?"calculateLongDistanceEVRoute":"calculateRoute"}`)(e)}/${gn(e.locations,t,n)}/json`),o=r.searchParams;G(o,e),"language"in e||o.append("language","en-GB"),Zt(o,e),Y(o,"computeTravelTimeFor",e.computeAdditionalTravelTimeFor),((e,t)=>{if(t?.guidance){const n=t.guidance;e.append("instructionsType",n.type),e.append("guidanceVersion",String(n.version??2)),e.append("instructionPhonetics",n.phonetics??"IPA"),e.append("instructionRoadShieldReferences",n.roadShieldReferences??"all"),e.append("language",t.language??"en-US")}})(o,e),!S(e.maxAlternatives)&&o.append("maxAlternatives",String(e.maxAlternatives)),((e,t,n)=>{const r=(t??(n?h:y)).map(e=>"vehicleRestricted"===e?"travelMode":e);z(e,"sectionType",r)})(o,e.sectionTypes,!!e.guidance?.type);for(const i of e.extendedRouteRepresentations??["distance","travelTime"])o.append("extendedRouteRepresentation",i);const a=((e,t,n)=>{const r=t.includes("path"),o=!!dn(e);if(!r&&!o)return null;const a=e.vehicle?.model,i=a?.engine?.charging;return{...r&&yn(e.locations,t,n),...o&&i&&{chargingParameters:T(i,"maxChargeKWH")}}})(e,t,n);return a?{method:"POST",url:r,data:a}:{method:"GET",url:r}},bn=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},Sn=(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:{...T(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:bn(n.chargingCurrentType),chargingSpeed:ue(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:ue(e.chargingParkPowerInkW)}}}},Tn=(e,t)=>{const n=t?.vehicle?.model?.engine?.charging?.maxChargeKWH;return{lengthInMeters:e.lengthInMeters,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,trafficDelayInSeconds:e.trafficDelayInSeconds,trafficLengthInMeters:e.trafficLengthInMeters,travelTimeInSeconds:e.travelTimeInSeconds,departureTime:new Date(e.departureTime),arrivalTime:new Date(e.arrivalTime),deviationDistanceInMeters:e.deviationDistance,fuelConsumptionInLiters:e.fuelConsumptionInLiters,...e.deviationPoint&&{deviationPoint:[e.deviationPoint.longitude,e.deviationPoint.latitude]},totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInkWh,...n&&e.batteryConsumptionInkWh&&{batteryConsumptionInPCT:100*e.batteryConsumptionInkWh/n},remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:Sn(e.chargingInformationAtEndOfLeg,n)}}},Pn=(e,t)=>e.reduce((e,n,r)=>{const o=0===r?0:e[r-1]?.endPointIndex;let a;return S(o)||(a=0===o?n.points?.length>0?n.points.length-1:0:o+n.points?.length),e.push({...!S(o)&&{startPointIndex:o},...a&&{endPointIndex:a},summary:Tn(n.summary,t),id:p()}),e},[]),Rn=e=>({id:p(),startPointIndex:e.startPointIndex,endPointIndex:e.endPointIndex}),In=e=>({...Rn(e),index:e.importantRoadStretchIndex,streetName:e.streetName?.text,roadNumbers:e.roadNumbers?.map(e=>e.text)}),Cn=e=>({...Rn(e),countryCodeISO3:e.countryCode}),xn=e=>"other"===e.travelMode?Rn(e):null,vn=e=>{if(e.tec?.causes?.length)return e.tec.causes.map(e=>(e=>{switch(e){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"}})(e.mainCauseCode));switch(e.simpleCategory){case"JAM":return["jam"];case"ROAD_WORK":return["roadworks"];case"ROAD_CLOSURE":return["road-closed"];default:return["other"]}},wn=e=>({...Rn(e),delayInSeconds:e.delayInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKmh,categories:vn(e),magnitudeOfDelay:f[e.magnitudeOfDelay],tec:e.tec}),An=e=>({...Rn(e),lanes:e.lanes,laneSeparators:e.laneSeparators,properties:e.properties}),Ln=e=>({...Rn(e),maxSpeedLimitInKmh:e.maxSpeedLimitInKmh}),Mn=e=>({...Rn(e),roadShieldReferences:e.roadShieldReferences}),En=(e,t)=>(t[e]||(t[e]=[]),t[e]),Wn=e=>{switch(e.sectionType){case"CAR_TRAIN":return{sectionType:"carTrain",mappingFunction:Rn};case"COUNTRY":return{sectionType:"country",mappingFunction:Cn};case"FERRY":return{sectionType:"ferry",mappingFunction:Rn};case"MOTORWAY":return{sectionType:"motorway",mappingFunction:Rn};case"PEDESTRIAN":return{sectionType:"pedestrian",mappingFunction:Rn};case"TOLL_VIGNETTE":return{sectionType:"tollVignette",mappingFunction:Cn};case"TOLL":return{sectionType:"toll",mappingFunction:Rn};case"TRAFFIC":return{sectionType:"traffic",mappingFunction:wn};case"TRAVEL_MODE":return{sectionType:"vehicleRestricted",mappingFunction:xn};case"TUNNEL":return{sectionType:"tunnel",mappingFunction:Rn};case"UNPAVED":return{sectionType:"unpaved",mappingFunction:Rn};case"URBAN":return{sectionType:"urban",mappingFunction:Rn};case"CARPOOL":return{sectionType:"carpool",mappingFunction:Rn};case"LOW_EMISSION_ZONE":return{sectionType:"lowEmissionZone",mappingFunction:Rn};case"LANES":return{sectionType:"lanes",mappingFunction:An};case"SPEED_LIMIT":return{sectionType:"speedLimit",mappingFunction:Ln};case"ROAD_SHIELDS":return{sectionType:"roadShields",mappingFunction:Mn};case"IMPORTANT_ROAD_STRETCH":return{sectionType:"importantRoadStretch",mappingFunction:In}}},jn=(e,t)=>{const n={leg:Pn(e.legs,t)};return((e,t)=>{if(Array.isArray(e))for(const n of e){const e=Wn(n),r=e?.mappingFunction(n);r&&En(e.sectionType,t).push(r)}})(e.sections,n),n},kn=1e-4,Fn=(e,t)=>Math.abs(e[0]-t[0])<kn&&Math.abs(e[1]-t[1])<kn,Un=(e,t)=>{const n=[];let r=0;for(const o of e.instructions){const e=[o.maneuverPoint.longitude,o.maneuverPoint.latitude];for(let n=r;n<t.length;n++){if(Fn(t[n],e)){r=n;break}if(n===t.length-1)break}n.push({...o,maneuverPoint:e,pathPointIndex:r,routePath:o.routePath.map(e=>({...e,point:[e.point.longitude,e.point.latitude]}))})}return{instructions:n}},Bn=(e,t)=>{const n=e.routes.map((e,n)=>((e,t,n)=>{const r={type:"LineString",coordinates:e.legs.flatMap(e=>e.points?.map(e=>[e.longitude,e.latitude]))};return{type:"Feature",geometry:r,id:p(),bbox:i(r),properties:{index:t,summary:Tn(e.summary,n),sections:jn(e,n),...e.guidance&&{guidance:Un(e.guidance,r.coordinates)},...e.progress&&{progress:e.progress}}}})(e,n,t)),r=i(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},Hn={requestValidation:{schema:ln,refinements:[{check:e=>!!e.locations.map(g).includes("path")||e.locations.length>=2,message:"When passing waypoints only: at least 2 must be defined. If passing also paths, at least one path must be defined"}]},buildRequest:fn,sendRequest:async(e,t)=>{const n=e.method;if("GET"===n)return j(e.url,t);if("POST"===n)return k(e,t);throw new Error(`Unsupported HTTP method received: ${n}`)},parseResponse:Bn,parseResponseError:(e,t)=>{const{data:n,message:r,status:o}=e;return new C(n?.error?.description??n?.detailedError?.message??r,t,o)},getAPIVersion:()=>2},qn={reverseGeocode:an,geocode:Fe,geometryData:$e,geometrySearch:et,calculateRoute:{buildCalculateRouteRequest:fn,parseCalculateRouteResponse:Bn,calculateRouteTemplate:Hn},reachableRange:Xt,evChargingStationsAvailability:Ie,placeByID:st,autocompleteSearch:se},Dn=async(e,t)=>M(e,{...Re,...t},"EVChargingStationsAvailability"),Kn=async e=>{const t=e.properties.dataSources?.chargingAvailability?.id;if(t)try{const n=await Dn({id:t}),r=e.properties.poi;return n?{...e,properties:{...e.properties,...r&&{poi:{...r,openingHours:n.openingHours}},chargingPark:{...e.properties.chargingPark,availability:n}}}:void 0}catch(n){return void console.error(n)}};async function On(e,t){const n=[];for(const r of e.features){const e=await Kn(r);e?n.push(e):t?.excludeIfAvailabilityUnknown||n.push(r)}return{...e,features:n,bbox:i(n)}}const $n=e=>Boolean(e&&"availability"in e&&e.availability),Nn=async(e,t)=>M(e,{...ke,...t},"Geocode"),Vn=async e=>(await Nn({query:e,limit:1})).features[0];async function Gn(e,t){const n=await M(e,{...Oe,...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)}const zn=async(e,t)=>M(e,{...it,...t},"PlaceById"),_n=async(e,t)=>M(e,{...on,...t},"ReverseGeocode"),Yn=async(e,t)=>M(e,{...Hn,...t},"Routing"),Zn=b.object({minFuzzyLevel:b.number().min(1).max(4).optional(),maxFuzzyLevel:b.number().min(1).max(4).optional()}),Jn=Ge.extend(Ce.extend(Zn.shape).shape),Qn=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:re(e.details)}};break;case"NEARBY":t={...e,details:{position:re({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},Xn={requestValidation:{schema:Jn},buildRequest:e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}${J}/search/${n.query}.json`}`);var n;Q(t,e);const r=t.searchParams;Y(r,"typeahead",e.typeahead),Y(r,"ofs",e.offset),_(r,"countrySet",e.countries),Y(r,"radius",e.radiusMeters);const o=e.boundingBox&&i(e.boundingBox);return o&&(r.append("topLeft",Le([o[3],o[0]])),r.append("btmRight",Le([o[1],o[2]]))),Y(r,"minFuzzyLevel",e.minFuzzyLevel),Y(r,"maxFuzzyLevel",e.maxFuzzyLevel),t},sendRequest:j,parseResponse:e=>{const t=e.results.map(Se),n=s(i(t));return{type:"FeatureCollection",properties:{...Te(e.summary),queryIntent:e.summary.queryIntent.map(Qn)},features:t,...n&&{bbox:n}}}},er=async(e,t)=>"geometries"in e?Xe(e,t):(async(e,t)=>M(e,{...Xn,...t},"FuzzySearch"))(e,t),tr=async e=>(await er({query:e,limit:1})).features[0];export{I as APIErrorCode,R as SDKError,C as SDKServiceError,ie as autocompleteSearch,v as buildResponseError,w as buildValidationError,Yn as calculateRoute,qn as customizeService,Dn as evChargingStationsAvailability,Nn as geocode,Vn as geocodeOne,Gn as geometryData,Kn as getPlaceWithEVAvailability,On as getPlacesWithEVAvailability,$n as hasChargingAvailability,x as parseDefaultResponseError,zn as placeById,_n as reverseGeocode,er as search,tr as searchOne};
|
|
1
|
+
import{mergeFromGlobal as e,generateTomTomHeaders as t,getPosition as n,poiCategoriesToID as r,toPointGeometry as i,views as o,bboxFromGeoJSON as a,bboxOnlyIfWithArea as s,generateId as c,bboxFromCoordsArray as p,plugTypes as u,currentTypes as d,avoidableTypes as l,getPositionStrict as m,getRoutePlanningLocationType as g,inputSectionTypesWithGuidance as h,inputSectionTypes as y,indexedMagnitudes as b}from"@tomtom-org/maps-sdk/core";import{z as f}from"zod";import{isNil as S,omit as v}from"lodash-es";var x=/* @__PURE__ */(e=>(e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e))(x||{});class P extends Error{constructor(e,t,n){super(e),this.service=t,this.issues=n,Error.captureStackTrace&&Error.captureStackTrace(this,P)}}const T={[x.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[x.FORBIDDEN]:"Request failed with status code 403"};class C extends P{constructor(e,t,n){super(e,t),this.status=n,this.status&&T[this.status]&&(this.message=T[this.status])}}const R=(e,t)=>{const{data:n,message:r,status:i}=e;return new C(n?.error||n?.errorText||r,t,i)},I=(e,t,n)=>{if(e.status){const r=e;return n?n(r,t):R(r,t)}return new P(e.message,t)},w=(e,t)=>new P(e.message,t,e.issues),L=f.object({apiKey:f.string().optional().describe("TomTom API key for authentication"),commonBaseURL:f.string().optional().describe("Common base URL for all services"),customServiceBaseURL:f.string().optional().describe("Custom base URL for specific service"),language:f.string().optional().describe('Language code for response text (e.g., "en-US", "nl-NL")')});class A extends Error{constructor(e){super(e.issues.map(e=>`${e.path.length>0?`${e.path.join(".")}: `:""}${e.message}`).join("; ")),this.issues=e.issues}}const M=async(n,r,i)=>{const o=r.getAPIVersion?.(n),a=e({...n,...o&&{apiVersion:o}});if(void 0===n.validateRequest||n.validateRequest)try{((e,t)=>{const n=(t?.schema?L.extend(t.schema.shape):L).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 A(n.error)})(a,r.requestValidation)}catch(p){return Promise.reject(w(p,i))}const s=r.buildRequest(a),c=t(a);n.onAPIRequest?.(s);try{const e=await r.sendRequest(s,c);return n.onAPIResponse?.(s,e),r.parseResponse(await e.data,a)}catch(p){return n.onAPIResponse?.(s,p),Promise.reject(I(p,i,r.parseResponseError))}};class k extends Error{constructor(e,t,n){super(t??`HTTP Error ${e}`),this.name="FetchError",this.status=e,this.data=n,Error.captureStackTrace&&Error.captureStackTrace(this,k)}}const E=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)},F=async(e,t)=>E(await fetch(e,{headers:t})),W=async(e,t)=>E(await fetch(e.url,{method:"POST",body:JSON.stringify(e.data),headers:{...t,"Content-Type":"application/json"}})),j=f.array(f.array(f.number())).describe("Array of coordinate arrays representing a line string"),q=f.object({type:f.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]).describe("GeoJSON geometry type"),coordinates:f.union([f.array(f.number()),j,f.array(f.array(f.array(f.number()))),f.array(f.array(f.array(f.array(f.number()))))]).describe("Coordinate array(s) for the geometry"),radius:f.optional(f.number()).describe("Radius for Circle geometries"),radiusMeters:f.optional(f.number()).describe("Radius in meters for Circle geometries"),bbox:f.optional(f.array(f.number())).describe("Bounding box [minLng, minLat, maxLng, maxLat]")}).check(f.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),U=f.object({type:f.literal("Feature").describe("GeoJSON type identifier"),geometry:q.describe("GeoJSON geometry object"),id:f.optional(f.union([f.string(),f.number()])).describe("Optional feature identifier"),properties:f.any().describe("Feature properties"),bbox:f.optional(f.array(f.number())).describe("Bounding box [minLng, minLat, maxLng, maxLat]")}),O=f.object({type:f.literal("FeatureCollection").describe("GeoJSON type identifier"),features:f.array(U).describe("Array of GeoJSON features"),id:f.optional(f.union([f.string(),f.number()])).describe("Optional collection identifier"),properties:f.any().describe("Collection properties"),bbox:f.optional(f.array(f.number())).describe("Bounding box [minLng, minLat, maxLng, maxLat]")}),B=f.union([f.tuple([f.number().min(-180).max(180),f.number().min(-90).max(90)]),f.tuple([f.number().min(-180).max(180),f.number().min(-90).max(90),f.number()]),f.object({type:f.literal("Point"),coordinates:f.array(f.number())}),U]).describe("Geographic position as [longitude, latitude] tuple, Point geometry, or Feature"),D=f.union([f.array(f.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),f.array(f.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]).describe("GeoJSON bounding box array [minLng, minLat, maxLng, maxLat] or [minLng, minLat, minAlt, maxLng, maxLat, maxAlt]"),H=f.union([q,U,O]).describe("Any GeoJSON object (Geometry, Feature, or FeatureCollection)"),K=f.union([D,H,f.array(H)]).describe("Bounding box as array, GeoJSON object, or array of GeoJSON objects"),N=f.object({query:f.string().describe("Partial search query for autocomplete suggestions")}),G=f.object({position:B.optional().describe("Geographic position [longitude, latitude] to bias search results"),limit:f.number().max(100).optional().describe("Maximum number of autocomplete suggestions to return (1-100)"),radiusMeters:f.number().optional().describe("Search radius in meters around the specified position"),countries:f.array(f.string()).optional().describe("Country codes to restrict search results (ISO 3166-1 alpha-2)"),resultType:f.array(f.string()).optional().describe("Types of results to include in suggestions")}),V=N.extend(G.shape),z=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),e.append("key",t.apiKey),t.language&&e.append("language",t.language)},$=(e,t,n)=>{for(const r of n||[])e.append(t,r)},_=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},J=(e,t,n)=>{!S(n)&&e.append(t,String(n))},Y=(e,t)=>{const r=n(t);r&&(e.append("lat",String(r[1])),e.append("lon",String(r[0])))},Z="/maps/orbis/places",Q=(e,t)=>{const n=e.searchParams;z(n,t),J(n,"limit",t.limit),Y(n,t.position),_(n,"fuelSet",t.fuelTypes),_(n,"idxSet",t.indexes),_(n,"brandSet",t.poiBrands),t.poiCategories&&_(n,"categorySet",t.poiCategories.map(e=>"number"!=typeof e?r[e]:e)),_(n,"connectorSet",t.connectors),_(n,"mapcodes",t.mapcodes),_(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),J(n,"minPowerKW",t.minPowerKW),J(n,"maxPowerKW",t.maxPowerKW),J(n,"view",t.view),J(n,"openingHours",t.openingHours),J(n,"timeZone",t.timeZone),J(n,"relatedPois",t.relatedPois),_(n,"entityTypeSet",t.geographyTypes)},X=e=>{const t=new URL(`${n=e,n.customServiceBaseURL||`${n.commonBaseURL}${Z}/autocomplete/${n.query}.json`}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",z(r,e),J(r,"limit",e.limit),Y(r,e.position),_(r,"countrySet",e.countries),J(r,"radius",e.radiusMeters),_(r,"resultSet",e.resultType),t},ee=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},te=e=>`${e[1]},${e[0]}`,ne=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=ee(e.southWest),n=ee(e.northEast)),[t[0],t[1],n[0],n[1]]},re=e=>[e.lon,e.lat],ie=e=>{const{position:t,...n}=e.context.geoBias||{};return{...e,context:{...e.context,geoBias:{...t&&{position:re(t)},radiusMeters:n.radius}}}},oe={requestValidation:{schema:V},buildRequest:X,sendRequest:F,parseResponse:ie},ae=async(e,t)=>M(e,{...oe,...t},"Autocomplete"),se={autocompleteSearch:ae,buildAutocompleteSearchRequest:X,parseAutocompleteSearchResponse:ie,autocompleteSearchTemplate:oe},ce=L.extend({id:f.string().describe("Unique identifier of the EV charging station")}),pe=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}${Z}/ev/id`)(e)),n=t.searchParams;return z(n,e),n.append("id",e.id),t},ue=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",de=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},le=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,me=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>le(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}:{}})}},ge=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>le(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},he=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)me(e.connectors,e.status,t);return t},ye=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,fe=e=>{const t=e.timeRanges.map(e=>({start:ye(e.startTime),end:ye(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:be(t)}},Se=e=>{const{position:t,entryPoints:n,poi:r,id:o,dist:a,boundingBox:s,chargingPark:c,...p}=e,u=c?.connectors?.map(e=>({...v(e,"connectorType"),type:e.connectorType,chargingSpeed:ue(e.ratedPowerKW)}));return{type:"Feature",geometry:i(re(t)),...s&&{bbox:ne(s)},id:o,properties:{...v(p,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:re(e.position)}))},...u?.length&&{chargingPark:{...c,connectors:ge(u)}},...r&&{poi:{...v(r,"categorySet","openingHours"),brands:r?.brands?.map(e=>e.name)??[],categoryIds:r?.categorySet?.map(e=>e.id)??[],...r?.openingHours&&{openingHours:fe(r?.openingHours)}}}}}},ve=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:re(t)},...n}},xe=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:ue(e.ratedPowerKW)}))}))}))),chargingPointAvailability:de(t.chargingStations),connectorAvailabilities:he(t.chargingStations),...t.openingHours&&{openingHours:fe(t.openingHours)}}:void 0;var n},Pe={requestValidation:{schema:ce},buildRequest:pe,sendRequest:F,parseResponse:xe,parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new C(n,t,e.status)}},Te={buildEVChargingStationsAvailabilityRequest:pe,parseEVChargingStationsAvailabilityResponse:xe,evChargingStationsAvailabilityTemplate:Pe},Ce=f.object({typeahead:f.boolean().optional().describe("Enable predictive/autocomplete mode for partial input queries"),offset:f.number().max(1900).optional().describe("Starting position within result set for pagination (zero-based index)"),radiusMeters:f.number().optional().describe("Search radius in meters around the specified position"),boundingBox:K.optional().describe("Bounding box to constrain search results to a rectangular area"),countries:f.array(f.string()).optional().describe("Country codes to restrict search results (ISO 3166-1 alpha-2)")}),Re=f.object({query:f.string().describe("Search query for places, addresses, or locations")}),Ie=f.object({position:B.optional().describe("Geographic position [longitude, latitude] to bias search results"),limit:f.number().max(100).optional().describe("Maximum number of results to return (1-100)"),extendedPostalCodesFor:f.array(f.string()).optional().describe("Indexes for which to include extended postal codes in results"),mapcodes:f.array(f.string()).optional().describe("Request mapcode representations for locations (Local, International, Alternative)"),view:f.enum(o).optional().describe("Geopolitical view for disputed territories"),geographyTypes:f.array(f.string()).optional().describe("Filter results to specific geography types (Country, Municipality, etc.)")}),we=Re.extend(Ie.shape),Le=L.extend(we.shape).extend(Ce.shape),Ae=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",Me=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let i;const o=Math.ceil(n/t);for(i=0;i<n;i+=o)r.push(e[i]);return i>=n-o&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},ke=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}${Z}/geocode`)(e)}/${e.query}.json`),n=t.searchParams;z(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!S(e.limit)&&n.append("limit",String(e.limit)),!S(e.offset)&&n.append("ofs",String(e.offset)),Y(n,e.position),e.countries&&n.append("countrySet",Ae(e.countries)),!S(e.radiusMeters)&&n.append("radius",String(e.radiusMeters));const r=e.boundingBox&&a(e.boundingBox);return r&&(n.append("topLeft",Ae([r[3],r[0]])),n.append("btmRight",Ae([r[1],r[2]]))),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",Ae(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",Ae(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",Ae(e.geographyTypes)),t},Ee=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:s,id:c,...p}=e;return{type:"Feature",geometry:i(re(t)),...n&&{bbox:ne(n)},id:c,properties:{...v(p,"viewport"),...r&&{distance:r},...s&&{geographyType:s.split(",")},...o&&{entryPoints:o.map(e=>({...e,position:re(e.position)}))},...a&&{addressRanges:{...a,from:re(a.from),to:re(a.to)}}}}},Fe=e=>{const t=e.results.map(Ee),n=s(a(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}},We={requestValidation:{schema:Le},buildRequest:ke,sendRequest:F,parseResponse:Fe},je={buildGeocodingRequest:ke,parseGeocodingResponse:Fe,geocodingTemplate:We},qe=f.object({geometries:f.union([O,f.array(f.union([f.string(),U])).min(1).max(20)]).describe("GeoJSON FeatureCollection or array of geometry IDs/Features (max 20)")}),Ue=f.object({zoom:f.number().min(0).max(22).optional().describe("Zoom level for geometry data simplification (0-22)")}),Oe=qe.extend(Ue.shape),Be=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),De=e=>{const t=new URL((e=>e.customServiceBaseURL||`${e.commonBaseURL}${Z}/additionalData.json`)(e)),n=t.searchParams;return n.append("apiVersion",String(e.apiVersion)),n.append("key",e.apiKey),((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:Be(t):Be(t.features),e.append("geometries",Ae(n))})(n,e.geometries),J(n,"geometriesZoom",e.zoom),t},He=e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??c(),bbox:a(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:a(t),features:t}},Ke={requestValidation:{schema:Oe},buildRequest:De,sendRequest:F,parseResponse:He},Ne={buildGeometryDataRequest:De,parseGeometryDataResponse:He,geometryDataTemplate:Ke},Ge=f.object(r),Ve=f.object({indexes:f.array(f.string()).optional().describe("Search indexes to query (Geo, PAD, Addr, Str, XStr, POI)"),poiCategories:f.array(f.union([f.number(),f.keyof(Ge)])).optional().describe("Filter results to specific POI categories"),poiBrands:f.array(f.string()).optional().describe("Filter results to specific POI brands"),connectors:f.array(f.string()).optional().describe("Filter EV charging stations by connector types"),fuelTypes:f.array(f.string()).optional().describe("Filter fuel stations by available fuel types"),openingHours:f.string().optional().describe("Request opening hours information for POIs"),timeZone:f.string().optional().describe("Request timezone information for POI locations (iana)"),relatedPois:f.string().optional().describe("Related POI inclusion mode (off, child, parent, all)"),minPowerKW:f.number().optional().describe("Minimum charging power in kilowatts for EV charging stations"),maxPowerKW:f.number().optional().describe("Maximum charging power in kilowatts for EV charging stations"),minFuzzyLevel:f.number().optional().describe("Minimum fuzzy matching level (1-4)"),mixFuzzyLevel:f.number().optional().describe("Maximum fuzzy matching level (1-4)")}),ze=we.extend(Ve.shape),$e=f.object({geometries:f.array(f.union([O,q])).describe("Array of GeoJSON geometries or FeatureCollections to search within")}),_e=ze.extend($e.shape),Je=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:te(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:Me(e.coordinates[0],50).map(e=>te(e))}];case"MultiPolygon":return e.coordinates.length>50?(e=>{let t=/* @__PURE__ */new Map;return e.coordinates.forEach(e=>{const n=p(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=>Je({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>Je({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>Je(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},Ye=e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}${Z}/geometrySearch/${n.query}.json`}`);var n;return Q(t,e),{url:t,data:{geometryList:e.geometries.flatMap(Je)}}},Ze=e=>{const t=e.results.map(Se),n=s(a(t));return{type:"FeatureCollection",properties:{...ve(e.summary)},features:t,...n&&{bbox:n}}},Qe={requestValidation:{schema:_e},buildRequest:Ye,sendRequest:W,parseResponse:Ze},Xe=async(e,t)=>M(e,{...Qe,...t},"GeometrySearch"),et={geometrySearch:Xe,buildGeometrySearchRequest:Ye,parseGeometrySearchResponse:Ze,geometrySearchTemplate:Qe},tt=f.object({entityId:f.string().describe("Unique identifier of the place/entity to retrieve")}),nt=f.object({mapcodes:f.array(f.string()).optional().describe("Request mapcode representations for location"),view:f.enum(o).optional().describe("Geopolitical view for disputed territories"),openingHours:f.string().optional().describe("Request opening hours information for the place"),timeZone:f.string().optional().describe("Request timezone information for the place location"),relatedPois:f.string().optional().describe("Related POI inclusion mode (off, child, parent, all)")}),rt=tt.extend(nt.shape),it=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}${Z}/place.json`)(e)}`),n=t.searchParams;return z(n,e),J(n,"entityId",e.entityId),_(n,"mapcodes",e.mapcodes),J(n,"view",e.view),J(n,"openingHours",e.openingHours),J(n,"timeZone",e.timeZone),J(n,"relatedPois",e.relatedPois),t},ot=e=>e.results?.length?Se(e.results[0]):void 0,at={requestValidation:{schema:rt},buildRequest:it,sendRequest:F,parseResponse:ot},st={buildPlaceByIdRequest:it,parsePlaceByIdResponse:ot,placeByIdTemplate:at},ct=f.number().positive(),pt=f.number().min(0),ut=f.number().min(0).max(100),dt=ct.optional(),lt=pt.optional(),mt=f.number().min(0).max(1).optional(),gt=f.object({speedKMH:f.number().describe("Speed in kilometers per hour"),consumptionUnitsPer100KM:f.number().describe("Consumption rate per 100 kilometers")}),ht={efficiency:f.object({acceleration:mt.describe("Acceleration efficiency factor (0-1)"),deceleration:mt.describe("Deceleration efficiency factor (0-1)"),uphill:mt.describe("Uphill efficiency factor (0-1)"),downhill:mt.describe("Downhill efficiency factor (0-1)")}).optional()},yt=f.array(gt).min(1).max(25),bt=f.object({...ht,speedsToConsumptionsLiters:yt.describe("Array of speed-to-fuel-consumption mappings in liters per 100km"),auxiliaryPowerInLitersPerHour:lt.describe("Auxiliary power consumption in liters per hour"),fuelEnergyDensityInMJoulesPerLiter:f.number().min(1).optional().describe("Fuel energy density in megajoules per liter")}),ft=f.object({...ht,speedsToConsumptionsKWH:yt.describe("Array of speed-to-energy-consumption mappings in kWh per 100km"),auxiliaryPowerInkW:lt.describe("Auxiliary power consumption in kilowatts"),consumptionInKWHPerKMAltitudeGain:f.number().max(500).optional().describe("Energy consumption per kilometer of altitude gain in kWh"),recuperationInKWHPerKMAltitudeLoss:lt.describe("Energy recuperation per kilometer of altitude loss in kWh")}),St=f.object({currentType:f.enum(d).describe("Type of electrical current (AC or DC)"),plugTypes:f.array(f.enum(u)).min(1).describe("Compatible plug/connector types"),efficiency:mt.describe("Charging efficiency factor (0-1)"),baseLoadInkW:lt.describe("Base load in kilowatts"),maxPowerInkW:lt.describe("Maximum charging power in kilowatts"),maxVoltageInV:lt.describe("Maximum voltage in volts"),maxCurrentInA:lt.describe("Maximum current in amperes"),voltageRange:f.object({minVoltageInV:lt.describe("Minimum voltage in volts"),maxVoltageInV:f.number().optional().describe("Maximum voltage in volts")}).optional().describe("Acceptable voltage range")}),vt=f.object({stateOfChargeInkWh:pt.describe("State of charge in kilowatt-hours"),maxPowerInkW:ct.describe("Maximum charging power at this state of charge in kilowatts")}),xt=f.object({maxChargeKWH:ct.describe("Maximum battery capacity in kilowatt-hours"),batteryCurve:f.array(vt).max(20).optional().describe("Battery charging curve with up to 20 data points"),chargingConnectors:f.array(St).min(1).optional().describe("Available charging connectors on the vehicle"),chargingTimeOffsetInSec:lt.describe("Time offset for charging start in seconds")}),Pt=f.object({consumption:bt.describe("Fuel consumption model for combustion engine")}),Tt=f.object({consumption:ft.describe("Energy consumption model for electric engine"),charging:xt.optional().describe("Battery and charging specifications")}),Ct=f.object({lengthMeters:dt.describe("Vehicle length in meters"),widthMeters:dt.describe("Vehicle width in meters"),heightMeters:dt.describe("Vehicle height in meters"),weightKG:dt.describe("Vehicle weight in kilograms"),axleWeightKG:dt.describe("Vehicle axle weight in kilograms")}).optional(),Rt=f.object({variantId:f.string().describe("Predefined vehicle variant identifier")}),It=f.object({dimensions:Ct.describe("Physical dimensions and weight of the vehicle"),engine:f.union([Pt,Tt]).optional().describe("Engine type and consumption characteristics")}),wt=f.union([Rt,It]).optional(),Lt=f.object({heading:f.number().min(0).max(360).optional().describe("Current vehicle heading in degrees (0-360)")}),At=Lt.extend({currentFuelInLiters:pt.describe("Current fuel level in liters")}),Mt=Lt.extend({currentChargePCT:ut.describe("Current battery charge as percentage (0-100)")}),kt=Lt.extend({currentChargeInkWh:pt.describe("Current battery charge in kilowatt-hours")}),Et=f.union([Mt,kt]),Ft=f.object({minChargeAtDestinationPCT:ut.describe("Minimum battery charge percentage required at destination (0-100)"),minChargeAtChargingStopsPCT:f.number().min(0).max(50).describe("Minimum battery charge percentage at charging stops (0-50)")}),Wt=f.object({minChargeAtDestinationInkWh:pt.describe("Minimum battery charge in kWh required at destination"),minChargeAtChargingStopsInkWh:pt.describe("Minimum battery charge in kWh at charging stops")}),jt=f.union([Ft,Wt]),qt=f.object({chargingPreferences:jt.optional().describe("Preferences for charging stops along the route")}),Ut={model:wt,restrictions:f.object({loadTypes:f.array(f.enum(["USHazmatClass1","USHazmatClass2","USHazmatClass3","USHazmatClass4","USHazmatClass5","USHazmatClass6","USHazmatClass7","USHazmatClass8","USHazmatClass9","otherHazmatExplosive","otherHazmatGeneral","otherHazmatHarmfulToWater"])).optional().describe("Types of hazardous or restricted loads being carried"),maxSpeedKMH:f.number().min(0).max(250).optional().describe("Maximum vehicle speed in kilometers per hour (0-250)"),adrCode:f.enum(["B","C","D","E"]).optional().describe("ADR tunnel restriction code for hazardous materials"),commercial:f.boolean().optional().describe("Whether the vehicle is used for commercial purposes")}).optional()},Ot=f.object({...Ut,engineType:f.undefined(),state:Lt.optional().describe("Current state of the vehicle"),preferences:f.object({}).optional().describe("Vehicle preferences")}),Bt=f.object({...Ut,engineType:f.literal("combustion").describe("Combustion engine type"),state:At.optional().describe("Current state of the combustion vehicle including fuel level"),preferences:f.object({}).optional().describe("Combustion vehicle preferences")}),Dt=f.object({...Ut,engineType:f.literal("electric").describe("Electric engine type"),state:Et.optional().describe("Current state of the electric vehicle including battery charge"),preferences:qt.optional().describe("Electric vehicle preferences including charging requirements")}),Ht=f.union([f.discriminatedUnion("engineType",[Bt,Dt]),Ot]),Kt=f.object({costModel:f.object({avoid:f.array(f.enum(l)).optional().describe("Road types and features to avoid when calculating route"),traffic:f.enum(["live","historical"]).optional().describe("Traffic consideration mode (live: real-time + historical, historical: typical patterns only)"),routeType:f.enum(["fast","short","efficient","thrilling"]).optional().describe("Route optimization strategy (fast, short, efficient, thrilling)"),thrillingParams:f.object({hilliness:f.enum(["low","normal","high"]).optional().describe("Level of hilliness for thrilling routes"),windingness:f.enum(["low","normal","high"]).optional().describe("Level of windingness for thrilling routes")}).optional().describe("Optional parameters for thrilling route type")}).optional().describe("Cost model criteria for route optimization"),travelMode:f.string().optional().describe("Travel mode (car, truck, pedestrian, bicycle)"),vehicle:Ht.optional().describe("Vehicle-specific parameters including dimensions, engine type, and consumption model"),when:f.object({option:f.enum(["departAt","arriveBy"]).describe("Whether to specify a departure or arrival time"),date:f.date().describe("The date and time to depart or arrive")}).optional().describe("Departure or arrival time specification for route planning")}),Nt=f.object({origin:B.describe("Starting position [longitude, latitude] for reachable range calculation"),budget:f.object({type:f.enum(["timeMinutes","remainingChargeCPT","spentChargePCT","spentFuelLiters","distanceKM"]).describe("Budget type (time, distance, or energy/fuel)"),value:f.number().min(0).describe("Budget value (depends on type: seconds, meters, liters, or kWh)")}).describe("Travel budget constraints for reachable range")}),Gt=f.object({maxFerryLengthMeters:f.number().min(0).optional().describe("Maximum ferry distance in meters to include in range")}),Vt=Kt.extend(Nt.extend(Gt.shape).shape),zt=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),$t=(e,t,n)=>{((e,t)=>{t&&(!S(t.acceleration)&&e.append("accelerationEfficiency",String(t.acceleration)),!S(t.deceleration)&&e.append("decelerationEfficiency",String(t.deceleration)),!S(t.uphill)&&e.append("uphillEfficiency",String(t.uphill)),!S(t.downhill)&&e.append("downhillEfficiency",String(t.downhill)))})(e,n.consumption.efficiency),"electric"===t?(((e,t)=>{t.speedsToConsumptionsKWH&&e.append("constantSpeedConsumptionInkWhPerHundredkm",zt(t.speedsToConsumptionsKWH)),!S(t.auxiliaryPowerInkW)&&e.append("auxiliaryPowerInkW",String(t.auxiliaryPowerInkW)),!S(t.consumptionInKWHPerKMAltitudeGain)&&e.append("consumptionInkWhPerkmAltitudeGain",String(t.consumptionInKWHPerKMAltitudeGain)),!S(t.recuperationInKWHPerKMAltitudeLoss)&&e.append("recuperationInkWhPerkmAltitudeLoss",String(t.recuperationInKWHPerKMAltitudeLoss))})(e,n.consumption),((e,t)=>{const n=t.charging;n?.maxChargeKWH&&e.append("maxChargeInkWh",String(n.maxChargeKWH))})(e,n)):((e,t)=>{const n=t.consumption;n.speedsToConsumptionsLiters&&e.append("constantSpeedConsumptionInLitersPerHundredkm",zt(n.speedsToConsumptionsLiters)),!S(n.auxiliaryPowerInLitersPerHour)&&e.append("auxiliaryPowerInLitersPerHour",String(n.auxiliaryPowerInLitersPerHour)),!S(n.fuelEnergyDensityInMJoulesPerLiter)&&e.append("fuelEnergyDensityInMJoulesPerLiter",String(n.fuelEnergyDensityInMJoulesPerLiter))})(e,n)},_t=(e,t)=>{t.model&&("variantId"in t.model?e.append("vehicleModelId",t.model.variantId):(((e,t)=>{t&&(t.lengthMeters&&e.append("vehicleLength",String(t.lengthMeters)),t.heightMeters&&e.append("vehicleHeight",String(t.heightMeters)),t.widthMeters&&e.append("vehicleWidth",String(t.widthMeters)),t.weightKG&&e.append("vehicleWeight",String(t.weightKG)),t.axleWeightKG&&e.append("vehicleAxleWeight",String(t.axleWeightKG)))})(e,t.model.dimensions),t.model.engine&&$t(e,"engineType"in t?t.engineType:void 0,t.model.engine)))},Jt=(e,t)=>{t&&("electric"===t.engineType&&e.append("vehicleEngineType","electric"),_t(e,t),((e,t)=>{if(t.state&&(t.state.heading&&e.append("vehicleHeading",String(t.state.heading)),"engineType"in t))if("combustion"===t.engineType){const n=t.state;n.currentFuelInLiters&&e.append("currentFuelInLiters",String(n.currentFuelInLiters))}else if("electric"===t.engineType){const n=t.state,r=n,i=n;if(r.currentChargeInkWh)e.append("currentChargeInkWh",String(r.currentChargeInkWh));else if(i.currentChargePCT&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine,r=n.charging?.maxChargeKWH;r&&e.append("currentChargeInkWh",String(r*i.currentChargePCT/100))}}})(e,t),((e,t)=>{if(t.preferences&&"engineType"in t&&"electric"===t.engineType){const n=t.preferences;if(n.chargingPreferences){const r=n.chargingPreferences,i=r,o=r;if(i.minChargeAtChargingStopsInkWh||i.minChargeAtDestinationInkWh)e.append("minChargeAtDestinationInkWh",String(i.minChargeAtDestinationInkWh)),e.append("minChargeAtChargingStopsInkWh",String(i.minChargeAtChargingStopsInkWh));else if((o.minChargeAtChargingStopsPCT||o.minChargeAtDestinationPCT)&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine,r=n.charging?.maxChargeKWH;r&&(e.append("minChargeAtDestinationInkWh",String(r*o.minChargeAtDestinationPCT/100)),e.append("minChargeAtChargingStopsInkWh",String(r*o.minChargeAtChargingStopsPCT/100)))}}}})(e,t),((e,t)=>{const n=t.restrictions;n&&($(e,"vehicleLoadType",n.loadTypes),n.adrCode&&e.append("vehicleAdrTunnelRestrictionCode",n.adrCode),n.commercial&&e.append("vehicleCommercial",String(n.commercial)),n.maxSpeedKMH&&e.append("vehicleMaxSpeed",String(n.maxSpeedKMH)))})(e,t))},Yt=(e,t)=>{const n=t.costModel;$(e,"avoid",n?.avoid),J(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),J(e,"routeType",n?.routeType),J(e,"travelMode",t.travelMode),Jt(e,t.vehicle)},Zt=e=>{const t=new URL((e=>e.customServiceBaseURL||`${e.commonBaseURL}/routing/1/calculateReachableRange/${te(m(e.origin))}/json`)(e)),n=t.searchParams;return z(n,e),Yt(n,e),J(n,"maxFerryLengthInMeters",e.maxFerryLengthMeters),t},Qt=(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:a(n),properties:t}},Xt={buildReachableRangeRequest:Zt,parseReachableRangeResponse:Qt,reachableRangeTemplate:{requestValidation:{schema:Vt},buildRequest:Zt,sendRequest:F,parseResponse:Qt}},en=e=>{const t=m(e.position),n=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}${Z}/reverseGeocode`)(e)}/${t[1]},${t[0]}.json`),r=n.searchParams;return z(r,e),e.allowFreeformNewline&&r.append("allowFreeformNewline",String(e.allowFreeformNewline)),e.geographyType&&r.append("entityType",Ae(e.geographyType)),!S(e.heading)&&r.append("heading",String(e.heading)),e.mapcodes&&r.append("mapcodes",Ae(e.mapcodes)),e.number&&r.append("number",e.number),!S(e.radiusMeters)&&r.append("radius",String(e.radiusMeters)),e.returnSpeedLimit&&r.append("returnSpeedLimit",String(e.returnSpeedLimit)),e.returnRoadUse&&r.append("returnRoadUse",String(e.returnRoadUse)),e.roadUses&&r.append("roadUse",JSON.stringify(e.roadUses)),n},tn=(e,t)=>{const n=e.addresses[0],{boundingBox:r,sideOfStreet:o,offsetPosition:a,...s}=n?.address||{};return{type:"Feature",geometry:i(m(t.position)),...r&&{bbox:ne(r)},id:c(),...n&&{properties:{type:n?.entityType?"Geography":s.streetNumber?"Point Address":"Street",address:s,...n.dataSources&&{dataSources:n.dataSources},...n.mapcodes&&{mapcodes:n.mapcodes},...o&&{sideOfStreet:o},...a&&{offsetPosition:ee(a)},originalPosition:ee(n.position)}}}},nn=f.object({position:B.describe("Geographic position [longitude, latitude] to reverse geocode")}),rn=f.object({allowFreeformNewline:f.boolean().optional().describe("Allow newline characters in freeform address"),geographyType:f.array(f.string()).optional().describe("Filter results to specific geography types"),heading:f.number().min(-360).max(360).optional().describe("Vehicle heading in degrees (-360 to 360) for directional results"),mapcodes:f.array(f.string()).optional().describe("Request mapcode representations for location"),number:f.string().optional().describe("Street number for more precise address results"),radiusMeters:f.number().optional().describe("Search radius in meters for reverse geocoding"),returnMatchType:f.boolean().optional().describe("Include match type information in response"),returnRoadUse:f.boolean().optional().describe("Include road use information in response"),returnSpeedLimit:f.boolean().optional().describe("Include speed limit information in response"),roadUses:f.array(f.string()).optional().describe("Filter results to specific road use types"),view:f.enum(o).optional().describe("Geopolitical view for disputed territories")}),on={requestValidation:{schema:nn.extend(rn.shape)},buildRequest:en,sendRequest:F,parseResponse:tn},an={buildRevGeoRequest:en,parseRevGeoResponse:tn,reverseGeocodingTemplate:on},sn=f.union([B,q]).describe("Waypoint as position or geometry"),cn=f.union([j,U]).describe("Path as line string coordinates or feature"),pn=f.object({locations:f.array(f.union([sn,cn])).min(1).describe("Array of route locations (waypoints or paths) - minimum 2 waypoints or 1 path required")}),un=f.object({computeAdditionalTravelTimeFor:f.enum(["none","all"]).optional().describe("Calculate additional travel time estimates for different traffic scenarios (none or all)"),vehicleHeading:f.number().min(0).max(359.5).optional().describe("Vehicle heading in degrees (0-359.5) at departure"),maxAlternatives:f.number().min(0).max(5).optional().describe("Maximum number of alternative routes to calculate (0-5)"),sectionTypes:f.array(f.enum(h)).optional().describe("Types of route sections to include in response (toll, ferry, traffic, etc.)")}),dn=Kt.extend(pn.extend(un.shape).shape),ln=e=>e.vehicle?.preferences?.chargingPreferences,mn=e=>Array.isArray(e)?e:e.geometry.coordinates,gn=(e,t,n)=>((e,t)=>e.map(e=>{const n=te(m(e,{useEntryPoint:t})),r=(e=>e.properties||null)(e)?.radiusMeters;return r?`circle(${n},${r})`:n}).join(":"))(t.includes("path")?((e,t,n)=>{let r;const i=e[0];r="path"===t[0]?mn(i)[0]:m(i,{useEntryPoint:n});const o=e[e.length-1];let a;if("path"===t[t.length-1]){const e=mn(o);a=e[e.length-1]}else a=m(o,{useEntryPoint:n});return[r,a]})(e,t,n):e,n),hn=e=>({latitude:e[1],longitude:e[0]}),yn=(e,t,n)=>{const r=[],i=[];return e.forEach((o,a)=>{"path"===t[a]?((e,t,n,r,i)=>{const o=r.length;for(const a of mn(e))r.push(hn(a));Array.isArray(e)||(e.properties.sections.leg.forEach((e,n)=>{(t>0||n>0)&&i.push({supportingPointIndex:o+e.startPointIndex,waypointSourceType:"USER_DEFINED"})}),t<n.length-1&&i.push({supportingPointIndex:o+e.geometry.coordinates.length-1,waypointSourceType:"USER_DEFINED"}))})(o,a,e,r,i):((e,t,n,r,i,o)=>{r.push(hn(m(e,{useEntryPoint:o}))),t>0&&t<n.length-1&&i.push({supportingPointIndex:r.length-1,waypointSourceType:"USER_DEFINED"})})(o,a,e,r,i,n)}),{supportingPoints:r,...i.length&&{pointWaypoints:i}}},bn=e=>{const t=e.locations.map(g),n=e.useEntryPoints??"main-when-available",r=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/routing/${ln(e)?"calculateLongDistanceEVRoute":"calculateRoute"}`)(e)}/${gn(e.locations,t,n)}/json`),i=r.searchParams;z(i,e),"language"in e||i.append("language","en-GB"),Yt(i,e),J(i,"computeTravelTimeFor",e.computeAdditionalTravelTimeFor),((e,t)=>{if(t?.guidance){const n=t.guidance;e.append("instructionsType",n.type),e.append("guidanceVersion",String(n.version??2)),e.append("instructionPhonetics",n.phonetics??"IPA"),e.append("instructionRoadShieldReferences",n.roadShieldReferences??"all"),e.append("language",t.language??"en-US")}})(i,e),!S(e.maxAlternatives)&&i.append("maxAlternatives",String(e.maxAlternatives)),((e,t,n)=>{const r=(t??(n?h:y)).map(e=>"vehicleRestricted"===e?"travelMode":e);$(e,"sectionType",r)})(i,e.sectionTypes,!!e.guidance?.type);for(const a of e.extendedRouteRepresentations??["distance","travelTime"])i.append("extendedRouteRepresentation",a);const o=((e,t,n)=>{const r=t.includes("path"),i=!!ln(e);if(!r&&!i)return null;const o=e.vehicle?.model,a=o?.engine?.charging;return{...r&&yn(e.locations,t,n),...i&&a&&{chargingParameters:v(a,"maxChargeKWH")}}})(e,t,n);return o?{method:"POST",url:r,data:o}:{method:"GET",url:r}},fn=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},Sn=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,i=[r.coordinate.longitude,r.coordinate.latitude],o=[r.street,r.houseNumber].filter(Boolean),a=o.length>0?o.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:i},properties:{...v(e,["chargingConnectionInfo","chargingParkLocation"]),type:"POI",address:{freeformAddress:a,...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:fn(n.chargingCurrentType),chargingSpeed:ue(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:ue(e.chargingParkPowerInkW)}}}},vn=(e,t)=>{const n=t?.vehicle?.model?.engine?.charging?.maxChargeKWH;return{lengthInMeters:e.lengthInMeters,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,trafficDelayInSeconds:e.trafficDelayInSeconds,trafficLengthInMeters:e.trafficLengthInMeters,travelTimeInSeconds:e.travelTimeInSeconds,departureTime:new Date(e.departureTime),arrivalTime:new Date(e.arrivalTime),deviationDistanceInMeters:e.deviationDistance,fuelConsumptionInLiters:e.fuelConsumptionInLiters,...e.deviationPoint&&{deviationPoint:[e.deviationPoint.longitude,e.deviationPoint.latitude]},totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInkWh,...n&&e.batteryConsumptionInkWh&&{batteryConsumptionInPCT:100*e.batteryConsumptionInkWh/n},remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:Sn(e.chargingInformationAtEndOfLeg,n)}}},xn=(e,t)=>e.reduce((e,n,r)=>{const i=0===r?0:e[r-1]?.endPointIndex;let o;return S(i)||(o=0===i?n.points?.length>0?n.points.length-1:0:i+n.points?.length),e.push({...!S(i)&&{startPointIndex:i},...o&&{endPointIndex:o},summary:vn(n.summary,t),id:c()}),e},[]),Pn=e=>({id:c(),startPointIndex:e.startPointIndex,endPointIndex:e.endPointIndex}),Tn=e=>({...Pn(e),index:e.importantRoadStretchIndex,streetName:e.streetName?.text,roadNumbers:e.roadNumbers?.map(e=>e.text)}),Cn=e=>({...Pn(e),countryCodeISO3:e.countryCode}),Rn=e=>"other"===e.travelMode?Pn(e):null,In=e=>{if(e.tec?.causes?.length)return e.tec.causes.map(e=>(e=>{switch(e){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"}})(e.mainCauseCode));switch(e.simpleCategory){case"JAM":return["jam"];case"ROAD_WORK":return["roadworks"];case"ROAD_CLOSURE":return["road-closed"];default:return["other"]}},wn=e=>({...Pn(e),delayInSeconds:e.delayInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKmh,categories:In(e),magnitudeOfDelay:b[e.magnitudeOfDelay],tec:e.tec}),Ln=e=>({...Pn(e),lanes:e.lanes,laneSeparators:e.laneSeparators,properties:e.properties}),An=e=>({...Pn(e),maxSpeedLimitInKmh:e.maxSpeedLimitInKmh}),Mn=e=>({...Pn(e),roadShieldReferences:e.roadShieldReferences}),kn=(e,t)=>(t[e]||(t[e]=[]),t[e]),En=e=>{switch(e.sectionType){case"CAR_TRAIN":return{sectionType:"carTrain",mappingFunction:Pn};case"COUNTRY":return{sectionType:"country",mappingFunction:Cn};case"FERRY":return{sectionType:"ferry",mappingFunction:Pn};case"MOTORWAY":return{sectionType:"motorway",mappingFunction:Pn};case"PEDESTRIAN":return{sectionType:"pedestrian",mappingFunction:Pn};case"TOLL_VIGNETTE":return{sectionType:"tollVignette",mappingFunction:Cn};case"TOLL":return{sectionType:"toll",mappingFunction:Pn};case"TRAFFIC":return{sectionType:"traffic",mappingFunction:wn};case"TRAVEL_MODE":return{sectionType:"vehicleRestricted",mappingFunction:Rn};case"TUNNEL":return{sectionType:"tunnel",mappingFunction:Pn};case"UNPAVED":return{sectionType:"unpaved",mappingFunction:Pn};case"URBAN":return{sectionType:"urban",mappingFunction:Pn};case"CARPOOL":return{sectionType:"carpool",mappingFunction:Pn};case"LOW_EMISSION_ZONE":return{sectionType:"lowEmissionZone",mappingFunction:Pn};case"LANES":return{sectionType:"lanes",mappingFunction:Ln};case"SPEED_LIMIT":return{sectionType:"speedLimit",mappingFunction:An};case"ROAD_SHIELDS":return{sectionType:"roadShields",mappingFunction:Mn};case"IMPORTANT_ROAD_STRETCH":return{sectionType:"importantRoadStretch",mappingFunction:Tn}}},Fn=(e,t)=>{const n={leg:xn(e.legs,t)};return((e,t)=>{if(Array.isArray(e))for(const n of e){const e=En(n),r=e?.mappingFunction(n);r&&kn(e.sectionType,t).push(r)}})(e.sections,n),n},Wn=1e-4,jn=(e,t)=>Math.abs(e[0]-t[0])<Wn&&Math.abs(e[1]-t[1])<Wn,qn=(e,t)=>{const n=[];let r=0;for(const i of e.instructions){const e=[i.maneuverPoint.longitude,i.maneuverPoint.latitude];for(let n=r;n<t.length;n++){if(jn(t[n],e)){r=n;break}if(n===t.length-1)break}n.push({...i,maneuverPoint:e,pathPointIndex:r,routePath:i.routePath.map(e=>({...e,point:[e.point.longitude,e.point.latitude]}))})}return{instructions:n}},Un=(e,t)=>{const n=e.routes.map((e,n)=>((e,t,n)=>{const r={type:"LineString",coordinates:e.legs.flatMap(e=>e.points?.map(e=>[e.longitude,e.latitude]))};return{type:"Feature",geometry:r,id:c(),bbox:a(r),properties:{index:t,summary:vn(e.summary,n),sections:Fn(e,n),...e.guidance&&{guidance:qn(e.guidance,r.coordinates)},...e.progress&&{progress:e.progress}}}})(e,n,t)),r=a(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},On={requestValidation:{schema:dn,refinements:[{check:e=>!!e.locations.map(g).includes("path")||e.locations.length>=2,message:"When passing waypoints only: at least 2 must be defined. If passing also paths, at least one path must be defined"}]},buildRequest:bn,sendRequest:async(e,t)=>{const n=e.method;if("GET"===n)return F(e.url,t);if("POST"===n)return W(e,t);throw new Error(`Unsupported HTTP method received: ${n}`)},parseResponse:Un,parseResponseError:(e,t)=>{const{data:n,message:r,status:i}=e;return new C(n?.error?.description??n?.detailedError?.message??r,t,i)},getAPIVersion:()=>2},Bn={reverseGeocode:an,geocode:je,geometryData:Ne,geometrySearch:et,calculateRoute:{buildCalculateRouteRequest:bn,parseCalculateRouteResponse:Un,calculateRouteTemplate:On},reachableRange:Xt,evChargingStationsAvailability:Te,placeByID:st,autocompleteSearch:se},Dn=async(e,t)=>M(e,{...Pe,...t},"EVChargingStationsAvailability"),Hn=async e=>{const t=e.properties.dataSources?.chargingAvailability?.id;if(t)try{const n=await Dn({id:t}),r=e.properties.poi;return n?{...e,properties:{...e.properties,...r&&{poi:{...r,openingHours:n.openingHours}},chargingPark:{...e.properties.chargingPark,availability:n}}}:void 0}catch(n){return void console.error(n)}};async function Kn(e,t){const n=[];for(const r of e.features){const e=await Hn(r);e?n.push(e):t?.excludeIfAvailabilityUnknown||n.push(r)}return{...e,features:n,bbox:a(n)}}const Nn=e=>Boolean(e&&"availability"in e&&e.availability),Gn=async(e,t)=>M(e,{...We,...t},"Geocode"),Vn=async e=>(await Gn({query:e,limit:1})).features[0];async function zn(e,t){const n=await M(e,{...Ke,...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)}const $n=async(e,t)=>M(e,{...at,...t},"PlaceById"),_n=async(e,t)=>M(e,{...on,...t},"ReverseGeocode"),Jn=async(e,t)=>M(e,{...On,...t},"Routing"),Yn=f.object({minFuzzyLevel:f.number().min(1).max(4).optional().describe("Minimum fuzzy matching level (1-4, higher allows more typos)"),maxFuzzyLevel:f.number().min(1).max(4).optional().describe("Maximum fuzzy matching level (1-4, higher allows more typos)")}),Zn=ze.extend(Ce.extend(Yn.shape).shape),Qn=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:re(e.details)}};break;case"NEARBY":t={...e,details:{position:re({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},Xn={requestValidation:{schema:Zn},buildRequest:e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}${Z}/search/${n.query}.json`}`);var n;Q(t,e);const r=t.searchParams;J(r,"typeahead",e.typeahead),J(r,"ofs",e.offset),_(r,"countrySet",e.countries),J(r,"radius",e.radiusMeters);const i=e.boundingBox&&a(e.boundingBox);return i&&(r.append("topLeft",Ae([i[3],i[0]])),r.append("btmRight",Ae([i[1],i[2]]))),J(r,"minFuzzyLevel",e.minFuzzyLevel),J(r,"maxFuzzyLevel",e.maxFuzzyLevel),t},sendRequest:F,parseResponse:e=>{const t=e.results.map(Se),n=s(a(t));return{type:"FeatureCollection",properties:{...ve(e.summary),queryIntent:e.summary.queryIntent.map(Qn)},features:t,...n&&{bbox:n}}}},er=async(e,t)=>"geometries"in e?Xe(e,t):(async(e,t)=>M(e,{...Xn,...t},"FuzzySearch"))(e,t),tr=async e=>(await er({query:e,limit:1})).features[0];export{T as APIErrorCode,P as SDKError,C as SDKServiceError,ae as autocompleteSearch,I as buildResponseError,w as buildValidationError,Jn as calculateRoute,Bn as customizeService,Dn as evChargingStationsAvailability,Gn as geocode,Vn as geocodeOne,zn as geometryData,Hn as getPlaceWithEVAvailability,Kn as getPlacesWithEVAvailability,Nn as hasChargingAvailability,R as parseDefaultResponseError,$n as placeById,_n as reverseGeocode,er as search,tr as searchOne};
|
|
2
2
|
//# sourceMappingURL=services.es.js.map
|