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