@garagem-ai/site-sdk 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -479,2307 +479,2342 @@ async function getShareLink(options) {
479
479
  );
480
480
  }
481
481
 
482
- // src/schedule.ts
483
- var VISIT_TIME_ZONE = "America/Sao_Paulo";
484
- var HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
485
- var VISIT_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)(?::[0-5]\d(?:\.\d+)?)?$/;
486
- var YMD_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
487
- var ISO_INSTANT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
488
- var DATETIME_LOCAL_RE = /^(\d{4}-\d{2}-\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
489
- var WEEKDAY_SHORT = {
490
- Sun: 0,
491
- Mon: 1,
492
- Tue: 2,
493
- Wed: 3,
494
- Thu: 4,
495
- Fri: 5,
496
- Sat: 6
497
- };
498
- function pad2(value) {
499
- return String(value).padStart(2, "0");
482
+ // ../search-url/types.ts
483
+ var SEARCH_BASE_ROUTE = "imoveis";
484
+ var MAX_PAGE = 1e4;
485
+ var MAX_LOC_GROUPS = 20;
486
+ var DEFAULT_MIN_PRICE = 0;
487
+ var DEFAULT_MAX_PRICE = 1e9;
488
+ var DEFAULT_MIN_AREA = 0;
489
+ var DEFAULT_MAX_AREA = 1e5;
490
+ var SORT_URL_TOKENS = [
491
+ "recentes",
492
+ "preco-asc",
493
+ "preco-desc",
494
+ "area-asc",
495
+ "area-desc"
496
+ ];
497
+
498
+ // ../search-url/slugify.ts
499
+ function slugifyForUrl(text2) {
500
+ if (!text2) return "";
501
+ const withDashes = text2.replace(/([a-z])([A-Z])/g, "$1-$2");
502
+ return withDashes.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
500
503
  }
501
- function parseHHmm(value) {
502
- const match = HHMM_RE.exec(value);
503
- if (!match) return null;
504
- return { hour: Number(match[1]), minute: Number(match[2]) };
504
+
505
+ // ../search-url/catalog.ts
506
+ var PROPERTY_TYPE_SLUG_ALIASES = {
507
+ rural: ["chacara", "fazenda", "sitio"]
508
+ };
509
+ function buildListingTypeOptions(enabled) {
510
+ const flags = enabled ?? { sale: true, rental: true };
511
+ const out = [];
512
+ if (flags.sale !== false) {
513
+ out.push({ id: "sale", slug: "venda", label: "Venda" });
514
+ }
515
+ if (flags.rental !== false) {
516
+ out.push({ id: "rental", slug: "aluguel", label: "Aluguel" });
517
+ }
518
+ return out;
505
519
  }
506
- function minutesOfDay(hhmm) {
507
- const parsed = parseHHmm(hhmm);
508
- if (!parsed) return null;
509
- return parsed.hour * 60 + parsed.minute;
520
+ function emptySearchUrlDictionary() {
521
+ return {
522
+ listingTypes: buildListingTypeOptions(null),
523
+ propertyTypes: [],
524
+ propertyFeatures: [],
525
+ buildingAmenities: []
526
+ };
510
527
  }
511
- function normalizeVisitTime(value) {
512
- const match = VISIT_TIME_RE.exec(value.trim());
513
- return match ? `${match[1]}:${match[2]}` : null;
528
+ function norm(value) {
529
+ return slugifyForUrl(value) || value.toLowerCase();
514
530
  }
515
- function expandVisitTimeSlots(hours) {
516
- const start = minutesOfDay(hours.start);
517
- const end = minutesOfDay(hours.end);
518
- if (start == null || end == null || start > end) return [];
519
- const slots = [];
520
- for (let minutes = start; minutes <= end; minutes += 60) {
521
- const hour = Math.floor(minutes / 60);
522
- const minute = minutes % 60;
523
- slots.push(`${pad2(hour)}:${pad2(minute)}`);
531
+ function matchOptionId(segment, options, extraAliases) {
532
+ const n = norm(segment);
533
+ for (const option of options) {
534
+ const aliases = extraAliases?.[option.id] ?? [];
535
+ const candidates = [option.id, option.slug, option.label, ...aliases];
536
+ if (candidates.some((c) => norm(c) === n)) return option.id;
524
537
  }
525
- return slots;
538
+ return null;
526
539
  }
527
- function unionSorted(left, right) {
528
- return Array.from(/* @__PURE__ */ new Set([...left, ...right])).sort();
540
+ function optionSlugById(id, options) {
541
+ const option = options.find((item) => item.id === id);
542
+ return option?.slug ?? null;
529
543
  }
530
- function expandVisitSchedule(config) {
531
- const weekendHours = config.weekend ?? (config.saturday || config.sunday ? config.weekday : null);
532
- const weekdayTimeSlots = expandVisitTimeSlots(config.weekday);
533
- const weekendTimeSlots = weekendHours ? expandVisitTimeSlots(weekendHours) : [];
534
- const disabledDays = [];
535
- if (!config.sunday) disabledDays.push(0);
536
- if (!config.saturday) disabledDays.push(6);
537
- return {
538
- ...config,
539
- weekend: weekendHours,
540
- disabledDays,
541
- weekdayTimeSlots,
542
- weekendTimeSlots,
543
- timeSlots: unionSorted(weekdayTimeSlots, weekendTimeSlots)
544
- };
544
+ var LISTING_TYPE_ALIASES = {
545
+ sale: ["comprar"],
546
+ rental: ["alugar"]
547
+ };
548
+
549
+ // ../search-url/path.ts
550
+ function toArray(value) {
551
+ if (value === void 0) return [];
552
+ return Array.isArray(value) ? value : [value];
545
553
  }
546
- var STUDIO_DEFAULT_VISIT_SCHEDULE = expandVisitSchedule(
547
- {
548
- timeZone: VISIT_TIME_ZONE,
549
- saturday: false,
550
- sunday: false,
551
- weekday: { start: "06:00", end: "22:00" },
552
- weekend: null,
553
- minHoursAhead: 2
554
- }
555
- );
556
- function zonedParts(date, timeZone) {
557
- const parts = new Intl.DateTimeFormat("en-US", {
558
- timeZone,
559
- weekday: "short",
560
- year: "numeric",
561
- month: "2-digit",
562
- day: "2-digit",
563
- hour: "2-digit",
564
- minute: "2-digit",
565
- hourCycle: "h23"
566
- }).formatToParts(date);
567
- const get = (type) => parts.find((part) => part.type === type)?.value ?? "";
568
- const weekday = WEEKDAY_SHORT[get("weekday")] ?? 0;
569
- return {
570
- year: Number(get("year")),
571
- month: Number(get("month")),
572
- day: Number(get("day")),
573
- hour: Number(get("hour")),
574
- minute: Number(get("minute")),
575
- weekday
576
- };
554
+ function formatNumeric(value) {
555
+ return Array.isArray(value) ? value.join("-") : String(value);
577
556
  }
578
- function calendarYmd(date, timeZone) {
579
- const parts = zonedParts(date, timeZone);
580
- return `${parts.year}-${pad2(parts.month)}-${pad2(parts.day)}`;
557
+ function formatRange(min, max, unit) {
558
+ return `de-${min}-a-${max}-${unit}`;
581
559
  }
582
- function parseYmd(value) {
583
- const match = YMD_RE.exec(value);
584
- if (!match) return null;
585
- const year = Number(match[1]);
586
- const month = Number(match[2]);
587
- const day = Number(match[3]);
588
- const utc = new Date(Date.UTC(year, month - 1, day));
589
- if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
590
- return null;
591
- }
592
- return { year, month, day };
560
+ function formatSuiteSuffix(value) {
561
+ const values = Array.isArray(value) ? value : [value];
562
+ const firstValue = values[0] ?? 0;
563
+ return firstValue === 0 || firstValue === 1 ? "suite" : "suites";
593
564
  }
594
- function normalizeVisitDate(date, timeZone = VISIT_TIME_ZONE) {
595
- if (typeof date === "string") {
596
- const trimmed = date.trim();
597
- if (parseYmd(trimmed)) return trimmed;
598
- if (ISO_INSTANT_RE.test(trimmed)) {
599
- const instant = new Date(trimmed);
600
- return Number.isFinite(instant.getTime()) ? calendarYmd(instant, timeZone) : null;
601
- }
602
- const local = DATETIME_LOCAL_RE.exec(trimmed);
603
- if (local && parseYmd(local[1])) return local[1];
604
- return null;
565
+ function composeSearchPublicPath(filters, dictionary = emptySearchUrlDictionary()) {
566
+ const segments = [];
567
+ const listingType = filters.listingType;
568
+ if (listingType) {
569
+ segments.push(
570
+ optionSlugById(listingType, dictionary.listingTypes) || slugifyForUrl(listingType)
571
+ );
605
572
  }
606
- if (date instanceof Date && Number.isFinite(date.getTime())) {
607
- return calendarYmd(date, timeZone);
573
+ for (const propertyType of toArray(filters.propertyType)) {
574
+ segments.push(
575
+ optionSlugById(propertyType, dictionary.propertyTypes) || slugifyForUrl(propertyType)
576
+ );
608
577
  }
609
- return null;
610
- }
611
- function weekdayOfYmd(ymd, timeZone) {
612
- const parsed = parseYmd(ymd);
613
- if (!parsed) return null;
614
- const utcNoonish = new Date(
615
- Date.UTC(parsed.year, parsed.month - 1, parsed.day, 15, 0, 0)
616
- );
617
- return zonedParts(utcNoonish, timeZone).weekday;
578
+ const location = filters.location;
579
+ if (location) {
580
+ if (location.state) segments.push(slugifyForUrl(location.state));
581
+ if (location.city) segments.push(slugifyForUrl(location.city));
582
+ if (location.neighborhood)
583
+ segments.push(slugifyForUrl(location.neighborhood));
584
+ if (location.street) segments.push(slugifyForUrl(location.street));
585
+ }
586
+ if (filters.bedrooms !== void 0) {
587
+ segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);
588
+ }
589
+ if (filters.bathrooms !== void 0) {
590
+ segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);
591
+ }
592
+ if (filters.suites !== void 0) {
593
+ const suffix = formatSuiteSuffix(filters.suites);
594
+ segments.push(`${formatNumeric(filters.suites)}-${suffix}`);
595
+ }
596
+ if (filters.parkingSpots !== void 0) {
597
+ segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);
598
+ }
599
+ if (filters.price && (filters.price.min !== void 0 || filters.price.max !== void 0)) {
600
+ const min = filters.price.min ?? DEFAULT_MIN_PRICE;
601
+ const max = filters.price.max ?? DEFAULT_MAX_PRICE;
602
+ segments.push(formatRange(min, max, "reais"));
603
+ }
604
+ if (filters.area && (filters.area.min !== void 0 || filters.area.max !== void 0)) {
605
+ const min = filters.area.min ?? DEFAULT_MIN_AREA;
606
+ const max = filters.area.max ?? DEFAULT_MAX_AREA;
607
+ segments.push(formatRange(min, max, "m2"));
608
+ }
609
+ const seenAmenities = /* @__PURE__ */ new Set();
610
+ for (const id of filters.propertyFeatures ?? []) {
611
+ const slug = optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);
612
+ if (!slug || seenAmenities.has(slug)) continue;
613
+ seenAmenities.add(slug);
614
+ segments.push(slug);
615
+ }
616
+ for (const id of filters.buildingAmenities ?? []) {
617
+ const slug = optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);
618
+ if (!slug || seenAmenities.has(slug)) continue;
619
+ seenAmenities.add(slug);
620
+ segments.push(slug);
621
+ }
622
+ const path = segments.filter(Boolean).join("/");
623
+ return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;
618
624
  }
619
- function slotsForDate(schedule, date, now = /* @__PURE__ */ new Date()) {
620
- const timeZone = schedule.timeZone;
621
- const ymd = normalizeVisitDate(date, timeZone);
622
- if (!ymd) return [];
623
- const weekday = weekdayOfYmd(ymd, timeZone);
624
- if (weekday == null) return [];
625
- if (schedule.disabledDays.includes(weekday)) return [];
626
- if (weekday === 0 && !schedule.sunday) return [];
627
- if (weekday === 6 && !schedule.saturday) return [];
628
- const base = weekday === 0 || weekday === 6 ? schedule.weekendTimeSlots : schedule.weekdayTimeSlots;
629
- const today = calendarYmd(now, timeZone);
630
- if (ymd < today) return [];
631
- if (ymd !== today) return [...base];
632
- const nowParts = zonedParts(now, timeZone);
633
- const cutoff = nowParts.hour * 60 + nowParts.minute + schedule.minHoursAhead * 60;
634
- return base.filter((slot) => {
635
- const minutes = minutesOfDay(slot);
636
- return minutes != null && minutes >= cutoff;
637
- });
625
+ var BEDROOMS = /^(\d+(?:-\d+)*)-quartos?$/;
626
+ var BATHROOMS = /^(\d+(?:-\d+)*)-banheiros?$/;
627
+ var SUITES = /^(\d+(?:-\d+)*)-suites?$/;
628
+ var PARKING = /^(\d+(?:-\d+)*)-vagas?$/;
629
+ var PRICE = /^de-(\d+)-a-(\d+)-(reais|real)$/;
630
+ var AREA = /^de-(\d+)-a-(\d+)-(m2|m²)$/;
631
+ function parseNumericList(raw) {
632
+ return raw.split("-").map((part) => Number(part)).filter((n) => Number.isFinite(n));
638
633
  }
639
- function isVisitSlotAllowed(schedule, visitDate, visitTime, now = /* @__PURE__ */ new Date()) {
640
- const time = normalizeVisitTime(visitTime);
641
- if (!time) return false;
642
- return slotsForDate(schedule, visitDate, now).includes(time);
634
+ function collapse(values) {
635
+ return values.length === 1 ? values[0] : values;
636
+ }
637
+ function parseSearchPublicPath(pathname, dictionary = emptySearchUrlDictionary()) {
638
+ const raw = pathname.split(/[?#]/)[0] ?? "";
639
+ let segments = raw.replace(/^\//, "").split("/").filter(Boolean);
640
+ if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);
641
+ if (segments.some((segment) => segment.includes("."))) return null;
642
+ if (segments.some((segment) => segment.toLowerCase().startsWith("id-"))) {
643
+ return null;
644
+ }
645
+ const filters = {};
646
+ const locationParts = [];
647
+ const propertyTypes = [];
648
+ const propertyFeatures = [];
649
+ const buildingAmenities = [];
650
+ for (const segment of segments) {
651
+ const lower = segment.toLowerCase();
652
+ const listingType = matchOptionId(
653
+ segment,
654
+ dictionary.listingTypes,
655
+ LISTING_TYPE_ALIASES
656
+ );
657
+ if (listingType && !filters.listingType) {
658
+ filters.listingType = listingType;
659
+ continue;
660
+ }
661
+ const propertyType = matchOptionId(
662
+ segment,
663
+ dictionary.propertyTypes,
664
+ PROPERTY_TYPE_SLUG_ALIASES
665
+ );
666
+ if (propertyType) {
667
+ propertyTypes.push(propertyType);
668
+ continue;
669
+ }
670
+ const bedrooms = lower.match(BEDROOMS);
671
+ if (bedrooms) {
672
+ filters.bedrooms = collapse(parseNumericList(bedrooms[1]));
673
+ continue;
674
+ }
675
+ const bathrooms = lower.match(BATHROOMS);
676
+ if (bathrooms) {
677
+ filters.bathrooms = collapse(parseNumericList(bathrooms[1]));
678
+ continue;
679
+ }
680
+ const suites = lower.match(SUITES);
681
+ if (suites) {
682
+ filters.suites = collapse(parseNumericList(suites[1]));
683
+ continue;
684
+ }
685
+ const parking = lower.match(PARKING);
686
+ if (parking) {
687
+ filters.parkingSpots = collapse(parseNumericList(parking[1]));
688
+ continue;
689
+ }
690
+ const price = lower.match(PRICE);
691
+ if (price) {
692
+ filters.price = { min: Number(price[1]), max: Number(price[2]) };
693
+ continue;
694
+ }
695
+ const area = lower.match(AREA);
696
+ if (area) {
697
+ filters.area = { min: Number(area[1]), max: Number(area[2]) };
698
+ continue;
699
+ }
700
+ const featureId = matchOptionId(segment, dictionary.propertyFeatures);
701
+ if (featureId) {
702
+ propertyFeatures.push(featureId);
703
+ continue;
704
+ }
705
+ const amenityId = matchOptionId(segment, dictionary.buildingAmenities);
706
+ if (amenityId) {
707
+ buildingAmenities.push(amenityId);
708
+ continue;
709
+ }
710
+ locationParts.push(segment);
711
+ }
712
+ if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];
713
+ else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;
714
+ if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;
715
+ if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;
716
+ const location = locationFromPathLeftovers(locationParts);
717
+ if (location) filters.location = location;
718
+ return filters;
719
+ }
720
+ var PATH_STREET_PREFIX = /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;
721
+ function locationFromPathLeftovers(parts) {
722
+ if (parts.length === 0) return void 0;
723
+ if (parts.length === 1) {
724
+ const value = parts[0];
725
+ if (PATH_STREET_PREFIX.test(value)) return { street: value };
726
+ if (/^[a-z]{2}$/i.test(value)) return { state: value };
727
+ return { neighborhood: value };
728
+ }
729
+ const [state, city, neighborhood, street] = parts;
730
+ return {
731
+ ...state ? { state } : {},
732
+ ...city ? { city } : {},
733
+ ...neighborhood ? { neighborhood } : {},
734
+ ...street ? { street } : {}
735
+ };
643
736
  }
644
737
 
645
- // src/phone.ts
646
- import {
647
- AsYouType,
648
- isValidPhoneNumber,
649
- parsePhoneNumber
650
- } from "libphonenumber-js";
651
-
652
- // src/phone-countries.ts
653
- var DEFAULT_PHONE_COUNTRY_CODE = "BR";
654
- var PHONE_COUNTRIES = [
655
- { code: "BR", name: "Brasil", dialCode: "55", flag: "\u{1F1E7}\u{1F1F7}" },
656
- { code: "US", name: "Estados Unidos", dialCode: "1", flag: "\u{1F1FA}\u{1F1F8}" },
657
- { code: "CA", name: "Canad\xE1", dialCode: "1", flag: "\u{1F1E8}\u{1F1E6}" },
658
- { code: "MX", name: "M\xE9xico", dialCode: "52", flag: "\u{1F1F2}\u{1F1FD}" },
659
- { code: "GT", name: "Guatemala", dialCode: "502", flag: "\u{1F1EC}\u{1F1F9}" },
660
- { code: "BZ", name: "Belize", dialCode: "501", flag: "\u{1F1E7}\u{1F1FF}" },
661
- { code: "SV", name: "El Salvador", dialCode: "503", flag: "\u{1F1F8}\u{1F1FB}" },
662
- { code: "HN", name: "Honduras", dialCode: "504", flag: "\u{1F1ED}\u{1F1F3}" },
663
- { code: "NI", name: "Nicar\xE1gua", dialCode: "505", flag: "\u{1F1F3}\u{1F1EE}" },
664
- { code: "CR", name: "Costa Rica", dialCode: "506", flag: "\u{1F1E8}\u{1F1F7}" },
665
- { code: "PA", name: "Panam\xE1", dialCode: "507", flag: "\u{1F1F5}\u{1F1E6}" },
666
- { code: "CU", name: "Cuba", dialCode: "53", flag: "\u{1F1E8}\u{1F1FA}" },
667
- { code: "DO", name: "Rep\xFAblica Dominicana", dialCode: "1", flag: "\u{1F1E9}\u{1F1F4}" },
668
- { code: "HT", name: "Haiti", dialCode: "509", flag: "\u{1F1ED}\u{1F1F9}" },
669
- { code: "AR", name: "Argentina", dialCode: "54", flag: "\u{1F1E6}\u{1F1F7}" },
670
- { code: "CL", name: "Chile", dialCode: "56", flag: "\u{1F1E8}\u{1F1F1}" },
671
- { code: "CO", name: "Col\xF4mbia", dialCode: "57", flag: "\u{1F1E8}\u{1F1F4}" },
672
- { code: "PE", name: "Peru", dialCode: "51", flag: "\u{1F1F5}\u{1F1EA}" },
673
- { code: "UY", name: "Uruguai", dialCode: "598", flag: "\u{1F1FA}\u{1F1FE}" },
674
- { code: "PY", name: "Paraguai", dialCode: "595", flag: "\u{1F1F5}\u{1F1FE}" },
675
- { code: "BO", name: "Bol\xEDvia", dialCode: "591", flag: "\u{1F1E7}\u{1F1F4}" },
676
- { code: "EC", name: "Equador", dialCode: "593", flag: "\u{1F1EA}\u{1F1E8}" },
677
- { code: "VE", name: "Venezuela", dialCode: "58", flag: "\u{1F1FB}\u{1F1EA}" },
678
- { code: "GY", name: "Guiana", dialCode: "592", flag: "\u{1F1EC}\u{1F1FE}" },
679
- { code: "SR", name: "Suriname", dialCode: "597", flag: "\u{1F1F8}\u{1F1F7}" },
680
- { code: "PT", name: "Portugal", dialCode: "351", flag: "\u{1F1F5}\u{1F1F9}" },
681
- { code: "ES", name: "Espanha", dialCode: "34", flag: "\u{1F1EA}\u{1F1F8}" },
682
- { code: "FR", name: "Fran\xE7a", dialCode: "33", flag: "\u{1F1EB}\u{1F1F7}" },
683
- { code: "UK", name: "Reino Unido", dialCode: "44", flag: "\u{1F1EC}\u{1F1E7}" },
684
- { code: "DE", name: "Alemanha", dialCode: "49", flag: "\u{1F1E9}\u{1F1EA}" },
685
- { code: "IT", name: "It\xE1lia", dialCode: "39", flag: "\u{1F1EE}\u{1F1F9}" },
686
- { code: "NL", name: "Holanda", dialCode: "31", flag: "\u{1F1F3}\u{1F1F1}" },
687
- { code: "BE", name: "B\xE9lgica", dialCode: "32", flag: "\u{1F1E7}\u{1F1EA}" },
688
- { code: "CH", name: "Su\xED\xE7a", dialCode: "41", flag: "\u{1F1E8}\u{1F1ED}" },
689
- { code: "AT", name: "\xC1ustria", dialCode: "43", flag: "\u{1F1E6}\u{1F1F9}" },
690
- { code: "SE", name: "Su\xE9cia", dialCode: "46", flag: "\u{1F1F8}\u{1F1EA}" },
691
- { code: "NO", name: "Noruega", dialCode: "47", flag: "\u{1F1F3}\u{1F1F4}" },
692
- { code: "DK", name: "Dinamarca", dialCode: "45", flag: "\u{1F1E9}\u{1F1F0}" },
693
- { code: "FI", name: "Finl\xE2ndia", dialCode: "358", flag: "\u{1F1EB}\u{1F1EE}" },
694
- { code: "IE", name: "Irlanda", dialCode: "353", flag: "\u{1F1EE}\u{1F1EA}" },
695
- { code: "AU", name: "Austr\xE1lia", dialCode: "61", flag: "\u{1F1E6}\u{1F1FA}" },
696
- { code: "NZ", name: "Nova Zel\xE2ndia", dialCode: "64", flag: "\u{1F1F3}\u{1F1FF}" },
697
- { code: "JP", name: "Jap\xE3o", dialCode: "81", flag: "\u{1F1EF}\u{1F1F5}" },
698
- { code: "KR", name: "Coreia do Sul", dialCode: "82", flag: "\u{1F1F0}\u{1F1F7}" },
699
- { code: "CN", name: "China", dialCode: "86", flag: "\u{1F1E8}\u{1F1F3}" },
700
- { code: "IN", name: "\xCDndia", dialCode: "91", flag: "\u{1F1EE}\u{1F1F3}" },
701
- { code: "RU", name: "R\xFAssia", dialCode: "7", flag: "\u{1F1F7}\u{1F1FA}" },
702
- { code: "UA", name: "Ucr\xE2nia", dialCode: "380", flag: "\u{1F1FA}\u{1F1E6}" },
703
- { code: "AE", name: "Emirados \xC1rabes", dialCode: "971", flag: "\u{1F1E6}\u{1F1EA}" },
704
- { code: "SA", name: "Ar\xE1bia Saudita", dialCode: "966", flag: "\u{1F1F8}\u{1F1E6}" },
705
- { code: "QA", name: "Catar", dialCode: "974", flag: "\u{1F1F6}\u{1F1E6}" },
706
- { code: "KW", name: "Kuwait", dialCode: "965", flag: "\u{1F1F0}\u{1F1FC}" },
707
- { code: "BH", name: "Bahrein", dialCode: "973", flag: "\u{1F1E7}\u{1F1ED}" },
708
- { code: "OM", name: "Om\xE3", dialCode: "968", flag: "\u{1F1F4}\u{1F1F2}" },
709
- { code: "JO", name: "Jord\xE2nia", dialCode: "962", flag: "\u{1F1EF}\u{1F1F4}" },
710
- { code: "LB", name: "L\xEDbano", dialCode: "961", flag: "\u{1F1F1}\u{1F1E7}" },
711
- { code: "IL", name: "Israel", dialCode: "972", flag: "\u{1F1EE}\u{1F1F1}" },
712
- { code: "TR", name: "Turquia", dialCode: "90", flag: "\u{1F1F9}\u{1F1F7}" },
713
- { code: "EG", name: "Egito", dialCode: "20", flag: "\u{1F1EA}\u{1F1EC}" },
714
- { code: "ZA", name: "\xC1frica do Sul", dialCode: "27", flag: "\u{1F1FF}\u{1F1E6}" },
715
- { code: "AO", name: "Angola", dialCode: "244", flag: "\u{1F1E6}\u{1F1F4}" },
716
- { code: "MZ", name: "Mo\xE7ambique", dialCode: "258", flag: "\u{1F1F2}\u{1F1FF}" },
717
- { code: "CV", name: "Cabo Verde", dialCode: "238", flag: "\u{1F1E8}\u{1F1FB}" }
718
- ];
719
- function phoneCountrySearchValue(country) {
720
- return `${country.name} ${country.code} ${country.dialCode} +${country.dialCode}`;
738
+ // ../search-url/applied-query.ts
739
+ var SORT_SET = new Set(SORT_URL_TOKENS);
740
+ function isSortToken(value) {
741
+ return SORT_SET.has(value);
721
742
  }
722
- function findPhoneCountry(code) {
723
- if (!code) return void 0;
724
- const normalized = code.trim().toUpperCase();
725
- return PHONE_COUNTRIES.find((country) => country.code === normalized);
743
+ function normalizeAppliedSearchQuery(query) {
744
+ if (query.loc && query.loc.length > 0) {
745
+ const { query: _query, ...rest } = query;
746
+ return rest;
747
+ }
748
+ return query;
726
749
  }
727
- function defaultPhoneCountry() {
728
- return findPhoneCountry(DEFAULT_PHONE_COUNTRY_CODE) ?? PHONE_COUNTRIES[0];
750
+ function parseAppliedSearchQuery(search) {
751
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
752
+ const result = {};
753
+ const pageRaw = params.get("page");
754
+ if (pageRaw) {
755
+ const page = Number.parseInt(pageRaw, 10);
756
+ if (Number.isFinite(page) && page > 1) {
757
+ result.page = Math.min(page, MAX_PAGE);
758
+ }
759
+ }
760
+ const sort = params.get("ordenar");
761
+ if (sort && isSortToken(sort)) result.sort = sort;
762
+ const q = params.get("q")?.trim();
763
+ if (q) result.query = q;
764
+ const loc = params.getAll("loc").map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
765
+ if (loc.length > 0) result.loc = loc;
766
+ return normalizeAppliedSearchQuery(result);
729
767
  }
730
-
731
- // src/phone.ts
732
- var MAX_NATIONAL_PHONE_DIGITS = 15;
733
- var VALID_BR_DDDS = /* @__PURE__ */ new Set([
734
- "11",
735
- "12",
736
- "13",
737
- "14",
738
- "15",
739
- "16",
740
- "17",
741
- "18",
742
- "19",
743
- "21",
744
- "22",
745
- "24",
746
- "27",
747
- "28",
748
- "31",
749
- "32",
750
- "33",
751
- "34",
752
- "35",
753
- "37",
754
- "38",
755
- "41",
756
- "42",
757
- "43",
758
- "44",
759
- "45",
760
- "46",
761
- "47",
762
- "48",
763
- "49",
764
- "51",
765
- "53",
766
- "54",
767
- "55",
768
- "61",
769
- "62",
770
- "63",
771
- "64",
772
- "65",
773
- "66",
774
- "67",
775
- "68",
776
- "69",
777
- "71",
778
- "73",
779
- "74",
780
- "75",
781
- "77",
782
- "79",
783
- "81",
784
- "82",
785
- "83",
786
- "84",
787
- "85",
788
- "86",
789
- "87",
790
- "88",
791
- "89",
792
- "91",
793
- "92",
794
- "93",
795
- "94",
796
- "95",
797
- "96",
798
- "97",
799
- "98",
800
- "99"
801
- ]);
802
- var PHONE_INPUT_COUNTRY_CODES = new Set(
803
- PHONE_COUNTRIES.map((country) => country.code)
804
- );
805
- var SORTED_PHONE_INPUT_DIAL_CODES = [
806
- ...new Set(PHONE_COUNTRIES.map((country) => country.dialCode))
807
- ].sort((a, b) => b.length - a.length);
808
- function toLibCountryCode(code) {
809
- if (code === "UK") return "GB";
810
- return code;
811
- }
812
- function fromLibCountryCode(code) {
813
- if (code === "GB") return "UK";
814
- return code;
815
- }
816
- function nationalPhoneDigits(value) {
817
- return String(value ?? "").replace(/\D/g, "");
818
- }
819
- function truncateNationalPhoneDigits(digits, max = MAX_NATIONAL_PHONE_DIGITS) {
820
- return digits.slice(0, max);
821
- }
822
- function collapseDuplicatedBrazilianMobileNine(digits) {
823
- if (digits.length === 14 && digits.startsWith("55")) {
824
- const national = collapseDuplicatedBrazilianMobileNine(digits.slice(2));
825
- return national === digits.slice(2) ? digits : `55${national}`;
768
+ var APPLIED_QUERY_KEYS = ["page", "ordenar", "q", "loc"];
769
+ function serializeAppliedSearchQuery(query) {
770
+ const normalized = normalizeAppliedSearchQuery(query);
771
+ const params = new URLSearchParams();
772
+ if (normalized.page !== void 0 && normalized.page > 1) {
773
+ params.set("page", String(Math.min(normalized.page, MAX_PAGE)));
826
774
  }
827
- if (digits.length !== 12) return digits;
828
- const ddd = digits.slice(0, 2);
829
- if (!VALID_BR_DDDS.has(ddd)) return digits;
830
- if (digits.charAt(2) !== "9") return digits;
831
- const rest = digits.slice(3);
832
- if (rest.length !== 9 || rest.charAt(0) !== "9") return digits;
833
- if (ddd === "55") {
834
- const subscriberFirst = digits.charAt(4);
835
- if (subscriberFirst >= "0" && subscriberFirst <= "5") {
836
- return digits;
837
- }
775
+ if (normalized.sort && isSortToken(normalized.sort)) {
776
+ params.set("ordenar", normalized.sort);
838
777
  }
839
- return `${ddd}${rest}`;
778
+ const text2 = normalized.query?.trim();
779
+ if (text2) params.set("q", text2);
780
+ for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {
781
+ const trimmed = value.trim();
782
+ if (trimmed) params.append("loc", trimmed);
783
+ }
784
+ return params;
840
785
  }
841
- var BR_DIAL_CODE = "55";
842
- function stripAccidentalDialCodePrefix(numbers, country) {
843
- const dial = country.dialCode;
844
- if (!numbers.startsWith(dial) || numbers.length <= dial.length) {
845
- return numbers;
786
+ function mergeAppliedSearchQueryIntoSearch(existing, query) {
787
+ const params = existing instanceof URLSearchParams ? new URLSearchParams(existing) : new URLSearchParams(
788
+ existing.startsWith("?") ? existing.slice(1) : existing
789
+ );
790
+ for (const key of APPLIED_QUERY_KEYS) {
791
+ params.delete(key);
846
792
  }
847
- const withoutDial = numbers.slice(dial.length);
848
- if (!withoutDial) return numbers;
849
- try {
850
- const parsed = parsePhoneNumber(numbers, toLibCountryCode(country.code));
851
- if (parsed.nationalNumber === numbers) {
852
- return numbers;
793
+ const serialized = serializeAppliedSearchQuery(query);
794
+ serialized.forEach((value, key) => {
795
+ if (key === "loc") {
796
+ params.append("loc", value);
797
+ } else {
798
+ params.set(key, value);
853
799
  }
854
- if (parsed.countryCallingCode === dial && parsed.nationalNumber === withoutDial) {
855
- return withoutDial;
800
+ });
801
+ return params;
802
+ }
803
+ function reduceAppliedSearchQuery(prev, change) {
804
+ switch (change.type) {
805
+ case "sort": {
806
+ const next = { ...prev };
807
+ delete next.page;
808
+ if (change.sort) next.sort = change.sort;
809
+ else delete next.sort;
810
+ return normalizeAppliedSearchQuery(next);
811
+ }
812
+ case "applyFilters": {
813
+ const next = { ...prev };
814
+ delete next.page;
815
+ return normalizeAppliedSearchQuery(next);
816
+ }
817
+ case "query": {
818
+ const next = { ...prev };
819
+ delete next.page;
820
+ const trimmed = change.query.trim();
821
+ if (trimmed) {
822
+ next.query = trimmed;
823
+ delete next.loc;
824
+ } else {
825
+ delete next.query;
826
+ }
827
+ return normalizeAppliedSearchQuery(next);
828
+ }
829
+ case "loc": {
830
+ const next = { ...prev };
831
+ delete next.page;
832
+ delete next.query;
833
+ const loc = change.loc.map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
834
+ if (loc.length > 0) next.loc = loc;
835
+ else delete next.loc;
836
+ return normalizeAppliedSearchQuery(next);
837
+ }
838
+ case "page": {
839
+ const next = { ...prev };
840
+ if (change.page <= 1) delete next.page;
841
+ else next.page = Math.min(change.page, MAX_PAGE);
842
+ return normalizeAppliedSearchQuery(next);
843
+ }
844
+ default: {
845
+ const _exhaustive = change;
846
+ return _exhaustive;
856
847
  }
857
- } catch {
858
848
  }
859
- return numbers;
860
849
  }
861
- function prepareNationalDigits(value, country) {
862
- const raw = nationalPhoneDigits(value);
863
- const stripped = stripAccidentalDialCodePrefix(raw, country);
864
- const digits = country.dialCode === BR_DIAL_CODE ? collapseDuplicatedBrazilianMobileNine(stripped) : stripped;
865
- return truncateNationalPhoneDigits(digits);
850
+ function composeSearchPublicHref(pathname, query, existingSearch) {
851
+ const params = existingSearch ? mergeAppliedSearchQueryIntoSearch(existingSearch, query) : serializeAppliedSearchQuery(query);
852
+ const qs = params.toString();
853
+ return qs ? `${pathname}?${qs}` : pathname;
866
854
  }
867
- function prepareInternationalDigits(value) {
868
- const digits = nationalPhoneDigits(value);
869
- const collapsed = collapseDuplicatedBrazilianMobileNine(digits);
870
- if (collapsed === digits) return digits;
871
- try {
872
- const original = parsePhoneNumber(`+${digits}`);
873
- if (original.isValid() && original.countryCallingCode !== BR_DIAL_CODE) {
874
- return digits;
875
- }
876
- } catch {
877
- }
878
- return collapsed;
855
+
856
+ // src/applied-query.ts
857
+ function parseAppliedSearchQuery2(search) {
858
+ return parseAppliedSearchQuery(search);
879
859
  }
880
- function formatNationalDigits(digits, country) {
881
- if (!digits) return "";
882
- const libCode = toLibCountryCode(country.code);
883
- const formatter = new AsYouType(libCode);
884
- formatter.input(`+${country.dialCode}${digits}`);
885
- const national = formatter.getNumber()?.formatNational();
886
- if (national && nationalPhoneDigits(national) === digits) return national;
887
- const asTyped = new AsYouType(libCode).input(digits);
888
- if (nationalPhoneDigits(asTyped) === digits) return asTyped;
889
- return digits;
860
+ function serializeAppliedSearchQuery2(query) {
861
+ return serializeAppliedSearchQuery(query);
890
862
  }
891
- function formatPhoneNational(value, countryCode = DEFAULT_PHONE_COUNTRY_CODE) {
892
- const country = findPhoneCountry(countryCode) ?? defaultPhoneCountry();
893
- return formatNationalDigits(prepareNationalDigits(value, country), country);
863
+ function mergeAppliedSearchQueryIntoSearch2(existing, query) {
864
+ return mergeAppliedSearchQueryIntoSearch(existing, query);
894
865
  }
895
- function parsePhoneInput(input) {
896
- const cleaned = String(input ?? "").replace(/[\s\-().]/g, "");
897
- if (!cleaned) {
898
- return { ddi: null, national: "", countryCode: null };
866
+ function reduceAppliedSearchQuery2(prev, change) {
867
+ return reduceAppliedSearchQuery(prev, change);
868
+ }
869
+ function composeSearchPublicHref2(pathname, query, existingSearch) {
870
+ return composeSearchPublicHref(pathname, query, existingSearch);
871
+ }
872
+
873
+ // src/loc-params.ts
874
+ function pathLocationToFilterInput(location) {
875
+ if (!location || typeof location !== "object") return null;
876
+ const { state, city, neighborhood, street } = location;
877
+ const levels = [];
878
+ if (state) levels.push(state);
879
+ if (city) levels.push(city);
880
+ if (neighborhood) levels.push(neighborhood);
881
+ if (street) levels.push(street);
882
+ if (levels.length === 0) return null;
883
+ if (levels.length === 1) {
884
+ if (state) return { type: "state", value: state };
885
+ if (city) return { type: "city", value: city };
886
+ if (neighborhood) return { type: "neighborhood", value: neighborhood };
887
+ if (street) return { type: "street", value: street };
899
888
  }
900
- const hasPlus = cleaned.startsWith("+");
901
- if (hasPlus) {
902
- try {
903
- const parsed = parsePhoneNumber(cleaned);
904
- if (parsed.country) {
905
- const ourCode = fromLibCountryCode(parsed.country);
906
- if (PHONE_INPUT_COUNTRY_CODES.has(ourCode)) {
907
- return {
908
- ddi: parsed.countryCallingCode,
909
- national: parsed.nationalNumber,
910
- countryCode: ourCode
911
- };
912
- }
913
- }
914
- } catch {
915
- }
916
- const digits = cleaned.slice(1);
917
- for (const ddi of SORTED_PHONE_INPUT_DIAL_CODES) {
918
- if (digits.startsWith(ddi)) {
919
- const national = digits.slice(ddi.length);
920
- const match = PHONE_COUNTRIES.find((c) => c.dialCode === ddi);
921
- return {
922
- ddi,
923
- national,
924
- countryCode: match?.code ?? null
925
- };
926
- }
927
- }
928
- return {
929
- ddi: null,
930
- national: digits,
931
- countryCode: null
932
- };
889
+ return { type: "path", value: levels.join("/") };
890
+ }
891
+
892
+ // src/path.ts
893
+ function composeSearchPublicPath2(filters, dictionary) {
894
+ return dictionary ? composeSearchPublicPath(filters, dictionary) : composeSearchPublicPath(filters);
895
+ }
896
+ function parseSearchPublicPath2(pathname, dictionary) {
897
+ return dictionary ? parseSearchPublicPath(pathname, dictionary) : parseSearchPublicPath(pathname);
898
+ }
899
+ function pathFiltersToQueryFilters(pathFilters) {
900
+ const result = {};
901
+ if (pathFilters.listingType !== void 0) {
902
+ result.listing_type = pathFilters.listingType;
933
903
  }
934
- return {
935
- ddi: null,
936
- national: cleaned.replace(/\D/g, ""),
937
- countryCode: null
938
- };
904
+ if (pathFilters.propertyType !== void 0) {
905
+ result.property_type = pathFilters.propertyType;
906
+ }
907
+ if (pathFilters.bedrooms !== void 0) {
908
+ result.property_bedrooms = pathFilters.bedrooms;
909
+ }
910
+ if (pathFilters.bathrooms !== void 0) {
911
+ result.property_bathrooms = pathFilters.bathrooms;
912
+ }
913
+ if (pathFilters.suites !== void 0) {
914
+ result.property_suites = pathFilters.suites;
915
+ }
916
+ if (pathFilters.parkingSpots !== void 0) {
917
+ result.property_parking_spots = pathFilters.parkingSpots;
918
+ }
919
+ if (pathFilters.price !== void 0) {
920
+ result.price = pathFilters.price;
921
+ }
922
+ if (pathFilters.area !== void 0) {
923
+ result.property_area_total = pathFilters.area;
924
+ }
925
+ if (pathFilters.propertyFeatures !== void 0) {
926
+ result.propertyFeatures = pathFilters.propertyFeatures;
927
+ }
928
+ if (pathFilters.buildingAmenities !== void 0) {
929
+ result.buildingAmenities = pathFilters.buildingAmenities;
930
+ }
931
+ return result;
939
932
  }
940
- function preferValidE164(candidate) {
933
+
934
+ // src/presentation.ts
935
+ function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
936
+ if (amount == null) return "Sob consulta";
941
937
  try {
942
- const number = parsePhoneNumber(candidate);
943
- if (number.isValid()) return number.number;
938
+ return new Intl.NumberFormat(locale, {
939
+ style: "currency",
940
+ currency,
941
+ minimumFractionDigits: 0,
942
+ maximumFractionDigits: 0
943
+ }).format(amount);
944
944
  } catch {
945
+ return `${currency} ${amount}`;
945
946
  }
946
- return candidate;
947
947
  }
948
- function toE164(value, countryCode = DEFAULT_PHONE_COUNTRY_CODE) {
949
- const trimmed = String(value ?? "").trim();
950
- if (!trimmed) return "";
951
- const parsed = parsePhoneInput(trimmed);
952
- if (parsed.ddi && parsed.national) {
953
- const ddiCountry = parsed.countryCode && findPhoneCountry(parsed.countryCode) || PHONE_COUNTRIES.find((c) => c.dialCode === parsed.ddi) || defaultPhoneCountry();
954
- return preferValidE164(
955
- `+${parsed.ddi}${prepareNationalDigits(parsed.national, ddiCountry)}`
956
- );
957
- }
958
- const country = findPhoneCountry(countryCode) ?? defaultPhoneCountry();
959
- const national = prepareNationalDigits(parsed.national || trimmed, country);
960
- if (!national) return "";
961
- return preferValidE164(`+${country.dialCode}${national}`);
948
+ function formatGroupedInteger(value, locale = "pt-BR") {
949
+ const digits = String(value ?? "").replace(/\D/g, "");
950
+ if (!digits) return "";
951
+ const amount = Number.parseInt(digits, 10);
952
+ if (!Number.isFinite(amount)) return "";
953
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
954
+ amount
955
+ );
962
956
  }
963
- function isValidPhone(value, countryCode) {
964
- const cleaned = String(value ?? "").trim();
965
- if (!cleaned) return false;
966
- if (cleaned.startsWith("+")) {
967
- const digits2 = prepareInternationalDigits(cleaned);
968
- return digits2 ? isValidPhoneNumber(`+${digits2}`) : false;
969
- }
970
- const country = countryCode ? findPhoneCountry(countryCode) : defaultPhoneCountry();
971
- if (!country) return false;
972
- const digits = prepareNationalDigits(cleaned, country);
973
- if (!digits) return false;
974
- if (countryCode) {
975
- return isValidPhoneNumber(digits, toLibCountryCode(countryCode));
957
+ function parseGroupedInteger(value) {
958
+ if (typeof value === "number") {
959
+ return Number.isFinite(value) ? Math.trunc(value) : void 0;
976
960
  }
977
- if (isValidPhoneNumber(`+${digits}`)) return true;
978
- return isValidPhoneNumber(digits, "BR");
961
+ const digits = String(value ?? "").replace(/\D/g, "");
962
+ if (!digits) return void 0;
963
+ const amount = Number.parseInt(digits, 10);
964
+ return Number.isFinite(amount) ? amount : void 0;
979
965
  }
980
- function remaskPhoneForCountry(nationalOrDraft, countryCode) {
981
- const country = findPhoneCountry(countryCode) ?? defaultPhoneCountry();
982
- const digits = truncateNationalPhoneDigits(
983
- nationalPhoneDigits(nationalOrDraft)
984
- );
985
- return {
986
- display: formatNationalDigits(digits, country),
987
- e164: digits ? `+${country.dialCode}${digits}` : "",
988
- country
989
- };
966
+ function formatAreaM2(area) {
967
+ if (area == null || !Number.isFinite(area)) return null;
968
+ return `${area} m\xB2`;
969
+ }
970
+ function listingBusinessLabel(businessType) {
971
+ return businessType === "rental" ? "Aluguel" : "Venda";
990
972
  }
991
973
 
992
- // src/resolve-site-id.ts
993
- var PREVIEW_HOST_SUFFIXES = [".vusercontent.net"];
994
- function isStudioPreviewHost(host) {
995
- const normalized = stripPort(host);
996
- if (normalized === "localhost" || normalized === "127.0.0.1") return true;
997
- return PREVIEW_HOST_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
974
+ // src/search-engine.ts
975
+ var PATH_FILTER_IDS = {
976
+ listing_type: "listingType",
977
+ property_type: "propertyType",
978
+ property_bedrooms: "bedrooms",
979
+ property_bathrooms: "bathrooms",
980
+ property_suites: "suites",
981
+ property_parking_spots: "parkingSpots",
982
+ price: "price",
983
+ property_area_total: "area",
984
+ propertyFeatures: "propertyFeatures",
985
+ buildingAmenities: "buildingAmenities"
986
+ };
987
+ var FORBIDDEN_SEARCH_QUERY_KEYS = [
988
+ "tipo",
989
+ "quartos",
990
+ "tipo-imovel",
991
+ "banheiros",
992
+ "vagas"
993
+ ];
994
+ var SEARCH_SORT_RELEVANCE = {
995
+ id: "",
996
+ label: "Mais relevantes"
997
+ };
998
+ function searchSortOptions(sorts) {
999
+ const fromApi = (sorts || []).filter((sort) => sort.id);
1000
+ return [
1001
+ { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },
1002
+ ...fromApi
1003
+ ];
998
1004
  }
999
- function stripPort(host) {
1000
- return host.trim().toLowerCase().split(":")[0] ?? "";
1005
+ var TOOLBAR_PRIMARY_FILTER_IDS = [
1006
+ "price",
1007
+ "property_bedrooms"
1008
+ ];
1009
+ var HIDDEN_FILTER_IDS = /* @__PURE__ */ new Set(["property_suites"]);
1010
+ function toFiniteNumber(value) {
1011
+ if (value === "" || value == null) return void 0;
1012
+ const n = Number(value);
1013
+ return Number.isFinite(n) ? n : void 0;
1001
1014
  }
1002
- async function resolvePublicSiteId(options) {
1003
- const fallback = options.fallback?.trim() ?? "";
1004
- const host = options.host ? stripPort(options.host) : "";
1005
- if (host && !isStudioPreviewHost(host)) {
1006
- const site = await getSite({
1007
- domain: host,
1008
- baseUrl: options.baseUrl,
1009
- fetch: options.fetch,
1010
- publishableKey: options.publishableKey
1011
- });
1012
- if (site?.id) return site.id;
1013
- throw new GaragemSdkError(
1014
- `Garagem SDK: no published site found for domain "${host}"`,
1015
- { status: 404, url: host }
1016
- );
1017
- }
1018
- if (fallback) return fallback;
1019
- throw new GaragemSdkError(
1020
- "Garagem SDK: could not resolve a site id (no host match and no fallback)",
1021
- { status: 404, url: host || "fallback" }
1022
- );
1015
+ function pathnameOnly(pathname) {
1016
+ return String(pathname || "").split(/[?#]/)[0] || "/";
1023
1017
  }
1024
-
1025
- // src/leads.ts
1026
- function browserHost() {
1027
- if (typeof window === "undefined") return "";
1028
- return window.location.host;
1018
+ function isListingDetailPath(pathname) {
1019
+ const parts = pathnameOnly(pathname).split("/").filter(Boolean);
1020
+ const last = parts[parts.length - 1] || "";
1021
+ return last.toLowerCase().startsWith("id-");
1029
1022
  }
1030
- async function resolveLeadSiteId(input) {
1031
- try {
1032
- return await coerceSiteId(input.siteId);
1033
- } catch (error) {
1034
- const host = browserHost();
1035
- if (!host) throw error;
1036
- return resolvePublicSiteId({
1037
- host,
1038
- baseUrl: input.baseUrl,
1039
- fetch: input.fetch,
1040
- publishableKey: input.publishableKey
1041
- });
1042
- }
1023
+ function readPublicSearch(pathname, search, dictionary) {
1024
+ const pathFilters = parseSearchPublicPath2(pathnameOnly(pathname), dictionary) || {};
1025
+ const applied = parseAppliedSearchQuery2(search || "");
1026
+ return { pathFilters, applied };
1043
1027
  }
1044
- var LeadSubmitError = class extends Error {
1045
- code;
1046
- status;
1047
- retryAfterSeconds;
1048
- /** Seconds to wait. Same value as `retryAfterSeconds`; `null` when unset. */
1049
- retryAfter;
1050
- constructor(message, info) {
1051
- super(message);
1052
- this.name = "LeadSubmitError";
1053
- this.code = info.code;
1054
- if (info.status != null) this.status = info.status;
1055
- if (info.retryAfterSeconds != null) {
1056
- this.retryAfterSeconds = info.retryAfterSeconds;
1057
- }
1058
- this.retryAfter = info.retryAfterSeconds ?? null;
1059
- }
1060
- };
1061
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1062
- var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1063
- var NAME_RE = /^[^\d\s]{2,}.*$/;
1064
- var MESSAGE_MAX = 2e3;
1065
- function isValidEmail(value) {
1066
- return EMAIL_RE.test(value.trim());
1067
- }
1068
- function isValidName(value) {
1069
- const name = value.trim();
1070
- return name.length <= 200 && NAME_RE.test(name);
1028
+ function lookupDisplay(table, slug) {
1029
+ if (!slug || !table) return slug;
1030
+ return table[slug] || table[String(slug).toLowerCase()] || slug;
1071
1031
  }
1072
- var CONTACT_FIELDS = [
1073
- { id: "name", required: true },
1074
- { id: "email", required: false },
1075
- { id: "phone", required: false },
1076
- { id: "message", required: false }
1077
- ];
1078
- function studioDefaultLeadUi() {
1032
+ function displayPathLocation(location, values) {
1033
+ if (!location) return null;
1034
+ const table = values || {};
1079
1035
  return {
1080
- defaultVariant: "visit",
1081
- timeZone: "America/Sao_Paulo",
1082
- variants: {
1083
- visit: {
1084
- ctaLabel: "Agendar visita",
1085
- requireDateTime: true,
1086
- schedule: STUDIO_DEFAULT_VISIT_SCHEDULE,
1087
- fields: CONTACT_FIELDS
1088
- },
1089
- contact: {
1090
- ctaLabel: "Fale conosco",
1091
- requireDateTime: false,
1092
- whatsappPhone: null,
1093
- fields: CONTACT_FIELDS
1094
- }
1095
- }
1036
+ state: lookupDisplay(table.states, location.state),
1037
+ city: lookupDisplay(table.cities, location.city),
1038
+ neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),
1039
+ street: lookupDisplay(table.streets, location.street)
1096
1040
  };
1097
1041
  }
1098
- async function getLeadUi(options) {
1099
- const siteId = await resolveLeadSiteId(options);
1100
- const url = `${normalizeBaseUrl(options.baseUrl)}/api/sites/${encodeURIComponent(siteId)}/leads/ui`;
1101
- return callJson(
1102
- url,
1103
- {
1104
- method: "GET",
1105
- headers: { Accept: "application/json" },
1106
- next: options.next
1107
- },
1108
- options.fetch ?? fetch,
1109
- options.publishableKey
1110
- );
1111
- }
1112
- function assertListingId(listingId) {
1113
- if (!UUID_RE.test(listingId.trim())) {
1114
- throw new LeadSubmitError(
1115
- "Garagem SDK: listingId must be the listing UUID, not a path or code.",
1116
- { code: "invalid_listing_id" }
1117
- );
1042
+ function buildQueryListingsParams(pathFilters, applied, schema, locationValues) {
1043
+ const filters = pathFiltersToQueryFilters(pathFilters || {});
1044
+ const locations = [];
1045
+ const displayed = displayPathLocation(pathFilters?.location, locationValues);
1046
+ const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;
1047
+ if (pathLoc) locations.push(pathLoc);
1048
+ for (const value of applied?.loc || []) {
1049
+ locations.push({ type: "loc", value });
1118
1050
  }
1051
+ const params = {
1052
+ page: applied?.page || 1,
1053
+ limit: schema?.defaultLimit || 12,
1054
+ filters
1055
+ };
1056
+ if (applied?.sort) params.sort = applied.sort;
1057
+ const hasLocation = locations.length > 0;
1058
+ if (applied?.query && !hasLocation) params.q = applied.query;
1059
+ if (hasLocation) params.location = locations;
1060
+ return params;
1119
1061
  }
1120
- function normalizeContact(input) {
1121
- const name = input.name.trim();
1122
- if (name.length < 2 || name.length > 200) {
1123
- throw new LeadSubmitError("Garagem SDK: name is required.", {
1124
- code: "invalid_contact"
1125
- });
1062
+ function applyPathFilter(pathFilters, filterId, value) {
1063
+ const next = { ...pathFilters || {} };
1064
+ const key = PATH_FILTER_IDS[filterId];
1065
+ if (!key) return next;
1066
+ if (value === "" || value == null) {
1067
+ delete next[key];
1068
+ return next;
1126
1069
  }
1127
- const email = input.email?.trim() || void 0;
1128
- const phone = input.phone?.trim() || void 0;
1129
- if (!email && !phone) {
1130
- throw new LeadSubmitError("Garagem SDK: email and/or phone is required.", {
1131
- code: "invalid_contact"
1132
- });
1070
+ if (key === "price" || key === "area") {
1071
+ const range = value || {};
1072
+ const parse = key === "price" ? parseGroupedInteger : toFiniteNumber;
1073
+ const min = parse(range.min);
1074
+ const max = parse(range.max);
1075
+ if (min == null && max == null) {
1076
+ delete next[key];
1077
+ return next;
1078
+ }
1079
+ next[key] = {
1080
+ ...min != null ? { min } : {},
1081
+ ...max != null ? { max } : {}
1082
+ };
1083
+ return next;
1133
1084
  }
1134
- if (email && !EMAIL_RE.test(email)) {
1135
- throw new LeadSubmitError("Garagem SDK: email is invalid.", {
1136
- code: "invalid_contact"
1137
- });
1085
+ if (key === "propertyFeatures" || key === "buildingAmenities") {
1086
+ const current = Array.isArray(next[key]) ? [...next[key]] : [];
1087
+ const id = String(value);
1088
+ const i = current.indexOf(id);
1089
+ if (i >= 0) current.splice(i, 1);
1090
+ else current.push(id);
1091
+ if (current.length) next[key] = current;
1092
+ else delete next[key];
1093
+ return next;
1138
1094
  }
1139
- let normalizedPhone;
1140
- if (phone) {
1141
- const e164 = toE164(phone);
1142
- if (!e164 || !isValidPhone(e164) || e164.length > 40) {
1143
- throw new LeadSubmitError("Garagem SDK: phone is invalid.", {
1144
- code: "invalid_contact"
1145
- });
1146
- }
1147
- normalizedPhone = e164;
1095
+ if (key === "propertyType") {
1096
+ const id = String(value);
1097
+ const current = Array.isArray(next.propertyType) ? [...next.propertyType] : next.propertyType ? [String(next.propertyType)] : [];
1098
+ const i = current.indexOf(id);
1099
+ if (i >= 0) current.splice(i, 1);
1100
+ else current.push(id);
1101
+ if (current.length === 0) delete next.propertyType;
1102
+ else if (current.length === 1) next.propertyType = current[0];
1103
+ else next.propertyType = current;
1104
+ return next;
1148
1105
  }
1149
- const message = input.message?.trim() || void 0;
1150
- if (message && message.length > MESSAGE_MAX) {
1151
- throw new LeadSubmitError("Garagem SDK: message is too long.", {
1152
- code: "invalid_contact"
1153
- });
1106
+ if (key === "listingType") {
1107
+ const id = String(value);
1108
+ if (next.listingType === id) delete next.listingType;
1109
+ else next.listingType = id;
1110
+ return next;
1154
1111
  }
1155
- return {
1156
- name,
1157
- ...email ? { email } : {},
1158
- ...normalizedPhone ? { phone: normalizedPhone } : {},
1159
- ...message ? { message } : {}
1160
- };
1161
- }
1162
- function normalizeSdkBusinessType(value) {
1163
- if (!value) return void 0;
1164
- const normalized = value.trim().toLowerCase();
1165
- if (normalized === "rent" || normalized === "rental" || normalized === "aluguel") {
1166
- return "rent";
1112
+ if (key === "bedrooms" || key === "bathrooms" || key === "suites" || key === "parkingSpots") {
1113
+ const n = Number(value);
1114
+ if (!Number.isFinite(n)) {
1115
+ delete next[key];
1116
+ return next;
1117
+ }
1118
+ if (next[key] === n) delete next[key];
1119
+ else next[key] = n;
1120
+ return next;
1167
1121
  }
1168
- if (normalized === "sale" || normalized === "venda") return "sale";
1169
- return void 0;
1122
+ return next;
1170
1123
  }
1171
- var ADDRESS_REJECTIONS = /* @__PURE__ */ new Set([
1172
- "missing_postal_code",
1173
- "ungeocoded_address"
1174
- ]);
1175
- async function rejectedLeadError(response) {
1176
- if (response.status !== 400 && response.status !== 409) return null;
1177
- const parsed = parseSdkErrorBody(await response.text().catch(() => ""));
1178
- if (response.status === 409 || parsed.reason === "duplicate_property") {
1179
- return new LeadSubmitError(
1180
- parsed.summary || "Garagem SDK: property already registered.",
1181
- { code: "duplicate_property", status: response.status }
1182
- );
1183
- }
1184
- if (parsed.reason && ADDRESS_REJECTIONS.has(parsed.reason)) {
1185
- return new LeadSubmitError(`Garagem SDK: ${parsed.reason}.`, {
1186
- code: "invalid_address",
1187
- status: 400
1188
- });
1124
+ function pathFilterValue(pathFilters, filterId) {
1125
+ const key = PATH_FILTER_IDS[filterId];
1126
+ const value = pathFilters && key ? pathFilters[key] : void 0;
1127
+ if (value == null) return "";
1128
+ if (Array.isArray(value)) return value[0] != null ? String(value[0]) : "";
1129
+ if (typeof value === "object") return "";
1130
+ return String(value);
1131
+ }
1132
+ function pathFilterHasOption(pathFilters, filterId, optionId) {
1133
+ const key = PATH_FILTER_IDS[filterId];
1134
+ const value = pathFilters && key ? pathFilters[key] : void 0;
1135
+ if (value == null) return false;
1136
+ if (Array.isArray(value)) return value.map(String).includes(optionId);
1137
+ if (typeof value === "object") return false;
1138
+ return String(value) === optionId;
1139
+ }
1140
+ function publicSearchHref(pathFilters, applied, dictionary, existingSearch) {
1141
+ const pathname = composeSearchPublicPath2(pathFilters || {}, dictionary);
1142
+ return composeSearchPublicHref2(pathname, applied || {}, existingSearch);
1143
+ }
1144
+ function hrefForPathFilters(pathname, search, dictionary, nextPathFilters) {
1145
+ const { applied } = readPublicSearch(pathname, search, dictionary);
1146
+ const nextApplied = reduceAppliedSearchQuery2(applied, {
1147
+ type: "applyFilters"
1148
+ });
1149
+ return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);
1150
+ }
1151
+ function hrefForAppliedChange(pathname, search, dictionary, change) {
1152
+ const { pathFilters, applied } = readPublicSearch(
1153
+ pathname,
1154
+ search,
1155
+ dictionary
1156
+ );
1157
+ let nextPath = pathFilters;
1158
+ if (change && change.type === "query") {
1159
+ nextPath = { ...pathFilters };
1160
+ delete nextPath.location;
1189
1161
  }
1190
- return null;
1162
+ const nextApplied = reduceAppliedSearchQuery2(applied, change);
1163
+ return publicSearchHref(nextPath, nextApplied, dictionary, search);
1191
1164
  }
1192
- async function postSiteLead(input) {
1193
- const siteId = await resolveLeadSiteId(input);
1194
- const base = normalizeBaseUrl(input.baseUrl);
1195
- const url = `${base}/api/webhooks/sites/${encodeURIComponent(siteId)}/leads`;
1196
- const f = input.fetch ?? fetch;
1197
- let response;
1198
- try {
1199
- response = await f(url, {
1200
- method: "POST",
1201
- headers: {
1202
- Accept: "application/json",
1203
- "Content-Type": "application/json",
1204
- ...publishableKeyHeaders(input.publishableKey)
1205
- },
1206
- body: JSON.stringify(input.body)
1207
- });
1208
- } catch (error) {
1209
- throw new LeadSubmitError(
1210
- error instanceof Error ? error.message : "Garagem SDK: network error.",
1211
- { code: "network" }
1212
- );
1213
- }
1214
- if (response.status === 202) {
1215
- const data = await response.json().catch(() => ({}));
1216
- const id = typeof data.id === "string" && data.id ? data.id : "";
1217
- return { ok: true, status: 202, id };
1218
- }
1219
- if (response.status === 401) {
1220
- throw new LeadSubmitError("Garagem SDK: invalid publishable key.", {
1221
- code: "unauthorized",
1222
- status: 401
1223
- });
1224
- }
1225
- if (response.status === 429) {
1226
- const text2 = await response.text().catch(() => "");
1227
- const parsed = parseSdkErrorBody(text2);
1228
- const retryAfter = retryAfterFromResponse(
1229
- response,
1230
- parsed.retryAfterSeconds
1231
- );
1232
- throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
1233
- code: "rate_limited",
1234
- status: 429,
1235
- ...retryAfter != null ? { retryAfterSeconds: retryAfter } : {}
1236
- });
1237
- }
1238
- if (response.status === 404) {
1239
- throw new LeadSubmitError("Garagem SDK: listing or site not found.", {
1240
- code: "not_found",
1241
- status: 404
1242
- });
1243
- }
1244
- const rejected = await rejectedLeadError(response);
1245
- if (rejected) throw rejected;
1246
- throw new LeadSubmitError(
1247
- `Garagem SDK: lead submit failed (${response.status}).`,
1248
- { code: "http", status: response.status }
1165
+ function currentSearchHref(pathname, search) {
1166
+ const path = pathnameOnly(pathname);
1167
+ const qs = search.replace(/^\?/, "");
1168
+ return qs ? `${path}?${qs}` : path;
1169
+ }
1170
+ function canonicalizeSearchHref(pathname, search, dictionary) {
1171
+ if (pathname.includes("/api/v0-preview/")) return null;
1172
+ if (isListingDetailPath(pathname)) return null;
1173
+ const { pathFilters, applied } = readPublicSearch(
1174
+ pathname,
1175
+ search,
1176
+ dictionary
1249
1177
  );
1178
+ const href = publicSearchHref(pathFilters, applied, dictionary, search);
1179
+ if (href === currentSearchHref(pathname, search)) return null;
1180
+ return href;
1250
1181
  }
1251
- function leadPostContext(input) {
1252
- assertListingId(input.listingId);
1253
- const businessType = normalizeSdkBusinessType(input.businessType) ?? normalizeSdkBusinessType(input.listingType);
1254
- return {
1255
- listingId: input.listingId.trim(),
1256
- contact: normalizeContact(input),
1257
- extras: {
1258
- ...input.visitorId ? { visitorId: input.visitorId } : {},
1259
- ...input.brokerRef ? { brokerRef: input.brokerRef } : {},
1260
- ...input.referrer ? { referrer: input.referrer } : {},
1261
- ...businessType ? { businessType } : {},
1262
- ...input.listingType ? { listingType: input.listingType } : {}
1263
- }
1264
- };
1182
+ function searchHrefUsesLegacyFilterQuery(href) {
1183
+ const query = href.split("?")[1] || "";
1184
+ const params = new URLSearchParams(query);
1185
+ return FORBIDDEN_SEARCH_QUERY_KEYS.some((key) => params.has(key));
1265
1186
  }
1266
- async function submitVisitLead(input) {
1267
- const prepared = leadPostContext(input);
1268
- const schedule = input.schedule ?? STUDIO_DEFAULT_VISIT_SCHEDULE;
1269
- const visitDate = normalizeVisitDate(input.visitDate, schedule.timeZone);
1270
- const visitTime = normalizeVisitTime(input.visitTime);
1271
- if (!visitDate || !visitTime || !isVisitSlotAllowed(schedule, visitDate, visitTime)) {
1272
- throw new LeadSubmitError(
1273
- "Garagem SDK: visitDate/visitTime is outside the published schedule.",
1274
- { code: "invalid_slot" }
1275
- );
1187
+ function clearStagedPathFilters(current, keepFilterIds = []) {
1188
+ const next = current.location ? { location: current.location } : {};
1189
+ for (const id of keepFilterIds) {
1190
+ const key = PATH_FILTER_IDS[id];
1191
+ if (!key || key === "location") continue;
1192
+ const value = current[key];
1193
+ if (value != null) Object.assign(next, { [key]: value });
1276
1194
  }
1277
- return postSiteLead({
1278
- siteId: input.siteId,
1279
- baseUrl: input.baseUrl,
1280
- fetch: input.fetch,
1281
- publishableKey: input.publishableKey,
1282
- body: {
1283
- source: "site-sdk",
1284
- leadType: "visit",
1285
- ...prepared.contact,
1286
- propertyId: prepared.listingId,
1287
- listingId: prepared.listingId,
1288
- visitDate,
1289
- visitTime,
1290
- ...prepared.extras
1291
- }
1292
- });
1195
+ return next;
1293
1196
  }
1294
- async function submitContactLead(input) {
1295
- const prepared = leadPostContext(input);
1296
- return postSiteLead({
1297
- siteId: input.siteId,
1298
- baseUrl: input.baseUrl,
1299
- fetch: input.fetch,
1300
- publishableKey: input.publishableKey,
1301
- body: {
1302
- source: "site-sdk",
1303
- leadType: "contact",
1304
- ...prepared.contact,
1305
- propertyId: prepared.listingId,
1306
- listingId: prepared.listingId,
1307
- ...prepared.extras
1197
+ function visibleSearchFilters(schema) {
1198
+ if (!schema?.filters) return [];
1199
+ return schema.filters.filter((filter) => {
1200
+ if (HIDDEN_FILTER_IDS.has(filter.id)) return false;
1201
+ if (filter.id === "listing_type" && (filter.options?.length ?? 0) <= 1) {
1202
+ return false;
1308
1203
  }
1204
+ return true;
1309
1205
  });
1310
1206
  }
1311
-
1312
- // src/seller-lead.ts
1313
- function text(value) {
1314
- return typeof value === "string" ? value.trim() : "";
1207
+ function toolbarFilterIds(schema) {
1208
+ const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));
1209
+ return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));
1315
1210
  }
1316
- function inRange(value, min, max) {
1317
- return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
1211
+ function countOptionLabel(option) {
1212
+ const label = String(option?.label ?? "");
1213
+ if (/^[1-9]\d*$/.test(label)) return `${label}+`;
1214
+ return label;
1318
1215
  }
1319
- function sellerAddressErrors(address) {
1320
- const errors = {};
1321
- if (!address || !text(address.fullAddress)) {
1322
- errors.fullAddress = "Informe o endere\xE7o do im\xF3vel.";
1323
- } else if (!inRange(address.latitude, -90, 90) || !inRange(address.longitude, -180, 180) || !text(address.street) || !text(address.city) || !text(address.neighborhood) || !/^[A-Za-z]{2}$/.test(text(address.state))) {
1324
- errors.fullAddress = "Selecione o endere\xE7o em uma das sugest\xF5es.";
1325
- }
1326
- if (!address?.noNumber && !text(address?.number)) {
1327
- errors.number = "Informe o n\xFAmero ou marque sem n\xFAmero.";
1328
- }
1329
- if (!address?.noBlocoTorre && !text(address?.blocoTorre)) {
1330
- errors.blocoTorre = "Informe o bloco/torre ou marque que n\xE3o tem.";
1331
- }
1332
- if (!address?.noUnidade && !text(address?.unidade)) {
1333
- errors.unidade = "Informe a unidade ou marque que n\xE3o tem.";
1334
- }
1335
- if (text(address?.postalCode).replace(/\D/g, "").length !== 8) {
1336
- errors.postalCode = "Informe um CEP com 8 d\xEDgitos.";
1216
+ function countFacetChoices(options) {
1217
+ const list = options || [];
1218
+ const zero = list.find((o) => o.id === "0" || o.label === "Studio");
1219
+ const isStudio = Boolean(
1220
+ zero && /studio/i.test(String(zero.label)) && zero.id === "0"
1221
+ );
1222
+ const max = isStudio ? 3 : 4;
1223
+ const out = [];
1224
+ if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });
1225
+ for (let n = 1; n <= max; n += 1) {
1226
+ const option = list.find((o) => o.id === String(n));
1227
+ out.push({
1228
+ id: String(n),
1229
+ label: countOptionLabel(option || { label: String(n) })
1230
+ });
1337
1231
  }
1338
- return errors;
1232
+ return out;
1339
1233
  }
1340
- var SELLER_LEAD_PHOTO_MAX_BYTES = 10 * 1024 * 1024;
1341
- var SELLER_LEAD_PHOTO_MAX_COUNT = 30;
1342
- var SELLER_LEAD_PHOTO_TYPES = [
1343
- "image/jpeg",
1344
- "image/png",
1345
- "image/webp"
1346
- ];
1347
- async function uploadSellerLeadPhoto(input) {
1348
- const { file } = input;
1349
- if (!SELLER_LEAD_PHOTO_TYPES.includes(file.type)) {
1350
- throw new LeadSubmitError("Garagem SDK: photo must be JPG, PNG or WEBP.", {
1351
- code: "invalid_photo"
1352
- });
1234
+ var FEMININE_HEADING = /(casa|cobertura|kitnet|loja|sala|fazenda|chácara|chacara)s?$/i;
1235
+ function pluralizePt(label) {
1236
+ const text2 = label.trim();
1237
+ if (!text2 || /s$/i.test(text2)) return text2;
1238
+ if (/il$/i.test(text2)) return `${text2.slice(0, -1)}is`;
1239
+ if (/m$/i.test(text2)) return `${text2.slice(0, -1)}ns`;
1240
+ return `${text2}s`;
1241
+ }
1242
+ function headingLocationSuffix(location) {
1243
+ if (!location) return "";
1244
+ if (location.street && location.neighborhood) {
1245
+ return `${location.street}, ${location.neighborhood}`;
1353
1246
  }
1354
- if (file.size <= 0) {
1355
- throw new LeadSubmitError("Garagem SDK: photo is empty.", {
1356
- code: "invalid_photo"
1357
- });
1247
+ if (location.neighborhood && location.city) {
1248
+ return `${location.neighborhood}, ${location.city}`;
1358
1249
  }
1359
- if (file.size > SELLER_LEAD_PHOTO_MAX_BYTES) {
1360
- throw new LeadSubmitError("Garagem SDK: photo is larger than 10MB.", {
1361
- code: "invalid_photo"
1362
- });
1250
+ if (location.city && location.state) {
1251
+ return `${location.city} - ${location.state}`;
1363
1252
  }
1364
- const siteId = await resolveLeadSiteId(input);
1365
- const url = `${normalizeBaseUrl(input.baseUrl)}/api/webhooks/sites/${encodeURIComponent(siteId)}/photos`;
1366
- const form = new FormData();
1367
- form.append("file", file);
1368
- if (file.name) form.append("fileName", file.name);
1369
- let response;
1370
- try {
1371
- response = await (input.fetch ?? fetch)(url, {
1372
- method: "POST",
1373
- body: form
1374
- });
1375
- } catch (error) {
1376
- throw new LeadSubmitError(
1377
- error instanceof Error ? error.message : "Garagem SDK: network error.",
1378
- { code: "network" }
1253
+ return location.city || location.neighborhood || location.street || location.state || "";
1254
+ }
1255
+ function searchResultsHeading(pathFilters, dictionary, locationNames) {
1256
+ const types = [].concat(pathFilters.propertyType || []).filter(Boolean);
1257
+ let noun = "Im\xF3veis";
1258
+ let found = "encontrados";
1259
+ if (types.length === 1) {
1260
+ const id = String(types[0]);
1261
+ const option = dictionary?.propertyTypes?.find(
1262
+ (entry) => entry.id === id || entry.slug === id
1379
1263
  );
1264
+ const label = option?.label;
1265
+ if (label) {
1266
+ noun = pluralizePt(label.charAt(0).toUpperCase() + label.slice(1));
1267
+ if (FEMININE_HEADING.test(id) || FEMININE_HEADING.test(label)) {
1268
+ found = "encontradas";
1269
+ }
1270
+ }
1380
1271
  }
1381
- if (response.status === 404) {
1382
- throw new LeadSubmitError("Garagem SDK: site not found.", {
1383
- code: "not_found",
1384
- status: 404
1385
- });
1386
- }
1387
- const data = await response.json().catch(() => ({}));
1388
- if (!response.ok || typeof data.url !== "string" || !data.url) {
1389
- throw new LeadSubmitError(
1390
- `Garagem SDK: photo upload failed (${response.status}).`,
1391
- {
1392
- code: response.status === 400 ? "invalid_photo" : "http",
1393
- status: response.status
1394
- }
1395
- );
1396
- }
1397
- return data.url;
1398
- }
1399
- var STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG = {
1400
- disabledDays: [0, 6],
1401
- weekdayTimeSlots: [
1402
- "09:00",
1403
- "10:00",
1404
- "11:00",
1405
- "14:00",
1406
- "15:00",
1407
- "16:00",
1408
- "17:00"
1409
- ],
1410
- weekendTimeSlots: ["10:00", "11:00", "14:00", "15:00", "16:00"]
1411
- };
1412
- function sellerPhotoSchedule(config = STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG) {
1413
- const weekdayTimeSlots = [...config.weekdayTimeSlots].sort();
1414
- const weekendTimeSlots = [...config.weekendTimeSlots].sort();
1415
- const hours = (slots) => slots.length > 0 ? { start: slots[0], end: slots[slots.length - 1] } : null;
1416
- return {
1417
- timeZone: VISIT_TIME_ZONE,
1418
- saturday: !config.disabledDays.includes(6),
1419
- sunday: !config.disabledDays.includes(0),
1420
- weekday: hours(weekdayTimeSlots) ?? { start: "09:00", end: "09:00" },
1421
- weekend: hours(weekendTimeSlots),
1422
- minHoursAhead: 2,
1423
- disabledDays: [...config.disabledDays],
1424
- weekdayTimeSlots,
1425
- weekendTimeSlots,
1426
- timeSlots: Array.from(
1427
- /* @__PURE__ */ new Set([...weekdayTimeSlots, ...weekendTimeSlots])
1428
- ).sort()
1429
- };
1272
+ const place = locationNames ? headingLocationSuffix(
1273
+ displayPathLocation(pathFilters.location, locationNames)
1274
+ ) : "";
1275
+ if (place) return `${noun} ${found} em ${place}`;
1276
+ return `${noun} ${found}`;
1430
1277
  }
1431
- function contactError(message) {
1432
- return new LeadSubmitError(`Garagem SDK: ${message}`, {
1433
- code: "invalid_contact"
1434
- });
1278
+ function hrefWithExplicitPage(href, page) {
1279
+ if (page !== 1 || /(?:\?|&)page=/.test(href)) return href;
1280
+ return href.includes("?") ? `${href}&page=1` : `${href}?page=1`;
1435
1281
  }
1436
- function normalizeOwner(owner) {
1437
- const name = text(owner?.name);
1438
- const email = text(owner?.email);
1439
- if (!isValidName(name)) throw contactError("owner name is invalid.");
1440
- if (!isValidEmail(email)) throw contactError("owner email is invalid.");
1441
- const phone = toE164(text(owner?.phone));
1442
- if (!phone || !isValidPhone(phone) || phone.length > 40) {
1443
- throw contactError("owner phone is invalid.");
1444
- }
1445
- return { name, email, phone };
1282
+ function paginationPages(currentPage, totalPages, padding) {
1283
+ if (totalPages < 1) return [];
1284
+ const current = Math.min(Math.max(1, currentPage), totalPages);
1285
+ const start = Math.max(1, current - padding);
1286
+ const end = Math.min(totalPages, current + padding);
1287
+ const pages = [];
1288
+ for (let i = start; i <= end; i += 1) pages.push(i);
1289
+ return pages;
1446
1290
  }
1447
- function normalizeAddress(address) {
1448
- const errors = sellerAddressErrors(address);
1449
- const first = Object.values(errors)[0];
1450
- if (first) {
1451
- throw new LeadSubmitError(`Garagem SDK: ${first}`, {
1452
- code: "invalid_address"
1453
- });
1454
- }
1455
- const optional = (value) => text(value) ? { value: text(value) } : null;
1456
- const number = address.noNumber ? null : optional(address.number);
1457
- const bloco = address.noBlocoTorre ? null : optional(address.blocoTorre);
1458
- const unidade = address.noUnidade ? null : optional(address.unidade);
1291
+ var SEARCH_EMPTY_COPY = "Nenhum im\xF3vel encontrado. Ajuste a busca ou os filtros.";
1292
+ function rangeDraftFromPath(pathFilters) {
1293
+ const price = pathFilters.price || {};
1294
+ const area = pathFilters.area || {};
1459
1295
  return {
1460
- fullAddress: text(address.fullAddress),
1461
- street: text(address.street),
1462
- ...number ? { number: number.value } : {},
1463
- neighborhood: text(address.neighborhood),
1464
- city: text(address.city),
1465
- state: text(address.state),
1466
- postalCode: text(address.postalCode).replace(/\D/g, ""),
1467
- country: text(address.country) || "BR",
1468
- latitude: address.latitude,
1469
- longitude: address.longitude,
1470
- ...bloco ? { blocoTorre: bloco.value } : {},
1471
- ...unidade ? { unidade: unidade.value } : {},
1472
- noNumber: address.noNumber === true,
1473
- noBlocoTorre: address.noBlocoTorre === true,
1474
- noUnidade: address.noUnidade === true
1296
+ price: {
1297
+ min: price.min != null ? formatGroupedInteger(price.min) : "",
1298
+ max: price.max != null ? formatGroupedInteger(price.max) : ""
1299
+ },
1300
+ property_area_total: {
1301
+ min: area.min != null ? String(area.min) : "",
1302
+ max: area.max != null ? String(area.max) : ""
1303
+ }
1475
1304
  };
1476
1305
  }
1477
- var COUNT_FIELDS = [
1478
- "bedrooms",
1479
- "bathrooms",
1480
- "suites",
1481
- "parkingSpaces"
1482
- ];
1483
- var AMOUNT_FIELDS = [
1484
- "saleValue",
1485
- "rentValue",
1486
- "condoFee",
1487
- "totalArea"
1488
- ];
1489
- function propertyError(message) {
1490
- return new LeadSubmitError(`Garagem SDK: ${message}`, {
1491
- code: "invalid_property"
1492
- });
1493
- }
1494
- function normalizeProperty(property) {
1495
- if (!["sale", "rent", "both"].includes(property?.businessType)) {
1496
- throw propertyError("businessType must be sale, rent or both.");
1497
- }
1498
- for (const field of COUNT_FIELDS) {
1499
- const value = property[field];
1500
- if (value != null && (!Number.isInteger(value) || value < 0 || value > 999)) {
1501
- throw propertyError(`${field} must be a whole number.`);
1502
- }
1503
- }
1504
- for (const field of AMOUNT_FIELDS) {
1505
- const value = property[field];
1506
- if (value != null && (!Number.isFinite(value) || value < 0 || value > 1e12)) {
1507
- throw propertyError(`${field} must be a non-negative number.`);
1508
- }
1509
- }
1510
- const sale = property.businessType === "rent" ? void 0 : property.saleValue;
1511
- const rent = property.businessType === "sale" ? void 0 : property.rentValue;
1512
- const price = property.businessType === "rent" ? rent : sale;
1513
- const counts = Object.fromEntries(
1514
- COUNT_FIELDS.filter((field) => property[field] != null).map((field) => [
1515
- field,
1516
- property[field]
1517
- ])
1518
- );
1306
+ function searchChromeModel(schema, pathFilters, locationNames) {
1307
+ const filters = visibleSearchFilters(schema);
1308
+ const toolbarIds = new Set(toolbarFilterIds(schema));
1519
1309
  return {
1520
- businessType: property.businessType,
1521
- ...price != null ? { price } : {},
1522
- ...property.businessType === "both" && rent != null ? { rentPrice: rent } : {},
1523
- ...property.condoFee != null ? { condominiumFee: property.condoFee } : {},
1524
- ...property.totalArea != null ? { totalArea: property.totalArea } : {},
1525
- ...counts
1310
+ headingTitle: searchResultsHeading(
1311
+ pathFilters,
1312
+ schema?.dictionary,
1313
+ locationNames
1314
+ ),
1315
+ toolbarFilters: filters.filter((filter) => toolbarIds.has(filter.id)),
1316
+ extraFilters: filters.filter((filter) => !toolbarIds.has(filter.id)),
1317
+ sortOptions: searchSortOptions(schema?.sorts)
1526
1318
  };
1527
1319
  }
1528
- function normalizePhotos(photos) {
1529
- if (!photos?.length) return void 0;
1530
- if (photos.length > SELLER_LEAD_PHOTO_MAX_COUNT) {
1531
- throw new LeadSubmitError("Garagem SDK: too many photos (max 30).", {
1532
- code: "invalid_photo"
1533
- });
1534
- }
1535
- return photos.map((url) => {
1536
- const trimmed = url.trim();
1537
- if (!trimmed.startsWith("https://")) {
1538
- throw new LeadSubmitError("Garagem SDK: photo URL must be https.", {
1539
- code: "invalid_photo"
1540
- });
1541
- }
1542
- return trimmed;
1543
- });
1320
+
1321
+ // src/analytics.ts
1322
+ var SITE_ANALYTICS_EVENT = "garagem:site-event";
1323
+ function emitSiteEvent(event, properties) {
1324
+ if (typeof window === "undefined") return;
1325
+ window.dispatchEvent(
1326
+ new CustomEvent(SITE_ANALYTICS_EVENT, { detail: { event, properties } })
1327
+ );
1544
1328
  }
1545
- function normalizePhotoSession(input) {
1546
- if (!input.photoSession) return void 0;
1547
- const schedule = input.photoSchedule ?? sellerPhotoSchedule();
1548
- const date = normalizeVisitDate(input.photoSession.date, schedule.timeZone);
1549
- const time = normalizeVisitTime(input.photoSession.time);
1550
- if (!date || !time || !isVisitSlotAllowed(schedule, date, time)) {
1551
- throw new LeadSubmitError(
1552
- "Garagem SDK: photo session slot is outside the schedule.",
1553
- { code: "invalid_slot" }
1554
- );
1555
- }
1556
- return { date, time };
1329
+ function catalogBusinessType(value) {
1330
+ return value === "sale" || value === "rental" ? value : void 0;
1331
+ }
1332
+ function trackListingView(listing) {
1333
+ if (!listing?.id) return;
1334
+ emitSiteEvent("property_viewed", {
1335
+ property_id: listing.id,
1336
+ listing_code: listing.listingCode ?? void 0,
1337
+ property_type: listing.property?.type || void 0,
1338
+ business_type: catalogBusinessType(listing.businessType),
1339
+ location_city: listing.location?.city || void 0,
1340
+ location_state: listing.location?.state || void 0,
1341
+ location_neighborhood: listing.location?.neighborhood || void 0
1342
+ });
1557
1343
  }
1558
- async function submitSellerLead(input) {
1559
- const owner = normalizeOwner(input.owner);
1560
- const address = normalizeAddress(input.address);
1561
- const property = normalizeProperty(input.property);
1562
- const photos = normalizePhotos(input.photos);
1563
- const photoScheduling = normalizePhotoSession(input);
1564
- return postSiteLead({
1565
- siteId: input.siteId,
1566
- baseUrl: input.baseUrl,
1567
- fetch: input.fetch,
1568
- publishableKey: input.publishableKey,
1569
- body: {
1570
- source: "site-sdk",
1571
- leadType: "seller_lead",
1572
- ...owner,
1573
- address,
1574
- ...property,
1575
- ...photos ? { photos } : {},
1576
- ...photoScheduling ? { photoScheduling } : {},
1577
- ...input.visitorId ? { visitorId: input.visitorId } : {},
1578
- ...input.brokerRef ? { brokerRef: input.brokerRef } : {},
1579
- ...input.referrer ? { referrer: input.referrer } : {}
1580
- }
1344
+ function trackLeadGenerated(leadType, listingId) {
1345
+ emitSiteEvent("lead_generated", {
1346
+ lead_type: leadType,
1347
+ property_id: listingId,
1348
+ form_location: "property_page"
1581
1349
  });
1582
1350
  }
1583
1351
 
1584
- // src/amenity-labels.ts
1585
- var LISTING_AMENITY_TITLES = {
1586
- unit: "Comodidades",
1587
- building: "Comodidades do condom\xEDnio"
1352
+ // src/schedule.ts
1353
+ var VISIT_TIME_ZONE = "America/Sao_Paulo";
1354
+ var HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
1355
+ var VISIT_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)(?::[0-5]\d(?:\.\d+)?)?$/;
1356
+ var YMD_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
1357
+ var ISO_INSTANT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
1358
+ var DATETIME_LOCAL_RE = /^(\d{4}-\d{2}-\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
1359
+ var WEEKDAY_SHORT = {
1360
+ Sun: 0,
1361
+ Mon: 1,
1362
+ Tue: 2,
1363
+ Wed: 3,
1364
+ Thu: 4,
1365
+ Fri: 5,
1366
+ Sat: 6
1588
1367
  };
1589
- var AMENITY_FALLBACK_LABELS = {
1590
- // ==================== PROPERTY FEATURES ====================
1591
- // Amenities
1592
- arCondicionado: "Ar condicionado",
1593
- banheira: "Banheira",
1594
- carregadorEletrico: "Carregador el\xE9trico",
1595
- churrasqueira: "Churrasqueira",
1596
- chuveiroGas: "Chuveiro a g\xE1s",
1597
- chuveiroEletrico: "Chuveiro el\xE9trico",
1598
- energiaSolar: "Energia solar",
1599
- fechaduraDigital: "Fechadura digital",
1600
- fechaduraEletronica: "Fechadura eletr\xF4nica",
1601
- geradorEletrico: "Gerador el\xE9trico",
1602
- gesso: "Gesso",
1603
- hidromassagem: "Hidromassagem",
1604
- lareira: "Lareira",
1605
- ofuro: "Ofur\xF4",
1606
- spa: "Spa",
1607
- painelSolar: "Painel solar",
1608
- portaoEletronico: "Port\xE3o eletr\xF4nico",
1609
- sistemaAlarme: "Sistema de alarme",
1610
- homeTheater: "Home theater",
1611
- adega: "Adega",
1612
- split: "Split",
1613
- arCentral: "Ar central",
1614
- esperaSplit: "Espera para split",
1615
- vistaMar: "Vista para o mar",
1616
- vistaPanoramica: "Vista panor\xE2mica",
1617
- aguaQuente: "\xC1gua quente",
1618
- reformado: "Reformado",
1619
- tvCabo: "TV a cabo",
1620
- gradeado: "Gradeado",
1621
- antenaParabolica: "Antena parab\xF3lica",
1622
- aquecimento: "Aquecimento",
1623
- aquecimentoEletrico: "Aquecimento el\xE9trico",
1624
- aquecimentoCentral: "Aquecimento central",
1625
- cercaEletrica: "Cerca el\xE9trica",
1626
- monitoramento: "Monitoramento",
1627
- vigiaInterno: "Vigia interno",
1628
- vigiaExterno: "Vigia externo",
1629
- alarme: "Alarme",
1630
- agua: "\xC1gua",
1631
- redeEsgoto: "Rede de esgoto",
1632
- pavimentacao: "Pavimenta\xE7\xE3o",
1633
- energiaEletrica: "Energia el\xE9trica",
1634
- // Furniture
1635
- mobiliado: "Mobiliado",
1636
- armarioEmbutido: "Arm\xE1rio embutido",
1637
- armarioEmbutidoQuarto: "Arm\xE1rio embutido quarto",
1638
- armarioCozinha: "Arm\xE1rio cozinha",
1639
- armarioBanheiro: "Arm\xE1rio banheiro",
1640
- cozinhaPlanejada: "Cozinha planejada",
1641
- fogao: "Fog\xE3o",
1642
- fornoPizza: "Forno de pizza",
1643
- freezer: "Freezer",
1644
- dormitorioComArmario: "Dormit\xF3rio com arm\xE1rio",
1645
- semiMobiliado: "Semi mobiliado",
1646
- salaArmarios: "Sala com arm\xE1rios",
1647
- // Structure
1648
- piscina: "Piscina",
1649
- piscinaAquecida: "Piscina aquecida",
1650
- piscinaCoberta: "Piscina coberta",
1651
- poco: "Po\xE7o",
1652
- pocoArtesiano: "Po\xE7o artesiano",
1653
- bar: "Bar",
1654
- jardim: "Jardim",
1655
- lago: "Lago",
1656
- lavabo: "Lavabo",
1657
- quintal: "Quintal",
1658
- solarium: "Solarium",
1659
- quartoServico: "Quarto de servi\xE7o",
1660
- varanda: "Varanda",
1661
- varandaFechadaVidro: "Varanda fechada com vidro",
1662
- varandaGourmet: "Varanda gourmet",
1663
- banheiroServico: "Banheiro de servi\xE7o",
1664
- areaServico: "\xC1rea de servi\xE7o",
1665
- cinema: "Cinema",
1666
- closet: "Closet",
1667
- cozinhaAmericana: "Cozinha americana",
1668
- cozinhaGourmet: "Cozinha gourmet",
1669
- despensa: "Despensa",
1670
- escritorio: "Escrit\xF3rio",
1671
- edicula: "Ed\xEDcula",
1672
- horta: "Horta",
1673
- sacada: "Sacada",
1674
- salaJantar: "Sala de jantar",
1675
- cozinha: "Cozinha",
1676
- banheiroSocial: "Banheiro social",
1677
- terraco: "Terra\xE7o",
1678
- copa: "Copa",
1679
- suiteMaster: "Su\xEDte master",
1680
- wcEmpregada: "WC empregada",
1681
- dependenciaEmpregada: "Depend\xEAncia de empregada",
1682
- dependenciadeEmpregada: "Depend\xEAncia empregada",
1683
- salaTv: "Sala de TV",
1684
- copaCozinha: "Copa cozinha",
1685
- sacadaComChurrasqueira: "Sacada com churrasqueira",
1686
- hallPrivativo: "Hall privativo",
1687
- estarIntimo: "Estar \xEDntimo",
1688
- livingHall: "Living hall",
1689
- piscinaInterna: "Piscina interna",
1690
- deck: "Deck",
1691
- jardimInverno: "Jardim de inverno",
1692
- rouparia: "Rouparia",
1693
- living: "Living",
1694
- familyRoom: "Family room",
1695
- salafitness: "Sala fitness",
1696
- salaEstar: "Sala de estar",
1697
- mezanino: "Mezanino",
1698
- pisoElevado: "Piso elevado",
1699
- entradaServicoIndependente: "Entrada de servi\xE7o independente",
1700
- forro: "Forro",
1701
- vitrine: "Vitrine",
1702
- banheiroAuxiliar: "Banheiro auxiliar",
1703
- gabinete: "Gabinete",
1704
- quadraTenisPrivativa: "Quadra de t\xEAnis privativa",
1705
- porao: "Por\xE3o",
1706
- sotao: "S\xF3t\xE3o",
1707
- patio: "P\xE1tio",
1708
- canaletasNoRodape: "Canaletas no rodap\xE9",
1709
- // Accessibility
1710
- barraApoioVaso: "Barra de apoio vaso",
1711
- barraApoioChuveiro: "Barra de apoio chuveiro",
1712
- entradaSemDegrau: "Entrada sem degrau",
1713
- rampasAcesso: "Rampas de acesso",
1714
- vagaDeficientes: "Vaga para deficientes",
1715
- // Flooring
1716
- cimentoQueimado: "Cimento queimado",
1717
- madeira: "Madeira",
1718
- pisoFrio: "Piso frio",
1719
- laminado: "Laminado",
1720
- vinilico: "Vin\xEDlico",
1721
- porcelanato: "Porcelanato",
1722
- // ==================== BUILDING FEATURES ====================
1723
- // Amenities
1724
- elevador: "Elevador",
1725
- bicicletario: "Biciclet\xE1rio",
1726
- carregadorEletronico: "Carregador eletr\xF4nico",
1727
- concierge: "Concierge",
1728
- coworking: "Coworking",
1729
- deposito: "Dep\xF3sito",
1730
- lavanderia: "Lavanderia",
1731
- petPlace: "Pet place",
1732
- recebimentoEncomendas: "Recebimento de encomendas",
1733
- salaReuniao: "Sala de reuni\xE3o",
1734
- salaoFestas: "Sal\xE3o de festas",
1735
- valet: "Valet",
1736
- garagemCoberta: "Garagem coberta",
1737
- elevadorServico: "Elevador de servi\xE7o",
1738
- // Leisure
1739
- academia: "Academia",
1740
- campoFutebol: "Campo de futebol",
1741
- espacoGourmet: "Espa\xE7o gourmet",
1742
- piscinaInfantil: "Piscina infantil",
1743
- pistaCaminhada: "Pista de caminhada",
1744
- playground: "Playground",
1745
- quadraPoliesportiva: "Quadra poliesportiva",
1746
- quadraTenis: "Quadra de t\xEAnis",
1747
- salaJogos: "Sala de jogos",
1748
- salaVapor: "Sala de vapor",
1749
- sauna: "Sauna",
1750
- // Security
1751
- circuitoTv: "Circuito fechado de TV",
1752
- controleAcessoEletronico: "Controle de acesso eletr\xF4nico",
1753
- interfone: "Interfone",
1754
- portaria24h: "Portaria 24h",
1755
- porteiroFisico: "Porteiro f\xEDsico",
1756
- seguranca24h: "Seguran\xE7a 24h",
1757
- segurancaPatrimonial: "Seguran\xE7a patrimonial",
1758
- condominioFechado: "Condom\xEDnio fechado",
1759
- // Accessibility
1760
- banheiroAcessivel: "Banheiro acess\xEDvel",
1761
- elevadorAcessivel: "Elevador acess\xEDvel",
1762
- pisoTatil: "Piso t\xE1til",
1763
- // ==================== CANONICAL HAS*/IS* KEYS ====================
1764
- has24hConcierge: "Portaria 24h",
1765
- has24hSecurity: "Seguran\xE7a 24h",
1766
- hasAccessRamps: "Rampas de acesso",
1767
- hasAccessibleBathroom: "Banheiro acess\xEDvel",
1768
- hasAccessibleElevator: "Elevador acess\xEDvel",
1769
- hasAirConditioning: "Ar condicionado",
1770
- hasAlarmSystem: "Sistema de alarme",
1771
- hasBalcony: "Varanda",
1772
- hasBikeStorage: "Biciclet\xE1rio",
1773
- hasBuiltInWardrobe: "Arm\xE1rio embutido",
1774
- hasCCTV: "CFTV",
1775
- hasCloset: "Closet",
1776
- hasConcierge: "Portaria",
1777
- hasControlledAccess: "Condom\xEDnio fechado",
1778
- hasCoworking: "Coworking",
1779
- hasDisabledParking: "Vaga para deficientes",
1780
- hasElectricCharger: "Carregador eletr\xF4nico",
1781
- hasElectronicGate: "Port\xE3o eletr\xF4nico",
1782
- hasElevator: "Elevador",
1783
- hasFireplace: "Lareira",
1784
- hasGarden: "Jardim",
1785
- hasGasShower: "Chuveiro a g\xE1s",
1786
- hasGenerator: "Gerador",
1787
- hasGourmetBalcony: "Varanda gourmet",
1788
- hasGourmetKitchen: "Cozinha gourmet",
1789
- hasGrill: "Churrasqueira",
1790
- hasGuestParking: "Estacionamento para visitantes",
1791
- hasGym: "Academia",
1792
- hasHeating: "Aquecimento",
1793
- hasHomeOffice: "Home office",
1794
- hasIntercom: "Interfone",
1795
- hasJacuzzi: "Hidromassagem",
1796
- hasKidsPool: "Piscina infantil",
1797
- hasLaundry: "Lavanderia",
1798
- hasMeetingRoom: "Sala de reuni\xE3o",
1799
- hasOffice: "Escrit\xF3rio",
1800
- hasOpenKitchen: "Cozinha americana",
1801
- hasPackageReceival: "Recebimento de encomendas",
1802
- hasPantry: "Despensa",
1803
- hasParkingGarage: "Garagem coberta",
1804
- hasPartySaloon: "Sal\xE3o de festas",
1805
- hasPetArea: "Pet place",
1806
- hasPipedGas: "G\xE1s encanado",
1807
- hasPlayground: "Playground",
1808
- hasPowderRoom: "Lavabo",
1809
- hasPrivatePool: "Piscina privativa",
1810
- hasSauna: "Sauna",
1811
- hasSecurity: "Seguran\xE7a",
1812
- hasServiceArea: "\xC1rea de servi\xE7o",
1813
- hasSolarPanel: "Painel solar",
1814
- hasSpa: "Spa",
1815
- hasSportsCourt: "Quadra de esportes",
1816
- hasStepFreeEntrance: "Entrada sem degrau",
1817
- hasStorage: "Dep\xF3sito",
1818
- hasSwimmingPool: "Piscina",
1819
- hasTennisCourt: "Quadra de t\xEAnis",
1820
- hasValetParking: "Valet",
1821
- homeOffice: "Home office",
1822
- isPetFriendly: "Pet friendly",
1823
- isFurnished: "Mobiliado",
1824
- isPartiallyFurnished: "Semi-mobiliado",
1825
- petFriendly: "Pet friendly",
1826
- piscinaPrivativa: "Piscina privativa",
1827
- pisoLaminado: "Piso laminado",
1828
- pisoMadeira: "Piso de madeira",
1829
- pisoPorcelanato: "Piso porcelanato",
1830
- quadraEsportes: "Quadra de esportes",
1831
- rooftop: "Rooftop",
1832
- suite: "Su\xEDte",
1833
- triplex: "Triplex",
1834
- duplex: "Duplex",
1835
- cobertura: "Cobertura",
1836
- forroGesso: "Forro de gesso",
1837
- gerador: "Gerador",
1838
- armariosCozinha: "Arm\xE1rios na cozinha",
1839
- armariosQuarto: "Arm\xE1rios nos quartos",
1840
- cftv: "CFTV"
1841
- };
1842
- function lookupLabel(id, options) {
1843
- const fromDictionary = options?.find((option) => option.id === id)?.label;
1844
- if (fromDictionary?.trim()) return fromDictionary.trim();
1845
- return AMENITY_FALLBACK_LABELS[id];
1368
+ function pad2(value) {
1369
+ return String(value).padStart(2, "0");
1846
1370
  }
1847
- function labelAmenities(ids, dictionary) {
1848
- if (!ids?.length) return [];
1849
- const labels = [];
1850
- const seen = /* @__PURE__ */ new Set();
1851
- for (const id of ids) {
1852
- if (!id) continue;
1853
- const label = lookupLabel(id, dictionary);
1854
- if (!label || seen.has(label)) continue;
1855
- seen.add(label);
1856
- labels.push(label);
1371
+ function parseHHmm(value) {
1372
+ const match = HHMM_RE.exec(value);
1373
+ if (!match) return null;
1374
+ return { hour: Number(match[1]), minute: Number(match[2]) };
1375
+ }
1376
+ function minutesOfDay(hhmm) {
1377
+ const parsed = parseHHmm(hhmm);
1378
+ if (!parsed) return null;
1379
+ return parsed.hour * 60 + parsed.minute;
1380
+ }
1381
+ function normalizeVisitTime(value) {
1382
+ const match = VISIT_TIME_RE.exec(value.trim());
1383
+ return match ? `${match[1]}:${match[2]}` : null;
1384
+ }
1385
+ function expandVisitTimeSlots(hours) {
1386
+ const start = minutesOfDay(hours.start);
1387
+ const end = minutesOfDay(hours.end);
1388
+ if (start == null || end == null || start > end) return [];
1389
+ const slots = [];
1390
+ for (let minutes = start; minutes <= end; minutes += 60) {
1391
+ const hour = Math.floor(minutes / 60);
1392
+ const minute = minutes % 60;
1393
+ slots.push(`${pad2(hour)}:${pad2(minute)}`);
1857
1394
  }
1858
- return labels.sort((a, b) => a.localeCompare(b, "pt-BR"));
1395
+ return slots;
1859
1396
  }
1860
- function presentIds(ids) {
1861
- return (ids ?? []).filter((id) => Boolean(id));
1397
+ function unionSorted(left, right) {
1398
+ return Array.from(/* @__PURE__ */ new Set([...left, ...right])).sort();
1862
1399
  }
1863
- function buildingIdsFromMergedAmenities(listing, unitIds) {
1864
- if (!listing.amenities || listing.propertyFeatures == null) return [];
1865
- const unitCounts = /* @__PURE__ */ new Map();
1866
- for (const id of unitIds) {
1867
- unitCounts.set(id, (unitCounts.get(id) ?? 0) + 1);
1400
+ function expandVisitSchedule(config) {
1401
+ const weekendHours = config.weekend ?? (config.saturday || config.sunday ? config.weekday : null);
1402
+ const weekdayTimeSlots = expandVisitTimeSlots(config.weekday);
1403
+ const weekendTimeSlots = weekendHours ? expandVisitTimeSlots(weekendHours) : [];
1404
+ const disabledDays = [];
1405
+ if (!config.sunday) disabledDays.push(0);
1406
+ if (!config.saturday) disabledDays.push(6);
1407
+ return {
1408
+ ...config,
1409
+ weekend: weekendHours,
1410
+ disabledDays,
1411
+ weekdayTimeSlots,
1412
+ weekendTimeSlots,
1413
+ timeSlots: unionSorted(weekdayTimeSlots, weekendTimeSlots)
1414
+ };
1415
+ }
1416
+ var STUDIO_DEFAULT_VISIT_SCHEDULE = expandVisitSchedule(
1417
+ {
1418
+ timeZone: VISIT_TIME_ZONE,
1419
+ saturday: false,
1420
+ sunday: false,
1421
+ weekday: { start: "06:00", end: "22:00" },
1422
+ weekend: null,
1423
+ minHoursAhead: 2
1868
1424
  }
1869
- return listing.amenities.filter((id) => {
1870
- if (!id) return false;
1871
- const count = unitCounts.get(id);
1872
- if (count === void 0 || count === 0) return true;
1873
- unitCounts.set(id, count - 1);
1874
- return false;
1875
- });
1425
+ );
1426
+ function zonedParts(date, timeZone) {
1427
+ const parts = new Intl.DateTimeFormat("en-US", {
1428
+ timeZone,
1429
+ weekday: "short",
1430
+ year: "numeric",
1431
+ month: "2-digit",
1432
+ day: "2-digit",
1433
+ hour: "2-digit",
1434
+ minute: "2-digit",
1435
+ hourCycle: "h23"
1436
+ }).formatToParts(date);
1437
+ const get = (type) => parts.find((part) => part.type === type)?.value ?? "";
1438
+ const weekday = WEEKDAY_SHORT[get("weekday")] ?? 0;
1439
+ return {
1440
+ year: Number(get("year")),
1441
+ month: Number(get("month")),
1442
+ day: Number(get("day")),
1443
+ hour: Number(get("hour")),
1444
+ minute: Number(get("minute")),
1445
+ weekday
1446
+ };
1876
1447
  }
1877
- function unitAmenityIds(listing) {
1878
- if (listing.propertyFeatures != null) {
1879
- return presentIds(listing.propertyFeatures);
1448
+ function calendarYmd(date, timeZone) {
1449
+ const parts = zonedParts(date, timeZone);
1450
+ return `${parts.year}-${pad2(parts.month)}-${pad2(parts.day)}`;
1451
+ }
1452
+ function parseYmd(value) {
1453
+ const match = YMD_RE.exec(value);
1454
+ if (!match) return null;
1455
+ const year = Number(match[1]);
1456
+ const month = Number(match[2]);
1457
+ const day = Number(match[3]);
1458
+ const utc = new Date(Date.UTC(year, month - 1, day));
1459
+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
1460
+ return null;
1880
1461
  }
1881
- const building = new Set(
1882
- listing.building?.amenities ?? listing.buildingAmenities ?? []
1883
- );
1884
- return (listing.amenities ?? []).filter((id) => id && !building.has(id));
1462
+ return { year, month, day };
1885
1463
  }
1886
- function buildingAmenityIds(listing) {
1887
- if (listing.building != null && listing.building.amenities != null) {
1888
- return presentIds(listing.building.amenities);
1464
+ function normalizeVisitDate(date, timeZone = VISIT_TIME_ZONE) {
1465
+ if (typeof date === "string") {
1466
+ const trimmed = date.trim();
1467
+ if (parseYmd(trimmed)) return trimmed;
1468
+ if (ISO_INSTANT_RE.test(trimmed)) {
1469
+ const instant = new Date(trimmed);
1470
+ return Number.isFinite(instant.getTime()) ? calendarYmd(instant, timeZone) : null;
1471
+ }
1472
+ const local = DATETIME_LOCAL_RE.exec(trimmed);
1473
+ if (local && parseYmd(local[1])) return local[1];
1474
+ return null;
1889
1475
  }
1890
- if (listing.buildingAmenities != null) {
1891
- return presentIds(listing.buildingAmenities);
1476
+ if (date instanceof Date && Number.isFinite(date.getTime())) {
1477
+ return calendarYmd(date, timeZone);
1892
1478
  }
1893
- return buildingIdsFromMergedAmenities(listing, unitAmenityIds(listing));
1479
+ return null;
1894
1480
  }
1895
- function listingAmenityGroups(listing, dictionary) {
1896
- const groups = [];
1897
- const unitIds = unitAmenityIds(listing);
1898
- const unitLabels = labelAmenities(unitIds, dictionary?.propertyFeatures);
1899
- if (unitLabels.length > 0) {
1900
- groups.push({
1901
- key: "unit",
1902
- title: dictionary?.amenitySectionTitles?.unit ?? LISTING_AMENITY_TITLES.unit,
1903
- labels: unitLabels
1904
- });
1905
- }
1906
- const buildingLabels = labelAmenities(
1907
- buildingAmenityIds(listing),
1908
- dictionary?.buildingAmenities
1481
+ function weekdayOfYmd(ymd, timeZone) {
1482
+ const parsed = parseYmd(ymd);
1483
+ if (!parsed) return null;
1484
+ const utcNoonish = new Date(
1485
+ Date.UTC(parsed.year, parsed.month - 1, parsed.day, 15, 0, 0)
1909
1486
  );
1910
- if (buildingLabels.length > 0) {
1911
- groups.push({
1912
- key: "building",
1913
- title: dictionary?.amenitySectionTitles?.building ?? LISTING_AMENITY_TITLES.building,
1914
- labels: buildingLabels
1915
- });
1916
- }
1917
- return groups;
1487
+ return zonedParts(utcNoonish, timeZone).weekday;
1918
1488
  }
1919
-
1920
- // src/presentation.ts
1921
- function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
1922
- if (amount == null) return "Sob consulta";
1923
- try {
1924
- return new Intl.NumberFormat(locale, {
1925
- style: "currency",
1926
- currency,
1927
- minimumFractionDigits: 0,
1928
- maximumFractionDigits: 0
1929
- }).format(amount);
1930
- } catch {
1931
- return `${currency} ${amount}`;
1932
- }
1489
+ function slotsForDate(schedule, date, now = /* @__PURE__ */ new Date()) {
1490
+ const timeZone = schedule.timeZone;
1491
+ const ymd = normalizeVisitDate(date, timeZone);
1492
+ if (!ymd) return [];
1493
+ const weekday = weekdayOfYmd(ymd, timeZone);
1494
+ if (weekday == null) return [];
1495
+ if (schedule.disabledDays.includes(weekday)) return [];
1496
+ if (weekday === 0 && !schedule.sunday) return [];
1497
+ if (weekday === 6 && !schedule.saturday) return [];
1498
+ const base = weekday === 0 || weekday === 6 ? schedule.weekendTimeSlots : schedule.weekdayTimeSlots;
1499
+ const today = calendarYmd(now, timeZone);
1500
+ if (ymd < today) return [];
1501
+ if (ymd !== today) return [...base];
1502
+ const nowParts = zonedParts(now, timeZone);
1503
+ const cutoff = nowParts.hour * 60 + nowParts.minute + schedule.minHoursAhead * 60;
1504
+ return base.filter((slot) => {
1505
+ const minutes = minutesOfDay(slot);
1506
+ return minutes != null && minutes >= cutoff;
1507
+ });
1933
1508
  }
1934
- function formatGroupedInteger(value, locale = "pt-BR") {
1935
- const digits = String(value ?? "").replace(/\D/g, "");
1936
- if (!digits) return "";
1937
- const amount = Number.parseInt(digits, 10);
1938
- if (!Number.isFinite(amount)) return "";
1939
- return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
1940
- amount
1941
- );
1509
+ function isVisitSlotAllowed(schedule, visitDate, visitTime, now = /* @__PURE__ */ new Date()) {
1510
+ const time = normalizeVisitTime(visitTime);
1511
+ if (!time) return false;
1512
+ return slotsForDate(schedule, visitDate, now).includes(time);
1942
1513
  }
1943
- function parseGroupedInteger(value) {
1944
- if (typeof value === "number") {
1945
- return Number.isFinite(value) ? Math.trunc(value) : void 0;
1946
- }
1947
- const digits = String(value ?? "").replace(/\D/g, "");
1948
- if (!digits) return void 0;
1949
- const amount = Number.parseInt(digits, 10);
1950
- return Number.isFinite(amount) ? amount : void 0;
1514
+
1515
+ // src/phone.ts
1516
+ import {
1517
+ AsYouType,
1518
+ isValidPhoneNumber,
1519
+ parsePhoneNumber
1520
+ } from "libphonenumber-js";
1521
+
1522
+ // src/phone-countries.ts
1523
+ var DEFAULT_PHONE_COUNTRY_CODE = "BR";
1524
+ var PHONE_COUNTRIES = [
1525
+ { code: "BR", name: "Brasil", dialCode: "55", flag: "\u{1F1E7}\u{1F1F7}" },
1526
+ { code: "US", name: "Estados Unidos", dialCode: "1", flag: "\u{1F1FA}\u{1F1F8}" },
1527
+ { code: "CA", name: "Canad\xE1", dialCode: "1", flag: "\u{1F1E8}\u{1F1E6}" },
1528
+ { code: "MX", name: "M\xE9xico", dialCode: "52", flag: "\u{1F1F2}\u{1F1FD}" },
1529
+ { code: "GT", name: "Guatemala", dialCode: "502", flag: "\u{1F1EC}\u{1F1F9}" },
1530
+ { code: "BZ", name: "Belize", dialCode: "501", flag: "\u{1F1E7}\u{1F1FF}" },
1531
+ { code: "SV", name: "El Salvador", dialCode: "503", flag: "\u{1F1F8}\u{1F1FB}" },
1532
+ { code: "HN", name: "Honduras", dialCode: "504", flag: "\u{1F1ED}\u{1F1F3}" },
1533
+ { code: "NI", name: "Nicar\xE1gua", dialCode: "505", flag: "\u{1F1F3}\u{1F1EE}" },
1534
+ { code: "CR", name: "Costa Rica", dialCode: "506", flag: "\u{1F1E8}\u{1F1F7}" },
1535
+ { code: "PA", name: "Panam\xE1", dialCode: "507", flag: "\u{1F1F5}\u{1F1E6}" },
1536
+ { code: "CU", name: "Cuba", dialCode: "53", flag: "\u{1F1E8}\u{1F1FA}" },
1537
+ { code: "DO", name: "Rep\xFAblica Dominicana", dialCode: "1", flag: "\u{1F1E9}\u{1F1F4}" },
1538
+ { code: "HT", name: "Haiti", dialCode: "509", flag: "\u{1F1ED}\u{1F1F9}" },
1539
+ { code: "AR", name: "Argentina", dialCode: "54", flag: "\u{1F1E6}\u{1F1F7}" },
1540
+ { code: "CL", name: "Chile", dialCode: "56", flag: "\u{1F1E8}\u{1F1F1}" },
1541
+ { code: "CO", name: "Col\xF4mbia", dialCode: "57", flag: "\u{1F1E8}\u{1F1F4}" },
1542
+ { code: "PE", name: "Peru", dialCode: "51", flag: "\u{1F1F5}\u{1F1EA}" },
1543
+ { code: "UY", name: "Uruguai", dialCode: "598", flag: "\u{1F1FA}\u{1F1FE}" },
1544
+ { code: "PY", name: "Paraguai", dialCode: "595", flag: "\u{1F1F5}\u{1F1FE}" },
1545
+ { code: "BO", name: "Bol\xEDvia", dialCode: "591", flag: "\u{1F1E7}\u{1F1F4}" },
1546
+ { code: "EC", name: "Equador", dialCode: "593", flag: "\u{1F1EA}\u{1F1E8}" },
1547
+ { code: "VE", name: "Venezuela", dialCode: "58", flag: "\u{1F1FB}\u{1F1EA}" },
1548
+ { code: "GY", name: "Guiana", dialCode: "592", flag: "\u{1F1EC}\u{1F1FE}" },
1549
+ { code: "SR", name: "Suriname", dialCode: "597", flag: "\u{1F1F8}\u{1F1F7}" },
1550
+ { code: "PT", name: "Portugal", dialCode: "351", flag: "\u{1F1F5}\u{1F1F9}" },
1551
+ { code: "ES", name: "Espanha", dialCode: "34", flag: "\u{1F1EA}\u{1F1F8}" },
1552
+ { code: "FR", name: "Fran\xE7a", dialCode: "33", flag: "\u{1F1EB}\u{1F1F7}" },
1553
+ { code: "UK", name: "Reino Unido", dialCode: "44", flag: "\u{1F1EC}\u{1F1E7}" },
1554
+ { code: "DE", name: "Alemanha", dialCode: "49", flag: "\u{1F1E9}\u{1F1EA}" },
1555
+ { code: "IT", name: "It\xE1lia", dialCode: "39", flag: "\u{1F1EE}\u{1F1F9}" },
1556
+ { code: "NL", name: "Holanda", dialCode: "31", flag: "\u{1F1F3}\u{1F1F1}" },
1557
+ { code: "BE", name: "B\xE9lgica", dialCode: "32", flag: "\u{1F1E7}\u{1F1EA}" },
1558
+ { code: "CH", name: "Su\xED\xE7a", dialCode: "41", flag: "\u{1F1E8}\u{1F1ED}" },
1559
+ { code: "AT", name: "\xC1ustria", dialCode: "43", flag: "\u{1F1E6}\u{1F1F9}" },
1560
+ { code: "SE", name: "Su\xE9cia", dialCode: "46", flag: "\u{1F1F8}\u{1F1EA}" },
1561
+ { code: "NO", name: "Noruega", dialCode: "47", flag: "\u{1F1F3}\u{1F1F4}" },
1562
+ { code: "DK", name: "Dinamarca", dialCode: "45", flag: "\u{1F1E9}\u{1F1F0}" },
1563
+ { code: "FI", name: "Finl\xE2ndia", dialCode: "358", flag: "\u{1F1EB}\u{1F1EE}" },
1564
+ { code: "IE", name: "Irlanda", dialCode: "353", flag: "\u{1F1EE}\u{1F1EA}" },
1565
+ { code: "AU", name: "Austr\xE1lia", dialCode: "61", flag: "\u{1F1E6}\u{1F1FA}" },
1566
+ { code: "NZ", name: "Nova Zel\xE2ndia", dialCode: "64", flag: "\u{1F1F3}\u{1F1FF}" },
1567
+ { code: "JP", name: "Jap\xE3o", dialCode: "81", flag: "\u{1F1EF}\u{1F1F5}" },
1568
+ { code: "KR", name: "Coreia do Sul", dialCode: "82", flag: "\u{1F1F0}\u{1F1F7}" },
1569
+ { code: "CN", name: "China", dialCode: "86", flag: "\u{1F1E8}\u{1F1F3}" },
1570
+ { code: "IN", name: "\xCDndia", dialCode: "91", flag: "\u{1F1EE}\u{1F1F3}" },
1571
+ { code: "RU", name: "R\xFAssia", dialCode: "7", flag: "\u{1F1F7}\u{1F1FA}" },
1572
+ { code: "UA", name: "Ucr\xE2nia", dialCode: "380", flag: "\u{1F1FA}\u{1F1E6}" },
1573
+ { code: "AE", name: "Emirados \xC1rabes", dialCode: "971", flag: "\u{1F1E6}\u{1F1EA}" },
1574
+ { code: "SA", name: "Ar\xE1bia Saudita", dialCode: "966", flag: "\u{1F1F8}\u{1F1E6}" },
1575
+ { code: "QA", name: "Catar", dialCode: "974", flag: "\u{1F1F6}\u{1F1E6}" },
1576
+ { code: "KW", name: "Kuwait", dialCode: "965", flag: "\u{1F1F0}\u{1F1FC}" },
1577
+ { code: "BH", name: "Bahrein", dialCode: "973", flag: "\u{1F1E7}\u{1F1ED}" },
1578
+ { code: "OM", name: "Om\xE3", dialCode: "968", flag: "\u{1F1F4}\u{1F1F2}" },
1579
+ { code: "JO", name: "Jord\xE2nia", dialCode: "962", flag: "\u{1F1EF}\u{1F1F4}" },
1580
+ { code: "LB", name: "L\xEDbano", dialCode: "961", flag: "\u{1F1F1}\u{1F1E7}" },
1581
+ { code: "IL", name: "Israel", dialCode: "972", flag: "\u{1F1EE}\u{1F1F1}" },
1582
+ { code: "TR", name: "Turquia", dialCode: "90", flag: "\u{1F1F9}\u{1F1F7}" },
1583
+ { code: "EG", name: "Egito", dialCode: "20", flag: "\u{1F1EA}\u{1F1EC}" },
1584
+ { code: "ZA", name: "\xC1frica do Sul", dialCode: "27", flag: "\u{1F1FF}\u{1F1E6}" },
1585
+ { code: "AO", name: "Angola", dialCode: "244", flag: "\u{1F1E6}\u{1F1F4}" },
1586
+ { code: "MZ", name: "Mo\xE7ambique", dialCode: "258", flag: "\u{1F1F2}\u{1F1FF}" },
1587
+ { code: "CV", name: "Cabo Verde", dialCode: "238", flag: "\u{1F1E8}\u{1F1FB}" }
1588
+ ];
1589
+ function phoneCountrySearchValue(country) {
1590
+ return `${country.name} ${country.code} ${country.dialCode} +${country.dialCode}`;
1951
1591
  }
1952
- function formatAreaM2(area) {
1953
- if (area == null || !Number.isFinite(area)) return null;
1954
- return `${area} m\xB2`;
1592
+ function findPhoneCountry(code) {
1593
+ if (!code) return void 0;
1594
+ const normalized = code.trim().toUpperCase();
1595
+ return PHONE_COUNTRIES.find((country) => country.code === normalized);
1955
1596
  }
1956
- function listingBusinessLabel(businessType) {
1957
- return businessType === "rental" ? "Aluguel" : "Venda";
1597
+ function defaultPhoneCountry() {
1598
+ return findPhoneCountry(DEFAULT_PHONE_COUNTRY_CODE) ?? PHONE_COUNTRIES[0];
1599
+ }
1600
+
1601
+ // src/phone.ts
1602
+ var MAX_NATIONAL_PHONE_DIGITS = 15;
1603
+ var VALID_BR_DDDS = /* @__PURE__ */ new Set([
1604
+ "11",
1605
+ "12",
1606
+ "13",
1607
+ "14",
1608
+ "15",
1609
+ "16",
1610
+ "17",
1611
+ "18",
1612
+ "19",
1613
+ "21",
1614
+ "22",
1615
+ "24",
1616
+ "27",
1617
+ "28",
1618
+ "31",
1619
+ "32",
1620
+ "33",
1621
+ "34",
1622
+ "35",
1623
+ "37",
1624
+ "38",
1625
+ "41",
1626
+ "42",
1627
+ "43",
1628
+ "44",
1629
+ "45",
1630
+ "46",
1631
+ "47",
1632
+ "48",
1633
+ "49",
1634
+ "51",
1635
+ "53",
1636
+ "54",
1637
+ "55",
1638
+ "61",
1639
+ "62",
1640
+ "63",
1641
+ "64",
1642
+ "65",
1643
+ "66",
1644
+ "67",
1645
+ "68",
1646
+ "69",
1647
+ "71",
1648
+ "73",
1649
+ "74",
1650
+ "75",
1651
+ "77",
1652
+ "79",
1653
+ "81",
1654
+ "82",
1655
+ "83",
1656
+ "84",
1657
+ "85",
1658
+ "86",
1659
+ "87",
1660
+ "88",
1661
+ "89",
1662
+ "91",
1663
+ "92",
1664
+ "93",
1665
+ "94",
1666
+ "95",
1667
+ "96",
1668
+ "97",
1669
+ "98",
1670
+ "99"
1671
+ ]);
1672
+ var PHONE_INPUT_COUNTRY_CODES = new Set(
1673
+ PHONE_COUNTRIES.map((country) => country.code)
1674
+ );
1675
+ var SORTED_PHONE_INPUT_DIAL_CODES = [
1676
+ ...new Set(PHONE_COUNTRIES.map((country) => country.dialCode))
1677
+ ].sort((a, b) => b.length - a.length);
1678
+ function toLibCountryCode(code) {
1679
+ if (code === "UK") return "GB";
1680
+ return code;
1958
1681
  }
1959
-
1960
- // src/listing-card-model.ts
1961
- function listingLocationLabel(location) {
1962
- return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
1682
+ function fromLibCountryCode(code) {
1683
+ if (code === "GB") return "UK";
1684
+ return code;
1963
1685
  }
1964
- function toListingCardModel(listing) {
1965
- const isPrivate = listing.priceVisibility === "private";
1966
- const area = listing.property?.usableArea ?? listing.property?.totalArea;
1967
- return {
1968
- href: listingPublicPath(listing),
1969
- title: listing.title,
1970
- businessType: listing.businessType,
1971
- businessLabel: listingBusinessLabel(listing.businessType),
1972
- priceVisibility: listing.priceVisibility,
1973
- price: listing.price,
1974
- priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price, "pt-BR", listing.currency ?? "BRL"),
1975
- pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
1976
- locationLabel: listingLocationLabel(listing.location || {}),
1977
- propertyType: listing.property?.type ?? null,
1978
- coverSrc: listing.coverImage?.src ?? null,
1979
- coverAlt: listing.coverImage?.alt ?? listing.title,
1980
- bedrooms: listing.property?.bedrooms ?? null,
1981
- bathrooms: listing.property?.bathrooms ?? null,
1982
- parkingSpaces: listing.property?.parkingSpaces ?? null,
1983
- areaM2: area ?? null
1984
- };
1686
+ function nationalPhoneDigits(value) {
1687
+ return String(value ?? "").replace(/\D/g, "");
1985
1688
  }
1986
-
1987
- // ../search-url/types.ts
1988
- var SEARCH_BASE_ROUTE = "imoveis";
1989
- var MAX_PAGE = 1e4;
1990
- var MAX_LOC_GROUPS = 20;
1991
- var DEFAULT_MIN_PRICE = 0;
1992
- var DEFAULT_MAX_PRICE = 1e9;
1993
- var DEFAULT_MIN_AREA = 0;
1994
- var DEFAULT_MAX_AREA = 1e5;
1995
- var SORT_URL_TOKENS = [
1996
- "recentes",
1997
- "preco-asc",
1998
- "preco-desc",
1999
- "area-asc",
2000
- "area-desc"
2001
- ];
2002
-
2003
- // ../search-url/slugify.ts
2004
- function slugifyForUrl(text2) {
2005
- if (!text2) return "";
2006
- const withDashes = text2.replace(/([a-z])([A-Z])/g, "$1-$2");
2007
- return withDashes.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
1689
+ function truncateNationalPhoneDigits(digits, max = MAX_NATIONAL_PHONE_DIGITS) {
1690
+ return digits.slice(0, max);
2008
1691
  }
2009
-
2010
- // ../search-url/catalog.ts
2011
- var PROPERTY_TYPE_SLUG_ALIASES = {
2012
- rural: ["chacara", "fazenda", "sitio"]
2013
- };
2014
- function buildListingTypeOptions(enabled) {
2015
- const flags = enabled ?? { sale: true, rental: true };
2016
- const out = [];
2017
- if (flags.sale !== false) {
2018
- out.push({ id: "sale", slug: "venda", label: "Venda" });
1692
+ function collapseDuplicatedBrazilianMobileNine(digits) {
1693
+ if (digits.length === 14 && digits.startsWith("55")) {
1694
+ const national = collapseDuplicatedBrazilianMobileNine(digits.slice(2));
1695
+ return national === digits.slice(2) ? digits : `55${national}`;
2019
1696
  }
2020
- if (flags.rental !== false) {
2021
- out.push({ id: "rental", slug: "aluguel", label: "Aluguel" });
1697
+ if (digits.length !== 12) return digits;
1698
+ const ddd = digits.slice(0, 2);
1699
+ if (!VALID_BR_DDDS.has(ddd)) return digits;
1700
+ if (digits.charAt(2) !== "9") return digits;
1701
+ const rest = digits.slice(3);
1702
+ if (rest.length !== 9 || rest.charAt(0) !== "9") return digits;
1703
+ if (ddd === "55") {
1704
+ const subscriberFirst = digits.charAt(4);
1705
+ if (subscriberFirst >= "0" && subscriberFirst <= "5") {
1706
+ return digits;
1707
+ }
2022
1708
  }
2023
- return out;
2024
- }
2025
- function emptySearchUrlDictionary() {
2026
- return {
2027
- listingTypes: buildListingTypeOptions(null),
2028
- propertyTypes: [],
2029
- propertyFeatures: [],
2030
- buildingAmenities: []
2031
- };
2032
- }
2033
- function norm(value) {
2034
- return slugifyForUrl(value) || value.toLowerCase();
1709
+ return `${ddd}${rest}`;
2035
1710
  }
2036
- function matchOptionId(segment, options, extraAliases) {
2037
- const n = norm(segment);
2038
- for (const option of options) {
2039
- const aliases = extraAliases?.[option.id] ?? [];
2040
- const candidates = [option.id, option.slug, option.label, ...aliases];
2041
- if (candidates.some((c) => norm(c) === n)) return option.id;
1711
+ var BR_DIAL_CODE = "55";
1712
+ function stripAccidentalDialCodePrefix(numbers, country) {
1713
+ const dial = country.dialCode;
1714
+ if (!numbers.startsWith(dial) || numbers.length <= dial.length) {
1715
+ return numbers;
2042
1716
  }
2043
- return null;
2044
- }
2045
- function optionSlugById(id, options) {
2046
- const option = options.find((item) => item.id === id);
2047
- return option?.slug ?? null;
1717
+ const withoutDial = numbers.slice(dial.length);
1718
+ if (!withoutDial) return numbers;
1719
+ try {
1720
+ const parsed = parsePhoneNumber(numbers, toLibCountryCode(country.code));
1721
+ if (parsed.nationalNumber === numbers) {
1722
+ return numbers;
1723
+ }
1724
+ if (parsed.countryCallingCode === dial && parsed.nationalNumber === withoutDial) {
1725
+ return withoutDial;
1726
+ }
1727
+ } catch {
1728
+ }
1729
+ return numbers;
2048
1730
  }
2049
- var LISTING_TYPE_ALIASES = {
2050
- sale: ["comprar"],
2051
- rental: ["alugar"]
2052
- };
2053
-
2054
- // ../search-url/path.ts
2055
- function toArray(value) {
2056
- if (value === void 0) return [];
2057
- return Array.isArray(value) ? value : [value];
1731
+ function prepareNationalDigits(value, country) {
1732
+ const raw = nationalPhoneDigits(value);
1733
+ const stripped = stripAccidentalDialCodePrefix(raw, country);
1734
+ const digits = country.dialCode === BR_DIAL_CODE ? collapseDuplicatedBrazilianMobileNine(stripped) : stripped;
1735
+ return truncateNationalPhoneDigits(digits);
2058
1736
  }
2059
- function formatNumeric(value) {
2060
- return Array.isArray(value) ? value.join("-") : String(value);
1737
+ function prepareInternationalDigits(value) {
1738
+ const digits = nationalPhoneDigits(value);
1739
+ const collapsed = collapseDuplicatedBrazilianMobileNine(digits);
1740
+ if (collapsed === digits) return digits;
1741
+ try {
1742
+ const original = parsePhoneNumber(`+${digits}`);
1743
+ if (original.isValid() && original.countryCallingCode !== BR_DIAL_CODE) {
1744
+ return digits;
1745
+ }
1746
+ } catch {
1747
+ }
1748
+ return collapsed;
2061
1749
  }
2062
- function formatRange(min, max, unit) {
2063
- return `de-${min}-a-${max}-${unit}`;
1750
+ function formatNationalDigits(digits, country) {
1751
+ if (!digits) return "";
1752
+ const libCode = toLibCountryCode(country.code);
1753
+ const formatter = new AsYouType(libCode);
1754
+ formatter.input(`+${country.dialCode}${digits}`);
1755
+ const national = formatter.getNumber()?.formatNational();
1756
+ if (national && nationalPhoneDigits(national) === digits) return national;
1757
+ const asTyped = new AsYouType(libCode).input(digits);
1758
+ if (nationalPhoneDigits(asTyped) === digits) return asTyped;
1759
+ return digits;
2064
1760
  }
2065
- function formatSuiteSuffix(value) {
2066
- const values = Array.isArray(value) ? value : [value];
2067
- const firstValue = values[0] ?? 0;
2068
- return firstValue === 0 || firstValue === 1 ? "suite" : "suites";
1761
+ function formatPhoneNational(value, countryCode = DEFAULT_PHONE_COUNTRY_CODE) {
1762
+ const country = findPhoneCountry(countryCode) ?? defaultPhoneCountry();
1763
+ return formatNationalDigits(prepareNationalDigits(value, country), country);
2069
1764
  }
2070
- function composeSearchPublicPath(filters, dictionary = emptySearchUrlDictionary()) {
2071
- const segments = [];
2072
- const listingType = filters.listingType;
2073
- if (listingType) {
2074
- segments.push(
2075
- optionSlugById(listingType, dictionary.listingTypes) || slugifyForUrl(listingType)
2076
- );
2077
- }
2078
- for (const propertyType of toArray(filters.propertyType)) {
2079
- segments.push(
2080
- optionSlugById(propertyType, dictionary.propertyTypes) || slugifyForUrl(propertyType)
2081
- );
2082
- }
2083
- const location = filters.location;
2084
- if (location) {
2085
- if (location.state) segments.push(slugifyForUrl(location.state));
2086
- if (location.city) segments.push(slugifyForUrl(location.city));
2087
- if (location.neighborhood)
2088
- segments.push(slugifyForUrl(location.neighborhood));
2089
- if (location.street) segments.push(slugifyForUrl(location.street));
2090
- }
2091
- if (filters.bedrooms !== void 0) {
2092
- segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);
2093
- }
2094
- if (filters.bathrooms !== void 0) {
2095
- segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);
2096
- }
2097
- if (filters.suites !== void 0) {
2098
- const suffix = formatSuiteSuffix(filters.suites);
2099
- segments.push(`${formatNumeric(filters.suites)}-${suffix}`);
1765
+ function parsePhoneInput(input) {
1766
+ const cleaned = String(input ?? "").replace(/[\s\-().]/g, "");
1767
+ if (!cleaned) {
1768
+ return { ddi: null, national: "", countryCode: null };
2100
1769
  }
2101
- if (filters.parkingSpots !== void 0) {
2102
- segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);
1770
+ const hasPlus = cleaned.startsWith("+");
1771
+ if (hasPlus) {
1772
+ try {
1773
+ const parsed = parsePhoneNumber(cleaned);
1774
+ if (parsed.country) {
1775
+ const ourCode = fromLibCountryCode(parsed.country);
1776
+ if (PHONE_INPUT_COUNTRY_CODES.has(ourCode)) {
1777
+ return {
1778
+ ddi: parsed.countryCallingCode,
1779
+ national: parsed.nationalNumber,
1780
+ countryCode: ourCode
1781
+ };
1782
+ }
1783
+ }
1784
+ } catch {
1785
+ }
1786
+ const digits = cleaned.slice(1);
1787
+ for (const ddi of SORTED_PHONE_INPUT_DIAL_CODES) {
1788
+ if (digits.startsWith(ddi)) {
1789
+ const national = digits.slice(ddi.length);
1790
+ const match = PHONE_COUNTRIES.find((c) => c.dialCode === ddi);
1791
+ return {
1792
+ ddi,
1793
+ national,
1794
+ countryCode: match?.code ?? null
1795
+ };
1796
+ }
1797
+ }
1798
+ return {
1799
+ ddi: null,
1800
+ national: digits,
1801
+ countryCode: null
1802
+ };
2103
1803
  }
2104
- if (filters.price && (filters.price.min !== void 0 || filters.price.max !== void 0)) {
2105
- const min = filters.price.min ?? DEFAULT_MIN_PRICE;
2106
- const max = filters.price.max ?? DEFAULT_MAX_PRICE;
2107
- segments.push(formatRange(min, max, "reais"));
1804
+ return {
1805
+ ddi: null,
1806
+ national: cleaned.replace(/\D/g, ""),
1807
+ countryCode: null
1808
+ };
1809
+ }
1810
+ function preferValidE164(candidate) {
1811
+ try {
1812
+ const number = parsePhoneNumber(candidate);
1813
+ if (number.isValid()) return number.number;
1814
+ } catch {
2108
1815
  }
2109
- if (filters.area && (filters.area.min !== void 0 || filters.area.max !== void 0)) {
2110
- const min = filters.area.min ?? DEFAULT_MIN_AREA;
2111
- const max = filters.area.max ?? DEFAULT_MAX_AREA;
2112
- segments.push(formatRange(min, max, "m2"));
1816
+ return candidate;
1817
+ }
1818
+ function toE164(value, countryCode = DEFAULT_PHONE_COUNTRY_CODE) {
1819
+ const trimmed = String(value ?? "").trim();
1820
+ if (!trimmed) return "";
1821
+ const parsed = parsePhoneInput(trimmed);
1822
+ if (parsed.ddi && parsed.national) {
1823
+ const ddiCountry = parsed.countryCode && findPhoneCountry(parsed.countryCode) || PHONE_COUNTRIES.find((c) => c.dialCode === parsed.ddi) || defaultPhoneCountry();
1824
+ return preferValidE164(
1825
+ `+${parsed.ddi}${prepareNationalDigits(parsed.national, ddiCountry)}`
1826
+ );
2113
1827
  }
2114
- const seenAmenities = /* @__PURE__ */ new Set();
2115
- for (const id of filters.propertyFeatures ?? []) {
2116
- const slug = optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);
2117
- if (!slug || seenAmenities.has(slug)) continue;
2118
- seenAmenities.add(slug);
2119
- segments.push(slug);
1828
+ const country = findPhoneCountry(countryCode) ?? defaultPhoneCountry();
1829
+ const national = prepareNationalDigits(parsed.national || trimmed, country);
1830
+ if (!national) return "";
1831
+ return preferValidE164(`+${country.dialCode}${national}`);
1832
+ }
1833
+ function isValidPhone(value, countryCode) {
1834
+ const cleaned = String(value ?? "").trim();
1835
+ if (!cleaned) return false;
1836
+ if (cleaned.startsWith("+")) {
1837
+ const digits2 = prepareInternationalDigits(cleaned);
1838
+ return digits2 ? isValidPhoneNumber(`+${digits2}`) : false;
2120
1839
  }
2121
- for (const id of filters.buildingAmenities ?? []) {
2122
- const slug = optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);
2123
- if (!slug || seenAmenities.has(slug)) continue;
2124
- seenAmenities.add(slug);
2125
- segments.push(slug);
1840
+ const country = countryCode ? findPhoneCountry(countryCode) : defaultPhoneCountry();
1841
+ if (!country) return false;
1842
+ const digits = prepareNationalDigits(cleaned, country);
1843
+ if (!digits) return false;
1844
+ if (countryCode) {
1845
+ return isValidPhoneNumber(digits, toLibCountryCode(countryCode));
2126
1846
  }
2127
- const path = segments.filter(Boolean).join("/");
2128
- return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;
1847
+ if (isValidPhoneNumber(`+${digits}`)) return true;
1848
+ return isValidPhoneNumber(digits, "BR");
2129
1849
  }
2130
- var BEDROOMS = /^(\d+(?:-\d+)*)-quartos?$/;
2131
- var BATHROOMS = /^(\d+(?:-\d+)*)-banheiros?$/;
2132
- var SUITES = /^(\d+(?:-\d+)*)-suites?$/;
2133
- var PARKING = /^(\d+(?:-\d+)*)-vagas?$/;
2134
- var PRICE = /^de-(\d+)-a-(\d+)-(reais|real)$/;
2135
- var AREA = /^de-(\d+)-a-(\d+)-(m2|m²)$/;
2136
- function parseNumericList(raw) {
2137
- return raw.split("-").map((part) => Number(part)).filter((n) => Number.isFinite(n));
1850
+ function remaskPhoneForCountry(nationalOrDraft, countryCode) {
1851
+ const country = findPhoneCountry(countryCode) ?? defaultPhoneCountry();
1852
+ const digits = truncateNationalPhoneDigits(
1853
+ nationalPhoneDigits(nationalOrDraft)
1854
+ );
1855
+ return {
1856
+ display: formatNationalDigits(digits, country),
1857
+ e164: digits ? `+${country.dialCode}${digits}` : "",
1858
+ country
1859
+ };
2138
1860
  }
2139
- function collapse(values) {
2140
- return values.length === 1 ? values[0] : values;
1861
+
1862
+ // src/resolve-site-id.ts
1863
+ var PREVIEW_HOST_SUFFIXES = [".vusercontent.net"];
1864
+ function isStudioPreviewHost(host) {
1865
+ const normalized = stripPort(host);
1866
+ if (normalized === "localhost" || normalized === "127.0.0.1") return true;
1867
+ return PREVIEW_HOST_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
2141
1868
  }
2142
- function parseSearchPublicPath(pathname, dictionary = emptySearchUrlDictionary()) {
2143
- const raw = pathname.split(/[?#]/)[0] ?? "";
2144
- let segments = raw.replace(/^\//, "").split("/").filter(Boolean);
2145
- if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);
2146
- if (segments.some((segment) => segment.includes("."))) return null;
2147
- if (segments.some((segment) => segment.toLowerCase().startsWith("id-"))) {
2148
- return null;
2149
- }
2150
- const filters = {};
2151
- const locationParts = [];
2152
- const propertyTypes = [];
2153
- const propertyFeatures = [];
2154
- const buildingAmenities = [];
2155
- for (const segment of segments) {
2156
- const lower = segment.toLowerCase();
2157
- const listingType = matchOptionId(
2158
- segment,
2159
- dictionary.listingTypes,
2160
- LISTING_TYPE_ALIASES
2161
- );
2162
- if (listingType && !filters.listingType) {
2163
- filters.listingType = listingType;
2164
- continue;
2165
- }
2166
- const propertyType = matchOptionId(
2167
- segment,
2168
- dictionary.propertyTypes,
2169
- PROPERTY_TYPE_SLUG_ALIASES
1869
+ function stripPort(host) {
1870
+ return host.trim().toLowerCase().split(":")[0] ?? "";
1871
+ }
1872
+ async function resolvePublicSiteId(options) {
1873
+ const fallback = options.fallback?.trim() ?? "";
1874
+ const host = options.host ? stripPort(options.host) : "";
1875
+ if (host && !isStudioPreviewHost(host)) {
1876
+ const site = await getSite({
1877
+ domain: host,
1878
+ baseUrl: options.baseUrl,
1879
+ fetch: options.fetch,
1880
+ publishableKey: options.publishableKey
1881
+ });
1882
+ if (site?.id) return site.id;
1883
+ throw new GaragemSdkError(
1884
+ `Garagem SDK: no published site found for domain "${host}"`,
1885
+ { status: 404, url: host }
2170
1886
  );
2171
- if (propertyType) {
2172
- propertyTypes.push(propertyType);
2173
- continue;
2174
- }
2175
- const bedrooms = lower.match(BEDROOMS);
2176
- if (bedrooms) {
2177
- filters.bedrooms = collapse(parseNumericList(bedrooms[1]));
2178
- continue;
2179
- }
2180
- const bathrooms = lower.match(BATHROOMS);
2181
- if (bathrooms) {
2182
- filters.bathrooms = collapse(parseNumericList(bathrooms[1]));
2183
- continue;
2184
- }
2185
- const suites = lower.match(SUITES);
2186
- if (suites) {
2187
- filters.suites = collapse(parseNumericList(suites[1]));
2188
- continue;
2189
- }
2190
- const parking = lower.match(PARKING);
2191
- if (parking) {
2192
- filters.parkingSpots = collapse(parseNumericList(parking[1]));
2193
- continue;
2194
- }
2195
- const price = lower.match(PRICE);
2196
- if (price) {
2197
- filters.price = { min: Number(price[1]), max: Number(price[2]) };
2198
- continue;
2199
- }
2200
- const area = lower.match(AREA);
2201
- if (area) {
2202
- filters.area = { min: Number(area[1]), max: Number(area[2]) };
2203
- continue;
2204
- }
2205
- const featureId = matchOptionId(segment, dictionary.propertyFeatures);
2206
- if (featureId) {
2207
- propertyFeatures.push(featureId);
2208
- continue;
1887
+ }
1888
+ if (fallback) return fallback;
1889
+ throw new GaragemSdkError(
1890
+ "Garagem SDK: could not resolve a site id (no host match and no fallback)",
1891
+ { status: 404, url: host || "fallback" }
1892
+ );
1893
+ }
1894
+
1895
+ // src/leads.ts
1896
+ function browserHost() {
1897
+ if (typeof window === "undefined") return "";
1898
+ return window.location.host;
1899
+ }
1900
+ async function resolveLeadSiteId(input) {
1901
+ try {
1902
+ return await coerceSiteId(input.siteId);
1903
+ } catch (error) {
1904
+ const host = browserHost();
1905
+ if (!host) throw error;
1906
+ return resolvePublicSiteId({
1907
+ host,
1908
+ baseUrl: input.baseUrl,
1909
+ fetch: input.fetch,
1910
+ publishableKey: input.publishableKey
1911
+ });
1912
+ }
1913
+ }
1914
+ var LeadSubmitError = class extends Error {
1915
+ code;
1916
+ status;
1917
+ retryAfterSeconds;
1918
+ /** Seconds to wait. Same value as `retryAfterSeconds`; `null` when unset. */
1919
+ retryAfter;
1920
+ constructor(message, info) {
1921
+ super(message);
1922
+ this.name = "LeadSubmitError";
1923
+ this.code = info.code;
1924
+ if (info.status != null) this.status = info.status;
1925
+ if (info.retryAfterSeconds != null) {
1926
+ this.retryAfterSeconds = info.retryAfterSeconds;
2209
1927
  }
2210
- const amenityId = matchOptionId(segment, dictionary.buildingAmenities);
2211
- if (amenityId) {
2212
- buildingAmenities.push(amenityId);
2213
- continue;
1928
+ this.retryAfter = info.retryAfterSeconds ?? null;
1929
+ }
1930
+ };
1931
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1932
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1933
+ var NAME_RE = /^[^\d\s]{2,}.*$/;
1934
+ var MESSAGE_MAX = 2e3;
1935
+ function isValidEmail(value) {
1936
+ return EMAIL_RE.test(value.trim());
1937
+ }
1938
+ function isValidName(value) {
1939
+ const name = value.trim();
1940
+ return name.length <= 200 && NAME_RE.test(name);
1941
+ }
1942
+ var CONTACT_FIELDS = [
1943
+ { id: "name", required: true },
1944
+ { id: "email", required: false },
1945
+ { id: "phone", required: false },
1946
+ { id: "message", required: false }
1947
+ ];
1948
+ function studioDefaultLeadUi() {
1949
+ return {
1950
+ defaultVariant: "visit",
1951
+ timeZone: "America/Sao_Paulo",
1952
+ variants: {
1953
+ visit: {
1954
+ ctaLabel: "Agendar visita",
1955
+ requireDateTime: true,
1956
+ schedule: STUDIO_DEFAULT_VISIT_SCHEDULE,
1957
+ fields: CONTACT_FIELDS
1958
+ },
1959
+ contact: {
1960
+ ctaLabel: "Fale conosco",
1961
+ requireDateTime: false,
1962
+ whatsappPhone: null,
1963
+ fields: CONTACT_FIELDS
1964
+ }
2214
1965
  }
2215
- locationParts.push(segment);
1966
+ };
1967
+ }
1968
+ async function getLeadUi(options) {
1969
+ const siteId = await resolveLeadSiteId(options);
1970
+ const url = `${normalizeBaseUrl(options.baseUrl)}/api/sites/${encodeURIComponent(siteId)}/leads/ui`;
1971
+ return callJson(
1972
+ url,
1973
+ {
1974
+ method: "GET",
1975
+ headers: { Accept: "application/json" },
1976
+ next: options.next
1977
+ },
1978
+ options.fetch ?? fetch,
1979
+ options.publishableKey
1980
+ );
1981
+ }
1982
+ function assertListingId(listingId) {
1983
+ if (!UUID_RE.test(listingId.trim())) {
1984
+ throw new LeadSubmitError(
1985
+ "Garagem SDK: listingId must be the listing UUID, not a path or code.",
1986
+ { code: "invalid_listing_id" }
1987
+ );
2216
1988
  }
2217
- if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];
2218
- else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;
2219
- if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;
2220
- if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;
2221
- const location = locationFromPathLeftovers(locationParts);
2222
- if (location) filters.location = location;
2223
- return filters;
2224
1989
  }
2225
- var PATH_STREET_PREFIX = /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;
2226
- function locationFromPathLeftovers(parts) {
2227
- if (parts.length === 0) return void 0;
2228
- if (parts.length === 1) {
2229
- const value = parts[0];
2230
- if (PATH_STREET_PREFIX.test(value)) return { street: value };
2231
- if (/^[a-z]{2}$/i.test(value)) return { state: value };
2232
- return { neighborhood: value };
1990
+ function normalizeContact(input) {
1991
+ const name = input.name.trim();
1992
+ if (name.length < 2 || name.length > 200) {
1993
+ throw new LeadSubmitError("Garagem SDK: name is required.", {
1994
+ code: "invalid_contact"
1995
+ });
1996
+ }
1997
+ const email = input.email?.trim() || void 0;
1998
+ const phone = input.phone?.trim() || void 0;
1999
+ if (!email && !phone) {
2000
+ throw new LeadSubmitError("Garagem SDK: email and/or phone is required.", {
2001
+ code: "invalid_contact"
2002
+ });
2003
+ }
2004
+ if (email && !EMAIL_RE.test(email)) {
2005
+ throw new LeadSubmitError("Garagem SDK: email is invalid.", {
2006
+ code: "invalid_contact"
2007
+ });
2008
+ }
2009
+ let normalizedPhone;
2010
+ if (phone) {
2011
+ const e164 = toE164(phone);
2012
+ if (!e164 || !isValidPhone(e164) || e164.length > 40) {
2013
+ throw new LeadSubmitError("Garagem SDK: phone is invalid.", {
2014
+ code: "invalid_contact"
2015
+ });
2016
+ }
2017
+ normalizedPhone = e164;
2018
+ }
2019
+ const message = input.message?.trim() || void 0;
2020
+ if (message && message.length > MESSAGE_MAX) {
2021
+ throw new LeadSubmitError("Garagem SDK: message is too long.", {
2022
+ code: "invalid_contact"
2023
+ });
2233
2024
  }
2234
- const [state, city, neighborhood, street] = parts;
2235
2025
  return {
2236
- ...state ? { state } : {},
2237
- ...city ? { city } : {},
2238
- ...neighborhood ? { neighborhood } : {},
2239
- ...street ? { street } : {}
2026
+ name,
2027
+ ...email ? { email } : {},
2028
+ ...normalizedPhone ? { phone: normalizedPhone } : {},
2029
+ ...message ? { message } : {}
2240
2030
  };
2241
2031
  }
2242
-
2243
- // ../search-url/applied-query.ts
2244
- var SORT_SET = new Set(SORT_URL_TOKENS);
2245
- function isSortToken(value) {
2246
- return SORT_SET.has(value);
2247
- }
2248
- function normalizeAppliedSearchQuery(query) {
2249
- if (query.loc && query.loc.length > 0) {
2250
- const { query: _query, ...rest } = query;
2251
- return rest;
2032
+ function normalizeSdkBusinessType(value) {
2033
+ if (!value) return void 0;
2034
+ const normalized = value.trim().toLowerCase();
2035
+ if (normalized === "rent" || normalized === "rental" || normalized === "aluguel") {
2036
+ return "rent";
2252
2037
  }
2253
- return query;
2038
+ if (normalized === "sale" || normalized === "venda") return "sale";
2039
+ return void 0;
2254
2040
  }
2255
- function parseAppliedSearchQuery(search) {
2256
- const params = search instanceof URLSearchParams ? search : new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
2257
- const result = {};
2258
- const pageRaw = params.get("page");
2259
- if (pageRaw) {
2260
- const page = Number.parseInt(pageRaw, 10);
2261
- if (Number.isFinite(page) && page > 1) {
2262
- result.page = Math.min(page, MAX_PAGE);
2263
- }
2041
+ var ADDRESS_REJECTIONS = /* @__PURE__ */ new Set([
2042
+ "missing_postal_code",
2043
+ "ungeocoded_address"
2044
+ ]);
2045
+ async function rejectedLeadError(response) {
2046
+ if (response.status !== 400 && response.status !== 409) return null;
2047
+ const parsed = parseSdkErrorBody(await response.text().catch(() => ""));
2048
+ if (response.status === 409 || parsed.reason === "duplicate_property") {
2049
+ return new LeadSubmitError(
2050
+ parsed.summary || "Garagem SDK: property already registered.",
2051
+ { code: "duplicate_property", status: response.status }
2052
+ );
2264
2053
  }
2265
- const sort = params.get("ordenar");
2266
- if (sort && isSortToken(sort)) result.sort = sort;
2267
- const q = params.get("q")?.trim();
2268
- if (q) result.query = q;
2269
- const loc = params.getAll("loc").map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
2270
- if (loc.length > 0) result.loc = loc;
2271
- return normalizeAppliedSearchQuery(result);
2054
+ if (parsed.reason && ADDRESS_REJECTIONS.has(parsed.reason)) {
2055
+ return new LeadSubmitError(`Garagem SDK: ${parsed.reason}.`, {
2056
+ code: "invalid_address",
2057
+ status: 400
2058
+ });
2059
+ }
2060
+ return null;
2272
2061
  }
2273
- var APPLIED_QUERY_KEYS = ["page", "ordenar", "q", "loc"];
2274
- function serializeAppliedSearchQuery(query) {
2275
- const normalized = normalizeAppliedSearchQuery(query);
2276
- const params = new URLSearchParams();
2277
- if (normalized.page !== void 0 && normalized.page > 1) {
2278
- params.set("page", String(Math.min(normalized.page, MAX_PAGE)));
2062
+ async function postSiteLead(input) {
2063
+ const siteId = await resolveLeadSiteId(input);
2064
+ const base = normalizeBaseUrl(input.baseUrl);
2065
+ const url = `${base}/api/webhooks/sites/${encodeURIComponent(siteId)}/leads`;
2066
+ const f = input.fetch ?? fetch;
2067
+ let response;
2068
+ try {
2069
+ response = await f(url, {
2070
+ method: "POST",
2071
+ headers: {
2072
+ Accept: "application/json",
2073
+ "Content-Type": "application/json",
2074
+ ...publishableKeyHeaders(input.publishableKey)
2075
+ },
2076
+ body: JSON.stringify(input.body)
2077
+ });
2078
+ } catch (error) {
2079
+ throw new LeadSubmitError(
2080
+ error instanceof Error ? error.message : "Garagem SDK: network error.",
2081
+ { code: "network" }
2082
+ );
2279
2083
  }
2280
- if (normalized.sort && isSortToken(normalized.sort)) {
2281
- params.set("ordenar", normalized.sort);
2084
+ if (response.status === 202) {
2085
+ const data = await response.json().catch(() => ({}));
2086
+ const id = typeof data.id === "string" && data.id ? data.id : "";
2087
+ return { ok: true, status: 202, id };
2282
2088
  }
2283
- const text2 = normalized.query?.trim();
2284
- if (text2) params.set("q", text2);
2285
- for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {
2286
- const trimmed = value.trim();
2287
- if (trimmed) params.append("loc", trimmed);
2089
+ if (response.status === 401) {
2090
+ throw new LeadSubmitError("Garagem SDK: invalid publishable key.", {
2091
+ code: "unauthorized",
2092
+ status: 401
2093
+ });
2288
2094
  }
2289
- return params;
2290
- }
2291
- function mergeAppliedSearchQueryIntoSearch(existing, query) {
2292
- const params = existing instanceof URLSearchParams ? new URLSearchParams(existing) : new URLSearchParams(
2293
- existing.startsWith("?") ? existing.slice(1) : existing
2294
- );
2295
- for (const key of APPLIED_QUERY_KEYS) {
2296
- params.delete(key);
2095
+ if (response.status === 429) {
2096
+ const text2 = await response.text().catch(() => "");
2097
+ const parsed = parseSdkErrorBody(text2);
2098
+ const retryAfter = retryAfterFromResponse(
2099
+ response,
2100
+ parsed.retryAfterSeconds
2101
+ );
2102
+ throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
2103
+ code: "rate_limited",
2104
+ status: 429,
2105
+ ...retryAfter != null ? { retryAfterSeconds: retryAfter } : {}
2106
+ });
2297
2107
  }
2298
- const serialized = serializeAppliedSearchQuery(query);
2299
- serialized.forEach((value, key) => {
2300
- if (key === "loc") {
2301
- params.append("loc", value);
2302
- } else {
2303
- params.set(key, value);
2304
- }
2305
- });
2306
- return params;
2108
+ if (response.status === 404) {
2109
+ throw new LeadSubmitError("Garagem SDK: listing or site not found.", {
2110
+ code: "not_found",
2111
+ status: 404
2112
+ });
2113
+ }
2114
+ const rejected = await rejectedLeadError(response);
2115
+ if (rejected) throw rejected;
2116
+ throw new LeadSubmitError(
2117
+ `Garagem SDK: lead submit failed (${response.status}).`,
2118
+ { code: "http", status: response.status }
2119
+ );
2307
2120
  }
2308
- function reduceAppliedSearchQuery(prev, change) {
2309
- switch (change.type) {
2310
- case "sort": {
2311
- const next = { ...prev };
2312
- delete next.page;
2313
- if (change.sort) next.sort = change.sort;
2314
- else delete next.sort;
2315
- return normalizeAppliedSearchQuery(next);
2316
- }
2317
- case "applyFilters": {
2318
- const next = { ...prev };
2319
- delete next.page;
2320
- return normalizeAppliedSearchQuery(next);
2321
- }
2322
- case "query": {
2323
- const next = { ...prev };
2324
- delete next.page;
2325
- const trimmed = change.query.trim();
2326
- if (trimmed) {
2327
- next.query = trimmed;
2328
- delete next.loc;
2329
- } else {
2330
- delete next.query;
2331
- }
2332
- return normalizeAppliedSearchQuery(next);
2333
- }
2334
- case "loc": {
2335
- const next = { ...prev };
2336
- delete next.page;
2337
- delete next.query;
2338
- const loc = change.loc.map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
2339
- if (loc.length > 0) next.loc = loc;
2340
- else delete next.loc;
2341
- return normalizeAppliedSearchQuery(next);
2342
- }
2343
- case "page": {
2344
- const next = { ...prev };
2345
- if (change.page <= 1) delete next.page;
2346
- else next.page = Math.min(change.page, MAX_PAGE);
2347
- return normalizeAppliedSearchQuery(next);
2348
- }
2349
- default: {
2350
- const _exhaustive = change;
2351
- return _exhaustive;
2121
+ function leadPostContext(input) {
2122
+ assertListingId(input.listingId);
2123
+ const businessType = normalizeSdkBusinessType(input.businessType) ?? normalizeSdkBusinessType(input.listingType);
2124
+ return {
2125
+ listingId: input.listingId.trim(),
2126
+ contact: normalizeContact(input),
2127
+ extras: {
2128
+ ...input.visitorId ? { visitorId: input.visitorId } : {},
2129
+ ...input.brokerRef ? { brokerRef: input.brokerRef } : {},
2130
+ ...input.referrer ? { referrer: input.referrer } : {},
2131
+ ...businessType ? { businessType } : {},
2132
+ ...input.listingType ? { listingType: input.listingType } : {}
2352
2133
  }
2134
+ };
2135
+ }
2136
+ async function submitVisitLead(input) {
2137
+ const prepared = leadPostContext(input);
2138
+ const schedule = input.schedule ?? STUDIO_DEFAULT_VISIT_SCHEDULE;
2139
+ const visitDate = normalizeVisitDate(input.visitDate, schedule.timeZone);
2140
+ const visitTime = normalizeVisitTime(input.visitTime);
2141
+ if (!visitDate || !visitTime || !isVisitSlotAllowed(schedule, visitDate, visitTime)) {
2142
+ throw new LeadSubmitError(
2143
+ "Garagem SDK: visitDate/visitTime is outside the published schedule.",
2144
+ { code: "invalid_slot" }
2145
+ );
2353
2146
  }
2147
+ const result = await postSiteLead({
2148
+ siteId: input.siteId,
2149
+ baseUrl: input.baseUrl,
2150
+ fetch: input.fetch,
2151
+ publishableKey: input.publishableKey,
2152
+ body: {
2153
+ source: "site-sdk",
2154
+ leadType: "visit",
2155
+ ...prepared.contact,
2156
+ propertyId: prepared.listingId,
2157
+ listingId: prepared.listingId,
2158
+ visitDate,
2159
+ visitTime,
2160
+ ...prepared.extras
2161
+ }
2162
+ });
2163
+ trackLeadGenerated("visit", prepared.listingId);
2164
+ return result;
2354
2165
  }
2355
- function composeSearchPublicHref(pathname, query, existingSearch) {
2356
- const params = existingSearch ? mergeAppliedSearchQueryIntoSearch(existingSearch, query) : serializeAppliedSearchQuery(query);
2357
- const qs = params.toString();
2358
- return qs ? `${pathname}?${qs}` : pathname;
2166
+ async function submitContactLead(input) {
2167
+ const prepared = leadPostContext(input);
2168
+ const result = await postSiteLead({
2169
+ siteId: input.siteId,
2170
+ baseUrl: input.baseUrl,
2171
+ fetch: input.fetch,
2172
+ publishableKey: input.publishableKey,
2173
+ body: {
2174
+ source: "site-sdk",
2175
+ leadType: "contact",
2176
+ ...prepared.contact,
2177
+ propertyId: prepared.listingId,
2178
+ listingId: prepared.listingId,
2179
+ ...prepared.extras
2180
+ }
2181
+ });
2182
+ trackLeadGenerated("contact", prepared.listingId);
2183
+ return result;
2359
2184
  }
2360
2185
 
2361
- // src/applied-query.ts
2362
- function parseAppliedSearchQuery2(search) {
2363
- return parseAppliedSearchQuery(search);
2364
- }
2365
- function serializeAppliedSearchQuery2(query) {
2366
- return serializeAppliedSearchQuery(query);
2367
- }
2368
- function mergeAppliedSearchQueryIntoSearch2(existing, query) {
2369
- return mergeAppliedSearchQueryIntoSearch(existing, query);
2370
- }
2371
- function reduceAppliedSearchQuery2(prev, change) {
2372
- return reduceAppliedSearchQuery(prev, change);
2186
+ // src/seller-lead.ts
2187
+ function text(value) {
2188
+ return typeof value === "string" ? value.trim() : "";
2373
2189
  }
2374
- function composeSearchPublicHref2(pathname, query, existingSearch) {
2375
- return composeSearchPublicHref(pathname, query, existingSearch);
2190
+ function inRange(value, min, max) {
2191
+ return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
2376
2192
  }
2377
-
2378
- // src/loc-params.ts
2379
- function pathLocationToFilterInput(location) {
2380
- if (!location || typeof location !== "object") return null;
2381
- const { state, city, neighborhood, street } = location;
2382
- const levels = [];
2383
- if (state) levels.push(state);
2384
- if (city) levels.push(city);
2385
- if (neighborhood) levels.push(neighborhood);
2386
- if (street) levels.push(street);
2387
- if (levels.length === 0) return null;
2388
- if (levels.length === 1) {
2389
- if (state) return { type: "state", value: state };
2390
- if (city) return { type: "city", value: city };
2391
- if (neighborhood) return { type: "neighborhood", value: neighborhood };
2392
- if (street) return { type: "street", value: street };
2193
+ function sellerAddressErrors(address) {
2194
+ const errors = {};
2195
+ if (!address || !text(address.fullAddress)) {
2196
+ errors.fullAddress = "Informe o endere\xE7o do im\xF3vel.";
2197
+ } else if (!inRange(address.latitude, -90, 90) || !inRange(address.longitude, -180, 180) || !text(address.street) || !text(address.city) || !text(address.neighborhood) || !/^[A-Za-z]{2}$/.test(text(address.state))) {
2198
+ errors.fullAddress = "Selecione o endere\xE7o em uma das sugest\xF5es.";
2393
2199
  }
2394
- return { type: "path", value: levels.join("/") };
2395
- }
2396
-
2397
- // src/path.ts
2398
- function composeSearchPublicPath2(filters, dictionary) {
2399
- return dictionary ? composeSearchPublicPath(filters, dictionary) : composeSearchPublicPath(filters);
2400
- }
2401
- function parseSearchPublicPath2(pathname, dictionary) {
2402
- return dictionary ? parseSearchPublicPath(pathname, dictionary) : parseSearchPublicPath(pathname);
2403
- }
2404
- function pathFiltersToQueryFilters(pathFilters) {
2405
- const result = {};
2406
- if (pathFilters.listingType !== void 0) {
2407
- result.listing_type = pathFilters.listingType;
2200
+ if (!address?.noNumber && !text(address?.number)) {
2201
+ errors.number = "Informe o n\xFAmero ou marque sem n\xFAmero.";
2408
2202
  }
2409
- if (pathFilters.propertyType !== void 0) {
2410
- result.property_type = pathFilters.propertyType;
2203
+ if (!address?.noBlocoTorre && !text(address?.blocoTorre)) {
2204
+ errors.blocoTorre = "Informe o bloco/torre ou marque que n\xE3o tem.";
2411
2205
  }
2412
- if (pathFilters.bedrooms !== void 0) {
2413
- result.property_bedrooms = pathFilters.bedrooms;
2206
+ if (!address?.noUnidade && !text(address?.unidade)) {
2207
+ errors.unidade = "Informe a unidade ou marque que n\xE3o tem.";
2414
2208
  }
2415
- if (pathFilters.bathrooms !== void 0) {
2416
- result.property_bathrooms = pathFilters.bathrooms;
2209
+ if (text(address?.postalCode).replace(/\D/g, "").length !== 8) {
2210
+ errors.postalCode = "Informe um CEP com 8 d\xEDgitos.";
2417
2211
  }
2418
- if (pathFilters.suites !== void 0) {
2419
- result.property_suites = pathFilters.suites;
2212
+ return errors;
2213
+ }
2214
+ var SELLER_LEAD_PHOTO_MAX_BYTES = 10 * 1024 * 1024;
2215
+ var SELLER_LEAD_PHOTO_MAX_COUNT = 30;
2216
+ var SELLER_LEAD_PHOTO_TYPES = [
2217
+ "image/jpeg",
2218
+ "image/png",
2219
+ "image/webp"
2220
+ ];
2221
+ async function uploadSellerLeadPhoto(input) {
2222
+ const { file } = input;
2223
+ if (!SELLER_LEAD_PHOTO_TYPES.includes(file.type)) {
2224
+ throw new LeadSubmitError("Garagem SDK: photo must be JPG, PNG or WEBP.", {
2225
+ code: "invalid_photo"
2226
+ });
2420
2227
  }
2421
- if (pathFilters.parkingSpots !== void 0) {
2422
- result.property_parking_spots = pathFilters.parkingSpots;
2228
+ if (file.size <= 0) {
2229
+ throw new LeadSubmitError("Garagem SDK: photo is empty.", {
2230
+ code: "invalid_photo"
2231
+ });
2423
2232
  }
2424
- if (pathFilters.price !== void 0) {
2425
- result.price = pathFilters.price;
2233
+ if (file.size > SELLER_LEAD_PHOTO_MAX_BYTES) {
2234
+ throw new LeadSubmitError("Garagem SDK: photo is larger than 10MB.", {
2235
+ code: "invalid_photo"
2236
+ });
2426
2237
  }
2427
- if (pathFilters.area !== void 0) {
2428
- result.property_area_total = pathFilters.area;
2238
+ const siteId = await resolveLeadSiteId(input);
2239
+ const url = `${normalizeBaseUrl(input.baseUrl)}/api/webhooks/sites/${encodeURIComponent(siteId)}/photos`;
2240
+ const form = new FormData();
2241
+ form.append("file", file);
2242
+ if (file.name) form.append("fileName", file.name);
2243
+ let response;
2244
+ try {
2245
+ response = await (input.fetch ?? fetch)(url, {
2246
+ method: "POST",
2247
+ body: form
2248
+ });
2249
+ } catch (error) {
2250
+ throw new LeadSubmitError(
2251
+ error instanceof Error ? error.message : "Garagem SDK: network error.",
2252
+ { code: "network" }
2253
+ );
2429
2254
  }
2430
- if (pathFilters.propertyFeatures !== void 0) {
2431
- result.propertyFeatures = pathFilters.propertyFeatures;
2255
+ if (response.status === 404) {
2256
+ throw new LeadSubmitError("Garagem SDK: site not found.", {
2257
+ code: "not_found",
2258
+ status: 404
2259
+ });
2432
2260
  }
2433
- if (pathFilters.buildingAmenities !== void 0) {
2434
- result.buildingAmenities = pathFilters.buildingAmenities;
2261
+ const data = await response.json().catch(() => ({}));
2262
+ if (!response.ok || typeof data.url !== "string" || !data.url) {
2263
+ throw new LeadSubmitError(
2264
+ `Garagem SDK: photo upload failed (${response.status}).`,
2265
+ {
2266
+ code: response.status === 400 ? "invalid_photo" : "http",
2267
+ status: response.status
2268
+ }
2269
+ );
2435
2270
  }
2436
- return result;
2271
+ return data.url;
2437
2272
  }
2438
-
2439
- // src/search-engine.ts
2440
- var PATH_FILTER_IDS = {
2441
- listing_type: "listingType",
2442
- property_type: "propertyType",
2443
- property_bedrooms: "bedrooms",
2444
- property_bathrooms: "bathrooms",
2445
- property_suites: "suites",
2446
- property_parking_spots: "parkingSpots",
2447
- price: "price",
2448
- property_area_total: "area",
2449
- propertyFeatures: "propertyFeatures",
2450
- buildingAmenities: "buildingAmenities"
2451
- };
2452
- var FORBIDDEN_SEARCH_QUERY_KEYS = [
2453
- "tipo",
2454
- "quartos",
2455
- "tipo-imovel",
2456
- "banheiros",
2457
- "vagas"
2458
- ];
2459
- var SEARCH_SORT_RELEVANCE = {
2460
- id: "",
2461
- label: "Mais relevantes"
2273
+ var STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG = {
2274
+ disabledDays: [0, 6],
2275
+ weekdayTimeSlots: [
2276
+ "09:00",
2277
+ "10:00",
2278
+ "11:00",
2279
+ "14:00",
2280
+ "15:00",
2281
+ "16:00",
2282
+ "17:00"
2283
+ ],
2284
+ weekendTimeSlots: ["10:00", "11:00", "14:00", "15:00", "16:00"]
2462
2285
  };
2463
- function searchSortOptions(sorts) {
2464
- const fromApi = (sorts || []).filter((sort) => sort.id);
2465
- return [
2466
- { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },
2467
- ...fromApi
2468
- ];
2469
- }
2470
- var TOOLBAR_PRIMARY_FILTER_IDS = [
2471
- "price",
2472
- "property_bedrooms"
2473
- ];
2474
- var HIDDEN_FILTER_IDS = /* @__PURE__ */ new Set(["property_suites"]);
2475
- function toFiniteNumber(value) {
2476
- if (value === "" || value == null) return void 0;
2477
- const n = Number(value);
2478
- return Number.isFinite(n) ? n : void 0;
2479
- }
2480
- function pathnameOnly(pathname) {
2481
- return String(pathname || "").split(/[?#]/)[0] || "/";
2482
- }
2483
- function isListingDetailPath(pathname) {
2484
- const parts = pathnameOnly(pathname).split("/").filter(Boolean);
2485
- const last = parts[parts.length - 1] || "";
2486
- return last.toLowerCase().startsWith("id-");
2286
+ function sellerPhotoSchedule(config = STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG) {
2287
+ const weekdayTimeSlots = [...config.weekdayTimeSlots].sort();
2288
+ const weekendTimeSlots = [...config.weekendTimeSlots].sort();
2289
+ const hours = (slots) => slots.length > 0 ? { start: slots[0], end: slots[slots.length - 1] } : null;
2290
+ return {
2291
+ timeZone: VISIT_TIME_ZONE,
2292
+ saturday: !config.disabledDays.includes(6),
2293
+ sunday: !config.disabledDays.includes(0),
2294
+ weekday: hours(weekdayTimeSlots) ?? { start: "09:00", end: "09:00" },
2295
+ weekend: hours(weekendTimeSlots),
2296
+ minHoursAhead: 2,
2297
+ disabledDays: [...config.disabledDays],
2298
+ weekdayTimeSlots,
2299
+ weekendTimeSlots,
2300
+ timeSlots: Array.from(
2301
+ /* @__PURE__ */ new Set([...weekdayTimeSlots, ...weekendTimeSlots])
2302
+ ).sort()
2303
+ };
2487
2304
  }
2488
- function readPublicSearch(pathname, search, dictionary) {
2489
- const pathFilters = parseSearchPublicPath2(pathnameOnly(pathname), dictionary) || {};
2490
- const applied = parseAppliedSearchQuery2(search || "");
2491
- return { pathFilters, applied };
2305
+ function contactError(message) {
2306
+ return new LeadSubmitError(`Garagem SDK: ${message}`, {
2307
+ code: "invalid_contact"
2308
+ });
2492
2309
  }
2493
- function lookupDisplay(table, slug) {
2494
- if (!slug || !table) return slug;
2495
- return table[slug] || table[String(slug).toLowerCase()] || slug;
2310
+ function normalizeOwner(owner) {
2311
+ const name = text(owner?.name);
2312
+ const email = text(owner?.email);
2313
+ if (!isValidName(name)) throw contactError("owner name is invalid.");
2314
+ if (!isValidEmail(email)) throw contactError("owner email is invalid.");
2315
+ const phone = toE164(text(owner?.phone));
2316
+ if (!phone || !isValidPhone(phone) || phone.length > 40) {
2317
+ throw contactError("owner phone is invalid.");
2318
+ }
2319
+ return { name, email, phone };
2496
2320
  }
2497
- function displayPathLocation(location, values) {
2498
- if (!location) return null;
2499
- const table = values || {};
2321
+ function normalizeAddress(address) {
2322
+ const errors = sellerAddressErrors(address);
2323
+ const first = Object.values(errors)[0];
2324
+ if (first) {
2325
+ throw new LeadSubmitError(`Garagem SDK: ${first}`, {
2326
+ code: "invalid_address"
2327
+ });
2328
+ }
2329
+ const optional = (value) => text(value) ? { value: text(value) } : null;
2330
+ const number = address.noNumber ? null : optional(address.number);
2331
+ const bloco = address.noBlocoTorre ? null : optional(address.blocoTorre);
2332
+ const unidade = address.noUnidade ? null : optional(address.unidade);
2500
2333
  return {
2501
- state: lookupDisplay(table.states, location.state),
2502
- city: lookupDisplay(table.cities, location.city),
2503
- neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),
2504
- street: lookupDisplay(table.streets, location.street)
2334
+ fullAddress: text(address.fullAddress),
2335
+ street: text(address.street),
2336
+ ...number ? { number: number.value } : {},
2337
+ neighborhood: text(address.neighborhood),
2338
+ city: text(address.city),
2339
+ state: text(address.state),
2340
+ postalCode: text(address.postalCode).replace(/\D/g, ""),
2341
+ country: text(address.country) || "BR",
2342
+ latitude: address.latitude,
2343
+ longitude: address.longitude,
2344
+ ...bloco ? { blocoTorre: bloco.value } : {},
2345
+ ...unidade ? { unidade: unidade.value } : {},
2346
+ noNumber: address.noNumber === true,
2347
+ noBlocoTorre: address.noBlocoTorre === true,
2348
+ noUnidade: address.noUnidade === true
2505
2349
  };
2506
2350
  }
2507
- function buildQueryListingsParams(pathFilters, applied, schema, locationValues) {
2508
- const filters = pathFiltersToQueryFilters(pathFilters || {});
2509
- const locations = [];
2510
- const displayed = displayPathLocation(pathFilters?.location, locationValues);
2511
- const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;
2512
- if (pathLoc) locations.push(pathLoc);
2513
- for (const value of applied?.loc || []) {
2514
- locations.push({ type: "loc", value });
2515
- }
2516
- const params = {
2517
- page: applied?.page || 1,
2518
- limit: schema?.defaultLimit || 12,
2519
- filters
2520
- };
2521
- if (applied?.sort) params.sort = applied.sort;
2522
- const hasLocation = locations.length > 0;
2523
- if (applied?.query && !hasLocation) params.q = applied.query;
2524
- if (hasLocation) params.location = locations;
2525
- return params;
2351
+ var COUNT_FIELDS = [
2352
+ "bedrooms",
2353
+ "bathrooms",
2354
+ "suites",
2355
+ "parkingSpaces"
2356
+ ];
2357
+ var AMOUNT_FIELDS = [
2358
+ "saleValue",
2359
+ "rentValue",
2360
+ "condoFee",
2361
+ "totalArea"
2362
+ ];
2363
+ function propertyError(message) {
2364
+ return new LeadSubmitError(`Garagem SDK: ${message}`, {
2365
+ code: "invalid_property"
2366
+ });
2526
2367
  }
2527
- function applyPathFilter(pathFilters, filterId, value) {
2528
- const next = { ...pathFilters || {} };
2529
- const key = PATH_FILTER_IDS[filterId];
2530
- if (!key) return next;
2531
- if (value === "" || value == null) {
2532
- delete next[key];
2533
- return next;
2368
+ function normalizeProperty(property) {
2369
+ if (!["sale", "rent", "both"].includes(property?.businessType)) {
2370
+ throw propertyError("businessType must be sale, rent or both.");
2534
2371
  }
2535
- if (key === "price" || key === "area") {
2536
- const range = value || {};
2537
- const parse = key === "price" ? parseGroupedInteger : toFiniteNumber;
2538
- const min = parse(range.min);
2539
- const max = parse(range.max);
2540
- if (min == null && max == null) {
2541
- delete next[key];
2542
- return next;
2372
+ for (const field of COUNT_FIELDS) {
2373
+ const value = property[field];
2374
+ if (value != null && (!Number.isInteger(value) || value < 0 || value > 999)) {
2375
+ throw propertyError(`${field} must be a whole number.`);
2543
2376
  }
2544
- next[key] = {
2545
- ...min != null ? { min } : {},
2546
- ...max != null ? { max } : {}
2547
- };
2548
- return next;
2549
- }
2550
- if (key === "propertyFeatures" || key === "buildingAmenities") {
2551
- const current = Array.isArray(next[key]) ? [...next[key]] : [];
2552
- const id = String(value);
2553
- const i = current.indexOf(id);
2554
- if (i >= 0) current.splice(i, 1);
2555
- else current.push(id);
2556
- if (current.length) next[key] = current;
2557
- else delete next[key];
2558
- return next;
2559
- }
2560
- if (key === "propertyType") {
2561
- const id = String(value);
2562
- const current = Array.isArray(next.propertyType) ? [...next.propertyType] : next.propertyType ? [String(next.propertyType)] : [];
2563
- const i = current.indexOf(id);
2564
- if (i >= 0) current.splice(i, 1);
2565
- else current.push(id);
2566
- if (current.length === 0) delete next.propertyType;
2567
- else if (current.length === 1) next.propertyType = current[0];
2568
- else next.propertyType = current;
2569
- return next;
2570
- }
2571
- if (key === "listingType") {
2572
- const id = String(value);
2573
- if (next.listingType === id) delete next.listingType;
2574
- else next.listingType = id;
2575
- return next;
2576
2377
  }
2577
- if (key === "bedrooms" || key === "bathrooms" || key === "suites" || key === "parkingSpots") {
2578
- const n = Number(value);
2579
- if (!Number.isFinite(n)) {
2580
- delete next[key];
2581
- return next;
2378
+ for (const field of AMOUNT_FIELDS) {
2379
+ const value = property[field];
2380
+ if (value != null && (!Number.isFinite(value) || value < 0 || value > 1e12)) {
2381
+ throw propertyError(`${field} must be a non-negative number.`);
2582
2382
  }
2583
- if (next[key] === n) delete next[key];
2584
- else next[key] = n;
2585
- return next;
2586
2383
  }
2587
- return next;
2588
- }
2589
- function pathFilterValue(pathFilters, filterId) {
2590
- const key = PATH_FILTER_IDS[filterId];
2591
- const value = pathFilters && key ? pathFilters[key] : void 0;
2592
- if (value == null) return "";
2593
- if (Array.isArray(value)) return value[0] != null ? String(value[0]) : "";
2594
- if (typeof value === "object") return "";
2595
- return String(value);
2384
+ const sale = property.businessType === "rent" ? void 0 : property.saleValue;
2385
+ const rent = property.businessType === "sale" ? void 0 : property.rentValue;
2386
+ const price = property.businessType === "rent" ? rent : sale;
2387
+ const counts = Object.fromEntries(
2388
+ COUNT_FIELDS.filter((field) => property[field] != null).map((field) => [
2389
+ field,
2390
+ property[field]
2391
+ ])
2392
+ );
2393
+ return {
2394
+ businessType: property.businessType,
2395
+ ...price != null ? { price } : {},
2396
+ ...property.businessType === "both" && rent != null ? { rentPrice: rent } : {},
2397
+ ...property.condoFee != null ? { condominiumFee: property.condoFee } : {},
2398
+ ...property.totalArea != null ? { totalArea: property.totalArea } : {},
2399
+ ...counts
2400
+ };
2596
2401
  }
2597
- function pathFilterHasOption(pathFilters, filterId, optionId) {
2598
- const key = PATH_FILTER_IDS[filterId];
2599
- const value = pathFilters && key ? pathFilters[key] : void 0;
2600
- if (value == null) return false;
2601
- if (Array.isArray(value)) return value.map(String).includes(optionId);
2602
- if (typeof value === "object") return false;
2603
- return String(value) === optionId;
2402
+ function normalizePhotos(photos) {
2403
+ if (!photos?.length) return void 0;
2404
+ if (photos.length > SELLER_LEAD_PHOTO_MAX_COUNT) {
2405
+ throw new LeadSubmitError("Garagem SDK: too many photos (max 30).", {
2406
+ code: "invalid_photo"
2407
+ });
2408
+ }
2409
+ return photos.map((url) => {
2410
+ const trimmed = url.trim();
2411
+ if (!trimmed.startsWith("https://")) {
2412
+ throw new LeadSubmitError("Garagem SDK: photo URL must be https.", {
2413
+ code: "invalid_photo"
2414
+ });
2415
+ }
2416
+ return trimmed;
2417
+ });
2604
2418
  }
2605
- function publicSearchHref(pathFilters, applied, dictionary, existingSearch) {
2606
- const pathname = composeSearchPublicPath2(pathFilters || {}, dictionary);
2607
- return composeSearchPublicHref2(pathname, applied || {}, existingSearch);
2419
+ function normalizePhotoSession(input) {
2420
+ if (!input.photoSession) return void 0;
2421
+ const schedule = input.photoSchedule ?? sellerPhotoSchedule();
2422
+ const date = normalizeVisitDate(input.photoSession.date, schedule.timeZone);
2423
+ const time = normalizeVisitTime(input.photoSession.time);
2424
+ if (!date || !time || !isVisitSlotAllowed(schedule, date, time)) {
2425
+ throw new LeadSubmitError(
2426
+ "Garagem SDK: photo session slot is outside the schedule.",
2427
+ { code: "invalid_slot" }
2428
+ );
2429
+ }
2430
+ return { date, time };
2608
2431
  }
2609
- function hrefForPathFilters(pathname, search, dictionary, nextPathFilters) {
2610
- const { applied } = readPublicSearch(pathname, search, dictionary);
2611
- const nextApplied = reduceAppliedSearchQuery2(applied, {
2612
- type: "applyFilters"
2432
+ async function submitSellerLead(input) {
2433
+ const owner = normalizeOwner(input.owner);
2434
+ const address = normalizeAddress(input.address);
2435
+ const property = normalizeProperty(input.property);
2436
+ const photos = normalizePhotos(input.photos);
2437
+ const photoScheduling = normalizePhotoSession(input);
2438
+ return postSiteLead({
2439
+ siteId: input.siteId,
2440
+ baseUrl: input.baseUrl,
2441
+ fetch: input.fetch,
2442
+ publishableKey: input.publishableKey,
2443
+ body: {
2444
+ source: "site-sdk",
2445
+ leadType: "seller_lead",
2446
+ ...owner,
2447
+ address,
2448
+ ...property,
2449
+ ...photos ? { photos } : {},
2450
+ ...photoScheduling ? { photoScheduling } : {},
2451
+ ...input.visitorId ? { visitorId: input.visitorId } : {},
2452
+ ...input.brokerRef ? { brokerRef: input.brokerRef } : {},
2453
+ ...input.referrer ? { referrer: input.referrer } : {}
2454
+ }
2613
2455
  });
2614
- return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);
2615
2456
  }
2616
- function hrefForAppliedChange(pathname, search, dictionary, change) {
2617
- const { pathFilters, applied } = readPublicSearch(
2618
- pathname,
2619
- search,
2620
- dictionary
2621
- );
2622
- let nextPath = pathFilters;
2623
- if (change && change.type === "query") {
2624
- nextPath = { ...pathFilters };
2625
- delete nextPath.location;
2457
+
2458
+ // src/amenity-labels.ts
2459
+ var LISTING_AMENITY_TITLES = {
2460
+ unit: "Comodidades",
2461
+ building: "Comodidades do condom\xEDnio"
2462
+ };
2463
+ var AMENITY_FALLBACK_LABELS = {
2464
+ // ==================== PROPERTY FEATURES ====================
2465
+ // Amenities
2466
+ arCondicionado: "Ar condicionado",
2467
+ banheira: "Banheira",
2468
+ carregadorEletrico: "Carregador el\xE9trico",
2469
+ churrasqueira: "Churrasqueira",
2470
+ chuveiroGas: "Chuveiro a g\xE1s",
2471
+ chuveiroEletrico: "Chuveiro el\xE9trico",
2472
+ energiaSolar: "Energia solar",
2473
+ fechaduraDigital: "Fechadura digital",
2474
+ fechaduraEletronica: "Fechadura eletr\xF4nica",
2475
+ geradorEletrico: "Gerador el\xE9trico",
2476
+ gesso: "Gesso",
2477
+ hidromassagem: "Hidromassagem",
2478
+ lareira: "Lareira",
2479
+ ofuro: "Ofur\xF4",
2480
+ spa: "Spa",
2481
+ painelSolar: "Painel solar",
2482
+ portaoEletronico: "Port\xE3o eletr\xF4nico",
2483
+ sistemaAlarme: "Sistema de alarme",
2484
+ homeTheater: "Home theater",
2485
+ adega: "Adega",
2486
+ split: "Split",
2487
+ arCentral: "Ar central",
2488
+ esperaSplit: "Espera para split",
2489
+ vistaMar: "Vista para o mar",
2490
+ vistaPanoramica: "Vista panor\xE2mica",
2491
+ aguaQuente: "\xC1gua quente",
2492
+ reformado: "Reformado",
2493
+ tvCabo: "TV a cabo",
2494
+ gradeado: "Gradeado",
2495
+ antenaParabolica: "Antena parab\xF3lica",
2496
+ aquecimento: "Aquecimento",
2497
+ aquecimentoEletrico: "Aquecimento el\xE9trico",
2498
+ aquecimentoCentral: "Aquecimento central",
2499
+ cercaEletrica: "Cerca el\xE9trica",
2500
+ monitoramento: "Monitoramento",
2501
+ vigiaInterno: "Vigia interno",
2502
+ vigiaExterno: "Vigia externo",
2503
+ alarme: "Alarme",
2504
+ agua: "\xC1gua",
2505
+ redeEsgoto: "Rede de esgoto",
2506
+ pavimentacao: "Pavimenta\xE7\xE3o",
2507
+ energiaEletrica: "Energia el\xE9trica",
2508
+ // Furniture
2509
+ mobiliado: "Mobiliado",
2510
+ armarioEmbutido: "Arm\xE1rio embutido",
2511
+ armarioEmbutidoQuarto: "Arm\xE1rio embutido quarto",
2512
+ armarioCozinha: "Arm\xE1rio cozinha",
2513
+ armarioBanheiro: "Arm\xE1rio banheiro",
2514
+ cozinhaPlanejada: "Cozinha planejada",
2515
+ fogao: "Fog\xE3o",
2516
+ fornoPizza: "Forno de pizza",
2517
+ freezer: "Freezer",
2518
+ dormitorioComArmario: "Dormit\xF3rio com arm\xE1rio",
2519
+ semiMobiliado: "Semi mobiliado",
2520
+ salaArmarios: "Sala com arm\xE1rios",
2521
+ // Structure
2522
+ piscina: "Piscina",
2523
+ piscinaAquecida: "Piscina aquecida",
2524
+ piscinaCoberta: "Piscina coberta",
2525
+ poco: "Po\xE7o",
2526
+ pocoArtesiano: "Po\xE7o artesiano",
2527
+ bar: "Bar",
2528
+ jardim: "Jardim",
2529
+ lago: "Lago",
2530
+ lavabo: "Lavabo",
2531
+ quintal: "Quintal",
2532
+ solarium: "Solarium",
2533
+ quartoServico: "Quarto de servi\xE7o",
2534
+ varanda: "Varanda",
2535
+ varandaFechadaVidro: "Varanda fechada com vidro",
2536
+ varandaGourmet: "Varanda gourmet",
2537
+ banheiroServico: "Banheiro de servi\xE7o",
2538
+ areaServico: "\xC1rea de servi\xE7o",
2539
+ cinema: "Cinema",
2540
+ closet: "Closet",
2541
+ cozinhaAmericana: "Cozinha americana",
2542
+ cozinhaGourmet: "Cozinha gourmet",
2543
+ despensa: "Despensa",
2544
+ escritorio: "Escrit\xF3rio",
2545
+ edicula: "Ed\xEDcula",
2546
+ horta: "Horta",
2547
+ sacada: "Sacada",
2548
+ salaJantar: "Sala de jantar",
2549
+ cozinha: "Cozinha",
2550
+ banheiroSocial: "Banheiro social",
2551
+ terraco: "Terra\xE7o",
2552
+ copa: "Copa",
2553
+ suiteMaster: "Su\xEDte master",
2554
+ wcEmpregada: "WC empregada",
2555
+ dependenciaEmpregada: "Depend\xEAncia de empregada",
2556
+ dependenciadeEmpregada: "Depend\xEAncia empregada",
2557
+ salaTv: "Sala de TV",
2558
+ copaCozinha: "Copa cozinha",
2559
+ sacadaComChurrasqueira: "Sacada com churrasqueira",
2560
+ hallPrivativo: "Hall privativo",
2561
+ estarIntimo: "Estar \xEDntimo",
2562
+ livingHall: "Living hall",
2563
+ piscinaInterna: "Piscina interna",
2564
+ deck: "Deck",
2565
+ jardimInverno: "Jardim de inverno",
2566
+ rouparia: "Rouparia",
2567
+ living: "Living",
2568
+ familyRoom: "Family room",
2569
+ salafitness: "Sala fitness",
2570
+ salaEstar: "Sala de estar",
2571
+ mezanino: "Mezanino",
2572
+ pisoElevado: "Piso elevado",
2573
+ entradaServicoIndependente: "Entrada de servi\xE7o independente",
2574
+ forro: "Forro",
2575
+ vitrine: "Vitrine",
2576
+ banheiroAuxiliar: "Banheiro auxiliar",
2577
+ gabinete: "Gabinete",
2578
+ quadraTenisPrivativa: "Quadra de t\xEAnis privativa",
2579
+ porao: "Por\xE3o",
2580
+ sotao: "S\xF3t\xE3o",
2581
+ patio: "P\xE1tio",
2582
+ canaletasNoRodape: "Canaletas no rodap\xE9",
2583
+ // Accessibility
2584
+ barraApoioVaso: "Barra de apoio vaso",
2585
+ barraApoioChuveiro: "Barra de apoio chuveiro",
2586
+ entradaSemDegrau: "Entrada sem degrau",
2587
+ rampasAcesso: "Rampas de acesso",
2588
+ vagaDeficientes: "Vaga para deficientes",
2589
+ // Flooring
2590
+ cimentoQueimado: "Cimento queimado",
2591
+ madeira: "Madeira",
2592
+ pisoFrio: "Piso frio",
2593
+ laminado: "Laminado",
2594
+ vinilico: "Vin\xEDlico",
2595
+ porcelanato: "Porcelanato",
2596
+ // ==================== BUILDING FEATURES ====================
2597
+ // Amenities
2598
+ elevador: "Elevador",
2599
+ bicicletario: "Biciclet\xE1rio",
2600
+ carregadorEletronico: "Carregador eletr\xF4nico",
2601
+ concierge: "Concierge",
2602
+ coworking: "Coworking",
2603
+ deposito: "Dep\xF3sito",
2604
+ lavanderia: "Lavanderia",
2605
+ petPlace: "Pet place",
2606
+ recebimentoEncomendas: "Recebimento de encomendas",
2607
+ salaReuniao: "Sala de reuni\xE3o",
2608
+ salaoFestas: "Sal\xE3o de festas",
2609
+ valet: "Valet",
2610
+ garagemCoberta: "Garagem coberta",
2611
+ elevadorServico: "Elevador de servi\xE7o",
2612
+ // Leisure
2613
+ academia: "Academia",
2614
+ campoFutebol: "Campo de futebol",
2615
+ espacoGourmet: "Espa\xE7o gourmet",
2616
+ piscinaInfantil: "Piscina infantil",
2617
+ pistaCaminhada: "Pista de caminhada",
2618
+ playground: "Playground",
2619
+ quadraPoliesportiva: "Quadra poliesportiva",
2620
+ quadraTenis: "Quadra de t\xEAnis",
2621
+ salaJogos: "Sala de jogos",
2622
+ salaVapor: "Sala de vapor",
2623
+ sauna: "Sauna",
2624
+ // Security
2625
+ circuitoTv: "Circuito fechado de TV",
2626
+ controleAcessoEletronico: "Controle de acesso eletr\xF4nico",
2627
+ interfone: "Interfone",
2628
+ portaria24h: "Portaria 24h",
2629
+ porteiroFisico: "Porteiro f\xEDsico",
2630
+ seguranca24h: "Seguran\xE7a 24h",
2631
+ segurancaPatrimonial: "Seguran\xE7a patrimonial",
2632
+ condominioFechado: "Condom\xEDnio fechado",
2633
+ // Accessibility
2634
+ banheiroAcessivel: "Banheiro acess\xEDvel",
2635
+ elevadorAcessivel: "Elevador acess\xEDvel",
2636
+ pisoTatil: "Piso t\xE1til",
2637
+ // ==================== CANONICAL HAS*/IS* KEYS ====================
2638
+ has24hConcierge: "Portaria 24h",
2639
+ has24hSecurity: "Seguran\xE7a 24h",
2640
+ hasAccessRamps: "Rampas de acesso",
2641
+ hasAccessibleBathroom: "Banheiro acess\xEDvel",
2642
+ hasAccessibleElevator: "Elevador acess\xEDvel",
2643
+ hasAirConditioning: "Ar condicionado",
2644
+ hasAlarmSystem: "Sistema de alarme",
2645
+ hasBalcony: "Varanda",
2646
+ hasBikeStorage: "Biciclet\xE1rio",
2647
+ hasBuiltInWardrobe: "Arm\xE1rio embutido",
2648
+ hasCCTV: "CFTV",
2649
+ hasCloset: "Closet",
2650
+ hasConcierge: "Portaria",
2651
+ hasControlledAccess: "Condom\xEDnio fechado",
2652
+ hasCoworking: "Coworking",
2653
+ hasDisabledParking: "Vaga para deficientes",
2654
+ hasElectricCharger: "Carregador eletr\xF4nico",
2655
+ hasElectronicGate: "Port\xE3o eletr\xF4nico",
2656
+ hasElevator: "Elevador",
2657
+ hasFireplace: "Lareira",
2658
+ hasGarden: "Jardim",
2659
+ hasGasShower: "Chuveiro a g\xE1s",
2660
+ hasGenerator: "Gerador",
2661
+ hasGourmetBalcony: "Varanda gourmet",
2662
+ hasGourmetKitchen: "Cozinha gourmet",
2663
+ hasGrill: "Churrasqueira",
2664
+ hasGuestParking: "Estacionamento para visitantes",
2665
+ hasGym: "Academia",
2666
+ hasHeating: "Aquecimento",
2667
+ hasHomeOffice: "Home office",
2668
+ hasIntercom: "Interfone",
2669
+ hasJacuzzi: "Hidromassagem",
2670
+ hasKidsPool: "Piscina infantil",
2671
+ hasLaundry: "Lavanderia",
2672
+ hasMeetingRoom: "Sala de reuni\xE3o",
2673
+ hasOffice: "Escrit\xF3rio",
2674
+ hasOpenKitchen: "Cozinha americana",
2675
+ hasPackageReceival: "Recebimento de encomendas",
2676
+ hasPantry: "Despensa",
2677
+ hasParkingGarage: "Garagem coberta",
2678
+ hasPartySaloon: "Sal\xE3o de festas",
2679
+ hasPetArea: "Pet place",
2680
+ hasPipedGas: "G\xE1s encanado",
2681
+ hasPlayground: "Playground",
2682
+ hasPowderRoom: "Lavabo",
2683
+ hasPrivatePool: "Piscina privativa",
2684
+ hasSauna: "Sauna",
2685
+ hasSecurity: "Seguran\xE7a",
2686
+ hasServiceArea: "\xC1rea de servi\xE7o",
2687
+ hasSolarPanel: "Painel solar",
2688
+ hasSpa: "Spa",
2689
+ hasSportsCourt: "Quadra de esportes",
2690
+ hasStepFreeEntrance: "Entrada sem degrau",
2691
+ hasStorage: "Dep\xF3sito",
2692
+ hasSwimmingPool: "Piscina",
2693
+ hasTennisCourt: "Quadra de t\xEAnis",
2694
+ hasValetParking: "Valet",
2695
+ homeOffice: "Home office",
2696
+ isPetFriendly: "Pet friendly",
2697
+ isFurnished: "Mobiliado",
2698
+ isPartiallyFurnished: "Semi-mobiliado",
2699
+ petFriendly: "Pet friendly",
2700
+ piscinaPrivativa: "Piscina privativa",
2701
+ pisoLaminado: "Piso laminado",
2702
+ pisoMadeira: "Piso de madeira",
2703
+ pisoPorcelanato: "Piso porcelanato",
2704
+ quadraEsportes: "Quadra de esportes",
2705
+ rooftop: "Rooftop",
2706
+ suite: "Su\xEDte",
2707
+ triplex: "Triplex",
2708
+ duplex: "Duplex",
2709
+ cobertura: "Cobertura",
2710
+ forroGesso: "Forro de gesso",
2711
+ gerador: "Gerador",
2712
+ armariosCozinha: "Arm\xE1rios na cozinha",
2713
+ armariosQuarto: "Arm\xE1rios nos quartos",
2714
+ cftv: "CFTV"
2715
+ };
2716
+ function lookupLabel(id, options) {
2717
+ const fromDictionary = options?.find((option) => option.id === id)?.label;
2718
+ if (fromDictionary?.trim()) return fromDictionary.trim();
2719
+ return AMENITY_FALLBACK_LABELS[id];
2720
+ }
2721
+ function labelAmenities(ids, dictionary) {
2722
+ if (!ids?.length) return [];
2723
+ const labels = [];
2724
+ const seen = /* @__PURE__ */ new Set();
2725
+ for (const id of ids) {
2726
+ if (!id) continue;
2727
+ const label = lookupLabel(id, dictionary);
2728
+ if (!label || seen.has(label)) continue;
2729
+ seen.add(label);
2730
+ labels.push(label);
2626
2731
  }
2627
- const nextApplied = reduceAppliedSearchQuery2(applied, change);
2628
- return publicSearchHref(nextPath, nextApplied, dictionary, search);
2629
- }
2630
- function currentSearchHref(pathname, search) {
2631
- const path = pathnameOnly(pathname);
2632
- const qs = search.replace(/^\?/, "");
2633
- return qs ? `${path}?${qs}` : path;
2634
- }
2635
- function canonicalizeSearchHref(pathname, search, dictionary) {
2636
- if (pathname.includes("/api/v0-preview/")) return null;
2637
- if (isListingDetailPath(pathname)) return null;
2638
- const { pathFilters, applied } = readPublicSearch(
2639
- pathname,
2640
- search,
2641
- dictionary
2642
- );
2643
- const href = publicSearchHref(pathFilters, applied, dictionary, search);
2644
- if (href === currentSearchHref(pathname, search)) return null;
2645
- return href;
2732
+ return labels.sort((a, b) => a.localeCompare(b, "pt-BR"));
2646
2733
  }
2647
- function searchHrefUsesLegacyFilterQuery(href) {
2648
- const query = href.split("?")[1] || "";
2649
- const params = new URLSearchParams(query);
2650
- return FORBIDDEN_SEARCH_QUERY_KEYS.some((key) => params.has(key));
2734
+ function presentIds(ids) {
2735
+ return (ids ?? []).filter((id) => Boolean(id));
2651
2736
  }
2652
- function clearStagedPathFilters(current, keepFilterIds = []) {
2653
- const next = current.location ? { location: current.location } : {};
2654
- for (const id of keepFilterIds) {
2655
- const key = PATH_FILTER_IDS[id];
2656
- if (!key || key === "location") continue;
2657
- const value = current[key];
2658
- if (value != null) Object.assign(next, { [key]: value });
2737
+ function buildingIdsFromMergedAmenities(listing, unitIds) {
2738
+ if (!listing.amenities || listing.propertyFeatures == null) return [];
2739
+ const unitCounts = /* @__PURE__ */ new Map();
2740
+ for (const id of unitIds) {
2741
+ unitCounts.set(id, (unitCounts.get(id) ?? 0) + 1);
2659
2742
  }
2660
- return next;
2661
- }
2662
- function visibleSearchFilters(schema) {
2663
- if (!schema?.filters) return [];
2664
- return schema.filters.filter((filter) => {
2665
- if (HIDDEN_FILTER_IDS.has(filter.id)) return false;
2666
- if (filter.id === "listing_type" && (filter.options?.length ?? 0) <= 1) {
2667
- return false;
2668
- }
2669
- return true;
2743
+ return listing.amenities.filter((id) => {
2744
+ if (!id) return false;
2745
+ const count = unitCounts.get(id);
2746
+ if (count === void 0 || count === 0) return true;
2747
+ unitCounts.set(id, count - 1);
2748
+ return false;
2670
2749
  });
2671
2750
  }
2672
- function toolbarFilterIds(schema) {
2673
- const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));
2674
- return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));
2675
- }
2676
- function countOptionLabel(option) {
2677
- const label = String(option?.label ?? "");
2678
- if (/^[1-9]\d*$/.test(label)) return `${label}+`;
2679
- return label;
2680
- }
2681
- function countFacetChoices(options) {
2682
- const list = options || [];
2683
- const zero = list.find((o) => o.id === "0" || o.label === "Studio");
2684
- const isStudio = Boolean(
2685
- zero && /studio/i.test(String(zero.label)) && zero.id === "0"
2686
- );
2687
- const max = isStudio ? 3 : 4;
2688
- const out = [];
2689
- if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });
2690
- for (let n = 1; n <= max; n += 1) {
2691
- const option = list.find((o) => o.id === String(n));
2692
- out.push({
2693
- id: String(n),
2694
- label: countOptionLabel(option || { label: String(n) })
2695
- });
2751
+ function unitAmenityIds(listing) {
2752
+ if (listing.propertyFeatures != null) {
2753
+ return presentIds(listing.propertyFeatures);
2696
2754
  }
2697
- return out;
2698
- }
2699
- var FEMININE_HEADING = /(casa|cobertura|kitnet|loja|sala|fazenda|chácara|chacara)s?$/i;
2700
- function pluralizePt(label) {
2701
- const text2 = label.trim();
2702
- if (!text2 || /s$/i.test(text2)) return text2;
2703
- if (/il$/i.test(text2)) return `${text2.slice(0, -1)}is`;
2704
- if (/m$/i.test(text2)) return `${text2.slice(0, -1)}ns`;
2705
- return `${text2}s`;
2755
+ const building = new Set(
2756
+ listing.building?.amenities ?? listing.buildingAmenities ?? []
2757
+ );
2758
+ return (listing.amenities ?? []).filter((id) => id && !building.has(id));
2706
2759
  }
2707
- function headingLocationSuffix(location) {
2708
- if (!location) return "";
2709
- if (location.street && location.neighborhood) {
2710
- return `${location.street}, ${location.neighborhood}`;
2711
- }
2712
- if (location.neighborhood && location.city) {
2713
- return `${location.neighborhood}, ${location.city}`;
2760
+ function buildingAmenityIds(listing) {
2761
+ if (listing.building != null && listing.building.amenities != null) {
2762
+ return presentIds(listing.building.amenities);
2714
2763
  }
2715
- if (location.city && location.state) {
2716
- return `${location.city} - ${location.state}`;
2764
+ if (listing.buildingAmenities != null) {
2765
+ return presentIds(listing.buildingAmenities);
2717
2766
  }
2718
- return location.city || location.neighborhood || location.street || location.state || "";
2767
+ return buildingIdsFromMergedAmenities(listing, unitAmenityIds(listing));
2719
2768
  }
2720
- function searchResultsHeading(pathFilters, dictionary, locationNames) {
2721
- const types = [].concat(pathFilters.propertyType || []).filter(Boolean);
2722
- let noun = "Im\xF3veis";
2723
- let found = "encontrados";
2724
- if (types.length === 1) {
2725
- const id = String(types[0]);
2726
- const option = dictionary?.propertyTypes?.find(
2727
- (entry) => entry.id === id || entry.slug === id
2728
- );
2729
- const label = option?.label;
2730
- if (label) {
2731
- noun = pluralizePt(label.charAt(0).toUpperCase() + label.slice(1));
2732
- if (FEMININE_HEADING.test(id) || FEMININE_HEADING.test(label)) {
2733
- found = "encontradas";
2734
- }
2735
- }
2769
+ function listingAmenityGroups(listing, dictionary) {
2770
+ const groups = [];
2771
+ const unitIds = unitAmenityIds(listing);
2772
+ const unitLabels = labelAmenities(unitIds, dictionary?.propertyFeatures);
2773
+ if (unitLabels.length > 0) {
2774
+ groups.push({
2775
+ key: "unit",
2776
+ title: dictionary?.amenitySectionTitles?.unit ?? LISTING_AMENITY_TITLES.unit,
2777
+ labels: unitLabels
2778
+ });
2736
2779
  }
2737
- const place = locationNames ? headingLocationSuffix(
2738
- displayPathLocation(pathFilters.location, locationNames)
2739
- ) : "";
2740
- if (place) return `${noun} ${found} em ${place}`;
2741
- return `${noun} ${found}`;
2742
- }
2743
- function hrefWithExplicitPage(href, page) {
2744
- if (page !== 1 || /(?:\?|&)page=/.test(href)) return href;
2745
- return href.includes("?") ? `${href}&page=1` : `${href}?page=1`;
2746
- }
2747
- function paginationPages(currentPage, totalPages, padding) {
2748
- if (totalPages < 1) return [];
2749
- const current = Math.min(Math.max(1, currentPage), totalPages);
2750
- const start = Math.max(1, current - padding);
2751
- const end = Math.min(totalPages, current + padding);
2752
- const pages = [];
2753
- for (let i = start; i <= end; i += 1) pages.push(i);
2754
- return pages;
2780
+ const buildingLabels = labelAmenities(
2781
+ buildingAmenityIds(listing),
2782
+ dictionary?.buildingAmenities
2783
+ );
2784
+ if (buildingLabels.length > 0) {
2785
+ groups.push({
2786
+ key: "building",
2787
+ title: dictionary?.amenitySectionTitles?.building ?? LISTING_AMENITY_TITLES.building,
2788
+ labels: buildingLabels
2789
+ });
2790
+ }
2791
+ return groups;
2755
2792
  }
2756
- var SEARCH_EMPTY_COPY = "Nenhum im\xF3vel encontrado. Ajuste a busca ou os filtros.";
2757
- function rangeDraftFromPath(pathFilters) {
2758
- const price = pathFilters.price || {};
2759
- const area = pathFilters.area || {};
2760
- return {
2761
- price: {
2762
- min: price.min != null ? formatGroupedInteger(price.min) : "",
2763
- max: price.max != null ? formatGroupedInteger(price.max) : ""
2764
- },
2765
- property_area_total: {
2766
- min: area.min != null ? String(area.min) : "",
2767
- max: area.max != null ? String(area.max) : ""
2768
- }
2769
- };
2793
+
2794
+ // src/listing-card-model.ts
2795
+ function listingLocationLabel(location) {
2796
+ return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
2770
2797
  }
2771
- function searchChromeModel(schema, pathFilters, locationNames) {
2772
- const filters = visibleSearchFilters(schema);
2773
- const toolbarIds = new Set(toolbarFilterIds(schema));
2798
+ function toListingCardModel(listing) {
2799
+ const isPrivate = listing.priceVisibility === "private";
2800
+ const area = listing.property?.usableArea ?? listing.property?.totalArea;
2774
2801
  return {
2775
- headingTitle: searchResultsHeading(
2776
- pathFilters,
2777
- schema?.dictionary,
2778
- locationNames
2779
- ),
2780
- toolbarFilters: filters.filter((filter) => toolbarIds.has(filter.id)),
2781
- extraFilters: filters.filter((filter) => !toolbarIds.has(filter.id)),
2782
- sortOptions: searchSortOptions(schema?.sorts)
2802
+ href: listingPublicPath(listing),
2803
+ title: listing.title,
2804
+ businessType: listing.businessType,
2805
+ businessLabel: listingBusinessLabel(listing.businessType),
2806
+ priceVisibility: listing.priceVisibility,
2807
+ price: listing.price,
2808
+ priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price, "pt-BR", listing.currency ?? "BRL"),
2809
+ pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
2810
+ locationLabel: listingLocationLabel(listing.location || {}),
2811
+ propertyType: listing.property?.type ?? null,
2812
+ coverSrc: listing.coverImage?.src ?? null,
2813
+ coverAlt: listing.coverImage?.alt ?? listing.title,
2814
+ bedrooms: listing.property?.bedrooms ?? null,
2815
+ bathrooms: listing.property?.bathrooms ?? null,
2816
+ parkingSpaces: listing.property?.parkingSpaces ?? null,
2817
+ areaM2: area ?? null
2783
2818
  };
2784
2819
  }
2785
2820
 
@@ -3296,7 +3331,15 @@ var STUDIO_SDK_CONTRACT = {
3296
3331
  * v0 installs the pin and copies any identifier it sees.
3297
3332
  */
3298
3333
  shareExports: ["getShareLink"],
3299
- shareLinkSince: "0.12.0"
3334
+ shareLinkSince: "0.12.0",
3335
+ /**
3336
+ * Listing-view analytics. Search and lead catalog events need no prompt:
3337
+ * `usePublicSearch` and the lead helpers emit them from `analyticsSince`.
3338
+ * Below it `studioListingViewInstruction` prints nothing and
3339
+ * `studioCodegenContractViolations` flags `trackListingView`.
3340
+ */
3341
+ analyticsExports: ["trackListingView"],
3342
+ analyticsSince: "0.13.0"
3300
3343
  };
3301
3344
  function isSellerLeadOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3302
3345
  return compareSemver(pin, STUDIO_SDK_CONTRACT.sellerLeadSince) >= 0;
@@ -3304,6 +3347,14 @@ function isSellerLeadOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3304
3347
  function isShareLinkOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3305
3348
  return compareSemver(pin, STUDIO_SDK_CONTRACT.shareLinkSince) >= 0;
3306
3349
  }
3350
+ function isAnalyticsOnPin(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3351
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.analyticsSince) >= 0;
3352
+ }
3353
+ function studioListingViewInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3354
+ if (!isAnalyticsOnPin(pin)) return "";
3355
+ const name = STUDIO_SDK_CONTRACT.analyticsExports[0];
3356
+ return `Listing view analytics: import ${name} from \`${STUDIO_SDK_PACKAGE}\` in a client component the listing page already renders (the visit/contact component is the usual place) and call \`useEffect(() => { ${name}(listing); }, [listing.id])\`. Call it once per listing page, never in a card, carousel or similar-listings loop. Do not build or post the event yourself.`;
3357
+ }
3307
3358
  function studioShareLinkInstruction(pin = STUDIO_SDK_CONTRACT.minNpmVersion) {
3308
3359
  if (!isShareLinkOnPin(pin)) return "";
3309
3360
  const name = STUDIO_SDK_CONTRACT.shareExports[0];
@@ -3561,6 +3612,13 @@ function studioCodegenContractViolations(text2) {
3561
3612
  }
3562
3613
  }
3563
3614
  }
3615
+ if (!isAnalyticsOnPin()) {
3616
+ for (const name of STUDIO_SDK_CONTRACT.analyticsExports) {
3617
+ if (mentionsExportName(text2, name) && !violations.includes(name)) {
3618
+ violations.push(name);
3619
+ }
3620
+ }
3621
+ }
3564
3622
  const pin = STUDIO_SDK_CONTRACT.minNpmVersion;
3565
3623
  if (!marketExportsAvailableAt(pin)) {
3566
3624
  for (const name of STUDIO_SDK_CONTRACT.marketExports) {
@@ -4920,6 +4978,7 @@ export {
4920
4978
  SELLER_LEAD_PHOTO_MAX_BYTES,
4921
4979
  SELLER_LEAD_PHOTO_MAX_COUNT,
4922
4980
  SELLER_LEAD_PHOTO_TYPES,
4981
+ SITE_ANALYTICS_EVENT,
4923
4982
  STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG,
4924
4983
  STUDIO_DEFAULT_VISIT_SCHEDULE,
4925
4984
  STUDIO_SDK_CONTRACT,
@@ -4980,6 +5039,7 @@ export {
4980
5039
  hrefForAppliedChange,
4981
5040
  hrefForPathFilters,
4982
5041
  hrefWithExplicitPage,
5042
+ isAnalyticsOnPin,
4983
5043
  isListingDetailPath,
4984
5044
  isMapBounds,
4985
5045
  isMapPolygon,
@@ -5070,6 +5130,7 @@ export {
5070
5130
  studioLeadInstruction,
5071
5131
  studioListingCardInstruction,
5072
5132
  studioListingDetailInstruction,
5133
+ studioListingViewInstruction,
5073
5134
  studioMapSearchInstruction,
5074
5135
  studioMapsInstruction,
5075
5136
  studioMarketInstruction,
@@ -5089,6 +5150,7 @@ export {
5089
5150
  toE164,
5090
5151
  toListingCardModel,
5091
5152
  toolbarFilterIds,
5153
+ trackListingView,
5092
5154
  travelTimeCacheKey,
5093
5155
  travelTimeFromListing,
5094
5156
  travelTimesFromListing,