@garagem-ai/site-sdk 0.12.0 → 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/react.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as SearchUi, J as Listing, ai as LocationNameTables, S as SearchPathFilters, A as AppliedSearchQuery, bp as MapSearchSubscription, an as MapBounds, as as MapPolygon, au as MapSearchResult, ar as MapPinCluster, O as PhotoSearchItem, U as ListingWithMatchedPhoto, F as FetchLike } from './types-photo-search-Bmf1f1-Y.mjs';
1
+ import { k as SearchUi, a as Listing, ai as LocationNameTables, S as SearchPathFilters, A as AppliedSearchQuery, bp as MapSearchSubscription, an as MapBounds, as as MapPolygon, au as MapSearchResult, ar as MapPinCluster, O as PhotoSearchItem, U as ListingWithMatchedPhoto, F as FetchLike } from './types-photo-search-BPLxl65M.mjs';
2
2
 
3
3
  type SiteIdInput = string | Promise<string> | (() => string | Promise<string>);
4
4
  type PublicSearchSnapshot = {
package/dist/react.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as SearchUi, J as Listing, ai as LocationNameTables, S as SearchPathFilters, A as AppliedSearchQuery, bp as MapSearchSubscription, an as MapBounds, as as MapPolygon, au as MapSearchResult, ar as MapPinCluster, O as PhotoSearchItem, U as ListingWithMatchedPhoto, F as FetchLike } from './types-photo-search-Bmf1f1-Y.js';
1
+ import { k as SearchUi, a as Listing, ai as LocationNameTables, S as SearchPathFilters, A as AppliedSearchQuery, bp as MapSearchSubscription, an as MapBounds, as as MapPolygon, au as MapSearchResult, ar as MapPinCluster, O as PhotoSearchItem, U as ListingWithMatchedPhoto, F as FetchLike } from './types-photo-search-BPLxl65M.js';
2
2
 
3
3
  type SiteIdInput = string | Promise<string> | (() => string | Promise<string>);
4
4
  type PublicSearchSnapshot = {
package/dist/react.js CHANGED
@@ -32,197 +32,6 @@ module.exports = __toCommonJS(react_exports);
32
32
  var import_react = require("react");
33
33
  var import_navigation = require("next/navigation");
34
34
 
35
- // src/listing-path.ts
36
- function listingPublicPath(listing) {
37
- const composed = listing.path?.trim() ?? "";
38
- if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
39
- const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
40
- if (!identity || identity === "undefined" || identity === "null") {
41
- throw new TypeError("listingPublicPath: listing has no listingCode or id");
42
- }
43
- return `/imoveis/id-${identity}`;
44
- }
45
-
46
- // src/internal/sdk-http.ts
47
- var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
48
- function publishableKeyHeaders(publishableKey) {
49
- const key = publishableKey?.trim();
50
- if (!key) return {};
51
- return { [PUBLISHABLE_KEY_HEADER]: key };
52
- }
53
- function withPublishableKeyHeader(init, publishableKey) {
54
- const extra = publishableKeyHeaders(publishableKey);
55
- if (Object.keys(extra).length === 0) return init;
56
- const current = init.headers;
57
- const base = plainHeaders(current);
58
- return { ...init, headers: { ...base, ...extra } };
59
- }
60
- function plainHeaders(headers) {
61
- const out = {};
62
- if (!headers) return out;
63
- if (typeof Headers !== "undefined" && headers instanceof Headers) {
64
- headers.forEach((value, name) => {
65
- out[name] = value;
66
- });
67
- return out;
68
- }
69
- if (Array.isArray(headers)) {
70
- for (const pair of headers) {
71
- out[String(pair[0])] = String(pair[1]);
72
- }
73
- return out;
74
- }
75
- for (const [name, value] of Object.entries(
76
- headers
77
- )) {
78
- if (typeof value === "string") out[name] = value;
79
- }
80
- return out;
81
- }
82
- function finiteNonNegative(value) {
83
- if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
84
- return value;
85
- }
86
- if (typeof value === "string" && value.trim()) {
87
- const parsed = Number(value);
88
- if (Number.isFinite(parsed) && parsed >= 0) return parsed;
89
- }
90
- return null;
91
- }
92
- function parseSdkErrorBody(text) {
93
- const raw = text ? text.slice(0, 200) : "";
94
- if (!text) {
95
- return { reason: null, retryAfterSeconds: null, summary: "" };
96
- }
97
- try {
98
- const body = JSON.parse(text);
99
- if (!body || typeof body !== "object") {
100
- return { reason: null, retryAfterSeconds: null, summary: raw };
101
- }
102
- const record = body;
103
- const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
104
- const retryAfterSeconds = finiteNonNegative(
105
- record.retryAfterSeconds ?? record.retryAfter
106
- );
107
- const errorText = typeof record.error === "string" && record.error ? record.error : raw;
108
- return {
109
- reason,
110
- retryAfterSeconds,
111
- summary: errorText.slice(0, 200)
112
- };
113
- } catch {
114
- return { reason: null, retryAfterSeconds: null, summary: raw };
115
- }
116
- }
117
- function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
118
- const header = response.headers.get("Retry-After")?.trim();
119
- if (header) {
120
- const delta = finiteNonNegative(header);
121
- if (delta != null) return delta;
122
- const at = Date.parse(header);
123
- if (Number.isFinite(at)) {
124
- return Math.max(0, Math.ceil((at - nowMs) / 1e3));
125
- }
126
- }
127
- return bodySeconds;
128
- }
129
-
130
- // src/internal/url.ts
131
- var DEFAULT_BASE_URL = "https://app.garagem.ai";
132
- function normalizeBaseUrl(baseUrl) {
133
- const url = baseUrl ?? DEFAULT_BASE_URL;
134
- return url.endsWith("/") ? url.slice(0, -1) : url;
135
- }
136
- async function coerceSiteId(siteId) {
137
- const raw = typeof siteId === "function" ? siteId() : siteId;
138
- const value = await Promise.resolve(raw);
139
- if (typeof value !== "string" || !value.trim()) {
140
- throw new TypeError(
141
- "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
142
- );
143
- }
144
- return value;
145
- }
146
-
147
- // src/fetchers.ts
148
- async function callJson(url, init, fetchImpl, publishableKey) {
149
- const response = await fetchImpl(
150
- url,
151
- withPublishableKeyHeader(init, publishableKey)
152
- );
153
- if (!response.ok) {
154
- throw await readGaragemSdkError(response, url);
155
- }
156
- return await response.json();
157
- }
158
- var GaragemSdkError = class extends Error {
159
- status;
160
- url;
161
- /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
162
- reason;
163
- /**
164
- * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
165
- * or the body's `retryAfterSeconds`. `null` when the response has neither.
166
- */
167
- retryAfter;
168
- constructor(message, info) {
169
- super(message);
170
- this.name = "GaragemSdkError";
171
- this.status = info.status;
172
- this.url = info.url;
173
- this.reason = info.reason ?? null;
174
- this.retryAfter = info.retryAfter ?? null;
175
- }
176
- };
177
- async function readGaragemSdkError(response, url) {
178
- const text = await response.text().catch(() => "");
179
- const parsed = parseSdkErrorBody(text);
180
- const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
181
- const detail = parsed.summary;
182
- return new GaragemSdkError(
183
- `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
184
- {
185
- status: response.status,
186
- url,
187
- reason: parsed.reason,
188
- retryAfter
189
- }
190
- );
191
- }
192
- async function getSearchUi(options) {
193
- const { baseUrl, fetch: fetchImpl, next } = options;
194
- const siteId = await coerceSiteId(options.siteId);
195
- const base = normalizeBaseUrl(baseUrl);
196
- const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
197
- return callJson(
198
- url,
199
- { method: "GET", headers: { Accept: "application/json" }, next },
200
- fetchImpl ?? fetch,
201
- options.publishableKey
202
- );
203
- }
204
- async function queryListings(options) {
205
- const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
206
- const siteId = await coerceSiteId(options.siteId);
207
- const base = normalizeBaseUrl(baseUrl);
208
- const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
209
- return callJson(
210
- url,
211
- {
212
- method: "POST",
213
- headers: {
214
- Accept: "application/json",
215
- "Content-Type": "application/json"
216
- },
217
- body: JSON.stringify(params ?? {}),
218
- next,
219
- signal
220
- },
221
- fetchImpl ?? fetch,
222
- options.publishableKey
223
- );
224
- }
225
-
226
35
  // ../search-url/types.ts
227
36
  var SEARCH_BASE_ROUTE = "imoveis";
228
37
  var MAX_PAGE = 1e4;
@@ -823,6 +632,16 @@ function applyPathFilter(pathFilters, filterId, value) {
823
632
  }
824
633
  return next;
825
634
  }
635
+ function changedPathFilters(current, next) {
636
+ const changed = [];
637
+ for (const [filterId, key] of Object.entries(PATH_FILTER_IDS)) {
638
+ const before = current?.[key];
639
+ const after = next?.[key];
640
+ if (JSON.stringify(before) === JSON.stringify(after)) continue;
641
+ changed.push({ filterId, value: after });
642
+ }
643
+ return changed;
644
+ }
826
645
  function publicSearchHref(pathFilters, applied, dictionary, existingSearch) {
827
646
  const pathname = composeSearchPublicPath2(pathFilters || {}, dictionary);
828
647
  return composeSearchPublicHref2(pathname, applied || {}, existingSearch);
@@ -876,6 +695,265 @@ function clearStagedPathFilters(current, keepFilterIds = []) {
876
695
  return next;
877
696
  }
878
697
 
698
+ // src/analytics.ts
699
+ var SITE_ANALYTICS_EVENT = "garagem:site-event";
700
+ function emitSiteEvent(event, properties) {
701
+ if (typeof window === "undefined") return;
702
+ window.dispatchEvent(
703
+ new CustomEvent(SITE_ANALYTICS_EVENT, { detail: { event, properties } })
704
+ );
705
+ }
706
+ function catalogBusinessType(value) {
707
+ return value === "sale" || value === "rental" ? value : void 0;
708
+ }
709
+ function minOf(value) {
710
+ if (!Array.isArray(value)) return value;
711
+ return value.length ? Math.min(...value) : void 0;
712
+ }
713
+ function trackSearchResults(input) {
714
+ const { pathFilters, applied, listingIds, page } = input;
715
+ const location = displayPathLocation(
716
+ pathFilters.location,
717
+ input.locationNames
718
+ );
719
+ emitSiteEvent("property_search", {
720
+ query: applied.query || void 0,
721
+ business_type: catalogBusinessType(pathFilters.listingType),
722
+ property_type: pathFilters.propertyType,
723
+ location_city: location?.city,
724
+ location_neighborhood: location?.neighborhood,
725
+ min_price: pathFilters.price?.min,
726
+ max_price: pathFilters.price?.max,
727
+ min_bedrooms: minOf(pathFilters.bedrooms),
728
+ min_area: pathFilters.area?.min,
729
+ max_area: pathFilters.area?.max,
730
+ result_count: input.total,
731
+ page,
732
+ sort_by: applied.sort || void 0
733
+ });
734
+ if (!listingIds.length) return;
735
+ emitSiteEvent("listings_impressed", {
736
+ property_ids: listingIds,
737
+ impression_count: listingIds.length,
738
+ source: "search",
739
+ page
740
+ });
741
+ }
742
+ function filterValue(value) {
743
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
744
+ return value;
745
+ }
746
+ if (Array.isArray(value)) return value.map(String);
747
+ if (value && typeof value === "object") {
748
+ const { min, max } = value;
749
+ return `${min ?? ""}-${max ?? ""}`;
750
+ }
751
+ return "";
752
+ }
753
+ function trackFilterApplied(filterId, value) {
754
+ emitSiteEvent("filter_applied", {
755
+ filter_name: filterId,
756
+ filter_value: filterValue(value),
757
+ ...value == null ? { filter_action: "clear" } : {}
758
+ });
759
+ }
760
+ function trackStagedFiltersApplied(current, staged) {
761
+ for (const { filterId, value } of changedPathFilters(current, staged)) {
762
+ trackFilterApplied(filterId, value);
763
+ }
764
+ }
765
+
766
+ // src/listing-path.ts
767
+ function listingPublicPath(listing) {
768
+ const composed = listing.path?.trim() ?? "";
769
+ if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
770
+ const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
771
+ if (!identity || identity === "undefined" || identity === "null") {
772
+ throw new TypeError("listingPublicPath: listing has no listingCode or id");
773
+ }
774
+ return `/imoveis/id-${identity}`;
775
+ }
776
+
777
+ // src/internal/sdk-http.ts
778
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
779
+ function publishableKeyHeaders(publishableKey) {
780
+ const key = publishableKey?.trim();
781
+ if (!key) return {};
782
+ return { [PUBLISHABLE_KEY_HEADER]: key };
783
+ }
784
+ function withPublishableKeyHeader(init, publishableKey) {
785
+ const extra = publishableKeyHeaders(publishableKey);
786
+ if (Object.keys(extra).length === 0) return init;
787
+ const current = init.headers;
788
+ const base = plainHeaders(current);
789
+ return { ...init, headers: { ...base, ...extra } };
790
+ }
791
+ function plainHeaders(headers) {
792
+ const out = {};
793
+ if (!headers) return out;
794
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
795
+ headers.forEach((value, name) => {
796
+ out[name] = value;
797
+ });
798
+ return out;
799
+ }
800
+ if (Array.isArray(headers)) {
801
+ for (const pair of headers) {
802
+ out[String(pair[0])] = String(pair[1]);
803
+ }
804
+ return out;
805
+ }
806
+ for (const [name, value] of Object.entries(
807
+ headers
808
+ )) {
809
+ if (typeof value === "string") out[name] = value;
810
+ }
811
+ return out;
812
+ }
813
+ function finiteNonNegative(value) {
814
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
815
+ return value;
816
+ }
817
+ if (typeof value === "string" && value.trim()) {
818
+ const parsed = Number(value);
819
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
820
+ }
821
+ return null;
822
+ }
823
+ function parseSdkErrorBody(text) {
824
+ const raw = text ? text.slice(0, 200) : "";
825
+ if (!text) {
826
+ return { reason: null, retryAfterSeconds: null, summary: "" };
827
+ }
828
+ try {
829
+ const body = JSON.parse(text);
830
+ if (!body || typeof body !== "object") {
831
+ return { reason: null, retryAfterSeconds: null, summary: raw };
832
+ }
833
+ const record = body;
834
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
835
+ const retryAfterSeconds = finiteNonNegative(
836
+ record.retryAfterSeconds ?? record.retryAfter
837
+ );
838
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
839
+ return {
840
+ reason,
841
+ retryAfterSeconds,
842
+ summary: errorText.slice(0, 200)
843
+ };
844
+ } catch {
845
+ return { reason: null, retryAfterSeconds: null, summary: raw };
846
+ }
847
+ }
848
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
849
+ const header = response.headers.get("Retry-After")?.trim();
850
+ if (header) {
851
+ const delta = finiteNonNegative(header);
852
+ if (delta != null) return delta;
853
+ const at = Date.parse(header);
854
+ if (Number.isFinite(at)) {
855
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
856
+ }
857
+ }
858
+ return bodySeconds;
859
+ }
860
+
861
+ // src/internal/url.ts
862
+ var DEFAULT_BASE_URL = "https://app.garagem.ai";
863
+ function normalizeBaseUrl(baseUrl) {
864
+ const url = baseUrl ?? DEFAULT_BASE_URL;
865
+ return url.endsWith("/") ? url.slice(0, -1) : url;
866
+ }
867
+ async function coerceSiteId(siteId) {
868
+ const raw = typeof siteId === "function" ? siteId() : siteId;
869
+ const value = await Promise.resolve(raw);
870
+ if (typeof value !== "string" || !value.trim()) {
871
+ throw new TypeError(
872
+ "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
873
+ );
874
+ }
875
+ return value;
876
+ }
877
+
878
+ // src/fetchers.ts
879
+ async function callJson(url, init, fetchImpl, publishableKey) {
880
+ const response = await fetchImpl(
881
+ url,
882
+ withPublishableKeyHeader(init, publishableKey)
883
+ );
884
+ if (!response.ok) {
885
+ throw await readGaragemSdkError(response, url);
886
+ }
887
+ return await response.json();
888
+ }
889
+ var GaragemSdkError = class extends Error {
890
+ status;
891
+ url;
892
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
893
+ reason;
894
+ /**
895
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
896
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
897
+ */
898
+ retryAfter;
899
+ constructor(message, info) {
900
+ super(message);
901
+ this.name = "GaragemSdkError";
902
+ this.status = info.status;
903
+ this.url = info.url;
904
+ this.reason = info.reason ?? null;
905
+ this.retryAfter = info.retryAfter ?? null;
906
+ }
907
+ };
908
+ async function readGaragemSdkError(response, url) {
909
+ const text = await response.text().catch(() => "");
910
+ const parsed = parseSdkErrorBody(text);
911
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
912
+ const detail = parsed.summary;
913
+ return new GaragemSdkError(
914
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
915
+ {
916
+ status: response.status,
917
+ url,
918
+ reason: parsed.reason,
919
+ retryAfter
920
+ }
921
+ );
922
+ }
923
+ async function getSearchUi(options) {
924
+ const { baseUrl, fetch: fetchImpl, next } = options;
925
+ const siteId = await coerceSiteId(options.siteId);
926
+ const base = normalizeBaseUrl(baseUrl);
927
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
928
+ return callJson(
929
+ url,
930
+ { method: "GET", headers: { Accept: "application/json" }, next },
931
+ fetchImpl ?? fetch,
932
+ options.publishableKey
933
+ );
934
+ }
935
+ async function queryListings(options) {
936
+ const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
937
+ const siteId = await coerceSiteId(options.siteId);
938
+ const base = normalizeBaseUrl(baseUrl);
939
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
940
+ return callJson(
941
+ url,
942
+ {
943
+ method: "POST",
944
+ headers: {
945
+ Accept: "application/json",
946
+ "Content-Type": "application/json"
947
+ },
948
+ body: JSON.stringify(params ?? {}),
949
+ next,
950
+ signal
951
+ },
952
+ fetchImpl ?? fetch,
953
+ options.publishableKey
954
+ );
955
+ }
956
+
879
957
  // src/react/public-search-snapshot.ts
880
958
  function hrefParts(href) {
881
959
  const q = href.indexOf("?");
@@ -925,6 +1003,13 @@ function shouldPreservePaintedListingsOnRefetchFailure(options) {
925
1003
  options.dictionary
926
1004
  );
927
1005
  }
1006
+ function shouldTrackSearchResults(options) {
1007
+ return !searchKeysRepresentSameQuery(
1008
+ options.trackedSearchKey,
1009
+ options.searchKey,
1010
+ options.dictionary
1011
+ );
1012
+ }
928
1013
  function initialQueryDraft(pathname, search, dictionary) {
929
1014
  return readPublicSearch(pathname, search, dictionary).applied.query || "";
930
1015
  }
@@ -1025,6 +1110,7 @@ function usePublicSearch(options) {
1025
1110
  replaceStaged({ ...parsed.pathFilters });
1026
1111
  }, [parsed.pathFilters, replaceStaged]);
1027
1112
  const locationsRef = (0, import_react.useRef)(seed.locationNames);
1113
+ const trackedSearchKeyRef = (0, import_react.useRef)(null);
1028
1114
  (0, import_react.useEffect)(() => {
1029
1115
  if (!schema) return;
1030
1116
  const canonical = canonicalizeSearchHref(
@@ -1150,6 +1236,21 @@ function usePublicSearch(options) {
1150
1236
  )
1151
1237
  });
1152
1238
  if (!active) return;
1239
+ if (shouldTrackSearchResults({
1240
+ trackedSearchKey: trackedSearchKeyRef.current,
1241
+ searchKey,
1242
+ dictionary: currentSchema.dictionary
1243
+ })) {
1244
+ trackedSearchKeyRef.current = searchKey;
1245
+ trackSearchResults({
1246
+ pathFilters,
1247
+ applied,
1248
+ locationNames: locationsRef.current,
1249
+ listingIds: (response.listings || []).map((listing) => listing.id),
1250
+ total: response.total || 0,
1251
+ page: response.page || 1
1252
+ });
1253
+ }
1153
1254
  setListings(response.listings || []);
1154
1255
  setPage(response.page || 1);
1155
1256
  setTotal(response.total || 0);
@@ -1188,6 +1289,7 @@ function usePublicSearch(options) {
1188
1289
  const applyFilter = (0, import_react.useCallback)(
1189
1290
  (filterId, value) => {
1190
1291
  if (!schema) return;
1292
+ trackFilterApplied(filterId, value);
1191
1293
  go(
1192
1294
  hrefForPathFilters(
1193
1295
  pathname,
@@ -1210,6 +1312,10 @@ function usePublicSearch(options) {
1210
1312
  }, []);
1211
1313
  const applyStaged = (0, import_react.useCallback)(() => {
1212
1314
  if (!schema) return;
1315
+ trackStagedFiltersApplied(
1316
+ parsed.pathFilters,
1317
+ stagedMirrorRef.current.value
1318
+ );
1213
1319
  go(
1214
1320
  hrefForPathFilters(
1215
1321
  pathname,
@@ -1218,7 +1324,7 @@ function usePublicSearch(options) {
1218
1324
  stagedMirrorRef.current.value
1219
1325
  )
1220
1326
  );
1221
- }, [go, pathname, search, schema]);
1327
+ }, [go, pathname, search, schema, parsed.pathFilters]);
1222
1328
  const clearStaged = (0, import_react.useCallback)(() => {
1223
1329
  setStagedState(stagedMirrorRef.current.clear());
1224
1330
  }, []);