@garagem-ai/site-sdk 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js CHANGED
@@ -22,6 +22,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
22
22
  var react_exports = {};
23
23
  __export(react_exports, {
24
24
  PHOTO_SEARCH_DEBOUNCE_MS: () => PHOTO_SEARCH_DEBOUNCE_MS,
25
+ useMapSearch: () => useMapSearch,
25
26
  usePublicPhotoSearch: () => usePublicPhotoSearch,
26
27
  usePublicSearch: () => usePublicSearch
27
28
  });
@@ -31,6 +32,101 @@ module.exports = __toCommonJS(react_exports);
31
32
  var import_react = require("react");
32
33
  var import_navigation = require("next/navigation");
33
34
 
35
+ // src/listing-path.ts
36
+ function listingPublicPath(listing) {
37
+ const composed = listing.path?.trim() ?? "";
38
+ if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
39
+ const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
40
+ if (!identity || identity === "undefined" || identity === "null") {
41
+ throw new TypeError("listingPublicPath: listing has no listingCode or id");
42
+ }
43
+ return `/imoveis/id-${identity}`;
44
+ }
45
+
46
+ // src/internal/sdk-http.ts
47
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
48
+ function publishableKeyHeaders(publishableKey) {
49
+ const key = publishableKey?.trim();
50
+ if (!key) return {};
51
+ return { [PUBLISHABLE_KEY_HEADER]: key };
52
+ }
53
+ function withPublishableKeyHeader(init, publishableKey) {
54
+ const extra = publishableKeyHeaders(publishableKey);
55
+ if (Object.keys(extra).length === 0) return init;
56
+ const current = init.headers;
57
+ const base = plainHeaders(current);
58
+ return { ...init, headers: { ...base, ...extra } };
59
+ }
60
+ function plainHeaders(headers) {
61
+ const out = {};
62
+ if (!headers) return out;
63
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
64
+ headers.forEach((value, name) => {
65
+ out[name] = value;
66
+ });
67
+ return out;
68
+ }
69
+ if (Array.isArray(headers)) {
70
+ for (const pair of headers) {
71
+ out[String(pair[0])] = String(pair[1]);
72
+ }
73
+ return out;
74
+ }
75
+ for (const [name, value] of Object.entries(
76
+ headers
77
+ )) {
78
+ if (typeof value === "string") out[name] = value;
79
+ }
80
+ return out;
81
+ }
82
+ function finiteNonNegative(value) {
83
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
84
+ return value;
85
+ }
86
+ if (typeof value === "string" && value.trim()) {
87
+ const parsed = Number(value);
88
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
89
+ }
90
+ return null;
91
+ }
92
+ function parseSdkErrorBody(text) {
93
+ const raw = text ? text.slice(0, 200) : "";
94
+ if (!text) {
95
+ return { reason: null, retryAfterSeconds: null, summary: "" };
96
+ }
97
+ try {
98
+ const body = JSON.parse(text);
99
+ if (!body || typeof body !== "object") {
100
+ return { reason: null, retryAfterSeconds: null, summary: raw };
101
+ }
102
+ const record = body;
103
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
104
+ const retryAfterSeconds = finiteNonNegative(
105
+ record.retryAfterSeconds ?? record.retryAfter
106
+ );
107
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
108
+ return {
109
+ reason,
110
+ retryAfterSeconds,
111
+ summary: errorText.slice(0, 200)
112
+ };
113
+ } catch {
114
+ return { reason: null, retryAfterSeconds: null, summary: raw };
115
+ }
116
+ }
117
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
118
+ const header = response.headers.get("Retry-After")?.trim();
119
+ if (header) {
120
+ const delta = finiteNonNegative(header);
121
+ if (delta != null) return delta;
122
+ const at = Date.parse(header);
123
+ if (Number.isFinite(at)) {
124
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
125
+ }
126
+ }
127
+ return bodySeconds;
128
+ }
129
+
34
130
  // src/internal/url.ts
35
131
  var DEFAULT_BASE_URL = "https://app.garagem.ai";
36
132
  function normalizeBaseUrl(baseUrl) {
@@ -49,27 +145,50 @@ async function coerceSiteId(siteId) {
49
145
  }
50
146
 
51
147
  // src/fetchers.ts
52
- async function callJson(url, init, fetchImpl) {
53
- const response = await fetchImpl(url, init);
148
+ async function callJson(url, init, fetchImpl, publishableKey) {
149
+ const response = await fetchImpl(
150
+ url,
151
+ withPublishableKeyHeader(init, publishableKey)
152
+ );
54
153
  if (!response.ok) {
55
- const text = await response.text().catch(() => "");
56
- throw new GaragemSdkError(
57
- `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text ? ` \u2014 ${text.slice(0, 200)}` : ""}`,
58
- { status: response.status, url }
59
- );
154
+ throw await readGaragemSdkError(response, url);
60
155
  }
61
156
  return await response.json();
62
157
  }
63
158
  var GaragemSdkError = class extends Error {
64
159
  status;
65
160
  url;
161
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
162
+ reason;
163
+ /**
164
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
165
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
166
+ */
167
+ retryAfter;
66
168
  constructor(message, info) {
67
169
  super(message);
68
170
  this.name = "GaragemSdkError";
69
171
  this.status = info.status;
70
172
  this.url = info.url;
173
+ this.reason = info.reason ?? null;
174
+ this.retryAfter = info.retryAfter ?? null;
71
175
  }
72
176
  };
177
+ async function readGaragemSdkError(response, url) {
178
+ const text = await response.text().catch(() => "");
179
+ const parsed = parseSdkErrorBody(text);
180
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
181
+ const detail = parsed.summary;
182
+ return new GaragemSdkError(
183
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
184
+ {
185
+ status: response.status,
186
+ url,
187
+ reason: parsed.reason,
188
+ retryAfter
189
+ }
190
+ );
191
+ }
73
192
  async function getSearchUi(options) {
74
193
  const { baseUrl, fetch: fetchImpl, next } = options;
75
194
  const siteId = await coerceSiteId(options.siteId);
@@ -78,11 +197,12 @@ async function getSearchUi(options) {
78
197
  return callJson(
79
198
  url,
80
199
  { method: "GET", headers: { Accept: "application/json" }, next },
81
- fetchImpl ?? fetch
200
+ fetchImpl ?? fetch,
201
+ options.publishableKey
82
202
  );
83
203
  }
84
204
  async function queryListings(options) {
85
- const { params, baseUrl, fetch: fetchImpl, next } = options;
205
+ const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
86
206
  const siteId = await coerceSiteId(options.siteId);
87
207
  const base = normalizeBaseUrl(baseUrl);
88
208
  const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
@@ -95,9 +215,11 @@ async function queryListings(options) {
95
215
  "Content-Type": "application/json"
96
216
  },
97
217
  body: JSON.stringify(params ?? {}),
98
- next
218
+ next,
219
+ signal
99
220
  },
100
- fetchImpl ?? fetch
221
+ fetchImpl ?? fetch,
222
+ options.publishableKey
101
223
  );
102
224
  }
103
225
 
@@ -548,6 +670,19 @@ function pathFiltersToQueryFilters(pathFilters) {
548
670
  }
549
671
 
550
672
  // src/presentation.ts
673
+ function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
674
+ if (amount == null) return "Sob consulta";
675
+ try {
676
+ return new Intl.NumberFormat(locale, {
677
+ style: "currency",
678
+ currency,
679
+ minimumFractionDigits: 0,
680
+ maximumFractionDigits: 0
681
+ }).format(amount);
682
+ } catch {
683
+ return `${currency} ${amount}`;
684
+ }
685
+ }
551
686
  function parseGroupedInteger(value) {
552
687
  if (typeof value === "number") {
553
688
  return Number.isFinite(value) ? Math.trunc(value) : void 0;
@@ -557,6 +692,9 @@ function parseGroupedInteger(value) {
557
692
  const amount = Number.parseInt(digits, 10);
558
693
  return Number.isFinite(amount) ? amount : void 0;
559
694
  }
695
+ function listingBusinessLabel(businessType) {
696
+ return businessType === "rental" ? "Aluguel" : "Venda";
697
+ }
560
698
 
561
699
  // src/search-engine.ts
562
700
  var PATH_FILTER_IDS = {
@@ -835,7 +973,13 @@ function currentHref(pathname, search) {
835
973
  return search ? `${pathname}?${search}` : pathname;
836
974
  }
837
975
  function usePublicSearch(options) {
838
- const { siteId, baseUrl, initial, search: searchFromServer = "" } = options;
976
+ const {
977
+ siteId,
978
+ baseUrl,
979
+ publishableKey,
980
+ initial,
981
+ search: searchFromServer = ""
982
+ } = options;
839
983
  const router = (0, import_navigation.useRouter)();
840
984
  const pathname = (0, import_navigation.usePathname)() || "/imoveis";
841
985
  const search = searchFromServer;
@@ -924,13 +1068,23 @@ function usePublicSearch(options) {
924
1068
  }
925
1069
  async function loadSchema() {
926
1070
  try {
927
- const nextSchema = await getSearchUi({ siteId: id, baseUrl });
1071
+ const nextSchema = await getSearchUi({
1072
+ siteId: id,
1073
+ baseUrl,
1074
+ publishableKey
1075
+ });
928
1076
  if (!active) return;
929
1077
  let locations = null;
930
1078
  if (nextSchema.locationsPath.startsWith("/")) {
931
1079
  try {
932
1080
  const response = await fetch(
933
- `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
1081
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`,
1082
+ {
1083
+ headers: {
1084
+ Accept: "application/json",
1085
+ ...publishableKeyHeaders(publishableKey)
1086
+ }
1087
+ }
934
1088
  );
935
1089
  if (response.ok) {
936
1090
  locations = await response.json();
@@ -964,7 +1118,7 @@ function usePublicSearch(options) {
964
1118
  return () => {
965
1119
  active = false;
966
1120
  };
967
- }, [baseUrl, catalogId]);
1121
+ }, [baseUrl, catalogId, publishableKey]);
968
1122
  (0, import_react.useEffect)(() => {
969
1123
  if (!schema || !catalogId) return;
970
1124
  const currentSchema = schema;
@@ -987,6 +1141,7 @@ function usePublicSearch(options) {
987
1141
  const response = await queryListings({
988
1142
  siteId: id,
989
1143
  baseUrl,
1144
+ publishableKey,
990
1145
  params: buildQueryListingsParams(
991
1146
  pathFilters,
992
1147
  applied,
@@ -1023,7 +1178,7 @@ function usePublicSearch(options) {
1023
1178
  return () => {
1024
1179
  active = false;
1025
1180
  };
1026
- }, [pathname, search, baseUrl, schema, catalogId]);
1181
+ }, [pathname, search, baseUrl, schema, catalogId, publishableKey]);
1027
1182
  const go = (0, import_react.useCallback)(
1028
1183
  (href) => {
1029
1184
  if (href && href !== currentHref(pathname, search)) router.push(href);
@@ -1137,9 +1292,466 @@ function usePublicSearch(options) {
1137
1292
  };
1138
1293
  }
1139
1294
 
1140
- // src/react/use-public-photo-search.ts
1295
+ // src/react/use-map-search.ts
1141
1296
  var import_react2 = require("react");
1142
1297
 
1298
+ // src/listing-card-model.ts
1299
+ function listingLocationLabel(location) {
1300
+ return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
1301
+ }
1302
+ function toListingCardModel(listing) {
1303
+ const isPrivate = listing.priceVisibility === "private";
1304
+ const area = listing.property?.usableArea ?? listing.property?.totalArea;
1305
+ return {
1306
+ href: listingPublicPath(listing),
1307
+ title: listing.title,
1308
+ businessType: listing.businessType,
1309
+ businessLabel: listingBusinessLabel(listing.businessType),
1310
+ priceVisibility: listing.priceVisibility,
1311
+ price: listing.price,
1312
+ priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price, "pt-BR", listing.currency ?? "BRL"),
1313
+ pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
1314
+ locationLabel: listingLocationLabel(listing.location || {}),
1315
+ propertyType: listing.property?.type ?? null,
1316
+ coverSrc: listing.coverImage?.src ?? null,
1317
+ coverAlt: listing.coverImage?.alt ?? listing.title,
1318
+ bedrooms: listing.property?.bedrooms ?? null,
1319
+ bathrooms: listing.property?.bathrooms ?? null,
1320
+ parkingSpaces: listing.property?.parkingSpaces ?? null,
1321
+ areaM2: area ?? null
1322
+ };
1323
+ }
1324
+
1325
+ // src/maps.ts
1326
+ function finite(value) {
1327
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
1328
+ }
1329
+ function listingCoordinates(listing) {
1330
+ const raw = listing?.location?.coordinates;
1331
+ const lat = finite(raw?.lat);
1332
+ const lng = finite(raw?.lng);
1333
+ if (lat == null || lng == null) return null;
1334
+ if (lat === 0 && lng === 0) return null;
1335
+ if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return null;
1336
+ return { lat, lng };
1337
+ }
1338
+ function coordinateDecimals(value) {
1339
+ if (!Number.isFinite(value)) return 0;
1340
+ const text = Math.abs(value).toString();
1341
+ if (text.includes("e")) {
1342
+ const fixed = Math.abs(value).toFixed(12).replace(/0+$/, "");
1343
+ const dot2 = fixed.indexOf(".");
1344
+ return dot2 === -1 ? 0 : fixed.length - dot2 - 1;
1345
+ }
1346
+ const dot = text.indexOf(".");
1347
+ return dot === -1 ? 0 : text.length - dot - 1;
1348
+ }
1349
+ function roundTo(value, decimals) {
1350
+ const factor = 10 ** decimals;
1351
+ return Math.round(value * factor) / factor;
1352
+ }
1353
+ function coarsenCoordinates(coordinates, maxDecimals) {
1354
+ if (maxDecimals == null || !Number.isFinite(maxDecimals)) return coordinates;
1355
+ const limit = Math.max(0, Math.floor(maxDecimals));
1356
+ return {
1357
+ lat: coordinateDecimals(coordinates.lat) > limit ? roundTo(coordinates.lat, limit) : coordinates.lat,
1358
+ lng: coordinateDecimals(coordinates.lng) > limit ? roundTo(coordinates.lng, limit) : coordinates.lng
1359
+ };
1360
+ }
1361
+ function createTravelTimeCache(options = {}) {
1362
+ const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? 200));
1363
+ const ttlMs = Math.max(0, options.ttlMs ?? 15 * 60 * 1e3);
1364
+ const entries = /* @__PURE__ */ new Map();
1365
+ return {
1366
+ get(key) {
1367
+ const hit = entries.get(key);
1368
+ if (!hit) return void 0;
1369
+ if (hit.expiresAt <= Date.now()) {
1370
+ entries.delete(key);
1371
+ return void 0;
1372
+ }
1373
+ entries.delete(key);
1374
+ entries.set(key, hit);
1375
+ return hit.value;
1376
+ },
1377
+ set(key, value) {
1378
+ entries.delete(key);
1379
+ entries.set(key, { value, expiresAt: Date.now() + ttlMs });
1380
+ while (entries.size > maxEntries) {
1381
+ const oldest = entries.keys().next().value;
1382
+ if (oldest === void 0) break;
1383
+ entries.delete(oldest);
1384
+ }
1385
+ },
1386
+ clear() {
1387
+ entries.clear();
1388
+ },
1389
+ get size() {
1390
+ return entries.size;
1391
+ }
1392
+ };
1393
+ }
1394
+ var defaultTravelTimeCache = createTravelTimeCache();
1395
+
1396
+ // src/map-search.ts
1397
+ var MAP_SEARCH_MAX_PAGE_SIZE = 100;
1398
+ var MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
1399
+ var MAP_SEARCH_MAX_PAGE = 1e4;
1400
+ var MAP_VIEWPORT_DEBOUNCE_MS = 400;
1401
+ var MAP_POLYGON_MAX_VERTICES = 64;
1402
+ function capMapPageSize(value) {
1403
+ if (value == null || !Number.isFinite(value) || value <= 0) {
1404
+ return MAP_SEARCH_DEFAULT_PAGE_SIZE;
1405
+ }
1406
+ return Math.min(MAP_SEARCH_MAX_PAGE_SIZE, Math.floor(value));
1407
+ }
1408
+ function capMapPage(value) {
1409
+ if (value == null || !Number.isFinite(value) || value <= 1) return 1;
1410
+ return Math.min(MAP_SEARCH_MAX_PAGE, Math.floor(value));
1411
+ }
1412
+ function finitePair(lat, lng) {
1413
+ if (typeof lat !== "number" || typeof lng !== "number") return null;
1414
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
1415
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
1416
+ return [lat, lng];
1417
+ }
1418
+ function isMapBounds(bounds) {
1419
+ if (!bounds) return false;
1420
+ const north = finitePair(bounds.north, bounds.east);
1421
+ const south = finitePair(bounds.south, bounds.west);
1422
+ if (!north || !south) return false;
1423
+ return bounds.north > bounds.south && bounds.east > bounds.west;
1424
+ }
1425
+ function isMapPolygon(polygon) {
1426
+ if (!Array.isArray(polygon)) return false;
1427
+ if (polygon.length < 3 || polygon.length > MAP_POLYGON_MAX_VERTICES + 1) {
1428
+ return false;
1429
+ }
1430
+ let unique = 0;
1431
+ let prev = null;
1432
+ for (const point of polygon) {
1433
+ if (!Array.isArray(point)) return false;
1434
+ const pair = finitePair(point[0], point[1]);
1435
+ if (!pair) return false;
1436
+ if (prev && prev[0] === pair[0] && prev[1] === pair[1]) continue;
1437
+ prev = pair;
1438
+ unique += 1;
1439
+ }
1440
+ if (unique >= 2 && polygon.length >= 2) {
1441
+ const first = finitePair(polygon[0]?.[0], polygon[0]?.[1]);
1442
+ const last = finitePair(
1443
+ polygon[polygon.length - 1]?.[0],
1444
+ polygon[polygon.length - 1]?.[1]
1445
+ );
1446
+ if (first && last && first[0] === last[0] && first[1] === last[1] && unique > 1) {
1447
+ unique -= 1;
1448
+ }
1449
+ }
1450
+ return unique >= 3 && unique <= MAP_POLYGON_MAX_VERTICES;
1451
+ }
1452
+ function emptyMapSearchResult(pageSize = MAP_SEARCH_DEFAULT_PAGE_SIZE) {
1453
+ return {
1454
+ pins: [],
1455
+ cards: [],
1456
+ listings: [],
1457
+ page: 1,
1458
+ pageSize,
1459
+ total: 0,
1460
+ totalPages: 0
1461
+ };
1462
+ }
1463
+ function mapSearchPins(listings) {
1464
+ const pins = [];
1465
+ for (const listing of listings) {
1466
+ const coords = listingCoordinates(listing);
1467
+ if (!coords || !listing.id) continue;
1468
+ const src = listing.coverImage?.src;
1469
+ pins.push({
1470
+ id: listing.id,
1471
+ lat: coords.lat,
1472
+ lng: coords.lng,
1473
+ price: listing.price ?? null,
1474
+ coverImage: src ? src : null
1475
+ });
1476
+ }
1477
+ return pins;
1478
+ }
1479
+ function listingsResult(listings, meta, requestedPageSize) {
1480
+ return {
1481
+ pins: mapSearchPins(listings),
1482
+ cards: listings.map((listing) => toListingCardModel(listing)),
1483
+ listings,
1484
+ page: meta.page ?? 1,
1485
+ pageSize: meta.limit ?? requestedPageSize,
1486
+ total: meta.total ?? listings.length,
1487
+ totalPages: meta.totalPages ?? 0
1488
+ };
1489
+ }
1490
+ function searchParams(area, options) {
1491
+ const params = {
1492
+ page: capMapPage(options.page),
1493
+ limit: capMapPageSize(options.pageSize)
1494
+ };
1495
+ if (options.q !== void 0) params.q = options.q;
1496
+ if (options.sort !== void 0) params.sort = options.sort;
1497
+ if (options.location !== void 0) params.location = options.location;
1498
+ if (options.filters) params.filters = options.filters;
1499
+ if (area.polygon) params.polygon = area.polygon;
1500
+ else if (area.bounds) params.bounds = area.bounds;
1501
+ return params;
1502
+ }
1503
+ async function runMapSearch(siteId, area, options) {
1504
+ const pageSize = capMapPageSize(options.pageSize);
1505
+ const result = await queryListings({
1506
+ siteId,
1507
+ params: searchParams(area, options),
1508
+ baseUrl: options.baseUrl,
1509
+ fetch: options.fetch,
1510
+ signal: options.signal,
1511
+ publishableKey: options.publishableKey,
1512
+ next: options.next
1513
+ });
1514
+ return listingsResult(result.listings ?? [], result, pageSize);
1515
+ }
1516
+ async function searchListingsInBounds(siteId, options) {
1517
+ if (!isMapBounds(options.bounds)) {
1518
+ throw new TypeError(
1519
+ "searchListingsInBounds: bounds must be a finite rectangle with north > south and east > west (no antimeridian)."
1520
+ );
1521
+ }
1522
+ return runMapSearch(siteId, { bounds: options.bounds }, options);
1523
+ }
1524
+ async function searchListingsInPolygon(siteId, options) {
1525
+ if (!isMapPolygon(options.polygon)) {
1526
+ throw new TypeError(
1527
+ `searchListingsInPolygon: polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} finite [lat, lng] points.`
1528
+ );
1529
+ }
1530
+ return runMapSearch(siteId, { polygon: options.polygon }, options);
1531
+ }
1532
+ function clampZoom(zoom) {
1533
+ if (!Number.isFinite(zoom)) return 0;
1534
+ return Math.min(22, Math.max(0, zoom));
1535
+ }
1536
+ function mapClusterCellDegrees(zoom) {
1537
+ return 360 / 2 ** clampZoom(zoom) / 4;
1538
+ }
1539
+ function usablePin(pin) {
1540
+ return finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0);
1541
+ }
1542
+ function groupPrecision(group) {
1543
+ let min = 12;
1544
+ for (const pin of group) {
1545
+ min = Math.min(
1546
+ min,
1547
+ coordinateDecimals(pin.lat),
1548
+ coordinateDecimals(pin.lng)
1549
+ );
1550
+ }
1551
+ return min;
1552
+ }
1553
+ function multiCluster(key, group) {
1554
+ const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
1555
+ const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
1556
+ const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
1557
+ return {
1558
+ id: key,
1559
+ lat: center.lat,
1560
+ lng: center.lng,
1561
+ count: group.length,
1562
+ pinIds: group.map((pin) => pin.id),
1563
+ pin: null
1564
+ };
1565
+ }
1566
+ function singleCluster(pin) {
1567
+ return {
1568
+ id: pin.id,
1569
+ lat: pin.lat,
1570
+ lng: pin.lng,
1571
+ count: 1,
1572
+ pinIds: [pin.id],
1573
+ pin
1574
+ };
1575
+ }
1576
+ function clusterPins(pins, zoom) {
1577
+ if (pins.length === 0) return [];
1578
+ const cell = mapClusterCellDegrees(zoom);
1579
+ const groups = /* @__PURE__ */ new Map();
1580
+ for (const pin of pins) {
1581
+ if (!usablePin(pin)) continue;
1582
+ const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
1583
+ const list = groups.get(key);
1584
+ if (list) list.push(pin);
1585
+ else groups.set(key, [pin]);
1586
+ }
1587
+ const clusters = [];
1588
+ for (const [key, group] of groups) {
1589
+ const only = group[0];
1590
+ clusters.push(
1591
+ group.length === 1 && only ? singleCluster(only) : multiCluster(key, group)
1592
+ );
1593
+ }
1594
+ clusters.sort((a, b) => a.id.localeCompare(b.id));
1595
+ return clusters;
1596
+ }
1597
+ function describeArea(query) {
1598
+ if (query.polygon != null) {
1599
+ if (!isMapPolygon(query.polygon)) {
1600
+ return {
1601
+ kind: "invalid",
1602
+ message: `Map search polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} [lat, lng] points.`
1603
+ };
1604
+ }
1605
+ return { kind: "polygon", polygon: query.polygon };
1606
+ }
1607
+ if (query.bounds != null) {
1608
+ if (!isMapBounds(query.bounds)) {
1609
+ return {
1610
+ kind: "invalid",
1611
+ message: "Map search bounds must be a finite rectangle with north > south and east > west."
1612
+ };
1613
+ }
1614
+ return { kind: "bounds", bounds: query.bounds };
1615
+ }
1616
+ return { kind: "empty" };
1617
+ }
1618
+ function isAbort(error, signal) {
1619
+ if (signal.aborted) return true;
1620
+ return error instanceof Error && error.name === "AbortError";
1621
+ }
1622
+ function asError(error) {
1623
+ return error instanceof Error ? error : new Error(String(error));
1624
+ }
1625
+ function requestFromSubscription(query, signal) {
1626
+ const {
1627
+ siteId: _siteId,
1628
+ bounds: _bounds,
1629
+ polygon: _polygon,
1630
+ ...request
1631
+ } = query;
1632
+ return { ...request, signal };
1633
+ }
1634
+ async function fetchArea(query, area, signal) {
1635
+ const request = requestFromSubscription(query, signal);
1636
+ if (area.kind === "polygon") {
1637
+ return searchListingsInPolygon(query.siteId, {
1638
+ ...request,
1639
+ polygon: area.polygon
1640
+ });
1641
+ }
1642
+ return searchListingsInBounds(query.siteId, {
1643
+ ...request,
1644
+ bounds: area.bounds
1645
+ });
1646
+ }
1647
+ function mapSearchSubscriptionKey(query) {
1648
+ return JSON.stringify({
1649
+ siteId: query.siteId,
1650
+ baseUrl: query.baseUrl ?? "",
1651
+ bounds: query.bounds ?? null,
1652
+ polygon: query.polygon ?? null,
1653
+ q: query.q ?? null,
1654
+ sort: query.sort ?? null,
1655
+ location: query.location ?? null,
1656
+ filters: query.filters ?? null,
1657
+ publishableKey: query.publishableKey ?? null,
1658
+ next: query.next ?? null,
1659
+ page: query.page ?? 1,
1660
+ pageSize: query.pageSize ?? MAP_SEARCH_DEFAULT_PAGE_SIZE
1661
+ });
1662
+ }
1663
+ function subscribeMapSearch(query, listener, options) {
1664
+ const area = describeArea(query);
1665
+ if (area.kind === "empty") {
1666
+ listener({ type: "empty" });
1667
+ return () => {
1668
+ };
1669
+ }
1670
+ if (area.kind === "invalid") {
1671
+ listener({ type: "error", error: new TypeError(area.message) });
1672
+ return () => {
1673
+ };
1674
+ }
1675
+ const controller = new AbortController();
1676
+ const debounceMs = options?.debounceMs ?? MAP_VIEWPORT_DEBOUNCE_MS;
1677
+ const timer = setTimeout(() => {
1678
+ listener({ type: "loading" });
1679
+ void fetchArea(query, area, controller.signal).then(
1680
+ (result) => {
1681
+ if (controller.signal.aborted) return;
1682
+ listener({ type: "ready", result });
1683
+ },
1684
+ (error) => {
1685
+ if (isAbort(error, controller.signal)) return;
1686
+ listener({ type: "error", error: asError(error) });
1687
+ }
1688
+ );
1689
+ }, debounceMs);
1690
+ return () => {
1691
+ clearTimeout(timer);
1692
+ controller.abort();
1693
+ };
1694
+ }
1695
+
1696
+ // src/react/use-map-search.ts
1697
+ var IDLE = emptyMapSearchResult();
1698
+ function areaKey(options) {
1699
+ return JSON.stringify({
1700
+ search: mapSearchSubscriptionKey(options),
1701
+ enabled: options.enabled !== false,
1702
+ debounceMs: options.debounceMs ?? MAP_VIEWPORT_DEBOUNCE_MS
1703
+ });
1704
+ }
1705
+ function useMapSearch(options) {
1706
+ const [result, setResult] = (0, import_react2.useState)(IDLE);
1707
+ const [loading, setLoading] = (0, import_react2.useState)(false);
1708
+ const [error, setError] = (0, import_react2.useState)(null);
1709
+ const optionsRef = (0, import_react2.useRef)(options);
1710
+ optionsRef.current = options;
1711
+ const key = areaKey(options);
1712
+ const zoom = options.zoom ?? 14;
1713
+ (0, import_react2.useEffect)(() => {
1714
+ const current = optionsRef.current;
1715
+ if (current.enabled === false) {
1716
+ setLoading(false);
1717
+ return;
1718
+ }
1719
+ return subscribeMapSearch(
1720
+ current,
1721
+ (event) => {
1722
+ if (event.type === "empty") {
1723
+ setResult(emptyMapSearchResult(current.pageSize));
1724
+ setLoading(false);
1725
+ setError(null);
1726
+ return;
1727
+ }
1728
+ if (event.type === "loading") {
1729
+ setLoading(true);
1730
+ setError(null);
1731
+ return;
1732
+ }
1733
+ if (event.type === "error") {
1734
+ setLoading(false);
1735
+ setError(event.error);
1736
+ return;
1737
+ }
1738
+ setResult(event.result);
1739
+ setLoading(false);
1740
+ setError(null);
1741
+ },
1742
+ { debounceMs: current.debounceMs }
1743
+ );
1744
+ }, [key]);
1745
+ const clusters = (0, import_react2.useMemo)(
1746
+ () => clusterPins(result.pins, zoom),
1747
+ [result.pins, zoom]
1748
+ );
1749
+ return { ...result, clusters, loading, error };
1750
+ }
1751
+
1752
+ // src/react/use-public-photo-search.ts
1753
+ var import_react3 = require("react");
1754
+
1143
1755
  // src/fetchers-photo-search.ts
1144
1756
  var PHOTO_SEARCH_MIN_QUERY_LENGTH = 3;
1145
1757
  var EMPTY_RESULT = {
@@ -1253,17 +1865,17 @@ function usePublicPhotoSearch(options) {
1253
1865
  } = options;
1254
1866
  const query = (options.query ?? "").trim();
1255
1867
  const searchable = enabled && query.length >= PHOTO_SEARCH_MIN_QUERY_LENGTH;
1256
- const siteIdRef = (0, import_react2.useRef)(siteId);
1868
+ const siteIdRef = (0, import_react3.useRef)(siteId);
1257
1869
  siteIdRef.current = siteId;
1258
1870
  const siteIdToken = typeof siteId === "string" ? siteId : null;
1259
- const fetchRef = (0, import_react2.useRef)(fetchImpl);
1871
+ const fetchRef = (0, import_react3.useRef)(fetchImpl);
1260
1872
  fetchRef.current = fetchImpl;
1261
- const requestRef = (0, import_react2.useRef)(0);
1262
- const [result, setResult] = (0, import_react2.useState)(EMPTY);
1263
- const [answered, setAnswered] = (0, import_react2.useState)("");
1264
- const [loading, setLoading] = (0, import_react2.useState)(searchable);
1265
- const [error, setError] = (0, import_react2.useState)(null);
1266
- (0, import_react2.useEffect)(() => {
1873
+ const requestRef = (0, import_react3.useRef)(0);
1874
+ const [result, setResult] = (0, import_react3.useState)(EMPTY);
1875
+ const [answered, setAnswered] = (0, import_react3.useState)("");
1876
+ const [loading, setLoading] = (0, import_react3.useState)(searchable);
1877
+ const [error, setError] = (0, import_react3.useState)(null);
1878
+ (0, import_react3.useEffect)(() => {
1267
1879
  const requestId = ++requestRef.current;
1268
1880
  if (!searchable) {
1269
1881
  setResult(EMPTY);
@@ -1307,7 +1919,7 @@ function usePublicPhotoSearch(options) {
1307
1919
  if (timer != null) clearTimeout(timer);
1308
1920
  };
1309
1921
  }, [searchable, query, limit, page, baseUrl, siteIdToken, debounceMs]);
1310
- const listings = (0, import_react2.useMemo)(
1922
+ const listings = (0, import_react3.useMemo)(
1311
1923
  () => applyMatchedPhotoCover(
1312
1924
  result.items.map((item) => item.listing),
1313
1925
  result.items
@@ -1329,6 +1941,7 @@ function usePublicPhotoSearch(options) {
1329
1941
  // Annotate the CommonJS export names for ESM import in node:
1330
1942
  0 && (module.exports = {
1331
1943
  PHOTO_SEARCH_DEBOUNCE_MS,
1944
+ useMapSearch,
1332
1945
  usePublicPhotoSearch,
1333
1946
  usePublicSearch
1334
1947
  });