@tomtom-org/maps-sdk 0.56.0 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +143 -0
- package/README.md +6 -6
- package/THIRD_PARTY.txt +38 -2
- 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 +865 -653
- 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 +1 -1
- package/services/dist/index.d.ts +2293 -3325
- package/services/dist/services.es.js +1 -1
- package/services/dist/services.es.js.map +1 -1
- package/services/dist/third-party.json +1 -1
|
@@ -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 R,poiCategories as T,poiCategoriesToID as S,poiIDsToCategories as b,toPointGeometry as I,trafficIncidentRequestCategories as v,trafficIncidentToIconCategory as C,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)},B=(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)},_=(e,t)=>new D(e.message,t,e.issues),G=L.object({apiKey:L.string().optional(),commonBaseURL:L.string().optional(),customServiceBaseURL:L.string().optional(),language:L.string().optional()}),U=(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=>U(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},H=class extends Error{constructor(e){super(`${e.issues.map(e=>U(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},F=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?G.extend(t.schema.shape):G).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 H(n.error)})(o,t.requestValidation)}catch(s){throw _(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),B(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)}},K=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)},W=(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 W(r,n),c*=a,l=await t()}return l},j=()=>y()?"include":void 0,q=async(e,t,n)=>K(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)=>K(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(T)).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)},...e.language&&{"Accept-Language":e.language}}),ye=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),t.apiKey&&e.append("key",t.apiKey),t.language&&e.append("language",t.language)},fe=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},Re=(e,t,n)=>{!P(n)&&e.append(t,String(n))},Te=(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 Re(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]])))},Se=(e,t)=>{const n=e.searchParams;ye(n,t),Re(n,"limit",t.limit),fe(n,"fuelSet",t.fuelTypes),fe(n,"idxSet",t.indexes),fe(n,"brandSet",t.poiBrands),t.poiCategories&&fe(n,"categorySet",t.poiCategories.map(e=>S[e])),fe(n,"connectorSet",t.connectors),fe(n,"mapcodes",t.mapcodes),fe(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),Re(n,"minPowerKW",t.minPowerKW),Re(n,"maxPowerKW",t.maxPowerKW),Re(n,"view",t.view),Re(n,"openingHours",t.openingHours),Re(n,"timeZone",t.timeZone),Re(n,"relatedPois",t.relatedPois),fe(n,"entityTypeSet",t.geographyTypes)},be=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/searchAlongRoute/${e.query??""}.json`)(e));Se(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),Re(n,"sortBy",e.sortBy),Re(n,"spreadingMode","plan"),{url:t,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},Ie=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},ve=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,Ce=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>ve(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}:{}})}},Ae=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>ve(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Le=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)Ce(e.connectors,e.status,t);return t},Pe=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",Ee=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},Me=e=>`${e[1]},${e[0]}`,De=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]]},Ne=e=>[e.lon,e.lat],we=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)}},Oe=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,xe=e=>{const t=e.timeRanges.map(e=>({start:we(e.startTime),end:we(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:Oe(t)}},Be=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:Pe(e.ratedPowerKW)}));return{type:"Feature",geometry:I(Ne(t)),...i&&{bbox:De(i)},id:o,properties:{...E(c,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:Ne(e.position)}))},...l?.length&&{chargingPark:{...s,connectors:Ae(l)}},...r&&{poi:{name:r.name,categories:(r.categorySet?.map(e=>b[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:xe(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},_e=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:Ne(t)},...n}},Ge=e=>{const t=e.results.map(Be),n=a(o(t));return{type:"FeatureCollection",properties:{..._e(e.summary)},features:t,...n&&{bbox:n}}},Ue={requestValidation:{schema:pe},buildRequest:be,sendRequest:Y,parseResponse:Ge},He=async(e,t)=>F(e,{...Ue,...t},"AlongRouteSearch"),Fe=L.object({position:X,radiusMeters:L.number().optional()}),ke=L.union([Fe,L.object({boundingBox:ne})]),Ke=L.object({query:L.string()}),We=L.object({geoBias:Fe.optional(),limit:L.number().max(100).optional(),countries:L.array(L.string()).optional(),resultType:L.array(L.string()).optional()}),Ve=Ke.extend(We.shape),je=e=>{const t=new URL(`${n=e,n.customServiceBaseURL||`${n.commonBaseURL}/maps/orbis/places/autocomplete/${n.query}.json`}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",ye(r,e),Re(r,"limit",e.limit),Te(r,e.geoBias),fe(r,"countrySet",e.countries),fe(r,"resultSet",e.resultType),t},qe=e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:Ne(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:b[Number(t)]}}return e})})))};var r},Ye={requestValidation:{schema:Ve},buildRequest:je,sendRequest:q,parseResponse:qe},$e=async(e,t)=>F(e,{...Ye,...t},"Autocomplete"),Ze={alongRouteSearch:He,buildAlongRouteSearchRequest:be,parseAlongRouteSearchResponse:Ge,alongRouteSearchTemplate:Ue},Je={autocompleteSearch:$e,buildAutocompleteSearchRequest:je,parseAutocompleteSearchResponse:qe,autocompleteSearchTemplate:Ye},ze=G.extend({id:L.string()}),Qe=["fast","short","efficient","thrilling"],Xe=["all","unknown","none"],et=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/ev/id`)(e)),n=t.searchParams;return ye(n,e),n.append("id",e.id),t},tt=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:Pe(e.ratedPowerKW)}))}))}))),chargingPointAvailability:Ie(t.chargingStations),connectorAvailabilities:Le(t.chargingStations),...t.openingHours&&{openingHours:xe(t.openingHours)}}:void 0;var n},nt={requestValidation:{schema:ze},buildRequest:et,sendRequest:q,parseResponse:tt,parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new w(n,t,e.status)}},rt={buildEVChargingStationsAvailabilityRequest:et,parseEVChargingStationsAvailabilityResponse:tt,evChargingStationsAvailabilityTemplate:nt},ot=L.object({typeahead:L.boolean().optional(),offset:L.number().max(1900).optional(),geoBias:ke.optional(),countries:L.array(L.string()).optional()}),at=G.extend(re.shape).extend(ot.shape).extend({query:L.string()}),it=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/geocode`)(e)}/${e.query}.json`),n=t.searchParams;return ye(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)),Te(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)),t},st=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:I(Ne(t)),...n&&{bbox:De(n)},id:s,properties:{...E(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...o&&{entryPoints:o.map(e=>({...e,position:Ne(e.position)}))},...a&&{addressRanges:{...a,from:Ne(a.from),to:Ne(a.to)}}}}},ct=e=>{const t=e.results.map(st),n=a(o(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}},lt={requestValidation:{schema:at},buildRequest:it,sendRequest:q,parseResponse:ct},ut={buildGeocodingRequest:it,parseGeocodingResponse:ct,geocodingTemplate:lt},dt=L.object({geometries:L.union([Q,L.array(L.union([L.string(),z])).min(1).max(20)])}),pt=L.object({zoom:L.number().min(0).max(22).optional()}),mt=dt.extend(pt.shape),gt=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),ht=e=>{const t=new URL((e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/additionalData.json`)(e)),n=t.searchParams;return n.append("apiVersion",String(e.apiVersion)),e.apiKey&&n.append("key",e.apiKey),((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:gt(t):gt(t.features),e.append("geometries",me(n))})(n,e.geometries),Re(n,"geometriesZoom",e.zoom),t},yt=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}},ft={requestValidation:{schema:mt},buildRequest:ht,sendRequest:q,parseResponse:yt},Rt={buildGeometryDataRequest:ht,parseGeometryDataResponse:yt,geometryDataTemplate:ft},Tt=L.object({geometries:L.array(L.union([Q,J]))}),St=ae.extend(Tt.shape),bt=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:Me(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:ge(e.coordinates[0],50).map(e=>Me(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=>bt({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>bt({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>bt(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},It=e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}/maps/orbis/places/geometrySearch/${n.query??""}.json`}`);var n;return Se(t,e),{url:t,data:{geometryList:e.geometries.flatMap(bt)}}},vt=e=>{const t=e.results.map(Be),n=a(o(t));return{type:"FeatureCollection",properties:{..._e(e.summary)},features:t,...n&&{bbox:n}}},Ct={requestValidation:{schema:St},buildRequest:It,sendRequest:Y,parseResponse:vt},At=async(e,t)=>F(e,{...Ct,...t},"GeometrySearch"),Lt={geometrySearch:At,buildGeometrySearchRequest:It,parseGeometrySearchResponse:vt,geometrySearchTemplate:Ct},Pt=L.object({entityId:L.string()}),Et=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()}),Mt=Pt.extend(Et.shape),Dt=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/place.json`)(e)}`),n=t.searchParams;return ye(n,e),Re(n,"entityId",e.entityId),fe(n,"mapcodes",e.mapcodes),Re(n,"view",e.view),Re(n,"openingHours",e.openingHours),Re(n,"timeZone",e.timeZone),Re(n,"relatedPois",e.relatedPois),t},Nt=e=>e.results?.length?Be(e.results[0]):void 0,wt={requestValidation:{schema:Mt},buildRequest:Dt,sendRequest:q,parseResponse:Nt},Ot={buildPlaceByIdRequest:Dt,parsePlaceByIdResponse:Nt,placeByIdTemplate:wt},xt=(e,t)=>{const{data:n,message:r,status:o}=e;return new w(n?.error?.description??n?.detailedError?.message??r,t,o)},Bt=L.number().positive(),_t=L.number().min(0),Gt=L.number().min(0).max(100),Ut=Bt.optional(),Ht=_t.optional(),Ft=L.number().min(0).max(1).optional(),kt=L.object({speedKMH:L.number(),consumptionUnitsPer100KM:L.number()}),Kt={efficiency:L.object({acceleration:Ft,deceleration:Ft,uphill:Ft,downhill:Ft}).optional()},Wt=L.array(kt).min(1).max(25),Vt=L.object({...Kt,speedsToConsumptionsLiters:Wt,auxiliaryPowerInLitersPerHour:Ht,fuelEnergyDensityInMJoulesPerLiter:L.number().min(1).optional()}),jt=L.object({...Kt,speedsToConsumptionsKWH:Wt,auxiliaryPowerInkW:Ht,consumptionInKWHPerKMAltitudeGain:L.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Ht}),qt=L.object({currentType:L.enum(i),plugTypes:L.array(L.enum(R)).min(1),efficiency:Ft,baseLoadInkW:Ht,maxPowerInkW:Ht,maxVoltageInV:Ht,maxCurrentInA:Ht,voltageRange:L.object({minVoltageInV:Ht,maxVoltageInV:L.number().optional()}).optional()}),Yt=L.object({stateOfChargeInkWh:_t,maxPowerInkW:Bt}),$t=L.object({maxChargeKWH:Bt,batteryCurve:L.array(Yt).max(20).optional(),chargingConnectors:L.array(qt).min(1).optional(),chargingTimeOffsetInSec:Ht}),Zt=L.object({consumption:Vt}),Jt=L.object({consumption:jt,charging:$t.optional()}),zt=L.object({weightKG:Ut}).optional(),Qt=L.object({variantId:L.string()}),Xt=L.object({dimensions:zt,engine:L.union([Zt,Jt]).optional()}),en=L.union([Qt,Xt]).optional(),tn=L.object({heading:L.number().min(0).max(360).optional()}),nn=tn.extend({currentFuelInLiters:_t}),rn=tn.extend({currentChargePCT:Gt}),on=tn.extend({currentChargeInkWh:_t}),an=L.union([rn,on]),sn=L.object({minChargeAtDestinationPCT:Gt,minChargeAtChargingStopsPCT:L.number().min(0).max(50)}),cn=L.object({minChargeAtDestinationInkWh:_t,minChargeAtChargingStopsInkWh:_t}),ln=L.union([sn,cn]),un=L.object({chargingPreferences:ln.optional()}),dn={model:en,restrictions:L.object({maxSpeedKMH:L.number().min(0).max(250).optional(),tollTransponder:L.enum(Xe).optional()}).optional()},pn=L.object({...dn,engineType:L.undefined().optional(),state:tn.optional(),preferences:L.object({}).optional()}),mn=L.object({...dn,engineType:L.literal("combustion"),state:nn.optional(),preferences:L.object({}).optional()}),gn=L.object({...dn,engineType:L.literal("electric"),state:an.optional(),preferences:un.optional()}),hn=L.union([L.discriminatedUnion("engineType",[mn,gn]),pn]),yn=L.object({costModel:L.object({avoid:L.array(L.enum(n)).optional(),traffic:L.enum(["live","historical"]).optional(),routeType:L.enum(Qe).optional(),avoidAreas:L.array(ne).max(10).optional()}).optional(),travelMode:L.string().optional(),vehicle:hn.optional(),when:L.object({option:L.enum(["departAt","arriveBy"]),date:L.date()}).optional()}),fn=["timeMinutes","remainingChargeCPT","spentChargePCT","spentFuelLiters","distanceKM"],Rn=L.object({origin:X,budget:L.object({type:L.enum(fn),value:L.number().min(0)})}),Tn=L.enum(n).exclude(["alreadyUsedRoads"]),Sn=hn.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")),bn=L.object({vehicle:Sn.optional(),costModel:L.object({avoid:L.array(Tn).optional(),traffic:L.enum(["live","historical"]).optional(),routeType:L.enum(Qe).optional()}).optional(),maxFerryLengthMeters:L.number().min(0).optional(),smoothing:L.enum(["none","weak","strong"]).optional()}),In=yn.extend(Rn.extend(bn.shape).shape),vn=(e,t,n)=>{P(n)||(e[t]=String(n))},Cn=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),An=e=>{const t={};return e?(vn(t,"accelerationEfficiency",e.acceleration),vn(t,"decelerationEfficiency",e.deceleration),vn(t,"uphillEfficiency",e.uphill),vn(t,"downhillEfficiency",e.downhill),t):t},Ln=e=>{const t={};return e.speedsToConsumptionsKWH?.length&&(t.constantSpeedConsumptionInkWhPerHundredkm=Cn(e.speedsToConsumptionsKWH)),vn(t,"auxiliaryPowerInkW",e.auxiliaryPowerInkW),vn(t,"consumptionInkWhPerkmAltitudeGain",e.consumptionInKWHPerKMAltitudeGain),vn(t,"recuperationInkWhPerkmAltitudeLoss",e.recuperationInKWHPerKMAltitudeLoss),{...t,...An(e.efficiency)}},Pn=e=>{const t=e.consumption,n={};return t.speedsToConsumptionsLiters?.length&&(n.constantSpeedConsumptionInLitersPerHundredkm=Cn(t.speedsToConsumptionsLiters)),vn(n,"auxiliaryPowerInLitersPerHour",t.auxiliaryPowerInLitersPerHour),vn(n,"fuelEnergyDensityInMJoulesPerLiter",t.fuelEnergyDensityInMJoulesPerLiter),{...n,...An(t.efficiency)}},En=e=>{if(e.model&&!("variantId"in e.model))return e.model.engine?.charging?.maxChargeKWH},Mn=e=>{const t={};return e.charging?.maxChargeKWH&&(t.maxChargeInkWh=String(e.charging.maxChargeKWH)),t},Dn=e=>{const t={},n=e.state;if(n?.currentChargeInkWh)return t.currentChargeInkWh=String(n.currentChargeInkWh),t;const r=e.state?.currentChargePCT,o=En(e);return r&&o&&(t.currentChargeInkWh=String(o*r/100)),t},Nn=e=>{const t={};return vn(t,"currentFuelInLiters",e.state?.currentFuelInLiters),t},wn=e=>{const t=e.preferences?.chargingPreferences,n={};if(!t)return n;const r=t;if(!P(r.minChargeAtDestinationInkWh)||!P(r.minChargeAtChargingStopsInkWh))return vn(n,"minChargeAtDestinationInkWh",r.minChargeAtDestinationInkWh),vn(n,"minChargeAtChargingStopsInkWh",r.minChargeAtChargingStopsInkWh),n;const o=En(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},On=(e,t)=>{for(const[n,r]of Object.entries(t))e.append(n,r)},xn=(e,t)=>{for(const[n,r]of Object.entries(t))e.set(n,r)},Bn=(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 On(e,{...Ln(t.consumption),...Mn(t)})}On(e,Pn(n))})(e,"engineType"in t?t.engineType:void 0,t.model.engine)))},_n=(e,t)=>{t&&("electric"===t.engineType&&e.append("vehicleEngineType","electric"),Bn(e,t),((e,t)=>{if(!t.state||!("engineType"in t))return;const n="electric"===t.engineType?Dn:Nn;On(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))},Gn=e=>e.vehicle&&En(e.vehicle),Un=(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=Gn(t);null!=r&&e.append("energyBudgetInkWh",(r*n.value/100).toString());break}case"remainingChargeCPT":{const r=(e=>{if(!e.vehicle)return;const t=Dn(e.vehicle).currentChargeInkWh;return void 0===t?void 0:Number(t)})(t),o=Gn(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())}},Hn=e=>{const t=Me(d(e.origin)),n=new URL(((e,t)=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange/${t}/json`)(e,t)),r=n.searchParams;return ye(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),Re(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),Re(e,"routeType",n?.routeType),Re(e,"travelMode",t.travelMode),_n(e,t.vehicle)})(r,e),Un(r,e),Re(r,"maxFerryLengthInMeters",e.maxFerryLengthMeters),Re(r,"smoothing",e.smoothing??"strong"),{method:"GET",url:n}},Fn=(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}},kn={requestValidation:{schema:In},buildRequest:Hn,sendRequest:$,parseResponse:Fn,parseResponseError:xt,getAPIVersion:()=>2},Kn={buildReachableRangeRequest:Hn,parseReachableRangeResponse:Fn,reachableRangeTemplate:kn},Wn={Country:"country",CountrySubdivision:"countrySubdivision",CountrySecondarySubdivision:"countrySecondarySubdivision",CountryTertiarySubdivision:"countryTertiarySubdivision",Municipality:"municipality",MunicipalitySubdivision:"municipalitySubdivision",MunicipalitySecondarySubdivision:"municipalitySecondarySubdivision",Neighbourhood:"neighborhood",PostalCodeArea:"postalCode"},Vn=e=>{const[t,n]=d(e.position),r=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/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=>Wn[e]).join(",")),!P(e.heading)&&o.append("vehicleHeadingInDegrees",String(e.heading)),e.view&&o.append("geopoliticalView",e.view),{url:r,headers:{...he(e),Attributes:"results(*)"}}},jn={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"},qn=e=>jn[e]??e,Yn={street:"Street",area:"Geography",address:"Point Address"},$n=Object.fromEntries(Object.entries(Wn).map(([e,t])=>[t,e])),Zn=e=>{const{street:t,houseNumber:n,countryCodeIso2:r,...o}=e;return{...o,...t&&{streetName:t},...n&&{streetNumber:n},...r&&{countryCode:r,countryCodeISO3:qn(r)}}},Jn=(e,t)=>{const n=e.results[0];return{type:"Feature",geometry:I(d(t.position)),id:n?.id??s(),...n&&{properties:{type:Yn[n.type],address:{freeformAddress:n.title,...Zn(n.address)},...n.areaType&&{geographyType:[$n[n.areaType]],dataSources:{geometry:{id:n.id}}},...n.accessPoints?.length&&{entryPoints:n.accessPoints.map(e=>({position:e.position.coordinates}))},originalPosition:n.position.coordinates}}}},zn=L.object({position:X}),Qn=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()}),Xn={requestValidation:{schema:zn.extend(Qn.shape)},buildRequest:Vn,getAPIVersion:()=>2,sendRequest:q,parseResponse:Jn},er={buildRevGeoRequest:Vn,parseRevGeoResponse:Jn,reverseGeocodingTemplate:Xn},tr=["tollVignette","tollRoad","roadShields","importantRoadStretch"],nr=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 tr)(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},rr=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},or=e=>({...Ln(e.consumption),...Mn(e)}),ar=e=>{if(e.model&&!("variantId"in e.model))return e.model.engine},ir=e=>!!e.vehicle?.preferences?.chargingPreferences,sr=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]}]},cr=e=>{if(!Array.isArray(e)&&"properties"in e)return e.properties??void 0},lr=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}}},ur=(e,t)=>{t.computeTravelTimeFor&&e.searchParams.set("computeTravelTimeFor",t.computeTravelTimeFor)},dr=(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=ar(t);n&&xn(e.searchParams,or(n))}xn(e.searchParams,{...t.state&&Dn(t),...wn(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}},pr=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=cr(r),o=e?.candidateEntryPoints?.length?"ignore":t,[a,i]=d(r,{useEntryPoint:o});n.push({coordinate:[a,i],...e&&{options:e}})}else n.push(...sr(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=>({...he(e),Attributes:nr(e)}))(e),s=((e,t)=>{const n=e.slice(1).map((t,n)=>({...e[n].legToNext,...lr(t)}));if(t||!n.every(e=>0===Object.keys(e).length))return n})(n,t),c={routePlanningLocations:r,...a,...s&&{legs:s},...e.vehicle&&rr(e.vehicle)};if(ir(e)){const t=dr(e,c,i);return ur(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=ar(t);if(!n)return;const r="electric"===t.engineType;xn(e.searchParams,{...r?{...or(n),...Dn(t)}:{...Pn(n),...Nn(t)}})})(u,e.vehicle),ur(u,e),{method:"POST",url:u,data:c,headers:i}},mr=L.union([X,J]),gr=L.union([Z,z]),hr=L.object({locations:L.array(L.union([mr,gr])).min(1)}),yr=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()}),fr=yn.extend(hr.extend(yr.shape).shape),Rr=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},Tr=(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:Rr(n.chargingCurrentType),chargingSpeed:Pe(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:Pe(e.chargingParkPowerInkW)}}}},Sr=(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:Tr(e.chargingInformationAtEndOfLeg,n)}}},br=(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:{...Sr(r.summary,t),...void 0!==l&&{stopTimeInSeconds:l}},id:s()}),n},[]),Ir=e=>({id:s(),startPointIndex:e.startPathIndex,endPointIndex:e.endPathIndex}),vr=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"]}},Cr=(e,t)=>{const n={leg:br(e.legs,t)},r=e.sections;if(!r)return n;const o=(e,t)=>{t?.length&&(n[e]=t.map(Ir))};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=>({...Ir(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:qn(e.countryCodeIso2??"")}))),r.travelMode?.length&&(n.vehicleRestricted=r.travelMode.filter(e=>"other"===e.travelMode).map(Ir)),r.traffic?.length&&(n.traffic=r.traffic.map(e=>({...Ir(e),delayInSeconds:e.delayDurationInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKilometersPerHour,categories:vr(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:{...Ir(e),maxSpeedLimitInKmh:t}}).filter(e=>!!e)),r.lanes?.length&&(n.lanes=r.lanes.map(e=>({...Ir(e),lanes:(e.lanes??[]).map(e=>({directions:e.directions.map(e=>Nr[e]??e),...e.follow&&{follow:Nr[e.follow]??e.follow}})),laneSeparators:(e.laneSeparators??[]).map(e=>wr[e]??e),properties:e.properties}))),r.roadShields?.length&&(n.roadShields=r.roadShields.map(e=>({...Ir(e),roadShieldReferences:e.roadShieldReferences}))),r.tollVignette?.length&&(n.tollVignette=r.tollVignette.map(e=>({...Ir(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:qn(e.countryCodeIso2??"")}))),r.importantRoadStretch?.length&&(n.importantRoadStretch=r.importantRoadStretch.map(e=>({...Ir(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},Ar=1e-4,Lr=(e,t)=>Math.abs(e[0]-t[0])<Ar&&Math.abs(e[1]-t[1])<Ar,Pr={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"},Er={urban:"URBAN",motorway:"MOTORWAY",controlledAccess:"CONTROLLED_ACCESS"},Mr={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"},Dr={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"},Nr={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"},wr={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"},Or={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",back:"BACK"},xr={regular:"REGULAR",small:"SMALL"},Br={left:"LEFT",right:"RIGHT",leftAndRight:"LEFT_AND_RIGHT"},_r={properties:[]},Gr=e=>{const t=e.phonetic;return{text:e.text,...t&&{phonetic:t},...e.phoneticLanguageCode&&{phoneticLanguageCode:e.phoneticLanguageCode}}},Ur=e=>({properties:(e.properties??[]).map(e=>Er[e]??e.toUpperCase()),...e.roadNames?.length&&{streetName:Gr(e.roadNames[0].identifier)},...e.countryCodeIso2&&{countryCode:qn(e.countryCodeIso2)},...e.roadShields?.length&&{roadShields:e.roadShields.map(e=>({roadNumber:e.roadNumber?Gr(e.roadNumber):{text:""},countryCode:qn(e.countryCodeIso2??""),...e.countrySubdivisionCodeIso&&{stateCode:e.countrySubdivisionCodeIso},...e.iconReference&&{roadShieldReference:e.iconReference}}))}}),Hr=e=>({...e.tollgateName&&{tollgateName:Gr(e.tollgateName)},...e.tollPaymentTypes?.length&&{tollPaymentTypes:e.tollPaymentTypes.map(e=>Dr[e]??e)},...e.countryCrossingFromName&&{countryCrossingFromName:Gr(e.countryCrossingFromName)},...e.countryCrossingFromCodeIso2&&{countryCrossingFromCode:qn(e.countryCrossingFromCodeIso2)},...e.countryCrossingToName&&{countryCrossingToName:Gr(e.countryCrossingToName)},...e.countryCrossingToCodeIso2&&{countryCrossingToCode:qn(e.countryCrossingToCodeIso2)}}),Fr=e=>Or[e]??e,kr=e=>{return{...e.message&&{message:e.message},...e.intersectionName&&{intersectionName:Gr(e.intersectionName)},...e.drivingSide&&{drivingSide:e.drivingSide.toUpperCase()},...e.landmark&&{landmark:Mr[e.landmark]??e.landmark},...!P(e.distanceToPreviousTrafficLightInMeters)&&{trafficLightOffsetInMeters:e.distanceToPreviousTrafficLightInMeters},...e.sideRoads&&{sideRoads:(n=e.sideRoads,n.map(e=>({side:Br[e.side]??e.side,offsetFromManeuverInMeters:e.offsetFromManeuverInMeters,...!P(e.isDrivable)&&{isDrivable:e.isDrivable}})))},...e.maneuverView&&{maneuverView:(t=e.maneuverView,{...t.onRouteAngle&&{onRouteAngle:Fr(t.onRouteAngle)},offRouteAngles:(t.offRouteAngles??[]).map(Fr)})},...e.roundaboutType&&{roundaboutType:xr[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},Kr=(e,t)=>{const n=e.signpost?(e=>{if(e.exitName||e.exitNumber||e.towardName)return{...e.exitName&&{exitName:Gr(e.exitName)},...e.exitNumber&&{exitNumber:Gr(e.exitNumber)},towardName:e.towardName?Gr(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]}}},Wr=(e,t,n,r)=>({maneuverPoint:t,pathPointIndex:n,routeOffsetInMeters:e.routeOffsetInMeters,maneuver:e.maneuver?Pr[e.maneuver]??e.maneuver:e.maneuver,routePath:(e.routePath??[]).map(e=>({point:e.point.coordinates,distanceInMeters:e.distanceFromRouteStartInMeters,travelTimeInSeconds:e.travelTimeFromRouteStartInSeconds})),nextRoadInfo:e.nextRoadInformation?Ur(e.nextRoadInformation):_r,previousRoadInfo:e.previousRoadInformation?Ur(e.previousRoadInformation):_r,...kr(e),...Kr(e,r),...Hr(e)}),Vr=(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(Lr(t[n],e)){o=n;break}r.push(Wr(a,e,o,n))}return{instructions:r}},jr=(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:Sr(e.summary,n),sections:Cr(e,n),...e.instructions?.length&&{guidance:Vr(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}},qr={requestValidation:{schema:fr,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||ir(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)||ir(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:pr,sendRequest:$,parseResponse:jr,parseResponseError:xt,getAPIVersion:()=>3},Yr={buildCalculateRouteRequest:pr,parseCalculateRouteResponse:jr,calculateRouteTemplate:qr},$r=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],Zr={speed:"SPEED",freeFlowSpeed:"FREE_FLOW_SPEED",congestionLevel:"CONGESTION_LEVEL",travelTime:"TRAVEL_TIME",networkLength:"NETWORK_LENGTH"},Jr=e=>e instanceof Date?e.toISOString().slice(0,10):e,zr=Array.from({length:24},(e,t)=>t),Qr=e=>$r.indexOf(e),Xr=e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));ye(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(Jr)}:{startDate:Jr(e.startDate??r(3)),endDate:Jr(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=>Zr[e]):e.metrics.map(e=>Zr[e]),frcs:"all"===e.functionalRoadClasses?$r.map((e,t)=>t):e.functionalRoadClasses.map(Qr),hours:"all"===e.hours?zr:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},eo=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}}),to=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},...eo(e)}),no=(e,t)=>{const n=new Date(e);return n.setDate(n.getDate()+t),n},ro=(e,t)=>e.map((e,n)=>{const r=to(e);return void 0===r.date&&(r.date=no(t,Math.floor(n/24))),void 0===r.hour&&(r.hour=n%24),r}),oo=(e,t)=>e.map((e,n)=>{const r=to(e);return void 0===r.date&&(r.date=no(t,n)),r}),ao=e=>({tileCentre:[e.lon,e.lat],...eo(e)}),io=e=>({startDate:new Date(e.startDate),endDate:new Date(e.endDate),labels:e.labels}),so=(e,t)=>{return{...e.yearly&&{yearly:e.yearly.map(to)},...e.monthly&&{monthly:e.monthly.map(to)},...e.weekly&&{weekly:e.weekly.map(to)},...e.daily&&{daily:oo(e.daily,t)},...e.hourly&&{hourly:ro(e.hourly,t)},...e.average&&{average:(n=e.average,n.map((e,t)=>{const n=to(e);return void 0===n.day&&(n.day=Math.floor(t/24)+1),void 0===n.hour&&(n.hour=t%24),n}))}};var n},co={SPEED:"speed",FREE_FLOW_SPEED:"freeFlowSpeed",CONGESTION_LEVEL:"congestionLevel",TRAVEL_TIME:"travelTime",NETWORK_LENGTH:"networkLength"},lo=e=>{const t={};for(const[n,r]of Object.entries(e)){const e=co[n];e&&(t[e]=r.map(io))}return t},uo=(e,t)=>({name:e.name,timezone:e.timezone,level:e.level,baseData:eo(e.baseData),timedData:so(e.timedData,t),...e.tiledData&&{tiledData:{tiles:e.tiledData.tiles.map(ao)}},...e.anomalies&&{anomalies:lo(e.anomalies)}}),po=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},mo=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:uo(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=>co[e]).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:po(n)},features:n}},go=L.union([L.date(),L.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),ho=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)})]),yo=e=>e instanceof Date?e:new Date(e),fo=e=>{const t=/* @__PURE__ */new Date,n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return(e=>{const t=yo(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())})(e)<=n-1728e5},Ro={requestValidation:{schema:G.extend({name:L.string().optional(),startDate:go.optional(),endDate:go.optional(),days:L.array(go).min(1).optional(),metrics:L.union([L.array(L.enum(t)).min(1),L.literal("all")]),functionalRoadClasses:L.union([L.array(L.enum($r)).min(1),L.literal("all")]),hours:L.union([L.array(L.number().int().min(0).max(23)).min(1),L.literal("all")]),geometry:ho}).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?yo(e.endDate):/* @__PURE__ */new Date).getTime()-yo(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(fo);const t=e.endDate??/* @__PURE__ */new Date;return fo(t)},{message:"Dates must be at least 2 days before today"})},buildRequest:Xr,sendRequest:$,parseResponse:mo},To={buildTrafficAreaAnalyticsRequest:Xr,parseTrafficAreaAnalyticsResponse:mo,trafficAreaAnalyticsTemplate:Ro},So=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidentDetails`)(e)),n=t.searchParams;if(ye(n,e),((e,t)=>{Re(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}}}}}"),Re(e,"t",t.trafficModelId),fe(e,"categoryFilter",t.categoryFilter?.map(C)),fe(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})},bo=e=>({description:e.description,code:e.code,category:m(e.iconCategory)}),Io=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(bo),...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},vo=e=>({type:"FeatureCollection",features:(e.incidents??[]).filter(e=>null!==e).map(Io)}),Co={requestValidation:{schema:G.extend({bbox:ne.optional(),ids:L.array(L.string()).optional(),trafficModelId:L.string().optional(),categoryFilter:L.array(L.enum(v)).optional(),timeValidityFilter:L.array(L.enum(["present","future"])).optional()}).refine(e=>!(e.bbox&&e.ids),{message:"Provide either bbox or ids, not both"})},buildRequest:So,sendRequest:$,parseResponse:vo},Ao={alongRouteSearch:Ze,reverseGeocode:er,geocode:ut,geometryData:Rt,geometrySearch:Lt,calculateRoute:Yr,reachableRange:Kn,evChargingStationsAvailability:rt,trafficAreaAnalytics:To,trafficIncidentDetails:{buildTrafficIncidentDetailsRequest:So,parseTrafficIncidentDetailsResponse:vo,trafficIncidentDetailsTemplate:Co},placeByID:Ot,autocompleteSearch:Je},Lo=async(e,t)=>F(e,{...nt,...t},"EVChargingStationsAvailability"),Po=async(e,t)=>{const n=e.properties.dataSources?.chargingAvailability?.id;if(n)try{const r=await Lo({...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 Eo(e,t){const{excludeIfAvailabilityUnknown:n,...r}=t??{},a=[];for(const o of e.features){const e=await Po(o,r);e?a.push(e):n||a.push(o)}return{...e,features:a,bbox:o(a)}}var Mo=e=>Boolean(e&&"availability"in e&&e.availability),Do=async(e,t)=>F(e,{...lt,...t},"Geocode"),No=async e=>{const t=await Do({query:e,limit:1});if(!t.features[0])throw new Error(`geocodeOne: no results found for "${e}"`);return t.features[0]};async function wo(e,t){const n=await F(e,{...ft,...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 Oo=async(e,t)=>F(e,{...wt,...t},"PlaceById"),xo=/* @__PURE__ */new Map,Bo=/* @__PURE__ */new Map,_o="en-GB",Go=e=>e??_o,Uo=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),Ho=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(Uo);for(const r of e)t[r]=n}return t},Fo=G.extend({filters:L.array(L.string()).optional()}),ko=e=>{const t=b[e.id];return t?{code:t,name:e.name,childCategoryCodes:e.childCategoryIds.map(e=>b[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)},Ko={requestValidation:{schema:Fo},buildRequest:e=>{const t=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/poiCategories.json`,n=new URL(t);return ye(n.searchParams,e),n},getAPIVersion:()=>1,sendRequest:q,parseResponse:e=>({poiCategories:e.poiCategories.map(ko).filter(e=>null!==e)})},Wo=(e,t)=>{const n=(e=>Bo.get(e??_o)??{})(e),r=/* @__PURE__ */new Map;for(const o of t){const e=Uo(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()]},Vo=async(e={})=>{const{language:t}=f(e);let n=(e=>xo.get(Go(e)))(t);return n||(n=(await F(e,Ko,"POICategories")).poiCategories,((e,t)=>{const n=Go(e);xo.set(n,t),Bo.set(n,Ho(t))})(t,n)),e.filters?.length?{poiCategories:Wo(t,e.filters)}:{poiCategories:n}},jo=async(e={})=>{const{poiCategories:t}=await Vo(e);return t.map(e=>e.code)},qo=async(e,t)=>F(e,{...kn,...t},"Reachable Range"),Yo=(...e)=>{const t=e.filter(e=>!!e);return t.length<2?t[0]:AbortSignal.any(t)},$o=async(e,t,n)=>{const r=[];for(const o of e){const e=Yo(o.signal,t?.signal);try{r.push(await qo({...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}},Zo=async(e,t)=>F(e,{...Xn,...t},"ReverseGeocode"),Jo=async(e,t)=>F(e,{...qr,...t},"Routing"),zo=L.object({minFuzzyLevel:L.number().min(1).max(4).optional(),maxFuzzyLevel:L.number().min(1).max(4).optional()}),Qo=ae.extend(ot.extend(zo.shape).shape),Xo=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:Ne(e.details)}};break;case"NEARBY":t={...e,details:{position:Ne({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},ea={requestValidation:{schema:Qo},buildRequest:e=>{const t=new URL(`${(e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/search/${e.query??""}.json`)(e)}`);Se(t,e);const n=t.searchParams;return Re(n,"typeahead",e.typeahead),Re(n,"ofs",e.offset),fe(n,"countrySet",e.countries),Te(n,e.geoBias),Re(n,"minFuzzyLevel",e.minFuzzyLevel),Re(n,"maxFuzzyLevel",e.maxFuzzyLevel),t},sendRequest:q,parseResponse:e=>{const t=e.results.map(Be),n=a(o(t));return{type:"FeatureCollection",properties:{..._e(e.summary),queryIntent:e.summary.queryIntent.map(Xo)},features:t,...n&&{bbox:n}}}},ta=async(e,t)=>"route"in e?He(e,t):"geometries"in e?At(e,t):(async(e,t)=>F(e,{...ea,...t},"FuzzySearch"))(e,t),na=async e=>{const t=await ta({query:e,limit:1});if(!t.features[0])throw new Error(`searchOne: no results found for "${e}"`);return t.features[0]},ra=async(e,t)=>F(e,{...Ro,...t},"TrafficAreaAnalytics"),oa=async(e,t)=>F(e,{...Co,...t},"TrafficIncidentDetails");export{N as APIErrorCode,O as SDKAbortError,D as SDKError,w as SDKServiceError,He as alongRouteSearch,$e as autocompleteSearch,fn as budgetTypes,B as buildResponseError,_ as buildValidationError,qo as calculateReachableRange,$o as calculateReachableRanges,Jo as calculateRoute,Ao as customizeService,Lo as evChargingStationsAvailability,Do as geocode,No as geocodeOne,wo as geometryData,Vo as getPOICategories,jo as getPOICategoryCodes,Po as getPlaceWithEVAvailability,Eo as getPlacesWithEVAvailability,Mo as hasChargingAvailability,x as parseDefaultResponseError,Oo as placeById,Zo as reverseGeocode,Qe as routeTypes,ta as search,na as searchOne,Xe as tollTransponderOptions,ra as trafficAreaAnalytics,oa 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 u,getPosition as l,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 I,trafficIncidentRequestCategories as b,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";var O=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),N=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},x={[O.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[O.FORBIDDEN]:"Request failed with status code 403"},B=class extends N{constructor(e,t,n){super(e,t),this.status=n,this.status&&x[this.status]&&(this.message=x[this.status])}},H=class extends N{constructor(e,t){super("The operation was aborted.",e),this.name="AbortError",this.cause=t}},_=(e,t)=>{const{data:n,message:r,status:o}=e;return new B(n?.error||n?.errorText||r,t,o)},F=(e,t,n,r)=>{if(r?.aborted&&e===r.reason)return new H(t,r.reason);if(r?.aborted&&"AbortError"===e?.name)return new H(t,r.reason);if(e.status){const r=e;return n?n(r,t):_(r,t)}return new N(e.message,t)},U=(e,t)=>new N(e.message,t,e.issues),G=C.object({apiKey:C.string().optional(),commonBaseURL:C.string().optional(),customServiceBaseURL:C.string().optional(),language:C.string().optional()}),k=(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=>k(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},K=class extends Error{constructor(e){super(`${e.issues.map(e=>k(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},W=async(e,t,n)=>{if(e.signal?.aborted)throw new H(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?G.extend(t.schema.shape):G).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 K(n.error)})(o,t.requestValidation)}catch(s){throw U(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),F(s,n,t.parseResponseError,e.signal)}},j=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)}},V=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 j(e.status,t,n)},q=(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})}),Y=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,u=await t();for(;429===u.status;){const e=Number.parseInt(u.headers.get("retry-after")??"",10),r=Number.isFinite(e)?1e3*e:c;if(Date.now()-s+r>i)break;await u.text().catch(()=>{}),await q(r,n),c*=a,u=await t()}return u},$=()=>g()?"include":void 0,Z=async(e,t,n)=>V(await Y(()=>{const r=$(),{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)),z=async(e,t,n)=>V(await Y(()=>{const r=$(),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)),J=async(e,t,n)=>{if("GET"===e.method)return Z(e,t,n);if("POST"===e.method)return z(e,t,n);throw new Error(`Unsupported HTTP method received: ${e.method}`)},Q=C.array(C.array(C.number())),X=C.object({type:C.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:C.union([C.array(C.number()),Q,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')),ee=C.object({type:C.literal("Feature"),geometry:X,id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),te=C.object({type:C.literal("FeatureCollection"),features:C.array(ee),id:C.optional(C.union([C.string(),C.number()])),properties:C.unknown().optional(),bbox:C.optional(C.array(C.number()))}),ne=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())}),ee]),re=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"})]),oe=C.union([X,ee,te]),ae=C.union([re,oe,C.array(oe)]),ie=C.object({query:C.string().optional(),position:ne.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()}),se=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()}),ce=ie.extend(se.shape),ue=C.object({type:C.literal("LineString"),coordinates:Q}),le=C.object({type:C.literal("Feature"),geometry:ue}),de=Q,pe=C.union([ue,le,de]),me=C.object({route:pe,maxDetourTimeSeconds:C.number().int().positive()}),ge=C.object({sortBy:C.enum(["detourTime","detourOffset"]).optional()}),he=ce.extend({...me.shape,...ge.shape}),ye=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",fe=(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},Te=e=>({...e.apiKey&&{"TomTom-Api-Key":e.apiKey},...!A(e.apiVersion)&&{"TomTom-Api-Version":String(e.apiVersion)}}),Re=e=>({...Te(e),...e.language&&{"Accept-Language":e.language}}),Ie=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),t.apiKey&&e.append("key",t.apiKey),t.language&&e.append("language",t.language)},be=e=>Te(e),Se=(e,t)=>{t.language&&e.append("language",t.language)},Ce=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},ve=(e,t,n)=>{!A(n)&&e.append(t,String(n))},Ae=(e,t)=>{if(!t)return;if(void 0!==t.position)return((e,t)=>{const n=l(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))})(e,t.position),void ve(e,"radius",t.radiusMeters);const n=o(t.boundingBox);n&&(e.append("topLeft",ye([n[3],n[0]])),e.append("btmRight",ye([n[1],n[2]])))},Pe=(e,t)=>{const n=e.searchParams;Se(n,t),ve(n,"limit",t.limit),Ce(n,"fuelSet",t.fuelTypes),Ce(n,"idxSet",t.indexes),Ce(n,"brandSet",t.poiBrands),t.poiCategories&&Ce(n,"categorySet",t.poiCategories.map(e=>T[e])),Ce(n,"connectorSet",t.connectors),Ce(n,"mapcodes",t.mapcodes),Ce(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),ve(n,"minPowerKW",t.minPowerKW),ve(n,"maxPowerKW",t.maxPowerKW),ve(n,"view",t.view),ve(n,"openingHours",t.openingHours),ve(n,"timeZone",t.timeZone),ve(n,"relatedPois",t.relatedPois),Ce(n,"entityTypeSet",t.geographyTypes)},Le=(e,t)=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/${t}`,Me=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},Ee=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,we=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>Ee(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}:{}})}},De=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>Ee(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Oe=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)we(e.connectors,e.status,t);return t},Ne=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",xe=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},Be=e=>`${e[1]},${e[0]}`,He=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=xe(e.southWest),n=xe(e.northEast)),[t[0],t[1],n[0],n[1]]},_e=e=>[e.lon,e.lat],Fe=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)}},Ue=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,Ge=e=>{const t=e.timeRanges.map(e=>({start:Fe(e.startTime),end:Fe(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:Ue(t)}},ke=e=>{const{position:t,entryPoints:n,poi:r,id:o,dist:a,boundingBox:i,chargingPark:s,...c}=e,u=s?.connectors?.map(e=>({...M(e,"connectorType"),type:e.connectorType,chargingSpeed:Ne(e.ratedPowerKW)}));return{type:"Feature",geometry:I(_e(t)),...i&&{bbox:He(i)},id:o,properties:{...M(c,"viewport"),...a&&{distance:a},...n?.length&&{entryPoints:n.map(e=>({...e,position:_e(e.position)}))},...u?.length&&{chargingPark:{...s,connectors:De(u)}},...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:Ge(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},Ke=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:_e(t)},...n}},We={requestValidation:{schema:he},buildRequest:e=>{const t=new URL((e=>Le(e,`searchAlongRoute/${encodeURIComponent(e.query??"")}.json`))(e));Pe(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),ve(n,"sortBy",e.sortBy),ve(n,"spreadingMode","plan"),{url:t,headers:be(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:z,parseResponse:e=>{const t=e.results.map(ke),n=a(o(t));return{type:"FeatureCollection",properties:{...Ke(e.summary)},features:t,...n&&{bbox:n}}}},je=async e=>W(e,We,"AlongRouteSearch"),Ve=G.extend({id:C.string()}),qe=["fast","short","efficient","thrilling"],Ye=["all","unknown","none"],$e={requestValidation:{schema:Ve},buildRequest:e=>{const t=new URL((e=>Le(e,"ev/id"))(e)),n=t.searchParams;return Ie(n,e),n.append("id",e.id),t},sendRequest:Z,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:Ne(e.ratedPowerKW)}))}))}))),chargingPointAvailability:Me(t.chargingStations),connectorAvailabilities:Oe(t.chargingStations),...t.openingHours&&{openingHours:Ge(t.openingHours)}}:void 0;var n},parseResponseError:(e,t)=>{const n=e.data?.detailedError?.message??e.message;return new B(n,t,e.status)}},Ze=async e=>W(e,$e,"EVChargingStationsAvailability"),ze=async(e,t)=>{const n=e.properties.dataSources?.chargingAvailability?.id;if(n)try{const r=await Ze({...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 Je(e,t){const{excludeIfAvailabilityUnknown:n,...r}=t??{},a=[];for(const o of e.features){const e=await ze(o,r);e?a.push(e):n||a.push(o)}return{...e,features:a,bbox:o(a)}}var Qe=e=>Boolean(e&&"availability"in e&&e.availability),Xe=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},et=C.object({position:ne,radiusMeters:C.number().optional()}),tt=C.union([et,C.object({boundingBox:ae})]),nt=C.object({typeahead:C.boolean().optional(),offset:C.number().max(1900).optional(),geoBias:tt.optional(),countries:C.array(C.string()).optional()}),rt=G.extend(ie.shape).extend(nt.shape).extend({query:C.string()}),ot=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:o,addressRanges:a,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:I(_e(t)),...n&&{bbox:He(n)},id:s,properties:{...M(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)}}}}},at={requestValidation:{schema:rt},buildRequest:e=>{const t=new URL(`${(e=>Le(e,"geocode"))(e)}/${encodeURIComponent(e.query)}.json`),n=t.searchParams;return Se(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)),Ae(n,e.geoBias),e.countries&&n.append("countrySet",ye(e.countries)),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",ye(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",ye(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",ye(e.geographyTypes)),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>{const t=e.results.map(ot),n=a(o(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}}},it=async e=>W(e,at,"Geocode"),st=async e=>Xe("geocodeOne",e,it),ct=C.object({geometries:C.union([te,C.array(C.union([C.string(),ee])).min(1).max(20)])}),ut=C.object({zoom:C.number().min(0).max(22).optional()}),lt=ct.extend(ut.shape),dt=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),pt={requestValidation:{schema:lt},buildRequest:e=>{const t=new URL((e=>Le(e,"additionalData.json"))(e)),n=t.searchParams;return((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:dt(t):dt(t.features),e.append("geometries",ye(n))})(n,e.geometries),ve(n,"geometriesZoom",e.zoom),{url:t,headers:be(e)}},sendRequest:Z,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 mt(e){const t=await W(e,pt,"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 gt=C.object({entityId:C.string()}),ht=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()}),yt=gt.extend(ht.shape),ft={requestValidation:{schema:yt},buildRequest:e=>{const t=new URL(`${(e=>Le(e,"place.json"))(e)}`),n=t.searchParams;return Se(n,e),ve(n,"entityId",e.entityId),Ce(n,"mapcodes",e.mapcodes),ve(n,"view",e.view),ve(n,"openingHours",e.openingHours),ve(n,"timeZone",e.timeZone),ve(n,"relatedPois",e.relatedPois),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>e.results?.length?ke(e.results[0]):void 0},Tt=async e=>W(e,ft,"PlaceDetails"),Rt=/* @__PURE__ */new Map,It=/* @__PURE__ */new Map,bt="en-GB",St=e=>e??bt,Ct=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),vt=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(Ct);for(const r of e)t[r]=n}return t},At=G.extend({filters:C.array(C.string()).optional()}),Pt=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)},Lt={requestValidation:{schema:At},buildRequest:e=>{const t=Le(e,"poiCategories.json"),n=new URL(t);return Se(n.searchParams,e),{url:n,headers:be(e)}},getAPIVersion:()=>1,sendRequest:Z,parseResponse:e=>({poiCategories:e.poiCategories.map(Pt).filter(e=>null!==e)})},Mt=(e,t)=>{const n=(e=>It.get(e??bt)??{})(e),r=/* @__PURE__ */new Map;for(const o of t){const e=Ct(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()]},Et=async(e={})=>{const{language:t}=h(e);let n=(e=>Rt.get(St(e)))(t);return n||(n=(await W(e,Lt,"POICategories")).poiCategories,((e,t)=>{const n=St(e);Rt.set(n,t),It.set(n,vt(t))})(t,n)),e.filters?.length?{poiCategories:Mt(t,e.filters)}:{poiCategories:n}},wt=async(e={})=>{const{poiCategories:t}=await Et(e);return t.map(e=>e.code)},Dt=(e,t)=>{const{data:n,message:r,status:o}=e;return new B(n?.error?.description??n?.detailedError?.message??r,t,o)},Ot=(e,t)=>e*t/100,Nt=e=>"engineType"in e&&"electric"===e.engineType,xt=e=>{if(Nt(e)&&e.model&&!("variantId"in e.model))return e.model.engine},Bt=(e,t,n)=>{A(n)||(e[t]=String(n))},Ht=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),_t=e=>{const t={};return e?(Bt(t,"accelerationEfficiency",e.acceleration),Bt(t,"decelerationEfficiency",e.deceleration),Bt(t,"uphillEfficiency",e.uphill),Bt(t,"downhillEfficiency",e.downhill),t):t},Ft=e=>{const t={};return e.speedsToConsumptionsKWH?.length&&(t.constantSpeedConsumptionInkWhPerHundredkm=Ht(e.speedsToConsumptionsKWH)),Bt(t,"auxiliaryPowerInkW",e.auxiliaryPowerInkW),Bt(t,"consumptionInkWhPerkmAltitudeGain",e.consumptionInKWHPerKMAltitudeGain),Bt(t,"recuperationInkWhPerkmAltitudeLoss",e.recuperationInKWHPerKMAltitudeLoss),{...t,..._t(e.efficiency)}},Ut=e=>{const t=e.consumption,n={};return t.speedsToConsumptionsLiters?.length&&(n.constantSpeedConsumptionInLitersPerHundredkm=Ht(t.speedsToConsumptionsLiters)),Bt(n,"auxiliaryPowerInLitersPerHour",t.auxiliaryPowerInLitersPerHour),Bt(n,"fuelEnergyDensityInMJoulesPerLiter",t.fuelEnergyDensityInMJoulesPerLiter),{...n,..._t(t.efficiency)}},Gt=e=>xt(e)?.charging?.maxChargeKWH,kt=e=>{const t={};return e.charging?.maxChargeKWH&&(t.maxChargeInkWh=String(e.charging.maxChargeKWH)),t},Kt=e=>{const t=e.state?.currentChargeInkWh;if(!A(t))return t;const n=e.state?.currentChargePCT,r=Gt(e);return!A(n)&&r?Ot(r,n):void 0},Wt=e=>{const t={};return Bt(t,"currentChargeInkWh",Kt(e)),t},jt=e=>{const t={};return Bt(t,"currentFuelInLiters",e.state?.currentFuelInLiters),t},Vt=e=>Nt(e)?e.preferences?.chargingPreferences:void 0,qt=(e,t)=>{for(const[n,r]of Object.entries(t))e.set(n,r)},Yt=C.number().positive(),$t=C.number().min(0),Zt=C.number().min(0).max(100),zt=Yt.optional(),Jt=$t.optional(),Qt=C.number().min(0).max(1).optional(),Xt=C.object({speedKMH:C.number(),consumptionUnitsPer100KM:C.number()}),en={efficiency:C.object({acceleration:Qt,deceleration:Qt,uphill:Qt,downhill:Qt}).optional()},tn=C.array(Xt).min(1).max(25),nn=C.object({...en,speedsToConsumptionsLiters:tn,auxiliaryPowerInLitersPerHour:Jt,fuelEnergyDensityInMJoulesPerLiter:C.number().min(1).optional()}),rn=C.object({...en,speedsToConsumptionsKWH:tn,auxiliaryPowerInkW:Jt,consumptionInKWHPerKMAltitudeGain:C.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Jt}),on=C.object({currentType:C.enum(i),plugTypes:C.array(C.enum(y)).min(1),efficiency:Qt,baseLoadInkW:Jt,maxPowerInkW:Jt,maxVoltageInV:Jt,maxCurrentInA:Jt,voltageRange:C.object({minVoltageInV:Jt,maxVoltageInV:C.number().optional()}).optional()}),an=C.object({stateOfChargeInkWh:$t,maxPowerInkW:Yt}),sn=C.object({maxChargeKWH:Yt,batteryCurve:C.array(an).max(20).optional(),chargingConnectors:C.array(on).min(1).optional(),chargingTimeOffsetInSec:Jt}),cn=C.object({consumption:nn}),un=C.object({consumption:rn,charging:sn.optional()}),ln=C.object({weightKG:zt}).optional(),dn=C.object({variantId:C.string()}),pn=C.object({dimensions:ln,engine:C.union([cn,un]).optional()}),mn=C.union([dn,pn]).optional(),gn=C.object({heading:C.number().min(0).max(360).optional()}),hn=gn.extend({currentFuelInLiters:$t}),yn=gn.extend({currentChargePCT:Zt}),fn=gn.extend({currentChargeInkWh:$t}),Tn=C.union([yn,fn]),Rn=C.object({minChargeAtDestinationPCT:Zt,minChargeAtChargingStopsPCT:C.number().min(0).max(50)}),In=C.object({minChargeAtDestinationInkWh:$t,minChargeAtChargingStopsInkWh:$t}),bn=C.union([Rn,In]),Sn=C.object({chargingPreferences:bn.optional()}),Cn={model:mn,restrictions:C.object({maxSpeedKMH:C.number().min(0).max(250).optional(),tollTransponder:C.enum(Ye).optional()}).optional()},vn=C.object({...Cn,engineType:C.undefined().optional(),state:gn.optional()}),An=C.object({...Cn,engineType:C.literal("combustion"),state:hn.optional()}),Pn=C.object({...Cn,engineType:C.literal("electric"),state:Tn.optional(),preferences:Sn.optional()}),Ln=C.union([C.discriminatedUnion("engineType",[An,Pn]),vn]),Mn=C.object({avoid:C.array(C.enum(n)).optional(),traffic:C.enum(["live","historical"]).optional(),routeType:C.enum(qe).optional(),avoidAreas:C.array(ae).max(10).optional()}),En=C.object({option:C.enum(["departAt","arriveBy"]),date:C.date()}),wn=C.object({costModel:Mn.optional(),travelMode:C.string().optional(),vehicle:Ln.optional(),when:En.optional()}),Dn=["timeMinutes","remainingChargePCT","spentChargePCT","spentFuelLiters","distanceKM"],On=C.object({origin:ne,budget:C.object({type:C.enum(Dn),value:C.number().min(0)})}),Nn=C.enum(n).exclude(["alreadyUsedRoads"]),xn=Ln.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.")),Bn=En.check(C.refine(e=>"arriveBy"!==e.option,"when.arriveBy: calculateReachableRange has no arrival-time parameter. Use when.departAt instead, or omit when entirely.")),Hn=Mn.extend({avoid:C.array(Nn).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.")),_n=C.object({when:Bn.optional(),vehicle:xn.optional(),costModel:Hn.optional(),maxFerryLengthMeters:C.number().min(0).optional(),smoothing:C.enum(["none","weak","strong"]).optional()}),Fn=wn.extend(On.extend(_n.shape).shape),Un=/* @__PURE__ */new Set(["spentChargePCT","remainingChargePCT"]),Gn={check:e=>!Un.has(e.budget.type)||!!e.vehicle&&void 0!==Gt(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."},kn={check:e=>"remainingChargePCT"!==e.budget.type||!!e.vehicle&&void 0!==Kt(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."},Kn={schema:Fn,refinements:[Gn,kn]},Wn=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()}}),jn=e=>e.model&&"variantId"in e.model?e.model.variantId:void 0,Vn=e=>{const t={};return Nt(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},qn=(e,t)=>{const n=xt(t),r=(e=>"engineType"in e&&"combustion"===e.engineType?e.model?.engine:void 0)(t);var o;qt(e.searchParams,Nt(t)?{...n&&(o=n,{...Ft(o.consumption),...kt(o)}),...Wt(t)}:{...r&&Ut(r),...jt(t)})},Yn=(e,t)=>{const n=jn(t);n&&e.searchParams.set("vehicleModelId",n),qn(e,t)},$n=e=>({origin:{type:"Point",coordinates:d(e.origin)},...Wn(e),...e.vehicle&&Vn(e.vehicle)}),Zn=e=>({...Re(e),Attributes:"reachableRange(boundary)"}),zn=Object.keys({origin:!0,budget:!0,costModel:!0,vehicle:!0,travelMode:!0,when:!0,maxFerryLengthMeters:!0,smoothing:!0}),Jn={requestValidation:Kn,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&&Gt(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",Ot(r,n.value).toString());break;case"remainingChargePCT":{const o=t.vehicle&&Kt(t.vehicle);if(r&&void 0!==o){const t=Ot(r,n.value);e.append("energyBudgetInkWh",Math.max(0,o-t).toString())}break}}})(t.searchParams,e),ve(t.searchParams,"maxFerryLengthInMeters",e.maxFerryLengthMeters),ve(t.searchParams,"smoothing",e.smoothing??"strong"),e.vehicle&&Yn(t,e.vehicle),{method:"POST",url:t,data:$n(e),headers:Zn(e)}},sendRequest:J,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,zn)}},parseResponseError:Dt,getAPIVersion:()=>3},Qn=async e=>W(e,Jn,"Reachable Range"),Xn=(...e)=>{const t=e.filter(e=>!!e);return t.length<2?t[0]:AbortSignal.any(t)},er=async(e,t)=>{const n=[];for(const o of e){const e=Xn(o.signal,t?.signal);try{n.push(await Qn({...o,...e&&{signal:e}}))}catch(a){if(!(a instanceof B)||403===a.status||429===a.status)throw a}}const r=o(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},tr={Country:"country",CountrySubdivision:"countrySubdivision",CountrySecondarySubdivision:"countrySecondarySubdivision",CountryTertiarySubdivision:"countryTertiarySubdivision",Municipality:"municipality",MunicipalitySubdivision:"municipalitySubdivision",MunicipalitySecondarySubdivision:"municipalitySecondarySubdivision",Neighbourhood:"neighborhood",PostalCodeArea:"postalCode"},nr={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"},rr=e=>nr[e]??e,or={street:"Street",area:"Geography",address:"Point Address"},ar=Object.fromEntries(Object.entries(tr).map(([e,t])=>[t,e])),ir=e=>{const{street:t,houseNumber:n,countryCodeIso2:r,...o}=e;return{...o,...t&&{streetName:t},...n&&{streetNumber:n},...r&&{countryCode:r,countryCodeISO3:rr(r)}}},sr=C.object({position:ne}),cr=C.object({geographyTypes:C.array(C.enum(u)).optional(),heading:C.number().min(-360).max(360).optional(),radiusMeters:C.number().positive().max(5e6).optional(),view:C.enum(S).optional()}),ur={requestValidation:{schema:sr.extend(cr.shape)},buildRequest:e=>{const[t,n]=d(e.position),r=new URL((e=>Le(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=>tr[e]).join(",")),!A(e.heading)&&o.append("vehicleHeadingInDegrees",String(e.heading)),e.view&&o.append("geopoliticalView",e.view),{url:r,headers:{...Re(e),Attributes:"results(*)"}}},getAPIVersion:()=>2,sendRequest:Z,parseResponse:(e,t)=>{const n=e.results[0];return{type:"Feature",geometry:I(d(t.position)),id:n?.id??s(),...n&&{properties:{type:or[n.type],address:{freeformAddress:n.title,...ir(n.address)},...n.areaType&&{geographyType:[ar[n.areaType]],dataSources:{geometry:{id:n.id}}},...n.accessPoints?.length&&{entryPoints:n.accessPoints.map(e=>({position:e.position.coordinates}))},originalPosition:n.position.coordinates}}}}},lr=async e=>W(e,ur,"ReverseGeocode"),dr=["tollVignette","tollRoad","roadShields","importantRoadStretch"],pr=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 dr)(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},mr=e=>{const t=e.state?.heading;return{...Vn(e),...!A(t)&&{vehicleHeadingInDegrees:t}}},gr=(e,t)=>{Yn(e,t),qt(e.searchParams,(e=>{const t=Vt(e),n={};if(!t)return n;const r=t;if(!A(r.minChargeAtDestinationInkWh)||!A(r.minChargeAtChargingStopsInkWh))return Bt(n,"minChargeAtDestinationInkWh",r.minChargeAtDestinationInkWh),Bt(n,"minChargeAtChargingStopsInkWh",r.minChargeAtChargingStopsInkWh),n;const o=Gt(e);if(!o)return n;const a=t;return A(a.minChargeAtDestinationPCT)||(n.minChargeAtDestinationInkWh=String(Ot(o,a.minChargeAtDestinationPCT))),A(a.minChargeAtChargingStopsPCT)||(n.minChargeAtChargingStopsInkWh=String(Ot(o,a.minChargeAtChargingStopsPCT))),n})(t))},hr=e=>!!e.vehicle&&!!Vt(e.vehicle),yr="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.",fr=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]}]},Tr=e=>{if(!Array.isArray(e)&&"properties"in e)return e.properties??void 0},Rr=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}}},Ir=(e,t)=>{t.computeTravelTimeFor&&e.searchParams.set("computeTravelTimeFor",t.computeTravelTimeFor)},br=C.union([ne,X]),Sr=C.union([Q,ee]),Cr=C.object({locations:C.array(C.union([br,Sr])).min(1)}),vr=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()}),Ar={schema:wn.extend(Cr.extend(vr.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||hr(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&&jn(e.vehicle))||hr(e),message:yr},{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."}]},Pr={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"},Lr=new Map(Object.entries(Pr)),Mr=new Map(b.map(e=>[Pr[e],e])),Er=new Map(Object.entries({unknown:"unknown",minor:"minor",moderate:"moderate",major:"major",undefined:"indefinite"})),wr=e=>Lr.get(e)??e,Dr=e=>Mr.get(e)??"other",Or=e=>Er.get(e)??"unknown",Nr=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},xr=(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:Nr(n.chargingCurrentType),chargingSpeed:Ne(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:Ne(e.chargingParkPowerInkW)}}}},Br=(e,t)=>{const n=t?.vehicle&&Gt(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:xr(e.chargingInformationAtEndOfLeg,n)}}},Hr=(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 u=((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:l}=r.summary;return n.push({...!A(i)&&{startPointIndex:i},...void 0!==c&&{endPointIndex:c},...!A(l)&&{originalWaypointIndex:l},summary:{...Br(r.summary,t),...void 0!==u&&{stopTimeInSeconds:u}},id:s()}),n},[]),_r=e=>({id:s(),startPointIndex:e.startPathIndex,endPointIndex:e.endPathIndex}),Fr=(e,t)=>{const n={leg:Hr(e.legs,t)},r=e.sections;if(!r)return n;const o=(e,t)=>{t?.length&&(n[e]=t.map(_r))};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=>({..._r(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:rr(e.countryCodeIso2??"")}))),r.travelMode?.length&&(n.vehicleRestricted=r.travelMode.filter(e=>"other"===e.travelMode).map(_r)),r.traffic?.length&&(n.traffic=r.traffic.map(e=>{return{..._r(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"}}):[Dr(t.iconCategory)]),magnitudeOfDelay:Or(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:{..._r(e),maxSpeedLimitInKmh:t}}).filter(e=>!!e)),r.lanes?.length&&(n.lanes=r.lanes.map(e=>({..._r(e),lanes:(e.lanes??[]).map(e=>({directions:e.directions.map(e=>Vr[e]??e),...e.follow&&{follow:Vr[e.follow]??e.follow}})),laneSeparators:(e.laneSeparators??[]).map(e=>qr[e]??e),properties:e.properties}))),r.roadShields?.length&&(n.roadShields=r.roadShields.map(e=>({..._r(e),roadShieldReferences:e.roadShieldReferences}))),r.tollVignette?.length&&(n.tollVignette=r.tollVignette.map(e=>({..._r(e),countryCodeISO2:e.countryCodeIso2??"",countryCodeISO3:rr(e.countryCodeIso2??"")}))),r.importantRoadStretch?.length&&(n.importantRoadStretch=r.importantRoadStretch.map(e=>({..._r(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},Ur=1e-4,Gr=(e,t)=>Math.abs(e[0]-t[0])<Ur&&Math.abs(e[1]-t[1])<Ur,kr={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"},Kr={urban:"URBAN",motorway:"MOTORWAY",controlledAccess:"CONTROLLED_ACCESS"},Wr={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"},jr={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"},Vr={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"},qr={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"},Yr={straight:"STRAIGHT",slightRight:"SLIGHT_RIGHT",right:"RIGHT",sharpRight:"SHARP_RIGHT",slightLeft:"SLIGHT_LEFT",left:"LEFT",sharpLeft:"SHARP_LEFT",back:"BACK"},$r={regular:"REGULAR",small:"SMALL"},Zr={left:"LEFT",right:"RIGHT",leftAndRight:"LEFT_AND_RIGHT"},zr={properties:[]},Jr=e=>({text:e.text}),Qr=e=>({properties:(e.properties??[]).map(e=>Kr[e]??e.toUpperCase()),...e.roadNames?.length&&{streetName:Jr(e.roadNames[0].identifier)},...e.countryCodeIso2&&{countryCode:rr(e.countryCodeIso2)},...e.roadShields?.length&&{roadShields:e.roadShields.map(e=>({roadNumber:e.roadNumber?Jr(e.roadNumber):{text:""},countryCode:rr(e.countryCodeIso2??""),...e.countrySubdivisionCodeIso&&{stateCode:e.countrySubdivisionCodeIso},...e.iconReference&&{roadShieldReference:e.iconReference}}))}}),Xr=e=>({...e.tollgateName&&{tollgateName:Jr(e.tollgateName)},...e.tollPaymentTypes?.length&&{tollPaymentTypes:e.tollPaymentTypes.map(e=>jr[e]??e)},...e.countryCrossingFromName&&{countryCrossingFromName:Jr(e.countryCrossingFromName)},...e.countryCrossingFromCodeIso2&&{countryCrossingFromCode:rr(e.countryCrossingFromCodeIso2)},...e.countryCrossingToName&&{countryCrossingToName:Jr(e.countryCrossingToName)},...e.countryCrossingToCodeIso2&&{countryCrossingToCode:rr(e.countryCrossingToCodeIso2)}}),eo=e=>Yr[e]??e,to=e=>{return{...e.message&&{message:e.message},...e.intersectionName&&{intersectionName:Jr(e.intersectionName)},...e.drivingSide&&{drivingSide:e.drivingSide.toUpperCase()},...e.landmark&&{landmark:Wr[e.landmark]??e.landmark},...!A(e.distanceToPreviousTrafficLightInMeters)&&{trafficLightOffsetInMeters:e.distanceToPreviousTrafficLightInMeters},...e.sideRoads&&{sideRoads:(n=e.sideRoads,n.map(e=>({side:Zr[e.side]??e.side,offsetFromManeuverInMeters:e.offsetFromManeuverInMeters,...!A(e.isDrivable)&&{isDrivable:e.isDrivable}})))},...e.maneuverView&&{maneuverView:(t=e.maneuverView,{...t.onRouteAngle&&{onRouteAngle:eo(t.onRouteAngle)},offRouteAngles:(t.offRouteAngles??[]).map(eo)})},...e.roundaboutType&&{roundaboutType:$r[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},no=(e,t)=>{const n=e.signpost?(e=>{if(e.exitName||e.exitNumber||e.towardName)return{...e.exitName&&{exitName:Jr(e.exitName)},...e.exitNumber&&{exitNumber:Jr(e.exitNumber)},towardName:e.towardName?Jr(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]}}},ro=(e,t,n,r)=>({maneuverPoint:t,pathPointIndex:n,routeOffsetInMeters:e.routeOffsetInMeters,maneuver:e.maneuver?kr[e.maneuver]??e.maneuver:e.maneuver,routePath:(e.routePath??[]).map(e=>({point:e.point.coordinates,distanceInMeters:e.distanceFromRouteStartInMeters,travelTimeInSeconds:e.travelTimeFromRouteStartInSeconds})),nextRoadInfo:e.nextRoadInformation?Qr(e.nextRoadInformation):zr,previousRoadInfo:e.previousRoadInformation?Qr(e.previousRoadInformation):zr,...to(e),...no(e,r),...Xr(e)}),oo=(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(Gr(t[n],e)){o=n;break}r.push(ro(a,e,o,n))}return{instructions:r}},ao={requestValidation:Ar,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=Tr(r),o=e?.candidateEntryPoints?.length?"ignore":t,[a,i]=d(r,{useEntryPoint:o});n.push({coordinate:[a,i],...e&&{options:e}})}else n.push(...fr(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{...Wn(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=>({...Re(e),Attributes:pr(e)}))(e),s=((e,t)=>{const n=e.slice(1).map((t,n)=>({...e[n].legToNext,...Rr(t)}));if(t||!n.every(e=>0===Object.keys(e).length))return n})(n,t),c={routePlanningLocations:r,...a,...s&&{legs:s},...e.vehicle&&mr(e.vehicle)};if(hr(e)){const t=((e,t,n)=>{const r=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateLongDistanceEVRoute`,o=new URL(r);gr(o,e.vehicle),e.chargingStopsStrategy&&o.searchParams.set("chargingStopsStrategy",e.chargingStopsStrategy);const a=xt(e.vehicle)?.charging;if(!jn(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 Ir(t.url,e),t}if(e.vehicle&&jn(e.vehicle))throw new Error(yr);const u=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/routes/calculate`,l=new URL(u);return e.vehicle&&qn(l,e.vehicle),Ir(l,e),{method:"POST",url:l,data:c,headers:i}},sendRequest:J,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:Br(e.summary,n),sections:Fr(e,n),...e.instructions?.length&&{guidance:oo(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:Dt,getAPIVersion:()=>3},io=async e=>W(e,ao,"Routing"),so=C.object({minFuzzyLevel:C.number().min(1).max(4).optional(),maxFuzzyLevel:C.number().min(1).max(4).optional()}),co=ce.extend(nt.extend(so.shape).shape),uo=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},lo={requestValidation:{schema:co},buildRequest:e=>{const t=new URL(`${(e=>Le(e,`search/${encodeURIComponent(e.query??"")}.json`))(e)}`);Pe(t,e);const n=t.searchParams;return ve(n,"typeahead",e.typeahead),ve(n,"ofs",e.offset),Ce(n,"countrySet",e.countries),Ae(n,e.geoBias),ve(n,"minFuzzyLevel",e.minFuzzyLevel),ve(n,"maxFuzzyLevel",e.maxFuzzyLevel),{url:t,headers:be(e)}},sendRequest:Z,parseResponse:e=>{const t=e.results.map(ke),n=a(o(t)),r=e.summary.queryIntent?.map(uo);return{type:"FeatureCollection",properties:{...Ke(e.summary),...r&&{queryIntent:r}},features:t,...n&&{bbox:n}}}},po=C.object({geometries:C.array(C.union([te,X]))}),mo=ce.extend(po.shape),go=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:Be(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:fe(e.coordinates[0],50).map(e=>Be(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=>go({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>go({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>go(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},ho={requestValidation:{schema:mo},buildRequest:e=>{const t=new URL(`${n=e,Le(n,`geometrySearch/${encodeURIComponent(n.query??"")}.json`)}`);var n;return Pe(t,e),{url:t,headers:be(e),data:{geometryList:e.geometries.flatMap(go)}}},sendRequest:z,parseResponse:e=>{const t=e.results.map(ke),n=a(o(t));return{type:"FeatureCollection",properties:{...Ke(e.summary)},features:t,...n&&{bbox:n}}}},yo=async e=>"route"in e?je(e):"geometries"in e?(async e=>W(e,ho,"GeometrySearch"))(e):(async e=>W(e,lo,"FuzzySearch"))(e),fo=async e=>Xe("discoverOnePlace",e,yo),To=C.object({query:C.string()}),Ro=C.object({geoBias:et.optional(),limit:C.number().max(100).optional(),countries:C.array(C.string()).optional(),resultTypes:C.array(C.string()).optional()}),Io=To.extend(Ro.shape),bo={requestValidation:{schema:Io},buildRequest:e=>{const t=new URL(`${n=e,Le(n,`autocomplete/${encodeURIComponent(n.query)}.json`)}`);var n;const r=t.searchParams;return e.language=e.language??"en-GB",Se(r,e),ve(r,"limit",e.limit),Ae(r,e.geoBias),Ce(r,"countrySet",e.countries),Ce(r,"resultSet",e.resultTypes),{url:t,headers:be(e)}},sendRequest:Z,parseResponse: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:R[Number(t)]}}return e})})))};var r}},So=async e=>W(e,bo,"Autocomplete"),Co=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean),vo=e=>"category"===e.type&&e.matchedAlternativeName?[e.value,e.matchedAlternativeName]:[e.value],Ao=(e,t)=>{const n=t.flatMap(({segments:t})=>{const[n]=t;return 1===t.length&&"plaintext"!==n.type&&vo(n).some(t=>((e,t)=>{const n=Co(t).join(""),r=Co(e);return""!==n&&r.some((e,t)=>r.slice(t).join("").startsWith(n))})(t,e))?[n]:[]});return n.find(t=>vo(t).some(t=>((e,t)=>{const[n,...r]=Co(t);return 0===r.length&&Co(e).some(e=>e.startsWith(n)&&2*n.length>=e.length)})(t,e)))??n[0]},Po=({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=Co(e);return Co(t).every(e=>n.some(t=>t.startsWith(e)))})(t.title,e)).flat();return[..."shown"===t.status?[t.suggestion]:[],...a].slice(0,r)},Lo="SearchSuggestions",Mo={brand:!0,category:!0},Eo=e=>e in Mo,wo={place:["POI"],address:["PAD","Addr","XStr"],street:["Str"],area:["Geo"]},Do={POI:"place",Street:"street",Geography:"area","Point Address":"address","Address Range":"address","Cross Street":"address"},Oo=e=>e*Math.PI/180,No=(e,t)=>e.properties.distance??(t&&(([e,t],[n,r])=>{const o=Math.sin(Oo(r-t)/2)**2+Math.cos(Oo(t))*Math.cos(Oo(r))*Math.sin(Oo(n-e)/2)**2;return 12742017.6*Math.asin(Math.sqrt(o))})(t,e.geometry.coordinates)),xo=(e,t)=>{const n=l(t)??void 0,r=((e,t)=>{if(t)return L(e,e=>No(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,u=o.countryCode!==t?o.country:void 0;return{kind:Do[r],id:String(e.id),title:s,subtitles:u?[...c,u]:c,distanceInMeters:No(e,n),resolve:async()=>({...e,properties:M(e.properties,["distance","score"])})}})(e,r,n))},Bo=e=>{if(e instanceof H)throw new H(Lo,e.cause);if(e instanceof B)throw new B(e.message,Lo,e.status);if(e instanceof N)throw new N(e.message,Lo,e.issues);throw e},Ho=(e,t)=>{const n={...t,..."brand"===e.type?{poiBrands:[e.value]}:{poiCategories:[e.category]}},r={title:e.value,refineParams:n,refine:e=>yo({...n,...e&&{signal:e}})};return"brand"===e.type?{...r,kind:"brand"}:{...r,kind:"category",category:e.category}},_o=(e,t)=>D(e.flatMap(e=>e.segments.flatMap(e=>"plaintext"===e.type?[]:[Ho(e,t)])),e=>`${e.kind}:${e.title}`),Fo=(e,t,n,r)=>{const o=Ao(e,t);return o?"brand"!==o.type||((e,t)=>{const n=Co(e).join("");return t.slice(0,5).some(e=>e.properties.poi?.brands?.some(e=>Co(e).join("")===n))})(o.value,n)?{status:"shown",suggestion:Ho(o,r)}:{status:"withheld"}:{status:"none"}},Uo=async e=>{const{query:t,maxResults:n,filters:r,origin:o,view:a,signal:i,...s}=e,c=r?.countries,u=Math.max(1,Math.min(n??5,10)),{placeKinds:l,refinementKinds:d,wantsPlaces:p,wantsRefinements:m}=(e=>{const t=e?.filter(e=>!Eo(e)),n=e?.filter(Eo);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:l?.flatMap(e=>wo[e]),poiCategories:r?.poiTypes,geographyTypes:r?.areaTypes},[T,R]=await Promise.all([p?yo(f):void 0,m?So({...s,signal:i,query:t,limit:u,countries:c,geoBias:g,resultTypes:d??["brand","category"]}):void 0]).catch(Bo),I=R?.results??[];if(!p)return{suggestions:_o(I,y).slice(0,u)};const b=(T?.features??[]).filter(e=>!l||l.includes(Do[e.properties.type]));return{suggestions:Po({query:t,concept:Fo(t,I,b,y),places:xo(b,o),maxResults:u})}},Go=864e5,ko=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n},Ko=e=>ko(/* @__PURE__ */new Date,-e),Wo=e=>e instanceof Date?e.toISOString().slice(0,10):e,jo=e=>Date.parse(Wo(e)),Vo=/(?:Z|[+-]\d{2}:\d{2})$/,qo=e=>new Date(Vo.test(e)?e:`${e}Z`),Yo=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],$o={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"}},Zo=Array.from({length:24},(e,t)=>t),zo=e=>Yo.indexOf(e),Jo=(e,n)=>{const r={};for(const o of t){const t=e[$o[o].field];void 0!==t&&(r[o]=n(t))}return r},Qo=e=>Jo(e,e=>e),Xo=e=>t.find(t=>$o[t].dataType===e),ea=e=>{const t=qo(e);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,date:new Date(jo(t)),hour:t.getUTCHours()}},ta={yearly:({year:e})=>({year:e}),monthly:({year:e,month:t})=>({year:e,month:t}),weekly:({date:e})=>(e=>{const t=ko(e,4-(e.getUTCDay()||7)),n=t.getUTCFullYear(),r=(t.getTime()-Date.UTC(n,0,1))/Go;return{year:n,week:Math.floor(r/7)+1}})(e),daily:({date:e})=>({date:e}),hourly:({date:e,hour:t})=>({date:e,hour:t})},na=(e,t)=>e.map(e=>({...ta[t](ea(e.time)),...Qo(e)})),ra={MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,SUNDAY:7},oa=e=>{const[t,n]=e.time.split("-"),r=Object.hasOwn(ra,t)?ra[t]:void 0;return void 0===r?void 0:{day:r,hour:Number(n),...Qo(e)}},aa=({day:e,hour:t})=>24*(e-1)+t,ia=e=>({tileCentre:[e.lon,e.lat],...Qo(e)}),sa=e=>({startDate:qo(e.startDate),endDate:qo(e.endDate),labels:e.labels.map(({name:e})=>e)}),ca=e=>{return{...e.yearly&&{yearly:na(e.yearly,"yearly")},...e.monthly&&{monthly:na(e.monthly,"monthly")},...e.weekly&&{weekly:na(e.weekly,"weekly")},...e.daily&&{daily:na(e.daily,"daily")},...e.hourly&&{hourly:na(e.hourly,"hourly")},...e.average&&{average:(t=e.average,t.map(oa).filter(e=>void 0!==e).sort((e,t)=>aa(e)-aa(t)))}};var t},ua=e=>Jo(e,e=>e.map(sa)),la=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:Qo(t.baseData),timedData:ca(t.timedData),...t.tiledData&&{tiledData:{tiles:t.tiledData.tiles.map(ia)}},...t.anomalies&&{anomalies:ua(t.anomalies)}}),bbox:o(e.geometry)};var t},da=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},pa=e=>{const t=e.map(jo);return{startDate:new Date(Math.min(...t)),endDate:new Date(Math.max(...t))}},ma=C.union([C.date(),C.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),ga=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)})]),ha=e=>jo(e)<=jo(Ko(2)),ya={requestValidation:{schema:G.extend({name:C.string().optional(),startDate:ma.optional(),endDate:ma.optional(),days:C.array(ma).min(1).optional(),metrics:C.union([C.array(C.enum(t)).min(1),C.literal("all")]),functionalRoadClasses:C.union([C.array(C.enum(Yo)).min(1),C.literal("all")]),hours:C.union([C.array(C.number().int().min(0).max(23)).min(1),C.literal("all")]),geometry:ga}).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??Ko(3),n=(jo(t)-jo(e.startDate))/Go;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(ha):void 0===e.endDate||ha(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));Ie(n.searchParams,e);const r=Array.isArray(e.days)?{days:e.days.map(Wo)}:{startDate:Wo(e.startDate??Ko(4)),endDate:Wo(e.endDate??Ko(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=>$o[e].dataType),frcs:"all"===e.functionalRoadClasses?Yo.map((e,t)=>t):e.functionalRoadClasses.map(zo),hours:"all"===e.hours?Zo:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},sendRequest:J,parseResponse:e=>{const t=e.features.map(la);return{type:"FeatureCollection",properties:{...pa(e.properties.days),metrics:e.properties.dataTypes.map(Xo).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:da(t)},features:t}}},fa=async e=>W(e,ya,"TrafficAreaAnalytics"),Ta=["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(","),Ra=e=>({description:e.description,code:e.code,category:Dr(e.iconCategory)}),Ia=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:Dr(t.iconCategory),magnitudeOfDelay:Or(t.magnitudeOfDelay),events:(t.events??[]).map(Ra),...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)}}}},ba={requestValidation:{schema:G.extend({bbox:ae.optional(),ids:C.array(C.string()).optional(),categoryFilter:C.array(C.enum(b)).optional(),timeValidityFilter:C.array(C.enum(["present","future"])).optional()}).refine(e=>!(e.bbox&&e.ids),{message:"Provide either bbox or ids, not both"})},getAPIVersion:()=>2,buildRequest:e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidents/details`)(e)),n=t.searchParams;((e,t)=>{Ce(e,"iconCategories",t.categoryFilter?.map(wr)),Ce(e,"timeValidity",t.timeValidityFilter)})(n,e);const r=(e=>({...Re(e),Attributes:Ta}))(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=o(e.bbox);return a&&n.append("bbox",a.join(",")),{method:"GET",url:t,headers:r}},sendRequest:J,parseResponse:e=>({type:"FeatureCollection",features:(e.incidents??[]).filter(e=>null!==e).map(Ia)})},Sa=async e=>W(e,ba,"TrafficIncidentDetails");export{x as APIErrorCode,H as SDKAbortError,N as SDKError,B as SDKServiceError,je as alongRouteSearch,Dn as budgetTypes,F as buildResponseError,U as buildValidationError,Qn as calculateReachableRange,er as calculateReachableRanges,io as calculateRoute,fo as discoverOnePlace,yo as discoverPlaces,Ze as evChargingStationsAvailability,it as geocode,st as geocodeOne,mt as geometryData,Et as getPOICategories,wt as getPOICategoryCodes,Tt as getPlaceDetails,ze as getPlaceWithEVAvailability,Je as getPlacesWithEVAvailability,Uo as getSearchSuggestions,Qe as hasChargingAvailability,_ as parseDefaultResponseError,lr as reverseGeocode,qe as routeTypes,Ye as tollTransponderOptions,fa as trafficAreaAnalytics,Sa as trafficIncidentDetails};
|
|
2
2
|
//# sourceMappingURL=services.es.js.map
|