@garagem-ai/site-sdk 0.10.1 → 0.11.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/index.mjs CHANGED
@@ -2800,6 +2800,7 @@ function isVideoPlatformUrl(url) {
2800
2800
  }
2801
2801
  function overlayKind(type, src) {
2802
2802
  if (type === "image" || type === "photo") return null;
2803
+ if (/\.(mp4|webm|ogg|mov)(\?|#|$)/i.test(src)) return "video";
2803
2804
  const host = new URL(src).hostname.toLowerCase();
2804
2805
  if (type === "tour" || type === "virtual_tour" || host.includes("matterport")) {
2805
2806
  return "tour";
@@ -3155,7 +3156,9 @@ var STUDIO_SDK_CONTRACT = {
3155
3156
  "visibleSearchFilters",
3156
3157
  "toolbarFilterIds",
3157
3158
  "paginationPages",
3158
- "hrefWithExplicitPage"
3159
+ "hrefWithExplicitPage",
3160
+ "countOptionLabel",
3161
+ "countFacetChoices"
3159
3162
  ],
3160
3163
  /**
3161
3164
  * Main-package helpers in git / newer tarballs but not required on
@@ -3178,6 +3181,12 @@ var STUDIO_SDK_CONTRACT = {
3178
3181
  * pin sentence does not name it.
3179
3182
  */
3180
3183
  mapsSince: "0.9.0",
3184
+ /**
3185
+ * `useMapSearch` returns weighted location buckets (`map.buckets`, and
3186
+ * `map.clusters` built from them) when the matches overflow one page.
3187
+ * The map-search guidance teaches bucket clicks only from this pin on.
3188
+ */
3189
+ mapBucketsSince: "0.11.0",
3181
3190
  mapsExports: [
3182
3191
  "listingStaticMapUrl",
3183
3192
  "listingStreetViewUrl",
@@ -3243,7 +3252,7 @@ function isSellerLeadOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3243
3252
  function studioSellerLeadSdkInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3244
3253
  if (!isSellerLeadOnPin(pin)) return "";
3245
3254
  const names = STUDIO_SDK_CONTRACT.sellerLeadExports.join(", ");
3246
- return `Property registration (\`/anunciar-imovel\`, client component): import ${names}, isValidPhone, toE164 from \`${STUDIO_SDK_PACKAGE}\`. Address: load Maps JS only through \`<script src="https://maps.fndn.ai/sdk.js?callback=initPlaces" async defer />\` (Places is included; never a Google key, never \`maps.googleapis.com\`), then \`google.maps.places.Autocomplete\` with \`componentRestrictions: { country: "br" }\` and pt-BR. Picking a suggestion fills fullAddress, street, number, neighborhood, city, state (the 2-letter code), postalCode, latitude and longitude from the place; a typed address without a suggestion is not enough. The visitor confirms number or "Sem n\xFAmero", bloco/torre or "N\xE3o tem", unidade or "N\xE3o tem" (noNumber, noBlocoTorre, noUnidade). Block the next group while \`sellerAddressErrors(address)\` has keys and show each message on its field. Owner: name, email and phone are all required \u2014 \`isValidName\`, \`isValidEmail\`, the phone mask with \`isValidPhone(toE164(phone))\`. Photos: \`await uploadSellerLeadPhoto({ siteId, baseUrl: GARAGEM_API_BASE, file, publishableKey })\` per file (JPG/PNG/WEBP, 10MB, up to 30), keep the returned URLs. Photo session: \`const schedule = sellerPhotoSchedule(config)\` and \`slotsForDate(schedule, day)\` for the hours. Submit once with \`await submitSellerLead({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey, owner: { name, email, phone }, address, property: { businessType, saleValue, rentValue, condoFee, totalArea, bedrooms, bathrooms, suites, parkingSpaces }, photos, photoSession: { date, time }, photoSchedule: schedule })\` (omit what the visitor did not fill). Errors are \`LeadSubmitError\`: \`duplicate_property\` \u2192 "Este im\xF3vel j\xE1 est\xE1 cadastrado. Nossa equipe entrar\xE1 em contato."; \`invalid_address\` \u2192 ask to pick the address again; anything else \u2192 a retry message. Disable the submit while pending and show a success state after it resolves. Never POST the leads webhook by hand.`;
3255
+ return `Property registration (\`/anunciar-imovel\`, client component): import ${names}, isValidPhone, toE164 from \`${STUDIO_SDK_PACKAGE}\`. Address: load Maps JS only through \`<script src="https://maps.fndn.ai/sdk.js?callback=initPlaces" async defer />\` (Places is included; never a Google key, never \`maps.googleapis.com\`), then \`google.maps.places.Autocomplete\` with \`componentRestrictions: { country: "br" }\` and pt-BR. Picking a suggestion fills fullAddress, street, number, neighborhood, city, state (the 2-letter code), postalCode, country, latitude and longitude from the place and replaces every one of those values. Show CEP, Rua, N\xFAmero, Bairro, Cidade, Estado and Pa\xEDs as editable inputs bound to postalCode, street, number, neighborhood, city, state and country; the visitor can edit every value submitSellerLead sends. Latitude and longitude come from \`place.geometry.location.lat()\` and \`.lng()\`, are stored on the address and sent, and they are not inputs. A typed address without a suggestion is not enough. The visitor confirms number or "Sem n\xFAmero", bloco/torre or "N\xE3o tem", unidade or "N\xE3o tem" (noNumber, noBlocoTorre, noUnidade). Block the next group while \`sellerAddressErrors(address)\` has keys and show each message on its field. Owner: name, email and phone are all required \u2014 \`isValidName\`, \`isValidEmail\`, the phone mask with \`isValidPhone(toE164(phone))\`. Photos: \`await uploadSellerLeadPhoto({ siteId, baseUrl: GARAGEM_API_BASE, file, publishableKey })\` per file (JPG/PNG/WEBP, 10MB, up to 30), keep the returned URLs. Photo session: \`const schedule = sellerPhotoSchedule(config)\` and \`slotsForDate(schedule, day)\` for the hours. Submit once with \`await submitSellerLead({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey, owner: { name, email, phone }, address, property: { businessType, saleValue, rentValue, condoFee, totalArea, bedrooms, bathrooms, suites, parkingSpaces }, photos, photoSession: { date, time }, photoSchedule: schedule })\` (omit what the visitor did not fill). Errors are \`LeadSubmitError\`: \`duplicate_property\` \u2192 "Este im\xF3vel j\xE1 est\xE1 cadastrado. Nossa equipe entrar\xE1 em contato."; \`invalid_address\` \u2192 ask to pick the address again; anything else \u2192 a retry message. Disable the submit while pending and show a success state after it resolves. Never POST the leads webhook by hand.`;
3247
3256
  }
3248
3257
  function isPhotoSearchOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3249
3258
  return compareSemver(pin, STUDIO_SDK_CONTRACT.photoSearchSince) >= 0;
@@ -3383,7 +3392,7 @@ function studioAmenityInstruction() {
3383
3392
  function studioSearchInstruction() {
3384
3393
  const reactNames = STUDIO_SDK_CONTRACT.reactExports.join(", ");
3385
3394
  const libNames = STUDIO_SDK_CONTRACT.searchExports.join(", ");
3386
- 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)}`;
3395
+ 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+"\`. Count-button text is \`countOptionLabel(option)\`; never map id \`"0"\` to "Studio" (only bedrooms gets that label, from the schema). 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)}`;
3387
3396
  }
3388
3397
  function mapsExportsPublished(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3389
3398
  return compareSemver(pin, STUDIO_SDK_CONTRACT.mapsSince) >= 0;
@@ -3395,7 +3404,9 @@ function studioMapsInstruction(options = {}) {
3395
3404
  }
3396
3405
  function studioMapSearchInstruction(options = {}) {
3397
3406
  if (!mapsExportsPublished(options.pin)) return "";
3398
- 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.`;
3407
+ const pin = options.pin ?? STUDIO_SDK_CONTRACT.minNpmVersion;
3408
+ const buckets = compareSemver(pin, STUDIO_SDK_CONTRACT.mapBucketsSince) >= 0 ? " When the matches do not fit on one page, the hook builds `map.clusters` from location buckets whose counts add up to `map.total`; render them as they come and never fetch or merge more pages. A cluster with empty `pinIds` is a bucket: draw it as a cluster, and on click center the map on `cluster.lat`/`cluster.lng` and zoom in two levels \u2014 the next viewport search returns finer buckets or the listings themselves." : "";
3409
+ 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. The card content is \`toListingCardModel(map.listings.find((listing) => listing.id === pin.id))\` and shows, in order: a large cover (\`coverSrc\`, aspect 4/3, full card width), title, \`priceLabel\`, \`locationLabel\`, then the facts that are present: \`bedrooms\` quartos, \`bathrooms\` banheiros, \`parkingSpaces\` vagas, \`areaM2\` m\xB2. Title and price alone are incomplete. On a wide screen the card opens next to its pin, never at the bottom of the map, where it falls below the viewport when the page is scrolled. Use one \`google.maps.InfoWindow\` and open it on the clicked marker: \`infoWindow.open({ map: googleMap, anchor: marker })\`. Its content is a div that React fills with \`createPortal\`. The InfoWindow pans the map so the card is in view. On a narrow screen the same card sits in a bottom sheet across the map width. Dismissing it leaves the pins. While \`map.loading\` the map is \`aria-busy\` with a visible progress indicator and the previous pins stay mounted. 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. Lista and Mapa are icon buttons with the site tooltip and \`aria-label\` \u201CLista\u201D / \u201CMapa\u201D, not icon-plus-text. 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. That row fits the viewport and never widens the page; sort may truncate. 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.${buckets}`;
3399
3410
  }
3400
3411
  function marketExportsAvailableAt(pin) {
3401
3412
  return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
@@ -3409,7 +3420,7 @@ function studioMarketInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3409
3420
  return `Market data: import ${names} from \`${STUDIO_SDK_PACKAGE}\`. **IPTU module required.** Every helper returns \`{ available: false, reason }\` (HTTP 200, never a throw) unless the site's organization has the IPTU module (\`iptu_itbi_integration\`) and the city is covered \u2014 most sites get \`available: false\`. ALWAYS render these blocks conditionally: \`if (!result.available) return null\` (omit the whole section, heading included); never a placeholder, never \u201Cdados indispon\xEDveis\u201D, never a local fallback number. The payloads carry only aggregates and a trimmed estimate \u2014 never render, request, or invent cadastral ids, IPTU lookups, ITBI transactions, comparables, or addresses from market data. Reasons are codes (\`module_not_enabled\`, \`city_unsupported\`, \`no_data\`, \`rate_limited\`, \u2026) \u2014 do not print them. Three blocks (all optional, design is free):
3410
3421
  - Neighborhood summary (listing detail, optionally search heading): \`const summary = await ${summary}({ siteId, baseUrl: GARAGEM_API_BASE, query: { city: listing.location.city, neighborhood: listing.location.neighborhood } })\`. Render \`summary.pricePerSqmFormatted.p25\` / \`.p50\` / \`.p75\` (strings, already \`R$ X/m\xB2\`) and \`summary.sampleSize\` (\u201Ccom base em N vendas\u201D); omit the sample line when null.
3411
3422
  - Listing market position (listing detail, near the price): \`const position = await ${position}({ siteId, baseUrl: GARAGEM_API_BASE, listingId: listing.id })\`. Copy comes from the helpers only: \`${positionLabel}(position)\` (\u201C8% abaixo da mediana do bairro\u201D) and \`${bandLabel}(position)\` (\u201CNa faixa do bairro, abaixo da mediana\u201D); both return \`null\` when unavailable \u2014 hide the line on \`null\`. Show \`position.listingPricePerSqmFormatted\` vs \`position.medianPricePerSqmFormatted\` if a comparison row is wanted. Do not compute the percent in the app.
3412
- - Visitor price estimate (\`/anunciar\` or a dedicated page, client component): a form with city, bairro, \xE1rea (m\xB2), quartos, vagas, tipo; on submit \`const estimate = await ${estimate}({ siteId, baseUrl: GARAGEM_API_BASE, input: { city, neighborhood, areaSqm, bedrooms, parkingSpots, propertyType } })\`. Render \`estimate.estimatedPriceFormatted\` with the range \`estimate.rangeLowFormatted\` \u2013 \`estimate.rangeHighFormatted\` and \`estimate.confidenceLabel\` mapped to pt-BR (alta / m\xE9dia / baixa). When \`available\` is false show \`estimate.message\` (pt-BR, already written) and the contact CTA. It is rate limited per visitor \u2014 disable the submit while pending. Never call it on page load.
3423
+ - Visitor price estimate (its own page, never \`/anunciar\` or \`/anunciar-imovel\`, client component): an address suggestion fills editable fields for city, bairro, \xE1rea (m\xB2), quartos, banheiros, vagas, tipo; latitude and longitude come from the suggestion and are not inputs. On submit \`const input = { city, neighborhood, areaSqm, bedrooms, bathrooms, parkingSpots, propertyType, latitude, longitude }; const estimate = await ${estimate}({ siteId, baseUrl: GARAGEM_API_BASE, input })\`. Render \`estimate.estimatedPriceFormatted\` with the range \`estimate.rangeLowFormatted\` \u2013 \`estimate.rangeHighFormatted\` and \`estimate.confidenceLabel\` mapped to pt-BR (alta / m\xE9dia / baixa). When \`available\` is false show \`estimate.message\` (pt-BR, already written) and the contact CTA. It is rate limited per visitor \u2014 disable the submit while pending. Never call it on page load.
3413
3424
  Fetch on the server page (\`next: { revalidate: 900 }\`) for the summary and position; the estimate is a user action. Resolve \`siteId\` the same way as every other SDK call.`;
3414
3425
  }
3415
3426
  function studioPhotoSearchInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
@@ -4167,21 +4178,24 @@ function mapSearchPins(listings) {
4167
4178
  }
4168
4179
  return pins;
4169
4180
  }
4170
- function listingsResult(listings, meta, requestedPageSize) {
4181
+ function listingsResult(result, requestedPageSize) {
4182
+ const listings = result.listings ?? [];
4171
4183
  return {
4172
4184
  pins: mapSearchPins(listings),
4173
4185
  cards: listings.map((listing) => toListingCardModel(listing)),
4174
4186
  listings,
4175
- page: meta.page ?? 1,
4176
- pageSize: meta.limit ?? requestedPageSize,
4177
- total: meta.total ?? listings.length,
4178
- totalPages: meta.totalPages ?? 0
4187
+ page: result.page ?? 1,
4188
+ pageSize: result.limit ?? requestedPageSize,
4189
+ total: result.total ?? listings.length,
4190
+ totalPages: result.totalPages ?? 0,
4191
+ buckets: result.buckets ?? []
4179
4192
  };
4180
4193
  }
4181
4194
  function searchParams(area, options) {
4182
4195
  const params = {
4183
4196
  page: capMapPage(options.page),
4184
- limit: capMapPageSize(options.pageSize)
4197
+ limit: capMapPageSize(options.pageSize),
4198
+ buckets: true
4185
4199
  };
4186
4200
  if (options.q !== void 0) params.q = options.q;
4187
4201
  if (options.sort !== void 0) params.sort = options.sort;
@@ -4202,7 +4216,7 @@ async function runMapSearch(siteId, area, options) {
4202
4216
  publishableKey: options.publishableKey,
4203
4217
  next: options.next
4204
4218
  });
4205
- return listingsResult(result.listings ?? [], result, pageSize);
4219
+ return listingsResult(result, pageSize);
4206
4220
  }
4207
4221
  async function searchListingsInBounds(siteId, options) {
4208
4222
  if (!isMapBounds(options.bounds)) {
@@ -4227,63 +4241,63 @@ function clampZoom(zoom) {
4227
4241
  function mapClusterCellDegrees(zoom) {
4228
4242
  return 360 / 2 ** clampZoom(zoom) / 4;
4229
4243
  }
4230
- function usablePin(pin) {
4231
- return finitePair(pin.lat, pin.lng) !== null && !(pin.lat === 0 && pin.lng === 0);
4244
+ function usablePoint(point) {
4245
+ return finitePair(point.lat, point.lng) !== null && !(point.lat === 0 && point.lng === 0);
4232
4246
  }
4233
4247
  function groupPrecision(group) {
4234
4248
  let max = 0;
4235
- for (const pin of group) {
4249
+ for (const point of group) {
4236
4250
  max = Math.max(
4237
4251
  max,
4238
- coordinateDecimals(pin.lat),
4239
- coordinateDecimals(pin.lng)
4252
+ coordinateDecimals(point.lat),
4253
+ coordinateDecimals(point.lng)
4240
4254
  );
4241
4255
  }
4242
4256
  return max;
4243
4257
  }
4244
- function multiCluster(key, group) {
4245
- const lat = group.reduce((sum, pin) => sum + pin.lat, 0) / group.length;
4246
- const lng = group.reduce((sum, pin) => sum + pin.lng, 0) / group.length;
4247
- const center = coarsenCoordinates({ lat, lng }, groupPrecision(group));
4248
- return {
4249
- id: key,
4250
- lat: center.lat,
4251
- lng: center.lng,
4252
- count: group.length,
4253
- pinIds: group.map((pin) => pin.id),
4254
- pin: null
4255
- };
4256
- }
4257
- function singleCluster(pin) {
4258
- return {
4259
- id: pin.id,
4260
- lat: pin.lat,
4261
- lng: pin.lng,
4262
- count: 1,
4263
- pinIds: [pin.id],
4264
- pin
4265
- };
4266
- }
4267
- function clusterPins(pins, zoom) {
4268
- if (pins.length === 0) return [];
4258
+ function gridCells(points, zoom, weight) {
4269
4259
  const cell = mapClusterCellDegrees(zoom);
4270
4260
  const groups = /* @__PURE__ */ new Map();
4271
- for (const pin of pins) {
4272
- if (!usablePin(pin)) continue;
4273
- const key = `${Math.floor(pin.lat / cell)}:${Math.floor(pin.lng / cell)}`;
4261
+ for (const point of points) {
4262
+ if (!usablePoint(point)) continue;
4263
+ const key = `${Math.floor(point.lat / cell)}:${Math.floor(point.lng / cell)}`;
4274
4264
  const list = groups.get(key);
4275
- if (list) list.push(pin);
4276
- else groups.set(key, [pin]);
4277
- }
4278
- const clusters = [];
4279
- for (const [key, group] of groups) {
4280
- const only = group[0];
4281
- clusters.push(
4282
- group.length === 1 && only ? singleCluster(only) : multiCluster(key, group)
4283
- );
4265
+ if (list) list.push(point);
4266
+ else groups.set(key, [point]);
4284
4267
  }
4285
- clusters.sort((a, b) => a.id.localeCompare(b.id));
4286
- return clusters;
4268
+ return [...groups].map(([key, members]) => {
4269
+ const count = members.reduce((sum, point) => sum + weight(point), 0);
4270
+ const only = members.length === 1 ? members[0] : void 0;
4271
+ const center = only ?? coarsenCoordinates(
4272
+ {
4273
+ lat: members.reduce((sum, p) => sum + p.lat * weight(p), 0) / count,
4274
+ lng: members.reduce((sum, p) => sum + p.lng * weight(p), 0) / count
4275
+ },
4276
+ groupPrecision(members)
4277
+ );
4278
+ return {
4279
+ id: only?.id ?? key,
4280
+ lat: center.lat,
4281
+ lng: center.lng,
4282
+ count,
4283
+ pinIds: [],
4284
+ pin: null,
4285
+ members
4286
+ };
4287
+ }).sort((a, b) => a.id.localeCompare(b.id));
4288
+ }
4289
+ function clusterPins(pins, zoom) {
4290
+ return gridCells(pins, zoom, () => 1).map(({ members, ...cluster }) => ({
4291
+ ...cluster,
4292
+ pinIds: members.map((pin) => pin.id),
4293
+ pin: members.length === 1 ? members[0] ?? null : null
4294
+ }));
4295
+ }
4296
+ function clusterBuckets(buckets, zoom) {
4297
+ const weighted = buckets.filter((bucket) => bucket.count > 0);
4298
+ return gridCells(weighted, zoom, (bucket) => bucket.count).map(
4299
+ ({ members: _members, ...cluster }) => cluster
4300
+ );
4287
4301
  }
4288
4302
 
4289
4303
  // src/fetchers-photos.ts
@@ -4847,6 +4861,7 @@ export {
4847
4861
  capMapPageSize,
4848
4862
  clearStagedPathFilters,
4849
4863
  clearTravelTimeCache,
4864
+ clusterBuckets,
4850
4865
  clusterPins,
4851
4866
  coarsenCoordinates,
4852
4867
  coerceNpmVersion,