@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.
@@ -0,0 +1,491 @@
1
+ /**
2
+ * Map search on top of the friendly public listings route.
3
+ *
4
+ * Bounds and polygons are structured numbers. The server (see
5
+ * `@garagem/site-search` `map-geo.ts`) turns them into one allowlisted
6
+ * `coordinates:(…)` clause. This module never sends `filter_by`,
7
+ * `vector_query`, or `nl_query`.
8
+ *
9
+ * Pins copy `listing.location.coordinates` as the API returned them.
10
+ * Those values are already masked. Nothing here adds precision.
11
+ */
12
+
13
+ import { queryListings, type FetchLike } from "./fetchers";
14
+ import {
15
+ toListingCardModel,
16
+ type ListingCardModel,
17
+ } from "./listing-card-model";
18
+ import {
19
+ coarsenCoordinates,
20
+ coordinateDecimals,
21
+ listingCoordinates,
22
+ } from "./maps";
23
+ import type {
24
+ Listing,
25
+ QueryListingsFilters,
26
+ QueryListingsParams,
27
+ RequestNextOptions,
28
+ } from "./types";
29
+ import type {
30
+ MapBounds,
31
+ MapPin,
32
+ MapPinCluster,
33
+ MapPolygon,
34
+ } from "./types-maps";
35
+
36
+ /** Matches `FRIENDLY_SEARCH_MAX_LIMIT` on the public listings route. */
37
+ export const MAP_SEARCH_MAX_PAGE_SIZE = 100;
38
+ export const MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
39
+ export const MAP_SEARCH_MAX_PAGE = 10_000;
40
+ /** Same pause Foundation's `/imoveis` map uses before a viewport search. */
41
+ export const MAP_VIEWPORT_DEBOUNCE_MS = 400;
42
+ /** Keep aligned with `MAP_GEO_MAX_VERTICES` in `@garagem/site-search`. */
43
+ export const MAP_POLYGON_MAX_VERTICES = 64;
44
+
45
+ export interface MapSearchRequest {
46
+ baseUrl?: string;
47
+ fetch?: FetchLike;
48
+ signal?: AbortSignal;
49
+ /**
50
+ * Same `pk_live_…` as `queryListings`. Without it the viewport search
51
+ * spends the anonymous listings budget.
52
+ */
53
+ publishableKey?: string;
54
+ /** Next.js fetch cache hints, forwarded to `queryListings`. */
55
+ next?: RequestNextOptions;
56
+ /** Friendly list query. A moved map must keep these, not only `filters`. */
57
+ q?: string;
58
+ sort?: string;
59
+ location?: QueryListingsParams["location"];
60
+ filters?: QueryListingsFilters;
61
+ page?: number;
62
+ pageSize?: number;
63
+ /** Client hint for `clusterPins`. Not sent to the server. */
64
+ zoom?: number;
65
+ }
66
+
67
+ export interface MapBoundsSearchOptions extends MapSearchRequest {
68
+ bounds: MapBounds;
69
+ }
70
+
71
+ export interface MapPolygonSearchOptions extends MapSearchRequest {
72
+ polygon: MapPolygon;
73
+ }
74
+
75
+ export interface MapSearchResult {
76
+ pins: MapPin[];
77
+ cards: ListingCardModel[];
78
+ listings: Listing[];
79
+ page: number;
80
+ pageSize: number;
81
+ total: number;
82
+ totalPages: number;
83
+ }
84
+
85
+ export type MapSearchListenerEvent =
86
+ | { type: "empty" }
87
+ | { type: "loading" }
88
+ | { type: "ready"; result: MapSearchResult }
89
+ | { type: "error"; error: Error };
90
+
91
+ export interface MapSearchSubscription extends MapSearchRequest {
92
+ siteId: string;
93
+ bounds?: MapBounds | null;
94
+ polygon?: MapPolygon | null;
95
+ }
96
+
97
+ export function capMapPageSize(value: number | undefined): number {
98
+ if (value == null || !Number.isFinite(value) || value <= 0) {
99
+ return MAP_SEARCH_DEFAULT_PAGE_SIZE;
100
+ }
101
+ return Math.min(MAP_SEARCH_MAX_PAGE_SIZE, Math.floor(value));
102
+ }
103
+
104
+ export function capMapPage(value: number | undefined): number {
105
+ if (value == null || !Number.isFinite(value) || value <= 1) return 1;
106
+ return Math.min(MAP_SEARCH_MAX_PAGE, Math.floor(value));
107
+ }
108
+
109
+ function finitePair(lat: unknown, lng: unknown): [number, number] | null {
110
+ if (typeof lat !== "number" || typeof lng !== "number") return null;
111
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
112
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
113
+ return [lat, lng];
114
+ }
115
+
116
+ /** Rectangle the server will accept. `false` when it crosses the antimeridian. */
117
+ export function isMapBounds(
118
+ bounds: MapBounds | null | undefined
119
+ ): bounds is MapBounds {
120
+ if (!bounds) return false;
121
+ const north = finitePair(bounds.north, bounds.east);
122
+ const south = finitePair(bounds.south, bounds.west);
123
+ if (!north || !south) return false;
124
+ return bounds.north > bounds.south && bounds.east > bounds.west;
125
+ }
126
+
127
+ export function isMapPolygon(
128
+ polygon: MapPolygon | null | undefined
129
+ ): polygon is MapPolygon {
130
+ if (!Array.isArray(polygon)) return false;
131
+ if (polygon.length < 3 || polygon.length > MAP_POLYGON_MAX_VERTICES + 1) {
132
+ return false;
133
+ }
134
+ let unique = 0;
135
+ let prev: [number, number] | null = null;
136
+ for (const point of polygon) {
137
+ if (!Array.isArray(point)) return false;
138
+ const pair = finitePair(point[0], point[1]);
139
+ if (!pair) return false;
140
+ if (prev && prev[0] === pair[0] && prev[1] === pair[1]) continue;
141
+ prev = pair;
142
+ unique += 1;
143
+ }
144
+ if (unique >= 2 && polygon.length >= 2) {
145
+ const first = finitePair(polygon[0]?.[0], polygon[0]?.[1]);
146
+ const last = finitePair(
147
+ polygon[polygon.length - 1]?.[0],
148
+ polygon[polygon.length - 1]?.[1]
149
+ );
150
+ if (
151
+ first &&
152
+ last &&
153
+ first[0] === last[0] &&
154
+ first[1] === last[1] &&
155
+ unique > 1
156
+ ) {
157
+ unique -= 1;
158
+ }
159
+ }
160
+ return unique >= 3 && unique <= MAP_POLYGON_MAX_VERTICES;
161
+ }
162
+
163
+ export function emptyMapSearchResult(
164
+ pageSize = MAP_SEARCH_DEFAULT_PAGE_SIZE
165
+ ): MapSearchResult {
166
+ return {
167
+ pins: [],
168
+ cards: [],
169
+ listings: [],
170
+ page: 1,
171
+ pageSize,
172
+ total: 0,
173
+ totalPages: 0,
174
+ };
175
+ }
176
+
177
+ /** Pins from public listings. Coordinates are copied, never sharpened. */
178
+ export function mapSearchPins(listings: readonly Listing[]): MapPin[] {
179
+ const pins: MapPin[] = [];
180
+ for (const listing of listings) {
181
+ const coords = listingCoordinates(listing);
182
+ if (!coords || !listing.id) continue;
183
+ const src = listing.coverImage?.src;
184
+ pins.push({
185
+ id: listing.id,
186
+ lat: coords.lat,
187
+ lng: coords.lng,
188
+ price: listing.price ?? null,
189
+ coverImage: src ? src : null,
190
+ });
191
+ }
192
+ return pins;
193
+ }
194
+
195
+ function listingsResult(
196
+ listings: Listing[],
197
+ meta: { page?: number; limit?: number; total?: number; totalPages?: number },
198
+ requestedPageSize: number
199
+ ): MapSearchResult {
200
+ return {
201
+ pins: mapSearchPins(listings),
202
+ cards: listings.map((listing) => toListingCardModel(listing)),
203
+ listings,
204
+ page: meta.page ?? 1,
205
+ pageSize: meta.limit ?? requestedPageSize,
206
+ total: meta.total ?? listings.length,
207
+ totalPages: meta.totalPages ?? 0,
208
+ };
209
+ }
210
+
211
+ function searchParams(
212
+ area: { bounds?: MapBounds; polygon?: MapPolygon },
213
+ options: MapSearchRequest
214
+ ): QueryListingsParams {
215
+ const params: QueryListingsParams = {
216
+ page: capMapPage(options.page),
217
+ limit: capMapPageSize(options.pageSize),
218
+ };
219
+ if (options.q !== undefined) params.q = options.q;
220
+ if (options.sort !== undefined) params.sort = options.sort;
221
+ if (options.location !== undefined) params.location = options.location;
222
+ if (options.filters) params.filters = options.filters;
223
+ if (area.polygon) params.polygon = area.polygon;
224
+ else if (area.bounds) params.bounds = area.bounds;
225
+ return params;
226
+ }
227
+
228
+ async function runMapSearch(
229
+ siteId: string,
230
+ area: { bounds?: MapBounds; polygon?: MapPolygon },
231
+ options: MapSearchRequest
232
+ ): Promise<MapSearchResult> {
233
+ const pageSize = capMapPageSize(options.pageSize);
234
+ const result = await queryListings({
235
+ siteId,
236
+ params: searchParams(area, options),
237
+ baseUrl: options.baseUrl,
238
+ fetch: options.fetch,
239
+ signal: options.signal,
240
+ publishableKey: options.publishableKey,
241
+ next: options.next,
242
+ });
243
+ return listingsResult(result.listings ?? [], result, pageSize);
244
+ }
245
+
246
+ export async function searchListingsInBounds(
247
+ siteId: string,
248
+ options: MapBoundsSearchOptions
249
+ ): Promise<MapSearchResult> {
250
+ if (!isMapBounds(options.bounds)) {
251
+ throw new TypeError(
252
+ "searchListingsInBounds: bounds must be a finite rectangle with north > south and east > west (no antimeridian)."
253
+ );
254
+ }
255
+ return runMapSearch(siteId, { bounds: options.bounds }, options);
256
+ }
257
+
258
+ export async function searchListingsInPolygon(
259
+ siteId: string,
260
+ options: MapPolygonSearchOptions
261
+ ): Promise<MapSearchResult> {
262
+ if (!isMapPolygon(options.polygon)) {
263
+ throw new TypeError(
264
+ `searchListingsInPolygon: polygon must be 3–${MAP_POLYGON_MAX_VERTICES} finite [lat, lng] points.`
265
+ );
266
+ }
267
+ return runMapSearch(siteId, { polygon: options.polygon }, options);
268
+ }
269
+
270
+ function clampZoom(zoom: number): number {
271
+ if (!Number.isFinite(zoom)) return 0;
272
+ return Math.min(22, Math.max(0, zoom));
273
+ }
274
+
275
+ /** Degrees per grid cell: a quarter of one world tile at this zoom. */
276
+ export function mapClusterCellDegrees(zoom: number): number {
277
+ return 360 / 2 ** clampZoom(zoom) / 4;
278
+ }
279
+
280
+ function usablePin(pin: MapPin): boolean {
281
+ return (
282
+ finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0)
283
+ );
284
+ }
285
+
286
+ /**
287
+ * The finest precision any member shows. A masked `-23.600` prints as
288
+ * `-23.6`, so the coarsest member would round the centroid kilometres away.
289
+ */
290
+ function groupPrecision(group: readonly MapPin[]): number {
291
+ let max = 0;
292
+ for (const pin of group) {
293
+ max = Math.max(
294
+ max,
295
+ coordinateDecimals(pin.lat),
296
+ coordinateDecimals(pin.lng)
297
+ );
298
+ }
299
+ return max;
300
+ }
301
+
302
+ function multiCluster(key: string, group: MapPin[]): MapPinCluster {
303
+ const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
304
+ const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
305
+ const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
306
+ return {
307
+ id: key,
308
+ lat: center.lat,
309
+ lng: center.lng,
310
+ count: group.length,
311
+ pinIds: group.map((pin) => pin.id),
312
+ pin: null,
313
+ };
314
+ }
315
+
316
+ function singleCluster(pin: MapPin): MapPinCluster {
317
+ return {
318
+ id: pin.id,
319
+ lat: pin.lat,
320
+ lng: pin.lng,
321
+ count: 1,
322
+ pinIds: [pin.id],
323
+ pin,
324
+ };
325
+ }
326
+
327
+ /**
328
+ * Headless grid cluster. A cell with one pin keeps that pin's coordinates.
329
+ * A group centroid is rounded to the members' own precision so clustering
330
+ * cannot invent extra decimals.
331
+ */
332
+ export function clusterPins(
333
+ pins: readonly MapPin[],
334
+ zoom: number
335
+ ): MapPinCluster[] {
336
+ if (pins.length === 0) return [];
337
+ const cell = mapClusterCellDegrees(zoom);
338
+ const groups = new Map<string, MapPin[]>();
339
+ for (const pin of pins) {
340
+ if (!usablePin(pin)) continue;
341
+ const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
342
+ const list = groups.get(key);
343
+ if (list) list.push(pin);
344
+ else groups.set(key, [pin]);
345
+ }
346
+ const clusters: MapPinCluster[] = [];
347
+ for (const [key, group] of groups) {
348
+ const only = group[0];
349
+ clusters.push(
350
+ group.length === 1 && only
351
+ ? singleCluster(only)
352
+ : multiCluster(key, group)
353
+ );
354
+ }
355
+ clusters.sort((a, b) => a.id.localeCompare(b.id));
356
+ return clusters;
357
+ }
358
+
359
+ type MapArea =
360
+ | { kind: "empty" }
361
+ | { kind: "invalid"; message: string }
362
+ | { kind: "bounds"; bounds: MapBounds }
363
+ | { kind: "polygon"; polygon: MapPolygon };
364
+
365
+ function describeArea(query: MapSearchSubscription): MapArea {
366
+ if (query.polygon != null) {
367
+ if (!isMapPolygon(query.polygon)) {
368
+ return {
369
+ kind: "invalid",
370
+ message: `Map search polygon must be 3–${MAP_POLYGON_MAX_VERTICES} [lat, lng] points.`,
371
+ };
372
+ }
373
+ return { kind: "polygon", polygon: query.polygon };
374
+ }
375
+ if (query.bounds != null) {
376
+ if (!isMapBounds(query.bounds)) {
377
+ return {
378
+ kind: "invalid",
379
+ message:
380
+ "Map search bounds must be a finite rectangle with north > south and east > west.",
381
+ };
382
+ }
383
+ return { kind: "bounds", bounds: query.bounds };
384
+ }
385
+ return { kind: "empty" };
386
+ }
387
+
388
+ function isAbort(error: unknown, signal: AbortSignal): boolean {
389
+ if (signal.aborted) return true;
390
+ return error instanceof Error && error.name === "AbortError";
391
+ }
392
+
393
+ function asError(error: unknown): Error {
394
+ return error instanceof Error ? error : new Error(String(error));
395
+ }
396
+
397
+ /**
398
+ * Every friendly-list field on the subscription, not a hand-picked subset.
399
+ * `siteId` / area geometry are arguments of the search call.
400
+ */
401
+ function requestFromSubscription(
402
+ query: MapSearchSubscription,
403
+ signal: AbortSignal
404
+ ): MapSearchRequest {
405
+ const {
406
+ siteId: _siteId,
407
+ bounds: _bounds,
408
+ polygon: _polygon,
409
+ ...request
410
+ } = query;
411
+ return { ...request, signal };
412
+ }
413
+
414
+ async function fetchArea(
415
+ query: MapSearchSubscription,
416
+ area: Exclude<MapArea, { kind: "empty" | "invalid" }>,
417
+ signal: AbortSignal
418
+ ): Promise<MapSearchResult> {
419
+ const request = requestFromSubscription(query, signal);
420
+ if (area.kind === "polygon") {
421
+ return searchListingsInPolygon(query.siteId, {
422
+ ...request,
423
+ polygon: area.polygon,
424
+ });
425
+ }
426
+ return searchListingsInBounds(query.siteId, {
427
+ ...request,
428
+ bounds: area.bounds,
429
+ });
430
+ }
431
+
432
+ /**
433
+ * Identity of a viewport search. Changing the list query, the publishable
434
+ * key, or the cache hint must start a new search.
435
+ */
436
+ export function mapSearchSubscriptionKey(query: MapSearchSubscription): string {
437
+ return JSON.stringify({
438
+ siteId: query.siteId,
439
+ baseUrl: query.baseUrl ?? "",
440
+ bounds: query.bounds ?? null,
441
+ polygon: query.polygon ?? null,
442
+ q: query.q ?? null,
443
+ sort: query.sort ?? null,
444
+ location: query.location ?? null,
445
+ filters: query.filters ?? null,
446
+ publishableKey: query.publishableKey ?? null,
447
+ next: query.next ?? null,
448
+ page: query.page ?? 1,
449
+ pageSize: query.pageSize ?? MAP_SEARCH_DEFAULT_PAGE_SIZE,
450
+ });
451
+ }
452
+
453
+ /**
454
+ * Debounced map search. The returned function aborts the in-flight request
455
+ * and cancels a pending debounce. Zoom is not part of the query: cluster
456
+ * the latest pins with `clusterPins` when only the zoom changes.
457
+ */
458
+ export function subscribeMapSearch(
459
+ query: MapSearchSubscription,
460
+ listener: (event: MapSearchListenerEvent) => void,
461
+ options?: { debounceMs?: number }
462
+ ): () => void {
463
+ const area = describeArea(query);
464
+ if (area.kind === "empty") {
465
+ listener({ type: "empty" });
466
+ return () => {};
467
+ }
468
+ if (area.kind === "invalid") {
469
+ listener({ type: "error", error: new TypeError(area.message) });
470
+ return () => {};
471
+ }
472
+ const controller = new AbortController();
473
+ const debounceMs = options?.debounceMs ?? MAP_VIEWPORT_DEBOUNCE_MS;
474
+ const timer = setTimeout(() => {
475
+ listener({ type: "loading" });
476
+ void fetchArea(query, area, controller.signal).then(
477
+ (result) => {
478
+ if (controller.signal.aborted) return;
479
+ listener({ type: "ready", result });
480
+ },
481
+ (error: unknown) => {
482
+ if (isAbort(error, controller.signal)) return;
483
+ listener({ type: "error", error: asError(error) });
484
+ }
485
+ );
486
+ }, debounceMs);
487
+ return () => {
488
+ clearTimeout(timer);
489
+ controller.abort();
490
+ };
491
+ }