@garagem-ai/site-sdk 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/maps.ts ADDED
@@ -0,0 +1,743 @@
1
+ /**
2
+ * maps.fndn.ai helpers: static map / street view image URLs, boundary
3
+ * layers for MapLibre, and travel time. All of them consume the coordinates
4
+ * the public listings API already masked for the site — nothing here calls
5
+ * Google directly or adds precision.
6
+ *
7
+ * URL shapes mirror `@garagem/geo` (`buildGoogleStaticMapImageUrl`,
8
+ * `buildStreetViewImageUrl`); the SDK keeps its own copy because the
9
+ * published package cannot bundle the private geo workspace package. A
10
+ * parity test in `tests/maps-geo-parity.test.ts` keeps the two in sync.
11
+ */
12
+
13
+ import type { FetchLike } from "./fetchers";
14
+ import type {
15
+ BoundaryCity,
16
+ BoundaryFeature,
17
+ BoundaryFeatureCollection,
18
+ BoundaryLayer,
19
+ BoundaryLayerOptions,
20
+ ListingWithLocation,
21
+ MapsBaseOptions,
22
+ MapsCoordinates,
23
+ MapsFetchOptions,
24
+ NeighborhoodBoundary,
25
+ NeighborhoodBoundaryOptions,
26
+ StaticMapOptions,
27
+ StreetViewAvailability,
28
+ StreetViewAvailabilityOptions,
29
+ StreetViewOptions,
30
+ TravelDestination,
31
+ TravelMode,
32
+ TravelTime,
33
+ TravelTimeCache,
34
+ TravelTimeCacheOptions,
35
+ TravelTimeElement,
36
+ TravelTimeOptions,
37
+ TravelTimesOptions,
38
+ } from "./types-maps";
39
+
40
+ export const DEFAULT_MAPS_BASE_URL = "https://maps.fndn.ai";
41
+ /** Header maps.fndn.ai meters per site. Mirrors `apps/maps` `SITE_HEADER`. */
42
+ export const MAPS_SITE_HEADER = "X-Garagem-Site";
43
+ /** Google Static Maps / Street View Static edge ceiling. */
44
+ export const MAPS_MAX_IMAGE_EDGE = 640;
45
+
46
+ const TRAVEL_MODES: ReadonlySet<string> = new Set<TravelMode>([
47
+ "driving",
48
+ "walking",
49
+ "bicycling",
50
+ "transit",
51
+ ]);
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // Coordinates (masked by the API; only ever coarsened here)
55
+ // ---------------------------------------------------------------------------
56
+
57
+ function finite(value: unknown): number | null {
58
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
59
+ }
60
+
61
+ /**
62
+ * Coordinates the public API returned for a listing, or `null` when the
63
+ * listing has none (or a `0,0` placeholder). Values are passed through
64
+ * untouched — they are already masked per the site's precision setting.
65
+ */
66
+ export function listingCoordinates(
67
+ listing: ListingWithLocation
68
+ ): MapsCoordinates | null {
69
+ const raw = listing?.location?.coordinates;
70
+ const lat = finite(raw?.lat);
71
+ const lng = finite(raw?.lng);
72
+ if (lat == null || lng == null) return null;
73
+ if (lat === 0 && lng === 0) return null;
74
+ if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return null;
75
+ return { lat, lng };
76
+ }
77
+
78
+ /** Number of decimal places carried by a coordinate (`-23.55` → 2). */
79
+ export function coordinateDecimals(value: number): number {
80
+ if (!Number.isFinite(value)) return 0;
81
+ const text = Math.abs(value).toString();
82
+ if (text.includes("e")) {
83
+ // Scientific notation only shows up for tiny values; count via toFixed.
84
+ const fixed = Math.abs(value).toFixed(12).replace(/0+$/, "");
85
+ const dot = fixed.indexOf(".");
86
+ return dot === -1 ? 0 : fixed.length - dot - 1;
87
+ }
88
+ const dot = text.indexOf(".");
89
+ return dot === -1 ? 0 : text.length - dot - 1;
90
+ }
91
+
92
+ function roundTo(value: number, decimals: number): number {
93
+ const factor = 10 ** decimals;
94
+ return Math.round(value * factor) / factor;
95
+ }
96
+
97
+ /**
98
+ * Reduce coordinates to at most `maxDecimals` places. Never adds precision:
99
+ * a point the API already masked to 3 decimals stays at 3 when asked for 6.
100
+ */
101
+ export function coarsenCoordinates(
102
+ coordinates: MapsCoordinates,
103
+ maxDecimals: number | undefined
104
+ ): MapsCoordinates {
105
+ if (maxDecimals == null || !Number.isFinite(maxDecimals)) return coordinates;
106
+ const limit = Math.max(0, Math.floor(maxDecimals));
107
+ return {
108
+ lat:
109
+ coordinateDecimals(coordinates.lat) > limit
110
+ ? roundTo(coordinates.lat, limit)
111
+ : coordinates.lat,
112
+ lng:
113
+ coordinateDecimals(coordinates.lng) > limit
114
+ ? roundTo(coordinates.lng, limit)
115
+ : coordinates.lng,
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Highest zoom that does not overstate the precision of the coordinates.
121
+ * 3 decimals (≈100 m, the public default) caps at 16; 2 (≈1 km) at 13;
122
+ * 1 or fewer at 11; 4+ decimals get the full Google range (21).
123
+ */
124
+ export function maxZoomForCoordinates(coordinates: MapsCoordinates): number {
125
+ const decimals = Math.min(
126
+ coordinateDecimals(coordinates.lat),
127
+ coordinateDecimals(coordinates.lng)
128
+ );
129
+ if (decimals >= 4) return 21;
130
+ if (decimals === 3) return 16;
131
+ if (decimals === 2) return 13;
132
+ return 11;
133
+ }
134
+
135
+ function clampInt(
136
+ value: number | undefined,
137
+ fallback: number,
138
+ min: number,
139
+ max: number
140
+ ): number {
141
+ if (value == null || !Number.isFinite(value)) return fallback;
142
+ return Math.min(max, Math.max(min, Math.round(value)));
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // URL plumbing
147
+ // ---------------------------------------------------------------------------
148
+
149
+ export function normalizeMapsBaseUrl(baseUrl: string | undefined): string {
150
+ const raw = (baseUrl ?? "").trim();
151
+ if (!raw) return DEFAULT_MAPS_BASE_URL;
152
+ return raw.replace(/\/+$/, "") || DEFAULT_MAPS_BASE_URL;
153
+ }
154
+
155
+ function siteTag(options: MapsBaseOptions | undefined): string | null {
156
+ const value = options?.siteId?.trim();
157
+ return value ? value : null;
158
+ }
159
+
160
+ function mapsUrl(
161
+ path: string,
162
+ params: Record<string, string | number | undefined>,
163
+ options: MapsBaseOptions | undefined
164
+ ): string {
165
+ const url = new URL(path, `${normalizeMapsBaseUrl(options?.mapsBaseUrl)}/`);
166
+ for (const [key, value] of Object.entries(params)) {
167
+ if (value === undefined || value === "") continue;
168
+ url.searchParams.set(key, String(value));
169
+ }
170
+ const site = siteTag(options);
171
+ if (site) url.searchParams.set("site", site);
172
+ return url.toString();
173
+ }
174
+
175
+ function resolveFetch(options: MapsFetchOptions | undefined): FetchLike {
176
+ const custom = options?.fetch;
177
+ if (custom) return custom;
178
+ const global = (globalThis as { fetch?: FetchLike }).fetch;
179
+ if (!global) {
180
+ throw new TypeError(
181
+ "Garagem SDK: no fetch available. Pass `fetch` in the options."
182
+ );
183
+ }
184
+ return global;
185
+ }
186
+
187
+ async function mapsFetchJson<T>(
188
+ url: string,
189
+ options: MapsFetchOptions | undefined,
190
+ init?: RequestInit
191
+ ): Promise<T | null> {
192
+ const headers = new Headers(init?.headers);
193
+ headers.set("accept", "application/json");
194
+ const site = siteTag(options);
195
+ if (site) headers.set(MAPS_SITE_HEADER, site);
196
+ try {
197
+ const response = await resolveFetch(options)(url, { ...init, headers });
198
+ if (!response.ok) return null;
199
+ return (await response.json()) as T;
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // 1. Static map + street view
207
+ // ---------------------------------------------------------------------------
208
+
209
+ /**
210
+ * `GET /v1/static-map` URL for an `<img>`. Returns `null` when the listing
211
+ * has no public coordinates. Zoom is capped by the coordinate precision.
212
+ */
213
+ export function listingStaticMapUrl(
214
+ listing: ListingWithLocation,
215
+ options: StaticMapOptions = {}
216
+ ): string | null {
217
+ const raw = listingCoordinates(listing);
218
+ if (!raw) return null;
219
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
220
+ const zoomCeiling = maxZoomForCoordinates(coordinates);
221
+ const zoom = Math.min(zoomCeiling, clampInt(options.zoom, 15, 1, 21));
222
+ const markerColor = options.markerColor ?? "red";
223
+ return mapsUrl(
224
+ "/v1/static-map",
225
+ {
226
+ lat: coordinates.lat,
227
+ lng: coordinates.lng,
228
+ zoom,
229
+ width: clampInt(options.width, 600, 1, MAPS_MAX_IMAGE_EDGE),
230
+ height: clampInt(options.height, 300, 1, MAPS_MAX_IMAGE_EDGE),
231
+ scale: options.scale === 1 ? 1 : 2,
232
+ maptype: options.style,
233
+ markerColor: markerColor !== "red" ? markerColor : undefined,
234
+ hidePoi: options.hidePoi ? "1" : undefined,
235
+ },
236
+ options
237
+ );
238
+ }
239
+
240
+ /**
241
+ * `GET /v1/street-view` URL for an `<img>`. Returns `null` when the listing
242
+ * has no public coordinates. Google picks the nearest panorama to the
243
+ * (masked) point, so pair it with `listingStreetViewAvailable`.
244
+ */
245
+ export function listingStreetViewUrl(
246
+ listing: ListingWithLocation,
247
+ options: StreetViewOptions = {}
248
+ ): string | null {
249
+ const raw = listingCoordinates(listing);
250
+ if (!raw) return null;
251
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
252
+ const width = clampInt(options.width, 640, 1, MAPS_MAX_IMAGE_EDGE);
253
+ const height = clampInt(options.height, 640, 1, MAPS_MAX_IMAGE_EDGE);
254
+ return mapsUrl(
255
+ "/v1/street-view",
256
+ {
257
+ lat: coordinates.lat,
258
+ lng: coordinates.lng,
259
+ size: `${width}x${height}`,
260
+ fov: clampInt(options.fov, 90, 10, 120),
261
+ heading: clampInt(options.heading, 0, 0, 360),
262
+ pitch: clampInt(options.pitch, 10, -90, 90),
263
+ },
264
+ options
265
+ );
266
+ }
267
+
268
+ /** `GET /v1/street-view/metadata` URL (free on Google's side). */
269
+ export function listingStreetViewMetadataUrl(
270
+ listing: ListingWithLocation,
271
+ options: StreetViewAvailabilityOptions = {}
272
+ ): string | null {
273
+ const raw = listingCoordinates(listing);
274
+ if (!raw) return null;
275
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
276
+ return mapsUrl(
277
+ "/v1/street-view/metadata",
278
+ { lat: coordinates.lat, lng: coordinates.lng },
279
+ options
280
+ );
281
+ }
282
+
283
+ type StreetViewMetadataPayload = {
284
+ status?: unknown;
285
+ pano_id?: unknown;
286
+ date?: unknown;
287
+ };
288
+
289
+ /**
290
+ * Whether Google has a panorama near the listing. Metadata lookups are free,
291
+ * so call this before rendering `listingStreetViewUrl` (which is billed).
292
+ * Network failures resolve to `{ available: false, status: "ERROR" }`.
293
+ */
294
+ export async function listingStreetViewAvailable(
295
+ listing: ListingWithLocation,
296
+ options: StreetViewAvailabilityOptions = {}
297
+ ): Promise<StreetViewAvailability> {
298
+ const url = listingStreetViewMetadataUrl(listing, options);
299
+ if (!url) {
300
+ return { available: false, status: "NO_COORDINATES", url: "" };
301
+ }
302
+ const data = await mapsFetchJson<StreetViewMetadataPayload>(url, options);
303
+ const status = typeof data?.status === "string" ? data.status : "ERROR";
304
+ const result: StreetViewAvailability = {
305
+ available: status === "OK",
306
+ status,
307
+ url,
308
+ };
309
+ if (typeof data?.pano_id === "string") result.panoId = data.pano_id;
310
+ if (typeof data?.date === "string") result.date = data.date;
311
+ return result;
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // 2. Boundary layers
316
+ // ---------------------------------------------------------------------------
317
+
318
+ /** `"São Paulo"` → `sao_paulo`; existing slugs pass through. */
319
+ export function boundaryCitySlug(city: string): string {
320
+ return city
321
+ .normalize("NFD")
322
+ .replace(/[̀-ͯ]/g, "")
323
+ .toLowerCase()
324
+ .replace(/[^a-z0-9]+/g, "_")
325
+ .replace(/^_+|_+$/g, "");
326
+ }
327
+
328
+ /** maps.fndn.ai layer id for a city's boundaries (`sao_paulo_boundaries`). */
329
+ export function boundaryLayerId(city: BoundaryCity): string {
330
+ const slug = boundaryCitySlug(city);
331
+ return slug.endsWith("_boundaries") ? slug : `${slug}_boundaries`;
332
+ }
333
+
334
+ /**
335
+ * URL for a city's boundary layer. `kind` picks the representation:
336
+ * `tilejson` (default) for MapLibre vector sources, `tiles` for the raw
337
+ * `{z}/{x}/{y}` template, `geojson` for the whole city, `layer` for the
338
+ * descriptor served by `/v1/layers/:id`.
339
+ */
340
+ export function boundaryLayerUrl(
341
+ city: BoundaryCity,
342
+ options: BoundaryLayerOptions = {}
343
+ ): string {
344
+ const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
345
+ const id = boundaryLayerId(city);
346
+ const slug = id.replace(/_boundaries$/, "");
347
+ switch (options.kind ?? "tilejson") {
348
+ case "layer":
349
+ return `${base}/v1/layers/${id}`;
350
+ case "tiles":
351
+ return `${base}/martin/${id}/{z}/{x}/{y}`;
352
+ case "geojson":
353
+ return `${base}/api/boundaries/${slug}`;
354
+ default:
355
+ return `${base}/martin/${id}`;
356
+ }
357
+ }
358
+
359
+ /** GeoJSON URL for one named outline (`/api/boundaries/:city/:name`). */
360
+ export function neighborhoodBoundaryUrl(
361
+ city: BoundaryCity,
362
+ neighborhood: string,
363
+ options: NeighborhoodBoundaryOptions = {}
364
+ ): string {
365
+ const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
366
+ const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
367
+ const url = new URL(
368
+ `${base}/api/boundaries/${slug}/${encodeURIComponent(neighborhood.trim())}`
369
+ );
370
+ if (options.source && options.source !== "listaaberta") {
371
+ url.searchParams.set("source", options.source);
372
+ }
373
+ return url.toString();
374
+ }
375
+
376
+ type LayerPayload = {
377
+ ok?: unknown;
378
+ layer?: Record<string, unknown>;
379
+ };
380
+
381
+ function asNumber(value: unknown, fallback: number): number {
382
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
383
+ }
384
+
385
+ /** Fetch the layer descriptor (`/v1/layers/:id`). `null` when unknown. */
386
+ export async function getBoundaryLayer(
387
+ city: BoundaryCity,
388
+ options: MapsFetchOptions = {}
389
+ ): Promise<BoundaryLayer | null> {
390
+ const data = await mapsFetchJson<LayerPayload>(
391
+ boundaryLayerUrl(city, { ...options, kind: "layer" }),
392
+ options
393
+ );
394
+ const layer = data?.layer;
395
+ if (!data?.ok || !layer || typeof layer.id !== "string") return null;
396
+ const rawSourceLayers = Array.isArray(layer.source_layers)
397
+ ? layer.source_layers
398
+ : [];
399
+ return {
400
+ id: layer.id,
401
+ name: typeof layer.name === "string" ? layer.name : layer.id,
402
+ description: typeof layer.description === "string" ? layer.description : "",
403
+ city: typeof layer.city === "string" ? layer.city : undefined,
404
+ tiles: typeof layer.tiles === "string" ? layer.tiles : "",
405
+ tilejson: typeof layer.tilejson === "string" ? layer.tilejson : "",
406
+ geojson: typeof layer.geojson === "string" ? layer.geojson : undefined,
407
+ sourceLayers: rawSourceLayers
408
+ .filter(
409
+ (entry): entry is Record<string, unknown> =>
410
+ !!entry && typeof entry === "object"
411
+ )
412
+ .map((entry) => ({
413
+ id: String(entry.id ?? ""),
414
+ label: String(entry.label ?? entry.id ?? ""),
415
+ minzoom: typeof entry.minzoom === "number" ? entry.minzoom : undefined,
416
+ maxzoom: typeof entry.maxzoom === "number" ? entry.maxzoom : undefined,
417
+ })),
418
+ minzoom: asNumber(layer.minzoom, 0),
419
+ maxzoom: asNumber(layer.maxzoom, 14),
420
+ attribution:
421
+ typeof layer.attribution === "string" ? layer.attribution : undefined,
422
+ available: layer.available !== false,
423
+ };
424
+ }
425
+
426
+ function isFeature(value: unknown): value is BoundaryFeature {
427
+ return (
428
+ !!value &&
429
+ typeof value === "object" &&
430
+ (value as { type?: unknown }).type === "Feature"
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Resolve a neighbourhood outline so a site map can draw it. maps.fndn.ai
436
+ * matches the name case-insensitively: an exact match returns one feature,
437
+ * a partial match may return several (`candidates`), none returns
438
+ * `feature: null`.
439
+ */
440
+ export async function neighborhoodBoundaryLayer(
441
+ city: BoundaryCity,
442
+ neighborhood: string,
443
+ options: NeighborhoodBoundaryOptions = {}
444
+ ): Promise<NeighborhoodBoundary> {
445
+ const url = neighborhoodBoundaryUrl(city, neighborhood, options);
446
+ const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
447
+ const result: NeighborhoodBoundary = {
448
+ city: slug,
449
+ neighborhood: neighborhood.trim(),
450
+ feature: null,
451
+ candidates: [],
452
+ url,
453
+ tiles: boundaryLayerUrl(city, { ...options, kind: "tiles" }),
454
+ };
455
+ if (!result.neighborhood) return result;
456
+ const data = await mapsFetchJson<BoundaryFeature | BoundaryFeatureCollection>(
457
+ url,
458
+ options
459
+ );
460
+ if (!data) return result;
461
+ if (isFeature(data)) {
462
+ result.feature = data;
463
+ result.candidates = [data];
464
+ return result;
465
+ }
466
+ const features = Array.isArray(data.features)
467
+ ? data.features.filter(isFeature)
468
+ : [];
469
+ result.candidates = features;
470
+ const wanted = result.neighborhood.toLocaleLowerCase("pt-BR");
471
+ result.feature =
472
+ features.find(
473
+ (feature) =>
474
+ typeof feature.properties?.name === "string" &&
475
+ feature.properties.name.toLocaleLowerCase("pt-BR") === wanted
476
+ ) ?? (features.length === 1 ? features[0] : null);
477
+ return result;
478
+ }
479
+
480
+ // ---------------------------------------------------------------------------
481
+ // 3. Travel time
482
+ // ---------------------------------------------------------------------------
483
+
484
+ /** Small LRU with TTL. Lives per module instance (one per page/worker). */
485
+ export function createTravelTimeCache(
486
+ options: TravelTimeCacheOptions = {}
487
+ ): TravelTimeCache {
488
+ const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? 200));
489
+ const ttlMs = Math.max(0, options.ttlMs ?? 15 * 60 * 1000);
490
+ const entries = new Map<string, { value: TravelTime; expiresAt: number }>();
491
+ return {
492
+ get(key) {
493
+ const hit = entries.get(key);
494
+ if (!hit) return undefined;
495
+ if (hit.expiresAt <= Date.now()) {
496
+ entries.delete(key);
497
+ return undefined;
498
+ }
499
+ // Refresh recency.
500
+ entries.delete(key);
501
+ entries.set(key, hit);
502
+ return hit.value;
503
+ },
504
+ set(key, value) {
505
+ entries.delete(key);
506
+ entries.set(key, { value, expiresAt: Date.now() + ttlMs });
507
+ while (entries.size > maxEntries) {
508
+ const oldest = entries.keys().next().value;
509
+ if (oldest === undefined) break;
510
+ entries.delete(oldest);
511
+ }
512
+ },
513
+ clear() {
514
+ entries.clear();
515
+ },
516
+ get size() {
517
+ return entries.size;
518
+ },
519
+ };
520
+ }
521
+
522
+ const defaultTravelTimeCache = createTravelTimeCache();
523
+
524
+ /** Drop every cached travel time (tests, or after a listing moves). */
525
+ export function clearTravelTimeCache(): void {
526
+ defaultTravelTimeCache.clear();
527
+ }
528
+
529
+ export function travelTimeCacheKey(
530
+ origin: MapsCoordinates,
531
+ destination: MapsCoordinates,
532
+ mode: TravelMode
533
+ ): string {
534
+ return `${origin.lat},${origin.lng}|${destination.lat},${destination.lng}|${mode}`;
535
+ }
536
+
537
+ /**
538
+ * String destinations are cached before geocode. The `q:` segment cannot
539
+ * collide with a coordinate key, so a repeat call does not hit `/v1/geocode`.
540
+ */
541
+ function travelTimeQueryCacheKey(
542
+ origin: MapsCoordinates,
543
+ query: string,
544
+ mode: TravelMode
545
+ ): string {
546
+ return `${origin.lat},${origin.lng}|q:${query}|${mode}`;
547
+ }
548
+
549
+ function trimmedDestinationQuery(
550
+ destination: TravelDestination
551
+ ): string | null {
552
+ if (typeof destination !== "string") return null;
553
+ const query = destination.trim();
554
+ return query ? query : null;
555
+ }
556
+
557
+ function recallTravelTime(
558
+ cache: TravelTimeCache | null,
559
+ key: string
560
+ ): TravelTime | null {
561
+ if (!cache) return null;
562
+ const hit = cache.get(key);
563
+ return hit ? { ...hit, cached: true } : null;
564
+ }
565
+
566
+ function rememberTravelTime(
567
+ cache: TravelTimeCache | null,
568
+ keys: readonly string[],
569
+ value: TravelTime
570
+ ): void {
571
+ if (!cache) return;
572
+ for (const key of keys) cache.set(key, value);
573
+ }
574
+
575
+ function normalizeMode(mode: string | undefined): TravelMode {
576
+ return mode && TRAVEL_MODES.has(mode) ? (mode as TravelMode) : "driving";
577
+ }
578
+
579
+ type GeocodePayload = {
580
+ ok?: unknown;
581
+ latitude?: unknown;
582
+ longitude?: unknown;
583
+ };
584
+
585
+ /**
586
+ * Resolve a free-text destination through `/v1/geocode` (Nominatim first,
587
+ * so usually free). Coordinates pass through.
588
+ */
589
+ export async function resolveTravelDestination(
590
+ destination: TravelDestination,
591
+ options: MapsFetchOptions = {}
592
+ ): Promise<MapsCoordinates | null> {
593
+ if (typeof destination !== "string") {
594
+ const lat = finite(destination?.lat);
595
+ const lng = finite(destination?.lng);
596
+ return lat == null || lng == null ? null : { lat, lng };
597
+ }
598
+ const query = destination.trim();
599
+ if (!query) return null;
600
+ const data = await mapsFetchJson<GeocodePayload>(
601
+ mapsUrl("/v1/geocode", { q: query }, options),
602
+ options
603
+ );
604
+ const lat = finite(data?.latitude);
605
+ const lng = finite(data?.longitude);
606
+ if (!data?.ok || lat == null || lng == null) return null;
607
+ return { lat, lng };
608
+ }
609
+
610
+ type DirectionsPayload = {
611
+ ok?: unknown;
612
+ route?: {
613
+ totalDistance?: unknown;
614
+ totalTravelTime?: unknown;
615
+ };
616
+ };
617
+
618
+ function minutesFromSeconds(seconds: number): number {
619
+ return Math.max(1, Math.round(seconds / 60));
620
+ }
621
+
622
+ /**
623
+ * Travel time from the listing's (masked) coordinates to a destination via
624
+ * `GET /v1/directions`. Each uncached call is one Google Directions request
625
+ * on the shared key (≈US$5 per 1 000 at list price, metered per site when
626
+ * `siteId` is set). Cache hits are free, including the geocode a string
627
+ * destination would otherwise spend. Returns `null` when the listing has no
628
+ * coordinates, the destination cannot be resolved, or no route exists.
629
+ */
630
+ export async function travelTimeFromListing(
631
+ listing: ListingWithLocation,
632
+ destination: TravelDestination,
633
+ options: TravelTimeOptions = {}
634
+ ): Promise<TravelTime | null> {
635
+ const raw = listingCoordinates(listing);
636
+ if (!raw) return null;
637
+ const origin = coarsenCoordinates(raw, options.maxDecimals);
638
+ const mode = normalizeMode(options.mode);
639
+ const cache =
640
+ options.cache === undefined ? defaultTravelTimeCache : options.cache;
641
+ const query = trimmedDestinationQuery(destination);
642
+ if (typeof destination === "string" && !query) return null;
643
+ if (query) {
644
+ const queryHit = recallTravelTime(
645
+ cache,
646
+ travelTimeQueryCacheKey(origin, query, mode)
647
+ );
648
+ if (queryHit) return queryHit;
649
+ }
650
+
651
+ const target = await resolveTravelDestination(query ?? destination, options);
652
+ if (!target) return null;
653
+ const coordKey = travelTimeCacheKey(origin, target, mode);
654
+ const stored = cache?.get(coordKey);
655
+ if (stored) {
656
+ if (query) {
657
+ rememberTravelTime(
658
+ cache,
659
+ [travelTimeQueryCacheKey(origin, query, mode)],
660
+ stored
661
+ );
662
+ }
663
+ return { ...stored, cached: true };
664
+ }
665
+
666
+ const data = await mapsFetchJson<DirectionsPayload>(
667
+ mapsUrl(
668
+ "/v1/directions",
669
+ {
670
+ origin: `${origin.lat},${origin.lng}`,
671
+ destination: `${target.lat},${target.lng}`,
672
+ mode,
673
+ },
674
+ options
675
+ ),
676
+ options
677
+ );
678
+ const seconds = finite(data?.route?.totalTravelTime);
679
+ const meters = finite(data?.route?.totalDistance);
680
+ if (!data?.ok || seconds == null || meters == null) return null;
681
+ const result: TravelTime = {
682
+ minutes: minutesFromSeconds(seconds),
683
+ seconds,
684
+ distanceMeters: meters,
685
+ distanceKm: Math.round(meters / 100) / 10,
686
+ mode,
687
+ origin,
688
+ destination: target,
689
+ cached: false,
690
+ };
691
+ const keys = query
692
+ ? [coordKey, travelTimeQueryCacheKey(origin, query, mode)]
693
+ : [coordKey];
694
+ rememberTravelTime(cache, keys, result);
695
+ return result;
696
+ }
697
+
698
+ type RouteMatrixPayload = {
699
+ ok?: unknown;
700
+ durations?: unknown;
701
+ };
702
+
703
+ /**
704
+ * Driving time from the listing to many destinations in one
705
+ * `POST /v1/route-matrix` call (Google Route Matrix, billed per element:
706
+ * ≈US$5 per 1 000 at list price). Distances are not returned by the matrix.
707
+ * Element is `null` when Google found no route; the whole result is `null`
708
+ * when the listing has no coordinates or the request failed.
709
+ */
710
+ export async function travelTimesFromListing(
711
+ listing: ListingWithLocation,
712
+ destinations: MapsCoordinates[],
713
+ options: TravelTimesOptions = {}
714
+ ): Promise<Array<TravelTimeElement | null> | null> {
715
+ const raw = listingCoordinates(listing);
716
+ if (!raw) return null;
717
+ const origin = coarsenCoordinates(raw, options.maxDecimals);
718
+ const targets = destinations
719
+ .map((destination) => {
720
+ const lat = finite(destination?.lat);
721
+ const lng = finite(destination?.lng);
722
+ return lat == null || lng == null ? null : { lat, lng };
723
+ })
724
+ .filter((item): item is MapsCoordinates => item !== null);
725
+ if (targets.length === 0) return [];
726
+ const data = await mapsFetchJson<RouteMatrixPayload>(
727
+ mapsUrl("/v1/route-matrix", {}, options),
728
+ options,
729
+ {
730
+ method: "POST",
731
+ headers: { "content-type": "application/json" },
732
+ body: JSON.stringify({ origin, destinations: targets }),
733
+ }
734
+ );
735
+ if (!data?.ok || !Array.isArray(data.durations)) return null;
736
+ return targets.map((destination, index) => {
737
+ const seconds = finite(
738
+ data.durations && (data.durations as unknown[])[index]
739
+ );
740
+ if (seconds == null) return null;
741
+ return { minutes: minutesFromSeconds(seconds), seconds, destination };
742
+ });
743
+ }