@garagem-ai/site-sdk 0.1.1 → 0.3.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.js CHANGED
@@ -21,14 +21,48 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  GaragemSdkError: () => GaragemSdkError,
24
+ composeSearchPublicHref: () => composeSearchPublicHref2,
25
+ composeSearchPublicPath: () => composeSearchPublicPath2,
24
26
  createGaragemClient: () => createGaragemClient,
27
+ getCmsCollection: () => getCmsCollection,
28
+ getCmsCollections: () => getCmsCollections,
29
+ getCmsEntries: () => getCmsEntries,
30
+ getCmsEntry: () => getCmsEntry,
25
31
  getListing: () => getListing,
26
32
  getListings: () => getListings,
33
+ getSearchUi: () => getSearchUi,
34
+ getSimilarListings: () => getSimilarListings,
27
35
  getSite: () => getSite,
28
- searchListings: () => searchListings
36
+ isStudioPreviewHost: () => isStudioPreviewHost,
37
+ listingLookupKey: () => listingLookupKey,
38
+ listingPublicPath: () => listingPublicPath,
39
+ mergeAppliedSearchQueryIntoSearch: () => mergeAppliedSearchQueryIntoSearch2,
40
+ parseAppliedSearchQuery: () => parseAppliedSearchQuery2,
41
+ parseSearchPublicPath: () => parseSearchPublicPath2,
42
+ pathFiltersToQueryFilters: () => pathFiltersToQueryFilters,
43
+ pathLocationToFilterInput: () => pathLocationToFilterInput,
44
+ queryListings: () => queryListings,
45
+ reduceAppliedSearchQuery: () => reduceAppliedSearchQuery2,
46
+ resolvePublicSiteId: () => resolvePublicSiteId,
47
+ searchListings: () => searchListings,
48
+ serializeAppliedSearchQuery: () => serializeAppliedSearchQuery2
29
49
  });
30
50
  module.exports = __toCommonJS(index_exports);
31
51
 
52
+ // src/listing-path.ts
53
+ function listingLookupKey(raw) {
54
+ return raw.trim().replace(/^id-/, "").trim();
55
+ }
56
+ function listingPublicPath(listing) {
57
+ const composed = listing.path?.trim() ?? "";
58
+ if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
59
+ const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
60
+ if (!identity || identity === "undefined" || identity === "null") {
61
+ throw new TypeError("listingPublicPath: listing has no listingCode or id");
62
+ }
63
+ return `/imoveis/id-${identity}`;
64
+ }
65
+
32
66
  // src/internal/url.ts
33
67
  var DEFAULT_BASE_URL = "https://app.garagem.ai";
34
68
  function normalizeBaseUrl(baseUrl) {
@@ -44,8 +78,10 @@ function buildListingFiltersQuery(filters) {
44
78
  if (filters.propertyType) params.set("propertyType", filters.propertyType);
45
79
  if (filters.city) params.set("city", filters.city);
46
80
  if (filters.neighborhood) params.set("neighborhood", filters.neighborhood);
47
- if (filters.minPrice != null) params.set("minPrice", String(filters.minPrice));
48
- if (filters.maxPrice != null) params.set("maxPrice", String(filters.maxPrice));
81
+ if (filters.minPrice != null)
82
+ params.set("minPrice", String(filters.minPrice));
83
+ if (filters.maxPrice != null)
84
+ params.set("maxPrice", String(filters.maxPrice));
49
85
  return params;
50
86
  }
51
87
 
@@ -79,7 +115,7 @@ async function getListings(options) {
79
115
  const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings${qs}`;
80
116
  const data = await callJson(
81
117
  url,
82
- { method: "GET", headers: { "Content-Type": "application/json" }, next },
118
+ { method: "GET", headers: { Accept: "application/json" }, next },
83
119
  fetchImpl ?? fetch
84
120
  );
85
121
  return {
@@ -88,14 +124,24 @@ async function getListings(options) {
88
124
  };
89
125
  }
90
126
  async function getListing(options) {
91
- const { siteId, listingId, baseUrl, fetch: fetchImpl, next } = options;
127
+ const {
128
+ siteId,
129
+ listingId: rawListingId,
130
+ baseUrl,
131
+ fetch: fetchImpl,
132
+ next
133
+ } = options;
134
+ const listingId = listingLookupKey(rawListingId ?? "");
135
+ if (!listingId || listingId === "undefined" || listingId === "null") {
136
+ throw new TypeError("getListing: `listingId` is required");
137
+ }
92
138
  const base = normalizeBaseUrl(baseUrl);
93
139
  const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(
94
140
  listingId
95
141
  )}`;
96
142
  return callJson(
97
143
  url,
98
- { method: "GET", headers: { "Content-Type": "application/json" }, next },
144
+ { method: "GET", headers: { Accept: "application/json" }, next },
99
145
  fetchImpl ?? fetch
100
146
  );
101
147
  }
@@ -119,7 +165,7 @@ async function getSite(options) {
119
165
  const f = fetchImpl ?? fetch;
120
166
  const response = await f(url, {
121
167
  method: "GET",
122
- headers: { "Content-Type": "application/json" },
168
+ headers: { Accept: "application/json" },
123
169
  next
124
170
  });
125
171
  if (response.status === 404) return null;
@@ -157,6 +203,638 @@ async function searchListings(options) {
157
203
  fetchImpl ?? fetch
158
204
  );
159
205
  }
206
+ async function getSearchUi(options) {
207
+ const { siteId, baseUrl, fetch: fetchImpl, next } = options;
208
+ const base = normalizeBaseUrl(baseUrl);
209
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
210
+ return callJson(
211
+ url,
212
+ { method: "GET", headers: { Accept: "application/json" }, next },
213
+ fetchImpl ?? fetch
214
+ );
215
+ }
216
+ async function queryListings(options) {
217
+ const { siteId, params, baseUrl, fetch: fetchImpl, next } = options;
218
+ const base = normalizeBaseUrl(baseUrl);
219
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
220
+ return callJson(
221
+ url,
222
+ {
223
+ method: "POST",
224
+ headers: {
225
+ Accept: "application/json",
226
+ "Content-Type": "application/json"
227
+ },
228
+ body: JSON.stringify(params ?? {}),
229
+ next
230
+ },
231
+ fetchImpl ?? fetch
232
+ );
233
+ }
234
+ async function getSimilarListings(options) {
235
+ const {
236
+ siteId,
237
+ listingId: rawListingId,
238
+ limit,
239
+ baseUrl,
240
+ fetch: fetchImpl,
241
+ next
242
+ } = options;
243
+ const listingId = listingLookupKey(rawListingId ?? "");
244
+ if (!listingId || listingId === "undefined" || listingId === "null") {
245
+ throw new TypeError("getSimilarListings: `listingId` is required");
246
+ }
247
+ const base = normalizeBaseUrl(baseUrl);
248
+ const params = new URLSearchParams();
249
+ if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) {
250
+ params.set("limit", String(Math.floor(limit)));
251
+ }
252
+ const qs = params.size > 0 ? `?${params.toString()}` : "";
253
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(
254
+ listingId
255
+ )}/similar${qs}`;
256
+ const data = await callJson(
257
+ url,
258
+ { method: "GET", headers: { Accept: "application/json" }, next },
259
+ fetchImpl ?? fetch
260
+ );
261
+ return {
262
+ listings: data.listings ?? [],
263
+ total: data.total ?? 0
264
+ };
265
+ }
266
+ async function getCmsCollections(options) {
267
+ const { siteId, baseUrl, fetch: fetchImpl, next } = options;
268
+ const base = normalizeBaseUrl(baseUrl);
269
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections`;
270
+ const data = await callJson(
271
+ url,
272
+ { method: "GET", headers: { Accept: "application/json" }, next },
273
+ fetchImpl ?? fetch
274
+ );
275
+ return data.collections ?? [];
276
+ }
277
+ async function getCmsCollection(options) {
278
+ const { siteId, slug, baseUrl, fetch: fetchImpl, next } = options;
279
+ if (!slug) {
280
+ throw new TypeError("getCmsCollection: `slug` is required");
281
+ }
282
+ const base = normalizeBaseUrl(baseUrl);
283
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/collections/${encodeURIComponent(
284
+ slug
285
+ )}`;
286
+ const data = await callJson(
287
+ url,
288
+ { method: "GET", headers: { Accept: "application/json" }, next },
289
+ fetchImpl ?? fetch
290
+ );
291
+ if (data && typeof data === "object" && "collection" in data && data.collection) {
292
+ return data.collection;
293
+ }
294
+ return data;
295
+ }
296
+ async function getCmsEntries(options) {
297
+ const {
298
+ siteId,
299
+ collection,
300
+ limit,
301
+ offset,
302
+ baseUrl,
303
+ fetch: fetchImpl,
304
+ next
305
+ } = options;
306
+ if (!collection) {
307
+ throw new TypeError("getCmsEntries: `collection` is required");
308
+ }
309
+ const base = normalizeBaseUrl(baseUrl);
310
+ const params = new URLSearchParams();
311
+ if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) {
312
+ params.set("limit", String(Math.floor(limit)));
313
+ }
314
+ if (typeof offset === "number" && Number.isFinite(offset) && offset >= 0) {
315
+ params.set("offset", String(Math.floor(offset)));
316
+ }
317
+ const qs = params.size > 0 ? `?${params.toString()}` : "";
318
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/${encodeURIComponent(
319
+ collection
320
+ )}/entries${qs}`;
321
+ const data = await callJson(
322
+ url,
323
+ { method: "GET", headers: { Accept: "application/json" }, next },
324
+ fetchImpl ?? fetch
325
+ );
326
+ return {
327
+ entries: data.entries ?? [],
328
+ total: data.total ?? 0,
329
+ limit: data.limit ?? 0,
330
+ offset: data.offset ?? 0
331
+ };
332
+ }
333
+ async function getCmsEntry(options) {
334
+ const { siteId, collection, slug, baseUrl, fetch: fetchImpl, next } = options;
335
+ if (!collection) {
336
+ throw new TypeError("getCmsEntry: `collection` is required");
337
+ }
338
+ if (!slug) {
339
+ throw new TypeError("getCmsEntry: `slug` is required");
340
+ }
341
+ const base = normalizeBaseUrl(baseUrl);
342
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/cms/${encodeURIComponent(
343
+ collection
344
+ )}/entries/${encodeURIComponent(slug)}`;
345
+ const data = await callJson(
346
+ url,
347
+ { method: "GET", headers: { Accept: "application/json" }, next },
348
+ fetchImpl ?? fetch
349
+ );
350
+ if (data && typeof data === "object" && "entry" in data && data.entry) {
351
+ return data.entry;
352
+ }
353
+ return data;
354
+ }
355
+
356
+ // ../search-url/types.ts
357
+ var SEARCH_BASE_ROUTE = "imoveis";
358
+ var MAX_PAGE = 1e4;
359
+ var MAX_LOC_GROUPS = 20;
360
+ var DEFAULT_MIN_PRICE = 0;
361
+ var DEFAULT_MAX_PRICE = 1e9;
362
+ var DEFAULT_MIN_AREA = 0;
363
+ var DEFAULT_MAX_AREA = 1e5;
364
+ var SORT_URL_TOKENS = [
365
+ "preco-asc",
366
+ "preco-desc",
367
+ "area-asc",
368
+ "area-desc"
369
+ ];
370
+
371
+ // ../search-url/slugify.ts
372
+ function slugifyForUrl(text) {
373
+ if (!text) return "";
374
+ const withDashes = text.replace(/([a-z])([A-Z])/g, "$1-$2");
375
+ return withDashes.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
376
+ }
377
+
378
+ // ../search-url/catalog.ts
379
+ var PROPERTY_TYPE_SLUG_ALIASES = {
380
+ rural: ["chacara", "fazenda", "sitio"]
381
+ };
382
+ function buildListingTypeOptions(enabled) {
383
+ const flags = enabled ?? { sale: true, rental: true };
384
+ const out = [];
385
+ if (flags.sale !== false) {
386
+ out.push({ id: "sale", slug: "venda", label: "Venda" });
387
+ }
388
+ if (flags.rental !== false) {
389
+ out.push({ id: "rental", slug: "aluguel", label: "Aluguel" });
390
+ }
391
+ return out;
392
+ }
393
+ function emptySearchUrlDictionary() {
394
+ return {
395
+ listingTypes: buildListingTypeOptions(null),
396
+ propertyTypes: [],
397
+ propertyFeatures: [],
398
+ buildingAmenities: []
399
+ };
400
+ }
401
+ function norm(value) {
402
+ return slugifyForUrl(value) || value.toLowerCase();
403
+ }
404
+ function matchOptionId(segment, options, extraAliases) {
405
+ const n = norm(segment);
406
+ for (const option of options) {
407
+ const aliases = extraAliases?.[option.id] ?? [];
408
+ const candidates = [option.id, option.slug, option.label, ...aliases];
409
+ if (candidates.some((c) => norm(c) === n)) return option.id;
410
+ }
411
+ return null;
412
+ }
413
+ function optionSlugById(id, options) {
414
+ const option = options.find((item) => item.id === id);
415
+ return option?.slug ?? null;
416
+ }
417
+ var LISTING_TYPE_ALIASES = {
418
+ sale: ["comprar"],
419
+ rental: ["alugar"]
420
+ };
421
+
422
+ // ../search-url/path.ts
423
+ function toArray(value) {
424
+ if (value === void 0) return [];
425
+ return Array.isArray(value) ? value : [value];
426
+ }
427
+ function formatNumeric(value) {
428
+ return Array.isArray(value) ? value.join("-") : String(value);
429
+ }
430
+ function formatRange(min, max, unit) {
431
+ return `de-${min}-a-${max}-${unit}`;
432
+ }
433
+ function formatSuiteSuffix(value) {
434
+ const values = Array.isArray(value) ? value : [value];
435
+ const firstValue = values[0] ?? 0;
436
+ return firstValue === 0 || firstValue === 1 ? "suite" : "suites";
437
+ }
438
+ function composeSearchPublicPath(filters, dictionary = emptySearchUrlDictionary()) {
439
+ const segments = [];
440
+ const listingType = filters.listingType;
441
+ if (listingType) {
442
+ segments.push(
443
+ optionSlugById(listingType, dictionary.listingTypes) || slugifyForUrl(listingType)
444
+ );
445
+ }
446
+ for (const propertyType of toArray(filters.propertyType)) {
447
+ segments.push(
448
+ optionSlugById(propertyType, dictionary.propertyTypes) || slugifyForUrl(propertyType)
449
+ );
450
+ }
451
+ const location = filters.location;
452
+ if (location) {
453
+ if (location.state) segments.push(slugifyForUrl(location.state));
454
+ if (location.city) segments.push(slugifyForUrl(location.city));
455
+ if (location.neighborhood)
456
+ segments.push(slugifyForUrl(location.neighborhood));
457
+ if (location.street) segments.push(slugifyForUrl(location.street));
458
+ }
459
+ if (filters.bedrooms !== void 0) {
460
+ segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);
461
+ }
462
+ if (filters.bathrooms !== void 0) {
463
+ segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);
464
+ }
465
+ if (filters.suites !== void 0) {
466
+ const suffix = formatSuiteSuffix(filters.suites);
467
+ segments.push(`${formatNumeric(filters.suites)}-${suffix}`);
468
+ }
469
+ if (filters.parkingSpots !== void 0) {
470
+ segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);
471
+ }
472
+ if (filters.price && (filters.price.min !== void 0 || filters.price.max !== void 0)) {
473
+ const min = filters.price.min ?? DEFAULT_MIN_PRICE;
474
+ const max = filters.price.max ?? DEFAULT_MAX_PRICE;
475
+ segments.push(formatRange(min, max, "reais"));
476
+ }
477
+ if (filters.area && (filters.area.min !== void 0 || filters.area.max !== void 0)) {
478
+ const min = filters.area.min ?? DEFAULT_MIN_AREA;
479
+ const max = filters.area.max ?? DEFAULT_MAX_AREA;
480
+ segments.push(formatRange(min, max, "m2"));
481
+ }
482
+ const seenAmenities = /* @__PURE__ */ new Set();
483
+ for (const id of filters.propertyFeatures ?? []) {
484
+ const slug = optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);
485
+ if (!slug || seenAmenities.has(slug)) continue;
486
+ seenAmenities.add(slug);
487
+ segments.push(slug);
488
+ }
489
+ for (const id of filters.buildingAmenities ?? []) {
490
+ const slug = optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);
491
+ if (!slug || seenAmenities.has(slug)) continue;
492
+ seenAmenities.add(slug);
493
+ segments.push(slug);
494
+ }
495
+ const path = segments.filter(Boolean).join("/");
496
+ return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;
497
+ }
498
+ var BEDROOMS = /^(\d+(?:-\d+)*)-quartos?$/;
499
+ var BATHROOMS = /^(\d+(?:-\d+)*)-banheiros?$/;
500
+ var SUITES = /^(\d+(?:-\d+)*)-suites?$/;
501
+ var PARKING = /^(\d+(?:-\d+)*)-vagas?$/;
502
+ var PRICE = /^de-(\d+)-a-(\d+)-(reais|real)$/;
503
+ var AREA = /^de-(\d+)-a-(\d+)-(m2|m²)$/;
504
+ function parseNumericList(raw) {
505
+ return raw.split("-").map((part) => Number(part)).filter((n) => Number.isFinite(n));
506
+ }
507
+ function collapse(values) {
508
+ return values.length === 1 ? values[0] : values;
509
+ }
510
+ function parseSearchPublicPath(pathname, dictionary = emptySearchUrlDictionary()) {
511
+ const raw = pathname.split(/[?#]/)[0] ?? "";
512
+ let segments = raw.replace(/^\//, "").split("/").filter(Boolean);
513
+ if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);
514
+ if (segments.some((segment) => segment.includes("."))) return null;
515
+ if (segments.some((segment) => segment.toLowerCase().startsWith("id-"))) {
516
+ return null;
517
+ }
518
+ const filters = {};
519
+ const locationParts = [];
520
+ const propertyTypes = [];
521
+ const propertyFeatures = [];
522
+ const buildingAmenities = [];
523
+ for (const segment of segments) {
524
+ const lower = segment.toLowerCase();
525
+ const listingType = matchOptionId(
526
+ segment,
527
+ dictionary.listingTypes,
528
+ LISTING_TYPE_ALIASES
529
+ );
530
+ if (listingType && !filters.listingType) {
531
+ filters.listingType = listingType;
532
+ continue;
533
+ }
534
+ const propertyType = matchOptionId(
535
+ segment,
536
+ dictionary.propertyTypes,
537
+ PROPERTY_TYPE_SLUG_ALIASES
538
+ );
539
+ if (propertyType) {
540
+ propertyTypes.push(propertyType);
541
+ continue;
542
+ }
543
+ const bedrooms = lower.match(BEDROOMS);
544
+ if (bedrooms) {
545
+ filters.bedrooms = collapse(parseNumericList(bedrooms[1]));
546
+ continue;
547
+ }
548
+ const bathrooms = lower.match(BATHROOMS);
549
+ if (bathrooms) {
550
+ filters.bathrooms = collapse(parseNumericList(bathrooms[1]));
551
+ continue;
552
+ }
553
+ const suites = lower.match(SUITES);
554
+ if (suites) {
555
+ filters.suites = collapse(parseNumericList(suites[1]));
556
+ continue;
557
+ }
558
+ const parking = lower.match(PARKING);
559
+ if (parking) {
560
+ filters.parkingSpots = collapse(parseNumericList(parking[1]));
561
+ continue;
562
+ }
563
+ const price = lower.match(PRICE);
564
+ if (price) {
565
+ filters.price = { min: Number(price[1]), max: Number(price[2]) };
566
+ continue;
567
+ }
568
+ const area = lower.match(AREA);
569
+ if (area) {
570
+ filters.area = { min: Number(area[1]), max: Number(area[2]) };
571
+ continue;
572
+ }
573
+ const featureId = matchOptionId(segment, dictionary.propertyFeatures);
574
+ if (featureId) {
575
+ propertyFeatures.push(featureId);
576
+ continue;
577
+ }
578
+ const amenityId = matchOptionId(segment, dictionary.buildingAmenities);
579
+ if (amenityId) {
580
+ buildingAmenities.push(amenityId);
581
+ continue;
582
+ }
583
+ locationParts.push(segment);
584
+ }
585
+ if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];
586
+ else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;
587
+ if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;
588
+ if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;
589
+ const location = locationFromPathLeftovers(locationParts);
590
+ if (location) filters.location = location;
591
+ return filters;
592
+ }
593
+ var PATH_STREET_PREFIX = /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;
594
+ function locationFromPathLeftovers(parts) {
595
+ if (parts.length === 0) return void 0;
596
+ if (parts.length === 1) {
597
+ const value = parts[0];
598
+ if (PATH_STREET_PREFIX.test(value)) return { street: value };
599
+ if (/^[a-z]{2}$/i.test(value)) return { state: value };
600
+ return { neighborhood: value };
601
+ }
602
+ const [state, city, neighborhood, street] = parts;
603
+ return {
604
+ ...state ? { state } : {},
605
+ ...city ? { city } : {},
606
+ ...neighborhood ? { neighborhood } : {},
607
+ ...street ? { street } : {}
608
+ };
609
+ }
610
+
611
+ // ../search-url/applied-query.ts
612
+ var SORT_SET = new Set(SORT_URL_TOKENS);
613
+ function isSortToken(value) {
614
+ return SORT_SET.has(value);
615
+ }
616
+ function normalizeAppliedSearchQuery(query) {
617
+ if (query.loc && query.loc.length > 0) {
618
+ const { query: _query, ...rest } = query;
619
+ return rest;
620
+ }
621
+ return query;
622
+ }
623
+ function parseAppliedSearchQuery(search) {
624
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
625
+ const result = {};
626
+ const pageRaw = params.get("page");
627
+ if (pageRaw) {
628
+ const page = Number.parseInt(pageRaw, 10);
629
+ if (Number.isFinite(page) && page > 1) {
630
+ result.page = Math.min(page, MAX_PAGE);
631
+ }
632
+ }
633
+ const sort = params.get("ordenar");
634
+ if (sort && isSortToken(sort)) result.sort = sort;
635
+ const q = params.get("q")?.trim();
636
+ if (q) result.query = q;
637
+ const loc = params.getAll("loc").map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
638
+ if (loc.length > 0) result.loc = loc;
639
+ return normalizeAppliedSearchQuery(result);
640
+ }
641
+ var APPLIED_QUERY_KEYS = ["page", "ordenar", "q", "loc"];
642
+ function serializeAppliedSearchQuery(query) {
643
+ const normalized = normalizeAppliedSearchQuery(query);
644
+ const params = new URLSearchParams();
645
+ if (normalized.page !== void 0 && normalized.page > 1) {
646
+ params.set("page", String(Math.min(normalized.page, MAX_PAGE)));
647
+ }
648
+ if (normalized.sort && isSortToken(normalized.sort)) {
649
+ params.set("ordenar", normalized.sort);
650
+ }
651
+ const text = normalized.query?.trim();
652
+ if (text) params.set("q", text);
653
+ for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {
654
+ const trimmed = value.trim();
655
+ if (trimmed) params.append("loc", trimmed);
656
+ }
657
+ return params;
658
+ }
659
+ function mergeAppliedSearchQueryIntoSearch(existing, query) {
660
+ const params = existing instanceof URLSearchParams ? new URLSearchParams(existing) : new URLSearchParams(
661
+ existing.startsWith("?") ? existing.slice(1) : existing
662
+ );
663
+ for (const key of APPLIED_QUERY_KEYS) {
664
+ params.delete(key);
665
+ }
666
+ const serialized = serializeAppliedSearchQuery(query);
667
+ serialized.forEach((value, key) => {
668
+ if (key === "loc") {
669
+ params.append("loc", value);
670
+ } else {
671
+ params.set(key, value);
672
+ }
673
+ });
674
+ return params;
675
+ }
676
+ function reduceAppliedSearchQuery(prev, change) {
677
+ switch (change.type) {
678
+ case "sort": {
679
+ const next = { ...prev };
680
+ delete next.page;
681
+ if (change.sort) next.sort = change.sort;
682
+ else delete next.sort;
683
+ return normalizeAppliedSearchQuery(next);
684
+ }
685
+ case "applyFilters": {
686
+ const next = { ...prev };
687
+ delete next.page;
688
+ return normalizeAppliedSearchQuery(next);
689
+ }
690
+ case "query": {
691
+ const next = { ...prev };
692
+ delete next.page;
693
+ const trimmed = change.query.trim();
694
+ if (trimmed) {
695
+ next.query = trimmed;
696
+ delete next.loc;
697
+ } else {
698
+ delete next.query;
699
+ }
700
+ return normalizeAppliedSearchQuery(next);
701
+ }
702
+ case "loc": {
703
+ const next = { ...prev };
704
+ delete next.page;
705
+ delete next.query;
706
+ const loc = change.loc.map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
707
+ if (loc.length > 0) next.loc = loc;
708
+ else delete next.loc;
709
+ return normalizeAppliedSearchQuery(next);
710
+ }
711
+ case "page": {
712
+ const next = { ...prev };
713
+ if (change.page <= 1) delete next.page;
714
+ else next.page = Math.min(change.page, MAX_PAGE);
715
+ return normalizeAppliedSearchQuery(next);
716
+ }
717
+ default: {
718
+ const _exhaustive = change;
719
+ return _exhaustive;
720
+ }
721
+ }
722
+ }
723
+ function composeSearchPublicHref(pathname, query, existingSearch) {
724
+ const params = existingSearch ? mergeAppliedSearchQueryIntoSearch(existingSearch, query) : serializeAppliedSearchQuery(query);
725
+ const qs = params.toString();
726
+ return qs ? `${pathname}?${qs}` : pathname;
727
+ }
728
+
729
+ // src/path.ts
730
+ function composeSearchPublicPath2(filters, dictionary) {
731
+ return dictionary ? composeSearchPublicPath(filters, dictionary) : composeSearchPublicPath(filters);
732
+ }
733
+ function parseSearchPublicPath2(pathname, dictionary) {
734
+ return dictionary ? parseSearchPublicPath(pathname, dictionary) : parseSearchPublicPath(pathname);
735
+ }
736
+ function pathFiltersToQueryFilters(pathFilters) {
737
+ const result = {};
738
+ if (pathFilters.listingType !== void 0) {
739
+ result.listing_type = pathFilters.listingType;
740
+ }
741
+ if (pathFilters.propertyType !== void 0) {
742
+ result.property_type = pathFilters.propertyType;
743
+ }
744
+ if (pathFilters.bedrooms !== void 0) {
745
+ result.property_bedrooms = pathFilters.bedrooms;
746
+ }
747
+ if (pathFilters.bathrooms !== void 0) {
748
+ result.property_bathrooms = pathFilters.bathrooms;
749
+ }
750
+ if (pathFilters.suites !== void 0) {
751
+ result.property_suites = pathFilters.suites;
752
+ }
753
+ if (pathFilters.parkingSpots !== void 0) {
754
+ result.property_parking_spots = pathFilters.parkingSpots;
755
+ }
756
+ if (pathFilters.price !== void 0) {
757
+ result.price = pathFilters.price;
758
+ }
759
+ if (pathFilters.area !== void 0) {
760
+ result.property_area_total = pathFilters.area;
761
+ }
762
+ if (pathFilters.propertyFeatures !== void 0) {
763
+ result.propertyFeatures = pathFilters.propertyFeatures;
764
+ }
765
+ if (pathFilters.buildingAmenities !== void 0) {
766
+ result.buildingAmenities = pathFilters.buildingAmenities;
767
+ }
768
+ return result;
769
+ }
770
+
771
+ // src/applied-query.ts
772
+ function parseAppliedSearchQuery2(search) {
773
+ return parseAppliedSearchQuery(search);
774
+ }
775
+ function serializeAppliedSearchQuery2(query) {
776
+ return serializeAppliedSearchQuery(query);
777
+ }
778
+ function mergeAppliedSearchQueryIntoSearch2(existing, query) {
779
+ return mergeAppliedSearchQueryIntoSearch(existing, query);
780
+ }
781
+ function reduceAppliedSearchQuery2(prev, change) {
782
+ return reduceAppliedSearchQuery(prev, change);
783
+ }
784
+ function composeSearchPublicHref2(pathname, query, existingSearch) {
785
+ return composeSearchPublicHref(pathname, query, existingSearch);
786
+ }
787
+
788
+ // src/loc-params.ts
789
+ function pathLocationToFilterInput(location) {
790
+ if (!location || typeof location !== "object") return null;
791
+ const { state, city, neighborhood, street } = location;
792
+ const levels = [];
793
+ if (state) levels.push(state);
794
+ if (city) levels.push(city);
795
+ if (neighborhood) levels.push(neighborhood);
796
+ if (street) levels.push(street);
797
+ if (levels.length === 0) return null;
798
+ if (levels.length === 1) {
799
+ if (state) return { type: "state", value: state };
800
+ if (city) return { type: "city", value: city };
801
+ if (neighborhood) return { type: "neighborhood", value: neighborhood };
802
+ if (street) return { type: "street", value: street };
803
+ }
804
+ return { type: "path", value: levels.join("/") };
805
+ }
806
+
807
+ // src/resolve-site-id.ts
808
+ var PREVIEW_HOST_SUFFIXES = [".vusercontent.net"];
809
+ function isStudioPreviewHost(host) {
810
+ const normalized = stripPort(host);
811
+ if (normalized === "localhost" || normalized === "127.0.0.1") return true;
812
+ return PREVIEW_HOST_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
813
+ }
814
+ function stripPort(host) {
815
+ return host.trim().toLowerCase().split(":")[0] ?? "";
816
+ }
817
+ async function resolvePublicSiteId(options) {
818
+ const fallback = options.fallback?.trim() ?? "";
819
+ const host = options.host ? stripPort(options.host) : "";
820
+ if (host && !isStudioPreviewHost(host)) {
821
+ const site = await getSite({
822
+ domain: host,
823
+ baseUrl: options.baseUrl,
824
+ fetch: options.fetch
825
+ });
826
+ if (site?.id) return site.id;
827
+ throw new GaragemSdkError(
828
+ `Garagem SDK: no published site found for domain "${host}"`,
829
+ { status: 404, url: host }
830
+ );
831
+ }
832
+ if (fallback) return fallback;
833
+ throw new GaragemSdkError(
834
+ "Garagem SDK: could not resolve a site id (no host match and no fallback)",
835
+ { status: 404, url: host || "fallback" }
836
+ );
837
+ }
160
838
 
161
839
  // src/client.ts
162
840
  function createGaragemClient(options = {}) {
@@ -173,26 +851,28 @@ function createGaragemClient(options = {}) {
173
851
  if (!options.next && !callNext) return void 0;
174
852
  return { ...options.next, ...callNext };
175
853
  };
854
+ const withDefaults = (opts) => {
855
+ const out = { ...opts };
856
+ if (options.baseUrl !== void 0) out.baseUrl = options.baseUrl;
857
+ if (options.fetch !== void 0) out.fetch = options.fetch;
858
+ return out;
859
+ };
176
860
  return {
177
861
  options: Object.freeze({ ...options }),
178
862
  async getListings({ filters, siteId, next } = {}) {
179
- const opts = {
863
+ const opts = withDefaults({
180
864
  siteId: resolveSiteId(siteId)
181
- };
865
+ });
182
866
  if (filters !== void 0) opts.filters = filters;
183
- if (options.baseUrl !== void 0) opts.baseUrl = options.baseUrl;
184
- if (options.fetch !== void 0) opts.fetch = options.fetch;
185
867
  const merged = mergeNext(next);
186
868
  if (merged !== void 0) opts.next = merged;
187
869
  return getListings(opts);
188
870
  },
189
871
  async getListing({ listingId, siteId, next }) {
190
- const opts = {
872
+ const opts = withDefaults({
191
873
  siteId: resolveSiteId(siteId),
192
874
  listingId
193
- };
194
- if (options.baseUrl !== void 0) opts.baseUrl = options.baseUrl;
195
- if (options.fetch !== void 0) opts.fetch = options.fetch;
875
+ });
196
876
  const merged = mergeNext(next);
197
877
  if (merged !== void 0) opts.next = merged;
198
878
  return getListing(opts);
@@ -212,25 +892,108 @@ function createGaragemClient(options = {}) {
212
892
  siteId,
213
893
  next
214
894
  }) {
215
- const opts = {
895
+ const opts = withDefaults({
216
896
  siteId: resolveSiteId(siteId),
217
897
  params
218
- };
219
- if (options.baseUrl !== void 0) opts.baseUrl = options.baseUrl;
220
- if (options.fetch !== void 0) opts.fetch = options.fetch;
898
+ });
221
899
  const merged = mergeNext(next);
222
900
  if (merged !== void 0) opts.next = merged;
223
901
  return searchListings(opts);
902
+ },
903
+ async getSearchUi({ siteId, next } = {}) {
904
+ const opts = withDefaults({
905
+ siteId: resolveSiteId(siteId)
906
+ });
907
+ const merged = mergeNext(next);
908
+ if (merged !== void 0) opts.next = merged;
909
+ return getSearchUi(opts);
910
+ },
911
+ async queryListings({ params, siteId, next } = {}) {
912
+ const opts = withDefaults({
913
+ siteId: resolveSiteId(siteId)
914
+ });
915
+ if (params !== void 0) opts.params = params;
916
+ const merged = mergeNext(next);
917
+ if (merged !== void 0) opts.next = merged;
918
+ return queryListings(opts);
919
+ },
920
+ async getSimilarListings({ listingId, limit, siteId, next }) {
921
+ const opts = withDefaults({
922
+ siteId: resolveSiteId(siteId),
923
+ listingId
924
+ });
925
+ if (limit !== void 0) opts.limit = limit;
926
+ const merged = mergeNext(next);
927
+ if (merged !== void 0) opts.next = merged;
928
+ return getSimilarListings(opts);
929
+ },
930
+ async getCmsCollections({ siteId, next } = {}) {
931
+ const opts = withDefaults({
932
+ siteId: resolveSiteId(siteId)
933
+ });
934
+ const merged = mergeNext(next);
935
+ if (merged !== void 0) opts.next = merged;
936
+ return getCmsCollections(opts);
937
+ },
938
+ async getCmsCollection({ slug, siteId, next }) {
939
+ const opts = withDefaults({
940
+ siteId: resolveSiteId(siteId),
941
+ slug
942
+ });
943
+ const merged = mergeNext(next);
944
+ if (merged !== void 0) opts.next = merged;
945
+ return getCmsCollection(opts);
946
+ },
947
+ async getCmsEntries({ collection, limit, offset, siteId, next }) {
948
+ const opts = withDefaults({
949
+ siteId: resolveSiteId(siteId),
950
+ collection
951
+ });
952
+ if (limit !== void 0) opts.limit = limit;
953
+ if (offset !== void 0) opts.offset = offset;
954
+ const merged = mergeNext(next);
955
+ if (merged !== void 0) opts.next = merged;
956
+ return getCmsEntries(opts);
957
+ },
958
+ async getCmsEntry({ collection, slug, siteId, next }) {
959
+ const opts = withDefaults({
960
+ siteId: resolveSiteId(siteId),
961
+ collection,
962
+ slug
963
+ });
964
+ const merged = mergeNext(next);
965
+ if (merged !== void 0) opts.next = merged;
966
+ return getCmsEntry(opts);
224
967
  }
225
968
  };
226
969
  }
227
970
  // Annotate the CommonJS export names for ESM import in node:
228
971
  0 && (module.exports = {
229
972
  GaragemSdkError,
973
+ composeSearchPublicHref,
974
+ composeSearchPublicPath,
230
975
  createGaragemClient,
976
+ getCmsCollection,
977
+ getCmsCollections,
978
+ getCmsEntries,
979
+ getCmsEntry,
231
980
  getListing,
232
981
  getListings,
982
+ getSearchUi,
983
+ getSimilarListings,
233
984
  getSite,
234
- searchListings
985
+ isStudioPreviewHost,
986
+ listingLookupKey,
987
+ listingPublicPath,
988
+ mergeAppliedSearchQueryIntoSearch,
989
+ parseAppliedSearchQuery,
990
+ parseSearchPublicPath,
991
+ pathFiltersToQueryFilters,
992
+ pathLocationToFilterInput,
993
+ queryListings,
994
+ reduceAppliedSearchQuery,
995
+ resolvePublicSiteId,
996
+ searchListings,
997
+ serializeAppliedSearchQuery
235
998
  });
236
999
  //# sourceMappingURL=index.js.map