@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/dist/index.js CHANGED
@@ -21,12 +21,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  AMENITY_FALLBACK_LABELS: () => AMENITY_FALLBACK_LABELS,
24
+ DEFAULT_MAPS_BASE_URL: () => DEFAULT_MAPS_BASE_URL,
24
25
  DEFAULT_PHONE_COUNTRY_CODE: () => DEFAULT_PHONE_COUNTRY_CODE,
25
26
  FORBIDDEN_SEARCH_QUERY_KEYS: () => FORBIDDEN_SEARCH_QUERY_KEYS,
26
27
  GaragemSdkError: () => GaragemSdkError,
27
28
  LISTING_AMENITY_TITLES: () => LISTING_AMENITY_TITLES,
28
29
  LISTING_DESCRIPTION_CLAMP: () => LISTING_DESCRIPTION_CLAMP,
29
30
  LeadSubmitError: () => LeadSubmitError,
31
+ MAPS_MAX_IMAGE_EDGE: () => MAPS_MAX_IMAGE_EDGE,
32
+ MAPS_SITE_HEADER: () => MAPS_SITE_HEADER,
33
+ MAP_POLYGON_MAX_VERTICES: () => MAP_POLYGON_MAX_VERTICES,
34
+ MAP_SEARCH_DEFAULT_PAGE_SIZE: () => MAP_SEARCH_DEFAULT_PAGE_SIZE,
35
+ MAP_SEARCH_MAX_PAGE_SIZE: () => MAP_SEARCH_MAX_PAGE_SIZE,
36
+ MAP_VIEWPORT_DEBOUNCE_MS: () => MAP_VIEWPORT_DEBOUNCE_MS,
30
37
  MATCHED_PHOTO_COVER_MAX_DISTANCE: () => MATCHED_PHOTO_COVER_MAX_DISTANCE,
31
38
  MAX_NATIONAL_PHONE_DIGITS: () => MAX_NATIONAL_PHONE_DIGITS,
32
39
  PHONE_COUNTRIES: () => PHONE_COUNTRIES,
@@ -43,18 +50,28 @@ __export(src_exports, {
43
50
  VISIT_TIME_ZONE: () => VISIT_TIME_ZONE,
44
51
  applyMatchedPhotoCover: () => applyMatchedPhotoCover,
45
52
  applyPathFilter: () => applyPathFilter,
53
+ boundaryCitySlug: () => boundaryCitySlug,
54
+ boundaryLayerId: () => boundaryLayerId,
55
+ boundaryLayerUrl: () => boundaryLayerUrl,
46
56
  buildQueryListingsParams: () => buildQueryListingsParams,
47
57
  canonicalizeSearchHref: () => canonicalizeSearchHref,
58
+ capMapPage: () => capMapPage,
59
+ capMapPageSize: () => capMapPageSize,
48
60
  clearStagedPathFilters: () => clearStagedPathFilters,
61
+ clearTravelTimeCache: () => clearTravelTimeCache,
62
+ clusterPins: () => clusterPins,
63
+ coarsenCoordinates: () => coarsenCoordinates,
49
64
  coerceNpmVersion: () => coerceNpmVersion,
50
65
  collapseDuplicatedBrazilianMobileNine: () => collapseDuplicatedBrazilianMobileNine,
51
66
  compareSemver: () => compareSemver,
52
67
  composeSearchPublicHref: () => composeSearchPublicHref2,
53
68
  composeSearchPublicPath: () => composeSearchPublicPath2,
69
+ coordinateDecimals: () => coordinateDecimals,
54
70
  countFacetChoices: () => countFacetChoices,
55
71
  countOptionLabel: () => countOptionLabel,
56
72
  createClient: () => createClient,
57
73
  createGaragemClient: () => createGaragemClient,
74
+ createTravelTimeCache: () => createTravelTimeCache,
58
75
  defaultPhoneCountry: () => defaultPhoneCountry,
59
76
  displayPathLocation: () => displayPathLocation,
60
77
  expandVisitSchedule: () => expandVisitSchedule,
@@ -64,6 +81,7 @@ __export(src_exports, {
64
81
  formatGroupedInteger: () => formatGroupedInteger,
65
82
  formatListingPrice: () => formatListingPrice,
66
83
  formatPhoneNational: () => formatPhoneNational,
84
+ getBoundaryLayer: () => getBoundaryLayer,
67
85
  getCmsCollection: () => getCmsCollection,
68
86
  getCmsCollections: () => getCmsCollections,
69
87
  getCmsEntries: () => getCmsEntries,
@@ -82,6 +100,8 @@ __export(src_exports, {
82
100
  hrefForPathFilters: () => hrefForPathFilters,
83
101
  hrefWithExplicitPage: () => hrefWithExplicitPage,
84
102
  isListingDetailPath: () => isListingDetailPath,
103
+ isMapBounds: () => isMapBounds,
104
+ isMapPolygon: () => isMapPolygon,
85
105
  isPhotoSearchOnPin: () => isPhotoSearchOnPin,
86
106
  isStudioPreviewHost: () => isStudioPreviewHost,
87
107
  isValidPhone: () => isValidPhone,
@@ -90,6 +110,7 @@ __export(src_exports, {
90
110
  listingAmenityGroups: () => listingAmenityGroups,
91
111
  listingBreadcrumb: () => listingBreadcrumb,
92
112
  listingBusinessLabel: () => listingBusinessLabel,
113
+ listingCoordinates: () => listingCoordinates,
93
114
  listingDescriptionPreview: () => listingDescriptionPreview,
94
115
  listingDetailFieldsModel: () => listingDetailFieldsModel,
95
116
  listingDetailModel: () => listingDetailModel,
@@ -101,12 +122,23 @@ __export(src_exports, {
101
122
  listingMediaOverlays: () => listingMediaOverlays,
102
123
  listingPhotoGroups: () => listingPhotoGroups,
103
124
  listingPublicPath: () => listingPublicPath,
125
+ listingStaticMapUrl: () => listingStaticMapUrl,
126
+ listingStreetViewAvailable: () => listingStreetViewAvailable,
127
+ listingStreetViewMetadataUrl: () => listingStreetViewMetadataUrl,
128
+ listingStreetViewUrl: () => listingStreetViewUrl,
104
129
  listingValues: () => listingValues,
105
130
  listingVisualHighlights: () => listingVisualHighlights,
131
+ mapClusterCellDegrees: () => mapClusterCellDegrees,
132
+ mapSearchPins: () => mapSearchPins,
133
+ mapsExportsPublished: () => mapsExportsPublished,
106
134
  marketExportsAvailableAt: () => marketExportsAvailableAt,
107
135
  marketPositionLabel: () => marketPositionLabel,
136
+ maxZoomForCoordinates: () => maxZoomForCoordinates,
108
137
  mergeAppliedSearchQueryIntoSearch: () => mergeAppliedSearchQueryIntoSearch2,
109
138
  nationalPhoneDigits: () => nationalPhoneDigits,
139
+ neighborhoodBoundaryLayer: () => neighborhoodBoundaryLayer,
140
+ neighborhoodBoundaryUrl: () => neighborhoodBoundaryUrl,
141
+ normalizeMapsBaseUrl: () => normalizeMapsBaseUrl,
110
142
  normalizeVisitDate: () => normalizeVisitDate,
111
143
  normalizeVisitTime: () => normalizeVisitTime,
112
144
  paginationPages: () => paginationPages,
@@ -132,10 +164,13 @@ __export(src_exports, {
132
164
  requestPriceEstimate: () => requestPriceEstimate,
133
165
  resolveMatchedCoverPhoto: () => resolveMatchedCoverPhoto,
134
166
  resolvePublicSiteId: () => resolvePublicSiteId,
167
+ resolveTravelDestination: () => resolveTravelDestination,
135
168
  searchChromeModel: () => searchChromeModel,
136
169
  searchHrefUsesLegacyFilterQuery: () => searchHrefUsesLegacyFilterQuery,
137
170
  searchListingPhotos: () => searchListingPhotos,
138
171
  searchListings: () => searchListings,
172
+ searchListingsInBounds: () => searchListingsInBounds,
173
+ searchListingsInPolygon: () => searchListingsInPolygon,
139
174
  searchResultsHeading: () => searchResultsHeading,
140
175
  searchSortOptions: () => searchSortOptions,
141
176
  serializeAppliedSearchQuery: () => serializeAppliedSearchQuery2,
@@ -148,6 +183,8 @@ __export(src_exports, {
148
183
  studioLeadInstruction: () => studioLeadInstruction,
149
184
  studioListingCardInstruction: () => studioListingCardInstruction,
150
185
  studioListingDetailInstruction: () => studioListingDetailInstruction,
186
+ studioMapSearchInstruction: () => studioMapSearchInstruction,
187
+ studioMapsInstruction: () => studioMapsInstruction,
151
188
  studioMarketInstruction: () => studioMarketInstruction,
152
189
  studioPhotoInstruction: () => studioPhotoInstruction,
153
190
  studioPhotoInstructionFor: () => studioPhotoInstructionFor,
@@ -162,6 +199,9 @@ __export(src_exports, {
162
199
  toE164: () => toE164,
163
200
  toListingCardModel: () => toListingCardModel,
164
201
  toolbarFilterIds: () => toolbarFilterIds,
202
+ travelTimeCacheKey: () => travelTimeCacheKey,
203
+ travelTimeFromListing: () => travelTimeFromListing,
204
+ travelTimesFromListing: () => travelTimesFromListing,
165
205
  truncateNationalPhoneDigits: () => truncateNationalPhoneDigits,
166
206
  unavailableReactImports: () => unavailableReactImports,
167
207
  visibleSearchFilters: () => visibleSearchFilters
@@ -457,7 +497,7 @@ async function getSearchUi(options) {
457
497
  );
458
498
  }
459
499
  async function queryListings(options) {
460
- const { params, baseUrl, fetch: fetchImpl, next } = options;
500
+ const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
461
501
  const siteId = await coerceSiteId(options.siteId);
462
502
  const base = normalizeBaseUrl(baseUrl);
463
503
  const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
@@ -470,7 +510,8 @@ async function queryListings(options) {
470
510
  "Content-Type": "application/json"
471
511
  },
472
512
  body: JSON.stringify(params ?? {}),
473
- next
513
+ next,
514
+ signal
474
515
  },
475
516
  fetchImpl ?? fetch,
476
517
  options.publishableKey
@@ -2900,11 +2941,13 @@ var STUDIO_SDK_CONTRACT = {
2900
2941
  * this and move that release's names from `optionalReactExports` /
2901
2942
  * `unpublishedSearchExports` / `unpublishedPhoneExports` into the
2902
2943
  * prompt-safe lists. Do not bump here until that tarball is on npm.
2903
- * Phone mask helpers shipped in 0.6.0. Search filter helpers
2944
+ * Phone mask helpers shipped in 0.6.0. Map search
2945
+ * (`useMapSearch`, `searchListingsInBounds`) shipped in 0.9.0 — 0.7.0
2946
+ * does not export them. Search filter helpers
2904
2947
  * (`visibleSearchFilters` / `toolbarFilterIds`) shipped in 0.4.12 and
2905
2948
  * remain on this pin.
2906
2949
  */
2907
- minNpmVersion: "0.6.0",
2950
+ minNpmVersion: "0.9.0",
2908
2951
  /** Historical: older tarballs inject card CSS when those components mount. */
2909
2952
  selfInjectSince: "0.4.2",
2910
2953
  chromeStrategy: "app-owned",
@@ -2917,7 +2960,8 @@ var STUDIO_SDK_CONTRACT = {
2917
2960
  * throws FatalRendererError.
2918
2961
  */
2919
2962
  optionalReactExports: {
2920
- usePublicPhotoSearch: "0.7.0"
2963
+ usePublicPhotoSearch: "0.7.0",
2964
+ useMapSearch: "0.9.0"
2921
2965
  },
2922
2966
  /**
2923
2967
  * Former `/react` chrome (including card/skeleton inject). Completeness
@@ -3026,6 +3070,28 @@ var STUDIO_SDK_CONTRACT = {
3026
3070
  "searchChromeModel",
3027
3071
  "rangeDraftFromPath"
3028
3072
  ],
3073
+ /**
3074
+ * maps.fndn.ai helpers (static map, street view, boundaries, travel
3075
+ * time) plus friendly map search. They ship in npm 0.9.0 (`mapsSince`).
3076
+ * Listing-detail map guidance stays empty: `studioMapsInstruction()`
3077
+ * keeps the listing contract for a later task and Studio does not
3078
+ * inject it. Map search is `studioMapSearchInstruction()`, and only
3079
+ * the site that opted into list-and-map may include that text.
3080
+ * `useMapSearch` is a `/react` hook in `optionalReactExports`; the
3081
+ * pin sentence does not name it.
3082
+ */
3083
+ mapsSince: "0.9.0",
3084
+ mapsExports: [
3085
+ "listingStaticMapUrl",
3086
+ "listingStreetViewUrl",
3087
+ "listingStreetViewAvailable",
3088
+ "neighborhoodBoundaryLayer",
3089
+ "boundaryLayerUrl",
3090
+ "travelTimeFromListing",
3091
+ "searchListingsInBounds",
3092
+ "searchListingsInPolygon",
3093
+ "clusterPins"
3094
+ ],
3029
3095
  /**
3030
3096
  * Market-data helpers (neighborhood price summary, listing market
3031
3097
  * position, visitor price estimate, pt-BR labels). They ship in
@@ -3150,7 +3216,7 @@ function studioPublishableKeyInstruction() {
3150
3216
  }
3151
3217
  function studioSdkPinInstruction() {
3152
3218
  const version = STUDIO_SDK_CONTRACT.minNpmVersion;
3153
- const names = [...reactExportsAvailableAt(version)].join(", ");
3219
+ const names = STUDIO_SDK_CONTRACT.reactExports.join(", ");
3154
3220
  return `In \`package.json\` set \`"@garagem-ai/site-sdk": "${version}"\` (exact). Import only these \`${STUDIO_SDK_PACKAGE}/react\` names: ${names}.`;
3155
3221
  }
3156
3222
  function studioLeadInstruction() {
@@ -3199,6 +3265,18 @@ function studioSearchInstruction() {
3199
3265
  const libNames = STUDIO_SDK_CONTRACT.searchExports.join(", ");
3200
3266
  return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Prefetch \`getSearchUi\` + \`queryListings\` on the server page. \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE, search: searchFromServer, initial })\` where \`searchFromServer\` is \`new URLSearchParams(await searchParams).toString()\` \u2014 never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file \u2014 heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app \u2014 do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` \u2014 never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range \u201CAtualizar\u201D on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / \u201CMais relevantes\u201D \u2014 map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give \u201CMais recentes\u201D (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton only for a slot whose content is still unknown, never as a Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (\u201CMais relevantes\u201D when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu \u2014 Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Pre\xE7o is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de im\xF3vel, caracter\xEDsticas and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no \u201CAplicar\u201D; the footer stages then applyStaged. Never read \`staged[filter.id]\` \u2014 path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set \u2014 never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
3201
3267
  }
3268
+ function mapsExportsPublished(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3269
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.mapsSince) >= 0;
3270
+ }
3271
+ function studioMapsInstruction(options = {}) {
3272
+ if (!mapsExportsPublished(options.pin)) return "";
3273
+ const names = STUDIO_SDK_CONTRACT.mapsExports.join(", ");
3274
+ return `Maps on listing detail: from \`${STUDIO_SDK_PACKAGE}\` import ${names}. \`listing.location.coordinates\` is already masked by the site's privacy settings (\u2248100 m by default) \u2014 pass the listing object as-is; never un-mask, never re-geocode the street address to get a sharper point, never add decimals (\`maxDecimals\` can only coarsen). Always pass \`siteId\` (the resolved site id / publishable key) so maps.fndn.ai meters the site. Static map: \`const mapSrc = listingStaticMapUrl(listing, { width: 640, height: 320, zoom: 15, style: "roadmap", siteId })\` then \`{mapSrc ? <img src={mapSrc} alt={model.location.label} /> : null}\` \u2014 \`null\` means no coordinates, so omit the block (never a placeholder image). Zoom is capped by the coordinate precision (16 on the default mask); do not work around it. Street View: on the server page \`const sv = await listingStreetViewAvailable(listing, { siteId })\` (metadata is free), and only when \`sv.available\` render \`<img src={listingStreetViewUrl(listing, { width: 640, height: 400, siteId })} alt="Street View" />\` \u2014 the image is billed per load. Neighbourhood outline on an interactive map: load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` (never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`); in \`initMap\` do \`const outline = await neighborhoodBoundaryLayer(listing.location.city, listing.location.neighborhood, { siteId })\` and \`if (outline.feature) map.data.addGeoJson(outline.feature)\`; with MapLibre the vector source url is \`boundaryLayerUrl(listing.location.city)\`. Travel time (\u201Cquanto tempo at\xE9\u2026\u201D): \`const trip = await travelTimeFromListing(listing, destination, { mode: "driving", siteId })\` gives \`{ minutes, distanceKm }\` or \`null\` (hide the row). Every uncached call is a billed Google Directions request: call it on demand \u2014 a destination the visitor typed, or at most one fixed landmark per listing page \u2014 never per listing card, never inside a search loop, keep the SDK cache on (default 15 min LRU, \`cache: null\` only in tests), and do not re-run it on every render.`;
3275
+ }
3276
+ function studioMapSearchInstruction(options = {}) {
3277
+ if (!mapsExportsPublished(options.pin)) return "";
3278
+ return `Map search on \`/imoveis\` (list and map of the same query). The list stays: keep \`usePublicSearch\` for the list, including its sort and pagination. The visitor switches on the same page. \`?modo=mapa\` is the map \u2014 read it on first paint. The list is the URL without \`modo\`; do not write \`modo=lista\` or \`modo=grade\`. Choosing the map sets \`modo=mapa\` and drops \`page\`. Choosing the list removes \`modo\`. On the map, hide sort and pagination. Do not add a map pager. The heading stays. Filters apply to both. Load Maps JS ONLY through \`<script src="https://maps.fndn.ai/sdk.js?callback=initMap" async defer />\` \u2014 never a Google key in the app, never \`NEXT_PUBLIC_GOOGLE_MAPS_API_KEY\`, never \`maps.googleapis.com\`, never \`@vis.gl/react-google-maps\`. From \`${STUDIO_SDK_PACKAGE}/react\` import useMapSearch; it fetches, debounces, and clusters. \`const map = useMapSearch({ siteId, baseUrl: GARAGEM_API_BASE, bounds, zoom, q, sort, location, filters, publishableKey })\` with the same q, sort, location, filters, and publishableKey as the list. Pass the map's current zoom on every zoom change, including after a cluster click. Changing zoom recomputes \`map.clusters\` and does not refetch; a bounds change refetches. Do not send filter_by, vector_query, or nl_query from the browser. Request page 1 and pageSize at most 100. Do not walk totalPages. Pins are the masked coordinates the API returned \u2014 plot them as returned, never geocode the street. Render \`map.clusters\` with \`google.maps.Marker\` (no map id needed), in two styles that never look alike. A cluster (\`count > 1\`) is a filled circle in the brand color with a white border and the white count as its label. A listing (\`count === 1\` with \`cluster.pin\`) is a white rounded-rectangle chip with a brand-color border, labelled with the short price in the brand color ("R$ 850 mil", "R$ 1,2 mi"; "Consulte" when the price is null or 0): \`icon: { path: "M-34,-12 h68 a6,6 0 0 1 6,6 v12 a6,6 0 0 1 -6,6 h-68 a6,6 0 0 1 -6,-6 v-12 a6,6 0 0 1 6,-6 z", fillColor: "#ffffff", fillOpacity: 1, strokeColor: brand, strokeWeight: 1.5, scale: 1, labelOrigin: new google.maps.Point(0, 0) }\`. Never draw a listing as a dot or a circle, and never without its price. Clicking a listing selects it and shows its card. Clicking a cluster opens its members: \`const members = map.pins.filter((pin) => cluster.pinIds.includes(pin.id))\`, then \`fitBounds\` a LatLngBounds of their coordinates with about 64px padding, so the listings land inside the new view and split into chips. Do not step the zoom around \`cluster.lat\`/\`cluster.lng\`: that point is approximate and the area around it can come back empty. When every member has the same coordinates, or the map is already at zoom 18, do not zoom: open a small list of those listings, each with its price and a link. Layout, top to bottom: query, heading, toolbar, then the view. On desktop the toolbar is one row: featured filters on the left, and the list/map toggle immediately beside the sort select on the right. On a narrow screen the filters stay in one horizontal scroll that does not wrap, and the toggle plus the sort sit together on the row below that scroll. On the map the sort is hidden, so the toggle keeps that place beside where the sort was. In map mode the map fills the remaining viewport height, with a minimum of about 240px. Keep the hook's 400ms viewport debounce. A drawn polygon is not required. Do not add a separate /mapa route, a regions page, or a map on the listing page. Do not call Street View or travel time inside the map search.`;
3279
+ }
3202
3280
  function marketExportsAvailableAt(pin) {
3203
3281
  return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
3204
3282
  }
@@ -3249,6 +3327,13 @@ function studioCodegenContractViolations(text) {
3249
3327
  violations.push(name);
3250
3328
  }
3251
3329
  }
3330
+ if (!mapsExportsPublished()) {
3331
+ for (const name of STUDIO_SDK_CONTRACT.mapsExports) {
3332
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
3333
+ violations.push(name);
3334
+ }
3335
+ }
3336
+ }
3252
3337
  for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
3253
3338
  if (mentionsExportName(text, name) && !violations.includes(name)) {
3254
3339
  violations.push(name);
@@ -3447,6 +3532,633 @@ function createGaragemClient(options = {}) {
3447
3532
  }
3448
3533
  var createClient = createGaragemClient;
3449
3534
 
3535
+ // src/maps.ts
3536
+ var DEFAULT_MAPS_BASE_URL = "https://maps.fndn.ai";
3537
+ var MAPS_SITE_HEADER = "X-Garagem-Site";
3538
+ var MAPS_MAX_IMAGE_EDGE = 640;
3539
+ var TRAVEL_MODES = /* @__PURE__ */ new Set([
3540
+ "driving",
3541
+ "walking",
3542
+ "bicycling",
3543
+ "transit"
3544
+ ]);
3545
+ function finite(value) {
3546
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
3547
+ }
3548
+ function listingCoordinates(listing) {
3549
+ const raw = listing?.location?.coordinates;
3550
+ const lat = finite(raw?.lat);
3551
+ const lng = finite(raw?.lng);
3552
+ if (lat == null || lng == null) return null;
3553
+ if (lat === 0 && lng === 0) return null;
3554
+ if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return null;
3555
+ return { lat, lng };
3556
+ }
3557
+ function coordinateDecimals(value) {
3558
+ if (!Number.isFinite(value)) return 0;
3559
+ const text = Math.abs(value).toString();
3560
+ if (text.includes("e")) {
3561
+ const fixed = Math.abs(value).toFixed(12).replace(/0+$/, "");
3562
+ const dot2 = fixed.indexOf(".");
3563
+ return dot2 === -1 ? 0 : fixed.length - dot2 - 1;
3564
+ }
3565
+ const dot = text.indexOf(".");
3566
+ return dot === -1 ? 0 : text.length - dot - 1;
3567
+ }
3568
+ function roundTo(value, decimals) {
3569
+ const factor = 10 ** decimals;
3570
+ return Math.round(value * factor) / factor;
3571
+ }
3572
+ function coarsenCoordinates(coordinates, maxDecimals) {
3573
+ if (maxDecimals == null || !Number.isFinite(maxDecimals)) return coordinates;
3574
+ const limit = Math.max(0, Math.floor(maxDecimals));
3575
+ return {
3576
+ lat: coordinateDecimals(coordinates.lat) > limit ? roundTo(coordinates.lat, limit) : coordinates.lat,
3577
+ lng: coordinateDecimals(coordinates.lng) > limit ? roundTo(coordinates.lng, limit) : coordinates.lng
3578
+ };
3579
+ }
3580
+ function maxZoomForCoordinates(coordinates) {
3581
+ const decimals = Math.min(
3582
+ coordinateDecimals(coordinates.lat),
3583
+ coordinateDecimals(coordinates.lng)
3584
+ );
3585
+ if (decimals >= 4) return 21;
3586
+ if (decimals === 3) return 16;
3587
+ if (decimals === 2) return 13;
3588
+ return 11;
3589
+ }
3590
+ function clampInt(value, fallback, min, max) {
3591
+ if (value == null || !Number.isFinite(value)) return fallback;
3592
+ return Math.min(max, Math.max(min, Math.round(value)));
3593
+ }
3594
+ function normalizeMapsBaseUrl(baseUrl) {
3595
+ const raw = (baseUrl ?? "").trim();
3596
+ if (!raw) return DEFAULT_MAPS_BASE_URL;
3597
+ return raw.replace(/\/+$/, "") || DEFAULT_MAPS_BASE_URL;
3598
+ }
3599
+ function siteTag(options) {
3600
+ const value = options?.siteId?.trim();
3601
+ return value ? value : null;
3602
+ }
3603
+ function mapsUrl(path, params, options) {
3604
+ const url = new URL(path, `${normalizeMapsBaseUrl(options?.mapsBaseUrl)}/`);
3605
+ for (const [key, value] of Object.entries(params)) {
3606
+ if (value === void 0 || value === "") continue;
3607
+ url.searchParams.set(key, String(value));
3608
+ }
3609
+ const site = siteTag(options);
3610
+ if (site) url.searchParams.set("site", site);
3611
+ return url.toString();
3612
+ }
3613
+ function resolveFetch(options) {
3614
+ const custom = options?.fetch;
3615
+ if (custom) return custom;
3616
+ const global = globalThis.fetch;
3617
+ if (!global) {
3618
+ throw new TypeError(
3619
+ "Garagem SDK: no fetch available. Pass `fetch` in the options."
3620
+ );
3621
+ }
3622
+ return global;
3623
+ }
3624
+ async function mapsFetchJson(url, options, init) {
3625
+ const headers = new Headers(init?.headers);
3626
+ headers.set("accept", "application/json");
3627
+ const site = siteTag(options);
3628
+ if (site) headers.set(MAPS_SITE_HEADER, site);
3629
+ try {
3630
+ const response = await resolveFetch(options)(url, { ...init, headers });
3631
+ if (!response.ok) return null;
3632
+ return await response.json();
3633
+ } catch {
3634
+ return null;
3635
+ }
3636
+ }
3637
+ function listingStaticMapUrl(listing, options = {}) {
3638
+ const raw = listingCoordinates(listing);
3639
+ if (!raw) return null;
3640
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
3641
+ const zoomCeiling = maxZoomForCoordinates(coordinates);
3642
+ const zoom = Math.min(zoomCeiling, clampInt(options.zoom, 15, 1, 21));
3643
+ const markerColor = options.markerColor ?? "red";
3644
+ return mapsUrl(
3645
+ "/v1/static-map",
3646
+ {
3647
+ lat: coordinates.lat,
3648
+ lng: coordinates.lng,
3649
+ zoom,
3650
+ width: clampInt(options.width, 600, 1, MAPS_MAX_IMAGE_EDGE),
3651
+ height: clampInt(options.height, 300, 1, MAPS_MAX_IMAGE_EDGE),
3652
+ scale: options.scale === 1 ? 1 : 2,
3653
+ maptype: options.style,
3654
+ markerColor: markerColor !== "red" ? markerColor : void 0,
3655
+ hidePoi: options.hidePoi ? "1" : void 0
3656
+ },
3657
+ options
3658
+ );
3659
+ }
3660
+ function listingStreetViewUrl(listing, options = {}) {
3661
+ const raw = listingCoordinates(listing);
3662
+ if (!raw) return null;
3663
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
3664
+ const width = clampInt(options.width, 640, 1, MAPS_MAX_IMAGE_EDGE);
3665
+ const height = clampInt(options.height, 640, 1, MAPS_MAX_IMAGE_EDGE);
3666
+ return mapsUrl(
3667
+ "/v1/street-view",
3668
+ {
3669
+ lat: coordinates.lat,
3670
+ lng: coordinates.lng,
3671
+ size: `${width}x${height}`,
3672
+ fov: clampInt(options.fov, 90, 10, 120),
3673
+ heading: clampInt(options.heading, 0, 0, 360),
3674
+ pitch: clampInt(options.pitch, 10, -90, 90)
3675
+ },
3676
+ options
3677
+ );
3678
+ }
3679
+ function listingStreetViewMetadataUrl(listing, options = {}) {
3680
+ const raw = listingCoordinates(listing);
3681
+ if (!raw) return null;
3682
+ const coordinates = coarsenCoordinates(raw, options.maxDecimals);
3683
+ return mapsUrl(
3684
+ "/v1/street-view/metadata",
3685
+ { lat: coordinates.lat, lng: coordinates.lng },
3686
+ options
3687
+ );
3688
+ }
3689
+ async function listingStreetViewAvailable(listing, options = {}) {
3690
+ const url = listingStreetViewMetadataUrl(listing, options);
3691
+ if (!url) {
3692
+ return { available: false, status: "NO_COORDINATES", url: "" };
3693
+ }
3694
+ const data = await mapsFetchJson(url, options);
3695
+ const status = typeof data?.status === "string" ? data.status : "ERROR";
3696
+ const result = {
3697
+ available: status === "OK",
3698
+ status,
3699
+ url
3700
+ };
3701
+ if (typeof data?.pano_id === "string") result.panoId = data.pano_id;
3702
+ if (typeof data?.date === "string") result.date = data.date;
3703
+ return result;
3704
+ }
3705
+ function boundaryCitySlug(city) {
3706
+ return city.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
3707
+ }
3708
+ function boundaryLayerId(city) {
3709
+ const slug = boundaryCitySlug(city);
3710
+ return slug.endsWith("_boundaries") ? slug : `${slug}_boundaries`;
3711
+ }
3712
+ function boundaryLayerUrl(city, options = {}) {
3713
+ const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
3714
+ const id = boundaryLayerId(city);
3715
+ const slug = id.replace(/_boundaries$/, "");
3716
+ switch (options.kind ?? "tilejson") {
3717
+ case "layer":
3718
+ return `${base}/v1/layers/${id}`;
3719
+ case "tiles":
3720
+ return `${base}/martin/${id}/{z}/{x}/{y}`;
3721
+ case "geojson":
3722
+ return `${base}/api/boundaries/${slug}`;
3723
+ default:
3724
+ return `${base}/martin/${id}`;
3725
+ }
3726
+ }
3727
+ function neighborhoodBoundaryUrl(city, neighborhood, options = {}) {
3728
+ const base = normalizeMapsBaseUrl(options.mapsBaseUrl);
3729
+ const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
3730
+ const url = new URL(
3731
+ `${base}/api/boundaries/${slug}/${encodeURIComponent(neighborhood.trim())}`
3732
+ );
3733
+ if (options.source && options.source !== "listaaberta") {
3734
+ url.searchParams.set("source", options.source);
3735
+ }
3736
+ return url.toString();
3737
+ }
3738
+ function asNumber(value, fallback) {
3739
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
3740
+ }
3741
+ async function getBoundaryLayer(city, options = {}) {
3742
+ const data = await mapsFetchJson(
3743
+ boundaryLayerUrl(city, { ...options, kind: "layer" }),
3744
+ options
3745
+ );
3746
+ const layer = data?.layer;
3747
+ if (!data?.ok || !layer || typeof layer.id !== "string") return null;
3748
+ const rawSourceLayers = Array.isArray(layer.source_layers) ? layer.source_layers : [];
3749
+ return {
3750
+ id: layer.id,
3751
+ name: typeof layer.name === "string" ? layer.name : layer.id,
3752
+ description: typeof layer.description === "string" ? layer.description : "",
3753
+ city: typeof layer.city === "string" ? layer.city : void 0,
3754
+ tiles: typeof layer.tiles === "string" ? layer.tiles : "",
3755
+ tilejson: typeof layer.tilejson === "string" ? layer.tilejson : "",
3756
+ geojson: typeof layer.geojson === "string" ? layer.geojson : void 0,
3757
+ sourceLayers: rawSourceLayers.filter(
3758
+ (entry) => !!entry && typeof entry === "object"
3759
+ ).map((entry) => ({
3760
+ id: String(entry.id ?? ""),
3761
+ label: String(entry.label ?? entry.id ?? ""),
3762
+ minzoom: typeof entry.minzoom === "number" ? entry.minzoom : void 0,
3763
+ maxzoom: typeof entry.maxzoom === "number" ? entry.maxzoom : void 0
3764
+ })),
3765
+ minzoom: asNumber(layer.minzoom, 0),
3766
+ maxzoom: asNumber(layer.maxzoom, 14),
3767
+ attribution: typeof layer.attribution === "string" ? layer.attribution : void 0,
3768
+ available: layer.available !== false
3769
+ };
3770
+ }
3771
+ function isFeature(value) {
3772
+ return !!value && typeof value === "object" && value.type === "Feature";
3773
+ }
3774
+ async function neighborhoodBoundaryLayer(city, neighborhood, options = {}) {
3775
+ const url = neighborhoodBoundaryUrl(city, neighborhood, options);
3776
+ const slug = boundaryLayerId(city).replace(/_boundaries$/, "");
3777
+ const result = {
3778
+ city: slug,
3779
+ neighborhood: neighborhood.trim(),
3780
+ feature: null,
3781
+ candidates: [],
3782
+ url,
3783
+ tiles: boundaryLayerUrl(city, { ...options, kind: "tiles" })
3784
+ };
3785
+ if (!result.neighborhood) return result;
3786
+ const data = await mapsFetchJson(
3787
+ url,
3788
+ options
3789
+ );
3790
+ if (!data) return result;
3791
+ if (isFeature(data)) {
3792
+ result.feature = data;
3793
+ result.candidates = [data];
3794
+ return result;
3795
+ }
3796
+ const features = Array.isArray(data.features) ? data.features.filter(isFeature) : [];
3797
+ result.candidates = features;
3798
+ const wanted = result.neighborhood.toLocaleLowerCase("pt-BR");
3799
+ result.feature = features.find(
3800
+ (feature) => typeof feature.properties?.name === "string" && feature.properties.name.toLocaleLowerCase("pt-BR") === wanted
3801
+ ) ?? (features.length === 1 ? features[0] : null);
3802
+ return result;
3803
+ }
3804
+ function createTravelTimeCache(options = {}) {
3805
+ const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? 200));
3806
+ const ttlMs = Math.max(0, options.ttlMs ?? 15 * 60 * 1e3);
3807
+ const entries = /* @__PURE__ */ new Map();
3808
+ return {
3809
+ get(key) {
3810
+ const hit = entries.get(key);
3811
+ if (!hit) return void 0;
3812
+ if (hit.expiresAt <= Date.now()) {
3813
+ entries.delete(key);
3814
+ return void 0;
3815
+ }
3816
+ entries.delete(key);
3817
+ entries.set(key, hit);
3818
+ return hit.value;
3819
+ },
3820
+ set(key, value) {
3821
+ entries.delete(key);
3822
+ entries.set(key, { value, expiresAt: Date.now() + ttlMs });
3823
+ while (entries.size > maxEntries) {
3824
+ const oldest = entries.keys().next().value;
3825
+ if (oldest === void 0) break;
3826
+ entries.delete(oldest);
3827
+ }
3828
+ },
3829
+ clear() {
3830
+ entries.clear();
3831
+ },
3832
+ get size() {
3833
+ return entries.size;
3834
+ }
3835
+ };
3836
+ }
3837
+ var defaultTravelTimeCache = createTravelTimeCache();
3838
+ function clearTravelTimeCache() {
3839
+ defaultTravelTimeCache.clear();
3840
+ }
3841
+ function travelTimeCacheKey(origin, destination, mode) {
3842
+ return `${origin.lat},${origin.lng}|${destination.lat},${destination.lng}|${mode}`;
3843
+ }
3844
+ function travelTimeQueryCacheKey(origin, query, mode) {
3845
+ return `${origin.lat},${origin.lng}|q:${query}|${mode}`;
3846
+ }
3847
+ function trimmedDestinationQuery(destination) {
3848
+ if (typeof destination !== "string") return null;
3849
+ const query = destination.trim();
3850
+ return query ? query : null;
3851
+ }
3852
+ function recallTravelTime(cache, key) {
3853
+ if (!cache) return null;
3854
+ const hit = cache.get(key);
3855
+ return hit ? { ...hit, cached: true } : null;
3856
+ }
3857
+ function rememberTravelTime(cache, keys, value) {
3858
+ if (!cache) return;
3859
+ for (const key of keys) cache.set(key, value);
3860
+ }
3861
+ function normalizeMode(mode) {
3862
+ return mode && TRAVEL_MODES.has(mode) ? mode : "driving";
3863
+ }
3864
+ async function resolveTravelDestination(destination, options = {}) {
3865
+ if (typeof destination !== "string") {
3866
+ const lat2 = finite(destination?.lat);
3867
+ const lng2 = finite(destination?.lng);
3868
+ return lat2 == null || lng2 == null ? null : { lat: lat2, lng: lng2 };
3869
+ }
3870
+ const query = destination.trim();
3871
+ if (!query) return null;
3872
+ const data = await mapsFetchJson(
3873
+ mapsUrl("/v1/geocode", { q: query }, options),
3874
+ options
3875
+ );
3876
+ const lat = finite(data?.latitude);
3877
+ const lng = finite(data?.longitude);
3878
+ if (!data?.ok || lat == null || lng == null) return null;
3879
+ return { lat, lng };
3880
+ }
3881
+ function minutesFromSeconds(seconds) {
3882
+ return Math.max(1, Math.round(seconds / 60));
3883
+ }
3884
+ async function travelTimeFromListing(listing, destination, options = {}) {
3885
+ const raw = listingCoordinates(listing);
3886
+ if (!raw) return null;
3887
+ const origin = coarsenCoordinates(raw, options.maxDecimals);
3888
+ const mode = normalizeMode(options.mode);
3889
+ const cache = options.cache === void 0 ? defaultTravelTimeCache : options.cache;
3890
+ const query = trimmedDestinationQuery(destination);
3891
+ if (typeof destination === "string" && !query) return null;
3892
+ if (query) {
3893
+ const queryHit = recallTravelTime(
3894
+ cache,
3895
+ travelTimeQueryCacheKey(origin, query, mode)
3896
+ );
3897
+ if (queryHit) return queryHit;
3898
+ }
3899
+ const target = await resolveTravelDestination(query ?? destination, options);
3900
+ if (!target) return null;
3901
+ const coordKey = travelTimeCacheKey(origin, target, mode);
3902
+ const stored = cache?.get(coordKey);
3903
+ if (stored) {
3904
+ if (query) {
3905
+ rememberTravelTime(
3906
+ cache,
3907
+ [travelTimeQueryCacheKey(origin, query, mode)],
3908
+ stored
3909
+ );
3910
+ }
3911
+ return { ...stored, cached: true };
3912
+ }
3913
+ const data = await mapsFetchJson(
3914
+ mapsUrl(
3915
+ "/v1/directions",
3916
+ {
3917
+ origin: `${origin.lat},${origin.lng}`,
3918
+ destination: `${target.lat},${target.lng}`,
3919
+ mode
3920
+ },
3921
+ options
3922
+ ),
3923
+ options
3924
+ );
3925
+ const seconds = finite(data?.route?.totalTravelTime);
3926
+ const meters = finite(data?.route?.totalDistance);
3927
+ if (!data?.ok || seconds == null || meters == null) return null;
3928
+ const result = {
3929
+ minutes: minutesFromSeconds(seconds),
3930
+ seconds,
3931
+ distanceMeters: meters,
3932
+ distanceKm: Math.round(meters / 100) / 10,
3933
+ mode,
3934
+ origin,
3935
+ destination: target,
3936
+ cached: false
3937
+ };
3938
+ const keys = query ? [coordKey, travelTimeQueryCacheKey(origin, query, mode)] : [coordKey];
3939
+ rememberTravelTime(cache, keys, result);
3940
+ return result;
3941
+ }
3942
+ async function travelTimesFromListing(listing, destinations, options = {}) {
3943
+ const raw = listingCoordinates(listing);
3944
+ if (!raw) return null;
3945
+ const origin = coarsenCoordinates(raw, options.maxDecimals);
3946
+ const targets = destinations.map((destination) => {
3947
+ const lat = finite(destination?.lat);
3948
+ const lng = finite(destination?.lng);
3949
+ return lat == null || lng == null ? null : { lat, lng };
3950
+ }).filter((item) => item !== null);
3951
+ if (targets.length === 0) return [];
3952
+ const data = await mapsFetchJson(
3953
+ mapsUrl("/v1/route-matrix", {}, options),
3954
+ options,
3955
+ {
3956
+ method: "POST",
3957
+ headers: { "content-type": "application/json" },
3958
+ body: JSON.stringify({ origin, destinations: targets })
3959
+ }
3960
+ );
3961
+ if (!data?.ok || !Array.isArray(data.durations)) return null;
3962
+ return targets.map((destination, index) => {
3963
+ const seconds = finite(
3964
+ data.durations && data.durations[index]
3965
+ );
3966
+ if (seconds == null) return null;
3967
+ return { minutes: minutesFromSeconds(seconds), seconds, destination };
3968
+ });
3969
+ }
3970
+
3971
+ // src/map-search.ts
3972
+ var MAP_SEARCH_MAX_PAGE_SIZE = 100;
3973
+ var MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
3974
+ var MAP_SEARCH_MAX_PAGE = 1e4;
3975
+ var MAP_VIEWPORT_DEBOUNCE_MS = 400;
3976
+ var MAP_POLYGON_MAX_VERTICES = 64;
3977
+ function capMapPageSize(value) {
3978
+ if (value == null || !Number.isFinite(value) || value <= 0) {
3979
+ return MAP_SEARCH_DEFAULT_PAGE_SIZE;
3980
+ }
3981
+ return Math.min(MAP_SEARCH_MAX_PAGE_SIZE, Math.floor(value));
3982
+ }
3983
+ function capMapPage(value) {
3984
+ if (value == null || !Number.isFinite(value) || value <= 1) return 1;
3985
+ return Math.min(MAP_SEARCH_MAX_PAGE, Math.floor(value));
3986
+ }
3987
+ function finitePair(lat, lng) {
3988
+ if (typeof lat !== "number" || typeof lng !== "number") return null;
3989
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
3990
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
3991
+ return [lat, lng];
3992
+ }
3993
+ function isMapBounds(bounds) {
3994
+ if (!bounds) return false;
3995
+ const north = finitePair(bounds.north, bounds.east);
3996
+ const south = finitePair(bounds.south, bounds.west);
3997
+ if (!north || !south) return false;
3998
+ return bounds.north > bounds.south && bounds.east > bounds.west;
3999
+ }
4000
+ function isMapPolygon(polygon) {
4001
+ if (!Array.isArray(polygon)) return false;
4002
+ if (polygon.length < 3 || polygon.length > MAP_POLYGON_MAX_VERTICES + 1) {
4003
+ return false;
4004
+ }
4005
+ let unique = 0;
4006
+ let prev = null;
4007
+ for (const point of polygon) {
4008
+ if (!Array.isArray(point)) return false;
4009
+ const pair = finitePair(point[0], point[1]);
4010
+ if (!pair) return false;
4011
+ if (prev && prev[0] === pair[0] && prev[1] === pair[1]) continue;
4012
+ prev = pair;
4013
+ unique += 1;
4014
+ }
4015
+ if (unique >= 2 && polygon.length >= 2) {
4016
+ const first = finitePair(polygon[0]?.[0], polygon[0]?.[1]);
4017
+ const last = finitePair(
4018
+ polygon[polygon.length - 1]?.[0],
4019
+ polygon[polygon.length - 1]?.[1]
4020
+ );
4021
+ if (first && last && first[0] === last[0] && first[1] === last[1] && unique > 1) {
4022
+ unique -= 1;
4023
+ }
4024
+ }
4025
+ return unique >= 3 && unique <= MAP_POLYGON_MAX_VERTICES;
4026
+ }
4027
+ function mapSearchPins(listings) {
4028
+ const pins = [];
4029
+ for (const listing of listings) {
4030
+ const coords = listingCoordinates(listing);
4031
+ if (!coords || !listing.id) continue;
4032
+ const src = listing.coverImage?.src;
4033
+ pins.push({
4034
+ id: listing.id,
4035
+ lat: coords.lat,
4036
+ lng: coords.lng,
4037
+ price: listing.price ?? null,
4038
+ coverImage: src ? src : null
4039
+ });
4040
+ }
4041
+ return pins;
4042
+ }
4043
+ function listingsResult(listings, meta, requestedPageSize) {
4044
+ return {
4045
+ pins: mapSearchPins(listings),
4046
+ cards: listings.map((listing) => toListingCardModel(listing)),
4047
+ listings,
4048
+ page: meta.page ?? 1,
4049
+ pageSize: meta.limit ?? requestedPageSize,
4050
+ total: meta.total ?? listings.length,
4051
+ totalPages: meta.totalPages ?? 0
4052
+ };
4053
+ }
4054
+ function searchParams(area, options) {
4055
+ const params = {
4056
+ page: capMapPage(options.page),
4057
+ limit: capMapPageSize(options.pageSize)
4058
+ };
4059
+ if (options.q !== void 0) params.q = options.q;
4060
+ if (options.sort !== void 0) params.sort = options.sort;
4061
+ if (options.location !== void 0) params.location = options.location;
4062
+ if (options.filters) params.filters = options.filters;
4063
+ if (area.polygon) params.polygon = area.polygon;
4064
+ else if (area.bounds) params.bounds = area.bounds;
4065
+ return params;
4066
+ }
4067
+ async function runMapSearch(siteId, area, options) {
4068
+ const pageSize = capMapPageSize(options.pageSize);
4069
+ const result = await queryListings({
4070
+ siteId,
4071
+ params: searchParams(area, options),
4072
+ baseUrl: options.baseUrl,
4073
+ fetch: options.fetch,
4074
+ signal: options.signal,
4075
+ publishableKey: options.publishableKey,
4076
+ next: options.next
4077
+ });
4078
+ return listingsResult(result.listings ?? [], result, pageSize);
4079
+ }
4080
+ async function searchListingsInBounds(siteId, options) {
4081
+ if (!isMapBounds(options.bounds)) {
4082
+ throw new TypeError(
4083
+ "searchListingsInBounds: bounds must be a finite rectangle with north > south and east > west (no antimeridian)."
4084
+ );
4085
+ }
4086
+ return runMapSearch(siteId, { bounds: options.bounds }, options);
4087
+ }
4088
+ async function searchListingsInPolygon(siteId, options) {
4089
+ if (!isMapPolygon(options.polygon)) {
4090
+ throw new TypeError(
4091
+ `searchListingsInPolygon: polygon must be 3\u2013${MAP_POLYGON_MAX_VERTICES} finite [lat, lng] points.`
4092
+ );
4093
+ }
4094
+ return runMapSearch(siteId, { polygon: options.polygon }, options);
4095
+ }
4096
+ function clampZoom(zoom) {
4097
+ if (!Number.isFinite(zoom)) return 0;
4098
+ return Math.min(22, Math.max(0, zoom));
4099
+ }
4100
+ function mapClusterCellDegrees(zoom) {
4101
+ return 360 / 2 ** clampZoom(zoom) / 4;
4102
+ }
4103
+ function usablePin(pin) {
4104
+ return finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0);
4105
+ }
4106
+ function groupPrecision(group) {
4107
+ let max = 0;
4108
+ for (const pin of group) {
4109
+ max = Math.max(
4110
+ max,
4111
+ coordinateDecimals(pin.lat),
4112
+ coordinateDecimals(pin.lng)
4113
+ );
4114
+ }
4115
+ return max;
4116
+ }
4117
+ function multiCluster(key, group) {
4118
+ const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
4119
+ const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
4120
+ const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
4121
+ return {
4122
+ id: key,
4123
+ lat: center.lat,
4124
+ lng: center.lng,
4125
+ count: group.length,
4126
+ pinIds: group.map((pin) => pin.id),
4127
+ pin: null
4128
+ };
4129
+ }
4130
+ function singleCluster(pin) {
4131
+ return {
4132
+ id: pin.id,
4133
+ lat: pin.lat,
4134
+ lng: pin.lng,
4135
+ count: 1,
4136
+ pinIds: [pin.id],
4137
+ pin
4138
+ };
4139
+ }
4140
+ function clusterPins(pins, zoom) {
4141
+ if (pins.length === 0) return [];
4142
+ const cell = mapClusterCellDegrees(zoom);
4143
+ const groups = /* @__PURE__ */ new Map();
4144
+ for (const pin of pins) {
4145
+ if (!usablePin(pin)) continue;
4146
+ const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
4147
+ const list = groups.get(key);
4148
+ if (list) list.push(pin);
4149
+ else groups.set(key, [pin]);
4150
+ }
4151
+ const clusters = [];
4152
+ for (const [key, group] of groups) {
4153
+ const only = group[0];
4154
+ clusters.push(
4155
+ group.length === 1 && only ? singleCluster(only) : multiCluster(key, group)
4156
+ );
4157
+ }
4158
+ clusters.sort((a, b) => a.id.localeCompare(b.id));
4159
+ return clusters;
4160
+ }
4161
+
3450
4162
  // src/fetchers-photos.ts
3451
4163
  var MEDIA_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3452
4164
  var HIDDEN_SIMILAR_PHOTOS = {
@@ -3967,12 +4679,19 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3967
4679
  // Annotate the CommonJS export names for ESM import in node:
3968
4680
  0 && (module.exports = {
3969
4681
  AMENITY_FALLBACK_LABELS,
4682
+ DEFAULT_MAPS_BASE_URL,
3970
4683
  DEFAULT_PHONE_COUNTRY_CODE,
3971
4684
  FORBIDDEN_SEARCH_QUERY_KEYS,
3972
4685
  GaragemSdkError,
3973
4686
  LISTING_AMENITY_TITLES,
3974
4687
  LISTING_DESCRIPTION_CLAMP,
3975
4688
  LeadSubmitError,
4689
+ MAPS_MAX_IMAGE_EDGE,
4690
+ MAPS_SITE_HEADER,
4691
+ MAP_POLYGON_MAX_VERTICES,
4692
+ MAP_SEARCH_DEFAULT_PAGE_SIZE,
4693
+ MAP_SEARCH_MAX_PAGE_SIZE,
4694
+ MAP_VIEWPORT_DEBOUNCE_MS,
3976
4695
  MATCHED_PHOTO_COVER_MAX_DISTANCE,
3977
4696
  MAX_NATIONAL_PHONE_DIGITS,
3978
4697
  PHONE_COUNTRIES,
@@ -3989,18 +4708,28 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3989
4708
  VISIT_TIME_ZONE,
3990
4709
  applyMatchedPhotoCover,
3991
4710
  applyPathFilter,
4711
+ boundaryCitySlug,
4712
+ boundaryLayerId,
4713
+ boundaryLayerUrl,
3992
4714
  buildQueryListingsParams,
3993
4715
  canonicalizeSearchHref,
4716
+ capMapPage,
4717
+ capMapPageSize,
3994
4718
  clearStagedPathFilters,
4719
+ clearTravelTimeCache,
4720
+ clusterPins,
4721
+ coarsenCoordinates,
3995
4722
  coerceNpmVersion,
3996
4723
  collapseDuplicatedBrazilianMobileNine,
3997
4724
  compareSemver,
3998
4725
  composeSearchPublicHref,
3999
4726
  composeSearchPublicPath,
4727
+ coordinateDecimals,
4000
4728
  countFacetChoices,
4001
4729
  countOptionLabel,
4002
4730
  createClient,
4003
4731
  createGaragemClient,
4732
+ createTravelTimeCache,
4004
4733
  defaultPhoneCountry,
4005
4734
  displayPathLocation,
4006
4735
  expandVisitSchedule,
@@ -4010,6 +4739,7 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4010
4739
  formatGroupedInteger,
4011
4740
  formatListingPrice,
4012
4741
  formatPhoneNational,
4742
+ getBoundaryLayer,
4013
4743
  getCmsCollection,
4014
4744
  getCmsCollections,
4015
4745
  getCmsEntries,
@@ -4028,6 +4758,8 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4028
4758
  hrefForPathFilters,
4029
4759
  hrefWithExplicitPage,
4030
4760
  isListingDetailPath,
4761
+ isMapBounds,
4762
+ isMapPolygon,
4031
4763
  isPhotoSearchOnPin,
4032
4764
  isStudioPreviewHost,
4033
4765
  isValidPhone,
@@ -4036,6 +4768,7 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4036
4768
  listingAmenityGroups,
4037
4769
  listingBreadcrumb,
4038
4770
  listingBusinessLabel,
4771
+ listingCoordinates,
4039
4772
  listingDescriptionPreview,
4040
4773
  listingDetailFieldsModel,
4041
4774
  listingDetailModel,
@@ -4047,12 +4780,23 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4047
4780
  listingMediaOverlays,
4048
4781
  listingPhotoGroups,
4049
4782
  listingPublicPath,
4783
+ listingStaticMapUrl,
4784
+ listingStreetViewAvailable,
4785
+ listingStreetViewMetadataUrl,
4786
+ listingStreetViewUrl,
4050
4787
  listingValues,
4051
4788
  listingVisualHighlights,
4789
+ mapClusterCellDegrees,
4790
+ mapSearchPins,
4791
+ mapsExportsPublished,
4052
4792
  marketExportsAvailableAt,
4053
4793
  marketPositionLabel,
4794
+ maxZoomForCoordinates,
4054
4795
  mergeAppliedSearchQueryIntoSearch,
4055
4796
  nationalPhoneDigits,
4797
+ neighborhoodBoundaryLayer,
4798
+ neighborhoodBoundaryUrl,
4799
+ normalizeMapsBaseUrl,
4056
4800
  normalizeVisitDate,
4057
4801
  normalizeVisitTime,
4058
4802
  paginationPages,
@@ -4078,10 +4822,13 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4078
4822
  requestPriceEstimate,
4079
4823
  resolveMatchedCoverPhoto,
4080
4824
  resolvePublicSiteId,
4825
+ resolveTravelDestination,
4081
4826
  searchChromeModel,
4082
4827
  searchHrefUsesLegacyFilterQuery,
4083
4828
  searchListingPhotos,
4084
4829
  searchListings,
4830
+ searchListingsInBounds,
4831
+ searchListingsInPolygon,
4085
4832
  searchResultsHeading,
4086
4833
  searchSortOptions,
4087
4834
  serializeAppliedSearchQuery,
@@ -4094,6 +4841,8 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4094
4841
  studioLeadInstruction,
4095
4842
  studioListingCardInstruction,
4096
4843
  studioListingDetailInstruction,
4844
+ studioMapSearchInstruction,
4845
+ studioMapsInstruction,
4097
4846
  studioMarketInstruction,
4098
4847
  studioPhotoInstruction,
4099
4848
  studioPhotoInstructionFor,
@@ -4108,6 +4857,9 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
4108
4857
  toE164,
4109
4858
  toListingCardModel,
4110
4859
  toolbarFilterIds,
4860
+ travelTimeCacheKey,
4861
+ travelTimeFromListing,
4862
+ travelTimesFromListing,
4111
4863
  truncateNationalPhoneDigits,
4112
4864
  unavailableReactImports,
4113
4865
  visibleSearchFilters