@garagem-ai/site-sdk 0.5.1 → 0.5.3

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react/index.ts","../src/react/listing-card.tsx","../src/presentation.ts","../src/listing-path.ts","../src/listing-card-model.ts","../src/react/cn.ts","../src/react/styles/search-chrome-styles.tsx","../src/react/styles/search-chrome-css.generated.ts","../src/amenity-labels.ts","../../search-url/types.ts","../../search-url/slugify.ts","../../search-url/catalog.ts","../../search-url/path.ts","../../search-url/applied-query.ts","../src/applied-query.ts","../src/loc-params.ts","../src/path.ts","../src/search-engine.ts","../src/listing-detail.ts","../src/listing-detail-fields.ts","../src/react/listing-detail-fields.tsx","../src/react/search-chrome.tsx","../src/react/use-public-search.ts","../src/internal/url.ts","../src/fetchers.ts"],"sourcesContent":["\"use client\";\n\nexport { ListingCard } from \"./listing-card\";\nexport { ListingDetailFields } from \"./listing-detail-fields\";\nexport type {\n ListingDetailFieldsClassNames,\n ListingDetailFieldsProps,\n} from \"./listing-detail-fields\";\nexport { SearchChromeStyles } from \"./styles\";\nexport { ResultsSkeleton } from \"./search-chrome\";\nexport { usePublicSearch } from \"./use-public-search\";\nexport type {\n ListingCardClassNames,\n ListingCardProps,\n ListingCardSlots,\n PublicSearchState,\n SiteIdInput,\n UsePublicSearchOptions,\n} from \"./types\";\n","\"use client\";\n\nimport type { ReactElement } from \"react\";\nimport Link from \"next/link\";\n\nimport { formatAreaM2 } from \"../presentation\";\nimport { toListingCardModel } from \"../listing-card-model\";\nimport type { Listing } from \"../types\";\nimport { cn } from \"./cn\";\nimport { SearchChromeStyles } from \"./styles\";\nimport type { ListingCardProps } from \"./types\";\n\nfunction isListing(value: ListingCardProps[\"listing\"]): value is Listing {\n return (\n \"priceVisibility\" in value && \"businessType\" in value && \"title\" in value\n );\n}\n\nexport function ListingCard({\n listing,\n href,\n className,\n classNames,\n slots,\n style,\n}: ListingCardProps): ReactElement {\n const model = isListing(listing) ? toListingCardModel(listing) : listing;\n const target = href ?? model.href;\n const areaLabel = formatAreaM2(model.areaM2);\n return (\n <>\n <SearchChromeStyles />\n <article\n data-slot=\"listing-card\"\n className={cn(className, classNames?.root)}\n style={style}\n >\n <Link href={target} data-slot=\"listing-card-link\">\n <div data-slot=\"listing-card-media\" className={classNames?.media}>\n {slots?.media ??\n (model.coverSrc ? (\n <img src={model.coverSrc} alt={model.coverAlt} />\n ) : (\n <div data-slot=\"listing-card-empty\">Sem foto</div>\n ))}\n {slots?.badge ?? (\n <span\n data-slot=\"listing-card-badge\"\n className={classNames?.badge}\n >\n {model.businessLabel}\n </span>\n )}\n </div>\n <div data-slot=\"listing-card-body\" className={classNames?.body}>\n <div data-slot=\"listing-card-price-row\">\n <p data-slot=\"listing-card-price\" className={classNames?.price}>\n {model.priceLabel}\n </p>\n {model.pricePeriod ? (\n <span data-slot=\"listing-card-period\">{model.pricePeriod}</span>\n ) : null}\n </div>\n <h3 data-slot=\"listing-card-title\" className={classNames?.title}>\n {model.title}\n </h3>\n <p\n data-slot=\"listing-card-location\"\n className={classNames?.location}\n >\n {model.locationLabel || model.propertyType || \"\"}\n </p>\n <ul\n data-slot=\"listing-card-features\"\n className={classNames?.features}\n >\n {model.bedrooms != null ? (\n <li>{model.bedrooms} quartos</li>\n ) : null}\n {model.bathrooms != null ? (\n <li>{model.bathrooms} banheiros</li>\n ) : null}\n {model.parkingSpaces != null ? (\n <li>{model.parkingSpaces} vagas</li>\n ) : null}\n {areaLabel ? <li>{areaLabel}</li> : null}\n </ul>\n {slots?.cta ? (\n <div data-slot=\"listing-card-cta\" className={classNames?.cta}>\n {slots.cta}\n </div>\n ) : null}\n </div>\n </Link>\n </article>\n </>\n );\n}\n","/**\n * Presentation helpers with no UI framework.\n * React / React Native / Flutter adapters consume these formatters and\n * CSS custom-property names; they must not live inside JSX.\n */\n\nexport const SEARCH_CSS_VARS = {\n cardRadius: \"--garagem-listing-card-radius\",\n cardGap: \"--garagem-listing-card-gap\",\n priceSize: \"--garagem-listing-price-size\",\n mediaRatio: \"--garagem-listing-media-ratio\",\n controlHeight: \"--garagem-search-control-height\",\n iconSize: \"--garagem-search-icon-size\",\n skeleton: \"--garagem-skeleton\",\n} as const;\n\n/** Paste into generated `globals.css` to override tokens. Layout lives in the chrome artifact. */\nexport const SEARCH_CSS_RECIPE = `:root {\n ${SEARCH_CSS_VARS.cardRadius}: 0.75rem;\n ${SEARCH_CSS_VARS.cardGap}: 1.5rem;\n ${SEARCH_CSS_VARS.priceSize}: 1.125rem;\n ${SEARCH_CSS_VARS.mediaRatio}: 4 / 3;\n ${SEARCH_CSS_VARS.controlHeight}: 2.75rem;\n ${SEARCH_CSS_VARS.iconSize}: 1.25rem;\n ${SEARCH_CSS_VARS.skeleton}: var(--muted, #e7e5e4);\n}\n`;\n\nexport function formatListingPrice(\n amount: number | null | undefined,\n locale = \"pt-BR\",\n currency = \"BRL\"\n): string {\n if (amount == null) return \"Sob consulta\";\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }).format(amount);\n } catch {\n return `${currency} ${amount}`;\n }\n}\n\n/** Input mask: `499000` → `\"499.000\"` (no currency symbol). */\nexport function formatGroupedInteger(\n value: string | number | null | undefined,\n locale = \"pt-BR\"\n): string {\n const digits = String(value ?? \"\").replace(/\\D/g, \"\");\n if (!digits) return \"\";\n const amount = Number.parseInt(digits, 10);\n if (!Number.isFinite(amount)) return \"\";\n return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(\n amount\n );\n}\n\n/** Inverse of `formatGroupedInteger`: `\"499.000\"` / `\"499000\"` → `499000`. */\nexport function parseGroupedInteger(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? Math.trunc(value) : undefined;\n }\n const digits = String(value ?? \"\").replace(/\\D/g, \"\");\n if (!digits) return undefined;\n const amount = Number.parseInt(digits, 10);\n return Number.isFinite(amount) ? amount : undefined;\n}\n\nexport function formatAreaM2(area: number | null | undefined): string | null {\n if (area == null || !Number.isFinite(area)) return null;\n return `${area} m²`;\n}\n\nexport function listingBusinessLabel(businessType: string | undefined): string {\n return businessType === \"rental\" ? \"Aluguel\" : \"Venda\";\n}\n","/** Public listing URLs. Prefer `listing.path` from the API; fallback is `/imoveis/id-{listingCode}`. */\n\nexport function listingLookupKey(raw: string): string {\n return raw.trim().replace(/^id-/, \"\").trim();\n}\n\nexport function listingPublicPath(listing: {\n path?: string | null;\n listingCode?: string | null;\n id?: string | null;\n}): string {\n const composed = listing.path?.trim() ?? \"\";\n if (composed.startsWith(\"/\") && !composed.startsWith(\"//\")) return composed;\n const identity = listing.listingCode?.trim() || listing.id?.trim() || \"\";\n if (!identity || identity === \"undefined\" || identity === \"null\") {\n throw new TypeError(\"listingPublicPath: listing has no listingCode or id\");\n }\n return `/imoveis/id-${identity}`;\n}\n","import { listingPublicPath } from \"./listing-path\";\nimport { formatListingPrice, listingBusinessLabel } from \"./presentation\";\nimport type {\n Listing,\n ListingBusinessType,\n ListingPriceVisibility,\n} from \"./types\";\n\n/** Fields every listing card must have — no JSX. */\nexport type ListingCardModel = {\n href: string;\n title: string;\n businessType: ListingBusinessType;\n businessLabel: string;\n priceVisibility: ListingPriceVisibility;\n price: number | null;\n priceLabel: string;\n pricePeriod: string | null;\n locationLabel: string;\n propertyType: string | null;\n coverSrc: string | null;\n coverAlt: string;\n bedrooms: number | null;\n bathrooms: number | null;\n parkingSpaces: number | null;\n areaM2: number | null;\n};\n\nexport function listingLocationLabel(location: {\n neighborhood?: string | null;\n city?: string | null;\n state?: string | null;\n}): string {\n return [location.neighborhood, location.city, location.state]\n .map((part) => (part ? String(part).trim() : \"\"))\n .filter(Boolean)\n .join(\", \");\n}\n\nexport function toListingCardModel(\n listing: Pick<\n Listing,\n | \"id\"\n | \"listingCode\"\n | \"path\"\n | \"title\"\n | \"businessType\"\n | \"price\"\n | \"priceVisibility\"\n | \"coverImage\"\n > & {\n property?: {\n type?: string | null;\n bedrooms?: number | null;\n bathrooms?: number | null;\n parkingSpaces?: number | null;\n usableArea?: number | null;\n totalArea?: number | null;\n };\n location?: {\n neighborhood?: string | null;\n city?: string | null;\n state?: string | null;\n };\n }\n): ListingCardModel {\n const isPrivate = listing.priceVisibility === \"private\";\n const area = listing.property?.usableArea ?? listing.property?.totalArea;\n return {\n href: listingPublicPath(listing),\n title: listing.title,\n businessType: listing.businessType,\n businessLabel: listingBusinessLabel(listing.businessType),\n priceVisibility: listing.priceVisibility,\n price: listing.price,\n priceLabel: isPrivate ? \"Sob consulta\" : formatListingPrice(listing.price),\n pricePeriod:\n listing.businessType === \"rental\" && !isPrivate && listing.price != null\n ? \"/mês\"\n : null,\n locationLabel: listingLocationLabel(listing.location || {}),\n propertyType: listing.property?.type ?? null,\n coverSrc: listing.coverImage?.src ?? null,\n coverAlt: listing.coverImage?.alt ?? listing.title,\n bedrooms: listing.property?.bedrooms ?? null,\n bathrooms: listing.property?.bathrooms ?? null,\n parkingSpaces: listing.property?.parkingSpaces ?? null,\n areaM2: area ?? null,\n };\n}\n","export function cn(...parts: Array<string | false | null | undefined>): string {\n return parts.filter(Boolean).join(\" \");\n}\n","\"use client\";\n\nimport { useLayoutEffect, type ReactElement } from \"react\";\n\nimport {\n SEARCH_CHROME_CSS,\n SEARCH_CHROME_CSS_VERSION,\n} from \"./search-chrome-css.generated\";\n\nconst STYLE_ID = `garagem-search-chrome-${SEARCH_CHROME_CSS_VERSION}`;\n\n/** Append once to document.head — never a React child (unmount must not remove it). */\nfunction injectSearchChromeOnce(): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(STYLE_ID)) return;\n const el = document.createElement(\"style\");\n el.id = STYLE_ID;\n el.textContent = SEARCH_CHROME_CSS;\n document.head.appendChild(el);\n}\n\nexport function SearchChromeStyles(): ReactElement | null {\n // Client render: inject before paint (Studio / v0 are client-heavy grids).\n if (typeof document !== \"undefined\") {\n injectSearchChromeOnce();\n }\n useLayoutEffect(() => {\n injectSearchChromeOnce();\n }, []);\n return null;\n}\n","/* Generated by scripts/build-search-chrome-css.mjs — do not edit. */\n/* eslint-disable */\n/* prettier-ignore */\nexport const SEARCH_CHROME_CSS_VERSION = \"0.5.1\";\nexport const SEARCH_CHROME_CSS = \":root{--garagem-listing-card-radius:0.75rem;--garagem-listing-card-gap:1.5rem;--garagem-listing-price-size:1.125rem;--garagem-listing-media-ratio:4 / 3;--garagem-skeleton:var(--muted,#e7e5e4)}[data-slot=\\\"search-grid\\\"],[data-slot=\\\"search-skeleton\\\"]{display:grid;grid-template-columns:1fr;gap:var(--garagem-listing-card-gap)}@media (min-width:640px){[data-slot=\\\"search-grid\\\"],[data-slot=\\\"search-skeleton\\\"]{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){[data-slot=\\\"search-grid\\\"],[data-slot=\\\"search-skeleton\\\"]{grid-template-columns:repeat(3,minmax(0,1fr))}}[data-slot=\\\"listing-card\\\"]{overflow:hidden;border-radius:var(--garagem-listing-card-radius);border:1px solid var(--border,#e4e4e7);background:var(--card,var(--background,#fff))}[data-slot=\\\"listing-card-price-row\\\"]{display:inline-flex;align-items:baseline;gap:0.25rem}[data-slot=\\\"listing-card-price\\\"]{font-size:var(--garagem-listing-price-size);font-weight:600}[data-slot=\\\"listing-card-period\\\"]{font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot=\\\"listing-card-link\\\"]{display:block;color:inherit;text-decoration:none;cursor:pointer}[data-slot=\\\"listing-card-media\\\"]{position:relative;width:100%;overflow:hidden;background:var(--muted,#f5f5f4);aspect-ratio:var(--garagem-listing-media-ratio)}[data-slot=\\\"listing-card-media\\\"] img{height:100%;width:100%;object-fit:cover;transition:transform 0.3s}[data-slot=\\\"listing-card\\\"]:hover [data-slot=\\\"listing-card-media\\\"] img{transform:scale(1.05)}@media (prefers-reduced-motion:reduce){[data-slot=\\\"listing-card-media\\\"] img{transition:none}[data-slot=\\\"listing-card\\\"]:hover [data-slot=\\\"listing-card-media\\\"] img{transform:none}}[data-slot=\\\"listing-card-empty\\\"]{display:flex;height:100%;width:100%;align-items:center;justify-content:center;font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot=\\\"listing-card-cta\\\"]{margin-top:0.75rem}[data-slot=\\\"listing-card-badge\\\"]{position:absolute;left:0.75rem;top:0.75rem;border-radius:999px;background:color-mix(in srgb,var(--background,#fff) 90%,transparent);padding:0.25rem 0.5rem;font-size:0.75rem;font-weight:500}[data-slot=\\\"listing-card-body\\\"]{padding:1rem}[data-slot=\\\"listing-card-title\\\"]{display:-webkit-box;margin-top:0.25rem;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1;font-size:0.875rem;font-weight:500}[data-slot=\\\"listing-card-location\\\"]{margin-top:0.125rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot=\\\"listing-card-features\\\"]{display:flex;flex-wrap:wrap;margin-top:0.75rem;gap:0.25rem 1rem;padding:0;list-style:none;font-size:0.75rem;color:var(--muted-foreground,#737373)}[data-slot=\\\"search-skeleton-block\\\"]{animation:garagem-search-pulse 1.2s ease-in-out infinite;background:var(--garagem-skeleton);border-radius:0.375rem}[data-slot=\\\"search-skeleton-card\\\"]{overflow:hidden;border-radius:var(--garagem-listing-card-radius);border:1px solid var(--border,#e4e4e7)}[data-slot=\\\"search-skeleton-body\\\"]{display:flex;flex-direction:column;gap:0.5rem;padding:1rem}[data-slot=\\\"search-skeleton-block\\\"][data-kind=\\\"media\\\"]{aspect-ratio:var(--garagem-listing-media-ratio)}[data-slot=\\\"search-skeleton-block\\\"][data-kind=\\\"line-lg\\\"]{height:1.25rem;width:50%}[data-slot=\\\"search-skeleton-block\\\"][data-kind=\\\"line-md\\\"]{height:1rem;width:75%}[data-slot=\\\"search-skeleton-block\\\"][data-kind=\\\"line-sm\\\"]{height:0.75rem;width:66.666667%}[data-slot=\\\"search-skeleton-block\\\"][data-kind=\\\"detail-media\\\"]{max-width:45rem;aspect-ratio:4 / 3}[data-slot=\\\"search-skeleton-block\\\"][data-kind=\\\"detail-title\\\"]{width:66.666667%;height:2rem;margin-top:1.5rem}@media (prefers-reduced-motion:reduce){[data-slot=\\\"search-skeleton-block\\\"]{animation:none}}@keyframes garagem-search-pulse{50%{opacity:0.55}}\";\n","/**\n * Portuguese labels for listing amenity ids. Tenant search-ui dictionary\n * wins; this map is the default-catalog fallback so generated Studio pages\n * never print camelCase keys.\n */\n\nexport const LISTING_AMENITY_TITLES = {\n unit: \"Comodidades\",\n building: \"Comodidades do condomínio\",\n} as const;\n\nexport type AmenityLabelOption = {\n id: string;\n label: string;\n};\n\nexport type AmenityLabelDictionary = {\n propertyFeatures?: AmenityLabelOption[];\n buildingAmenities?: AmenityLabelOption[];\n};\n\nexport type ListingAmenityGroupKey = keyof typeof LISTING_AMENITY_TITLES;\n\nexport type ListingAmenityGroup = {\n key: ListingAmenityGroupKey;\n title: string;\n labels: string[];\n};\n\nexport type ListingAmenitySource = {\n amenities?: string[] | null;\n propertyFeatures?: string[] | null;\n /** Condo amenity ids, even when `building` is null (no buildingId). */\n buildingAmenities?: string[] | null;\n building?: { amenities?: string[] | null } | null;\n};\n\n/**\n * Default tenant ids + canonical `has*` / `is*` keys seen on public listings.\n * Aligned with DEFAULT_PROPERTY_FEATURES and DEFAULT_BUILDING_FEATURES from\n * Foundation's field-definitions.ts so generated Studio pages never need a\n * dictionary for standard amenities.\n */\nexport const AMENITY_FALLBACK_LABELS: Record<string, string> = {\n // ==================== PROPERTY FEATURES ====================\n // Amenities\n arCondicionado: \"Ar condicionado\",\n banheira: \"Banheira\",\n carregadorEletrico: \"Carregador elétrico\",\n churrasqueira: \"Churrasqueira\",\n chuveiroGas: \"Chuveiro a gás\",\n chuveiroEletrico: \"Chuveiro elétrico\",\n energiaSolar: \"Energia solar\",\n fechaduraDigital: \"Fechadura digital\",\n fechaduraEletronica: \"Fechadura eletrônica\",\n geradorEletrico: \"Gerador elétrico\",\n gesso: \"Gesso\",\n hidromassagem: \"Hidromassagem\",\n lareira: \"Lareira\",\n ofuro: \"Ofurô\",\n spa: \"Spa\",\n painelSolar: \"Painel solar\",\n portaoEletronico: \"Portão eletrônico\",\n sistemaAlarme: \"Sistema de alarme\",\n homeTheater: \"Home theater\",\n adega: \"Adega\",\n split: \"Split\",\n arCentral: \"Ar central\",\n esperaSplit: \"Espera para split\",\n vistaMar: \"Vista para o mar\",\n vistaPanoramica: \"Vista panorâmica\",\n aguaQuente: \"Água quente\",\n reformado: \"Reformado\",\n tvCabo: \"TV a cabo\",\n gradeado: \"Gradeado\",\n antenaParabolica: \"Antena parabólica\",\n aquecimento: \"Aquecimento\",\n aquecimentoEletrico: \"Aquecimento elétrico\",\n aquecimentoCentral: \"Aquecimento central\",\n cercaEletrica: \"Cerca elétrica\",\n monitoramento: \"Monitoramento\",\n vigiaInterno: \"Vigia interno\",\n vigiaExterno: \"Vigia externo\",\n alarme: \"Alarme\",\n agua: \"Água\",\n redeEsgoto: \"Rede de esgoto\",\n pavimentacao: \"Pavimentação\",\n energiaEletrica: \"Energia elétrica\",\n // Furniture\n mobiliado: \"Mobiliado\",\n armarioEmbutido: \"Armário embutido\",\n armarioEmbutidoQuarto: \"Armário embutido quarto\",\n armarioCozinha: \"Armário cozinha\",\n armarioBanheiro: \"Armário banheiro\",\n cozinhaPlanejada: \"Cozinha planejada\",\n fogao: \"Fogão\",\n fornoPizza: \"Forno de pizza\",\n freezer: \"Freezer\",\n dormitorioComArmario: \"Dormitório com armário\",\n semiMobiliado: \"Semi mobiliado\",\n salaArmarios: \"Sala com armários\",\n // Structure\n piscina: \"Piscina\",\n piscinaAquecida: \"Piscina aquecida\",\n piscinaCoberta: \"Piscina coberta\",\n poco: \"Poço\",\n pocoArtesiano: \"Poço artesiano\",\n bar: \"Bar\",\n jardim: \"Jardim\",\n lago: \"Lago\",\n lavabo: \"Lavabo\",\n quintal: \"Quintal\",\n solarium: \"Solarium\",\n quartoServico: \"Quarto de serviço\",\n varanda: \"Varanda\",\n varandaFechadaVidro: \"Varanda fechada com vidro\",\n varandaGourmet: \"Varanda gourmet\",\n banheiroServico: \"Banheiro de serviço\",\n areaServico: \"Área de serviço\",\n cinema: \"Cinema\",\n closet: \"Closet\",\n cozinhaAmericana: \"Cozinha americana\",\n cozinhaGourmet: \"Cozinha gourmet\",\n despensa: \"Despensa\",\n escritorio: \"Escritório\",\n edicula: \"Edícula\",\n horta: \"Horta\",\n sacada: \"Sacada\",\n salaJantar: \"Sala de jantar\",\n cozinha: \"Cozinha\",\n banheiroSocial: \"Banheiro social\",\n terraco: \"Terraço\",\n copa: \"Copa\",\n suiteMaster: \"Suíte master\",\n wcEmpregada: \"WC empregada\",\n dependenciaEmpregada: \"Dependência de empregada\",\n dependenciadeEmpregada: \"Dependência empregada\",\n salaTv: \"Sala de TV\",\n copaCozinha: \"Copa cozinha\",\n sacadaComChurrasqueira: \"Sacada com churrasqueira\",\n hallPrivativo: \"Hall privativo\",\n estarIntimo: \"Estar íntimo\",\n livingHall: \"Living hall\",\n piscinaInterna: \"Piscina interna\",\n deck: \"Deck\",\n jardimInverno: \"Jardim de inverno\",\n rouparia: \"Rouparia\",\n living: \"Living\",\n familyRoom: \"Family room\",\n salafitness: \"Sala fitness\",\n salaEstar: \"Sala de estar\",\n mezanino: \"Mezanino\",\n pisoElevado: \"Piso elevado\",\n entradaServicoIndependente: \"Entrada de serviço independente\",\n forro: \"Forro\",\n vitrine: \"Vitrine\",\n banheiroAuxiliar: \"Banheiro auxiliar\",\n gabinete: \"Gabinete\",\n quadraTenisPrivativa: \"Quadra de tênis privativa\",\n porao: \"Porão\",\n sotao: \"Sótão\",\n patio: \"Pátio\",\n canaletasNoRodape: \"Canaletas no rodapé\",\n // Accessibility\n barraApoioVaso: \"Barra de apoio vaso\",\n barraApoioChuveiro: \"Barra de apoio chuveiro\",\n entradaSemDegrau: \"Entrada sem degrau\",\n rampasAcesso: \"Rampas de acesso\",\n vagaDeficientes: \"Vaga para deficientes\",\n // Flooring\n cimentoQueimado: \"Cimento queimado\",\n madeira: \"Madeira\",\n pisoFrio: \"Piso frio\",\n laminado: \"Laminado\",\n vinilico: \"Vinílico\",\n porcelanato: \"Porcelanato\",\n\n // ==================== BUILDING FEATURES ====================\n // Amenities\n elevador: \"Elevador\",\n bicicletario: \"Bicicletário\",\n carregadorEletronico: \"Carregador eletrônico\",\n concierge: \"Concierge\",\n coworking: \"Coworking\",\n deposito: \"Depósito\",\n lavanderia: \"Lavanderia\",\n petPlace: \"Pet place\",\n recebimentoEncomendas: \"Recebimento de encomendas\",\n salaReuniao: \"Sala de reunião\",\n salaoFestas: \"Salão de festas\",\n valet: \"Valet\",\n garagemCoberta: \"Garagem coberta\",\n elevadorServico: \"Elevador de serviço\",\n // Leisure\n academia: \"Academia\",\n campoFutebol: \"Campo de futebol\",\n espacoGourmet: \"Espaço gourmet\",\n piscinaInfantil: \"Piscina infantil\",\n pistaCaminhada: \"Pista de caminhada\",\n playground: \"Playground\",\n quadraPoliesportiva: \"Quadra poliesportiva\",\n quadraTenis: \"Quadra de tênis\",\n salaJogos: \"Sala de jogos\",\n salaVapor: \"Sala de vapor\",\n sauna: \"Sauna\",\n // Security\n circuitoTv: \"Circuito fechado de TV\",\n controleAcessoEletronico: \"Controle de acesso eletrônico\",\n interfone: \"Interfone\",\n portaria24h: \"Portaria 24h\",\n porteiroFisico: \"Porteiro físico\",\n seguranca24h: \"Segurança 24h\",\n segurancaPatrimonial: \"Segurança patrimonial\",\n condominioFechado: \"Condomínio fechado\",\n // Accessibility\n banheiroAcessivel: \"Banheiro acessível\",\n elevadorAcessivel: \"Elevador acessível\",\n pisoTatil: \"Piso tátil\",\n\n // ==================== CANONICAL HAS*/IS* KEYS ====================\n has24hConcierge: \"Portaria 24h\",\n has24hSecurity: \"Segurança 24h\",\n hasAccessRamps: \"Rampas de acesso\",\n hasAccessibleBathroom: \"Banheiro acessível\",\n hasAccessibleElevator: \"Elevador acessível\",\n hasAirConditioning: \"Ar condicionado\",\n hasAlarmSystem: \"Sistema de alarme\",\n hasBalcony: \"Varanda\",\n hasBikeStorage: \"Bicicletário\",\n hasBuiltInWardrobe: \"Armário embutido\",\n hasCCTV: \"CFTV\",\n hasCloset: \"Closet\",\n hasConcierge: \"Portaria\",\n hasControlledAccess: \"Condomínio fechado\",\n hasCoworking: \"Coworking\",\n hasDisabledParking: \"Vaga para deficientes\",\n hasElectricCharger: \"Carregador eletrônico\",\n hasElectronicGate: \"Portão eletrônico\",\n hasElevator: \"Elevador\",\n hasFireplace: \"Lareira\",\n hasGarden: \"Jardim\",\n hasGasShower: \"Chuveiro a gás\",\n hasGenerator: \"Gerador\",\n hasGourmetBalcony: \"Varanda gourmet\",\n hasGourmetKitchen: \"Cozinha gourmet\",\n hasGrill: \"Churrasqueira\",\n hasGuestParking: \"Estacionamento para visitantes\",\n hasGym: \"Academia\",\n hasHeating: \"Aquecimento\",\n hasHomeOffice: \"Home office\",\n hasIntercom: \"Interfone\",\n hasJacuzzi: \"Hidromassagem\",\n hasKidsPool: \"Piscina infantil\",\n hasLaundry: \"Lavanderia\",\n hasMeetingRoom: \"Sala de reunião\",\n hasOffice: \"Escritório\",\n hasOpenKitchen: \"Cozinha americana\",\n hasPackageReceival: \"Recebimento de encomendas\",\n hasPantry: \"Despensa\",\n hasParkingGarage: \"Garagem coberta\",\n hasPartySaloon: \"Salão de festas\",\n hasPetArea: \"Pet place\",\n hasPipedGas: \"Gás encanado\",\n hasPlayground: \"Playground\",\n hasPowderRoom: \"Lavabo\",\n hasPrivatePool: \"Piscina privativa\",\n hasSauna: \"Sauna\",\n hasSecurity: \"Segurança\",\n hasServiceArea: \"Área de serviço\",\n hasSolarPanel: \"Painel solar\",\n hasSpa: \"Spa\",\n hasSportsCourt: \"Quadra de esportes\",\n hasStepFreeEntrance: \"Entrada sem degrau\",\n hasStorage: \"Depósito\",\n hasSwimmingPool: \"Piscina\",\n hasTennisCourt: \"Quadra de tênis\",\n hasValetParking: \"Valet\",\n homeOffice: \"Home office\",\n isPetFriendly: \"Pet friendly\",\n isFurnished: \"Mobiliado\",\n isPartiallyFurnished: \"Semi-mobiliado\",\n petFriendly: \"Pet friendly\",\n piscinaPrivativa: \"Piscina privativa\",\n pisoLaminado: \"Piso laminado\",\n pisoMadeira: \"Piso de madeira\",\n pisoPorcelanato: \"Piso porcelanato\",\n quadraEsportes: \"Quadra de esportes\",\n rooftop: \"Rooftop\",\n suite: \"Suíte\",\n triplex: \"Triplex\",\n duplex: \"Duplex\",\n cobertura: \"Cobertura\",\n forroGesso: \"Forro de gesso\",\n gerador: \"Gerador\",\n armariosCozinha: \"Armários na cozinha\",\n armariosQuarto: \"Armários nos quartos\",\n cftv: \"CFTV\",\n};\n\nfunction lookupLabel(\n id: string,\n options?: AmenityLabelOption[]\n): string | undefined {\n const fromDictionary = options?.find((option) => option.id === id)?.label;\n if (fromDictionary?.trim()) return fromDictionary.trim();\n return AMENITY_FALLBACK_LABELS[id];\n}\n\nexport function labelAmenities(\n ids: readonly string[] | null | undefined,\n dictionary?: AmenityLabelOption[]\n): string[] {\n if (!ids?.length) return [];\n const labels: string[] = [];\n const seen = new Set<string>();\n for (const id of ids) {\n if (!id) continue;\n const label = lookupLabel(id, dictionary);\n if (!label || seen.has(label)) continue;\n seen.add(label);\n labels.push(label);\n }\n return labels.sort((a, b) => a.localeCompare(b, \"pt-BR\"));\n}\n\nfunction presentIds(ids: readonly string[] | null | undefined): string[] {\n return (ids ?? []).filter((id): id is string => Boolean(id));\n}\n\n/**\n * Older payloads merge unit + condo ids into `amenities` as\n * `[...propertyFeatures, ...buildingAmenities]` (duplicates kept). Consume\n * unit occurrences first so shared catalog ids stay in the building group.\n */\nfunction buildingIdsFromMergedAmenities(\n listing: ListingAmenitySource,\n unitIds: readonly string[]\n): string[] {\n if (!listing.amenities || listing.propertyFeatures == null) return [];\n const unitCounts = new Map<string, number>();\n for (const id of unitIds) {\n unitCounts.set(id, (unitCounts.get(id) ?? 0) + 1);\n }\n return listing.amenities.filter((id) => {\n if (!id) return false;\n const count = unitCounts.get(id);\n if (count === undefined || count === 0) return true;\n unitCounts.set(id, count - 1);\n return false;\n });\n}\n\nexport function unitAmenityIds(listing: ListingAmenitySource): string[] {\n if (listing.propertyFeatures != null) {\n return presentIds(listing.propertyFeatures);\n }\n const building = new Set(\n listing.building?.amenities ?? listing.buildingAmenities ?? []\n );\n return (listing.amenities ?? []).filter((id) => id && !building.has(id));\n}\n\nfunction buildingAmenityIds(listing: ListingAmenitySource): string[] {\n if (listing.building != null && listing.building.amenities != null) {\n return presentIds(listing.building.amenities);\n }\n if (listing.buildingAmenities != null) {\n return presentIds(listing.buildingAmenities);\n }\n return buildingIdsFromMergedAmenities(listing, unitAmenityIds(listing));\n}\n\nexport function listingAmenityGroups(\n listing: ListingAmenitySource,\n dictionary?: AmenityLabelDictionary\n): ListingAmenityGroup[] {\n const groups: ListingAmenityGroup[] = [];\n const unitIds = unitAmenityIds(listing);\n const unitLabels = labelAmenities(unitIds, dictionary?.propertyFeatures);\n if (unitLabels.length > 0) {\n groups.push({\n key: \"unit\",\n title: LISTING_AMENITY_TITLES.unit,\n labels: unitLabels,\n });\n }\n\n const buildingLabels = labelAmenities(\n buildingAmenityIds(listing),\n dictionary?.buildingAmenities\n );\n if (buildingLabels.length > 0) {\n groups.push({\n key: \"building\",\n title: LISTING_AMENITY_TITLES.building,\n labels: buildingLabels,\n });\n }\n return groups;\n}\n","export type ListingBusinessType = \"sale\" | \"rental\";\n\nexport type SearchUrlOption = {\n id: string;\n slug: string;\n label: string;\n};\n\nexport type SearchUrlDictionary = {\n listingTypes: SearchUrlOption[];\n propertyTypes: SearchUrlOption[];\n propertyFeatures: SearchUrlOption[];\n buildingAmenities: SearchUrlOption[];\n};\n\nexport type SearchPathLocation = {\n state?: string;\n city?: string;\n neighborhood?: string;\n street?: string;\n};\n\nexport type SearchPathFilters = {\n listingType?: ListingBusinessType | string;\n propertyType?: string | string[];\n location?: SearchPathLocation;\n bedrooms?: number | number[];\n bathrooms?: number | number[];\n suites?: number | number[];\n parkingSpots?: number | number[];\n price?: { min?: number; max?: number };\n area?: { min?: number; max?: number };\n propertyFeatures?: string[];\n buildingAmenities?: string[];\n};\n\nexport type AppliedSearchQuery = {\n page?: number;\n sort?: string | null;\n query?: string;\n loc?: string[];\n};\n\nexport const SEARCH_BASE_ROUTE = \"imoveis\";\nexport const MAX_PAGE = 10_000;\nexport const MAX_LOC_GROUPS = 20;\nexport const DEFAULT_MIN_PRICE = 0;\nexport const DEFAULT_MAX_PRICE = 1_000_000_000;\nexport const DEFAULT_MIN_AREA = 0;\nexport const DEFAULT_MAX_AREA = 100_000;\n\nexport const SORT_URL_TOKENS = [\n \"preco-asc\",\n \"preco-desc\",\n \"area-asc\",\n \"area-desc\",\n] as const;\n\nexport type SortUrlToken = (typeof SORT_URL_TOKENS)[number];\n","/** URL slug for search paths (camelCase → kebab, strip accents). */\nexport function slugifyForUrl(text: string | null | undefined): string {\n if (!text) return \"\";\n const withDashes = text.replace(/([a-z])([A-Z])/g, \"$1-$2\");\n return withDashes\n .toLowerCase()\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/\\s+/g, \"-\")\n .replace(/-+/g, \"-\")\n .trim();\n}\n","import { slugifyForUrl } from \"./slugify\";\nimport type { SearchUrlDictionary, SearchUrlOption } from \"./types\";\n\n/** Last-resort id → Portuguese path slug (tenant slug/label win). */\nexport const PROPERTY_TYPE_ID_TO_SLUG: Record<string, string> = {\n apartment: \"apartamento\",\n house: \"casa\",\n penthouse: \"cobertura\",\n flat: \"flat\",\n kitnet: \"kitnet\",\n loft: \"loft\",\n townhouse: \"sobrado\",\n studio: \"studio\",\n triplex: \"triplex\",\n duplex: \"duplex\",\n land: \"terreno\",\n commercial: \"comercial\",\n office: \"sala-comercial\",\n store: \"loja\",\n warehouse: \"galpao\",\n building: \"predio\",\n hotel: \"hotel\",\n rural: \"rural\",\n other: \"outro\",\n};\n\nconst PROPERTY_TYPE_SLUG_ALIASES: Record<string, string[]> = {\n rural: [\"chacara\", \"fazenda\", \"sitio\"],\n};\n\nexport function buildListingTypeOptions(\n enabled?: {\n sale?: boolean;\n rental?: boolean;\n } | null\n): SearchUrlOption[] {\n const flags = enabled ?? { sale: true, rental: true };\n const out: SearchUrlOption[] = [];\n if (flags.sale !== false) {\n out.push({ id: \"sale\", slug: \"venda\", label: \"Venda\" });\n }\n if (flags.rental !== false) {\n out.push({ id: \"rental\", slug: \"aluguel\", label: \"Aluguel\" });\n }\n return out;\n}\n\nexport function emptySearchUrlDictionary(): SearchUrlDictionary {\n return {\n listingTypes: buildListingTypeOptions(null),\n propertyTypes: [],\n propertyFeatures: [],\n buildingAmenities: [],\n };\n}\n\nfunction catalogSlug(\n id: string,\n label?: string | null,\n slug?: string | null,\n fallbackMap?: Record<string, string>\n): string {\n if (slug?.trim()) return slugifyForUrl(slug) || slug.trim().toLowerCase();\n if (fallbackMap?.[id]) return fallbackMap[id];\n if (label?.trim()) return slugifyForUrl(label) || id.toLowerCase();\n return slugifyForUrl(id) || id.toLowerCase();\n}\n\nexport function mapCatalogOption(\n input: {\n id: string;\n label?: string | null;\n slug?: string | null;\n active?: boolean;\n },\n fallbackMap?: Record<string, string>\n): SearchUrlOption | null {\n if (!input.id || input.active === false) return null;\n return {\n id: input.id,\n label: input.label?.trim() || input.id,\n slug: catalogSlug(input.id, input.label, input.slug, fallbackMap),\n };\n}\n\nexport function mapPropertyTypeOption(input: {\n id: string;\n label?: string | null;\n slug?: string | null;\n active?: boolean;\n}): SearchUrlOption | null {\n return mapCatalogOption(input, PROPERTY_TYPE_ID_TO_SLUG);\n}\n\nfunction allocateCollisionSlug(base: string, taken: Set<string>): string {\n if (!taken.has(base)) return base;\n let candidate = `${base}-comodidade`;\n let suffix = 2;\n while (taken.has(candidate)) {\n candidate = `${base}-comodidade-${suffix}`;\n suffix += 1;\n }\n return candidate;\n}\n\n/**\n * Disambiguate feature/amenity path slugs against property types and\n * against each other (`coworking` + type → `-comodidade`, second hit\n * → `-comodidade-2`), matching the editor runtime dictionary.\n */\nexport function withAmenityCollisionSlugs(\n dictionary: SearchUrlDictionary\n): SearchUrlDictionary {\n const taken = new Set(dictionary.propertyTypes.map((item) => item.slug));\n const propertyFeatures = dictionary.propertyFeatures.map((item) => {\n const slug = allocateCollisionSlug(item.slug, taken);\n taken.add(slug);\n return slug === item.slug ? item : { ...item, slug };\n });\n const buildingAmenities = dictionary.buildingAmenities.map((item) => {\n const slug = allocateCollisionSlug(item.slug, taken);\n taken.add(slug);\n return slug === item.slug ? item : { ...item, slug };\n });\n return { ...dictionary, propertyFeatures, buildingAmenities };\n}\n\nfunction norm(value: string): string {\n return slugifyForUrl(value) || value.toLowerCase();\n}\n\nexport function matchOptionId(\n segment: string,\n options: SearchUrlOption[],\n extraAliases?: Record<string, string[]>\n): string | null {\n const n = norm(segment);\n for (const option of options) {\n const aliases = extraAliases?.[option.id] ?? [];\n const candidates = [option.id, option.slug, option.label, ...aliases];\n if (candidates.some((c) => norm(c) === n)) return option.id;\n }\n return null;\n}\n\nexport function optionSlugById(\n id: string,\n options: SearchUrlOption[]\n): string | null {\n const option = options.find((item) => item.id === id);\n return option?.slug ?? null;\n}\n\nexport const LISTING_TYPE_ALIASES: Record<string, string[]> = {\n sale: [\"comprar\"],\n rental: [\"alugar\"],\n};\n\nexport { PROPERTY_TYPE_SLUG_ALIASES };\n","import {\n LISTING_TYPE_ALIASES,\n PROPERTY_TYPE_SLUG_ALIASES,\n emptySearchUrlDictionary,\n matchOptionId,\n optionSlugById,\n} from \"./catalog\";\nimport { slugifyForUrl } from \"./slugify\";\nimport type { SearchPathFilters, SearchUrlDictionary } from \"./types\";\nimport {\n DEFAULT_MAX_AREA,\n DEFAULT_MAX_PRICE,\n DEFAULT_MIN_AREA,\n DEFAULT_MIN_PRICE,\n SEARCH_BASE_ROUTE,\n} from \"./types\";\n\nfunction toArray<T>(value: T | T[] | undefined): T[] {\n if (value === undefined) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction formatNumeric(value: number | number[]): string {\n return Array.isArray(value) ? value.join(\"-\") : String(value);\n}\n\nfunction formatRange(min: number, max: number, unit: string): string {\n return `de-${min}-a-${max}-${unit}`;\n}\n\nfunction formatSuiteSuffix(value: number | number[]): string {\n const values = Array.isArray(value) ? value : [value];\n const firstValue = values[0] ?? 0;\n return firstValue === 0 || firstValue === 1 ? \"suite\" : \"suites\";\n}\n\nexport function composeSearchPublicPath(\n filters: SearchPathFilters,\n dictionary: SearchUrlDictionary = emptySearchUrlDictionary()\n): string {\n const segments: string[] = [];\n const listingType = filters.listingType;\n if (listingType) {\n segments.push(\n optionSlugById(listingType, dictionary.listingTypes) ||\n slugifyForUrl(listingType)\n );\n }\n\n for (const propertyType of toArray(filters.propertyType)) {\n segments.push(\n optionSlugById(propertyType, dictionary.propertyTypes) ||\n slugifyForUrl(propertyType)\n );\n }\n\n const location = filters.location;\n if (location) {\n if (location.state) segments.push(slugifyForUrl(location.state));\n if (location.city) segments.push(slugifyForUrl(location.city));\n if (location.neighborhood)\n segments.push(slugifyForUrl(location.neighborhood));\n if (location.street) segments.push(slugifyForUrl(location.street));\n }\n\n if (filters.bedrooms !== undefined) {\n segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);\n }\n if (filters.bathrooms !== undefined) {\n segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);\n }\n if (filters.suites !== undefined) {\n const suffix = formatSuiteSuffix(filters.suites);\n segments.push(`${formatNumeric(filters.suites)}-${suffix}`);\n }\n if (filters.parkingSpots !== undefined) {\n segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);\n }\n\n if (\n filters.price &&\n (filters.price.min !== undefined || filters.price.max !== undefined)\n ) {\n const min = filters.price.min ?? DEFAULT_MIN_PRICE;\n const max = filters.price.max ?? DEFAULT_MAX_PRICE;\n segments.push(formatRange(min, max, \"reais\"));\n }\n if (\n filters.area &&\n (filters.area.min !== undefined || filters.area.max !== undefined)\n ) {\n const min = filters.area.min ?? DEFAULT_MIN_AREA;\n const max = filters.area.max ?? DEFAULT_MAX_AREA;\n segments.push(formatRange(min, max, \"m2\"));\n }\n\n const seenAmenities = new Set<string>();\n for (const id of filters.propertyFeatures ?? []) {\n const slug =\n optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);\n if (!slug || seenAmenities.has(slug)) continue;\n seenAmenities.add(slug);\n segments.push(slug);\n }\n for (const id of filters.buildingAmenities ?? []) {\n const slug =\n optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);\n if (!slug || seenAmenities.has(slug)) continue;\n seenAmenities.add(slug);\n segments.push(slug);\n }\n\n const path = segments.filter(Boolean).join(\"/\");\n return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;\n}\n\nconst BEDROOMS = /^(\\d+(?:-\\d+)*)-quartos?$/;\nconst BATHROOMS = /^(\\d+(?:-\\d+)*)-banheiros?$/;\nconst SUITES = /^(\\d+(?:-\\d+)*)-suites?$/;\nconst PARKING = /^(\\d+(?:-\\d+)*)-vagas?$/;\nconst PRICE = /^de-(\\d+)-a-(\\d+)-(reais|real)$/;\nconst AREA = /^de-(\\d+)-a-(\\d+)-(m2|m²)$/;\n\nfunction parseNumericList(raw: string): number[] {\n return raw\n .split(\"-\")\n .map((part) => Number(part))\n .filter((n) => Number.isFinite(n));\n}\n\nfunction collapse(values: number[]): number | number[] {\n return values.length === 1 ? values[0]! : values;\n}\n\n/**\n * Parse a default-V2 search path. Order-flexible (detection), not generation.\n * `id-…` anywhere is listing detail — returns null so the caller can route.\n */\nexport function parseSearchPublicPath(\n pathname: string,\n dictionary: SearchUrlDictionary = emptySearchUrlDictionary()\n): SearchPathFilters | null {\n const raw = pathname.split(/[?#]/)[0] ?? \"\";\n let segments = raw.replace(/^\\//, \"\").split(\"/\").filter(Boolean);\n if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);\n if (segments.some((segment) => segment.includes(\".\"))) return null;\n if (segments.some((segment) => segment.toLowerCase().startsWith(\"id-\"))) {\n return null;\n }\n\n const filters: SearchPathFilters = {};\n const locationParts: string[] = [];\n const propertyTypes: string[] = [];\n const propertyFeatures: string[] = [];\n const buildingAmenities: string[] = [];\n\n for (const segment of segments) {\n const lower = segment.toLowerCase();\n const listingType = matchOptionId(\n segment,\n dictionary.listingTypes,\n LISTING_TYPE_ALIASES\n );\n if (listingType && !filters.listingType) {\n filters.listingType = listingType;\n continue;\n }\n\n const propertyType = matchOptionId(\n segment,\n dictionary.propertyTypes,\n PROPERTY_TYPE_SLUG_ALIASES\n );\n if (propertyType) {\n propertyTypes.push(propertyType);\n continue;\n }\n\n const bedrooms = lower.match(BEDROOMS);\n if (bedrooms) {\n filters.bedrooms = collapse(parseNumericList(bedrooms[1]!));\n continue;\n }\n const bathrooms = lower.match(BATHROOMS);\n if (bathrooms) {\n filters.bathrooms = collapse(parseNumericList(bathrooms[1]!));\n continue;\n }\n const suites = lower.match(SUITES);\n if (suites) {\n filters.suites = collapse(parseNumericList(suites[1]!));\n continue;\n }\n const parking = lower.match(PARKING);\n if (parking) {\n filters.parkingSpots = collapse(parseNumericList(parking[1]!));\n continue;\n }\n const price = lower.match(PRICE);\n if (price) {\n filters.price = { min: Number(price[1]), max: Number(price[2]) };\n continue;\n }\n const area = lower.match(AREA);\n if (area) {\n filters.area = { min: Number(area[1]), max: Number(area[2]) };\n continue;\n }\n\n const featureId = matchOptionId(segment, dictionary.propertyFeatures);\n if (featureId) {\n propertyFeatures.push(featureId);\n continue;\n }\n const amenityId = matchOptionId(segment, dictionary.buildingAmenities);\n if (amenityId) {\n buildingAmenities.push(amenityId);\n continue;\n }\n\n locationParts.push(segment);\n }\n\n if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];\n else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;\n if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;\n if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;\n\n const location = locationFromPathLeftovers(locationParts);\n if (location) filters.location = location;\n\n return filters;\n}\n\nconst PATH_STREET_PREFIX =\n /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;\n\n/**\n * Path leftovers are hierarchical from the left (compose writes\n * state → city → neighborhood → street). A single leftover is not a\n * state unless it is a 2-letter UF slug — otherwise it matches `?loc=`\n * (neighborhood, or street when the slug has a street prefix).\n */\nfunction locationFromPathLeftovers(\n parts: string[]\n): SearchPathFilters[\"location\"] | undefined {\n if (parts.length === 0) return undefined;\n if (parts.length === 1) {\n const value = parts[0]!;\n if (PATH_STREET_PREFIX.test(value)) return { street: value };\n if (/^[a-z]{2}$/i.test(value)) return { state: value };\n return { neighborhood: value };\n }\n const [state, city, neighborhood, street] = parts;\n return {\n ...(state ? { state } : {}),\n ...(city ? { city } : {}),\n ...(neighborhood ? { neighborhood } : {}),\n ...(street ? { street } : {}),\n };\n}\n","import type { AppliedSearchQuery, SortUrlToken } from \"./types\";\nimport { MAX_LOC_GROUPS, MAX_PAGE, SORT_URL_TOKENS } from \"./types\";\n\nconst SORT_SET = new Set<string>(SORT_URL_TOKENS);\n\nexport type AppliedSearchChange =\n | { type: \"sort\"; sort: string | null }\n | { type: \"page\"; page: number }\n | { type: \"query\"; query: string }\n | { type: \"loc\"; loc: string[] }\n | { type: \"applyFilters\" };\n\nfunction isSortToken(value: string): value is SortUrlToken {\n return SORT_SET.has(value);\n}\n\nexport function normalizeAppliedSearchQuery(\n query: AppliedSearchQuery\n): AppliedSearchQuery {\n if (query.loc && query.loc.length > 0) {\n const { query: _query, ...rest } = query;\n return rest;\n }\n return query;\n}\n\nexport function parseAppliedSearchQuery(\n search: string | URLSearchParams\n): AppliedSearchQuery {\n const params =\n search instanceof URLSearchParams\n ? search\n : new URLSearchParams(search.startsWith(\"?\") ? search.slice(1) : search);\n const result: AppliedSearchQuery = {};\n\n const pageRaw = params.get(\"page\");\n if (pageRaw) {\n const page = Number.parseInt(pageRaw, 10);\n if (Number.isFinite(page) && page > 1) {\n result.page = Math.min(page, MAX_PAGE);\n }\n }\n\n const sort = params.get(\"ordenar\");\n if (sort && isSortToken(sort)) result.sort = sort;\n\n const q = params.get(\"q\")?.trim();\n if (q) result.query = q;\n\n const loc = params\n .getAll(\"loc\")\n .map((value) => value.trim())\n .filter(Boolean)\n .slice(0, MAX_LOC_GROUPS);\n if (loc.length > 0) result.loc = loc;\n\n return normalizeAppliedSearchQuery(result);\n}\n\n/** Keys managed by AppliedSearchQuery (removed/rewritten on merge). */\nconst APPLIED_QUERY_KEYS = [\"page\", \"ordenar\", \"q\", \"loc\"] as const;\n\nexport function serializeAppliedSearchQuery(\n query: AppliedSearchQuery\n): URLSearchParams {\n const normalized = normalizeAppliedSearchQuery(query);\n const params = new URLSearchParams();\n if (normalized.page !== undefined && normalized.page > 1) {\n params.set(\"page\", String(Math.min(normalized.page, MAX_PAGE)));\n }\n if (normalized.sort && isSortToken(normalized.sort)) {\n params.set(\"ordenar\", normalized.sort);\n }\n const text = normalized.query?.trim();\n if (text) params.set(\"q\", text);\n for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {\n const trimmed = value.trim();\n if (trimmed) params.append(\"loc\", trimmed);\n }\n return params;\n}\n\n/**\n * Merge applied query into an existing search string, preserving unknown keys\n * (UTM params, etc.) while rewriting managed keys.\n */\nexport function mergeAppliedSearchQueryIntoSearch(\n existing: string | URLSearchParams,\n query: AppliedSearchQuery\n): URLSearchParams {\n const params =\n existing instanceof URLSearchParams\n ? new URLSearchParams(existing)\n : new URLSearchParams(\n existing.startsWith(\"?\") ? existing.slice(1) : existing\n );\n\n // Remove all managed keys\n for (const key of APPLIED_QUERY_KEYS) {\n params.delete(key);\n }\n\n // Merge in the serialized applied query\n const serialized = serializeAppliedSearchQuery(query);\n serialized.forEach((value, key) => {\n if (key === \"loc\") {\n params.append(\"loc\", value);\n } else {\n params.set(key, value);\n }\n });\n\n return params;\n}\n\nexport function reduceAppliedSearchQuery(\n prev: AppliedSearchQuery,\n change: AppliedSearchChange\n): AppliedSearchQuery {\n switch (change.type) {\n case \"sort\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n if (change.sort) next.sort = change.sort;\n else delete next.sort;\n return normalizeAppliedSearchQuery(next);\n }\n case \"applyFilters\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n return normalizeAppliedSearchQuery(next);\n }\n case \"query\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n const trimmed = change.query.trim();\n if (trimmed) {\n next.query = trimmed;\n delete next.loc;\n } else {\n delete next.query;\n }\n return normalizeAppliedSearchQuery(next);\n }\n case \"loc\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n delete next.query;\n const loc = change.loc\n .map((value) => value.trim())\n .filter(Boolean)\n .slice(0, MAX_LOC_GROUPS);\n if (loc.length > 0) next.loc = loc;\n else delete next.loc;\n return normalizeAppliedSearchQuery(next);\n }\n case \"page\": {\n const next: AppliedSearchQuery = { ...prev };\n if (change.page <= 1) delete next.page;\n else next.page = Math.min(change.page, MAX_PAGE);\n return normalizeAppliedSearchQuery(next);\n }\n default: {\n const _exhaustive: never = change;\n return _exhaustive;\n }\n }\n}\n\nexport function composeSearchPublicHref(\n pathname: string,\n query: AppliedSearchQuery,\n existingSearch?: string | URLSearchParams\n): string {\n const params = existingSearch\n ? mergeAppliedSearchQueryIntoSearch(existingSearch, query)\n : serializeAppliedSearchQuery(query);\n const qs = params.toString();\n return qs ? `${pathname}?${qs}` : pathname;\n}\n","import {\n composeSearchPublicHref as composeHref,\n mergeAppliedSearchQueryIntoSearch as mergeQuery,\n parseAppliedSearchQuery as parseQuery,\n reduceAppliedSearchQuery as reduceQuery,\n serializeAppliedSearchQuery as serializeQuery,\n} from \"@garagem/search-url\";\nimport type { AppliedSearchChange, AppliedSearchQuery } from \"./types\";\n\nexport function parseAppliedSearchQuery(\n search: string | URLSearchParams\n): AppliedSearchQuery {\n return parseQuery(search);\n}\n\nexport function serializeAppliedSearchQuery(\n query: AppliedSearchQuery\n): URLSearchParams {\n return serializeQuery(query);\n}\n\nexport function mergeAppliedSearchQueryIntoSearch(\n existing: string | URLSearchParams,\n query: AppliedSearchQuery\n): URLSearchParams {\n return mergeQuery(existing, query);\n}\n\nexport function reduceAppliedSearchQuery(\n prev: AppliedSearchQuery,\n change: AppliedSearchChange\n): AppliedSearchQuery {\n return reduceQuery(prev, change);\n}\n\nexport function composeSearchPublicHref(\n pathname: string,\n query: AppliedSearchQuery,\n existingSearch?: string | URLSearchParams\n): string {\n return composeHref(pathname, query, existingSearch);\n}\n","// Re-exported from @garagem/site-search to avoid publishing the private package\nexport type LocationFilterInput = {\n type: string;\n value: string;\n};\n\n/**\n * Convert a SearchPathLocation (from parseSearchPublicPath) to the correct\n * LocationFilterInput format for the friendly search API. This ensures that\n * hierarchical location filters are ANDed correctly instead of ORed.\n */\nexport function pathLocationToFilterInput(location: {\n state?: string;\n city?: string;\n neighborhood?: string;\n street?: string;\n}): LocationFilterInput | null {\n if (!location || typeof location !== \"object\") return null;\n\n const { state, city, neighborhood, street } = location;\n const levels: string[] = [];\n if (state) levels.push(state);\n if (city) levels.push(city);\n if (neighborhood) levels.push(neighborhood);\n if (street) levels.push(street);\n\n if (levels.length === 0) return null;\n if (levels.length === 1) {\n if (state) return { type: \"state\", value: state };\n if (city) return { type: \"city\", value: city };\n if (neighborhood) return { type: \"neighborhood\", value: neighborhood };\n if (street) return { type: \"street\", value: street };\n }\n\n return { type: \"path\", value: levels.join(\"/\") };\n}\n","import {\n composeSearchPublicPath as composePath,\n parseSearchPublicPath as parsePath,\n} from \"@garagem/search-url\";\nimport type {\n QueryListingsFilters,\n SearchPathFilters,\n SearchUiDictionary,\n} from \"./types\";\n\nexport function composeSearchPublicPath(\n filters: SearchPathFilters,\n dictionary?: SearchUiDictionary\n): string {\n return dictionary ? composePath(filters, dictionary) : composePath(filters);\n}\n\nexport function parseSearchPublicPath(\n pathname: string,\n dictionary?: SearchUiDictionary\n): SearchPathFilters | null {\n return dictionary ? parsePath(pathname, dictionary) : parsePath(pathname);\n}\n\n/**\n * Convert `SearchPathFilters` (returned by `parseSearchPublicPath`) to\n * `QueryListingsFilters` (accepted by `queryListings`).\n *\n * This maps path-based filter keys (`bedrooms`, `parkingSpots`, `area`)\n * to the POST API keys (`property_bedrooms`, `property_parking_spots`,\n * `property_area_total`).\n *\n * Location is **not** included — use `pathLocationToFilterInput` separately\n * and pass the result as the `location` field in `QueryListingsParams`.\n */\nexport function pathFiltersToQueryFilters(\n pathFilters: SearchPathFilters\n): QueryListingsFilters {\n const result: QueryListingsFilters = {};\n\n if (pathFilters.listingType !== undefined) {\n result.listing_type = pathFilters.listingType;\n }\n if (pathFilters.propertyType !== undefined) {\n result.property_type = pathFilters.propertyType;\n }\n if (pathFilters.bedrooms !== undefined) {\n result.property_bedrooms = pathFilters.bedrooms;\n }\n if (pathFilters.bathrooms !== undefined) {\n result.property_bathrooms = pathFilters.bathrooms;\n }\n if (pathFilters.suites !== undefined) {\n result.property_suites = pathFilters.suites;\n }\n if (pathFilters.parkingSpots !== undefined) {\n result.property_parking_spots = pathFilters.parkingSpots;\n }\n if (pathFilters.price !== undefined) {\n result.price = pathFilters.price;\n }\n if (pathFilters.area !== undefined) {\n result.property_area_total = pathFilters.area;\n }\n if (pathFilters.propertyFeatures !== undefined) {\n result.propertyFeatures = pathFilters.propertyFeatures;\n }\n if (pathFilters.buildingAmenities !== undefined) {\n result.buildingAmenities = pathFilters.buildingAmenities;\n }\n\n return result;\n}\n","import {\n composeSearchPublicHref,\n parseAppliedSearchQuery,\n reduceAppliedSearchQuery,\n} from \"./applied-query\";\nimport { pathLocationToFilterInput } from \"./loc-params\";\nimport {\n composeSearchPublicPath,\n parseSearchPublicPath,\n pathFiltersToQueryFilters,\n} from \"./path\";\nimport { formatGroupedInteger, parseGroupedInteger } from \"./presentation\";\nimport type {\n AppliedSearchChange,\n AppliedSearchQuery,\n QueryListingsParams,\n SearchPathFilters,\n SearchUi,\n SearchUiDictionary,\n SearchUiFilter,\n SearchUiOption,\n} from \"./types\";\n\nconst PATH_FILTER_IDS: Record<string, keyof SearchPathFilters> = {\n listing_type: \"listingType\",\n property_type: \"propertyType\",\n property_bedrooms: \"bedrooms\",\n property_bathrooms: \"bathrooms\",\n property_suites: \"suites\",\n property_parking_spots: \"parkingSpots\",\n price: \"price\",\n property_area_total: \"area\",\n propertyFeatures: \"propertyFeatures\",\n buildingAmenities: \"buildingAmenities\",\n};\n\n/** Query keys that must never encode filters (Editor/Studio path contract). */\nexport const FORBIDDEN_SEARCH_QUERY_KEYS = [\n \"tipo\",\n \"quartos\",\n \"tipo-imovel\",\n \"banheiros\",\n \"vagas\",\n] as const;\n\n/** Default option: omit `ordenar` (API has no relevance token). */\nexport const SEARCH_SORT_RELEVANCE = {\n id: \"\",\n label: \"Mais relevantes\",\n} as const;\n\nexport function searchSortOptions(\n sorts: Array<{ id: string; label: string }> | undefined\n): Array<{ id: string; label: string }> {\n const fromApi = (sorts || []).filter((sort) => sort.id);\n return [\n { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },\n ...fromApi,\n ];\n}\n\n/** Toolbar: price + bedrooms first and required when the schema has them. */\nexport const TOOLBAR_PRIMARY_FILTER_IDS = [\n \"price\",\n \"property_bedrooms\",\n] as const;\n\nconst HIDDEN_FILTER_IDS = new Set([\"property_suites\"]);\n\nfunction toFiniteNumber(value: unknown): number | undefined {\n if (value === \"\" || value == null) return undefined;\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n}\n\nfunction pathnameOnly(pathname: string): string {\n return String(pathname || \"\").split(/[?#]/)[0] || \"/\";\n}\n\nexport function isListingDetailPath(pathname: string): boolean {\n const parts = pathnameOnly(pathname).split(\"/\").filter(Boolean);\n const last = parts[parts.length - 1] || \"\";\n return last.toLowerCase().startsWith(\"id-\");\n}\n\nexport function readPublicSearch(\n pathname: string,\n search: string,\n dictionary?: SearchUiDictionary\n): { pathFilters: SearchPathFilters; applied: AppliedSearchQuery } {\n const pathFilters =\n parseSearchPublicPath(pathnameOnly(pathname), dictionary) || {};\n const applied = parseAppliedSearchQuery(search || \"\");\n return { pathFilters, applied };\n}\n\nfunction lookupDisplay(\n table: Record<string, string> | undefined,\n slug: string | undefined\n): string | undefined {\n if (!slug || !table) return slug;\n return table[slug] || table[String(slug).toLowerCase()] || slug;\n}\n\nexport type LocationNameTables = {\n states?: Record<string, string>;\n cities?: Record<string, string>;\n neighborhoods?: Record<string, string>;\n streets?: Record<string, string>;\n};\n\nexport function displayPathLocation(\n location: SearchPathFilters[\"location\"],\n values?: LocationNameTables | null\n): SearchPathFilters[\"location\"] | null {\n if (!location) return null;\n const table = values || {};\n return {\n state: lookupDisplay(table.states, location.state),\n city: lookupDisplay(table.cities, location.city),\n neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),\n street: lookupDisplay(table.streets, location.street),\n };\n}\n\nexport function buildQueryListingsParams(\n pathFilters: SearchPathFilters,\n applied: AppliedSearchQuery,\n schema: Pick<SearchUi, \"defaultLimit\"> | { defaultLimit?: number } | null,\n locationValues?: LocationNameTables | null\n): QueryListingsParams {\n const filters = pathFiltersToQueryFilters(pathFilters || {});\n const locations: Array<{ type: string; value: string }> = [];\n const displayed = displayPathLocation(pathFilters?.location, locationValues);\n const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;\n if (pathLoc) locations.push(pathLoc);\n for (const value of applied?.loc || []) {\n locations.push({ type: \"loc\", value });\n }\n const params: QueryListingsParams = {\n page: applied?.page || 1,\n limit: schema?.defaultLimit || 12,\n filters,\n };\n if (applied?.sort) params.sort = applied.sort;\n const hasLocation = locations.length > 0;\n if (applied?.query && !hasLocation) params.q = applied.query;\n if (hasLocation) params.location = locations;\n return params;\n}\n\nexport function applyPathFilter(\n pathFilters: SearchPathFilters,\n filterId: string,\n value: unknown\n): SearchPathFilters {\n const next: SearchPathFilters = { ...(pathFilters || {}) };\n const key = PATH_FILTER_IDS[filterId];\n if (!key) return next;\n if (value === \"\" || value == null) {\n delete next[key];\n return next;\n }\n if (key === \"price\" || key === \"area\") {\n const range = (value || {}) as { min?: unknown; max?: unknown };\n const parse = key === \"price\" ? parseGroupedInteger : toFiniteNumber;\n const min = parse(range.min);\n const max = parse(range.max);\n if (min == null && max == null) {\n delete next[key];\n return next;\n }\n next[key] = {\n ...(min != null ? { min } : {}),\n ...(max != null ? { max } : {}),\n };\n return next;\n }\n if (key === \"propertyFeatures\" || key === \"buildingAmenities\") {\n const current = Array.isArray(next[key]) ? [...next[key]] : [];\n const id = String(value);\n const i = current.indexOf(id);\n if (i >= 0) current.splice(i, 1);\n else current.push(id);\n if (current.length) next[key] = current;\n else delete next[key];\n return next;\n }\n if (key === \"propertyType\") {\n const id = String(value);\n const current = Array.isArray(next.propertyType)\n ? [...next.propertyType]\n : next.propertyType\n ? [String(next.propertyType)]\n : [];\n const i = current.indexOf(id);\n if (i >= 0) current.splice(i, 1);\n else current.push(id);\n if (current.length === 0) delete next.propertyType;\n else if (current.length === 1) next.propertyType = current[0];\n else next.propertyType = current;\n return next;\n }\n if (key === \"listingType\") {\n const id = String(value);\n if (next.listingType === id) delete next.listingType;\n else next.listingType = id;\n return next;\n }\n if (\n key === \"bedrooms\" ||\n key === \"bathrooms\" ||\n key === \"suites\" ||\n key === \"parkingSpots\"\n ) {\n const n = Number(value);\n if (!Number.isFinite(n)) {\n delete next[key];\n return next;\n }\n if (next[key] === n) delete next[key];\n else next[key] = n;\n return next;\n }\n return next;\n}\n\nexport function pathFilterValue(\n pathFilters: SearchPathFilters | undefined,\n filterId: string\n): string {\n const key = PATH_FILTER_IDS[filterId];\n const value = pathFilters && key ? pathFilters[key] : undefined;\n if (value == null) return \"\";\n if (Array.isArray(value)) return value[0] != null ? String(value[0]) : \"\";\n if (typeof value === \"object\") return \"\";\n return String(value);\n}\n\nexport function pathFilterHasOption(\n pathFilters: SearchPathFilters | undefined,\n filterId: string,\n optionId: string\n): boolean {\n const key = PATH_FILTER_IDS[filterId];\n const value = pathFilters && key ? pathFilters[key] : undefined;\n if (value == null) return false;\n if (Array.isArray(value)) return value.map(String).includes(optionId);\n if (typeof value === \"object\") return false;\n return String(value) === optionId;\n}\n\nexport function publicSearchHref(\n pathFilters: SearchPathFilters,\n applied: AppliedSearchQuery,\n dictionary?: SearchUiDictionary,\n existingSearch?: string\n): string {\n const pathname = composeSearchPublicPath(pathFilters || {}, dictionary);\n return composeSearchPublicHref(pathname, applied || {}, existingSearch);\n}\n\nexport function hrefForPathFilters(\n pathname: string,\n search: string,\n dictionary: SearchUiDictionary | undefined,\n nextPathFilters: SearchPathFilters\n): string {\n const { applied } = readPublicSearch(pathname, search, dictionary);\n const nextApplied = reduceAppliedSearchQuery(applied, {\n type: \"applyFilters\",\n });\n return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);\n}\n\nexport function hrefForAppliedChange(\n pathname: string,\n search: string,\n dictionary: SearchUiDictionary | undefined,\n change: AppliedSearchChange\n): string {\n const { pathFilters, applied } = readPublicSearch(\n pathname,\n search,\n dictionary\n );\n let nextPath = pathFilters;\n if (change && change.type === \"query\") {\n nextPath = { ...pathFilters };\n delete nextPath.location;\n }\n const nextApplied = reduceAppliedSearchQuery(applied, change);\n return publicSearchHref(nextPath, nextApplied, dictionary, search);\n}\n\nfunction currentSearchHref(pathname: string, search: string): string {\n const path = pathnameOnly(pathname);\n const qs = search.replace(/^\\?/, \"\");\n return qs ? `${path}?${qs}` : path;\n}\n\n/** Canonical href if the current URL is out of generation order; otherwise null. */\nexport function canonicalizeSearchHref(\n pathname: string,\n search: string,\n dictionary?: SearchUiDictionary\n): string | null {\n const { pathFilters, applied } = readPublicSearch(\n pathname,\n search,\n dictionary\n );\n const href = publicSearchHref(pathFilters, applied, dictionary, search);\n if (href === currentSearchHref(pathname, search)) return null;\n return href;\n}\n\nexport function searchHrefUsesLegacyFilterQuery(href: string): boolean {\n const query = href.split(\"?\")[1] || \"\";\n const params = new URLSearchParams(query);\n return FORBIDDEN_SEARCH_QUERY_KEYS.some((key) => params.has(key));\n}\n\n/**\n * Drop staged filters. Location always stays until apply.\n * `keepFilterIds` keeps toolbar-primary filters (price, bedrooms) so Limpar\n * in the extra-filters dialog does not wipe values already on the toolbar.\n */\nexport function clearStagedPathFilters(\n current: SearchPathFilters,\n keepFilterIds: readonly string[] = []\n): SearchPathFilters {\n const next: SearchPathFilters = current.location\n ? { location: current.location }\n : {};\n for (const id of keepFilterIds) {\n const key = PATH_FILTER_IDS[id];\n if (!key || key === \"location\") continue;\n const value = current[key];\n if (value != null) Object.assign(next, { [key]: value });\n }\n return next;\n}\n\nexport function visibleSearchFilters(\n schema: SearchUi | null\n): SearchUiFilter[] {\n if (!schema?.filters) return [];\n return schema.filters.filter((filter) => {\n if (HIDDEN_FILTER_IDS.has(filter.id)) return false;\n if (filter.id === \"listing_type\" && (filter.options?.length ?? 0) <= 1) {\n return false;\n }\n return true;\n });\n}\n\nexport function toolbarFilterIds(schema: SearchUi | null): string[] {\n const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));\n return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));\n}\n\nexport function countOptionLabel(\n option: Pick<SearchUiOption, \"label\">\n): string {\n const label = String(option?.label ?? \"\");\n if (/^[1-9]\\d*$/.test(label)) return `${label}+`;\n return label;\n}\n\nexport function countFacetChoices(\n options: SearchUiOption[] | undefined\n): Array<{ id: string; label: string }> {\n const list = options || [];\n const zero = list.find((o) => o.id === \"0\" || o.label === \"Studio\");\n const isStudio = Boolean(\n zero && /studio/i.test(String(zero.label)) && zero.id === \"0\"\n );\n const max = isStudio ? 3 : 4;\n const out: Array<{ id: string; label: string }> = [];\n if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });\n for (let n = 1; n <= max; n += 1) {\n const option = list.find((o) => o.id === String(n));\n out.push({\n id: String(n),\n label: countOptionLabel(option || { label: String(n) }),\n });\n }\n return out;\n}\n\nconst FEMININE_HEADING =\n /(casa|cobertura|kitnet|loja|sala|fazenda|chácara|chacara)s?$/i;\n\nfunction pluralizePt(label: string): string {\n const text = label.trim();\n if (!text || /s$/i.test(text)) return text;\n if (/il$/i.test(text)) return `${text.slice(0, -1)}is`;\n if (/m$/i.test(text)) return `${text.slice(0, -1)}ns`;\n return `${text}s`;\n}\n\nfunction headingLocationSuffix(\n location: SearchPathFilters[\"location\"] | null\n): string {\n if (!location) return \"\";\n if (location.street && location.neighborhood) {\n return `${location.street}, ${location.neighborhood}`;\n }\n if (location.neighborhood && location.city) {\n return `${location.neighborhood}, ${location.city}`;\n }\n if (location.city && location.state) {\n return `${location.city} - ${location.state}`;\n }\n return (\n location.city ||\n location.neighborhood ||\n location.street ||\n location.state ||\n \"\"\n );\n}\n\n/**\n * SEO H1 for a search URL. Must stay stable for the same path — never\n * include the hit count (Google treats a changing H1 on one URL as\n * volatile). Count is rendered in a sibling `<span>`.\n */\nexport function searchResultsHeading(\n pathFilters: SearchPathFilters,\n dictionary?: SearchUiDictionary | null,\n locationNames?: LocationNameTables | null\n): string {\n const types = ([] as string[])\n .concat(pathFilters.propertyType || [])\n .filter(Boolean);\n let noun = \"Imóveis\";\n let found = \"encontrados\";\n if (types.length === 1) {\n const id = String(types[0]);\n const option = dictionary?.propertyTypes?.find(\n (entry) => entry.id === id || entry.slug === id\n );\n const label = option?.label;\n if (label) {\n noun = pluralizePt(label.charAt(0).toUpperCase() + label.slice(1));\n if (FEMININE_HEADING.test(id) || FEMININE_HEADING.test(label)) {\n found = \"encontradas\";\n }\n }\n }\n const place = locationNames\n ? headingLocationSuffix(\n displayPathLocation(pathFilters.location, locationNames)\n )\n : \"\";\n if (place) return `${noun} ${found} em ${place}`;\n return `${noun} ${found}`;\n}\n\n/**\n * Next App Router does not navigate when the href is unchanged. Canonical\n * URLs omit `page=1`, so pagination must still emit `?page=1` on the link.\n */\nexport function hrefWithExplicitPage(href: string, page: number): string {\n if (page !== 1 || /(?:\\?|&)page=/.test(href)) return href;\n return href.includes(\"?\") ? `${href}&page=1` : `${href}?page=1`;\n}\n\nexport function paginationPages(\n currentPage: number,\n totalPages: number,\n padding: number\n): number[] {\n if (totalPages < 1) return [];\n const current = Math.min(Math.max(1, currentPage), totalPages);\n const start = Math.max(1, current - padding);\n const end = Math.min(totalPages, current + padding);\n const pages: number[] = [];\n for (let i = start; i <= end; i += 1) pages.push(i);\n return pages;\n}\n\nexport const SEARCH_EMPTY_COPY =\n \"Nenhum imóvel encontrado. Ajuste a busca ou os filtros.\";\n\nexport function rangeDraftFromPath(\n pathFilters: SearchPathFilters\n): Record<string, { min: string; max: string }> {\n const price = pathFilters.price || {};\n const area = pathFilters.area || {};\n return {\n price: {\n min: price.min != null ? formatGroupedInteger(price.min) : \"\",\n max: price.max != null ? formatGroupedInteger(price.max) : \"\",\n },\n property_area_total: {\n min: area.min != null ? String(area.min) : \"\",\n max: area.max != null ? String(area.max) : \"\",\n },\n };\n}\n\nexport type SearchChromeModel = {\n headingTitle: string;\n toolbarFilters: SearchUiFilter[];\n extraFilters: SearchUiFilter[];\n sortOptions: Array<{ id: string; label: string }>;\n};\n\nexport function searchChromeModel(\n schema: SearchUi | null,\n pathFilters: SearchPathFilters,\n locationNames?: LocationNameTables | null\n): SearchChromeModel {\n const filters = visibleSearchFilters(schema);\n const toolbarIds = new Set(toolbarFilterIds(schema));\n return {\n headingTitle: searchResultsHeading(\n pathFilters,\n schema?.dictionary,\n locationNames\n ),\n toolbarFilters: filters.filter((filter) => toolbarIds.has(filter.id)),\n extraFilters: filters.filter((filter) => !toolbarIds.has(filter.id)),\n sortOptions: searchSortOptions(schema?.sorts),\n };\n}\n","import { listingLocationLabel } from \"./listing-card-model\";\nimport { listingPublicPath } from \"./listing-path\";\nimport { formatAreaM2, formatListingPrice } from \"./presentation\";\nimport { isListingDetailPath } from \"./search-engine\";\nimport type { ListingDetail, ListingLocation, ListingMedia } from \"./types\";\n\nexport const LISTING_DESCRIPTION_CLAMP = 280;\n\nconst VIDEO_HOST_HINTS = [\n \"youtube.com\",\n \"youtu.be\",\n \"vimeo.com\",\n \"wistia.com\",\n \"wistia.net\",\n] as const;\n\nconst BREADCRUMB_LABELS: Record<string, string> = {\n imoveis: \"Imóveis\",\n venda: \"Venda\",\n aluguel: \"Aluguel\",\n rental: \"Aluguel\",\n sale: \"Venda\",\n};\n\n/** Visible listing fact. The number / area / floor is `text` — never omit it. */\nexport type ListingFact = { key: string; label: string; text: string };\n/** Visible listing amount. Price, condomínio and IPTU are `text`. */\nexport type ListingValue = { key: string; label: string; text: string };\nexport type ListingBreadcrumbCrumb = { label: string; href: string };\nexport type ListingLocationBlock = { label: string; mapsHref: string | null };\nexport type ListingDescriptionPreview = {\n text: string;\n truncated: boolean;\n toggleLabel: string | null;\n};\nexport type ListingMediaOverlay = {\n key: \"video\" | \"tour\";\n hash: \"video\" | \"tour\";\n title: string;\n href: string;\n embedSrc: string;\n};\n\nexport type ListingDetailModel = {\n breadcrumb: ListingBreadcrumbCrumb[];\n values: ListingValue[];\n facts: ListingFact[];\n location: ListingLocationBlock | null;\n /** Complete description string — never a sliced preview. */\n description: string | null;\n descriptionTruncated: boolean;\n descriptionToggleLabel: string | null;\n mediaOverlays: ListingMediaOverlay[];\n};\n\nfunction finiteNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return null;\n}\n\nfunction positiveCount(value: unknown): number | null {\n const amount = finiteNumber(value);\n return amount != null && amount > 0 ? amount : null;\n}\n\nfunction formatFloorFact(value: unknown): string | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value === 0 ? \"Térreo\" : String(value);\n }\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n if (!trimmed) return null;\n const parsed = Number(trimmed);\n if (Number.isFinite(parsed) && trimmed === String(parsed)) {\n return parsed === 0 ? \"Térreo\" : trimmed;\n }\n return trimmed;\n}\n\nfunction httpsUrl(raw: string | null | undefined): string | null {\n if (!raw) return null;\n try {\n const url = new URL(raw);\n if (url.protocol !== \"https:\") return null;\n return url.toString();\n } catch {\n return null;\n }\n}\n\nfunction isVideoPlatformUrl(url: string): boolean {\n const host = new URL(url).hostname.toLowerCase();\n return VIDEO_HOST_HINTS.some(\n (hint) => host === hint || host.endsWith(`.${hint}`)\n );\n}\n\nfunction overlayKind(\n type: string | undefined,\n src: string\n): \"video\" | \"tour\" | null {\n if (type === \"image\" || type === \"photo\") return null;\n const host = new URL(src).hostname.toLowerCase();\n if (\n type === \"tour\" ||\n type === \"virtual_tour\" ||\n host.includes(\"matterport\")\n ) {\n return \"tour\";\n }\n if (isVideoPlatformUrl(src) || type === \"video\") return \"video\";\n return type ? \"tour\" : null;\n}\n\n/** Mirrors `@garagem/ui` `extractVimeoVideoId` — site-sdk cannot import that package. */\nconst VIMEO_ID_RE =\n /vimeo\\.com\\/(?:video\\/|channels\\/[^/]+\\/|groups\\/[^/]+\\/videos\\/)?(\\d+)/i;\nconst WISTIA_ID_RE = /\\/(?:medias|embed\\/(?:iframe|medias))\\/([a-zA-Z0-9]+)/i;\n\nfunction vimeoPrivacyHash(url: URL, id: string): string | null {\n const fromQuery = url.searchParams.get(\"h\");\n if (fromQuery) return fromQuery;\n const segments = url.pathname.split(\"/\").filter(Boolean);\n const idIndex = segments.indexOf(id);\n const next = idIndex >= 0 ? segments[idIndex + 1] : undefined;\n return next && /^[a-f0-9]{6,12}$/i.test(next) ? next : null;\n}\n\nfunction embedSrc(src: string): string {\n const url = new URL(src);\n const host = url.hostname.toLowerCase();\n if (host === \"youtu.be\" || host.endsWith(\".youtu.be\")) {\n const id = url.pathname.replace(/^\\//, \"\").split(\"/\")[0];\n return id ? `https://www.youtube.com/embed/${id}` : src;\n }\n if (host.includes(\"youtube.com\")) {\n const id = url.searchParams.get(\"v\") || url.pathname.split(\"/\").pop();\n return id ? `https://www.youtube.com/embed/${id}` : src;\n }\n if (host.includes(\"player.vimeo.com\")) return src;\n if (host.includes(\"vimeo.com\")) {\n const id = src.match(VIMEO_ID_RE)?.[1];\n if (!id) return src;\n const hash = vimeoPrivacyHash(url, id);\n return hash\n ? `https://player.vimeo.com/video/${id}?h=${encodeURIComponent(hash)}`\n : `https://player.vimeo.com/video/${id}`;\n }\n if (host.includes(\"wistia.com\") || host.includes(\"wistia.net\")) {\n if (src.includes(\"/embed/iframe/\")) return src;\n const id = src.match(WISTIA_ID_RE)?.[1];\n return id ? `https://fast.wistia.net/embed/iframe/${id}` : src;\n }\n return src;\n}\n\nfunction crumbLabel(segment: string): string {\n const mapped = BREADCRUMB_LABELS[segment];\n if (mapped) return mapped;\n if (/^[a-z]{2}$/.test(segment)) return segment.toUpperCase();\n return segment\n .split(\"-\")\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nexport function listingValues(listing: {\n price?: number | null;\n priceVisibility?: string | null;\n property?: { condoFee?: number | null; propertyTax?: number | null } | null;\n}): ListingValue[] {\n const values: ListingValue[] = [\n {\n key: \"price\",\n label: \"Preço\",\n text:\n listing.priceVisibility === \"private\"\n ? \"Sob consulta\"\n : formatListingPrice(listing.price),\n },\n ];\n const condoFee = positiveCount(listing.property?.condoFee);\n if (condoFee != null) {\n values.push({\n key: \"condoFee\",\n label: \"Condomínio\",\n text: formatListingPrice(condoFee),\n });\n }\n const propertyTax = positiveCount(listing.property?.propertyTax);\n if (propertyTax != null) {\n values.push({\n key: \"propertyTax\",\n label: \"IPTU\",\n text: formatListingPrice(propertyTax),\n });\n }\n return values;\n}\n\nexport function listingFacts(listing: {\n property?: {\n totalArea?: number | null;\n usableArea?: number | null;\n bedrooms?: number | null;\n suites?: number | null;\n parkingSpaces?: number | null;\n rooms?: number | null;\n floor?: number | string | null;\n } | null;\n}): ListingFact[] {\n const property = listing.property ?? {};\n const facts: ListingFact[] = [];\n const area = formatAreaM2(\n positiveCount(property.usableArea) ?? positiveCount(property.totalArea)\n );\n if (area) facts.push({ key: \"area\", label: \"Área\", text: area });\n const bedrooms = positiveCount(property.bedrooms);\n if (bedrooms != null) {\n facts.push({\n key: \"bedrooms\",\n label: \"Dormitórios\",\n text: String(bedrooms),\n });\n }\n const suites = positiveCount(property.suites);\n if (suites != null) {\n facts.push({ key: \"suites\", label: \"Suítes\", text: String(suites) });\n }\n const parking = positiveCount(property.parkingSpaces);\n if (parking != null) {\n facts.push({ key: \"parkingSpaces\", label: \"Vagas\", text: String(parking) });\n }\n const rooms = positiveCount(property.rooms);\n if (rooms != null) {\n facts.push({ key: \"rooms\", label: \"Salas\", text: String(rooms) });\n }\n const floorText = formatFloorFact(property.floor);\n if (floorText) {\n facts.push({ key: \"floor\", label: \"Andar\", text: floorText });\n }\n return facts;\n}\n\nexport function listingMapsHref(\n location: ListingLocation | null | undefined\n): string | null {\n if (!location) return null;\n const lat = finiteNumber(location.coordinates?.lat);\n const lng = finiteNumber(location.coordinates?.lng);\n if (lat != null && lng != null && !(lat === 0 && lng === 0)) {\n return `https://www.google.com/maps/search/?api=1&query=${lat},${lng}`;\n }\n const query = [\n [location.street, location.number].filter(Boolean).join(\" \").trim(),\n location.neighborhood,\n location.city,\n location.state,\n ]\n .map((part) => (part ? String(part).trim() : \"\"))\n .filter(Boolean)\n .join(\", \");\n if (!query) return null;\n return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;\n}\n\nexport function listingLocationBlock(\n listing: { location?: ListingLocation | null } | null | undefined\n): ListingLocationBlock | null {\n const location = listing?.location;\n if (!location) return null;\n const street = [location.street, location.number]\n .filter(Boolean)\n .join(\" \")\n .trim();\n const label = street || listingLocationLabel(location);\n const mapsHref = listingMapsHref(location);\n if (!label && !mapsHref) return null;\n return { label, mapsHref };\n}\n\nexport function listingBreadcrumb(listing: {\n path?: string | null;\n listingCode?: string | null;\n id?: string | null;\n}): ListingBreadcrumbCrumb[] {\n const path = listingPublicPath(listing);\n const segments = path.split(\"/\").filter(Boolean);\n if (segments[0] !== \"imoveis\") return [];\n const crumbs: ListingBreadcrumbCrumb[] = [\n { label: \"Imóveis\", href: \"/imoveis\" },\n ];\n let href = \"/imoveis\";\n for (const segment of segments.slice(1)) {\n if (segment.startsWith(\"id-\")) break;\n href = `${href}/${segment}`;\n if (isListingDetailPath(href)) continue;\n crumbs.push({ label: crumbLabel(segment), href });\n }\n return crumbs;\n}\n\nexport function listingDescriptionPreview(\n description: string | null | undefined,\n expanded = false\n): ListingDescriptionPreview | null {\n const text = description?.trim() ?? \"\";\n if (!text) return null;\n if (text.length <= LISTING_DESCRIPTION_CLAMP) {\n return { text, truncated: false, toggleLabel: null };\n }\n if (expanded) {\n return { text, truncated: true, toggleLabel: \"Ler menos\" };\n }\n return {\n text: `${text.slice(0, LISTING_DESCRIPTION_CLAMP).trimEnd()}…`,\n truncated: true,\n toggleLabel: \"Ler mais\",\n };\n}\n\nexport function listingMediaOverlays(listing: {\n media?: ListingMedia[] | null;\n}): ListingMediaOverlay[] {\n const overlays: ListingMediaOverlay[] = [];\n const seen = new Set<\"video\" | \"tour\">();\n for (const item of listing.media ?? []) {\n const src = httpsUrl(item.src);\n if (!src) continue;\n const kind = overlayKind(item.type, src);\n if (!kind || seen.has(kind)) continue;\n seen.add(kind);\n overlays.push({\n key: kind,\n hash: kind,\n title: kind === \"video\" ? \"Vídeo\" : \"Tour virtual\",\n href: `#${kind}`,\n embedSrc: embedSrc(src),\n });\n }\n return overlays;\n}\n\nexport function listingDetailModel(\n listing: Pick<\n ListingDetail,\n \"id\" | \"listingCode\" | \"path\" | \"price\" | \"priceVisibility\" | \"description\"\n > & {\n property?: ListingDetail[\"property\"] | null;\n location?: ListingLocation | null;\n media?: ListingMedia[] | null;\n },\n options?: { descriptionExpanded?: boolean }\n): ListingDetailModel {\n const text = listing.description?.trim() ?? \"\";\n const description = text || null;\n const truncated =\n description != null && description.length > LISTING_DESCRIPTION_CLAMP;\n const expanded = options?.descriptionExpanded === true;\n return {\n breadcrumb: listingBreadcrumb(listing),\n values: listingValues(listing),\n facts: listingFacts(listing),\n location: listingLocationBlock(listing),\n description,\n descriptionTruncated: truncated,\n descriptionToggleLabel: truncated\n ? expanded\n ? \"Ler menos\"\n : \"Ler mais\"\n : null,\n mediaOverlays: listingMediaOverlays(listing),\n };\n}\n","import {\n listingAmenityGroups,\n type AmenityLabelDictionary,\n type ListingAmenityGroup,\n type ListingAmenitySource,\n} from \"./amenity-labels\";\nimport { listingFacts, listingValues } from \"./listing-detail\";\nimport type { ListingFact, ListingValue } from \"./listing-detail\";\nimport type { ListingDetail } from \"./types\";\n\nfunction visibleText(value: string | null | undefined): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"undefined\" || trimmed === \"null\") return null;\n return trimmed;\n}\n\nfunction visibleRows<T extends { label: string; text: string }>(\n rows: readonly T[]\n): T[] {\n return rows.filter((row) => {\n const label = visibleText(row.label);\n const text = visibleText(row.text);\n return label != null && text != null;\n });\n}\n\nexport type ListingDetailFieldsModel = {\n facts: ListingFact[];\n values: ListingValue[];\n amenityGroups: ListingAmenityGroup[];\n};\n\nexport type ListingDetailFieldsSource = ListingAmenitySource &\n Pick<ListingDetail, \"price\" | \"priceVisibility\"> & {\n property?: ListingDetail[\"property\"] | null;\n };\n\n/**\n * Facts, values, and amenity groups that are safe to render: every row has\n * a real label and text. Missing condo/IPTU/empty facts never appear.\n */\nexport function listingDetailFieldsModel(\n listing: ListingDetailFieldsSource,\n dictionary?: AmenityLabelDictionary\n): ListingDetailFieldsModel {\n return {\n facts: visibleRows(listingFacts(listing)),\n values: visibleRows(listingValues(listing)),\n amenityGroups: listingAmenityGroups(listing, dictionary)\n .map((group) => ({\n ...group,\n labels: group.labels\n .map((label) => visibleText(label))\n .filter((label): label is string => label != null),\n }))\n .filter((group) => group.labels.length > 0),\n };\n}\n","\"use client\";\n\nimport type { CSSProperties, ReactElement } from \"react\";\n\nimport type { AmenityLabelDictionary } from \"../amenity-labels\";\nimport {\n listingDetailFieldsModel,\n type ListingDetailFieldsSource,\n} from \"../listing-detail-fields\";\nimport { cn } from \"./cn\";\n\nexport type ListingDetailFieldsClassNames = {\n root?: string;\n facts?: string;\n fact?: string;\n values?: string;\n value?: string;\n amenityGroup?: string;\n amenityTitle?: string;\n amenityList?: string;\n amenityLabel?: string;\n};\n\nexport type ListingDetailFieldsProps = {\n listing: ListingDetailFieldsSource;\n dictionary?: AmenityLabelDictionary | null;\n className?: string;\n classNames?: ListingDetailFieldsClassNames;\n style?: CSSProperties;\n};\n\n/**\n * Renders listing facts, values, and amenities. Omits empty rows so JSX\n * never prints `undefined`. Theme via `data-slot` / classNames — do not\n * reimplement these blocks in generated pages.\n */\nexport function ListingDetailFields({\n listing,\n dictionary,\n className,\n classNames,\n style,\n}: ListingDetailFieldsProps): ReactElement | null {\n const model = listingDetailFieldsModel(listing, dictionary ?? undefined);\n if (\n model.facts.length === 0 &&\n model.values.length === 0 &&\n model.amenityGroups.length === 0\n ) {\n return null;\n }\n return (\n <div\n data-slot=\"listing-detail-fields\"\n className={cn(className, classNames?.root)}\n style={style}\n >\n {model.facts.length > 0 ? (\n <ul data-slot=\"listing-facts\" className={classNames?.facts}>\n {model.facts.map((fact) => (\n <li\n key={fact.key}\n data-slot=\"listing-fact\"\n data-key={fact.key}\n className={classNames?.fact}\n >\n <span data-slot=\"listing-fact-label\">{fact.label}</span>\n <span data-slot=\"listing-fact-text\">{fact.text}</span>\n </li>\n ))}\n </ul>\n ) : null}\n {model.values.length > 0 ? (\n <dl data-slot=\"listing-values\" className={classNames?.values}>\n {model.values.map((value) => (\n <div\n key={value.key}\n data-slot=\"listing-value\"\n data-key={value.key}\n className={classNames?.value}\n >\n <dt data-slot=\"listing-value-label\">{value.label}</dt>\n <dd data-slot=\"listing-value-text\">{value.text}</dd>\n </div>\n ))}\n </dl>\n ) : null}\n {model.amenityGroups.map((group) => (\n <section\n key={group.key}\n data-slot=\"listing-amenities\"\n data-key={group.key}\n className={classNames?.amenityGroup}\n >\n <h2\n data-slot=\"listing-amenities-title\"\n className={classNames?.amenityTitle}\n >\n {group.title}\n </h2>\n <ul\n data-slot=\"listing-amenities-list\"\n className={classNames?.amenityList}\n >\n {group.labels.map((label) => (\n <li\n key={label}\n data-slot=\"listing-amenity-label\"\n className={classNames?.amenityLabel}\n >\n {label}\n </li>\n ))}\n </ul>\n </section>\n ))}\n </div>\n );\n}\n","\"use client\";\n\nimport type { ReactElement } from \"react\";\n\nimport { SearchChromeStyles } from \"./styles\";\n\nexport function ResultsSkeleton({\n className,\n}: {\n className?: string;\n}): ReactElement {\n return (\n <>\n <SearchChromeStyles />\n <div data-slot=\"search-skeleton\" className={className}>\n {Array.from({ length: 6 }, (_, i) => (\n <div key={i} data-slot=\"search-skeleton-card\">\n <div data-slot=\"search-skeleton-block\" data-kind=\"media\" />\n <div data-slot=\"search-skeleton-body\">\n <div data-slot=\"search-skeleton-block\" data-kind=\"line-lg\" />\n <div data-slot=\"search-skeleton-block\" data-kind=\"line-md\" />\n <div data-slot=\"search-skeleton-block\" data-kind=\"line-sm\" />\n </div>\n </div>\n ))}\n </div>\n </>\n );\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { usePathname, useRouter, useSearchParams } from \"next/navigation\";\n\nimport { getSearchUi, queryListings } from \"../fetchers\";\nimport { coerceSiteId, normalizeBaseUrl } from \"../internal/url\";\nimport {\n applyPathFilter,\n buildQueryListingsParams,\n canonicalizeSearchHref,\n clearStagedPathFilters,\n hrefForAppliedChange,\n hrefForPathFilters,\n readPublicSearch,\n type LocationNameTables,\n} from \"../search-engine\";\nimport type { SearchPathFilters, SearchUi } from \"../types\";\nimport type {\n PublicSearchState,\n SiteIdInput,\n UsePublicSearchOptions,\n} from \"./types\";\n\nasync function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {\n const value = typeof siteId === \"function\" ? siteId() : siteId;\n return coerceSiteId(value);\n}\n\nfunction currentHref(pathname: string, search: string): string {\n return search ? `${pathname}?${search}` : pathname;\n}\n\nexport function usePublicSearch(\n options: UsePublicSearchOptions\n): PublicSearchState {\n const { siteId, baseUrl } = options;\n const router = useRouter();\n const pathname = usePathname() || \"/imoveis\";\n const searchParams = useSearchParams();\n const search = searchParams.toString();\n\n const siteIdRef = useRef(siteId);\n siteIdRef.current = siteId;\n const siteIdToken = typeof siteId === \"string\" ? siteId : null;\n\n const [catalogId, setCatalogId] = useState<string | null>(null);\n const [schema, setSchema] = useState<SearchUi | null>(null);\n const [listings, setListings] = useState<PublicSearchState[\"listings\"]>([]);\n const [page, setPage] = useState(1);\n const [total, setTotal] = useState(0);\n const [totalPages, setTotalPages] = useState(1);\n const [loading, setLoading] = useState(true);\n const [qDraft, setQDraft] = useState(\"\");\n const [staged, setStaged] = useState<SearchPathFilters>({});\n const [locationNames, setLocationNames] = useState<LocationNameTables | null>(\n null\n );\n\n const parsed = useMemo(\n () => readPublicSearch(pathname, search, schema?.dictionary),\n [pathname, search, schema?.dictionary]\n );\n\n useEffect(() => {\n setQDraft(parsed.applied.query || \"\");\n }, [parsed.applied.query]);\n\n const resetStagedFromUrl = useCallback(() => {\n setStaged({ ...parsed.pathFilters });\n }, [parsed.pathFilters]);\n\n useEffect(() => {\n setStaged({ ...parsed.pathFilters });\n }, [parsed.pathFilters]);\n\n const locationsRef = useRef<LocationNameTables | null>(null);\n\n useEffect(() => {\n if (!schema) return;\n const canonical = canonicalizeSearchHref(\n pathname,\n search,\n schema.dictionary\n );\n if (canonical) router.replace(canonical);\n }, [pathname, search, schema, router]);\n\n useEffect(() => {\n let active = true;\n setCatalogId(null);\n setSchema(null);\n setListings([]);\n setLoading(true);\n resolveSiteIdInput(siteIdRef.current)\n .then((id) => {\n if (active) setCatalogId(id);\n })\n .catch(() => {\n if (active) setLoading(false);\n });\n return () => {\n active = false;\n };\n }, [baseUrl, siteIdToken]);\n\n useEffect(() => {\n if (!catalogId) return;\n const id = catalogId;\n let active = true;\n locationsRef.current = null;\n setLocationNames(null);\n setSchema(null);\n setListings([]);\n setLoading(true);\n async function loadSchema() {\n try {\n const nextSchema = await getSearchUi({ siteId: id, baseUrl });\n if (!active) return;\n let locations: LocationNameTables | null = null;\n if (nextSchema.locationsPath.startsWith(\"/\")) {\n try {\n const response = await fetch(\n `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`\n );\n if (response.ok) {\n locations = (await response.json()) as LocationNameTables;\n }\n } catch {\n locations = null;\n }\n }\n if (!active) return;\n locationsRef.current = locations;\n setLocationNames(locations);\n setSchema(nextSchema);\n } catch {\n if (active) {\n locationsRef.current = null;\n setLocationNames(null);\n setSchema(null);\n setLoading(false);\n }\n }\n }\n loadSchema();\n return () => {\n active = false;\n };\n }, [baseUrl, catalogId]);\n\n useEffect(() => {\n if (!schema || !catalogId) return;\n const currentSchema = schema;\n const id = catalogId;\n let active = true;\n async function loadListings() {\n setLoading(true);\n try {\n const { pathFilters, applied } = readPublicSearch(\n pathname,\n search,\n currentSchema.dictionary\n );\n const response = await queryListings({\n siteId: id,\n baseUrl,\n params: buildQueryListingsParams(\n pathFilters,\n applied,\n currentSchema,\n locationsRef.current\n ),\n });\n if (!active) return;\n setListings(response.listings || []);\n setPage(response.page || 1);\n setTotal(response.total || 0);\n setTotalPages(response.totalPages || 1);\n } catch {\n if (active) {\n setListings([]);\n setPage(1);\n setTotal(0);\n setTotalPages(1);\n }\n } finally {\n if (active) setLoading(false);\n }\n }\n loadListings();\n return () => {\n active = false;\n };\n }, [pathname, search, baseUrl, schema, catalogId]);\n\n const go = useCallback(\n (href: string) => {\n if (href && href !== currentHref(pathname, search)) router.push(href);\n },\n [pathname, search, router]\n );\n\n const applyFilter = useCallback(\n (filterId: string, value: unknown) => {\n if (!schema) return;\n go(\n hrefForPathFilters(\n pathname,\n search,\n schema.dictionary,\n applyPathFilter(parsed.pathFilters, filterId, value)\n )\n );\n },\n [go, pathname, search, schema, parsed.pathFilters]\n );\n\n const stageFilter = useCallback((filterId: string, value: unknown) => {\n setStaged((current) => applyPathFilter(current, filterId, value));\n }, []);\n\n const applyStaged = useCallback(() => {\n if (!schema) return;\n go(hrefForPathFilters(pathname, search, schema.dictionary, staged));\n }, [go, pathname, search, schema, staged]);\n\n const clearStaged = useCallback(() => {\n setStaged((current) => clearStagedPathFilters(current));\n }, []);\n\n const submitQuery = useCallback(() => {\n if (!schema) return;\n go(\n hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"query\",\n query: qDraft,\n })\n );\n }, [go, pathname, search, schema, qDraft]);\n\n const clearQuery = useCallback(() => {\n setQDraft(\"\");\n if (!schema) return;\n go(\n hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"query\",\n query: \"\",\n })\n );\n }, [go, pathname, search, schema]);\n\n const setSort = useCallback(\n (sort: string | null) => {\n if (!schema) return;\n go(\n hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"sort\",\n sort,\n })\n );\n },\n [go, pathname, search, schema]\n );\n\n const hrefForPage = useCallback(\n (nextPage: number) => {\n if (!schema) return pathname;\n return hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"page\",\n page: nextPage,\n });\n },\n [pathname, search, schema]\n );\n\n return {\n schema,\n listings,\n page,\n total,\n totalPages,\n loading,\n pathname,\n search,\n pathFilters: parsed.pathFilters,\n applied: parsed.applied,\n qDraft,\n setQDraft,\n staged,\n setStaged,\n resetStagedFromUrl,\n applyFilter,\n stageFilter,\n applyStaged,\n clearStaged,\n submitQuery,\n clearQuery,\n setSort,\n hrefForPage,\n go,\n locationNames,\n };\n}\n","import type { ListingFilters } from \"../types\";\n\n/** Default base URL — the public Garagem API. Override via `baseUrl`. */\nexport const DEFAULT_BASE_URL = \"https://app.garagem.ai\";\n\nexport function normalizeBaseUrl(baseUrl: string | undefined): string {\n const url = baseUrl ?? DEFAULT_BASE_URL;\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n/**\n * v0 often writes `getListings({ siteId: resolveSiteId(host) })` without\n * await, which interpolates as `/api/sites/[object Promise]/listings`.\n */\nexport async function coerceSiteId(siteId: unknown): Promise<string> {\n const raw =\n typeof siteId === \"function\" ? (siteId as () => unknown)() : siteId;\n const value = await Promise.resolve(raw);\n if (typeof value !== \"string\" || !value.trim()) {\n throw new TypeError(\n \"Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings.\"\n );\n }\n return value;\n}\n\n/**\n * Serialize listing filters into URLSearchParams. Skips undefined/null\n * values so the URL stays clean. Kept separate from the fetcher so it's\n * testable in isolation.\n */\nexport function buildListingFiltersQuery(\n filters: ListingFilters | undefined\n): URLSearchParams {\n const params = new URLSearchParams();\n if (!filters) return params;\n\n if (filters.limit != null) params.set(\"limit\", String(filters.limit));\n if (filters.offset != null) params.set(\"offset\", String(filters.offset));\n if (filters.businessType) params.set(\"businessType\", filters.businessType);\n if (filters.propertyType) params.set(\"propertyType\", filters.propertyType);\n if (filters.city) params.set(\"city\", filters.city);\n if (filters.neighborhood) params.set(\"neighborhood\", filters.neighborhood);\n if (filters.minPrice != null)\n params.set(\"minPrice\", String(filters.minPrice));\n if (filters.maxPrice != null)\n params.set(\"maxPrice\", String(filters.maxPrice));\n\n return params;\n}\n","import type {\n CmsCollection,\n CmsEntriesResult,\n CmsEntry,\n Listing,\n ListingDetail,\n ListingFilters,\n ListingsResult,\n QueryListingsParams,\n QueryListingsResult,\n RequestNextOptions,\n SearchListingsParams,\n SearchListingsResult,\n SearchUi,\n SimilarListingsResult,\n Site,\n} from \"./types\";\nimport { listingLookupKey } from \"./listing-path\";\nimport {\n buildListingFiltersQuery,\n coerceSiteId,\n normalizeBaseUrl,\n} from \"./internal/url\";\n\n/** Custom fetch implementation. Defaults to the global `fetch`. */\nexport type FetchLike = typeof fetch;\n\ninterface BaseOptions {\n /** Garagem API base URL. Defaults to `https://app.garagem.ai`. */\n baseUrl?: string;\n /** Override the fetch implementation (testing, edge runtimes, retries). */\n fetch?: FetchLike;\n /**\n * Next.js App Router caching hints. Ignored on runtimes that don't\n * understand them.\n */\n next?: RequestNextOptions;\n}\n\nexport interface GetListingsOptions extends BaseOptions {\n siteId: string;\n filters?: ListingFilters;\n}\n\nexport interface GetListingOptions extends BaseOptions {\n siteId: string;\n listingId: string;\n}\n\nexport interface GetSiteOptions extends BaseOptions {\n /** Look up by site ID, or… */\n siteId?: string;\n /** …by domain. Exactly one of `siteId` / `domain` must be provided. */\n domain?: string;\n}\n\nexport interface SearchListingsOptions extends BaseOptions {\n siteId: string;\n params: SearchListingsParams;\n}\n\nexport interface GetSearchUiOptions extends BaseOptions {\n siteId: string;\n}\n\nexport interface QueryListingsOptions extends BaseOptions {\n siteId: string;\n params?: QueryListingsParams;\n}\n\nexport interface GetSimilarListingsOptions extends BaseOptions {\n siteId: string;\n listingId: string;\n /** Max similar cards to return (API default 6, cap 12). */\n limit?: number;\n}\n\nexport interface GetCmsCollectionsOptions extends BaseOptions {\n siteId: string;\n}\n\nexport interface GetCmsCollectionOptions extends BaseOptions {\n siteId: string;\n slug: string;\n}\n\nexport interface GetCmsEntriesOptions extends BaseOptions {\n siteId: string;\n collection: string;\n limit?: number;\n offset?: number;\n}\n\nexport interface GetCmsEntryOptions extends BaseOptions {\n siteId: string;\n collection: string;\n slug: string;\n}\n\ninterface FetchInit extends RequestInit {\n /**\n * Next.js attaches this on `fetch` (App Router). Adding it here keeps\n * `RequestInit` typed without forcing consumers to install Next types.\n */\n next?: RequestNextOptions;\n}\n\n/** Shared JSON fetch for SDK helpers (not part of the public barrel). */\nexport async function callJson<T>(\n url: string,\n init: FetchInit,\n fetchImpl: FetchLike\n): Promise<T> {\n const response = await fetchImpl(url, init);\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new GaragemSdkError(\n `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${\n text ? ` — ${text.slice(0, 200)}` : \"\"\n }`,\n { status: response.status, url }\n );\n }\n return (await response.json()) as T;\n}\n\n/** Error thrown when a fetcher hits a non-2xx response. */\nexport class GaragemSdkError extends Error {\n readonly status: number;\n readonly url: string;\n constructor(message: string, info: { status: number; url: string }) {\n super(message);\n this.name = \"GaragemSdkError\";\n this.status = info.status;\n this.url = info.url;\n }\n}\n\n/**\n * Fetch a paginated list of listings for a given site.\n *\n * @example\n * const { listings } = await getListings({\n * siteId: \"abc\",\n * filters: { city: \"São Paulo\", limit: 24 },\n * next: { revalidate: 300, tags: [`site:abc:listings`] },\n * });\n */\nexport async function getListings(\n options: GetListingsOptions\n): Promise<ListingsResult> {\n const { filters, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const params = buildListingFiltersQuery(filters);\n const qs = params.size > 0 ? `?${params.toString()}` : \"\";\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings${qs}`;\n\n const data = await callJson<{ listings?: Listing[]; total?: number }>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return {\n listings: data.listings ?? [],\n total: data.total ?? 0,\n };\n}\n\n/**\n * Fetch a single listing's full detail (amenities, gallery, building).\n * `listingId` accepts a code, UUID, or `id-{code}` URL segment.\n */\nexport async function getListing(\n options: GetListingOptions\n): Promise<ListingDetail> {\n const { listingId: rawListingId, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const listingId = listingLookupKey(rawListingId ?? \"\");\n if (!listingId || listingId === \"undefined\" || listingId === \"null\") {\n throw new TypeError(\"getListing: `listingId` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(\n listingId\n )}`;\n\n return callJson<ListingDetail>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Resolve a site's public profile by ID or by domain. Returns `null`\n * when the site does not exist or the host is unrecognized.\n *\n * @example\n * const site = await getSite({ domain: \"imobiliariax.com.br\" });\n * if (!site) return notFound();\n */\nexport async function getSite(options: GetSiteOptions): Promise<Site | null> {\n const { domain, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = options.siteId\n ? await coerceSiteId(options.siteId)\n : undefined;\n if (!siteId && !domain) {\n throw new TypeError(\n \"getSite: provide exactly one of `siteId` or `domain`.\"\n );\n }\n if (siteId && domain) {\n throw new TypeError(\n \"getSite: provide only one of `siteId` or `domain`, not both.\"\n );\n }\n\n const base = normalizeBaseUrl(baseUrl);\n const params = new URLSearchParams();\n if (siteId) params.set(\"siteId\", siteId);\n if (domain) params.set(\"domain\", domain);\n const url = `${base}/api/sites/resolve?${params.toString()}`;\n\n const f = fetchImpl ?? fetch;\n const response = await f(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n next,\n } as FetchInit);\n if (response.status === 404) return null;\n if (!response.ok) {\n throw new GaragemSdkError(\n `Garagem SDK: getSite failed (${response.status}) for ${url}`,\n { status: response.status, url }\n );\n }\n const data = (await response.json()) as {\n id: string;\n name: string;\n domain: string | null;\n tenantId: string;\n };\n return {\n id: data.id,\n name: data.name,\n domain: data.domain,\n tenantId: data.tenantId,\n };\n}\n\n/**\n * Advanced search escape hatch.\n *\n * Calls `POST /api/sites/{siteId}/search` directly and returns the raw\n * Typesense response (`{ found, page, hits: [{ document, ... }], ... }`).\n * Use when `queryListings` isn't expressive enough — faceted search,\n * multi-field sort, custom grouping, etc.\n *\n * @example\n * const result = await searchListings({\n * siteId: \"abc\",\n * params: {\n * q: \"frente mar\",\n * query_by: \"title,description,neighborhood\",\n * filter_by: \"businessType:=sale && bedrooms:>=3\",\n * sort_by: \"price:asc\",\n * per_page: 24,\n * page: 1,\n * facet_by: \"neighborhood,propertyType\",\n * },\n * });\n * for (const hit of result.hits) {\n * console.log(hit.document, hit.highlight);\n * }\n */\nexport async function searchListings<TDocument = Record<string, unknown>>(\n options: SearchListingsOptions\n): Promise<SearchListingsResult<TDocument>> {\n const { params, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!params || typeof params.q !== \"string\") {\n throw new TypeError(\n \"Garagem SDK: searchListings requires `params.q` (Typesense query string).\"\n );\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search`;\n return callJson<SearchListingsResult<TDocument>>(\n url,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(params),\n next,\n },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Tenant search schema: filters, slugs, sort tokens, defaultLimit 12.\n * Use this to render the search UI — do not hardcode property types.\n */\nexport async function getSearchUi(\n options: GetSearchUiOptions\n): Promise<SearchUi> {\n const { baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;\n return callJson<SearchUi>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Friendly catalog search (editor combinators). Prefer this over\n * `searchListings` — that helper is a raw Typesense escape hatch.\n */\nexport async function queryListings(\n options: QueryListingsOptions\n): Promise<QueryListingsResult> {\n const { params, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;\n return callJson<QueryListingsResult>(\n url,\n {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params ?? {}),\n next,\n },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Fetch similar listings for a detail page carousel.\n * Returns an empty list when the reference listing is missing.\n */\nexport async function getSimilarListings(\n options: GetSimilarListingsOptions\n): Promise<SimilarListingsResult> {\n const {\n listingId: rawListingId,\n limit,\n baseUrl,\n fetch: fetchImpl,\n next,\n } = options;\n const siteId = await coerceSiteId(options.siteId);\n const listingId = listingLookupKey(rawListingId ?? \"\");\n if (!listingId || listingId === \"undefined\" || listingId === \"null\") {\n throw new TypeError(\"getSimilarListings: `listingId` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const params = new URLSearchParams();\n if (typeof limit === \"number\" && Number.isFinite(limit) && limit > 0) {\n params.set(\"limit\", String(Math.floor(limit)));\n }\n const qs = params.size > 0 ? `?${params.toString()}` : \"\";\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(\n listingId\n )}/similar${qs}`;\n\n const data = await callJson<{ listings?: Listing[]; total?: number }>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return {\n listings: data.listings ?? [],\n total: data.total ?? 0,\n };\n}\n\n/** List CMS collections for a site. */\nexport async function getCmsCollections(\n options: GetCmsCollectionsOptions\n): Promise<CmsCollection[]> {\n const { baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections`;\n const data = await callJson<{ collections?: CmsCollection[] }>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return data.collections ?? [];\n}\n\n/** Fetch one CMS collection schema by slug. */\nexport async function getCmsCollection(\n options: GetCmsCollectionOptions\n): Promise<CmsCollection> {\n const { slug, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!slug) {\n throw new TypeError(\"getCmsCollection: `slug` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections/${encodeURIComponent(\n slug\n )}`;\n const data = await callJson<{ collection?: CmsCollection } | CmsCollection>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n if (\n data &&\n typeof data === \"object\" &&\n \"collection\" in data &&\n data.collection\n ) {\n return data.collection;\n }\n return data as CmsCollection;\n}\n\n/** List published CMS entries for a collection. */\nexport async function getCmsEntries(\n options: GetCmsEntriesOptions\n): Promise<CmsEntriesResult> {\n const {\n collection,\n limit,\n offset,\n baseUrl,\n fetch: fetchImpl,\n next,\n } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!collection) {\n throw new TypeError(\"getCmsEntries: `collection` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const params = new URLSearchParams();\n if (typeof limit === \"number\" && Number.isFinite(limit) && limit > 0) {\n params.set(\"limit\", String(Math.floor(limit)));\n }\n if (typeof offset === \"number\" && Number.isFinite(offset) && offset >= 0) {\n params.set(\"offset\", String(Math.floor(offset)));\n }\n const qs = params.size > 0 ? `?${params.toString()}` : \"\";\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/${encodeURIComponent(\n collection\n )}/entries${qs}`;\n\n const data = await callJson<Partial<CmsEntriesResult>>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return {\n entries: data.entries ?? [],\n total: data.total ?? 0,\n limit: data.limit ?? 0,\n offset: data.offset ?? 0,\n };\n}\n\n/** Fetch one published CMS entry by slug. */\nexport async function getCmsEntry(\n options: GetCmsEntryOptions\n): Promise<CmsEntry> {\n const { collection, slug, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!collection) {\n throw new TypeError(\"getCmsEntry: `collection` is required\");\n }\n if (!slug) {\n throw new TypeError(\"getCmsEntry: `slug` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/${encodeURIComponent(\n collection\n )}/entries/${encodeURIComponent(slug)}`;\n const data = await callJson<{ entry?: CmsEntry } | CmsEntry>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n if (data && typeof data === \"object\" && \"entry\" in data && data.entry) {\n return data.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;AACb;AAAA,QACE,qBAAqB,UAAU,QAAQ,OAAO,YAAY;AAAA,UACxD,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA,CAAC,IAAI,UAAU,QAAQ,MAAM;AAAA,EAC/B;AAEA,QAAM,kBAAc;AAAA,IAClB,CAAC,aAAqB;AACpB,UAAI,CAAC,OAAQ,QAAO;AACpB,aAAO,qBAAqB,UAAU,QAAQ,OAAO,YAAY;AAAA,QAC/D,MAAM;AAAA,QACN,MAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,IACA,CAAC,UAAU,QAAQ,MAAM;AAAA,EAC3B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,aAAa,OAAO;AAAA,IACpB,SAAS,OAAO;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["Link","parseAppliedSearchQuery","reduceAppliedSearchQuery","composeSearchPublicHref","composeSearchPublicPath","parseSearchPublicPath","parseSearchPublicPath","parseAppliedSearchQuery","composeSearchPublicPath","composeSearchPublicHref","reduceAppliedSearchQuery","import_jsx_runtime","import_jsx_runtime","import_react"]}
1
+ {"version":3,"sources":["../src/react/index.ts","../src/react/use-public-search.ts","../src/internal/url.ts","../src/fetchers.ts","../../search-url/types.ts","../../search-url/slugify.ts","../../search-url/catalog.ts","../../search-url/path.ts","../../search-url/applied-query.ts","../src/applied-query.ts","../src/loc-params.ts","../src/path.ts","../src/presentation.ts","../src/search-engine.ts","../src/react/staged-filters-mirror.ts"],"sourcesContent":["\"use client\";\n\nexport { usePublicSearch } from \"./use-public-search\";\nexport type {\n PublicSearchState,\n SiteIdInput,\n UsePublicSearchOptions,\n} from \"./types\";\n","\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { usePathname, useRouter, useSearchParams } from \"next/navigation\";\n\nimport { getSearchUi, queryListings } from \"../fetchers\";\nimport { coerceSiteId, normalizeBaseUrl } from \"../internal/url\";\nimport {\n applyPathFilter,\n buildQueryListingsParams,\n canonicalizeSearchHref,\n hrefForAppliedChange,\n hrefForPathFilters,\n readPublicSearch,\n type LocationNameTables,\n} from \"../search-engine\";\nimport type { SearchPathFilters, SearchUi } from \"../types\";\nimport type {\n PublicSearchState,\n SiteIdInput,\n UsePublicSearchOptions,\n} from \"./types\";\nimport { StagedFiltersMirror } from \"./staged-filters-mirror\";\n\nasync function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {\n const value = typeof siteId === \"function\" ? siteId() : siteId;\n return coerceSiteId(value);\n}\n\nfunction currentHref(pathname: string, search: string): string {\n return search ? `${pathname}?${search}` : pathname;\n}\n\nexport function usePublicSearch(\n options: UsePublicSearchOptions\n): PublicSearchState {\n const { siteId, baseUrl } = options;\n const router = useRouter();\n const pathname = usePathname() || \"/imoveis\";\n const searchParams = useSearchParams();\n const search = searchParams.toString();\n\n const siteIdRef = useRef(siteId);\n siteIdRef.current = siteId;\n const siteIdToken = typeof siteId === \"string\" ? siteId : null;\n\n const [catalogId, setCatalogId] = useState<string | null>(null);\n const [schema, setSchema] = useState<SearchUi | null>(null);\n const [listings, setListings] = useState<PublicSearchState[\"listings\"]>([]);\n const [page, setPage] = useState(1);\n const [total, setTotal] = useState(0);\n const [totalPages, setTotalPages] = useState(1);\n const [loading, setLoading] = useState(true);\n const [qDraft, setQDraft] = useState(\"\");\n const stagedMirrorRef = useRef(new StagedFiltersMirror());\n const [staged, setStagedState] = useState<SearchPathFilters>({});\n const [locationNames, setLocationNames] = useState<LocationNameTables | null>(\n null\n );\n\n const replaceStaged = useCallback((next: SearchPathFilters) => {\n stagedMirrorRef.current.replace(next);\n setStagedState(next);\n }, []);\n\n const parsed = useMemo(\n () => readPublicSearch(pathname, search, schema?.dictionary),\n [pathname, search, schema?.dictionary]\n );\n\n useEffect(() => {\n setQDraft(parsed.applied.query || \"\");\n }, [parsed.applied.query]);\n\n const resetStagedFromUrl = useCallback(() => {\n replaceStaged({ ...parsed.pathFilters });\n }, [parsed.pathFilters, replaceStaged]);\n\n useEffect(() => {\n replaceStaged({ ...parsed.pathFilters });\n }, [parsed.pathFilters, replaceStaged]);\n\n const locationsRef = useRef<LocationNameTables | null>(null);\n\n useEffect(() => {\n if (!schema) return;\n const canonical = canonicalizeSearchHref(\n pathname,\n search,\n schema.dictionary\n );\n if (canonical) router.replace(canonical);\n }, [pathname, search, schema, router]);\n\n useEffect(() => {\n let active = true;\n setCatalogId(null);\n setSchema(null);\n setListings([]);\n setLoading(true);\n resolveSiteIdInput(siteIdRef.current)\n .then((id) => {\n if (active) setCatalogId(id);\n })\n .catch(() => {\n if (active) setLoading(false);\n });\n return () => {\n active = false;\n };\n }, [baseUrl, siteIdToken]);\n\n useEffect(() => {\n if (!catalogId) return;\n const id = catalogId;\n let active = true;\n locationsRef.current = null;\n setLocationNames(null);\n setSchema(null);\n setListings([]);\n setLoading(true);\n async function loadSchema() {\n try {\n const nextSchema = await getSearchUi({ siteId: id, baseUrl });\n if (!active) return;\n let locations: LocationNameTables | null = null;\n if (nextSchema.locationsPath.startsWith(\"/\")) {\n try {\n const response = await fetch(\n `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`\n );\n if (response.ok) {\n locations = (await response.json()) as LocationNameTables;\n }\n } catch {\n locations = null;\n }\n }\n if (!active) return;\n locationsRef.current = locations;\n setLocationNames(locations);\n setSchema(nextSchema);\n } catch {\n if (active) {\n locationsRef.current = null;\n setLocationNames(null);\n setSchema(null);\n setLoading(false);\n }\n }\n }\n loadSchema();\n return () => {\n active = false;\n };\n }, [baseUrl, catalogId]);\n\n useEffect(() => {\n if (!schema || !catalogId) return;\n const currentSchema = schema;\n const id = catalogId;\n let active = true;\n async function loadListings() {\n setLoading(true);\n try {\n const { pathFilters, applied } = readPublicSearch(\n pathname,\n search,\n currentSchema.dictionary\n );\n const response = await queryListings({\n siteId: id,\n baseUrl,\n params: buildQueryListingsParams(\n pathFilters,\n applied,\n currentSchema,\n locationsRef.current\n ),\n });\n if (!active) return;\n setListings(response.listings || []);\n setPage(response.page || 1);\n setTotal(response.total || 0);\n setTotalPages(response.totalPages || 1);\n } catch {\n if (active) {\n setListings([]);\n setPage(1);\n setTotal(0);\n setTotalPages(1);\n }\n } finally {\n if (active) setLoading(false);\n }\n }\n loadListings();\n return () => {\n active = false;\n };\n }, [pathname, search, baseUrl, schema, catalogId]);\n\n const go = useCallback(\n (href: string) => {\n if (href && href !== currentHref(pathname, search)) router.push(href);\n },\n [pathname, search, router]\n );\n\n const applyFilter = useCallback(\n (filterId: string, value: unknown) => {\n if (!schema) return;\n go(\n hrefForPathFilters(\n pathname,\n search,\n schema.dictionary,\n applyPathFilter(parsed.pathFilters, filterId, value)\n )\n );\n },\n [go, pathname, search, schema, parsed.pathFilters]\n );\n\n const setStaged = useCallback(\n (next: SearchPathFilters) => {\n replaceStaged(next);\n },\n [replaceStaged]\n );\n\n const stageFilter = useCallback((filterId: string, value: unknown) => {\n setStagedState(stagedMirrorRef.current.stage(filterId, value));\n }, []);\n\n const applyStaged = useCallback(() => {\n if (!schema) return;\n go(\n hrefForPathFilters(\n pathname,\n search,\n schema.dictionary,\n stagedMirrorRef.current.value\n )\n );\n }, [go, pathname, search, schema]);\n\n const clearStaged = useCallback(() => {\n setStagedState(stagedMirrorRef.current.clear());\n }, []);\n\n const submitQuery = useCallback(() => {\n if (!schema) return;\n go(\n hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"query\",\n query: qDraft,\n })\n );\n }, [go, pathname, search, schema, qDraft]);\n\n const clearQuery = useCallback(() => {\n setQDraft(\"\");\n if (!schema) return;\n go(\n hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"query\",\n query: \"\",\n })\n );\n }, [go, pathname, search, schema]);\n\n const setSort = useCallback(\n (sort: string | null) => {\n if (!schema) return;\n go(\n hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"sort\",\n sort,\n })\n );\n },\n [go, pathname, search, schema]\n );\n\n const hrefForPage = useCallback(\n (nextPage: number) => {\n if (!schema) return pathname;\n return hrefForAppliedChange(pathname, search, schema.dictionary, {\n type: \"page\",\n page: nextPage,\n });\n },\n [pathname, search, schema]\n );\n\n return {\n schema,\n listings,\n page,\n total,\n totalPages,\n loading,\n pathname,\n search,\n pathFilters: parsed.pathFilters,\n applied: parsed.applied,\n qDraft,\n setQDraft,\n staged,\n setStaged,\n resetStagedFromUrl,\n applyFilter,\n stageFilter,\n applyStaged,\n clearStaged,\n submitQuery,\n clearQuery,\n setSort,\n hrefForPage,\n go,\n locationNames,\n };\n}\n","import type { ListingFilters } from \"../types\";\n\n/** Default base URL — the public Garagem API. Override via `baseUrl`. */\nexport const DEFAULT_BASE_URL = \"https://app.garagem.ai\";\nexport const DEFAULT_RESOLVE_BASE_URL = \"https://cdn.fndn.ai/site\";\n\nexport function normalizeBaseUrl(baseUrl: string | undefined): string {\n const url = baseUrl ?? DEFAULT_BASE_URL;\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\n/**\n * v0 often writes `getListings({ siteId: resolveSiteId(host) })` without\n * await, which interpolates as `/api/sites/[object Promise]/listings`.\n */\nexport async function coerceSiteId(siteId: unknown): Promise<string> {\n const raw =\n typeof siteId === \"function\" ? (siteId as () => unknown)() : siteId;\n const value = await Promise.resolve(raw);\n if (typeof value !== \"string\" || !value.trim()) {\n throw new TypeError(\n \"Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings.\"\n );\n }\n return value;\n}\n\n/**\n * Serialize listing filters into URLSearchParams. Skips undefined/null\n * values so the URL stays clean. Kept separate from the fetcher so it's\n * testable in isolation.\n */\nexport function buildListingFiltersQuery(\n filters: ListingFilters | undefined\n): URLSearchParams {\n const params = new URLSearchParams();\n if (!filters) return params;\n\n if (filters.limit != null) params.set(\"limit\", String(filters.limit));\n if (filters.offset != null) params.set(\"offset\", String(filters.offset));\n if (filters.businessType) params.set(\"businessType\", filters.businessType);\n if (filters.propertyType) params.set(\"propertyType\", filters.propertyType);\n if (filters.city) params.set(\"city\", filters.city);\n if (filters.neighborhood) params.set(\"neighborhood\", filters.neighborhood);\n if (filters.minPrice != null)\n params.set(\"minPrice\", String(filters.minPrice));\n if (filters.maxPrice != null)\n params.set(\"maxPrice\", String(filters.maxPrice));\n\n return params;\n}\n","import type {\n CmsCollection,\n CmsEntriesResult,\n CmsEntry,\n Listing,\n ListingDetail,\n ListingFilters,\n ListingsResult,\n QueryListingsParams,\n QueryListingsResult,\n RequestNextOptions,\n SearchListingsParams,\n SearchListingsResult,\n SearchUi,\n SimilarListingsResult,\n Site,\n} from \"./types\";\nimport { listingLookupKey } from \"./listing-path\";\nimport {\n buildListingFiltersQuery,\n coerceSiteId,\n DEFAULT_RESOLVE_BASE_URL,\n normalizeBaseUrl,\n} from \"./internal/url\";\n\n/** Custom fetch implementation. Defaults to the global `fetch`. */\nexport type FetchLike = typeof fetch;\n\ninterface BaseOptions {\n /** Garagem API base URL. Defaults to `https://app.garagem.ai`. */\n baseUrl?: string;\n /** Override the fetch implementation (testing, edge runtimes, retries). */\n fetch?: FetchLike;\n /**\n * Next.js App Router caching hints. Ignored on runtimes that don't\n * understand them.\n */\n next?: RequestNextOptions;\n}\n\nexport interface GetListingsOptions extends BaseOptions {\n siteId: string;\n filters?: ListingFilters;\n}\n\nexport interface GetListingOptions extends BaseOptions {\n siteId: string;\n listingId: string;\n}\n\nexport interface GetSiteOptions extends BaseOptions {\n /** Look up by site ID, or… */\n siteId?: string;\n /** …by domain. Exactly one of `siteId` / `domain` must be provided. */\n domain?: string;\n}\n\nexport interface SearchListingsOptions extends BaseOptions {\n siteId: string;\n params: SearchListingsParams;\n}\n\nexport interface GetSearchUiOptions extends BaseOptions {\n siteId: string;\n}\n\nexport interface QueryListingsOptions extends BaseOptions {\n siteId: string;\n params?: QueryListingsParams;\n}\n\nexport interface GetSimilarListingsOptions extends BaseOptions {\n siteId: string;\n listingId: string;\n /** Max similar cards to return (API default 6, cap 12). */\n limit?: number;\n}\n\nexport interface GetCmsCollectionsOptions extends BaseOptions {\n siteId: string;\n}\n\nexport interface GetCmsCollectionOptions extends BaseOptions {\n siteId: string;\n slug: string;\n}\n\nexport interface GetCmsEntriesOptions extends BaseOptions {\n siteId: string;\n collection: string;\n limit?: number;\n offset?: number;\n}\n\nexport interface GetCmsEntryOptions extends BaseOptions {\n siteId: string;\n collection: string;\n slug: string;\n}\n\ninterface FetchInit extends RequestInit {\n /**\n * Next.js attaches this on `fetch` (App Router). Adding it here keeps\n * `RequestInit` typed without forcing consumers to install Next types.\n */\n next?: RequestNextOptions;\n}\n\n/** Shared JSON fetch for SDK helpers (not part of the public barrel). */\nexport async function callJson<T>(\n url: string,\n init: FetchInit,\n fetchImpl: FetchLike\n): Promise<T> {\n const response = await fetchImpl(url, init);\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new GaragemSdkError(\n `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${\n text ? ` — ${text.slice(0, 200)}` : \"\"\n }`,\n { status: response.status, url }\n );\n }\n return (await response.json()) as T;\n}\n\n/** Error thrown when a fetcher hits a non-2xx response. */\nexport class GaragemSdkError extends Error {\n readonly status: number;\n readonly url: string;\n constructor(message: string, info: { status: number; url: string }) {\n super(message);\n this.name = \"GaragemSdkError\";\n this.status = info.status;\n this.url = info.url;\n }\n}\n\n/**\n * Fetch a paginated list of listings for a given site.\n *\n * @example\n * const { listings } = await getListings({\n * siteId: \"abc\",\n * filters: { city: \"São Paulo\", limit: 24 },\n * next: { revalidate: 300, tags: [`site:abc:listings`] },\n * });\n */\nexport async function getListings(\n options: GetListingsOptions\n): Promise<ListingsResult> {\n const { filters, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const params = buildListingFiltersQuery(filters);\n const qs = params.size > 0 ? `?${params.toString()}` : \"\";\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings${qs}`;\n\n const data = await callJson<{ listings?: Listing[]; total?: number }>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return {\n listings: data.listings ?? [],\n total: data.total ?? 0,\n };\n}\n\n/**\n * Fetch a single listing's full detail (amenities, gallery, building).\n * `listingId` accepts a code, UUID, or `id-{code}` URL segment.\n */\nexport async function getListing(\n options: GetListingOptions\n): Promise<ListingDetail> {\n const { listingId: rawListingId, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const listingId = listingLookupKey(rawListingId ?? \"\");\n if (!listingId || listingId === \"undefined\" || listingId === \"null\") {\n throw new TypeError(\"getListing: `listingId` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(\n listingId\n )}`;\n\n return callJson<ListingDetail>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Resolve a site's public profile by ID or by domain. Returns `null`\n * when the site does not exist or the host is unrecognized.\n *\n * @example\n * const site = await getSite({ domain: \"imobiliariax.com.br\" });\n * if (!site) return notFound();\n */\nexport async function getSite(options: GetSiteOptions): Promise<Site | null> {\n const { domain, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = options.siteId\n ? await coerceSiteId(options.siteId)\n : undefined;\n if (!siteId && !domain) {\n throw new TypeError(\n \"getSite: provide exactly one of `siteId` or `domain`.\"\n );\n }\n if (siteId && domain) {\n throw new TypeError(\n \"getSite: provide only one of `siteId` or `domain`, not both.\"\n );\n }\n\n const base = normalizeBaseUrl(baseUrl ?? DEFAULT_RESOLVE_BASE_URL);\n const params = new URLSearchParams();\n if (siteId) params.set(\"siteId\", siteId);\n if (domain) params.set(\"domain\", domain);\n const url = `${base}/api/sites/resolve?${params.toString()}`;\n\n const f = fetchImpl ?? fetch;\n const response = await f(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n next,\n } as FetchInit);\n if (response.status === 404) return null;\n if (!response.ok) {\n throw new GaragemSdkError(\n `Garagem SDK: getSite failed (${response.status}) for ${url}`,\n { status: response.status, url }\n );\n }\n const data = (await response.json()) as {\n id: string;\n name: string;\n domain: string | null;\n tenantId: string;\n };\n return {\n id: data.id,\n name: data.name,\n domain: data.domain,\n tenantId: data.tenantId,\n };\n}\n\n/**\n * Advanced search escape hatch.\n *\n * Calls `POST /api/sites/{siteId}/search` directly and returns the raw\n * Typesense response (`{ found, page, hits: [{ document, ... }], ... }`).\n * Use when `queryListings` isn't expressive enough — faceted search,\n * multi-field sort, custom grouping, etc.\n *\n * @example\n * const result = await searchListings({\n * siteId: \"abc\",\n * params: {\n * q: \"frente mar\",\n * query_by: \"title,description,neighborhood\",\n * filter_by: \"businessType:=sale && bedrooms:>=3\",\n * sort_by: \"price:asc\",\n * per_page: 24,\n * page: 1,\n * facet_by: \"neighborhood,propertyType\",\n * },\n * });\n * for (const hit of result.hits) {\n * console.log(hit.document, hit.highlight);\n * }\n */\nexport async function searchListings<TDocument = Record<string, unknown>>(\n options: SearchListingsOptions\n): Promise<SearchListingsResult<TDocument>> {\n const { params, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!params || typeof params.q !== \"string\") {\n throw new TypeError(\n \"Garagem SDK: searchListings requires `params.q` (Typesense query string).\"\n );\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search`;\n return callJson<SearchListingsResult<TDocument>>(\n url,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(params),\n next,\n },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Tenant search schema: filters, slugs, sort tokens, defaultLimit 12.\n * Use this to render the search UI — do not hardcode property types.\n */\nexport async function getSearchUi(\n options: GetSearchUiOptions\n): Promise<SearchUi> {\n const { baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;\n return callJson<SearchUi>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Friendly catalog search (editor combinators). Prefer this over\n * `searchListings` — that helper is a raw Typesense escape hatch.\n */\nexport async function queryListings(\n options: QueryListingsOptions\n): Promise<QueryListingsResult> {\n const { params, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;\n return callJson<QueryListingsResult>(\n url,\n {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(params ?? {}),\n next,\n },\n fetchImpl ?? fetch\n );\n}\n\n/**\n * Fetch similar listings for a detail page carousel.\n * Returns an empty list when the reference listing is missing.\n */\nexport async function getSimilarListings(\n options: GetSimilarListingsOptions\n): Promise<SimilarListingsResult> {\n const {\n listingId: rawListingId,\n limit,\n baseUrl,\n fetch: fetchImpl,\n next,\n } = options;\n const siteId = await coerceSiteId(options.siteId);\n const listingId = listingLookupKey(rawListingId ?? \"\");\n if (!listingId || listingId === \"undefined\" || listingId === \"null\") {\n throw new TypeError(\"getSimilarListings: `listingId` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const params = new URLSearchParams();\n if (typeof limit === \"number\" && Number.isFinite(limit) && limit > 0) {\n params.set(\"limit\", String(Math.floor(limit)));\n }\n const qs = params.size > 0 ? `?${params.toString()}` : \"\";\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(\n listingId\n )}/similar${qs}`;\n\n const data = await callJson<{ listings?: Listing[]; total?: number }>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return {\n listings: data.listings ?? [],\n total: data.total ?? 0,\n };\n}\n\n/** List CMS collections for a site. */\nexport async function getCmsCollections(\n options: GetCmsCollectionsOptions\n): Promise<CmsCollection[]> {\n const { baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections`;\n const data = await callJson<{ collections?: CmsCollection[] }>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return data.collections ?? [];\n}\n\n/** Fetch one CMS collection schema by slug. */\nexport async function getCmsCollection(\n options: GetCmsCollectionOptions\n): Promise<CmsCollection> {\n const { slug, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!slug) {\n throw new TypeError(\"getCmsCollection: `slug` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections/${encodeURIComponent(\n slug\n )}`;\n const data = await callJson<{ collection?: CmsCollection } | CmsCollection>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n if (\n data &&\n typeof data === \"object\" &&\n \"collection\" in data &&\n data.collection\n ) {\n return data.collection;\n }\n return data as CmsCollection;\n}\n\n/** List published CMS entries for a collection. */\nexport async function getCmsEntries(\n options: GetCmsEntriesOptions\n): Promise<CmsEntriesResult> {\n const {\n collection,\n limit,\n offset,\n baseUrl,\n fetch: fetchImpl,\n next,\n } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!collection) {\n throw new TypeError(\"getCmsEntries: `collection` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const params = new URLSearchParams();\n if (typeof limit === \"number\" && Number.isFinite(limit) && limit > 0) {\n params.set(\"limit\", String(Math.floor(limit)));\n }\n if (typeof offset === \"number\" && Number.isFinite(offset) && offset >= 0) {\n params.set(\"offset\", String(Math.floor(offset)));\n }\n const qs = params.size > 0 ? `?${params.toString()}` : \"\";\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/${encodeURIComponent(\n collection\n )}/entries${qs}`;\n\n const data = await callJson<Partial<CmsEntriesResult>>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n return {\n entries: data.entries ?? [],\n total: data.total ?? 0,\n limit: data.limit ?? 0,\n offset: data.offset ?? 0,\n };\n}\n\n/** Fetch one published CMS entry by slug. */\nexport async function getCmsEntry(\n options: GetCmsEntryOptions\n): Promise<CmsEntry> {\n const { collection, slug, baseUrl, fetch: fetchImpl, next } = options;\n const siteId = await coerceSiteId(options.siteId);\n if (!collection) {\n throw new TypeError(\"getCmsEntry: `collection` is required\");\n }\n if (!slug) {\n throw new TypeError(\"getCmsEntry: `slug` is required\");\n }\n const base = normalizeBaseUrl(baseUrl);\n const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/${encodeURIComponent(\n collection\n )}/entries/${encodeURIComponent(slug)}`;\n const data = await callJson<{ entry?: CmsEntry } | CmsEntry>(\n url,\n { method: \"GET\", headers: { Accept: \"application/json\" }, next },\n fetchImpl ?? fetch\n );\n if (data && typeof data === \"object\" && \"entry\" in data && data.entry) {\n return data.entry;\n }\n return data as CmsEntry;\n}\n","export type ListingBusinessType = \"sale\" | \"rental\";\n\nexport type SearchUrlOption = {\n id: string;\n slug: string;\n label: string;\n};\n\nexport type SearchUrlDictionary = {\n listingTypes: SearchUrlOption[];\n propertyTypes: SearchUrlOption[];\n propertyFeatures: SearchUrlOption[];\n buildingAmenities: SearchUrlOption[];\n /** Present only when Campos amenity display is flat (checkbox / alphabetical). */\n amenitySectionTitles?: {\n unit?: string;\n building?: string;\n };\n};\n\nexport type SearchPathLocation = {\n state?: string;\n city?: string;\n neighborhood?: string;\n street?: string;\n};\n\nexport type SearchPathFilters = {\n listingType?: ListingBusinessType | string;\n propertyType?: string | string[];\n location?: SearchPathLocation;\n bedrooms?: number | number[];\n bathrooms?: number | number[];\n suites?: number | number[];\n parkingSpots?: number | number[];\n price?: { min?: number; max?: number };\n area?: { min?: number; max?: number };\n propertyFeatures?: string[];\n buildingAmenities?: string[];\n};\n\nexport type AppliedSearchQuery = {\n page?: number;\n sort?: string | null;\n query?: string;\n loc?: string[];\n};\n\nexport const SEARCH_BASE_ROUTE = \"imoveis\";\nexport const MAX_PAGE = 10_000;\nexport const MAX_LOC_GROUPS = 20;\nexport const DEFAULT_MIN_PRICE = 0;\nexport const DEFAULT_MAX_PRICE = 1_000_000_000;\nexport const DEFAULT_MIN_AREA = 0;\nexport const DEFAULT_MAX_AREA = 100_000;\n\nexport const SORT_URL_TOKENS = [\n \"recentes\",\n \"preco-asc\",\n \"preco-desc\",\n \"area-asc\",\n \"area-desc\",\n] as const;\n\nexport type SortUrlToken = (typeof SORT_URL_TOKENS)[number];\n","/** URL slug for search paths (camelCase → kebab, strip accents). */\nexport function slugifyForUrl(text: string | null | undefined): string {\n if (!text) return \"\";\n const withDashes = text.replace(/([a-z])([A-Z])/g, \"$1-$2\");\n return withDashes\n .toLowerCase()\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/\\s+/g, \"-\")\n .replace(/-+/g, \"-\")\n .trim();\n}\n","import { slugifyForUrl } from \"./slugify\";\nimport type { SearchUrlDictionary, SearchUrlOption } from \"./types\";\n\n/** Last-resort id → Portuguese path slug (tenant slug/label win). */\nexport const PROPERTY_TYPE_ID_TO_SLUG: Record<string, string> = {\n apartment: \"apartamento\",\n house: \"casa\",\n penthouse: \"cobertura\",\n flat: \"flat\",\n kitnet: \"kitnet\",\n loft: \"loft\",\n townhouse: \"sobrado\",\n studio: \"studio\",\n triplex: \"triplex\",\n duplex: \"duplex\",\n land: \"terreno\",\n commercial: \"comercial\",\n office: \"sala-comercial\",\n store: \"loja\",\n warehouse: \"galpao\",\n building: \"predio\",\n hotel: \"hotel\",\n rural: \"rural\",\n other: \"outro\",\n};\n\nconst PROPERTY_TYPE_SLUG_ALIASES: Record<string, string[]> = {\n rural: [\"chacara\", \"fazenda\", \"sitio\"],\n};\n\nexport function buildListingTypeOptions(\n enabled?: {\n sale?: boolean;\n rental?: boolean;\n } | null\n): SearchUrlOption[] {\n const flags = enabled ?? { sale: true, rental: true };\n const out: SearchUrlOption[] = [];\n if (flags.sale !== false) {\n out.push({ id: \"sale\", slug: \"venda\", label: \"Venda\" });\n }\n if (flags.rental !== false) {\n out.push({ id: \"rental\", slug: \"aluguel\", label: \"Aluguel\" });\n }\n return out;\n}\n\nexport function emptySearchUrlDictionary(): SearchUrlDictionary {\n return {\n listingTypes: buildListingTypeOptions(null),\n propertyTypes: [],\n propertyFeatures: [],\n buildingAmenities: [],\n };\n}\n\nfunction catalogSlug(\n id: string,\n label?: string | null,\n slug?: string | null,\n fallbackMap?: Record<string, string>\n): string {\n if (slug?.trim()) return slugifyForUrl(slug) || slug.trim().toLowerCase();\n if (fallbackMap?.[id]) return fallbackMap[id];\n if (label?.trim()) return slugifyForUrl(label) || id.toLowerCase();\n return slugifyForUrl(id) || id.toLowerCase();\n}\n\nexport function mapCatalogOption(\n input: {\n id: string;\n label?: string | null;\n slug?: string | null;\n active?: boolean;\n },\n fallbackMap?: Record<string, string>\n): SearchUrlOption | null {\n if (!input.id || input.active === false) return null;\n return {\n id: input.id,\n label: input.label?.trim() || input.id,\n slug: catalogSlug(input.id, input.label, input.slug, fallbackMap),\n };\n}\n\nexport function mapPropertyTypeOption(input: {\n id: string;\n label?: string | null;\n slug?: string | null;\n active?: boolean;\n}): SearchUrlOption | null {\n return mapCatalogOption(input, PROPERTY_TYPE_ID_TO_SLUG);\n}\n\nfunction allocateCollisionSlug(base: string, taken: Set<string>): string {\n if (!taken.has(base)) return base;\n let candidate = `${base}-comodidade`;\n let suffix = 2;\n while (taken.has(candidate)) {\n candidate = `${base}-comodidade-${suffix}`;\n suffix += 1;\n }\n return candidate;\n}\n\n/**\n * Disambiguate feature/amenity path slugs against property types and\n * against each other (`coworking` + type → `-comodidade`, second hit\n * → `-comodidade-2`), matching the editor runtime dictionary.\n */\nexport function withAmenityCollisionSlugs(\n dictionary: SearchUrlDictionary\n): SearchUrlDictionary {\n const taken = new Set(dictionary.propertyTypes.map((item) => item.slug));\n const propertyFeatures = dictionary.propertyFeatures.map((item) => {\n const slug = allocateCollisionSlug(item.slug, taken);\n taken.add(slug);\n return slug === item.slug ? item : { ...item, slug };\n });\n const buildingAmenities = dictionary.buildingAmenities.map((item) => {\n const slug = allocateCollisionSlug(item.slug, taken);\n taken.add(slug);\n return slug === item.slug ? item : { ...item, slug };\n });\n return { ...dictionary, propertyFeatures, buildingAmenities };\n}\n\nfunction norm(value: string): string {\n return slugifyForUrl(value) || value.toLowerCase();\n}\n\nexport function matchOptionId(\n segment: string,\n options: SearchUrlOption[],\n extraAliases?: Record<string, string[]>\n): string | null {\n const n = norm(segment);\n for (const option of options) {\n const aliases = extraAliases?.[option.id] ?? [];\n const candidates = [option.id, option.slug, option.label, ...aliases];\n if (candidates.some((c) => norm(c) === n)) return option.id;\n }\n return null;\n}\n\nexport function optionSlugById(\n id: string,\n options: SearchUrlOption[]\n): string | null {\n const option = options.find((item) => item.id === id);\n return option?.slug ?? null;\n}\n\nexport const LISTING_TYPE_ALIASES: Record<string, string[]> = {\n sale: [\"comprar\"],\n rental: [\"alugar\"],\n};\n\nexport { PROPERTY_TYPE_SLUG_ALIASES };\n","import {\n LISTING_TYPE_ALIASES,\n PROPERTY_TYPE_SLUG_ALIASES,\n emptySearchUrlDictionary,\n matchOptionId,\n optionSlugById,\n} from \"./catalog\";\nimport { slugifyForUrl } from \"./slugify\";\nimport type { SearchPathFilters, SearchUrlDictionary } from \"./types\";\nimport {\n DEFAULT_MAX_AREA,\n DEFAULT_MAX_PRICE,\n DEFAULT_MIN_AREA,\n DEFAULT_MIN_PRICE,\n SEARCH_BASE_ROUTE,\n} from \"./types\";\n\nfunction toArray<T>(value: T | T[] | undefined): T[] {\n if (value === undefined) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction formatNumeric(value: number | number[]): string {\n return Array.isArray(value) ? value.join(\"-\") : String(value);\n}\n\nfunction formatRange(min: number, max: number, unit: string): string {\n return `de-${min}-a-${max}-${unit}`;\n}\n\nfunction formatSuiteSuffix(value: number | number[]): string {\n const values = Array.isArray(value) ? value : [value];\n const firstValue = values[0] ?? 0;\n return firstValue === 0 || firstValue === 1 ? \"suite\" : \"suites\";\n}\n\nexport function composeSearchPublicPath(\n filters: SearchPathFilters,\n dictionary: SearchUrlDictionary = emptySearchUrlDictionary()\n): string {\n const segments: string[] = [];\n const listingType = filters.listingType;\n if (listingType) {\n segments.push(\n optionSlugById(listingType, dictionary.listingTypes) ||\n slugifyForUrl(listingType)\n );\n }\n\n for (const propertyType of toArray(filters.propertyType)) {\n segments.push(\n optionSlugById(propertyType, dictionary.propertyTypes) ||\n slugifyForUrl(propertyType)\n );\n }\n\n const location = filters.location;\n if (location) {\n if (location.state) segments.push(slugifyForUrl(location.state));\n if (location.city) segments.push(slugifyForUrl(location.city));\n if (location.neighborhood)\n segments.push(slugifyForUrl(location.neighborhood));\n if (location.street) segments.push(slugifyForUrl(location.street));\n }\n\n if (filters.bedrooms !== undefined) {\n segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);\n }\n if (filters.bathrooms !== undefined) {\n segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);\n }\n if (filters.suites !== undefined) {\n const suffix = formatSuiteSuffix(filters.suites);\n segments.push(`${formatNumeric(filters.suites)}-${suffix}`);\n }\n if (filters.parkingSpots !== undefined) {\n segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);\n }\n\n if (\n filters.price &&\n (filters.price.min !== undefined || filters.price.max !== undefined)\n ) {\n const min = filters.price.min ?? DEFAULT_MIN_PRICE;\n const max = filters.price.max ?? DEFAULT_MAX_PRICE;\n segments.push(formatRange(min, max, \"reais\"));\n }\n if (\n filters.area &&\n (filters.area.min !== undefined || filters.area.max !== undefined)\n ) {\n const min = filters.area.min ?? DEFAULT_MIN_AREA;\n const max = filters.area.max ?? DEFAULT_MAX_AREA;\n segments.push(formatRange(min, max, \"m2\"));\n }\n\n const seenAmenities = new Set<string>();\n for (const id of filters.propertyFeatures ?? []) {\n const slug =\n optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);\n if (!slug || seenAmenities.has(slug)) continue;\n seenAmenities.add(slug);\n segments.push(slug);\n }\n for (const id of filters.buildingAmenities ?? []) {\n const slug =\n optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);\n if (!slug || seenAmenities.has(slug)) continue;\n seenAmenities.add(slug);\n segments.push(slug);\n }\n\n const path = segments.filter(Boolean).join(\"/\");\n return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;\n}\n\nconst BEDROOMS = /^(\\d+(?:-\\d+)*)-quartos?$/;\nconst BATHROOMS = /^(\\d+(?:-\\d+)*)-banheiros?$/;\nconst SUITES = /^(\\d+(?:-\\d+)*)-suites?$/;\nconst PARKING = /^(\\d+(?:-\\d+)*)-vagas?$/;\nconst PRICE = /^de-(\\d+)-a-(\\d+)-(reais|real)$/;\nconst AREA = /^de-(\\d+)-a-(\\d+)-(m2|m²)$/;\n\nfunction parseNumericList(raw: string): number[] {\n return raw\n .split(\"-\")\n .map((part) => Number(part))\n .filter((n) => Number.isFinite(n));\n}\n\nfunction collapse(values: number[]): number | number[] {\n return values.length === 1 ? values[0]! : values;\n}\n\n/**\n * Parse a default-V2 search path. Order-flexible (detection), not generation.\n * `id-…` anywhere is listing detail — returns null so the caller can route.\n */\nexport function parseSearchPublicPath(\n pathname: string,\n dictionary: SearchUrlDictionary = emptySearchUrlDictionary()\n): SearchPathFilters | null {\n const raw = pathname.split(/[?#]/)[0] ?? \"\";\n let segments = raw.replace(/^\\//, \"\").split(\"/\").filter(Boolean);\n if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);\n if (segments.some((segment) => segment.includes(\".\"))) return null;\n if (segments.some((segment) => segment.toLowerCase().startsWith(\"id-\"))) {\n return null;\n }\n\n const filters: SearchPathFilters = {};\n const locationParts: string[] = [];\n const propertyTypes: string[] = [];\n const propertyFeatures: string[] = [];\n const buildingAmenities: string[] = [];\n\n for (const segment of segments) {\n const lower = segment.toLowerCase();\n const listingType = matchOptionId(\n segment,\n dictionary.listingTypes,\n LISTING_TYPE_ALIASES\n );\n if (listingType && !filters.listingType) {\n filters.listingType = listingType;\n continue;\n }\n\n const propertyType = matchOptionId(\n segment,\n dictionary.propertyTypes,\n PROPERTY_TYPE_SLUG_ALIASES\n );\n if (propertyType) {\n propertyTypes.push(propertyType);\n continue;\n }\n\n const bedrooms = lower.match(BEDROOMS);\n if (bedrooms) {\n filters.bedrooms = collapse(parseNumericList(bedrooms[1]!));\n continue;\n }\n const bathrooms = lower.match(BATHROOMS);\n if (bathrooms) {\n filters.bathrooms = collapse(parseNumericList(bathrooms[1]!));\n continue;\n }\n const suites = lower.match(SUITES);\n if (suites) {\n filters.suites = collapse(parseNumericList(suites[1]!));\n continue;\n }\n const parking = lower.match(PARKING);\n if (parking) {\n filters.parkingSpots = collapse(parseNumericList(parking[1]!));\n continue;\n }\n const price = lower.match(PRICE);\n if (price) {\n filters.price = { min: Number(price[1]), max: Number(price[2]) };\n continue;\n }\n const area = lower.match(AREA);\n if (area) {\n filters.area = { min: Number(area[1]), max: Number(area[2]) };\n continue;\n }\n\n const featureId = matchOptionId(segment, dictionary.propertyFeatures);\n if (featureId) {\n propertyFeatures.push(featureId);\n continue;\n }\n const amenityId = matchOptionId(segment, dictionary.buildingAmenities);\n if (amenityId) {\n buildingAmenities.push(amenityId);\n continue;\n }\n\n locationParts.push(segment);\n }\n\n if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];\n else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;\n if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;\n if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;\n\n const location = locationFromPathLeftovers(locationParts);\n if (location) filters.location = location;\n\n return filters;\n}\n\nconst PATH_STREET_PREFIX =\n /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;\n\n/**\n * Path leftovers are hierarchical from the left (compose writes\n * state → city → neighborhood → street). A single leftover is not a\n * state unless it is a 2-letter UF slug — otherwise it matches `?loc=`\n * (neighborhood, or street when the slug has a street prefix).\n */\nfunction locationFromPathLeftovers(\n parts: string[]\n): SearchPathFilters[\"location\"] | undefined {\n if (parts.length === 0) return undefined;\n if (parts.length === 1) {\n const value = parts[0]!;\n if (PATH_STREET_PREFIX.test(value)) return { street: value };\n if (/^[a-z]{2}$/i.test(value)) return { state: value };\n return { neighborhood: value };\n }\n const [state, city, neighborhood, street] = parts;\n return {\n ...(state ? { state } : {}),\n ...(city ? { city } : {}),\n ...(neighborhood ? { neighborhood } : {}),\n ...(street ? { street } : {}),\n };\n}\n","import type { AppliedSearchQuery, SortUrlToken } from \"./types\";\nimport { MAX_LOC_GROUPS, MAX_PAGE, SORT_URL_TOKENS } from \"./types\";\n\nconst SORT_SET = new Set<string>(SORT_URL_TOKENS);\n\nexport type AppliedSearchChange =\n | { type: \"sort\"; sort: string | null }\n | { type: \"page\"; page: number }\n | { type: \"query\"; query: string }\n | { type: \"loc\"; loc: string[] }\n | { type: \"applyFilters\" };\n\nfunction isSortToken(value: string): value is SortUrlToken {\n return SORT_SET.has(value);\n}\n\nexport function normalizeAppliedSearchQuery(\n query: AppliedSearchQuery\n): AppliedSearchQuery {\n if (query.loc && query.loc.length > 0) {\n const { query: _query, ...rest } = query;\n return rest;\n }\n return query;\n}\n\nexport function parseAppliedSearchQuery(\n search: string | URLSearchParams\n): AppliedSearchQuery {\n const params =\n search instanceof URLSearchParams\n ? search\n : new URLSearchParams(search.startsWith(\"?\") ? search.slice(1) : search);\n const result: AppliedSearchQuery = {};\n\n const pageRaw = params.get(\"page\");\n if (pageRaw) {\n const page = Number.parseInt(pageRaw, 10);\n if (Number.isFinite(page) && page > 1) {\n result.page = Math.min(page, MAX_PAGE);\n }\n }\n\n const sort = params.get(\"ordenar\");\n if (sort && isSortToken(sort)) result.sort = sort;\n\n const q = params.get(\"q\")?.trim();\n if (q) result.query = q;\n\n const loc = params\n .getAll(\"loc\")\n .map((value) => value.trim())\n .filter(Boolean)\n .slice(0, MAX_LOC_GROUPS);\n if (loc.length > 0) result.loc = loc;\n\n return normalizeAppliedSearchQuery(result);\n}\n\n/** Keys managed by AppliedSearchQuery (removed/rewritten on merge). */\nconst APPLIED_QUERY_KEYS = [\"page\", \"ordenar\", \"q\", \"loc\"] as const;\n\nexport function serializeAppliedSearchQuery(\n query: AppliedSearchQuery\n): URLSearchParams {\n const normalized = normalizeAppliedSearchQuery(query);\n const params = new URLSearchParams();\n if (normalized.page !== undefined && normalized.page > 1) {\n params.set(\"page\", String(Math.min(normalized.page, MAX_PAGE)));\n }\n if (normalized.sort && isSortToken(normalized.sort)) {\n params.set(\"ordenar\", normalized.sort);\n }\n const text = normalized.query?.trim();\n if (text) params.set(\"q\", text);\n for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {\n const trimmed = value.trim();\n if (trimmed) params.append(\"loc\", trimmed);\n }\n return params;\n}\n\n/**\n * Merge applied query into an existing search string, preserving unknown keys\n * (UTM params, etc.) while rewriting managed keys.\n */\nexport function mergeAppliedSearchQueryIntoSearch(\n existing: string | URLSearchParams,\n query: AppliedSearchQuery\n): URLSearchParams {\n const params =\n existing instanceof URLSearchParams\n ? new URLSearchParams(existing)\n : new URLSearchParams(\n existing.startsWith(\"?\") ? existing.slice(1) : existing\n );\n\n // Remove all managed keys\n for (const key of APPLIED_QUERY_KEYS) {\n params.delete(key);\n }\n\n // Merge in the serialized applied query\n const serialized = serializeAppliedSearchQuery(query);\n serialized.forEach((value, key) => {\n if (key === \"loc\") {\n params.append(\"loc\", value);\n } else {\n params.set(key, value);\n }\n });\n\n return params;\n}\n\nexport function reduceAppliedSearchQuery(\n prev: AppliedSearchQuery,\n change: AppliedSearchChange\n): AppliedSearchQuery {\n switch (change.type) {\n case \"sort\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n if (change.sort) next.sort = change.sort;\n else delete next.sort;\n return normalizeAppliedSearchQuery(next);\n }\n case \"applyFilters\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n return normalizeAppliedSearchQuery(next);\n }\n case \"query\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n const trimmed = change.query.trim();\n if (trimmed) {\n next.query = trimmed;\n delete next.loc;\n } else {\n delete next.query;\n }\n return normalizeAppliedSearchQuery(next);\n }\n case \"loc\": {\n const next: AppliedSearchQuery = { ...prev };\n delete next.page;\n delete next.query;\n const loc = change.loc\n .map((value) => value.trim())\n .filter(Boolean)\n .slice(0, MAX_LOC_GROUPS);\n if (loc.length > 0) next.loc = loc;\n else delete next.loc;\n return normalizeAppliedSearchQuery(next);\n }\n case \"page\": {\n const next: AppliedSearchQuery = { ...prev };\n if (change.page <= 1) delete next.page;\n else next.page = Math.min(change.page, MAX_PAGE);\n return normalizeAppliedSearchQuery(next);\n }\n default: {\n const _exhaustive: never = change;\n return _exhaustive;\n }\n }\n}\n\nexport function composeSearchPublicHref(\n pathname: string,\n query: AppliedSearchQuery,\n existingSearch?: string | URLSearchParams\n): string {\n const params = existingSearch\n ? mergeAppliedSearchQueryIntoSearch(existingSearch, query)\n : serializeAppliedSearchQuery(query);\n const qs = params.toString();\n return qs ? `${pathname}?${qs}` : pathname;\n}\n","import {\n composeSearchPublicHref as composeHref,\n mergeAppliedSearchQueryIntoSearch as mergeQuery,\n parseAppliedSearchQuery as parseQuery,\n reduceAppliedSearchQuery as reduceQuery,\n serializeAppliedSearchQuery as serializeQuery,\n} from \"@garagem/search-url\";\nimport type { AppliedSearchChange, AppliedSearchQuery } from \"./types\";\n\nexport function parseAppliedSearchQuery(\n search: string | URLSearchParams\n): AppliedSearchQuery {\n return parseQuery(search);\n}\n\nexport function serializeAppliedSearchQuery(\n query: AppliedSearchQuery\n): URLSearchParams {\n return serializeQuery(query);\n}\n\nexport function mergeAppliedSearchQueryIntoSearch(\n existing: string | URLSearchParams,\n query: AppliedSearchQuery\n): URLSearchParams {\n return mergeQuery(existing, query);\n}\n\nexport function reduceAppliedSearchQuery(\n prev: AppliedSearchQuery,\n change: AppliedSearchChange\n): AppliedSearchQuery {\n return reduceQuery(prev, change);\n}\n\nexport function composeSearchPublicHref(\n pathname: string,\n query: AppliedSearchQuery,\n existingSearch?: string | URLSearchParams\n): string {\n return composeHref(pathname, query, existingSearch);\n}\n","// Re-exported from @garagem/site-search to avoid publishing the private package\nexport type LocationFilterInput = {\n type: string;\n value: string;\n};\n\n/**\n * Convert a SearchPathLocation (from parseSearchPublicPath) to the correct\n * LocationFilterInput format for the friendly search API. This ensures that\n * hierarchical location filters are ANDed correctly instead of ORed.\n */\nexport function pathLocationToFilterInput(location: {\n state?: string;\n city?: string;\n neighborhood?: string;\n street?: string;\n}): LocationFilterInput | null {\n if (!location || typeof location !== \"object\") return null;\n\n const { state, city, neighborhood, street } = location;\n const levels: string[] = [];\n if (state) levels.push(state);\n if (city) levels.push(city);\n if (neighborhood) levels.push(neighborhood);\n if (street) levels.push(street);\n\n if (levels.length === 0) return null;\n if (levels.length === 1) {\n if (state) return { type: \"state\", value: state };\n if (city) return { type: \"city\", value: city };\n if (neighborhood) return { type: \"neighborhood\", value: neighborhood };\n if (street) return { type: \"street\", value: street };\n }\n\n return { type: \"path\", value: levels.join(\"/\") };\n}\n","import {\n composeSearchPublicPath as composePath,\n parseSearchPublicPath as parsePath,\n} from \"@garagem/search-url\";\nimport type {\n QueryListingsFilters,\n SearchPathFilters,\n SearchUiDictionary,\n} from \"./types\";\n\nexport function composeSearchPublicPath(\n filters: SearchPathFilters,\n dictionary?: SearchUiDictionary\n): string {\n return dictionary ? composePath(filters, dictionary) : composePath(filters);\n}\n\nexport function parseSearchPublicPath(\n pathname: string,\n dictionary?: SearchUiDictionary\n): SearchPathFilters | null {\n return dictionary ? parsePath(pathname, dictionary) : parsePath(pathname);\n}\n\n/**\n * Convert `SearchPathFilters` (returned by `parseSearchPublicPath`) to\n * `QueryListingsFilters` (accepted by `queryListings`).\n *\n * This maps path-based filter keys (`bedrooms`, `parkingSpots`, `area`)\n * to the POST API keys (`property_bedrooms`, `property_parking_spots`,\n * `property_area_total`).\n *\n * Location is **not** included — use `pathLocationToFilterInput` separately\n * and pass the result as the `location` field in `QueryListingsParams`.\n */\nexport function pathFiltersToQueryFilters(\n pathFilters: SearchPathFilters\n): QueryListingsFilters {\n const result: QueryListingsFilters = {};\n\n if (pathFilters.listingType !== undefined) {\n result.listing_type = pathFilters.listingType;\n }\n if (pathFilters.propertyType !== undefined) {\n result.property_type = pathFilters.propertyType;\n }\n if (pathFilters.bedrooms !== undefined) {\n result.property_bedrooms = pathFilters.bedrooms;\n }\n if (pathFilters.bathrooms !== undefined) {\n result.property_bathrooms = pathFilters.bathrooms;\n }\n if (pathFilters.suites !== undefined) {\n result.property_suites = pathFilters.suites;\n }\n if (pathFilters.parkingSpots !== undefined) {\n result.property_parking_spots = pathFilters.parkingSpots;\n }\n if (pathFilters.price !== undefined) {\n result.price = pathFilters.price;\n }\n if (pathFilters.area !== undefined) {\n result.property_area_total = pathFilters.area;\n }\n if (pathFilters.propertyFeatures !== undefined) {\n result.propertyFeatures = pathFilters.propertyFeatures;\n }\n if (pathFilters.buildingAmenities !== undefined) {\n result.buildingAmenities = pathFilters.buildingAmenities;\n }\n\n return result;\n}\n","/**\n * Presentation helpers with no UI framework.\n * Adapters consume these formatters; they must not live inside JSX.\n */\n\nexport function formatListingPrice(\n amount: number | null | undefined,\n locale = \"pt-BR\",\n currency = \"BRL\"\n): string {\n if (amount == null) return \"Sob consulta\";\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }).format(amount);\n } catch {\n return `${currency} ${amount}`;\n }\n}\n\n/** Input mask: `499000` → `\"499.000\"` (no currency symbol). */\nexport function formatGroupedInteger(\n value: string | number | null | undefined,\n locale = \"pt-BR\"\n): string {\n const digits = String(value ?? \"\").replace(/\\D/g, \"\");\n if (!digits) return \"\";\n const amount = Number.parseInt(digits, 10);\n if (!Number.isFinite(amount)) return \"\";\n return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(\n amount\n );\n}\n\n/** Inverse of `formatGroupedInteger`: `\"499.000\"` / `\"499000\"` → `499000`. */\nexport function parseGroupedInteger(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? Math.trunc(value) : undefined;\n }\n const digits = String(value ?? \"\").replace(/\\D/g, \"\");\n if (!digits) return undefined;\n const amount = Number.parseInt(digits, 10);\n return Number.isFinite(amount) ? amount : undefined;\n}\n\nexport function formatAreaM2(area: number | null | undefined): string | null {\n if (area == null || !Number.isFinite(area)) return null;\n return `${area} m²`;\n}\n\nexport function listingBusinessLabel(businessType: string | undefined): string {\n return businessType === \"rental\" ? \"Aluguel\" : \"Venda\";\n}\n","import {\n composeSearchPublicHref,\n parseAppliedSearchQuery,\n reduceAppliedSearchQuery,\n} from \"./applied-query\";\nimport { pathLocationToFilterInput } from \"./loc-params\";\nimport {\n composeSearchPublicPath,\n parseSearchPublicPath,\n pathFiltersToQueryFilters,\n} from \"./path\";\nimport { formatGroupedInteger, parseGroupedInteger } from \"./presentation\";\nimport type {\n AppliedSearchChange,\n AppliedSearchQuery,\n QueryListingsParams,\n SearchPathFilters,\n SearchUi,\n SearchUiDictionary,\n SearchUiFilter,\n SearchUiOption,\n} from \"./types\";\n\nconst PATH_FILTER_IDS: Record<string, keyof SearchPathFilters> = {\n listing_type: \"listingType\",\n property_type: \"propertyType\",\n property_bedrooms: \"bedrooms\",\n property_bathrooms: \"bathrooms\",\n property_suites: \"suites\",\n property_parking_spots: \"parkingSpots\",\n price: \"price\",\n property_area_total: \"area\",\n propertyFeatures: \"propertyFeatures\",\n buildingAmenities: \"buildingAmenities\",\n};\n\n/** Query keys that must never encode filters (Editor/Studio path contract). */\nexport const FORBIDDEN_SEARCH_QUERY_KEYS = [\n \"tipo\",\n \"quartos\",\n \"tipo-imovel\",\n \"banheiros\",\n \"vagas\",\n] as const;\n\n/** Default option: omit `ordenar` (API has no relevance token). */\nexport const SEARCH_SORT_RELEVANCE = {\n id: \"\",\n label: \"Mais relevantes\",\n} as const;\n\nexport function searchSortOptions(\n sorts: Array<{ id: string; label: string }> | undefined\n): Array<{ id: string; label: string }> {\n const fromApi = (sorts || []).filter((sort) => sort.id);\n return [\n { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },\n ...fromApi,\n ];\n}\n\n/** Toolbar: price + bedrooms first and required when the schema has them. */\nexport const TOOLBAR_PRIMARY_FILTER_IDS = [\n \"price\",\n \"property_bedrooms\",\n] as const;\n\nconst HIDDEN_FILTER_IDS = new Set([\"property_suites\"]);\n\nfunction toFiniteNumber(value: unknown): number | undefined {\n if (value === \"\" || value == null) return undefined;\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n}\n\nfunction pathnameOnly(pathname: string): string {\n return String(pathname || \"\").split(/[?#]/)[0] || \"/\";\n}\n\nexport function isListingDetailPath(pathname: string): boolean {\n const parts = pathnameOnly(pathname).split(\"/\").filter(Boolean);\n const last = parts[parts.length - 1] || \"\";\n return last.toLowerCase().startsWith(\"id-\");\n}\n\nexport function readPublicSearch(\n pathname: string,\n search: string,\n dictionary?: SearchUiDictionary\n): { pathFilters: SearchPathFilters; applied: AppliedSearchQuery } {\n const pathFilters =\n parseSearchPublicPath(pathnameOnly(pathname), dictionary) || {};\n const applied = parseAppliedSearchQuery(search || \"\");\n return { pathFilters, applied };\n}\n\nfunction lookupDisplay(\n table: Record<string, string> | undefined,\n slug: string | undefined\n): string | undefined {\n if (!slug || !table) return slug;\n return table[slug] || table[String(slug).toLowerCase()] || slug;\n}\n\nexport type LocationNameTables = {\n states?: Record<string, string>;\n cities?: Record<string, string>;\n neighborhoods?: Record<string, string>;\n streets?: Record<string, string>;\n};\n\nexport function displayPathLocation(\n location: SearchPathFilters[\"location\"],\n values?: LocationNameTables | null\n): SearchPathFilters[\"location\"] | null {\n if (!location) return null;\n const table = values || {};\n return {\n state: lookupDisplay(table.states, location.state),\n city: lookupDisplay(table.cities, location.city),\n neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),\n street: lookupDisplay(table.streets, location.street),\n };\n}\n\nexport function buildQueryListingsParams(\n pathFilters: SearchPathFilters,\n applied: AppliedSearchQuery,\n schema: Pick<SearchUi, \"defaultLimit\"> | { defaultLimit?: number } | null,\n locationValues?: LocationNameTables | null\n): QueryListingsParams {\n const filters = pathFiltersToQueryFilters(pathFilters || {});\n const locations: Array<{ type: string; value: string }> = [];\n const displayed = displayPathLocation(pathFilters?.location, locationValues);\n const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;\n if (pathLoc) locations.push(pathLoc);\n for (const value of applied?.loc || []) {\n locations.push({ type: \"loc\", value });\n }\n const params: QueryListingsParams = {\n page: applied?.page || 1,\n limit: schema?.defaultLimit || 12,\n filters,\n };\n if (applied?.sort) params.sort = applied.sort;\n const hasLocation = locations.length > 0;\n if (applied?.query && !hasLocation) params.q = applied.query;\n if (hasLocation) params.location = locations;\n return params;\n}\n\nexport function applyPathFilter(\n pathFilters: SearchPathFilters,\n filterId: string,\n value: unknown\n): SearchPathFilters {\n const next: SearchPathFilters = { ...(pathFilters || {}) };\n const key = PATH_FILTER_IDS[filterId];\n if (!key) return next;\n if (value === \"\" || value == null) {\n delete next[key];\n return next;\n }\n if (key === \"price\" || key === \"area\") {\n const range = (value || {}) as { min?: unknown; max?: unknown };\n const parse = key === \"price\" ? parseGroupedInteger : toFiniteNumber;\n const min = parse(range.min);\n const max = parse(range.max);\n if (min == null && max == null) {\n delete next[key];\n return next;\n }\n next[key] = {\n ...(min != null ? { min } : {}),\n ...(max != null ? { max } : {}),\n };\n return next;\n }\n if (key === \"propertyFeatures\" || key === \"buildingAmenities\") {\n const current = Array.isArray(next[key]) ? [...next[key]] : [];\n const id = String(value);\n const i = current.indexOf(id);\n if (i >= 0) current.splice(i, 1);\n else current.push(id);\n if (current.length) next[key] = current;\n else delete next[key];\n return next;\n }\n if (key === \"propertyType\") {\n const id = String(value);\n const current = Array.isArray(next.propertyType)\n ? [...next.propertyType]\n : next.propertyType\n ? [String(next.propertyType)]\n : [];\n const i = current.indexOf(id);\n if (i >= 0) current.splice(i, 1);\n else current.push(id);\n if (current.length === 0) delete next.propertyType;\n else if (current.length === 1) next.propertyType = current[0];\n else next.propertyType = current;\n return next;\n }\n if (key === \"listingType\") {\n const id = String(value);\n if (next.listingType === id) delete next.listingType;\n else next.listingType = id;\n return next;\n }\n if (\n key === \"bedrooms\" ||\n key === \"bathrooms\" ||\n key === \"suites\" ||\n key === \"parkingSpots\"\n ) {\n const n = Number(value);\n if (!Number.isFinite(n)) {\n delete next[key];\n return next;\n }\n if (next[key] === n) delete next[key];\n else next[key] = n;\n return next;\n }\n return next;\n}\n\nexport function pathFilterValue(\n pathFilters: SearchPathFilters | undefined,\n filterId: string\n): string {\n const key = PATH_FILTER_IDS[filterId];\n const value = pathFilters && key ? pathFilters[key] : undefined;\n if (value == null) return \"\";\n if (Array.isArray(value)) return value[0] != null ? String(value[0]) : \"\";\n if (typeof value === \"object\") return \"\";\n return String(value);\n}\n\nexport function pathFilterHasOption(\n pathFilters: SearchPathFilters | undefined,\n filterId: string,\n optionId: string\n): boolean {\n const key = PATH_FILTER_IDS[filterId];\n const value = pathFilters && key ? pathFilters[key] : undefined;\n if (value == null) return false;\n if (Array.isArray(value)) return value.map(String).includes(optionId);\n if (typeof value === \"object\") return false;\n return String(value) === optionId;\n}\n\nexport function publicSearchHref(\n pathFilters: SearchPathFilters,\n applied: AppliedSearchQuery,\n dictionary?: SearchUiDictionary,\n existingSearch?: string\n): string {\n const pathname = composeSearchPublicPath(pathFilters || {}, dictionary);\n return composeSearchPublicHref(pathname, applied || {}, existingSearch);\n}\n\nexport function hrefForPathFilters(\n pathname: string,\n search: string,\n dictionary: SearchUiDictionary | undefined,\n nextPathFilters: SearchPathFilters\n): string {\n const { applied } = readPublicSearch(pathname, search, dictionary);\n const nextApplied = reduceAppliedSearchQuery(applied, {\n type: \"applyFilters\",\n });\n return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);\n}\n\nexport function hrefForAppliedChange(\n pathname: string,\n search: string,\n dictionary: SearchUiDictionary | undefined,\n change: AppliedSearchChange\n): string {\n const { pathFilters, applied } = readPublicSearch(\n pathname,\n search,\n dictionary\n );\n let nextPath = pathFilters;\n if (change && change.type === \"query\") {\n nextPath = { ...pathFilters };\n delete nextPath.location;\n }\n const nextApplied = reduceAppliedSearchQuery(applied, change);\n return publicSearchHref(nextPath, nextApplied, dictionary, search);\n}\n\nfunction currentSearchHref(pathname: string, search: string): string {\n const path = pathnameOnly(pathname);\n const qs = search.replace(/^\\?/, \"\");\n return qs ? `${path}?${qs}` : path;\n}\n\n/** Canonical href if the current URL is out of generation order; otherwise null. */\nexport function canonicalizeSearchHref(\n pathname: string,\n search: string,\n dictionary?: SearchUiDictionary\n): string | null {\n // A preview prefix is not a filter. Replacing it rewrites the URL forever.\n if (pathname.includes(\"/api/v0-preview/\")) return null;\n if (isListingDetailPath(pathname)) return null;\n const { pathFilters, applied } = readPublicSearch(\n pathname,\n search,\n dictionary\n );\n const href = publicSearchHref(pathFilters, applied, dictionary, search);\n if (href === currentSearchHref(pathname, search)) return null;\n return href;\n}\n\nexport function searchHrefUsesLegacyFilterQuery(href: string): boolean {\n const query = href.split(\"?\")[1] || \"\";\n const params = new URLSearchParams(query);\n return FORBIDDEN_SEARCH_QUERY_KEYS.some((key) => params.has(key));\n}\n\n/**\n * Drop staged filters. Location always stays until apply.\n * `keepFilterIds` keeps toolbar-primary filters (price, bedrooms) so Limpar\n * in the extra-filters dialog does not wipe values already on the toolbar.\n */\nexport function clearStagedPathFilters(\n current: SearchPathFilters,\n keepFilterIds: readonly string[] = []\n): SearchPathFilters {\n const next: SearchPathFilters = current.location\n ? { location: current.location }\n : {};\n for (const id of keepFilterIds) {\n const key = PATH_FILTER_IDS[id];\n if (!key || key === \"location\") continue;\n const value = current[key];\n if (value != null) Object.assign(next, { [key]: value });\n }\n return next;\n}\n\nexport function visibleSearchFilters(\n schema: SearchUi | null\n): SearchUiFilter[] {\n if (!schema?.filters) return [];\n return schema.filters.filter((filter) => {\n if (HIDDEN_FILTER_IDS.has(filter.id)) return false;\n if (filter.id === \"listing_type\" && (filter.options?.length ?? 0) <= 1) {\n return false;\n }\n return true;\n });\n}\n\nexport function toolbarFilterIds(schema: SearchUi | null): string[] {\n const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));\n return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));\n}\n\nexport function countOptionLabel(\n option: Pick<SearchUiOption, \"label\">\n): string {\n const label = String(option?.label ?? \"\");\n if (/^[1-9]\\d*$/.test(label)) return `${label}+`;\n return label;\n}\n\nexport function countFacetChoices(\n options: SearchUiOption[] | undefined\n): Array<{ id: string; label: string }> {\n const list = options || [];\n const zero = list.find((o) => o.id === \"0\" || o.label === \"Studio\");\n const isStudio = Boolean(\n zero && /studio/i.test(String(zero.label)) && zero.id === \"0\"\n );\n const max = isStudio ? 3 : 4;\n const out: Array<{ id: string; label: string }> = [];\n if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });\n for (let n = 1; n <= max; n += 1) {\n const option = list.find((o) => o.id === String(n));\n out.push({\n id: String(n),\n label: countOptionLabel(option || { label: String(n) }),\n });\n }\n return out;\n}\n\nconst FEMININE_HEADING =\n /(casa|cobertura|kitnet|loja|sala|fazenda|chácara|chacara)s?$/i;\n\nfunction pluralizePt(label: string): string {\n const text = label.trim();\n if (!text || /s$/i.test(text)) return text;\n if (/il$/i.test(text)) return `${text.slice(0, -1)}is`;\n if (/m$/i.test(text)) return `${text.slice(0, -1)}ns`;\n return `${text}s`;\n}\n\nfunction headingLocationSuffix(\n location: SearchPathFilters[\"location\"] | null\n): string {\n if (!location) return \"\";\n if (location.street && location.neighborhood) {\n return `${location.street}, ${location.neighborhood}`;\n }\n if (location.neighborhood && location.city) {\n return `${location.neighborhood}, ${location.city}`;\n }\n if (location.city && location.state) {\n return `${location.city} - ${location.state}`;\n }\n return (\n location.city ||\n location.neighborhood ||\n location.street ||\n location.state ||\n \"\"\n );\n}\n\n/**\n * SEO H1 for a search URL. Must stay stable for the same path — never\n * include the hit count (Google treats a changing H1 on one URL as\n * volatile). Count is rendered in a sibling `<span>`.\n */\nexport function searchResultsHeading(\n pathFilters: SearchPathFilters,\n dictionary?: SearchUiDictionary | null,\n locationNames?: LocationNameTables | null\n): string {\n const types = ([] as string[])\n .concat(pathFilters.propertyType || [])\n .filter(Boolean);\n let noun = \"Imóveis\";\n let found = \"encontrados\";\n if (types.length === 1) {\n const id = String(types[0]);\n const option = dictionary?.propertyTypes?.find(\n (entry) => entry.id === id || entry.slug === id\n );\n const label = option?.label;\n if (label) {\n noun = pluralizePt(label.charAt(0).toUpperCase() + label.slice(1));\n if (FEMININE_HEADING.test(id) || FEMININE_HEADING.test(label)) {\n found = \"encontradas\";\n }\n }\n }\n const place = locationNames\n ? headingLocationSuffix(\n displayPathLocation(pathFilters.location, locationNames)\n )\n : \"\";\n if (place) return `${noun} ${found} em ${place}`;\n return `${noun} ${found}`;\n}\n\n/**\n * Next App Router does not navigate when the href is unchanged. Canonical\n * URLs omit `page=1`, so pagination must still emit `?page=1` on the link.\n */\nexport function hrefWithExplicitPage(href: string, page: number): string {\n if (page !== 1 || /(?:\\?|&)page=/.test(href)) return href;\n return href.includes(\"?\") ? `${href}&page=1` : `${href}?page=1`;\n}\n\nexport function paginationPages(\n currentPage: number,\n totalPages: number,\n padding: number\n): number[] {\n if (totalPages < 1) return [];\n const current = Math.min(Math.max(1, currentPage), totalPages);\n const start = Math.max(1, current - padding);\n const end = Math.min(totalPages, current + padding);\n const pages: number[] = [];\n for (let i = start; i <= end; i += 1) pages.push(i);\n return pages;\n}\n\nexport const SEARCH_EMPTY_COPY =\n \"Nenhum imóvel encontrado. Ajuste a busca ou os filtros.\";\n\nexport function rangeDraftFromPath(\n pathFilters: SearchPathFilters\n): Record<string, { min: string; max: string }> {\n const price = pathFilters.price || {};\n const area = pathFilters.area || {};\n return {\n price: {\n min: price.min != null ? formatGroupedInteger(price.min) : \"\",\n max: price.max != null ? formatGroupedInteger(price.max) : \"\",\n },\n property_area_total: {\n min: area.min != null ? String(area.min) : \"\",\n max: area.max != null ? String(area.max) : \"\",\n },\n };\n}\n\nexport type SearchChromeModel = {\n headingTitle: string;\n toolbarFilters: SearchUiFilter[];\n extraFilters: SearchUiFilter[];\n sortOptions: Array<{ id: string; label: string }>;\n};\n\nexport function searchChromeModel(\n schema: SearchUi | null,\n pathFilters: SearchPathFilters,\n locationNames?: LocationNameTables | null\n): SearchChromeModel {\n const filters = visibleSearchFilters(schema);\n const toolbarIds = new Set(toolbarFilterIds(schema));\n return {\n headingTitle: searchResultsHeading(\n pathFilters,\n schema?.dictionary,\n locationNames\n ),\n toolbarFilters: filters.filter((filter) => toolbarIds.has(filter.id)),\n extraFilters: filters.filter((filter) => !toolbarIds.has(filter.id)),\n sortOptions: searchSortOptions(schema?.sorts),\n };\n}\n","import { applyPathFilter, clearStagedPathFilters } from \"../search-engine\";\nimport type { SearchPathFilters } from \"../types\";\n\n/**\n * Mutable mirror of staged path filters.\n *\n * React `setState` only schedules an update, so `stageFilter` then\n * `applyStaged` in the same click would otherwise navigate the previous\n * closed-over `staged` value and drop the write (e.g. Área drafts).\n * Every staged write path updates this mirror synchronously; `applyStaged`\n * reads it.\n */\nexport class StagedFiltersMirror {\n private current: SearchPathFilters;\n\n constructor(initial: SearchPathFilters = {}) {\n this.current = initial;\n }\n\n get value(): SearchPathFilters {\n return this.current;\n }\n\n replace(next: SearchPathFilters): SearchPathFilters {\n this.current = next;\n return this.current;\n }\n\n stage(filterId: string, value: unknown): SearchPathFilters {\n this.current = applyPathFilter(this.current, filterId, value);\n return this.current;\n }\n\n clear(keepFilterIds: readonly string[] = []): SearchPathFilters {\n this.current = clearStagedPathFilters(this.current, keepFilterIds);\n return this.current;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,mBAAkE;AAClE,wBAAwD;;;ACAjD,IAAM,mBAAmB;AAGzB,SAAS,iBAAiB,SAAqC;AACpE,QAAM,MAAM,WAAW;AACvB,SAAO,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AAChD;AAMA,eAAsB,aAAa,QAAkC;AACnE,QAAM,MACJ,OAAO,WAAW,aAAc,OAAyB,IAAI;AAC/D,QAAM,QAAQ,MAAM,QAAQ,QAAQ,GAAG;AACvC,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,GAAG;AAC9C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;ACoFA,eAAsB,SACpB,KACA,MACA,WACY;AACZ,QAAM,WAAW,MAAM,UAAU,KAAK,IAAI;AAC1C,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,EAAE;AACjD,UAAM,IAAI;AAAA,MACR,gCAAgC,SAAS,MAAM,IAAI,SAAS,UAAU,SAAS,GAAG,GAChF,OAAO,WAAM,KAAK,MAAM,GAAG,GAAG,CAAC,KAAK,EACtC;AAAA,MACA,EAAE,QAAQ,SAAS,QAAQ,IAAI;AAAA,IACjC;AAAA,EACF;AACA,SAAQ,MAAM,SAAS,KAAK;AAC9B;AAGO,IAAM,kBAAN,cAA8B,MAAM;AAAA,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AA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,aAAa,OAAO;AAAA,IACpB,SAAS,OAAO;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["parseAppliedSearchQuery","reduceAppliedSearchQuery","composeSearchPublicHref","composeSearchPublicPath","parseSearchPublicPath","parseSearchPublicPath","parseAppliedSearchQuery","composeSearchPublicPath","composeSearchPublicHref","reduceAppliedSearchQuery"]}