@tomtom-org/maps-sdk 0.47.5 → 0.47.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@tomtom-org/maps-sdk",
3
3
  "author": "TomTom International B.V.",
4
4
  "license": "See in LICENSE.txt",
5
- "version": "0.47.5",
5
+ "version": "0.47.6",
6
6
  "description": "TomTom Maps for JavaScript",
7
7
  "keywords": [
8
8
  "tomtom",
@@ -405,6 +405,27 @@ declare type AreaAnalyticsResponseAPI = {
405
405
  features: AreaAnalyticsFeatureAPI[];
406
406
  };
407
407
 
408
+ /**
409
+ * Area-tag token accepted by the places-api `area_tags` filter and
410
+ * returned on each hit's `areaTags` property.
411
+ *
412
+ * Resolves to the canonical {@link CanonicalAreaTag} union for editor
413
+ * autocompletion, but tolerates any other string so the SDK doesn't
414
+ * hard-error on tokens added in a future pipeline run. To strictly
415
+ * constrain inputs to the currently-known vocabulary, use
416
+ * {@link CanonicalAreaTag} (or {@link PopulatedAreaTag}) directly.
417
+ *
418
+ * @example
419
+ * ```typescript
420
+ * // Autocomplete on the canonical vocabulary, but new tokens still type-check.
421
+ * const tags: AreaTag[] = ['walkable', 'transit_connected'];
422
+ * ```
423
+ *
424
+ * @ignore
425
+ * @experimental
426
+ */
427
+ export declare type AreaTag = CanonicalAreaTag | string;
428
+
408
429
  /**
409
430
  * Base properties shared across all autocomplete segment types.
410
431
  *
@@ -1554,6 +1575,15 @@ declare type CalculateRouteResponseAPI = {
1554
1575
  */
1555
1576
  declare type CalculateRouteTemplate = ServiceTemplate<CalculateRouteParams, FetchInput<CalculateRoutePOSTDataAPI>, CalculateRouteResponseAPI, Routes>;
1556
1577
 
1578
+ /**
1579
+ * Union of every canonical (populated + reserved) area-tag token. Reserved
1580
+ * tokens may begin appearing as the pipeline evolves.
1581
+ *
1582
+ * @ignore
1583
+ * @experimental
1584
+ */
1585
+ export declare type CanonicalAreaTag = PopulatedAreaTag | (typeof RESERVED_AREA_TAGS)[number];
1586
+
1557
1587
  /**
1558
1588
  * @ignore
1559
1589
  */
@@ -4077,12 +4107,66 @@ export declare type ExplorationClassificationAPI = {
4077
4107
 
4078
4108
  /**
4079
4109
  * @ignore
4080
- * Raw TomTom opening-hours payload. The API exposes the compact string form
4081
- * (`raw`) plus the 24h flag; no parsed time ranges yet.
4110
+ * Opening-hours payload as returned by the places-api. The compact raw
4111
+ * TomTom hours string is parsed upstream into structured `intervals`; the
4112
+ * source string is not exposed in the API response.
4082
4113
  */
4083
4114
  export declare type ExplorationOpeningHoursAPI = {
4084
- raw: string;
4085
4115
  is24h?: boolean;
4116
+ intervals?: ExplorationOpeningIntervalAPI[];
4117
+ };
4118
+
4119
+ /**
4120
+ * @ignore
4121
+ * A single open interval inside {@link ExplorationOpeningHoursAPI.intervals}.
4122
+ *
4123
+ * - `days` — ISO day-of-week numbers `1` (Monday) through `7` (Sunday) the
4124
+ * interval applies to.
4125
+ * - `open` / `close` — `HH:MM` strings. `"24:00"` denotes end-of-day so that
4126
+ * round-the-clock intervals can be expressed as `00:00` → `24:00`.
4127
+ */
4128
+ export declare type ExplorationOpeningIntervalAPI = {
4129
+ days: number[];
4130
+ open: string;
4131
+ close: string;
4132
+ };
4133
+
4134
+ /**
4135
+ * Additional properties exposed on each feature in an exploration search
4136
+ * response. The places-api propagates "area" metadata from the municipality
4137
+ * polygon each hit sits in (currently populated for `DE` / `NL` / `FR`); the
4138
+ * SDK surfaces those fields alongside the standard {@link SearchPlaceProps}.
4139
+ *
4140
+ * The `address` is widened from the SDK's standard {@link AddressProperties}
4141
+ * to also expose the optional `entryPoint` string the places-api emits on
4142
+ * `PointAddress` records.
4143
+ *
4144
+ * @ignore
4145
+ * @experimental
4146
+ */
4147
+ export declare type ExplorationPlaceProps = Omit<SearchPlaceProps, 'address'> & {
4148
+ address: AddressProperties & {
4149
+ entryPoint?: string;
4150
+ };
4151
+ /**
4152
+ * Id of the municipality polygon this hit sits inside. Round-trips into
4153
+ * `areaId` on a subsequent request to fetch every other place in the
4154
+ * same municipality.
4155
+ */
4156
+ areaId?: string;
4157
+ /**
4158
+ * ISO 3166-1 alpha-2 country code of the hit's municipality polygon.
4159
+ */
4160
+ areaCountry?: string;
4161
+ /**
4162
+ * Area-character tokens describing the surrounding municipality
4163
+ * (e.g. `coastal`, `walkable`, `transit_connected`).
4164
+ *
4165
+ * Typed against {@link AreaTag} for editor autocompletion on the
4166
+ * canonical vocabulary; arbitrary strings stay compatible to
4167
+ * tolerate future pipeline-run additions.
4168
+ */
4169
+ areaTags?: AreaTag[];
4086
4170
  };
4087
4171
 
4088
4172
  /**
@@ -4187,6 +4271,8 @@ export declare const explorationSearch: (params: ExplorationSearchParams, custom
4187
4271
  * - `geometries` → `geometries` (Polygon/MultiPolygon passed through; Circle
4188
4272
  * buffered to a Polygon; FeatureCollection flattened to its features)
4189
4273
  * - `municipalities` → `municipalities`
4274
+ * - `areaId` → `area_id`
4275
+ * - `areaTags` → `area_tags`
4190
4276
  * - `offset` → `from`
4191
4277
  * - `limit` → `size`
4192
4278
  *
@@ -4231,6 +4317,25 @@ export declare type ExplorationSearchParams = CommonSearchParams<ExplorationSear
4231
4317
  * Example: `placeTypes: ['POI', 'PointAddress']` to exclude Street records.
4232
4318
  */
4233
4319
  placeTypes?: ExplorationRecordType[];
4320
+ /**
4321
+ * Exact id of a municipality polygon — restricts results to places that
4322
+ * sit inside that municipality. Typically populated from the `areaId`
4323
+ * of a previous hit ("what else is in this same area?"). Efficient
4324
+ * terms-only lookup, no spatial query required.
4325
+ */
4326
+ areaId?: string;
4327
+ /**
4328
+ * Area-character tokens describing the surrounding municipality
4329
+ * (`coastal`, `walkable`, `alpine`, `transit_connected`, …). Matches
4330
+ * places in any municipality tagged with ANY of the supplied tokens
4331
+ * (OR semantics). Populated for `DE` / `NL` / `FR` only — supplying
4332
+ * tags in other countries will return zero hits.
4333
+ *
4334
+ * Typed against {@link AreaTag} — autocompletes on the canonical
4335
+ * vocabulary but tolerates new tokens added in a future pipeline
4336
+ * run without a wire-protocol change.
4337
+ */
4338
+ areaTags?: AreaTag[];
4234
4339
  };
4235
4340
 
4236
4341
  /**
@@ -4243,6 +4348,8 @@ export declare type ExplorationSearchPayloadAPI = {
4243
4348
  brand?: string;
4244
4349
  categories?: string[];
4245
4350
  types?: ExplorationRecordType[];
4351
+ area_id?: string;
4352
+ area_tags?: AreaTag[];
4246
4353
  near?: NearAPI;
4247
4354
  bboxes?: BBox[];
4248
4355
  geometries?: (Polygon | MultiPolygon)[];
@@ -4261,12 +4368,14 @@ export declare type ExplorationSearchRequestAPI = PostObject<ExplorationSearchPa
4261
4368
  *
4262
4369
  * Matches the shape produced by {@link search} — a `FeatureCollection` of
4263
4370
  * place features with search-specific properties (`score`, `distance`) and a
4264
- * {@link SearchSummary} on the collection.
4371
+ * {@link SearchSummary} on the collection — extended with the
4372
+ * exploration-specific `areaId` / `areaCountry` / `areaTags` fields on each
4373
+ * feature.
4265
4374
  *
4266
4375
  * @ignore
4267
4376
  * @experimental
4268
4377
  */
4269
- export declare type ExplorationSearchResponse = Places<SearchPlaceProps, SearchSummary>;
4378
+ export declare type ExplorationSearchResponse = Places<ExplorationPlaceProps, SearchSummary>;
4270
4379
 
4271
4380
  /**
4272
4381
  * @ignore
@@ -4309,6 +4418,12 @@ export declare type ExplorationSearchResultAPI = {
4309
4418
  placeId?: string;
4310
4419
  adminChainId?: string;
4311
4420
  poi?: ExplorationPOIAPI;
4421
+ /** Id of the municipality polygon the hit sits in. Populated for DE / NL / FR only. */
4422
+ area_id?: string;
4423
+ /** ISO2 country of the municipality polygon the hit sits in. Populated for DE / NL / FR only. */
4424
+ area_country?: string;
4425
+ /** Area-character tokens propagated from the hit's municipality polygon. Populated for DE / NL / FR only. */
4426
+ area_tags?: string[];
4312
4427
  };
4313
4428
 
4314
4429
  /**
@@ -6470,6 +6585,42 @@ export declare type PolygonAPI = {
6470
6585
  vertices: string[];
6471
6586
  };
6472
6587
 
6588
+ /**
6589
+ * Canonical area-tag vocabulary used by the places-api. Tokens are
6590
+ * lowercase `snake_case` and describe the character of the municipality
6591
+ * polygon a hit sits in (currently populated for `DE` / `NL` / `FR`).
6592
+ *
6593
+ * Two groups are exposed below:
6594
+ *
6595
+ * - **Populated tokens** — the 46 tokens the current pipeline run actually
6596
+ * emits, grouped by classification axis (settlement scale, density,
6597
+ * terrain, tourism, etc.). These are what every live `area_tags` value
6598
+ * will be drawn from today.
6599
+ * - **Reserved tokens** — vocabulary tokens that exist canonically but
6600
+ * are not populated by the current pipeline run. They may appear in
6601
+ * future runs without an API change, so callers should treat them as
6602
+ * valid even though no hit returns them today.
6603
+ *
6604
+ * The schema doc warns the vocabulary may shift between pipeline
6605
+ * iterations, so SDK consumers should code defensively. The
6606
+ * {@link AreaTag} alias falls back to `string` to keep arbitrary
6607
+ * (yet-to-be-added) tokens type-compatible without losing IDE
6608
+ * autocompletion on the known set.
6609
+ *
6610
+ * @ignore
6611
+ * @experimental
6612
+ */
6613
+ declare const POPULATED_AREA_TAGS: readonly ["village", "small_town", "mid_town", "suburban", "rural", "semi_rural", "residential", "inland", "coastal", "atlantic_coast", "alpine", "mountain", "foothills", "forest", "plains", "farmland", "agricultural", "no_tourism", "low_tourism", "moderate_tourism", "tourism_economy", "eco_tourism", "heritage_tourism", "watersports", "hiking", "cycling", "industrial", "logistics_hub", "retail_hub", "shopping_district", "hospital_town", "dining_scene", "car_oriented", "walkable", "transit_connected", "transit_sparse", "highway_corridor", "commuter_town", "low_traffic", "moderate_traffic", "sparse_commercial", "western_europe", "central_europe", "southern_europe", "north_american", "iberian"];
6614
+
6615
+ /**
6616
+ * Union of every populated area-tag token currently emitted by the
6617
+ * places-api pipeline.
6618
+ *
6619
+ * @ignore
6620
+ * @experimental
6621
+ */
6622
+ export declare type PopulatedAreaTag = (typeof POPULATED_AREA_TAGS)[number];
6623
+
6473
6624
  /**
6474
6625
  * POST object with URL and optional payload.
6475
6626
  * @ignore
@@ -6869,6 +7020,18 @@ declare type RequestValidationConfig<Params = any> = {
6869
7020
  refinements?: SchemaRefinement<Params>[];
6870
7021
  };
6871
7022
 
7023
+ /**
7024
+ * Vocabulary tokens that exist canonically in the area-tag taxonomy but
7025
+ * aren't emitted by the current pipeline run (per the schema doc's
7026
+ * "tokens that exist… but are not populated" list). Filtering on these
7027
+ * today returns zero hits, but a future pipeline run may activate them
7028
+ * without a wire-protocol change.
7029
+ *
7030
+ * @ignore
7031
+ * @experimental
7032
+ */
7033
+ declare const RESERVED_AREA_TAGS: readonly ["lakefront", "riverine", "wetland", "marina", "harbor", "beach", "mediterranean", "ski_destination", "beach_destination", "wine_tourism", "vineyard", "university_town", "medieval_old_town", "unesco_site", "midwest_us", "rust_belt"];
7034
+
6872
7035
  /**
6873
7036
  * Convert geographic coordinates into human-readable addresses (reverse geocoding).
6874
7037
  *
@@ -1,2 +1,2 @@
1
- import{TomTomConfig as e,areaAnalyticsMetricKeys as t,avoidableTypes as n,bboxFromCoordsArray as r,bboxFromGeoJSON as a,bboxOnlyIfWithArea as o,currentTypes as i,generateId as s,generateTomTomHeaders as c,getPosition as p,getPositionStrict as u,getRoutePlanningLocationType as l,iconToTrafficIncidentCategory as d,indexedMagnitudes as m,inputSectionTypes as g,inputSectionTypesWithGuidance as y,mergeFromGlobal as h,plugTypes as f,poiCategories as b,poiCategoriesToID as T,poiIDsToCategories as R,toPointGeometry as v,trafficIncidentRequestCategories as S,trafficIncidentToIconCategory as C,views as P}from"@tomtom-org/maps-sdk/core";import{z as I}from"zod";import{isNil as x,omit as w}from"lodash-es";var A=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),L=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},D={[A.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[A.FORBIDDEN]:"Request failed with status code 403"},M=class extends L{constructor(e,t,n){super(e,t),this.status=n,this.status&&D[this.status]&&(this.message=D[this.status])}},E=(e,t)=>{const{data:n,message:r,status:a}=e;return new M(n?.error||n?.errorText||r,t,a)},O=(e,t,n)=>{if(e.status){const r=e;return n?n(r,t):E(r,t)}return new L(e.message,t)},F=(e,t)=>new L(e.message,t,e.issues),k=I.object({apiKey:I.string().optional(),commonBaseURL:I.string().optional(),customServiceBaseURL:I.string().optional(),language:I.string().optional()}),j=(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=>j(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},U=class extends Error{constructor(e){super(`${e.issues.map(e=>j(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},B=async(e,t,n)=>{const r=t.getAPIVersion?.(e),a=h({...e,...r&&{apiVersion:r}});if(void 0===e.validateRequest||e.validateRequest)try{((e,t)=>{const n=(t?.schema?k.extend(t.schema.shape):k).superRefine((e,n)=>{if("commonBaseURL"in e||"customServiceBaseURL"in e||n.addIssue({code:"custom",message:"commonBaseURL or customServiceBaseURL is required"}),t?.refinements?.length)for(const r of t.refinements)r.check(e)||n.addIssue({code:"custom",message:r.message})}).safeParse(e);if(!n.success)throw new U(n.error)})(a,t.requestValidation)}catch(s){throw F(s,n)}const o=t.buildRequest(a),i=c(a);e.onAPIRequest?.(o);try{const n=await t.sendRequest(o,i);return e.onAPIResponse?.(o,n),t.parseResponse(await n.data,a)}catch(s){throw e.onAPIResponse?.(o,s),O(s,n,t.parseResponseError)}},W=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)}},q=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 W(e.status,t,n)},N=async t=>{const n=e.instance.get().retry;if(!n)return t();const{initialWaitMs:r,backoffFactor:a,timeoutMs:o}=n,i=Date.now();let s=r,c=await t();for(;429===c.status;){const e=Number.parseInt(c.headers.get("retry-after")??"",10),n=Number.isFinite(e)?1e3*e:s;if(Date.now()-i+n>o)break;await c.text().catch(()=>{}),await new Promise(e=>setTimeout(e,n)),s*=a,c=await t()}return c},H=async(e,t)=>q(await N(()=>fetch(e,{headers:t}))),K=async(e,t)=>q(await N(()=>fetch(e.url,{method:"POST",body:JSON.stringify(e.data),headers:{...t,"Content-Type":"application/json"}}))),$=async(e,t)=>{const n=e.method;if("GET"===n)return H(e.url,t);if("POST"===n)return K(e,t);throw new Error(`Unsupported HTTP method received: ${n}`)},V=I.array(I.array(I.number())),_=I.object({type:I.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:I.union([I.array(I.number()),V,I.array(I.array(I.array(I.number()))),I.array(I.array(I.array(I.array(I.number()))))]),radius:I.optional(I.number()),radiusMeters:I.optional(I.number()),bbox:I.optional(I.array(I.number()))}).check(I.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),G=I.object({type:I.literal("Feature"),geometry:_,id:I.optional(I.union([I.string(),I.number()])),properties:I.unknown().optional(),bbox:I.optional(I.array(I.number()))}),z=I.object({type:I.literal("FeatureCollection"),features:I.array(G),id:I.optional(I.union([I.string(),I.number()])),properties:I.unknown().optional(),bbox:I.optional(I.array(I.number()))}),Y=I.union([I.tuple([I.number().min(-180).max(180),I.number().min(-90).max(90)]),I.tuple([I.number().min(-180).max(180),I.number().min(-90).max(90),I.number()]),I.object({type:I.literal("Point"),coordinates:I.array(I.number())}),G]),Z=I.union([I.array(I.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),I.array(I.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),J=I.union([_,G,z]),Q=I.union([Z,J,I.array(J)]),X=I.object({query:I.string().optional(),position:Y.optional(),limit:I.number().max(100).optional(),extendedPostalCodesFor:I.array(I.string()).optional(),mapcodes:I.array(I.string()).optional(),view:I.enum(P).optional(),geographyTypes:I.array(I.string()).optional()}),ee=I.object({indexes:I.array(I.string()).optional(),poiCategories:I.array(I.enum(b)).optional(),poiBrands:I.array(I.string()).optional(),connectors:I.array(I.string()).optional(),fuelTypes:I.array(I.string()).optional(),openingHours:I.string().optional(),timeZone:I.string().optional(),relatedPois:I.string().optional(),minPowerKW:I.number().optional(),maxPowerKW:I.number().optional(),minFuzzyLevel:I.number().optional(),maxFuzzyLevel:I.number().optional()}),te=X.extend(ee.shape),ne=I.object({type:I.literal("LineString"),coordinates:V}),re=I.object({type:I.literal("Feature"),geometry:ne}),ae=V,oe=I.union([ne,re,ae]),ie=I.object({route:oe,maxDetourTimeSeconds:I.number().int().positive()}),se=I.object({sortBy:I.enum(["detourTime","detourOffset"]).optional()}),ce=te.extend({...ie.shape,...se.shape}),pe=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),e.append("key",t.apiKey),t.language&&e.append("language",t.language)},ue=(e,t,n)=>{for(const r of n||[])e.append(t,r)},le=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},de=(e,t,n)=>{!x(n)&&e.append(t,String(n))},me=(e,t)=>{const n=p(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))},ge=(e,t)=>{const n=e.searchParams;pe(n,t),de(n,"limit",t.limit),me(n,"position"in t?t.position:void 0),le(n,"fuelSet",t.fuelTypes),le(n,"idxSet",t.indexes),le(n,"brandSet",t.poiBrands),t.poiCategories&&le(n,"categorySet",t.poiCategories.map(e=>T[e])),le(n,"connectorSet",t.connectors),le(n,"mapcodes",t.mapcodes),le(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),de(n,"minPowerKW",t.minPowerKW),de(n,"maxPowerKW",t.maxPowerKW),de(n,"view",t.view),de(n,"openingHours",t.openingHours),de(n,"timeZone",t.timeZone),de(n,"relatedPois",t.relatedPois),le(n,"entityTypeSet",t.geographyTypes)},ye=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/searchAlongRoute/${e.query??""}.json`)(e));ge(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),de(n,"sortBy",e.sortBy),de(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},he=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},fe=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,be=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>fe(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}:{}})}},Te=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>fe(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Re=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)be(e.connectors,e.status,t);return t},ve=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",Se=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},Ce=e=>`${e[1]},${e[0]}`,Pe=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=Se(e.southWest),n=Se(e.northEast)),[t[0],t[1],n[0],n[1]]},Ie=e=>[e.lon,e.lat],xe=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)}},we=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,Ae=e=>{const t=e.timeRanges.map(e=>({start:xe(e.startTime),end:xe(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:we(t)}},Le=e=>{const{position:t,entryPoints:n,poi:r,id:a,dist:o,boundingBox:i,chargingPark:s,...c}=e,p=s?.connectors?.map(e=>({...w(e,"connectorType"),type:e.connectorType,chargingSpeed:ve(e.ratedPowerKW)}));return{type:"Feature",geometry:v(Ie(t)),...i&&{bbox:Pe(i)},id:a,properties:{...w(c,"viewport"),...o&&{distance:o},...n?.length&&{entryPoints:n.map(e=>({...e,position:Ie(e.position)}))},...p?.length&&{chargingPark:{...s,connectors:Te(p)}},...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:Ae(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},De=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:Ie(t)},...n}},Me=e=>{const t=e.results.map(Le),n=o(a(t));return{type:"FeatureCollection",properties:{...De(e.summary)},features:t,...n&&{bbox:n}}},Ee={requestValidation:{schema:ce},buildRequest:ye,sendRequest:K,parseResponse:Me},Oe=async(e,t)=>B(e,{...Ee,...t},"AlongRouteSearch"),Fe=I.object({query:I.string()}),ke=I.object({position:Y.optional(),limit:I.number().max(100).optional(),radiusMeters:I.number().optional(),countries:I.array(I.string()).optional(),resultType:I.array(I.string()).optional()}),je=Fe.extend(ke.shape),Ue=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",pe(r,e),de(r,"limit",e.limit),me(r,e.position),le(r,"countrySet",e.countries),de(r,"radius",e.radiusMeters),le(r,"resultSet",e.resultType),t},Be=e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:Ie(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},We={requestValidation:{schema:je},buildRequest:Ue,sendRequest:H,parseResponse:Be},qe=async(e,t)=>B(e,{...We,...t},"Autocomplete"),Ne={alongRouteSearch:Oe,buildAlongRouteSearchRequest:ye,parseAlongRouteSearchResponse:Me,alongRouteSearchTemplate:Ee},He={autocompleteSearch:qe,buildAutocompleteSearchRequest:Ue,parseAutocompleteSearchResponse:Be,autocompleteSearchTemplate:We},Ke=k.extend({id:I.string()}),$e=["fast","short","efficient","thrilling"],Ve=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/ev/id`)(e)),n=t.searchParams;return pe(n,e),n.append("id",e.id),t},_e=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:ve(e.ratedPowerKW)}))}))}))),chargingPointAvailability:he(t.chargingStations),connectorAvailabilities:Re(t.chargingStations),...t.openingHours&&{openingHours:Ae(t.openingHours)}}:void 0;var n},Ge={requestValidation:{schema:Ke},buildRequest:Ve,sendRequest:H,parseResponse:_e,parseResponseError:(e,t)=>new M(e.data?.detailedError?.message??e.message,t,e.status)},ze={buildEVChargingStationsAvailabilityRequest:Ve,parseEVChargingStationsAvailabilityResponse:_e,evChargingStationsAvailabilityTemplate:Ge},Ye=I.object({typeahead:I.boolean().optional(),offset:I.number().max(1900).optional(),radiusMeters:I.number().optional(),boundingBox:Q.optional(),countries:I.array(I.string()).optional()}),Ze=k.extend(X.shape).extend(Ye.shape).extend({query:I.string()}),Je=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",Qe=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let a;const o=Math.ceil(n/t);for(a=0;a<n;a+=o)r.push(e[a]);return t>1&&a>=n-o&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},Xe=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/geocode`)(e)}/${e.query}.json`),n=t.searchParams;pe(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!x(e.limit)&&n.append("limit",String(e.limit)),!x(e.offset)&&n.append("ofs",String(e.offset)),me(n,e.position),e.countries&&n.append("countrySet",Je(e.countries)),!x(e.radiusMeters)&&n.append("radius",String(e.radiusMeters));const r=e.boundingBox&&a(e.boundingBox);return r&&(n.append("topLeft",Je([r[3],r[0]])),n.append("btmRight",Je([r[1],r[2]]))),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",Je(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",Je(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",Je(e.geographyTypes)),t},et=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:a,addressRanges:o,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:v(Ie(t)),...n&&{bbox:Pe(n)},id:s,properties:{...w(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...a&&{entryPoints:a.map(e=>({...e,position:Ie(e.position)}))},...o&&{addressRanges:{...o,from:Ie(o.from),to:Ie(o.to)}}}}},tt=e=>{const t=e.results.map(et),n=o(a(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}},nt={requestValidation:{schema:Ze},buildRequest:Xe,sendRequest:H,parseResponse:tt},rt={buildGeocodingRequest:Xe,parseGeocodingResponse:tt,geocodingTemplate:nt},at=I.object({geometries:I.union([z,I.array(I.union([I.string(),G])).min(1).max(20)])}),ot=I.object({zoom:I.number().min(0).max(22).optional()}),it=at.extend(ot.shape),st=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),ct=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)),n.append("key",e.apiKey),((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:st(t):st(t.features),e.append("geometries",Je(n))})(n,e.geometries),de(n,"geometriesZoom",e.zoom),t},pt=e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??s(),bbox:a(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:a(t),features:t}},ut={requestValidation:{schema:it},buildRequest:ct,sendRequest:H,parseResponse:pt},lt={buildGeometryDataRequest:ct,parseGeometryDataResponse:pt,geometryDataTemplate:ut},dt=I.object({geometries:I.array(I.union([z,_]))}),mt=te.extend(dt.shape),gt=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:Ce(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:Qe(e.coordinates[0],50).map(e=>Ce(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=>gt({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>gt({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>gt(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},yt=e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}/maps/orbis/places/geometrySearch/${n.query??""}.json`}`);var n;return ge(t,e),{url:t,data:{geometryList:e.geometries.flatMap(gt)}}},ht=e=>{const t=e.results.map(Le),n=o(a(t));return{type:"FeatureCollection",properties:{...De(e.summary)},features:t,...n&&{bbox:n}}},ft={requestValidation:{schema:mt},buildRequest:yt,sendRequest:K,parseResponse:ht},bt=async(e,t)=>B(e,{...ft,...t},"GeometrySearch"),Tt={geometrySearch:bt,buildGeometrySearchRequest:yt,parseGeometrySearchResponse:ht,geometrySearchTemplate:ft},Rt=I.object({entityId:I.string()}),vt=I.object({mapcodes:I.array(I.string()).optional(),view:I.enum(P).optional(),openingHours:I.string().optional(),timeZone:I.string().optional(),relatedPois:I.string().optional()}),St=Rt.extend(vt.shape),Ct=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/place.json`)(e)}`),n=t.searchParams;return pe(n,e),de(n,"entityId",e.entityId),le(n,"mapcodes",e.mapcodes),de(n,"view",e.view),de(n,"openingHours",e.openingHours),de(n,"timeZone",e.timeZone),de(n,"relatedPois",e.relatedPois),t},Pt=e=>e.results?.length?Le(e.results[0]):void 0,It={requestValidation:{schema:St},buildRequest:Ct,sendRequest:H,parseResponse:Pt},xt={buildPlaceByIdRequest:Ct,parsePlaceByIdResponse:Pt,placeByIdTemplate:It},wt=(e,t)=>{const{data:n,message:r,status:a}=e;return new M(n?.error?.description??n?.detailedError?.message??r,t,a)},At=I.number().positive(),Lt=I.number().min(0),Dt=I.number().min(0).max(100),Mt=At.optional(),Et=Lt.optional(),Ot=I.number().min(0).max(1).optional(),Ft=I.object({speedKMH:I.number(),consumptionUnitsPer100KM:I.number()}),kt={efficiency:I.object({acceleration:Ot,deceleration:Ot,uphill:Ot,downhill:Ot}).optional()},jt=I.array(Ft).min(1).max(25),Ut=I.object({...kt,speedsToConsumptionsLiters:jt,auxiliaryPowerInLitersPerHour:Et,fuelEnergyDensityInMJoulesPerLiter:I.number().min(1).optional()}),Bt=I.object({...kt,speedsToConsumptionsKWH:jt,auxiliaryPowerInkW:Et,consumptionInKWHPerKMAltitudeGain:I.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Et}),Wt=I.object({currentType:I.enum(i),plugTypes:I.array(I.enum(f)).min(1),efficiency:Ot,baseLoadInkW:Et,maxPowerInkW:Et,maxVoltageInV:Et,maxCurrentInA:Et,voltageRange:I.object({minVoltageInV:Et,maxVoltageInV:I.number().optional()}).optional()}),qt=I.object({stateOfChargeInkWh:Lt,maxPowerInkW:At}),Nt=I.object({maxChargeKWH:At,batteryCurve:I.array(qt).max(20).optional(),chargingConnectors:I.array(Wt).min(1).optional(),chargingTimeOffsetInSec:Et}),Ht=I.object({consumption:Ut}),Kt=I.object({consumption:Bt,charging:Nt.optional()}),$t=I.object({lengthMeters:Mt,widthMeters:Mt,heightMeters:Mt,weightKG:Mt,axleWeightKG:Mt}).optional(),Vt=I.object({variantId:I.string()}),_t=I.object({dimensions:$t,engine:I.union([Ht,Kt]).optional()}),Gt=I.union([Vt,_t]).optional(),zt=I.object({heading:I.number().min(0).max(360).optional()}),Yt=zt.extend({currentFuelInLiters:Lt}),Zt=zt.extend({currentChargePCT:Dt}),Jt=zt.extend({currentChargeInkWh:Lt}),Qt=I.union([Zt,Jt]),Xt=I.object({minChargeAtDestinationPCT:Dt,minChargeAtChargingStopsPCT:I.number().min(0).max(50)}),en=I.object({minChargeAtDestinationInkWh:Lt,minChargeAtChargingStopsInkWh:Lt}),tn=I.union([Xt,en]),nn=I.object({chargingPreferences:tn.optional()}),rn={model:Gt,restrictions:I.object({loadTypes:I.array(I.enum(["USHazmatClass1","USHazmatClass2","USHazmatClass3","USHazmatClass4","USHazmatClass5","USHazmatClass6","USHazmatClass7","USHazmatClass8","USHazmatClass9","otherHazmatExplosive","otherHazmatGeneral","otherHazmatHarmfulToWater"])).optional(),maxSpeedKMH:I.number().min(0).max(250).optional(),adrCode:I.enum(["B","C","D","E"]).optional(),commercial:I.boolean().optional()}).optional()},an=I.object({...rn,engineType:I.undefined().optional(),state:zt.optional(),preferences:I.object({}).optional()}),on=I.object({...rn,engineType:I.literal("combustion"),state:Yt.optional(),preferences:I.object({}).optional()}),sn=I.object({...rn,engineType:I.literal("electric"),state:Qt.optional(),preferences:nn.optional()}),cn=I.union([I.discriminatedUnion("engineType",[on,sn]),an]),pn=I.object({costModel:I.object({avoid:I.array(I.enum(n)).optional(),traffic:I.enum(["live","historical"]).optional(),routeType:I.enum($e).optional(),avoidAreas:I.array(Q).max(10).optional(),thrillingParams:I.object({hilliness:I.enum(["low","normal","high"]).optional(),windingness:I.enum(["low","normal","high"]).optional()}).optional()}).optional(),travelMode:I.string().optional(),vehicle:cn.optional(),when:I.object({option:I.enum(["departAt","arriveBy"]),date:I.date()}).optional()}),un=["timeMinutes","remainingChargeCPT","spentChargePCT","spentFuelLiters","distanceKM"],ln=I.object({origin:Y,budget:I.object({type:I.enum(un),value:I.number().min(0)})}),dn=I.object({maxFerryLengthMeters:I.number().min(0).optional(),smoothing:I.enum(["none","weak","strong"]).optional()}),mn=pn.extend(ln.extend(dn.shape).shape),gn=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),yn=(e,t,n)=>{((e,t)=>{t&&(!x(t.acceleration)&&e.append("accelerationEfficiency",String(t.acceleration)),!x(t.deceleration)&&e.append("decelerationEfficiency",String(t.deceleration)),!x(t.uphill)&&e.append("uphillEfficiency",String(t.uphill)),!x(t.downhill)&&e.append("downhillEfficiency",String(t.downhill)))})(e,n.consumption.efficiency),"electric"===t?(((e,t)=>{t.speedsToConsumptionsKWH&&e.append("constantSpeedConsumptionInkWhPerHundredkm",gn(t.speedsToConsumptionsKWH)),!x(t.auxiliaryPowerInkW)&&e.append("auxiliaryPowerInkW",String(t.auxiliaryPowerInkW)),!x(t.consumptionInKWHPerKMAltitudeGain)&&e.append("consumptionInkWhPerkmAltitudeGain",String(t.consumptionInKWHPerKMAltitudeGain)),!x(t.recuperationInKWHPerKMAltitudeLoss)&&e.append("recuperationInkWhPerkmAltitudeLoss",String(t.recuperationInKWHPerKMAltitudeLoss))})(e,n.consumption),((e,t)=>{const n=t.charging;n?.maxChargeKWH&&e.append("maxChargeInkWh",String(n.maxChargeKWH))})(e,n)):((e,t)=>{const n=t.consumption;n.speedsToConsumptionsLiters&&e.append("constantSpeedConsumptionInLitersPerHundredkm",gn(n.speedsToConsumptionsLiters)),!x(n.auxiliaryPowerInLitersPerHour)&&e.append("auxiliaryPowerInLitersPerHour",String(n.auxiliaryPowerInLitersPerHour)),!x(n.fuelEnergyDensityInMJoulesPerLiter)&&e.append("fuelEnergyDensityInMJoulesPerLiter",String(n.fuelEnergyDensityInMJoulesPerLiter))})(e,n)},hn=(e,t)=>{t.model&&("variantId"in t.model?e.append("vehicleModelId",t.model.variantId):(((e,t)=>{t&&(t.lengthMeters&&e.append("vehicleLength",String(t.lengthMeters)),t.heightMeters&&e.append("vehicleHeight",String(t.heightMeters)),t.widthMeters&&e.append("vehicleWidth",String(t.widthMeters)),t.weightKG&&e.append("vehicleWeight",String(t.weightKG)),t.axleWeightKG&&e.append("vehicleAxleWeight",String(t.axleWeightKG)))})(e,t.model.dimensions),t.model.engine&&yn(e,"engineType"in t?t.engineType:void 0,t.model.engine)))},fn=(e,t)=>{t&&("electric"===t.engineType&&e.append("vehicleEngineType","electric"),hn(e,t),((e,t)=>{if(t.state&&(t.state.heading&&e.append("vehicleHeading",String(t.state.heading)),"engineType"in t))if("combustion"===t.engineType){const n=t.state;n.currentFuelInLiters&&e.append("currentFuelInLiters",String(n.currentFuelInLiters))}else if("electric"===t.engineType){const n=t.state,r=n,a=n;if(r.currentChargeInkWh)e.append("currentChargeInkWh",String(r.currentChargeInkWh));else if(a.currentChargePCT&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine.charging?.maxChargeKWH;n&&e.append("currentChargeInkWh",String(n*a.currentChargePCT/100))}}})(e,t),((e,t)=>{if(t.preferences&&"engineType"in t&&"electric"===t.engineType){const n=t.preferences;if(n.chargingPreferences){const r=n.chargingPreferences,a=r,o=r;if(a.minChargeAtChargingStopsInkWh||a.minChargeAtDestinationInkWh)e.append("minChargeAtDestinationInkWh",String(a.minChargeAtDestinationInkWh)),e.append("minChargeAtChargingStopsInkWh",String(a.minChargeAtChargingStopsInkWh));else if((o.minChargeAtChargingStopsPCT||o.minChargeAtDestinationPCT)&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine.charging?.maxChargeKWH;n&&(e.append("minChargeAtDestinationInkWh",String(n*o.minChargeAtDestinationPCT/100)),e.append("minChargeAtChargingStopsInkWh",String(n*o.minChargeAtChargingStopsPCT/100)))}}}})(e,t),((e,t)=>{const n=t.restrictions;n&&(ue(e,"vehicleLoadType",n.loadTypes),n.adrCode&&e.append("vehicleAdrTunnelRestrictionCode",n.adrCode),n.commercial&&e.append("vehicleCommercial",String(n.commercial)),n.maxSpeedKMH&&e.append("vehicleMaxSpeed",String(n.maxSpeedKMH)))})(e,t))},bn=(e,t)=>{const n=t.costModel;ue(e,"avoid",n?.avoid),de(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),de(e,"routeType",n?.routeType),de(e,"travelMode",t.travelMode),fn(e,t.vehicle)},Tn=e=>{const t=e.vehicle;if(t?.model&&"engine"in t.model)return t.model.engine?.charging?.maxChargeKWH},Rn=(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=Tn(t);null!=r&&e.append("energyBudgetInkWh",(r*n.value/100).toString());break}case"remainingChargeCPT":{const r=(e=>{const t=e.vehicle;if(!t?.state)return;const n=t.state;if(null!=n.currentChargePCT){const t=Tn(e);if(null!=t)return t*n.currentChargePCT/100}})(t),a=Tn(t);if(null!=a&&null!=r){const t=a*n.value/100;e.append("energyBudgetInkWh",Math.max(0,r-t).toString())}break}default:e.append(n.type,n.value.toString())}},vn=e=>{const t=(e=>{const t=u(e.origin);return`${t[1]},${t[0]}`})(e),n=new URL(((e,t)=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange/${t}/json`)(e,t)),r=n.searchParams;return pe(r,e),r.delete("language"),bn(r,e),Rn(r,e),de(r,"maxFerryLengthInMeters",e.maxFerryLengthMeters),de(r,"smoothing",e.smoothing??"strong"),{method:"GET",url:n}},Sn=(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:a(n),properties:t}},Cn={requestValidation:{schema:mn},buildRequest:vn,sendRequest:$,parseResponse:Sn,parseResponseError:wt,getAPIVersion:()=>2},Pn={buildReachableRangeRequest:vn,parseReachableRangeResponse:Sn,reachableRangeTemplate:Cn},In=e=>{const t=u(e.position),n=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/reverseGeocode`)(e)}/${t[1]},${t[0]}.json`),r=n.searchParams;return pe(r,e),e.allowFreeformNewline&&r.append("allowFreeformNewline",String(e.allowFreeformNewline)),e.geographyType&&r.append("entityType",Je(e.geographyType)),!x(e.heading)&&r.append("heading",String(e.heading)),e.mapcodes&&r.append("mapcodes",Je(e.mapcodes)),e.number&&r.append("number",e.number),!x(e.radiusMeters)&&r.append("radius",String(e.radiusMeters)),e.returnSpeedLimit&&r.append("returnSpeedLimit",String(e.returnSpeedLimit)),e.returnRoadUse&&r.append("returnRoadUse",String(e.returnRoadUse)),e.roadUses&&r.append("roadUse",JSON.stringify(e.roadUses)),n},xn=(e,t)=>{const n=e.addresses[0],{boundingBox:r,sideOfStreet:a,offsetPosition:o,...i}=n?.address||{};return{type:"Feature",geometry:v(u(t.position)),...r&&{bbox:Pe(r)},id:s(),...n&&{properties:{type:n?.entityType?"Geography":i.streetNumber?"Point Address":"Street",address:i,...n.dataSources&&{dataSources:n.dataSources},...n.mapcodes&&{mapcodes:n.mapcodes},...a&&{sideOfStreet:a},...o&&{offsetPosition:Se(o)},originalPosition:Se(n.position)}}}},wn=I.object({position:Y}),An=I.object({allowFreeformNewline:I.boolean().optional(),geographyType:I.array(I.string()).optional(),heading:I.number().min(-360).max(360).optional(),mapcodes:I.array(I.string()).optional(),number:I.string().optional(),radiusMeters:I.number().optional(),returnMatchType:I.boolean().optional(),returnRoadUse:I.boolean().optional(),returnSpeedLimit:I.boolean().optional(),roadUses:I.array(I.string()).optional(),view:I.enum(P).optional()}),Ln={requestValidation:{schema:wn.extend(An.shape)},buildRequest:In,sendRequest:H,parseResponse:xn},Dn={buildRevGeoRequest:In,parseRevGeoResponse:xn,reverseGeocodingTemplate:Ln},Mn=I.union([Y,_]),En=I.union([V,G]),On=I.object({locations:I.array(I.union([Mn,En])).min(1)}),Fn=I.object({computeAdditionalTravelTimeFor:I.enum(["none","all"]).optional(),vehicleHeading:I.number().min(0).max(359.5).optional(),maxAlternatives:I.number().min(0).max(5).optional(),sectionTypes:I.array(I.enum(y)).optional()}),kn=pn.extend(On.extend(Fn.shape).shape),jn=e=>(e.vehicle?.preferences)?.chargingPreferences,Un=e=>Array.isArray(e)?e:e.geometry.coordinates,Bn=(e,t,n)=>((e,t)=>e.map(e=>{const n=Ce(u(e,{useEntryPoint:t})),r=(e=>e.properties||null)(e)?.radiusMeters;return r?`circle(${n},${r})`:n}).join(":"))(t.includes("path")?((e,t,n)=>{let r;const a=e[0];r="path"===t[0]?Un(a)[0]:u(a,{useEntryPoint:n});const o=e[e.length-1];let i;if("path"===t[t.length-1]){const e=Un(o);i=e[e.length-1]}else i=u(o,{useEntryPoint:n});return[r,i]})(e,t,n):e,n),Wn=e=>({latitude:e[1],longitude:e[0]}),qn=(e,t,n)=>{const r=[],a=[];return e.forEach((o,i)=>{"path"===t[i]?((e,t,n,r,a)=>{const o=r.length;for(const i of Un(e))r.push(Wn(i));Array.isArray(e)||(e.properties.sections.leg.forEach((e,n)=>{(t>0||n>0)&&a.push({supportingPointIndex:o+e.startPointIndex,waypointSourceType:"USER_DEFINED"})}),t<n.length-1&&a.push({supportingPointIndex:o+e.geometry.coordinates.length-1,waypointSourceType:"USER_DEFINED"}))})(o,i,e,r,a):((e,t,n,r,a,o)=>{r.push(Wn(u(e,{useEntryPoint:o}))),t>0&&t<n.length-1&&a.push({supportingPointIndex:r.length-1,waypointSourceType:"USER_DEFINED"})})(o,i,e,r,a,n)}),{supportingPoints:r,...a.length&&{pointWaypoints:a}}},Nn=e=>({rectangles:e.map(e=>{const t=a(e);if(!t)throw new Error("Could not derive a bounding box from an avoidAreas rectangle");const[n,r,o,i]=t;return{southWestCorner:{latitude:r,longitude:n},northEastCorner:{latitude:i,longitude:o}}})}),Hn=e=>{const t=e.locations.map(l),n=e.useEntryPoints??"main-when-available",r=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/routing/${jn(e)?"calculateLongDistanceEVRoute":"calculateRoute"}`)(e)}/${Bn(e.locations,t,n)}/json`),a=r.searchParams;pe(a,e),"language"in e||a.append("language","en-GB"),bn(a,e),de(a,"computeTravelTimeFor",e.computeAdditionalTravelTimeFor),((e,t)=>{if(t?.guidance){const n=t.guidance;e.append("instructionsType",n.type),e.append("guidanceVersion",String(n.version??2)),e.append("instructionPhonetics",n.phonetics??"IPA"),e.append("language",t.language??"en-US")}})(a,e),!x(e.maxAlternatives)&&a.append("maxAlternatives",String(e.maxAlternatives)),((e,t,n)=>{ue(e,"sectionType",(t??(n?y:g)).map(e=>"vehicleRestricted"===e?"travelMode":e))})(a,e.sectionTypes,!!e.guidance?.type);for(const i of e.extendedRouteRepresentations??["distance","travelTime"])a.append("extendedRouteRepresentation",i);const o=((e,t,n)=>{const r=t.includes("path"),a=!!jn(e),o=e.costModel?.avoidAreas;if(!r&&!a&&!o)return null;const i=(e.vehicle?.model)?.engine?.charging;return{...r&&qn(e.locations,t,n),...a&&i&&{chargingParameters:w(i,"maxChargeKWH")},...o?.length&&{avoidAreas:Nn(o)}}})(e,t,n);return o?{method:"POST",url:r,data:o}:{method:"GET",url:r}},Kn=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},$n=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,a=[r.coordinate.longitude,r.coordinate.latitude],o=[r.street,r.houseNumber].filter(Boolean),i=o.length>0?o.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:a},properties:{...w(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:Kn(n.chargingCurrentType),chargingSpeed:ve(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:ve(e.chargingParkPowerInkW)}}}},Vn=(e,t)=>{const n=(t?.vehicle?.model)?.engine?.charging?.maxChargeKWH;return{lengthInMeters:e.lengthInMeters,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,trafficDelayInSeconds:e.trafficDelayInSeconds,trafficLengthInMeters:e.trafficLengthInMeters,travelTimeInSeconds:e.travelTimeInSeconds,departureTime:new Date(e.departureTime),arrivalTime:new Date(e.arrivalTime),deviationDistanceInMeters:e.deviationDistance,fuelConsumptionInLiters:e.fuelConsumptionInLiters,...e.deviationPoint&&{deviationPoint:[e.deviationPoint.longitude,e.deviationPoint.latitude]},totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInkWh,...n&&e.batteryConsumptionInkWh&&{batteryConsumptionInPCT:100*e.batteryConsumptionInkWh/n},remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:$n(e.chargingInformationAtEndOfLeg,n)}}},_n=(e,t)=>e.reduce((e,n,r)=>{const a=0===r?0:e[r-1]?.endPointIndex;let o;return x(a)||(o=0===a?n.points?.length>0?n.points.length-1:0:a+n.points?.length),e.push({...!x(a)&&{startPointIndex:a},...o&&{endPointIndex:o},summary:Vn(n.summary,t),id:s()}),e},[]),Gn=e=>({id:s(),startPointIndex:e.startPointIndex,endPointIndex:e.endPointIndex}),zn=e=>({...Gn(e),index:e.importantRoadStretchIndex,streetName:e.streetName?.text,roadNumbers:e.roadNumbers?.map(e=>e.text)}),Yn=e=>({...Gn(e),countryCodeISO3:e.countryCode}),Zn=e=>"other"===e.travelMode?Gn(e):null,Jn=e=>{if(e.tec?.causes?.length)return e.tec.causes.map(e=>(e=>{switch(e){case 1:return"jam";case 2:return"accident";case 3:return"roadworks";case 4:return"narrow-lanes";case 5:return"road-closed";case 9:return"danger";case 11:return"animals-on-road";case 13:return"broken-down-vehicle";case 16:return"lane-closed";case 17:return"wind";case 18:return"fog";case 19:return"rain";case 22:return"frost";case 23:return"flooding";default:return"other"}})(e.mainCauseCode));switch(e.simpleCategory){case"JAM":return["jam"];case"ROAD_WORK":return["roadworks"];case"ROAD_CLOSURE":return["road-closed"];default:return["other"]}},Qn=e=>({...Gn(e),delayInSeconds:e.delayInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKmh,categories:Jn(e),magnitudeOfDelay:m[e.magnitudeOfDelay],tec:e.tec}),Xn=e=>({...Gn(e),lanes:e.lanes,laneSeparators:e.laneSeparators,properties:e.properties}),er=e=>({...Gn(e),maxSpeedLimitInKmh:e.maxSpeedLimitInKmh}),tr=e=>({...Gn(e),roadShieldReferences:e.roadShieldReferences}),nr=(e,t)=>(t[e]||(t[e]=[]),t[e]),rr=e=>{switch(e.sectionType){case"CAR_TRAIN":return{sectionType:"carTrain",mappingFunction:Gn};case"COUNTRY":return{sectionType:"country",mappingFunction:Yn};case"FERRY":return{sectionType:"ferry",mappingFunction:Gn};case"MOTORWAY":return{sectionType:"motorway",mappingFunction:Gn};case"PEDESTRIAN":return{sectionType:"pedestrian",mappingFunction:Gn};case"TOLL_VIGNETTE":return{sectionType:"tollVignette",mappingFunction:Yn};case"TOLL":return{sectionType:"toll",mappingFunction:Gn};case"TRAFFIC":return{sectionType:"traffic",mappingFunction:Qn};case"TRAVEL_MODE":return{sectionType:"vehicleRestricted",mappingFunction:Zn};case"TUNNEL":return{sectionType:"tunnel",mappingFunction:Gn};case"UNPAVED":return{sectionType:"unpaved",mappingFunction:Gn};case"URBAN":return{sectionType:"urban",mappingFunction:Gn};case"CARPOOL":return{sectionType:"carpool",mappingFunction:Gn};case"LOW_EMISSION_ZONE":return{sectionType:"lowEmissionZone",mappingFunction:Gn};case"LANES":return{sectionType:"lanes",mappingFunction:Xn};case"SPEED_LIMIT":return{sectionType:"speedLimit",mappingFunction:er};case"ROAD_SHIELDS":return{sectionType:"roadShields",mappingFunction:tr};case"IMPORTANT_ROAD_STRETCH":return{sectionType:"importantRoadStretch",mappingFunction:zn}}},ar=(e,t)=>{const n={leg:_n(e.legs,t)};return((e,t)=>{if(Array.isArray(e))for(const n of e){const e=rr(n),r=e?.mappingFunction(n);r&&nr(e.sectionType,t).push(r)}})(e.sections,n),n},or=1e-4,ir=(e,t)=>Math.abs(e[0]-t[0])<or&&Math.abs(e[1]-t[1])<or,sr=(e,t)=>{const n=[];let r=0;for(const a of e.instructions){const e=[a.maneuverPoint.longitude,a.maneuverPoint.latitude];for(let n=r;n<t.length;n++){if(ir(t[n],e)){r=n;break}if(n===t.length-1)break}n.push({...a,maneuverPoint:e,pathPointIndex:r,routePath:a.routePath.map(e=>({...e,point:[e.point.longitude,e.point.latitude]}))})}return{instructions:n}},cr=(e,t)=>{const n=e.routes.map((e,n)=>((e,t,n)=>{const r={type:"LineString",coordinates:e.legs.flatMap(e=>e.points?.map(e=>[e.longitude,e.latitude]))};return{type:"Feature",geometry:r,id:s(),bbox:a(r),properties:{index:t,summary:Vn(e.summary,n),sections:ar(e,n),...e.guidance&&{guidance:sr(e.guidance,r.coordinates)},...e.progress&&{progress:e.progress}}}})(e,n,t)),r=a(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},pr={requestValidation:{schema:kn,refinements:[{check:e=>!!e.locations.map(l).includes("path")||e.locations.length>=2,message:"When passing waypoints only: at least 2 must be defined. If passing also paths, at least one path must be defined"}]},buildRequest:Hn,sendRequest:$,parseResponse:cr,parseResponseError:wt,getAPIVersion:()=>2},ur={buildCalculateRouteRequest:Hn,parseCalculateRouteResponse:cr,calculateRouteTemplate:pr},lr=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],dr={speed:"SPEED",freeFlowSpeed:"FREE_FLOW_SPEED",congestionLevel:"CONGESTION_LEVEL",travelTime:"TRAVEL_TIME",networkLength:"NETWORK_LENGTH"},mr=e=>e instanceof Date?e.toISOString().slice(0,10):e,gr=Array.from({length:24},(e,t)=>t),yr=e=>lr.indexOf(e),hr=e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));pe(n.searchParams,e);const r=e=>{const t=/* @__PURE__ */new Date;return t.setDate(t.getDate()-e),t},a=Array.isArray(e.days)?{days:e.days.map(mr)}:{startDate:mr(e.startDate??r(3)),endDate:mr(e.endDate??r(2))};return{method:"POST",url:n,data:{name:e.name??`Maps SDK JS Area Analytics Report ${/* @__PURE__ */(new Date).toISOString()}`,...a,dataTypes:"all"===e.metrics?t.map(e=>dr[e]):e.metrics.map(e=>dr[e]),frcs:"all"===e.functionalRoadClasses?lr.map((e,t)=>t):e.functionalRoadClasses.map(yr),hours:"all"===e.hours?gr:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},fr=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}}),br=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},...fr(e)}),Tr=(e,t)=>{const n=new Date(e);return n.setDate(n.getDate()+t),n},Rr=(e,t)=>e.map((e,n)=>{const r=br(e);return void 0===r.date&&(r.date=Tr(t,Math.floor(n/24))),void 0===r.hour&&(r.hour=n%24),r}),vr=(e,t)=>e.map((e,n)=>{const r=br(e);return void 0===r.date&&(r.date=Tr(t,n)),r}),Sr=e=>({tileCentre:[e.lon,e.lat],...fr(e)}),Cr=e=>({startDate:new Date(e.startDate),endDate:new Date(e.endDate),labels:e.labels}),Pr=(e,t)=>{return{...e.yearly&&{yearly:e.yearly.map(br)},...e.monthly&&{monthly:e.monthly.map(br)},...e.weekly&&{weekly:e.weekly.map(br)},...e.daily&&{daily:vr(e.daily,t)},...e.hourly&&{hourly:Rr(e.hourly,t)},...e.average&&{average:(n=e.average,n.map((e,t)=>{const n=br(e);return void 0===n.day&&(n.day=Math.floor(t/24)+1),void 0===n.hour&&(n.hour=t%24),n}))}};var n},Ir={SPEED:"speed",FREE_FLOW_SPEED:"freeFlowSpeed",CONGESTION_LEVEL:"congestionLevel",TRAVEL_TIME:"travelTime",NETWORK_LENGTH:"networkLength"},xr=e=>{const t={};for(const[n,r]of Object.entries(e)){const e=Ir[n];e&&(t[e]=r.map(Cr))}return t},wr=(e,t)=>({name:e.name,timezone:e.timezone,level:e.level,baseData:fr(e.baseData),timedData:Pr(e.timedData,t),...e.tiledData&&{tiledData:{tiles:e.tiledData.tiles.map(Sr)}},...e.anomalies&&{anomalies:xr(e.anomalies)}}),Ar=e=>{const n=e.flatMap(e=>e.properties.tiledData?.tiles??[]),r={};for(const a of t){const e=n.map(e=>e[a]).filter(e=>null!=e);e.length>0&&(r[a]={min:Math.min(...e),max:Math.max(...e)})}return r},Lr=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:wr(e.properties,t),bbox:a(e.geometry)}))(e,t));return{type:"FeatureCollection",properties:{startDate:t,endDate:new Date(e.properties.endDate),metrics:e.properties.dataTypes.map(e=>Ir[e]).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:Ar(n)},features:n}},Dr=I.union([I.date(),I.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),Mr=I.union([I.object({type:I.literal("Polygon"),coordinates:I.array(I.array(I.array(I.number()))).min(1)}),I.object({type:I.literal("MultiPolygon"),coordinates:I.array(I.array(I.array(I.array(I.number())))).min(1)})]),Er=e=>e instanceof Date?e:new Date(e),Or=e=>{const t=/* @__PURE__ */new Date,n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return(e=>{const t=Er(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())})(e)<=n-1728e5},Fr={requestValidation:{schema:k.extend({name:I.string().optional(),startDate:Dr.optional(),endDate:Dr.optional(),days:I.array(Dr).min(1).optional(),metrics:I.union([I.array(I.enum([...t])).min(1),I.literal("all")]),functionalRoadClasses:I.union([I.array(I.enum([...lr])).min(1),I.literal("all")]),hours:I.union([I.array(I.number().int().min(0).max(23)).min(1),I.literal("all")]),geometry:Mr}).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?Er(e.endDate):/* @__PURE__ */new Date).getTime()-Er(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=>void 0!==e.days?e.days.every(Or):Or(e.endDate??/* @__PURE__ */new Date),{message:"Dates must be at least 2 days before today"})},buildRequest:hr,sendRequest:$,parseResponse:Lr},kr={buildTrafficAreaAnalyticsRequest:hr,parseTrafficAreaAnalyticsResponse:Lr,trafficAreaAnalyticsTemplate:Fr},jr=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidentDetails`)(e)),n=t.searchParams;if(pe(n,e),((e,t)=>{de(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}}}}}"),de(e,"t",t.trafficModelId),le(e,"categoryFilter",t.categoryFilter?.map(C)),le(e,"timeValidityFilter",t.timeValidityFilter)})(n,e),"bbox"in e&&e.bbox){const r=a(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})},Ur=e=>({description:e.description,code:e.code,category:d(e.iconCategory)}),Br=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:d(t.iconCategory),magnitudeOfDelay:m[t.magnitudeOfDelay]??"unknown",events:(t.events??[]).map(Ur),...t.startTime&&{startTime:new Date(t.startTime)},...t.endTime&&{endTime:new Date(t.endTime)},...t.from&&{from:t.from},...t.to&&{to:t.to},...void 0!==t.length&&{lengthInMeters:t.length},...void 0!==t.delay&&{delayInSeconds:t.delay},...t.roadNumbers&&{roadNumbers:t.roadNumbers},timeValidity:t.timeValidity,...t.probabilityOfOccurrence&&{probabilityOfOccurrence:t.probabilityOfOccurrence},...void 0!==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,...void 0!==e.offset&&{offset:e.offset}}))})}}};var n},Wr=e=>({type:"FeatureCollection",features:(e.incidents??[]).filter(e=>null!==e).map(Br)}),qr={requestValidation:{schema:k.extend({bbox:Q.optional(),ids:I.array(I.string()).optional(),trafficModelId:I.string().optional(),categoryFilter:I.array(I.enum([...S])).optional(),timeValidityFilter:I.array(I.enum(["present","future"])).optional()}).refine(e=>!(e.bbox&&e.ids),{message:"Provide either bbox or ids, not both"})},buildRequest:jr,sendRequest:$,parseResponse:Wr},Nr={alongRouteSearch:Ne,reverseGeocode:Dn,geocode:rt,geometryData:lt,geometrySearch:Tt,calculateRoute:ur,reachableRange:Pn,evChargingStationsAvailability:ze,trafficAreaAnalytics:kr,trafficIncidentDetails:{buildTrafficIncidentDetailsRequest:jr,parseTrafficIncidentDetailsResponse:Wr,trafficIncidentDetailsTemplate:qr},placeByID:xt,autocompleteSearch:He},Hr=async(e,t)=>B(e,{...Ge,...t},"EVChargingStationsAvailability"),Kr=async e=>{const t=e.properties.dataSources?.chargingAvailability?.id;if(t)try{const n=await Hr({id:t}),r=e.properties.poi;return n?{...e,properties:{...e.properties,...r&&{poi:{...r,openingHours:n.openingHours}},chargingPark:{...e.properties.chargingPark,availability:n}}}:void 0}catch(n){return void console.error(n)}};async function $r(e,t){const n=[];for(const r of e.features){const e=await Kr(r);e?n.push(e):t?.excludeIfAvailabilityUnknown||n.push(r)}return{...e,features:n,bbox:a(n)}}var Vr=e=>Boolean(e&&"availability"in e&&e.availability),_r=I.array(I.number()).min(2),Gr=I.object({type:I.literal("Polygon"),coordinates:I.array(I.array(I.array(I.number()))),bbox:I.array(I.number()).optional()}),zr=I.object({type:I.literal("MultiPolygon"),coordinates:I.array(I.array(I.array(I.array(I.number())))),bbox:I.array(I.number()).optional()}),Yr=I.object({type:I.literal("Circle"),coordinates:_r,radius:I.number().positive()}),Zr=I.object({type:I.literal("FeatureCollection"),features:I.array(I.object({type:I.literal("Feature"),geometry:I.union([Gr,zr]),properties:I.any().optional()}))}),Jr=I.union([Gr,zr,Yr,Zr]),Qr=I.tuple([I.number(),I.number(),I.number(),I.number()]),Xr=I.object({bbox:Qr}),ea=I.union([Qr,Xr]),ta=I.enum(["POI","PointAddress","Street"]),na=I.object({municipalities:I.array(I.string()).optional(),boundingBoxes:I.array(ea).optional(),geometries:I.array(Jr).optional(),placeTypes:I.array(ta).min(1).optional(),offset:I.number().int().min(0).max(1e4).optional(),limit:I.number().int().min(1).max(1e4).optional()}),ra=te.extend(Ye.extend(na.shape).shape),aa=e=>{const[t,n]=e.coordinates,r=e.radius/6371e3*(180/Math.PI),a=r/Math.cos(n*Math.PI/180),o=[];for(let i=0;i<64;i++){const e=2*Math.PI*i/64;o.push([t+a*Math.cos(e),n+r*Math.sin(e)])}return o.push(o[0]),{type:"Polygon",coordinates:[o]}},oa=e=>{switch(e.type){case"Polygon":case"MultiPolygon":return[e];case"Circle":return[aa(e)];case"FeatureCollection":return e.features.map(e=>e.geometry)}},ia=e=>(e=>{if(e.length<2)return e;const[t,n]=[e[0],e[e.length-1]];return t[0]===n[0]&&t[1]===n[1]?e:[...e,[...t]]})((e=>e.filter((t,n)=>0===n||t[0]!==e[n-1][0]||t[1]!==e[n-1][1]))(e)),sa=e=>"Polygon"===e.type?{...e,coordinates:e.coordinates.map(ia)}:{...e,coordinates:e.coordinates.map(e=>e.map(ia))},ca={POI:"POI",PointAddress:"Point Address",Street:"Street"},pa=e=>{const t=(e=>{const t=/* @__PURE__ */new Set;for(const n of e.categorySet??[])t.add(Number(n));return e.preferredCategoryId&&t.add(Number(e.preferredCategoryId)),[...t].filter(e=>Number.isFinite(e))})(e);t.sort((e,t)=>t-e);const n=/* @__PURE__ */new Set,r=[];for(const a of t){const e=R[a];e&&!n.has(e)&&(n.add(e),r.push(e))}return r},ua=e=>{const{id:t,position:n,address:r,score:a,distance_m:o,type:i,viewport:s}=e,c=ca[i??"POI"],p=(e=>{if(e?.name)return{name:e.name,categories:pa(e),localizedCategories:e.classifications?.map(e=>e.name)??[],...e.phone&&{phone:e.phone},...e.url&&{url:e.url},...e.brands?.length&&{brands:e.brands.map(e=>e.name)},...e.timeZone?.ianaId&&{timeZone:e.timeZone}}})(e.poi),u=(e=>{if(!e)return;const[[t,n],[r,a]]=e.coordinates;return[t,n,r,a]})(s);return{type:"Feature",id:t,geometry:v(n),...u&&{bbox:u},properties:{type:c,...r&&{address:r},...p&&{poi:p},...void 0!==a&&{score:a},...void 0!==o&&{distance:o}}}},la=(e,t)=>{const n=!!p(t.position),r=n?p(t.position):null;return{query:t.query??"",queryType:n?"NEARBY":"NON_NEAR",queryTime:0,numResults:e.hits.length,offset:t.offset??0,totalResults:e.total,fuzzyLevel:0,...r&&{geoBias:r}}},da={requestValidation:{schema:ra,refinements:[{check:e=>!!(e.position||e.boundingBox||e.boundingBoxes?.length||e.geometries?.length||e.municipalities?.length),message:"A geographic bias is required: provide one of position, boundingBox(es), geometries, or municipalities."}]},buildRequest:e=>{const t=new URL("/places",(e=>e.customServiceBaseURL??"https://search-places-poc.whitebush-bbe9c5f7.westeurope.azurecontainerapps.io")(e)),n=(e=>{const t=p(e.position);if(t)return{coordinates:t,radius_km:e.radiusMeters&&e.radiusMeters>0?e.radiusMeters/1e3:2}})(e),r=(e=>e.poiCategories?.length?e.poiCategories.map(e=>String(T[e])):void 0)(e),o=(e=>{const t=[...e.boundingBox?[e.boundingBox]:[],...e.boundingBoxes??[]].map(e=>a(e)).filter(e=>void 0!==e);return t.length?t:void 0})(e),i=(e=>{if(!e.geometries?.length)return;const t=e.geometries.flatMap(oa).map(sa);return t.length?t:void 0})(e),s=(e=>e.municipalities?.length?e.municipalities:void 0)(e);return{url:t,data:{...e.query&&{q:e.query},...e.countries?.[0]&&{country:e.countries[0]},...s&&{municipalities:s},...e.poiBrands?.[0]&&{brand:e.poiBrands[0]},...r&&{categories:r},...e.placeTypes?.length&&{types:e.placeTypes},...n&&{near:n},...o&&{bboxes:o},...i&&{geometries:i},...void 0!==e.offset&&{from:e.offset},...void 0!==e.limit&&{size:e.limit}}}},sendRequest:K,parseResponse:(e,t)=>{const n=e.hits.map(ua),r=o(a(n));return{type:"FeatureCollection",properties:la(e,t),features:n,...r&&{bbox:r}}}},ma=async(e,t)=>B(e,{...da,...t},"ExplorationSearch"),ga=async(e,t)=>B(e,{...nt,...t},"Geocode"),ya=async e=>{const t=await ga({query:e,limit:1});if(!t.features[0])throw new Error(`geocodeOne: no results found for "${e}"`);return t.features[0]};async function ha(e,t){const n=await B(e,{...ut,...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 fa=async(e,t)=>B(e,{...It,...t},"PlaceById"),ba=/* @__PURE__ */new Map,Ta=/* @__PURE__ */new Map,Ra="en-GB",va=e=>e??Ra,Sa=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),Ca=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(Sa);for(const r of e)t[r]=n}return t},Pa=k.extend({filters:I.array(I.string()).optional()}),Ia=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)},xa={requestValidation:{schema:Pa},buildRequest:e=>{const t=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/poiCategories.json`,n=new URL(t);return pe(n.searchParams,e),n},getAPIVersion:()=>1,sendRequest:H,parseResponse:e=>({poiCategories:e.poiCategories.map(Ia).filter(e=>null!==e)})},wa=(e,t)=>{const n=(e=>Ta.get(e??Ra)??{})(e),r=/* @__PURE__ */new Map;for(const a of t){const e=Sa(a);for(const[t,a]of Object.entries(n))t.includes(e)&&a&&r.set(a.code,a)}for(const a of r.values())for(const e of a.childCategoryCodes)r.delete(e);return[...r.values()]},Aa=async(e={})=>{const{language:t}=h(e);let n=(e=>ba.get(va(e)))(t);return n||(n=(await B(e,xa,"POICategories")).poiCategories,((e,t)=>{const n=va(e);ba.set(n,t),Ta.set(n,Ca(t))})(t,n)),e.filters?.length?{poiCategories:wa(t,e.filters)}:{poiCategories:n}},La=async(e={})=>{const{poiCategories:t}=await Aa(e);return t.map(e=>e.code)},Da=async(e,t)=>B(e,{...Cn,...t},"Reachable Range"),Ma=async(e,t,n)=>{const r=[];for(const a of e){t?.signal?.throwIfAborted();try{r.push(await Da(a,n))}catch(i){if(!(i instanceof M)||403===i.status||429===i.status)throw i}}const o=a(r);return{type:"FeatureCollection",...o&&{bbox:o},features:r}},Ea=async(e,t)=>B(e,{...Ln,...t},"ReverseGeocode"),Oa=async(e,t)=>B(e,{...pr,...t},"Routing"),Fa=I.object({minFuzzyLevel:I.number().min(1).max(4).optional(),maxFuzzyLevel:I.number().min(1).max(4).optional()}),ka=te.extend(Ye.extend(Fa.shape).shape),ja=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:Ie(e.details)}};break;case"NEARBY":t={...e,details:{position:Ie({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},Ua={requestValidation:{schema:ka},buildRequest:e=>{const t=new URL(`${(e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/search/${e.query??""}.json`)(e)}`);ge(t,e);const n=t.searchParams;de(n,"typeahead",e.typeahead),de(n,"ofs",e.offset),le(n,"countrySet",e.countries),de(n,"radius",e.radiusMeters);const r=e.boundingBox&&a(e.boundingBox);return r&&(n.append("topLeft",Je([r[3],r[0]])),n.append("btmRight",Je([r[1],r[2]]))),de(n,"minFuzzyLevel",e.minFuzzyLevel),de(n,"maxFuzzyLevel",e.maxFuzzyLevel),t},sendRequest:H,parseResponse:e=>{const t=e.results.map(Le),n=o(a(t));return{type:"FeatureCollection",properties:{...De(e.summary),queryIntent:e.summary.queryIntent.map(ja)},features:t,...n&&{bbox:n}}}},Ba=async(e,t)=>"route"in e?Oe(e,t):"geometries"in e?bt(e,t):(async(e,t)=>B(e,{...Ua,...t},"FuzzySearch"))(e,t),Wa=async e=>{const t=await Ba({query:e,limit:1});if(!t.features[0])throw new Error(`searchOne: no results found for "${e}"`);return t.features[0]},qa=async(e,t)=>B(e,{...Fr,...t},"TrafficAreaAnalytics"),Na=async(e,t)=>B(e,{...qr,...t},"TrafficIncidentDetails");export{D as APIErrorCode,L as SDKError,M as SDKServiceError,Oe as alongRouteSearch,qe as autocompleteSearch,un as budgetTypes,O as buildResponseError,F as buildValidationError,Da as calculateReachableRange,Ma as calculateReachableRanges,Oa as calculateRoute,Nr as customizeService,Hr as evChargingStationsAvailability,ma as explorationSearch,ga as geocode,ya as geocodeOne,ha as geometryData,Aa as getPOICategories,La as getPOICategoryCodes,Kr as getPlaceWithEVAvailability,$r as getPlacesWithEVAvailability,Vr as hasChargingAvailability,E as parseDefaultResponseError,fa as placeById,Ea as reverseGeocode,$e as routeTypes,Ba as search,Wa as searchOne,qa as trafficAreaAnalytics,Na as trafficIncidentDetails};
1
+ import{TomTomConfig as e,areaAnalyticsMetricKeys as t,avoidableTypes as n,bboxFromCoordsArray as r,bboxFromGeoJSON as a,bboxOnlyIfWithArea as o,currentTypes as i,generateId as s,generateTomTomHeaders as c,getPosition as p,getPositionStrict as u,getRoutePlanningLocationType as l,iconToTrafficIncidentCategory as d,indexedMagnitudes as m,inputSectionTypes as g,inputSectionTypesWithGuidance as y,mergeFromGlobal as h,plugTypes as f,poiCategories as b,poiCategoriesToID as T,poiIDsToCategories as R,toPointGeometry as v,trafficIncidentRequestCategories as S,trafficIncidentToIconCategory as C,views as P}from"@tomtom-org/maps-sdk/core";import{z as I}from"zod";import{isNil as x,omit as w}from"lodash-es";var A=/* @__PURE__ */function(e){return e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.FORBIDDEN=403]="FORBIDDEN",e}({}),L=class e extends Error{constructor(t,n,r){super(t),this.service=n,this.issues=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},D={[A.TOO_MANY_REQUESTS]:"Too Many Requests: The API Key is over QPS (Queries per second)",[A.FORBIDDEN]:"Request failed with status code 403"},M=class extends L{constructor(e,t,n){super(e,t),this.status=n,this.status&&D[this.status]&&(this.message=D[this.status])}},E=(e,t)=>{const{data:n,message:r,status:a}=e;return new M(n?.error||n?.errorText||r,t,a)},O=(e,t,n)=>{if(e.status){const r=e;return n?n(r,t):E(r,t)}return new L(e.message,t)},F=(e,t)=>new L(e.message,t,e.issues),k=I.object({apiKey:I.string().optional(),commonBaseURL:I.string().optional(),customServiceBaseURL:I.string().optional(),language:I.string().optional()}),j=(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=>j(e,t+1)).join(", ")} }`).join(" | ")})`}return`${n}${e.message}`},U=class extends Error{constructor(e){super(`${e.issues.map(e=>j(e)).join("; ")}\nIssues: ${JSON.stringify(e.issues,null,2)}`),this.issues=e.issues}},B=async(e,t,n)=>{const r=t.getAPIVersion?.(e),a=h({...e,...r&&{apiVersion:r}});if(void 0===e.validateRequest||e.validateRequest)try{((e,t)=>{const n=(t?.schema?k.extend(t.schema.shape):k).superRefine((e,n)=>{if("commonBaseURL"in e||"customServiceBaseURL"in e||n.addIssue({code:"custom",message:"commonBaseURL or customServiceBaseURL is required"}),t?.refinements?.length)for(const r of t.refinements)r.check(e)||n.addIssue({code:"custom",message:r.message})}).safeParse(e);if(!n.success)throw new U(n.error)})(a,t.requestValidation)}catch(s){throw F(s,n)}const o=t.buildRequest(a),i=c(a);e.onAPIRequest?.(o);try{const n=await t.sendRequest(o,i);return e.onAPIResponse?.(o,n),t.parseResponse(await n.data,a)}catch(s){throw e.onAPIResponse?.(o,s),O(s,n,t.parseResponseError)}},W=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)}},q=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 W(e.status,t,n)},N=async t=>{const n=e.instance.get().retry;if(!n)return t();const{initialWaitMs:r,backoffFactor:a,timeoutMs:o}=n,i=Date.now();let s=r,c=await t();for(;429===c.status;){const e=Number.parseInt(c.headers.get("retry-after")??"",10),n=Number.isFinite(e)?1e3*e:s;if(Date.now()-i+n>o)break;await c.text().catch(()=>{}),await new Promise(e=>setTimeout(e,n)),s*=a,c=await t()}return c},H=async(e,t)=>q(await N(()=>fetch(e,{headers:t}))),_=async(e,t)=>q(await N(()=>fetch(e.url,{method:"POST",body:JSON.stringify(e.data),headers:{...t,"Content-Type":"application/json"}}))),K=async(e,t)=>{const n=e.method;if("GET"===n)return H(e.url,t);if("POST"===n)return _(e,t);throw new Error(`Unsupported HTTP method received: ${n}`)},$=I.array(I.array(I.number())),V=I.object({type:I.enum(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","GeometryCollection","Circle"]),coordinates:I.union([I.array(I.number()),$,I.array(I.array(I.array(I.number()))),I.array(I.array(I.array(I.array(I.number()))))]),radius:I.optional(I.number()),radiusMeters:I.optional(I.number()),bbox:I.optional(I.array(I.number()))}).check(I.refine(e=>"Circle"!==e.type||Boolean(e.radius),'type: "Circle" must have radius property')),G=I.object({type:I.literal("Feature"),geometry:V,id:I.optional(I.union([I.string(),I.number()])),properties:I.unknown().optional(),bbox:I.optional(I.array(I.number()))}),z=I.object({type:I.literal("FeatureCollection"),features:I.array(G),id:I.optional(I.union([I.string(),I.number()])),properties:I.unknown().optional(),bbox:I.optional(I.array(I.number()))}),Y=I.union([I.tuple([I.number().min(-180).max(180),I.number().min(-90).max(90)]),I.tuple([I.number().min(-180).max(180),I.number().min(-90).max(90),I.number()]),I.object({type:I.literal("Point"),coordinates:I.array(I.number())}),G]),Z=I.union([I.array(I.number()).refine(e=>4===e.length,{message:"BBox must have 4 elements"}),I.array(I.number()).refine(e=>6===e.length,{message:"BBox must have 6 elements"})]),J=I.union([V,G,z]),Q=I.union([Z,J,I.array(J)]),X=I.object({query:I.string().optional(),position:Y.optional(),limit:I.number().max(100).optional(),extendedPostalCodesFor:I.array(I.string()).optional(),mapcodes:I.array(I.string()).optional(),view:I.enum(P).optional(),geographyTypes:I.array(I.string()).optional()}),ee=I.object({indexes:I.array(I.string()).optional(),poiCategories:I.array(I.enum(b)).optional(),poiBrands:I.array(I.string()).optional(),connectors:I.array(I.string()).optional(),fuelTypes:I.array(I.string()).optional(),openingHours:I.string().optional(),timeZone:I.string().optional(),relatedPois:I.string().optional(),minPowerKW:I.number().optional(),maxPowerKW:I.number().optional(),minFuzzyLevel:I.number().optional(),maxFuzzyLevel:I.number().optional()}),te=X.extend(ee.shape),ne=I.object({type:I.literal("LineString"),coordinates:$}),re=I.object({type:I.literal("Feature"),geometry:ne}),ae=$,oe=I.union([ne,re,ae]),ie=I.object({route:oe,maxDetourTimeSeconds:I.number().int().positive()}),se=I.object({sortBy:I.enum(["detourTime","detourOffset"]).optional()}),ce=te.extend({...ie.shape,...se.shape}),pe=(e,t)=>{e.append("apiVersion",String(t.apiVersion)),e.append("key",t.apiKey),t.language&&e.append("language",t.language)},ue=(e,t,n)=>{for(const r of n||[])e.append(t,r)},le=(e,t,n)=>{Array.isArray(n)&&n.length>0&&e.append(t,n.join(","))},de=(e,t,n)=>{!x(n)&&e.append(t,String(n))},me=(e,t)=>{const n=p(t);n&&(e.append("lat",String(n[1])),e.append("lon",String(n[0])))},ge=(e,t)=>{const n=e.searchParams;pe(n,t),de(n,"limit",t.limit),me(n,"position"in t?t.position:void 0),le(n,"fuelSet",t.fuelTypes),le(n,"idxSet",t.indexes),le(n,"brandSet",t.poiBrands),t.poiCategories&&le(n,"categorySet",t.poiCategories.map(e=>T[e])),le(n,"connectorSet",t.connectors),le(n,"mapcodes",t.mapcodes),le(n,"extendedPostalCodesFor",t.extendedPostalCodesFor),de(n,"minPowerKW",t.minPowerKW),de(n,"maxPowerKW",t.maxPowerKW),de(n,"view",t.view),de(n,"openingHours",t.openingHours),de(n,"timeZone",t.timeZone),de(n,"relatedPois",t.relatedPois),le(n,"entityTypeSet",t.geographyTypes)},ye=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/searchAlongRoute/${e.query??""}.json`)(e));ge(t,e);const n=t.searchParams;return n.append("maxDetourTime",String(e.maxDetourTimeSeconds)),de(n,"sortBy",e.sortBy),de(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},he=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},fe=(e,t)=>e.type===t.type&&e.ratedPowerKW===t.ratedPowerKW,be=(e,t,n)=>{if(e)for(const r of e){const e=n.find(e=>fe(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}:{}})}},Te=e=>{const t=[];return((e,t)=>{if(e)for(const n of e){const e=t.find(e=>fe(n,e.connector));e?e.count++:t.push({connector:n,count:1})}})(e,t),t},Re=e=>{const t=[];for(const n of e)for(const e of n.chargingPoints)be(e.connectors,e.status,t);return t},ve=e=>e<12?"slow":e<50?"regular":e<150?"fast":"ultra-fast",Se=e=>{const t=e.split(",");return[Number(t[1]),Number(t[0])]},Ce=e=>`${e[1]},${e[0]}`,Pe=e=>{let t,n;return void 0!==e.topLeftPoint?(t=[e.topLeftPoint.lon,e.btmRightPoint.lat],n=[e.btmRightPoint.lon,e.topLeftPoint.lat]):(t=Se(e.southWest),n=Se(e.northEast)),[t[0],t[1],n[0],n[1]]},Ie=e=>[e.lon,e.lat],xe=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)}},we=e=>1===e.length&&0===e[0].start.hour&&0===e[0].end.hour,Ae=e=>{const t=e.timeRanges.map(e=>({start:xe(e.startTime),end:xe(e.endTime)}));return{mode:e.mode,timeRanges:t,alwaysOpenThisPeriod:we(t)}},Le=e=>{const{position:t,entryPoints:n,poi:r,id:a,dist:o,boundingBox:i,chargingPark:s,...c}=e,p=s?.connectors?.map(e=>({...w(e,"connectorType"),type:e.connectorType,chargingSpeed:ve(e.ratedPowerKW)}));return{type:"Feature",geometry:v(Ie(t)),...i&&{bbox:Pe(i)},id:a,properties:{...w(c,"viewport"),...o&&{distance:o},...n?.length&&{entryPoints:n.map(e=>({...e,position:Ie(e.position)}))},...p?.length&&{chargingPark:{...s,connectors:Te(p)}},...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:Ae(r.openingHours)},...r.timeZone&&{timeZone:r.timeZone}}}}}},De=e=>{const{geoBias:t,...n}=e;return{...t&&{geoBias:Ie(t)},...n}},Me=e=>{const t=e.results.map(Le),n=o(a(t));return{type:"FeatureCollection",properties:{...De(e.summary)},features:t,...n&&{bbox:n}}},Ee={requestValidation:{schema:ce},buildRequest:ye,sendRequest:_,parseResponse:Me},Oe=async(e,t)=>B(e,{...Ee,...t},"AlongRouteSearch"),Fe=I.object({query:I.string()}),ke=I.object({position:Y.optional(),limit:I.number().max(100).optional(),radiusMeters:I.number().optional(),countries:I.array(I.string()).optional(),resultType:I.array(I.string()).optional()}),je=Fe.extend(ke.shape),Ue=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",pe(r,e),de(r,"limit",e.limit),me(r,e.position),le(r,"countrySet",e.countries),de(r,"radius",e.radiusMeters),le(r,"resultSet",e.resultType),t},Be=e=>{const{position:t,...n}=e.context.geoBias||{};return{context:{...e.context,geoBias:{...t&&{position:Ie(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},We={requestValidation:{schema:je},buildRequest:Ue,sendRequest:H,parseResponse:Be},qe=async(e,t)=>B(e,{...We,...t},"Autocomplete"),Ne={alongRouteSearch:Oe,buildAlongRouteSearchRequest:ye,parseAlongRouteSearchResponse:Me,alongRouteSearchTemplate:Ee},He={autocompleteSearch:qe,buildAutocompleteSearchRequest:Ue,parseAutocompleteSearchResponse:Be,autocompleteSearchTemplate:We},_e=k.extend({id:I.string()}),Ke=["fast","short","efficient","thrilling"],$e=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/ev/id`)(e)),n=t.searchParams;return pe(n,e),n.append("id",e.id),t},Ve=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:ve(e.ratedPowerKW)}))}))}))),chargingPointAvailability:he(t.chargingStations),connectorAvailabilities:Re(t.chargingStations),...t.openingHours&&{openingHours:Ae(t.openingHours)}}:void 0;var n},Ge={requestValidation:{schema:_e},buildRequest:$e,sendRequest:H,parseResponse:Ve,parseResponseError:(e,t)=>new M(e.data?.detailedError?.message??e.message,t,e.status)},ze={buildEVChargingStationsAvailabilityRequest:$e,parseEVChargingStationsAvailabilityResponse:Ve,evChargingStationsAvailabilityTemplate:Ge},Ye=I.object({typeahead:I.boolean().optional(),offset:I.number().max(1900).optional(),radiusMeters:I.number().optional(),boundingBox:Q.optional(),countries:I.array(I.string()).optional()}),Ze=k.extend(X.shape).extend(Ye.shape).extend({query:I.string()}),Je=e=>e?Array.isArray(e)?e.join(","):"string"==typeof e?e:String(e):"",Qe=(e,t)=>{const n=e.length;if(n<=t)return e;const r=[];let a;const o=Math.ceil(n/t);for(a=0;a<n;a+=o)r.push(e[a]);return t>1&&a>=n-o&&(r.length<t?r.push(e[n-1]):r[r.length-1]=e[n-1]),r},Xe=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/geocode`)(e)}/${e.query}.json`),n=t.searchParams;pe(n,e),e.typeahead&&n.append("typeahead",String(e.typeahead)),!x(e.limit)&&n.append("limit",String(e.limit)),!x(e.offset)&&n.append("ofs",String(e.offset)),me(n,e.position),e.countries&&n.append("countrySet",Je(e.countries)),!x(e.radiusMeters)&&n.append("radius",String(e.radiusMeters));const r=e.boundingBox&&a(e.boundingBox);return r&&(n.append("topLeft",Je([r[3],r[0]])),n.append("btmRight",Je([r[1],r[2]]))),e.extendedPostalCodesFor&&n.append("extendedPostalCodesFor",Je(e.extendedPostalCodesFor)),e.mapcodes&&n.append("mapcodes",Je(e.mapcodes)),e.view&&n.append("view",e.view),e.geographyTypes&&n.append("entityTypeSet",Je(e.geographyTypes)),t},et=e=>{const{position:t,boundingBox:n,dist:r,entryPoints:a,addressRanges:o,entityType:i,id:s,...c}=e;return{type:"Feature",geometry:v(Ie(t)),...n&&{bbox:Pe(n)},id:s,properties:{...w(c,"viewport"),...r&&{distance:r},...i&&{geographyType:i.split(",")},...a&&{entryPoints:a.map(e=>({...e,position:Ie(e.position)}))},...o&&{addressRanges:{...o,from:Ie(o.from),to:Ie(o.to)}}}}},tt=e=>{const t=e.results.map(et),n=o(a(t));return{type:"FeatureCollection",features:t,...n&&{bbox:n}}},nt={requestValidation:{schema:Ze},buildRequest:Xe,sendRequest:H,parseResponse:tt},rt={buildGeocodingRequest:Xe,parseGeocodingResponse:tt,geocodingTemplate:nt},at=I.object({geometries:I.union([z,I.array(I.union([I.string(),G])).min(1).max(20)])}),ot=I.object({zoom:I.number().min(0).max(22).optional()}),it=at.extend(ot.shape),st=e=>e.map(e=>e.properties.dataSources?.geometry?.id).filter(e=>e),ct=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)),n.append("key",e.apiKey),((e,t)=>{let n;n=Array.isArray(t)?"string"==typeof t[0]?t:st(t):st(t.features),e.append("geometries",Je(n))})(n,e.geometries),de(n,"geometriesZoom",e.zoom),t},pt=e=>{const t=e.additionalData.flatMap(e=>e.geometryData?.features.map(e=>({...e,id:e.id??s(),bbox:a(e.geometry)}))).filter(e=>e);return{type:"FeatureCollection",bbox:a(t),features:t}},ut={requestValidation:{schema:it},buildRequest:ct,sendRequest:H,parseResponse:pt},lt={buildGeometryDataRequest:ct,parseGeometryDataResponse:pt,geometryDataTemplate:ut},dt=I.object({geometries:I.array(I.union([z,V]))}),mt=te.extend(dt.shape),gt=e=>{switch(e.type){case"Circle":return[{type:"CIRCLE",radius:e.radius,position:Ce(e.coordinates)}];case"Polygon":return[{type:"POLYGON",vertices:Qe(e.coordinates[0],50).map(e=>Ce(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=>gt({type:"Polygon",coordinates:e})):e.coordinates.flatMap(e=>gt({type:"Polygon",coordinates:e}));case"FeatureCollection":return e.features.flatMap(e=>gt(e.geometry));default:throw new Error(`Type ${e.type} is not supported`)}},yt=e=>{const t=new URL(`${n=e,n.customServiceBaseURL??`${n.commonBaseURL}/maps/orbis/places/geometrySearch/${n.query??""}.json`}`);var n;return ge(t,e),{url:t,data:{geometryList:e.geometries.flatMap(gt)}}},ht=e=>{const t=e.results.map(Le),n=o(a(t));return{type:"FeatureCollection",properties:{...De(e.summary)},features:t,...n&&{bbox:n}}},ft={requestValidation:{schema:mt},buildRequest:yt,sendRequest:_,parseResponse:ht},bt=async(e,t)=>B(e,{...ft,...t},"GeometrySearch"),Tt={geometrySearch:bt,buildGeometrySearchRequest:yt,parseGeometrySearchResponse:ht,geometrySearchTemplate:ft},Rt=I.object({entityId:I.string()}),vt=I.object({mapcodes:I.array(I.string()).optional(),view:I.enum(P).optional(),openingHours:I.string().optional(),timeZone:I.string().optional(),relatedPois:I.string().optional()}),St=Rt.extend(vt.shape),Ct=e=>{const t=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/place.json`)(e)}`),n=t.searchParams;return pe(n,e),de(n,"entityId",e.entityId),le(n,"mapcodes",e.mapcodes),de(n,"view",e.view),de(n,"openingHours",e.openingHours),de(n,"timeZone",e.timeZone),de(n,"relatedPois",e.relatedPois),t},Pt=e=>e.results?.length?Le(e.results[0]):void 0,It={requestValidation:{schema:St},buildRequest:Ct,sendRequest:H,parseResponse:Pt},xt={buildPlaceByIdRequest:Ct,parsePlaceByIdResponse:Pt,placeByIdTemplate:It},wt=(e,t)=>{const{data:n,message:r,status:a}=e;return new M(n?.error?.description??n?.detailedError?.message??r,t,a)},At=I.number().positive(),Lt=I.number().min(0),Dt=I.number().min(0).max(100),Mt=At.optional(),Et=Lt.optional(),Ot=I.number().min(0).max(1).optional(),Ft=I.object({speedKMH:I.number(),consumptionUnitsPer100KM:I.number()}),kt={efficiency:I.object({acceleration:Ot,deceleration:Ot,uphill:Ot,downhill:Ot}).optional()},jt=I.array(Ft).min(1).max(25),Ut=I.object({...kt,speedsToConsumptionsLiters:jt,auxiliaryPowerInLitersPerHour:Et,fuelEnergyDensityInMJoulesPerLiter:I.number().min(1).optional()}),Bt=I.object({...kt,speedsToConsumptionsKWH:jt,auxiliaryPowerInkW:Et,consumptionInKWHPerKMAltitudeGain:I.number().max(500).optional(),recuperationInKWHPerKMAltitudeLoss:Et}),Wt=I.object({currentType:I.enum(i),plugTypes:I.array(I.enum(f)).min(1),efficiency:Ot,baseLoadInkW:Et,maxPowerInkW:Et,maxVoltageInV:Et,maxCurrentInA:Et,voltageRange:I.object({minVoltageInV:Et,maxVoltageInV:I.number().optional()}).optional()}),qt=I.object({stateOfChargeInkWh:Lt,maxPowerInkW:At}),Nt=I.object({maxChargeKWH:At,batteryCurve:I.array(qt).max(20).optional(),chargingConnectors:I.array(Wt).min(1).optional(),chargingTimeOffsetInSec:Et}),Ht=I.object({consumption:Ut}),_t=I.object({consumption:Bt,charging:Nt.optional()}),Kt=I.object({lengthMeters:Mt,widthMeters:Mt,heightMeters:Mt,weightKG:Mt,axleWeightKG:Mt}).optional(),$t=I.object({variantId:I.string()}),Vt=I.object({dimensions:Kt,engine:I.union([Ht,_t]).optional()}),Gt=I.union([$t,Vt]).optional(),zt=I.object({heading:I.number().min(0).max(360).optional()}),Yt=zt.extend({currentFuelInLiters:Lt}),Zt=zt.extend({currentChargePCT:Dt}),Jt=zt.extend({currentChargeInkWh:Lt}),Qt=I.union([Zt,Jt]),Xt=I.object({minChargeAtDestinationPCT:Dt,minChargeAtChargingStopsPCT:I.number().min(0).max(50)}),en=I.object({minChargeAtDestinationInkWh:Lt,minChargeAtChargingStopsInkWh:Lt}),tn=I.union([Xt,en]),nn=I.object({chargingPreferences:tn.optional()}),rn={model:Gt,restrictions:I.object({loadTypes:I.array(I.enum(["USHazmatClass1","USHazmatClass2","USHazmatClass3","USHazmatClass4","USHazmatClass5","USHazmatClass6","USHazmatClass7","USHazmatClass8","USHazmatClass9","otherHazmatExplosive","otherHazmatGeneral","otherHazmatHarmfulToWater"])).optional(),maxSpeedKMH:I.number().min(0).max(250).optional(),adrCode:I.enum(["B","C","D","E"]).optional(),commercial:I.boolean().optional()}).optional()},an=I.object({...rn,engineType:I.undefined().optional(),state:zt.optional(),preferences:I.object({}).optional()}),on=I.object({...rn,engineType:I.literal("combustion"),state:Yt.optional(),preferences:I.object({}).optional()}),sn=I.object({...rn,engineType:I.literal("electric"),state:Qt.optional(),preferences:nn.optional()}),cn=I.union([I.discriminatedUnion("engineType",[on,sn]),an]),pn=I.object({costModel:I.object({avoid:I.array(I.enum(n)).optional(),traffic:I.enum(["live","historical"]).optional(),routeType:I.enum(Ke).optional(),avoidAreas:I.array(Q).max(10).optional(),thrillingParams:I.object({hilliness:I.enum(["low","normal","high"]).optional(),windingness:I.enum(["low","normal","high"]).optional()}).optional()}).optional(),travelMode:I.string().optional(),vehicle:cn.optional(),when:I.object({option:I.enum(["departAt","arriveBy"]),date:I.date()}).optional()}),un=["timeMinutes","remainingChargeCPT","spentChargePCT","spentFuelLiters","distanceKM"],ln=I.object({origin:Y,budget:I.object({type:I.enum(un),value:I.number().min(0)})}),dn=I.object({maxFerryLengthMeters:I.number().min(0).optional(),smoothing:I.enum(["none","weak","strong"]).optional()}),mn=pn.extend(ln.extend(dn.shape).shape),gn=e=>e.map(e=>`${e.speedKMH},${e.consumptionUnitsPer100KM}`).join(":"),yn=(e,t,n)=>{((e,t)=>{t&&(!x(t.acceleration)&&e.append("accelerationEfficiency",String(t.acceleration)),!x(t.deceleration)&&e.append("decelerationEfficiency",String(t.deceleration)),!x(t.uphill)&&e.append("uphillEfficiency",String(t.uphill)),!x(t.downhill)&&e.append("downhillEfficiency",String(t.downhill)))})(e,n.consumption.efficiency),"electric"===t?(((e,t)=>{t.speedsToConsumptionsKWH&&e.append("constantSpeedConsumptionInkWhPerHundredkm",gn(t.speedsToConsumptionsKWH)),!x(t.auxiliaryPowerInkW)&&e.append("auxiliaryPowerInkW",String(t.auxiliaryPowerInkW)),!x(t.consumptionInKWHPerKMAltitudeGain)&&e.append("consumptionInkWhPerkmAltitudeGain",String(t.consumptionInKWHPerKMAltitudeGain)),!x(t.recuperationInKWHPerKMAltitudeLoss)&&e.append("recuperationInkWhPerkmAltitudeLoss",String(t.recuperationInKWHPerKMAltitudeLoss))})(e,n.consumption),((e,t)=>{const n=t.charging;n?.maxChargeKWH&&e.append("maxChargeInkWh",String(n.maxChargeKWH))})(e,n)):((e,t)=>{const n=t.consumption;n.speedsToConsumptionsLiters&&e.append("constantSpeedConsumptionInLitersPerHundredkm",gn(n.speedsToConsumptionsLiters)),!x(n.auxiliaryPowerInLitersPerHour)&&e.append("auxiliaryPowerInLitersPerHour",String(n.auxiliaryPowerInLitersPerHour)),!x(n.fuelEnergyDensityInMJoulesPerLiter)&&e.append("fuelEnergyDensityInMJoulesPerLiter",String(n.fuelEnergyDensityInMJoulesPerLiter))})(e,n)},hn=(e,t)=>{t.model&&("variantId"in t.model?e.append("vehicleModelId",t.model.variantId):(((e,t)=>{t&&(t.lengthMeters&&e.append("vehicleLength",String(t.lengthMeters)),t.heightMeters&&e.append("vehicleHeight",String(t.heightMeters)),t.widthMeters&&e.append("vehicleWidth",String(t.widthMeters)),t.weightKG&&e.append("vehicleWeight",String(t.weightKG)),t.axleWeightKG&&e.append("vehicleAxleWeight",String(t.axleWeightKG)))})(e,t.model.dimensions),t.model.engine&&yn(e,"engineType"in t?t.engineType:void 0,t.model.engine)))},fn=(e,t)=>{t&&("electric"===t.engineType&&e.append("vehicleEngineType","electric"),hn(e,t),((e,t)=>{if(t.state&&(t.state.heading&&e.append("vehicleHeading",String(t.state.heading)),"engineType"in t))if("combustion"===t.engineType){const n=t.state;n.currentFuelInLiters&&e.append("currentFuelInLiters",String(n.currentFuelInLiters))}else if("electric"===t.engineType){const n=t.state,r=n,a=n;if(r.currentChargeInkWh)e.append("currentChargeInkWh",String(r.currentChargeInkWh));else if(a.currentChargePCT&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine.charging?.maxChargeKWH;n&&e.append("currentChargeInkWh",String(n*a.currentChargePCT/100))}}})(e,t),((e,t)=>{if(t.preferences&&"engineType"in t&&"electric"===t.engineType){const n=t.preferences;if(n.chargingPreferences){const r=n.chargingPreferences,a=r,o=r;if(a.minChargeAtChargingStopsInkWh||a.minChargeAtDestinationInkWh)e.append("minChargeAtDestinationInkWh",String(a.minChargeAtDestinationInkWh)),e.append("minChargeAtChargingStopsInkWh",String(a.minChargeAtChargingStopsInkWh));else if((o.minChargeAtChargingStopsPCT||o.minChargeAtDestinationPCT)&&t.model&&"engine"in t.model&&t.model.engine){const n=t.model.engine.charging?.maxChargeKWH;n&&(e.append("minChargeAtDestinationInkWh",String(n*o.minChargeAtDestinationPCT/100)),e.append("minChargeAtChargingStopsInkWh",String(n*o.minChargeAtChargingStopsPCT/100)))}}}})(e,t),((e,t)=>{const n=t.restrictions;n&&(ue(e,"vehicleLoadType",n.loadTypes),n.adrCode&&e.append("vehicleAdrTunnelRestrictionCode",n.adrCode),n.commercial&&e.append("vehicleCommercial",String(n.commercial)),n.maxSpeedKMH&&e.append("vehicleMaxSpeed",String(n.maxSpeedKMH)))})(e,t))},bn=(e,t)=>{const n=t.costModel;ue(e,"avoid",n?.avoid),de(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),de(e,"routeType",n?.routeType),de(e,"travelMode",t.travelMode),fn(e,t.vehicle)},Tn=e=>{const t=e.vehicle;if(t?.model&&"engine"in t.model)return t.model.engine?.charging?.maxChargeKWH},Rn=(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=Tn(t);null!=r&&e.append("energyBudgetInkWh",(r*n.value/100).toString());break}case"remainingChargeCPT":{const r=(e=>{const t=e.vehicle;if(!t?.state)return;const n=t.state;if(null!=n.currentChargePCT){const t=Tn(e);if(null!=t)return t*n.currentChargePCT/100}})(t),a=Tn(t);if(null!=a&&null!=r){const t=a*n.value/100;e.append("energyBudgetInkWh",Math.max(0,r-t).toString())}break}default:e.append(n.type,n.value.toString())}},vn=e=>{const t=(e=>{const t=u(e.origin);return`${t[1]},${t[0]}`})(e),n=new URL(((e,t)=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/routing/calculateReachableRange/${t}/json`)(e,t)),r=n.searchParams;return pe(r,e),r.delete("language"),bn(r,e),Rn(r,e),de(r,"maxFerryLengthInMeters",e.maxFerryLengthMeters),de(r,"smoothing",e.smoothing??"strong"),{method:"GET",url:n}},Sn=(e,t)=>{const n={type:"Polygon",coordinates:[e.reachableRange.boundary.map(e=>[e.longitude,e.latitude])]};return{type:"Feature",geometry:n,bbox:a(n),properties:t}},Cn={requestValidation:{schema:mn},buildRequest:vn,sendRequest:K,parseResponse:Sn,parseResponseError:wt,getAPIVersion:()=>2},Pn={buildReachableRangeRequest:vn,parseReachableRangeResponse:Sn,reachableRangeTemplate:Cn},In=e=>{const t=u(e.position),n=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/places/reverseGeocode`)(e)}/${t[1]},${t[0]}.json`),r=n.searchParams;return pe(r,e),e.allowFreeformNewline&&r.append("allowFreeformNewline",String(e.allowFreeformNewline)),e.geographyType&&r.append("entityType",Je(e.geographyType)),!x(e.heading)&&r.append("heading",String(e.heading)),e.mapcodes&&r.append("mapcodes",Je(e.mapcodes)),e.number&&r.append("number",e.number),!x(e.radiusMeters)&&r.append("radius",String(e.radiusMeters)),e.returnSpeedLimit&&r.append("returnSpeedLimit",String(e.returnSpeedLimit)),e.returnRoadUse&&r.append("returnRoadUse",String(e.returnRoadUse)),e.roadUses&&r.append("roadUse",JSON.stringify(e.roadUses)),n},xn=(e,t)=>{const n=e.addresses[0],{boundingBox:r,sideOfStreet:a,offsetPosition:o,...i}=n?.address||{};return{type:"Feature",geometry:v(u(t.position)),...r&&{bbox:Pe(r)},id:s(),...n&&{properties:{type:n?.entityType?"Geography":i.streetNumber?"Point Address":"Street",address:i,...n.dataSources&&{dataSources:n.dataSources},...n.mapcodes&&{mapcodes:n.mapcodes},...a&&{sideOfStreet:a},...o&&{offsetPosition:Se(o)},originalPosition:Se(n.position)}}}},wn=I.object({position:Y}),An=I.object({allowFreeformNewline:I.boolean().optional(),geographyType:I.array(I.string()).optional(),heading:I.number().min(-360).max(360).optional(),mapcodes:I.array(I.string()).optional(),number:I.string().optional(),radiusMeters:I.number().optional(),returnMatchType:I.boolean().optional(),returnRoadUse:I.boolean().optional(),returnSpeedLimit:I.boolean().optional(),roadUses:I.array(I.string()).optional(),view:I.enum(P).optional()}),Ln={requestValidation:{schema:wn.extend(An.shape)},buildRequest:In,sendRequest:H,parseResponse:xn},Dn={buildRevGeoRequest:In,parseRevGeoResponse:xn,reverseGeocodingTemplate:Ln},Mn=I.union([Y,V]),En=I.union([$,G]),On=I.object({locations:I.array(I.union([Mn,En])).min(1)}),Fn=I.object({computeAdditionalTravelTimeFor:I.enum(["none","all"]).optional(),vehicleHeading:I.number().min(0).max(359.5).optional(),maxAlternatives:I.number().min(0).max(5).optional(),sectionTypes:I.array(I.enum(y)).optional()}),kn=pn.extend(On.extend(Fn.shape).shape),jn=e=>(e.vehicle?.preferences)?.chargingPreferences,Un=e=>Array.isArray(e)?e:e.geometry.coordinates,Bn=(e,t,n)=>((e,t)=>e.map(e=>{const n=Ce(u(e,{useEntryPoint:t})),r=(e=>e.properties||null)(e)?.radiusMeters;return r?`circle(${n},${r})`:n}).join(":"))(t.includes("path")?((e,t,n)=>{let r;const a=e[0];r="path"===t[0]?Un(a)[0]:u(a,{useEntryPoint:n});const o=e[e.length-1];let i;if("path"===t[t.length-1]){const e=Un(o);i=e[e.length-1]}else i=u(o,{useEntryPoint:n});return[r,i]})(e,t,n):e,n),Wn=e=>({latitude:e[1],longitude:e[0]}),qn=(e,t,n)=>{const r=[],a=[];return e.forEach((o,i)=>{"path"===t[i]?((e,t,n,r,a)=>{const o=r.length;for(const i of Un(e))r.push(Wn(i));Array.isArray(e)||(e.properties.sections.leg.forEach((e,n)=>{(t>0||n>0)&&a.push({supportingPointIndex:o+e.startPointIndex,waypointSourceType:"USER_DEFINED"})}),t<n.length-1&&a.push({supportingPointIndex:o+e.geometry.coordinates.length-1,waypointSourceType:"USER_DEFINED"}))})(o,i,e,r,a):((e,t,n,r,a,o)=>{r.push(Wn(u(e,{useEntryPoint:o}))),t>0&&t<n.length-1&&a.push({supportingPointIndex:r.length-1,waypointSourceType:"USER_DEFINED"})})(o,i,e,r,a,n)}),{supportingPoints:r,...a.length&&{pointWaypoints:a}}},Nn=e=>({rectangles:e.map(e=>{const t=a(e);if(!t)throw new Error("Could not derive a bounding box from an avoidAreas rectangle");const[n,r,o,i]=t;return{southWestCorner:{latitude:r,longitude:n},northEastCorner:{latitude:i,longitude:o}}})}),Hn=e=>{const t=e.locations.map(l),n=e.useEntryPoints??"main-when-available",r=new URL(`${(e=>e.customServiceBaseURL||`${e.commonBaseURL}/maps/orbis/routing/${jn(e)?"calculateLongDistanceEVRoute":"calculateRoute"}`)(e)}/${Bn(e.locations,t,n)}/json`),a=r.searchParams;pe(a,e),"language"in e||a.append("language","en-GB"),bn(a,e),de(a,"computeTravelTimeFor",e.computeAdditionalTravelTimeFor),((e,t)=>{if(t?.guidance){const n=t.guidance;e.append("instructionsType",n.type),e.append("guidanceVersion",String(n.version??2)),e.append("instructionPhonetics",n.phonetics??"IPA"),e.append("language",t.language??"en-US")}})(a,e),!x(e.maxAlternatives)&&a.append("maxAlternatives",String(e.maxAlternatives)),((e,t,n)=>{ue(e,"sectionType",(t??(n?y:g)).map(e=>"vehicleRestricted"===e?"travelMode":e))})(a,e.sectionTypes,!!e.guidance?.type);for(const i of e.extendedRouteRepresentations??["distance","travelTime"])a.append("extendedRouteRepresentation",i);const o=((e,t,n)=>{const r=t.includes("path"),a=!!jn(e),o=e.costModel?.avoidAreas;if(!r&&!a&&!o)return null;const i=(e.vehicle?.model)?.engine?.charging;return{...r&&qn(e.locations,t,n),...a&&i&&{chargingParameters:w(i,"maxChargeKWH")},...o?.length&&{avoidAreas:Nn(o)}}})(e,t,n);return o?{method:"POST",url:r,data:o}:{method:"GET",url:r}},_n=e=>{switch(e){case"Direct_Current":return"DC";case"Alternating_Current_1_Phase":return"AC1";case"Alternating_Current_3_Phase":return"AC3";default:return}},Kn=(e,t)=>{const n=e.chargingConnectionInfo,r=e.chargingParkLocation,a=[r.coordinate.longitude,r.coordinate.latitude],o=[r.street,r.houseNumber].filter(Boolean),i=o.length>0?o.join(", "):"";return{type:"Feature",id:e.chargingParkId,geometry:{type:"Point",coordinates:a},properties:{...w(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:_n(n.chargingCurrentType),chargingSpeed:ve(n.chargingPowerInkW)}},...t&&{targetChargeInPCT:100*e.targetChargeInkWh/t},...e.chargingParkPowerInkW&&{chargingParkSpeed:ve(e.chargingParkPowerInkW)}}}},$n=(e,t)=>{const n=(t?.vehicle?.model)?.engine?.charging?.maxChargeKWH;return{lengthInMeters:e.lengthInMeters,historicTrafficTravelTimeInSeconds:e.historicTrafficTravelTimeInSeconds,liveTrafficIncidentsTravelTimeInSeconds:e.liveTrafficIncidentsTravelTimeInSeconds,noTrafficTravelTimeInSeconds:e.noTrafficTravelTimeInSeconds,trafficDelayInSeconds:e.trafficDelayInSeconds,trafficLengthInMeters:e.trafficLengthInMeters,travelTimeInSeconds:e.travelTimeInSeconds,departureTime:new Date(e.departureTime),arrivalTime:new Date(e.arrivalTime),deviationDistanceInMeters:e.deviationDistance,fuelConsumptionInLiters:e.fuelConsumptionInLiters,...e.deviationPoint&&{deviationPoint:[e.deviationPoint.longitude,e.deviationPoint.latitude]},totalChargingTimeInSeconds:e.totalChargingTimeInSeconds,batteryConsumptionInkWh:e.batteryConsumptionInkWh,...n&&e.batteryConsumptionInkWh&&{batteryConsumptionInPCT:100*e.batteryConsumptionInkWh/n},remainingChargeAtArrivalInkWh:e.remainingChargeAtArrivalInkWh,...n&&e.remainingChargeAtArrivalInkWh&&{remainingChargeAtArrivalInPCT:100*e.remainingChargeAtArrivalInkWh/n},...e.chargingInformationAtEndOfLeg&&{chargingInformationAtEndOfLeg:Kn(e.chargingInformationAtEndOfLeg,n)}}},Vn=(e,t)=>e.reduce((e,n,r)=>{const a=0===r?0:e[r-1]?.endPointIndex;let o;return x(a)||(o=0===a?n.points?.length>0?n.points.length-1:0:a+n.points?.length),e.push({...!x(a)&&{startPointIndex:a},...o&&{endPointIndex:o},summary:$n(n.summary,t),id:s()}),e},[]),Gn=e=>({id:s(),startPointIndex:e.startPointIndex,endPointIndex:e.endPointIndex}),zn=e=>({...Gn(e),index:e.importantRoadStretchIndex,streetName:e.streetName?.text,roadNumbers:e.roadNumbers?.map(e=>e.text)}),Yn=e=>({...Gn(e),countryCodeISO3:e.countryCode}),Zn=e=>"other"===e.travelMode?Gn(e):null,Jn=e=>{if(e.tec?.causes?.length)return e.tec.causes.map(e=>(e=>{switch(e){case 1:return"jam";case 2:return"accident";case 3:return"roadworks";case 4:return"narrow-lanes";case 5:return"road-closed";case 9:return"danger";case 11:return"animals-on-road";case 13:return"broken-down-vehicle";case 16:return"lane-closed";case 17:return"wind";case 18:return"fog";case 19:return"rain";case 22:return"frost";case 23:return"flooding";default:return"other"}})(e.mainCauseCode));switch(e.simpleCategory){case"JAM":return["jam"];case"ROAD_WORK":return["roadworks"];case"ROAD_CLOSURE":return["road-closed"];default:return["other"]}},Qn=e=>({...Gn(e),delayInSeconds:e.delayInSeconds,effectiveSpeedInKmh:e.effectiveSpeedInKmh,categories:Jn(e),magnitudeOfDelay:m[e.magnitudeOfDelay],tec:e.tec}),Xn=e=>({...Gn(e),lanes:e.lanes,laneSeparators:e.laneSeparators,properties:e.properties}),er=e=>({...Gn(e),maxSpeedLimitInKmh:e.maxSpeedLimitInKmh}),tr=e=>({...Gn(e),roadShieldReferences:e.roadShieldReferences}),nr=(e,t)=>(t[e]||(t[e]=[]),t[e]),rr=e=>{switch(e.sectionType){case"CAR_TRAIN":return{sectionType:"carTrain",mappingFunction:Gn};case"COUNTRY":return{sectionType:"country",mappingFunction:Yn};case"FERRY":return{sectionType:"ferry",mappingFunction:Gn};case"MOTORWAY":return{sectionType:"motorway",mappingFunction:Gn};case"PEDESTRIAN":return{sectionType:"pedestrian",mappingFunction:Gn};case"TOLL_VIGNETTE":return{sectionType:"tollVignette",mappingFunction:Yn};case"TOLL":return{sectionType:"toll",mappingFunction:Gn};case"TRAFFIC":return{sectionType:"traffic",mappingFunction:Qn};case"TRAVEL_MODE":return{sectionType:"vehicleRestricted",mappingFunction:Zn};case"TUNNEL":return{sectionType:"tunnel",mappingFunction:Gn};case"UNPAVED":return{sectionType:"unpaved",mappingFunction:Gn};case"URBAN":return{sectionType:"urban",mappingFunction:Gn};case"CARPOOL":return{sectionType:"carpool",mappingFunction:Gn};case"LOW_EMISSION_ZONE":return{sectionType:"lowEmissionZone",mappingFunction:Gn};case"LANES":return{sectionType:"lanes",mappingFunction:Xn};case"SPEED_LIMIT":return{sectionType:"speedLimit",mappingFunction:er};case"ROAD_SHIELDS":return{sectionType:"roadShields",mappingFunction:tr};case"IMPORTANT_ROAD_STRETCH":return{sectionType:"importantRoadStretch",mappingFunction:zn}}},ar=(e,t)=>{const n={leg:Vn(e.legs,t)};return((e,t)=>{if(Array.isArray(e))for(const n of e){const e=rr(n),r=e?.mappingFunction(n);r&&nr(e.sectionType,t).push(r)}})(e.sections,n),n},or=1e-4,ir=(e,t)=>Math.abs(e[0]-t[0])<or&&Math.abs(e[1]-t[1])<or,sr=(e,t)=>{const n=[];let r=0;for(const a of e.instructions){const e=[a.maneuverPoint.longitude,a.maneuverPoint.latitude];for(let n=r;n<t.length;n++){if(ir(t[n],e)){r=n;break}if(n===t.length-1)break}n.push({...a,maneuverPoint:e,pathPointIndex:r,routePath:a.routePath.map(e=>({...e,point:[e.point.longitude,e.point.latitude]}))})}return{instructions:n}},cr=(e,t)=>{const n=e.routes.map((e,n)=>((e,t,n)=>{const r={type:"LineString",coordinates:e.legs.flatMap(e=>e.points?.map(e=>[e.longitude,e.latitude]))};return{type:"Feature",geometry:r,id:s(),bbox:a(r),properties:{index:t,summary:$n(e.summary,n),sections:ar(e,n),...e.guidance&&{guidance:sr(e.guidance,r.coordinates)},...e.progress&&{progress:e.progress}}}})(e,n,t)),r=a(n);return{type:"FeatureCollection",...r&&{bbox:r},features:n}},pr={requestValidation:{schema:kn,refinements:[{check:e=>!!e.locations.map(l).includes("path")||e.locations.length>=2,message:"When passing waypoints only: at least 2 must be defined. If passing also paths, at least one path must be defined"}]},buildRequest:Hn,sendRequest:K,parseResponse:cr,parseResponseError:wt,getAPIVersion:()=>2},ur={buildCalculateRouteRequest:Hn,parseCalculateRouteResponse:cr,calculateRouteTemplate:pr},lr=["MOTORWAY","MAJOR_ROAD","OTHER_MAJOR_ROAD","SECONDARY_ROAD","LOCAL_CONNECTING_ROAD","LOCAL_ROAD_HIGH_IMPORTANCE","LOCAL_ROAD","LOCAL_ROAD_MINOR_IMPORTANCE","OTHER_ROAD"],dr={speed:"SPEED",freeFlowSpeed:"FREE_FLOW_SPEED",congestionLevel:"CONGESTION_LEVEL",travelTime:"TRAVEL_TIME",networkLength:"NETWORK_LENGTH"},mr=e=>e instanceof Date?e.toISOString().slice(0,10):e,gr=Array.from({length:24},(e,t)=>t),yr=e=>lr.indexOf(e),hr=e=>{const n=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/areaanalytics/reports/lite`)(e));pe(n.searchParams,e);const r=e=>{const t=/* @__PURE__ */new Date;return t.setDate(t.getDate()-e),t},a=Array.isArray(e.days)?{days:e.days.map(mr)}:{startDate:mr(e.startDate??r(3)),endDate:mr(e.endDate??r(2))};return{method:"POST",url:n,data:{name:e.name??`Maps SDK JS Area Analytics Report ${/* @__PURE__ */(new Date).toISOString()}`,...a,dataTypes:"all"===e.metrics?t.map(e=>dr[e]):e.metrics.map(e=>dr[e]),frcs:"all"===e.functionalRoadClasses?lr.map((e,t)=>t):e.functionalRoadClasses.map(yr),hours:"all"===e.hours?gr:e.hours,features:[{type:"Feature",geometry:e.geometry}]}}},fr=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}}),br=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},...fr(e)}),Tr=(e,t)=>{const n=new Date(e);return n.setDate(n.getDate()+t),n},Rr=(e,t)=>e.map((e,n)=>{const r=br(e);return void 0===r.date&&(r.date=Tr(t,Math.floor(n/24))),void 0===r.hour&&(r.hour=n%24),r}),vr=(e,t)=>e.map((e,n)=>{const r=br(e);return void 0===r.date&&(r.date=Tr(t,n)),r}),Sr=e=>({tileCentre:[e.lon,e.lat],...fr(e)}),Cr=e=>({startDate:new Date(e.startDate),endDate:new Date(e.endDate),labels:e.labels}),Pr=(e,t)=>{return{...e.yearly&&{yearly:e.yearly.map(br)},...e.monthly&&{monthly:e.monthly.map(br)},...e.weekly&&{weekly:e.weekly.map(br)},...e.daily&&{daily:vr(e.daily,t)},...e.hourly&&{hourly:Rr(e.hourly,t)},...e.average&&{average:(n=e.average,n.map((e,t)=>{const n=br(e);return void 0===n.day&&(n.day=Math.floor(t/24)+1),void 0===n.hour&&(n.hour=t%24),n}))}};var n},Ir={SPEED:"speed",FREE_FLOW_SPEED:"freeFlowSpeed",CONGESTION_LEVEL:"congestionLevel",TRAVEL_TIME:"travelTime",NETWORK_LENGTH:"networkLength"},xr=e=>{const t={};for(const[n,r]of Object.entries(e)){const e=Ir[n];e&&(t[e]=r.map(Cr))}return t},wr=(e,t)=>({name:e.name,timezone:e.timezone,level:e.level,baseData:fr(e.baseData),timedData:Pr(e.timedData,t),...e.tiledData&&{tiledData:{tiles:e.tiledData.tiles.map(Sr)}},...e.anomalies&&{anomalies:xr(e.anomalies)}}),Ar=e=>{const n=e.flatMap(e=>e.properties.tiledData?.tiles??[]),r={};for(const a of t){const e=n.map(e=>e[a]).filter(e=>null!=e);e.length>0&&(r[a]={min:Math.min(...e),max:Math.max(...e)})}return r},Lr=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:wr(e.properties,t),bbox:a(e.geometry)}))(e,t));return{type:"FeatureCollection",properties:{startDate:t,endDate:new Date(e.properties.endDate),metrics:e.properties.dataTypes.map(e=>Ir[e]).filter(e=>void 0!==e),heatmap:e.properties.heatmap,frcs:e.properties.frcs,ranges:Ar(n)},features:n}},Dr=I.union([I.date(),I.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in 'YYYY-MM-DD' format")]),Mr=I.union([I.object({type:I.literal("Polygon"),coordinates:I.array(I.array(I.array(I.number()))).min(1)}),I.object({type:I.literal("MultiPolygon"),coordinates:I.array(I.array(I.array(I.array(I.number())))).min(1)})]),Er=e=>e instanceof Date?e:new Date(e),Or=e=>{const t=/* @__PURE__ */new Date,n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return(e=>{const t=Er(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())})(e)<=n-1728e5},Fr={requestValidation:{schema:k.extend({name:I.string().optional(),startDate:Dr.optional(),endDate:Dr.optional(),days:I.array(Dr).min(1).optional(),metrics:I.union([I.array(I.enum([...t])).min(1),I.literal("all")]),functionalRoadClasses:I.union([I.array(I.enum([...lr])).min(1),I.literal("all")]),hours:I.union([I.array(I.number().int().min(0).max(23)).min(1),I.literal("all")]),geometry:Mr}).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?Er(e.endDate):/* @__PURE__ */new Date).getTime()-Er(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=>void 0!==e.days?e.days.every(Or):Or(e.endDate??/* @__PURE__ */new Date),{message:"Dates must be at least 2 days before today"})},buildRequest:hr,sendRequest:K,parseResponse:Lr},kr={buildTrafficAreaAnalyticsRequest:hr,parseTrafficAreaAnalyticsResponse:Lr,trafficAreaAnalyticsTemplate:Fr},jr=e=>{const t=new URL((e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/traffic/incidentDetails`)(e)),n=t.searchParams;if(pe(n,e),((e,t)=>{de(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}}}}}"),de(e,"t",t.trafficModelId),le(e,"categoryFilter",t.categoryFilter?.map(C)),le(e,"timeValidityFilter",t.timeValidityFilter)})(n,e),"bbox"in e&&e.bbox){const r=a(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})},Ur=e=>({description:e.description,code:e.code,category:d(e.iconCategory)}),Br=e=>{const t=e.properties;return{type:"Feature",id:t.id,geometry:e.geometry,properties:{id:t.id,category:d(t.iconCategory),magnitudeOfDelay:m[t.magnitudeOfDelay]??"unknown",events:(t.events??[]).map(Ur),...t.startTime&&{startTime:new Date(t.startTime)},...t.endTime&&{endTime:new Date(t.endTime)},...t.from&&{from:t.from},...t.to&&{to:t.to},...void 0!==t.length&&{lengthInMeters:t.length},...void 0!==t.delay&&{delayInSeconds:t.delay},...t.roadNumbers&&{roadNumbers:t.roadNumbers},timeValidity:t.timeValidity,...t.probabilityOfOccurrence&&{probabilityOfOccurrence:t.probabilityOfOccurrence},...void 0!==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,...void 0!==e.offset&&{offset:e.offset}}))})}}};var n},Wr=e=>({type:"FeatureCollection",features:(e.incidents??[]).filter(e=>null!==e).map(Br)}),qr={requestValidation:{schema:k.extend({bbox:Q.optional(),ids:I.array(I.string()).optional(),trafficModelId:I.string().optional(),categoryFilter:I.array(I.enum([...S])).optional(),timeValidityFilter:I.array(I.enum(["present","future"])).optional()}).refine(e=>!(e.bbox&&e.ids),{message:"Provide either bbox or ids, not both"})},buildRequest:jr,sendRequest:K,parseResponse:Wr},Nr={alongRouteSearch:Ne,reverseGeocode:Dn,geocode:rt,geometryData:lt,geometrySearch:Tt,calculateRoute:ur,reachableRange:Pn,evChargingStationsAvailability:ze,trafficAreaAnalytics:kr,trafficIncidentDetails:{buildTrafficIncidentDetailsRequest:jr,parseTrafficIncidentDetailsResponse:Wr,trafficIncidentDetailsTemplate:qr},placeByID:xt,autocompleteSearch:He},Hr=async(e,t)=>B(e,{...Ge,...t},"EVChargingStationsAvailability"),_r=async e=>{const t=e.properties.dataSources?.chargingAvailability?.id;if(t)try{const n=await Hr({id:t}),r=e.properties.poi;return n?{...e,properties:{...e.properties,...r&&{poi:{...r,openingHours:n.openingHours}},chargingPark:{...e.properties.chargingPark,availability:n}}}:void 0}catch(n){return void console.error(n)}};async function Kr(e,t){const n=[];for(const r of e.features){const e=await _r(r);e?n.push(e):t?.excludeIfAvailabilityUnknown||n.push(r)}return{...e,features:n,bbox:a(n)}}var $r=e=>Boolean(e&&"availability"in e&&e.availability),Vr=I.array(I.number()).min(2),Gr=I.object({type:I.literal("Polygon"),coordinates:I.array(I.array(I.array(I.number()))),bbox:I.array(I.number()).optional()}),zr=I.object({type:I.literal("MultiPolygon"),coordinates:I.array(I.array(I.array(I.array(I.number())))),bbox:I.array(I.number()).optional()}),Yr=I.object({type:I.literal("Circle"),coordinates:Vr,radius:I.number().positive()}),Zr=I.object({type:I.literal("FeatureCollection"),features:I.array(I.object({type:I.literal("Feature"),geometry:I.union([Gr,zr]),properties:I.any().optional()}))}),Jr=I.union([Gr,zr,Yr,Zr]),Qr=I.tuple([I.number(),I.number(),I.number(),I.number()]),Xr=I.object({bbox:Qr}),ea=I.union([Qr,Xr]),ta=1e4,na=I.enum(["POI","PointAddress","Street"]),ra=I.object({municipalities:I.array(I.string()).optional(),boundingBoxes:I.array(ea).optional(),geometries:I.array(Jr).optional(),placeTypes:I.array(na).min(1).optional(),areaId:I.string().min(1).optional(),areaTags:I.array(I.string().min(1)).min(1).optional(),offset:I.number().int().min(0).max(ta).optional(),limit:I.number().int().min(1).max(ta).optional()}),aa=te.extend(Ye.extend(ra.shape).shape),oa=e=>{const[t,n]=e.coordinates,r=e.radius/6371e3*(180/Math.PI),a=r/Math.cos(n*Math.PI/180),o=[];for(let i=0;i<64;i++){const e=2*Math.PI*i/64;o.push([t+a*Math.cos(e),n+r*Math.sin(e)])}return o.push(o[0]),{type:"Polygon",coordinates:[o]}},ia=e=>{switch(e.type){case"Polygon":case"MultiPolygon":return[e];case"Circle":return[oa(e)];case"FeatureCollection":return e.features.map(e=>e.geometry)}},sa=e=>(e=>{if(e.length<2)return e;const[t,n]=[e[0],e[e.length-1]];return t[0]===n[0]&&t[1]===n[1]?e:[...e,[...t]]})((e=>e.filter((t,n)=>0===n||t[0]!==e[n-1][0]||t[1]!==e[n-1][1]))(e)),ca=e=>"Polygon"===e.type?{...e,coordinates:e.coordinates.map(sa)}:{...e,coordinates:e.coordinates.map(e=>e.map(sa))},pa={POI:"POI",PointAddress:"Point Address",Street:"Street"},ua=e=>{const t=(e=>{const t=/* @__PURE__ */new Set;for(const n of e.categorySet??[])t.add(Number(n));return e.preferredCategoryId&&t.add(Number(e.preferredCategoryId)),[...t].filter(e=>Number.isFinite(e))})(e);t.sort((e,t)=>t-e);const n=/* @__PURE__ */new Set,r=[];for(const a of t){const e=R[a];e&&!n.has(e)&&(n.add(e),r.push(e))}return r},la=e=>{const{id:t,position:n,address:r,score:a,distance_m:o,type:i,viewport:s}=e,c=pa[i??"POI"],p=(e=>{if(e?.name)return{name:e.name,categories:ua(e),localizedCategories:e.classifications?.map(e=>e.name)??[],...e.phone&&{phone:e.phone},...e.url&&{url:e.url},...e.brands?.length&&{brands:e.brands.map(e=>e.name)},...e.timeZone?.ianaId&&{timeZone:e.timeZone}}})(e.poi),u=(e=>{if(!e)return;const[[t,n],[r,a]]=e.coordinates;return[t,n,r,a]})(s);return{type:"Feature",id:t,geometry:v(n),...u&&{bbox:u},properties:{type:c,...r&&{address:r},...p&&{poi:p},...void 0!==a&&{score:a},...void 0!==o&&{distance:o},...e.area_id&&{areaId:e.area_id},...e.area_country&&{areaCountry:e.area_country},...e.area_tags?.length&&{areaTags:e.area_tags}}}},da=(e,t)=>{const n=!!p(t.position),r=n?p(t.position):null;return{query:t.query??"",queryType:n?"NEARBY":"NON_NEAR",queryTime:0,numResults:e.hits.length,offset:t.offset??0,totalResults:e.total,fuzzyLevel:0,...r&&{geoBias:r}}},ma={requestValidation:{schema:aa,refinements:[{check:e=>!!(e.position||e.boundingBox||e.boundingBoxes?.length||e.geometries?.length||e.municipalities?.length||e.areaId),message:"A geographic bias is required: provide one of position, boundingBox(es), geometries, municipalities, or areaId."},{check:e=>(e.offset??0)+(e.limit??10)<=ta,message:"offset + limit must not exceed 10000 (the places-api pagination window; when limit is omitted the backend defaults to 10)."}]},buildRequest:e=>{const t=new URL("/places",(e=>e.customServiceBaseURL??"https://search-places-poc.whitebush-bbe9c5f7.westeurope.azurecontainerapps.io")(e)),n=(e=>{const t=p(e.position);if(t)return{coordinates:t,radius_km:e.radiusMeters&&e.radiusMeters>0?e.radiusMeters/1e3:2}})(e),r=(e=>e.poiCategories?.length?e.poiCategories.map(e=>String(T[e])):void 0)(e),o=(e=>{const t=[...e.boundingBox?[e.boundingBox]:[],...e.boundingBoxes??[]].map(e=>a(e)).filter(e=>void 0!==e);return t.length?t:void 0})(e),i=(e=>{if(!e.geometries?.length)return;const t=e.geometries.flatMap(ia).map(ca);return t.length?t:void 0})(e),s=(e=>e.municipalities?.length?e.municipalities:void 0)(e);return{url:t,data:{...e.query&&{q:e.query},...e.countries?.[0]&&{country:e.countries[0]},...s&&{municipalities:s},...e.poiBrands?.[0]&&{brand:e.poiBrands[0]},...r&&{categories:r},...e.placeTypes?.length&&{types:e.placeTypes},...e.areaId&&{area_id:e.areaId},...e.areaTags?.length&&{area_tags:e.areaTags},...n&&{near:n},...o&&{bboxes:o},...i&&{geometries:i},...void 0!==e.offset&&{from:e.offset},...void 0!==e.limit&&{size:e.limit}}}},sendRequest:_,parseResponse:(e,t)=>{const n=e.hits.map(la),r=o(a(n));return{type:"FeatureCollection",properties:da(e,t),features:n,...r&&{bbox:r}}}},ga=async(e,t)=>B(e,{...ma,...t},"ExplorationSearch"),ya=async(e,t)=>B(e,{...nt,...t},"Geocode"),ha=async e=>{const t=await ya({query:e,limit:1});if(!t.features[0])throw new Error(`geocodeOne: no results found for "${e}"`);return t.features[0]};async function fa(e,t){const n=await B(e,{...ut,...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 ba=async(e,t)=>B(e,{...It,...t},"PlaceById"),Ta=/* @__PURE__ */new Map,Ra=/* @__PURE__ */new Map,va="en-GB",Sa=e=>e??va,Ca=e=>e.toLowerCase().replaceAll(/[\s\-_,]+/g,""),Pa=e=>{const t={};for(const n of e){const e=[n.name,...n.synonyms].map(Ca);for(const r of e)t[r]=n}return t},Ia=k.extend({filters:I.array(I.string()).optional()}),xa=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)},wa={requestValidation:{schema:Ia},buildRequest:e=>{const t=e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/poiCategories.json`,n=new URL(t);return pe(n.searchParams,e),n},getAPIVersion:()=>1,sendRequest:H,parseResponse:e=>({poiCategories:e.poiCategories.map(xa).filter(e=>null!==e)})},Aa=(e,t)=>{const n=(e=>Ra.get(e??va)??{})(e),r=/* @__PURE__ */new Map;for(const a of t){const e=Ca(a);for(const[t,a]of Object.entries(n))t.includes(e)&&a&&r.set(a.code,a)}for(const a of r.values())for(const e of a.childCategoryCodes)r.delete(e);return[...r.values()]},La=async(e={})=>{const{language:t}=h(e);let n=(e=>Ta.get(Sa(e)))(t);return n||(n=(await B(e,wa,"POICategories")).poiCategories,((e,t)=>{const n=Sa(e);Ta.set(n,t),Ra.set(n,Pa(t))})(t,n)),e.filters?.length?{poiCategories:Aa(t,e.filters)}:{poiCategories:n}},Da=async(e={})=>{const{poiCategories:t}=await La(e);return t.map(e=>e.code)},Ma=async(e,t)=>B(e,{...Cn,...t},"Reachable Range"),Ea=async(e,t,n)=>{const r=[];for(const a of e){t?.signal?.throwIfAborted();try{r.push(await Ma(a,n))}catch(i){if(!(i instanceof M)||403===i.status||429===i.status)throw i}}const o=a(r);return{type:"FeatureCollection",...o&&{bbox:o},features:r}},Oa=async(e,t)=>B(e,{...Ln,...t},"ReverseGeocode"),Fa=async(e,t)=>B(e,{...pr,...t},"Routing"),ka=I.object({minFuzzyLevel:I.number().min(1).max(4).optional(),maxFuzzyLevel:I.number().min(1).max(4).optional()}),ja=te.extend(Ye.extend(ka.shape).shape),Ua=e=>{let t;switch(e.type){case"COORDINATE":t={...e,details:{position:Ie(e.details)}};break;case"NEARBY":t={...e,details:{position:Ie({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},Ba={requestValidation:{schema:ja},buildRequest:e=>{const t=new URL(`${(e=>e.customServiceBaseURL??`${e.commonBaseURL}/maps/orbis/places/search/${e.query??""}.json`)(e)}`);ge(t,e);const n=t.searchParams;de(n,"typeahead",e.typeahead),de(n,"ofs",e.offset),le(n,"countrySet",e.countries),de(n,"radius",e.radiusMeters);const r=e.boundingBox&&a(e.boundingBox);return r&&(n.append("topLeft",Je([r[3],r[0]])),n.append("btmRight",Je([r[1],r[2]]))),de(n,"minFuzzyLevel",e.minFuzzyLevel),de(n,"maxFuzzyLevel",e.maxFuzzyLevel),t},sendRequest:H,parseResponse:e=>{const t=e.results.map(Le),n=o(a(t));return{type:"FeatureCollection",properties:{...De(e.summary),queryIntent:e.summary.queryIntent.map(Ua)},features:t,...n&&{bbox:n}}}},Wa=async(e,t)=>"route"in e?Oe(e,t):"geometries"in e?bt(e,t):(async(e,t)=>B(e,{...Ba,...t},"FuzzySearch"))(e,t),qa=async e=>{const t=await Wa({query:e,limit:1});if(!t.features[0])throw new Error(`searchOne: no results found for "${e}"`);return t.features[0]},Na=async(e,t)=>B(e,{...Fr,...t},"TrafficAreaAnalytics"),Ha=async(e,t)=>B(e,{...qr,...t},"TrafficIncidentDetails");export{D as APIErrorCode,L as SDKError,M as SDKServiceError,Oe as alongRouteSearch,qe as autocompleteSearch,un as budgetTypes,O as buildResponseError,F as buildValidationError,Ma as calculateReachableRange,Ea as calculateReachableRanges,Fa as calculateRoute,Nr as customizeService,Hr as evChargingStationsAvailability,ga as explorationSearch,ya as geocode,ha as geocodeOne,fa as geometryData,La as getPOICategories,Da as getPOICategoryCodes,_r as getPlaceWithEVAvailability,Kr as getPlacesWithEVAvailability,$r as hasChargingAvailability,E as parseDefaultResponseError,ba as placeById,Oa as reverseGeocode,Ke as routeTypes,Wa as search,qa as searchOne,Na as trafficAreaAnalytics,Ha as trafficIncidentDetails};
2
2
  //# sourceMappingURL=services.es.js.map