@garagem-ai/site-sdk 0.7.0 → 0.8.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
@@ -12,6 +12,90 @@ function listingPublicPath(listing) {
12
12
  return `/imoveis/id-${identity}`;
13
13
  }
14
14
 
15
+ // src/internal/sdk-http.ts
16
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
17
+ function publishableKeyHeaders(publishableKey) {
18
+ const key = publishableKey?.trim();
19
+ if (!key) return {};
20
+ return { [PUBLISHABLE_KEY_HEADER]: key };
21
+ }
22
+ function withPublishableKeyHeader(init, publishableKey) {
23
+ const extra = publishableKeyHeaders(publishableKey);
24
+ if (Object.keys(extra).length === 0) return init;
25
+ const current = init.headers;
26
+ const base = plainHeaders(current);
27
+ return { ...init, headers: { ...base, ...extra } };
28
+ }
29
+ function plainHeaders(headers) {
30
+ const out = {};
31
+ if (!headers) return out;
32
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
33
+ headers.forEach((value, name) => {
34
+ out[name] = value;
35
+ });
36
+ return out;
37
+ }
38
+ if (Array.isArray(headers)) {
39
+ for (const pair of headers) {
40
+ out[String(pair[0])] = String(pair[1]);
41
+ }
42
+ return out;
43
+ }
44
+ for (const [name, value] of Object.entries(
45
+ headers
46
+ )) {
47
+ if (typeof value === "string") out[name] = value;
48
+ }
49
+ return out;
50
+ }
51
+ function finiteNonNegative(value) {
52
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
53
+ return value;
54
+ }
55
+ if (typeof value === "string" && value.trim()) {
56
+ const parsed = Number(value);
57
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
58
+ }
59
+ return null;
60
+ }
61
+ function parseSdkErrorBody(text) {
62
+ const raw = text ? text.slice(0, 200) : "";
63
+ if (!text) {
64
+ return { reason: null, retryAfterSeconds: null, summary: "" };
65
+ }
66
+ try {
67
+ const body = JSON.parse(text);
68
+ if (!body || typeof body !== "object") {
69
+ return { reason: null, retryAfterSeconds: null, summary: raw };
70
+ }
71
+ const record = body;
72
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
73
+ const retryAfterSeconds = finiteNonNegative(
74
+ record.retryAfterSeconds ?? record.retryAfter
75
+ );
76
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
77
+ return {
78
+ reason,
79
+ retryAfterSeconds,
80
+ summary: errorText.slice(0, 200)
81
+ };
82
+ } catch {
83
+ return { reason: null, retryAfterSeconds: null, summary: raw };
84
+ }
85
+ }
86
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
87
+ const header = response.headers.get("Retry-After")?.trim();
88
+ if (header) {
89
+ const delta = finiteNonNegative(header);
90
+ if (delta != null) return delta;
91
+ const at = Date.parse(header);
92
+ if (Number.isFinite(at)) {
93
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
94
+ }
95
+ }
96
+ return bodySeconds;
97
+ }
98
+
15
99
  // src/internal/url.ts
16
100
  var DEFAULT_BASE_URL = "https://app.garagem.ai";
17
101
  var DEFAULT_RESOLVE_BASE_URL = "https://cdn.fndn.ai/site";
@@ -46,27 +130,50 @@ function buildListingFiltersQuery(filters) {
46
130
  }
47
131
 
48
132
  // src/fetchers.ts
49
- async function callJson(url, init, fetchImpl) {
50
- const response = await fetchImpl(url, init);
133
+ async function callJson(url, init, fetchImpl, publishableKey) {
134
+ const response = await fetchImpl(
135
+ url,
136
+ withPublishableKeyHeader(init, publishableKey)
137
+ );
51
138
  if (!response.ok) {
52
- const text = await response.text().catch(() => "");
53
- throw new GaragemSdkError(
54
- `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text ? ` \u2014 ${text.slice(0, 200)}` : ""}`,
55
- { status: response.status, url }
56
- );
139
+ throw await readGaragemSdkError(response, url);
57
140
  }
58
141
  return await response.json();
59
142
  }
60
143
  var GaragemSdkError = class extends Error {
61
144
  status;
62
145
  url;
146
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
147
+ reason;
148
+ /**
149
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
150
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
151
+ */
152
+ retryAfter;
63
153
  constructor(message, info) {
64
154
  super(message);
65
155
  this.name = "GaragemSdkError";
66
156
  this.status = info.status;
67
157
  this.url = info.url;
158
+ this.reason = info.reason ?? null;
159
+ this.retryAfter = info.retryAfter ?? null;
68
160
  }
69
161
  };
162
+ async function readGaragemSdkError(response, url) {
163
+ const text = await response.text().catch(() => "");
164
+ const parsed = parseSdkErrorBody(text);
165
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
166
+ const detail = parsed.summary;
167
+ return new GaragemSdkError(
168
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
169
+ {
170
+ status: response.status,
171
+ url,
172
+ reason: parsed.reason,
173
+ retryAfter
174
+ }
175
+ );
176
+ }
70
177
  async function getListings(options) {
71
178
  const { filters, baseUrl, fetch: fetchImpl, next } = options;
72
179
  const siteId = await coerceSiteId(options.siteId);
@@ -77,7 +184,8 @@ async function getListings(options) {
77
184
  const data = await callJson(
78
185
  url,
79
186
  { method: "GET", headers: { Accept: "application/json" }, next },
80
- fetchImpl ?? fetch
187
+ fetchImpl ?? fetch,
188
+ options.publishableKey
81
189
  );
82
190
  return {
83
191
  listings: data.listings ?? [],
@@ -98,7 +206,8 @@ async function getListing(options) {
98
206
  return callJson(
99
207
  url,
100
208
  { method: "GET", headers: { Accept: "application/json" }, next },
101
- fetchImpl ?? fetch
209
+ fetchImpl ?? fetch,
210
+ options.publishableKey
102
211
  );
103
212
  }
104
213
  async function getSite(options) {
@@ -120,17 +229,20 @@ async function getSite(options) {
120
229
  if (domain) params.set("domain", domain);
121
230
  const url = `${base}/api/sites/resolve?${params.toString()}`;
122
231
  const f = fetchImpl ?? fetch;
123
- const response = await f(url, {
124
- method: "GET",
125
- headers: { Accept: "application/json" },
126
- next
127
- });
232
+ const response = await f(
233
+ url,
234
+ withPublishableKeyHeader(
235
+ {
236
+ method: "GET",
237
+ headers: { Accept: "application/json" },
238
+ next
239
+ },
240
+ options.publishableKey
241
+ )
242
+ );
128
243
  if (response.status === 404) return null;
129
244
  if (!response.ok) {
130
- throw new GaragemSdkError(
131
- `Garagem SDK: getSite failed (${response.status}) for ${url}`,
132
- { status: response.status, url }
133
- );
245
+ throw await readGaragemSdkError(response, url);
134
246
  }
135
247
  const data = await response.json();
136
248
  return {
@@ -158,7 +270,8 @@ async function searchListings(options) {
158
270
  body: JSON.stringify(params),
159
271
  next
160
272
  },
161
- fetchImpl ?? fetch
273
+ fetchImpl ?? fetch,
274
+ options.publishableKey
162
275
  );
163
276
  }
164
277
  async function getSearchUi(options) {
@@ -169,7 +282,8 @@ async function getSearchUi(options) {
169
282
  return callJson(
170
283
  url,
171
284
  { method: "GET", headers: { Accept: "application/json" }, next },
172
- fetchImpl ?? fetch
285
+ fetchImpl ?? fetch,
286
+ options.publishableKey
173
287
  );
174
288
  }
175
289
  async function queryListings(options) {
@@ -188,7 +302,8 @@ async function queryListings(options) {
188
302
  body: JSON.stringify(params ?? {}),
189
303
  next
190
304
  },
191
- fetchImpl ?? fetch
305
+ fetchImpl ?? fetch,
306
+ options.publishableKey
192
307
  );
193
308
  }
194
309
  async function getSimilarListings(options) {
@@ -216,7 +331,8 @@ async function getSimilarListings(options) {
216
331
  const data = await callJson(
217
332
  url,
218
333
  { method: "GET", headers: { Accept: "application/json" }, next },
219
- fetchImpl ?? fetch
334
+ fetchImpl ?? fetch,
335
+ options.publishableKey
220
336
  );
221
337
  return {
222
338
  listings: data.listings ?? [],
@@ -231,7 +347,8 @@ async function getCmsCollections(options) {
231
347
  const data = await callJson(
232
348
  url,
233
349
  { method: "GET", headers: { Accept: "application/json" }, next },
234
- fetchImpl ?? fetch
350
+ fetchImpl ?? fetch,
351
+ options.publishableKey
235
352
  );
236
353
  return data.collections ?? [];
237
354
  }
@@ -248,7 +365,8 @@ async function getCmsCollection(options) {
248
365
  const data = await callJson(
249
366
  url,
250
367
  { method: "GET", headers: { Accept: "application/json" }, next },
251
- fetchImpl ?? fetch
368
+ fetchImpl ?? fetch,
369
+ options.publishableKey
252
370
  );
253
371
  if (data && typeof data === "object" && "collection" in data && data.collection) {
254
372
  return data.collection;
@@ -283,7 +401,8 @@ async function getCmsEntries(options) {
283
401
  const data = await callJson(
284
402
  url,
285
403
  { method: "GET", headers: { Accept: "application/json" }, next },
286
- fetchImpl ?? fetch
404
+ fetchImpl ?? fetch,
405
+ options.publishableKey
287
406
  );
288
407
  return {
289
408
  entries: data.entries ?? [],
@@ -308,7 +427,8 @@ async function getCmsEntry(options) {
308
427
  const data = await callJson(
309
428
  url,
310
429
  { method: "GET", headers: { Accept: "application/json" }, next },
311
- fetchImpl ?? fetch
430
+ fetchImpl ?? fetch,
431
+ options.publishableKey
312
432
  );
313
433
  if (data && typeof data === "object" && "entry" in data && data.entry) {
314
434
  return data.entry;
@@ -843,7 +963,8 @@ async function resolvePublicSiteId(options) {
843
963
  const site = await getSite({
844
964
  domain: host,
845
965
  baseUrl: options.baseUrl,
846
- fetch: options.fetch
966
+ fetch: options.fetch,
967
+ publishableKey: options.publishableKey
847
968
  });
848
969
  if (site?.id) return site.id;
849
970
  throw new GaragemSdkError(
@@ -872,7 +993,8 @@ async function resolveLeadSiteId(input) {
872
993
  return resolvePublicSiteId({
873
994
  host,
874
995
  baseUrl: input.baseUrl,
875
- fetch: input.fetch
996
+ fetch: input.fetch,
997
+ publishableKey: input.publishableKey
876
998
  });
877
999
  }
878
1000
  }
@@ -880,6 +1002,8 @@ var LeadSubmitError = class extends Error {
880
1002
  code;
881
1003
  status;
882
1004
  retryAfterSeconds;
1005
+ /** Seconds to wait. Same value as `retryAfterSeconds`; `null` when unset. */
1006
+ retryAfter;
883
1007
  constructor(message, info) {
884
1008
  super(message);
885
1009
  this.name = "LeadSubmitError";
@@ -888,6 +1012,7 @@ var LeadSubmitError = class extends Error {
888
1012
  if (info.retryAfterSeconds != null) {
889
1013
  this.retryAfterSeconds = info.retryAfterSeconds;
890
1014
  }
1015
+ this.retryAfter = info.retryAfterSeconds ?? null;
891
1016
  }
892
1017
  };
893
1018
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -929,7 +1054,8 @@ async function getLeadUi(options) {
929
1054
  headers: { Accept: "application/json" },
930
1055
  next: options.next
931
1056
  },
932
- options.fetch ?? fetch
1057
+ options.fetch ?? fetch,
1058
+ options.publishableKey
933
1059
  );
934
1060
  }
935
1061
  function assertListingId(listingId) {
@@ -1002,7 +1128,8 @@ async function postSiteLead(input) {
1002
1128
  method: "POST",
1003
1129
  headers: {
1004
1130
  Accept: "application/json",
1005
- "Content-Type": "application/json"
1131
+ "Content-Type": "application/json",
1132
+ ...publishableKeyHeaders(input.publishableKey)
1006
1133
  },
1007
1134
  body: JSON.stringify(input.body)
1008
1135
  });
@@ -1017,12 +1144,23 @@ async function postSiteLead(input) {
1017
1144
  const id = typeof data.id === "string" && data.id ? data.id : "";
1018
1145
  return { ok: true, status: 202, id };
1019
1146
  }
1020
- const retryAfter = Number(response.headers.get("Retry-After") ?? "");
1147
+ if (response.status === 401) {
1148
+ throw new LeadSubmitError("Garagem SDK: invalid publishable key.", {
1149
+ code: "unauthorized",
1150
+ status: 401
1151
+ });
1152
+ }
1021
1153
  if (response.status === 429) {
1154
+ const text = await response.text().catch(() => "");
1155
+ const parsed = parseSdkErrorBody(text);
1156
+ const retryAfter = retryAfterFromResponse(
1157
+ response,
1158
+ parsed.retryAfterSeconds
1159
+ );
1022
1160
  throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
1023
1161
  code: "rate_limited",
1024
1162
  status: 429,
1025
- retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : void 0
1163
+ ...retryAfter != null ? { retryAfterSeconds: retryAfter } : {}
1026
1164
  });
1027
1165
  }
1028
1166
  if (response.status === 404) {
@@ -1066,6 +1204,7 @@ async function submitVisitLead(input) {
1066
1204
  siteId: input.siteId,
1067
1205
  baseUrl: input.baseUrl,
1068
1206
  fetch: input.fetch,
1207
+ publishableKey: input.publishableKey,
1069
1208
  body: {
1070
1209
  source: "site-sdk",
1071
1210
  leadType: "visit",
@@ -1084,6 +1223,7 @@ async function submitContactLead(input) {
1084
1223
  siteId: input.siteId,
1085
1224
  baseUrl: input.baseUrl,
1086
1225
  fetch: input.fetch,
1226
+ publishableKey: input.publishableKey,
1087
1227
  body: {
1088
1228
  source: "site-sdk",
1089
1229
  leadType: "contact",
@@ -2673,6 +2813,29 @@ var STUDIO_SDK_CONTRACT = {
2673
2813
  */
2674
2814
  unpublishedPhoneExports: [],
2675
2815
  amenityExports: ["listingAmenityGroups"],
2816
+ /**
2817
+ * Prompt-safe photo helpers on `minNpmVersion`. Empty until the release
2818
+ * that carries `getSimilarByPhoto` / `listingPhotoGroups` /
2819
+ * `listingVisualHighlights` is on npm; then bump the pin, move the names
2820
+ * here from `unpublishedPhotoExports`, and `studioPhotoInstruction()`
2821
+ * starts teaching the gallery-by-room, highlight chips, and
2822
+ * "imóveis com fotos parecidas" blocks. The caption-based `media[].alt` /
2823
+ * `media[].caption` fields are API data (not tarball exports) and are
2824
+ * documented regardless of the pin.
2825
+ */
2826
+ photoExports: [],
2827
+ /**
2828
+ * Photo helpers in the repo but not on `minNpmVersion`. Prompts,
2829
+ * completeness, and repair text must not mention these until the pin
2830
+ * bumps — v0 installs the pin and the ESM loader throws on missing named
2831
+ * exports.
2832
+ */
2833
+ unpublishedPhotoExports: [
2834
+ "getSimilarByPhoto",
2835
+ "listingPhotoGroups",
2836
+ "listingVisualHighlights",
2837
+ "photoRoomLabel"
2838
+ ],
2676
2839
  /**
2677
2840
  * Names already on the pinned npm tarball (`minNpmVersion`) — safe for
2678
2841
  * Studio prompts and completeness. Includes `visibleSearchFilters` +
@@ -2816,6 +2979,9 @@ function unavailableReactImports(source, pin) {
2816
2979
  }
2817
2980
  return missing;
2818
2981
  }
2982
+ function studioPublishableKeyInstruction() {
2983
+ return `Public site API key (optional, backwards compatible). \`publishableKey\` (\`pk_live_\u2026\`) is not a secret. Create or rotate it in Garagem at Configura\xE7\xF5es \u2192 Sites \u2192 the site \u2192 API p\xFAblica (route \`/configuracoes/sites/[siteId]\`, section API p\xFAblica (SDK)). Pass it to \`createGaragemClient({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey })\` or on each call: \`getListings\`, \`getListing\`, \`getSite\`, \`getSearchUi\`, \`queryListings\`, \`searchListings\`, the CMS helpers, \`getLeadUi\`, \`submitVisitLead\`, \`submitContactLead\`, and \`usePublicSearch\`. The SDK sends header \`X-Garagem-Publishable-Key\` (a Bearer token that starts with \`pk_live_\` is also accepted). Omitting the key still succeeds. Once a site has a key, anonymous traffic uses the stricter per-IP budget (listings/search 30/min, detail 60/min, config 30/min). A site with no key uses the looser anonymous budget (120 / 300 / 120). With the key, budgets are listings/search 600/min, detail 1200/min, config 300/min. Window is 60 seconds. Success and 429 responses carry \`RateLimit-Limit\`, \`RateLimit-Remaining\`, \`RateLimit-Reset\`, and \`RateLimit-Policy\`. HTTP 401 throws \`GaragemSdkError\` with \`status\` 401 and \`reason\` \`invalid_publishable_key\` (wrong key). HTTP 403 has \`reason\` \`origin_not_allowed\` when the site's origin allowlist rejects the browser Origin or Referer. HTTP 429 has \`reason\` \`rate_limited\` and \`retryAfter\` seconds (same value as the \`Retry-After\` header). \`LeadSubmitError\` uses \`code\` \`rate_limited\` or \`unauthorized\`, and \`retryAfter\` / \`retryAfterSeconds\` on 429. A public constant next to \`GARAGEM_API_BASE\` is the right place for the key. Do not invent a second header name.`;
2984
+ }
2819
2985
  function studioSdkPinInstruction() {
2820
2986
  const version = STUDIO_SDK_CONTRACT.minNpmVersion;
2821
2987
  const names = [...reactExportsAvailableAt(version)].join(", ");
@@ -2834,6 +3000,31 @@ function studioListingDetailInstruction() {
2834
3000
  const names = STUDIO_SDK_CONTRACT.listingDetailExports.join(", ");
2835
3001
  return `Listing detail: import ${names} from \`${STUDIO_SDK_PACKAGE}\`. Render \`listingDetailModel\` leaves: \`model.facts[].label\` / \`.text\`, \`model.values[].label\` / \`.text\`, \`model.location.label\` / \`model.location.mapsHref\`, breadcrumb \`.href\` (search prefixes of \`listing.path\`). The pre\xE7o / sob consulta entry is the primary value; condom\xEDnio and IPTU are secondary and omitted when missing. \`model.description\` is the complete string \u2014 do not slice. A collapsed disclosure uses a container (max-height or overflow), not a cut of the string. Never interpolate \`model.location\`, \`model.facts\`, \`model.values\`, \`model.breadcrumb\`, or \`model.mediaOverlays\` as a React child. Video/tour: \`model.mediaOverlays\` as hash links (\`#video\` / \`#tour\`); player src is \`embedSrc\`; fullscreen overlay closes with browser back; omit when that overlay is absent. Do not key the page on \`location.hash\`. Similar listings: \`getSimilarListings({ siteId, listingId, baseUrl })\` plus the site listing-card module; hide the section when empty. Do not invent a local recommendation loop.`;
2836
3002
  }
3003
+ function studioPhotoInstructionFor(published) {
3004
+ const has = (name) => published.includes(name);
3005
+ const parts = [
3006
+ `Gallery photo text: \`item.alt\` on \`listing.media\` is the photo caption when the platform analyzed it (else "<title> - Foto N") \u2014 always pass it as the img alt. \`item.caption\` is optional: show it as the slide / overlay caption when present and omit the element when absent. Never invent captions or room names in generated source.`
3007
+ ];
3008
+ if (has("listingPhotoGroups")) {
3009
+ parts.push(
3010
+ `Gallery by room: \`const groups = listingPhotoGroups(listing)\` from \`${STUDIO_SDK_PACKAGE}\` returns \`{ key, label, photos }[]\` (pt-BR labels such as "Sala", "Quartos", "Cozinha"; "Outras fotos" last). Use it only inside the fullscreen photo overlay (room tabs or section headings over the thumbnail strip) \u2014 the page carousel stays one flat section. Render \`group.label\` and \`group.photos.length\`; when \`groups.length <= 1\` render the flat strip without headings. Never read \`item.roomType\` / \`item.sceneType\` directly to build sections and never hardcode room names.`
3011
+ );
3012
+ }
3013
+ if (has("listingVisualHighlights")) {
3014
+ parts.push(
3015
+ `Visual highlights: \`const highlights = listingVisualHighlights(listing, { limit: 6 })\` returns deduped strings ("piso de madeira", "vista livre"). Render them as small chips (site tokens, \`--radius\`) under the gallery or beside the facts, one chip per string, and omit the block when the array is empty. Do not merge them with \`listingAmenityGroups\` and do not read \`item.features\` directly.`
3016
+ );
3017
+ }
3018
+ if (has("getSimilarByPhoto")) {
3019
+ parts.push(
3020
+ `Im\xF3veis com fotos parecidas: on the server page, pick the first image item of \`listing.media\` and \`await getSimilarByPhoto(siteId, listing.id, photo.id, { limit: 6, baseUrl: GARAGEM_API_BASE })\` from \`${STUDIO_SDK_PACKAGE}\` (positional ids; \`listing.id\` is the UUID, never the path). The result is \`{ available, items }\`: when \`available === false\` (tenant without image search, or \`photo.id\` is not a media UUID such as the \`image-N\` / \`external-N\` gallery keys \u2014 that returns locally and does not throw) render nothing \u2014 no heading, no empty state; when \`items.length === 0\` also render nothing. Otherwise a section titled "Im\xF3veis com fotos parecidas" with the site listing-card module (\`toListingCardModel(item.listing)\`), using \`item.matchedPhoto.src\` / \`item.matchedPhoto.alt\` as that card's photo. Keep \`getSimilarListings\` as the default similar carousel; this section is additional, below it. Wrap the call in try/catch and treat an error like \`available: false\`.`
3021
+ );
3022
+ }
3023
+ return parts.join(" ");
3024
+ }
3025
+ function studioPhotoInstruction() {
3026
+ return studioPhotoInstructionFor(STUDIO_SDK_CONTRACT.photoExports);
3027
+ }
2837
3028
  function studioAmenityInstruction() {
2838
3029
  return `Listing amenities: Portuguese labels from \`listingAmenityGroups(listing, dictionary)\` (pass the dictionary from \`getSearchUi()\` so section titles follow Campos). Each group is \`{ title, labels: string[] }\` \u2014 render \`group.title\` and \`group.labels.map((label) => \u2026)\` and hide a group when \`group.labels.length === 0\`. Do not hardcode section titles. Never print amenity ids, never invent a local label map, and never title a section "Comodidades da unidade".`;
2839
3030
  }
@@ -2892,6 +3083,11 @@ function studioCodegenContractViolations(text) {
2892
3083
  violations.push(name);
2893
3084
  }
2894
3085
  }
3086
+ for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
3087
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
3088
+ violations.push(name);
3089
+ }
3090
+ }
2895
3091
  if (!isPhotoSearchOnPin()) {
2896
3092
  for (const name of STUDIO_SDK_CONTRACT.photoSearchExports) {
2897
3093
  if (mentionsExportName(text, name) && !violations.includes(name)) {
@@ -2941,6 +3137,9 @@ function createGaragemClient(options = {}) {
2941
3137
  const out = { ...opts };
2942
3138
  if (options.baseUrl !== void 0) out.baseUrl = options.baseUrl;
2943
3139
  if (options.fetch !== void 0) out.fetch = options.fetch;
3140
+ if (options.publishableKey !== void 0 && out.publishableKey === void 0) {
3141
+ out.publishableKey = options.publishableKey;
3142
+ }
2944
3143
  return out;
2945
3144
  };
2946
3145
  return {
@@ -2969,6 +3168,9 @@ function createGaragemClient(options = {}) {
2969
3168
  if (domain !== void 0) opts.domain = domain;
2970
3169
  if (options.baseUrl !== void 0) opts.baseUrl = options.baseUrl;
2971
3170
  if (options.fetch !== void 0) opts.fetch = options.fetch;
3171
+ if (options.publishableKey !== void 0) {
3172
+ opts.publishableKey = options.publishableKey;
3173
+ }
2972
3174
  const merged = mergeNext(next);
2973
3175
  if (merged !== void 0) opts.next = merged;
2974
3176
  return getSite(opts);
@@ -3077,6 +3279,290 @@ function createGaragemClient(options = {}) {
3077
3279
  }
3078
3280
  };
3079
3281
  }
3282
+ var createClient = createGaragemClient;
3283
+
3284
+ // src/fetchers-photos.ts
3285
+ var MEDIA_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3286
+ var HIDDEN_SIMILAR_PHOTOS = {
3287
+ available: false,
3288
+ items: []
3289
+ };
3290
+ async function getSimilarByPhoto(siteId, listingId, mediaId, options = {}) {
3291
+ const { baseUrl, fetch: fetchImpl, next, limit } = options;
3292
+ const resolvedSiteId = await coerceSiteId(siteId);
3293
+ const lookupId = listingLookupKey(listingId ?? "");
3294
+ if (!lookupId || lookupId === "undefined" || lookupId === "null") {
3295
+ throw new TypeError("getSimilarByPhoto: `listingId` is required");
3296
+ }
3297
+ const photoId = typeof mediaId === "string" ? mediaId.trim() : "";
3298
+ if (!photoId) {
3299
+ throw new TypeError("getSimilarByPhoto: `mediaId` is required");
3300
+ }
3301
+ if (!MEDIA_UUID_RE.test(photoId)) {
3302
+ return HIDDEN_SIMILAR_PHOTOS;
3303
+ }
3304
+ const base = normalizeBaseUrl(baseUrl);
3305
+ const params = new URLSearchParams({ mediaId: photoId });
3306
+ if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) {
3307
+ params.set("limit", String(Math.floor(limit)));
3308
+ }
3309
+ const url = `${base}/api/sites/${encodeURIComponent(resolvedSiteId)}/listings/${encodeURIComponent(
3310
+ lookupId
3311
+ )}/similar-photos?${params.toString()}`;
3312
+ const data = await callJson(
3313
+ url,
3314
+ { method: "GET", headers: { Accept: "application/json" }, next },
3315
+ fetchImpl ?? fetch
3316
+ );
3317
+ return {
3318
+ available: data.available !== false,
3319
+ items: Array.isArray(data.items) ? data.items : []
3320
+ };
3321
+ }
3322
+
3323
+ // src/listing-photos.ts
3324
+ var PHOTO_GROUP_OTHER_KEY = "outros";
3325
+ var PHOTO_GROUP_OTHER_LABEL = "Outras fotos";
3326
+ function normalizeRoomLabel(value) {
3327
+ return value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
3328
+ }
3329
+ var ROOM_GROUPS = [
3330
+ {
3331
+ key: "fachada",
3332
+ label: "Fachada",
3333
+ members: [
3334
+ "fachada",
3335
+ "exterior",
3336
+ "frente",
3337
+ "facade",
3338
+ "fachada do predio",
3339
+ "predio",
3340
+ "building exterior",
3341
+ "area externa do predio"
3342
+ ]
3343
+ },
3344
+ {
3345
+ key: "sala",
3346
+ label: "Sala",
3347
+ members: [
3348
+ "sala",
3349
+ "sala de estar",
3350
+ "living",
3351
+ "estar",
3352
+ "sala de tv",
3353
+ "living room",
3354
+ "sala de estar e jantar",
3355
+ "sala integrada"
3356
+ ]
3357
+ },
3358
+ {
3359
+ key: "sala de jantar",
3360
+ label: "Sala de jantar",
3361
+ members: ["sala de jantar", "jantar", "dining room", "copa jantar"]
3362
+ },
3363
+ {
3364
+ key: "cozinha",
3365
+ label: "Cozinha",
3366
+ members: [
3367
+ "cozinha",
3368
+ "copa",
3369
+ "copa cozinha",
3370
+ "cozinha americana",
3371
+ "kitchen"
3372
+ ]
3373
+ },
3374
+ {
3375
+ key: "quarto",
3376
+ label: "Quartos",
3377
+ members: [
3378
+ "quarto",
3379
+ "dormitorio",
3380
+ "suite",
3381
+ "suite master",
3382
+ "quarto de casal",
3383
+ "quarto de solteiro",
3384
+ "quarto infantil",
3385
+ "bedroom",
3386
+ "master bedroom"
3387
+ ]
3388
+ },
3389
+ {
3390
+ key: "banheiro",
3391
+ label: "Banheiros",
3392
+ members: [
3393
+ "banheiro",
3394
+ "lavabo",
3395
+ "wc",
3396
+ "toalete",
3397
+ "bathroom",
3398
+ "banheiro social",
3399
+ "banheiro da suite"
3400
+ ]
3401
+ },
3402
+ {
3403
+ key: "varanda",
3404
+ label: "Varanda",
3405
+ members: ["varanda", "sacada", "terraco", "balcony", "terrace"]
3406
+ },
3407
+ {
3408
+ key: "area gourmet",
3409
+ label: "\xC1rea gourmet",
3410
+ members: [
3411
+ "area gourmet",
3412
+ "varanda gourmet",
3413
+ "espaco gourmet",
3414
+ "churrasqueira",
3415
+ "gourmet",
3416
+ "terraco gourmet"
3417
+ ]
3418
+ },
3419
+ {
3420
+ key: "closet",
3421
+ label: "Closet",
3422
+ members: ["closet", "closet da suite", "walk in closet"]
3423
+ },
3424
+ {
3425
+ key: "escritorio",
3426
+ label: "Escrit\xF3rio",
3427
+ members: ["escritorio", "home office", "office"]
3428
+ },
3429
+ {
3430
+ key: "area de servico",
3431
+ label: "\xC1rea de servi\xE7o",
3432
+ members: ["area de servico", "lavanderia", "laundry", "servico"]
3433
+ },
3434
+ { key: "despensa", label: "Despensa", members: ["despensa", "pantry"] },
3435
+ {
3436
+ key: "corredor",
3437
+ label: "Corredor",
3438
+ members: ["corredor", "circulacao", "hallway"]
3439
+ },
3440
+ {
3441
+ key: "hall",
3442
+ label: "Hall",
3443
+ members: [
3444
+ "hall",
3445
+ "hall de entrada",
3446
+ "entrada",
3447
+ "recepcao",
3448
+ "lobby",
3449
+ "portaria"
3450
+ ]
3451
+ },
3452
+ {
3453
+ key: "garagem",
3454
+ label: "Garagem",
3455
+ members: [
3456
+ "garagem",
3457
+ "vaga",
3458
+ "vagas",
3459
+ "estacionamento",
3460
+ "garage",
3461
+ "vaga de garagem"
3462
+ ]
3463
+ },
3464
+ {
3465
+ key: "piscina",
3466
+ label: "Piscina",
3467
+ members: ["piscina", "pool", "piscina do condominio"]
3468
+ },
3469
+ {
3470
+ key: "academia",
3471
+ label: "Academia",
3472
+ members: ["academia", "fitness", "gym", "espaco fitness"]
3473
+ },
3474
+ {
3475
+ key: "salao de festas",
3476
+ label: "Sal\xE3o de festas",
3477
+ members: ["salao de festas", "festas", "salao", "party room"]
3478
+ },
3479
+ {
3480
+ key: "playground",
3481
+ label: "Playground",
3482
+ members: ["playground", "brinquedoteca", "espaco kids"]
3483
+ },
3484
+ {
3485
+ key: "jardim",
3486
+ label: "Jardim",
3487
+ members: ["jardim", "quintal", "area externa", "garden", "backyard"]
3488
+ },
3489
+ {
3490
+ key: "vista",
3491
+ label: "Vista",
3492
+ members: ["vista", "view", "vista da varanda"]
3493
+ },
3494
+ {
3495
+ key: "planta",
3496
+ label: "Planta",
3497
+ members: ["planta", "planta baixa", "floorplan", "floor plan"]
3498
+ }
3499
+ ];
3500
+ var GROUP_BY_MEMBER = /* @__PURE__ */ new Map();
3501
+ for (const group of ROOM_GROUPS) {
3502
+ for (const member of group.members) {
3503
+ GROUP_BY_MEMBER.set(member, { key: group.key, label: group.label });
3504
+ }
3505
+ }
3506
+ var NON_ROOM_LABELS = /* @__PURE__ */ new Set(["", "outro", "outros", "other", "unknown"]);
3507
+ function capitalize(value) {
3508
+ return value.charAt(0).toUpperCase() + value.slice(1);
3509
+ }
3510
+ function photoRoomLabel(roomType) {
3511
+ const raw = (roomType ?? "").trim();
3512
+ const normalized = normalizeRoomLabel(raw);
3513
+ if (NON_ROOM_LABELS.has(normalized)) {
3514
+ return { key: PHOTO_GROUP_OTHER_KEY, label: PHOTO_GROUP_OTHER_LABEL };
3515
+ }
3516
+ const known = GROUP_BY_MEMBER.get(normalized);
3517
+ if (known) return known;
3518
+ return { key: normalized, label: capitalize(raw) };
3519
+ }
3520
+ function isPhoto(item) {
3521
+ return (item.type || "image") === "image" && typeof item.src === "string";
3522
+ }
3523
+ function listingPhotoGroups(listing) {
3524
+ const groups = /* @__PURE__ */ new Map();
3525
+ const photos = [...listing.media ?? []].filter(isPhoto).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
3526
+ for (const photo of photos) {
3527
+ const { key, label } = photoRoomLabel(photo.roomType);
3528
+ const group = groups.get(key);
3529
+ if (group) {
3530
+ group.photos.push(photo);
3531
+ } else {
3532
+ groups.set(key, { key, label, photos: [photo] });
3533
+ }
3534
+ }
3535
+ const ordered = [...groups.values()];
3536
+ const otherIndex = ordered.findIndex((g) => g.key === PHOTO_GROUP_OTHER_KEY);
3537
+ if (otherIndex >= 0 && otherIndex !== ordered.length - 1) {
3538
+ const [other] = ordered.splice(otherIndex, 1);
3539
+ ordered.push(other);
3540
+ }
3541
+ return ordered;
3542
+ }
3543
+ function listingVisualHighlights(listing, options) {
3544
+ const limit = Math.max(0, Math.floor(options?.limit ?? 8));
3545
+ if (limit === 0) return [];
3546
+ const counts = /* @__PURE__ */ new Map();
3547
+ let seen = 0;
3548
+ for (const item of listing.media ?? []) {
3549
+ if (!isPhoto(item) || !Array.isArray(item.features)) continue;
3550
+ for (const feature of item.features) {
3551
+ if (typeof feature !== "string") continue;
3552
+ const text = feature.trim();
3553
+ if (!text) continue;
3554
+ const key = normalizeRoomLabel(text);
3555
+ if (!key) continue;
3556
+ const entry = counts.get(key);
3557
+ if (entry) {
3558
+ entry.count += 1;
3559
+ } else {
3560
+ counts.set(key, { text, count: 1, seen: seen++ });
3561
+ }
3562
+ }
3563
+ }
3564
+ return [...counts.values()].sort((a, b) => b.count - a.count || a.seen - b.seen).slice(0, limit).map((entry) => entry.text);
3565
+ }
3080
3566
 
3081
3567
  // src/fetchers-market.ts
3082
3568
  var RATE_LIMITED_MESSAGE = "Muitas consultas em pouco tempo. Tente novamente em instantes.";
@@ -3323,6 +3809,8 @@ export {
3323
3809
  MATCHED_PHOTO_COVER_MAX_DISTANCE,
3324
3810
  MAX_NATIONAL_PHONE_DIGITS,
3325
3811
  PHONE_COUNTRIES,
3812
+ PHOTO_GROUP_OTHER_KEY,
3813
+ PHOTO_GROUP_OTHER_LABEL,
3326
3814
  PHOTO_SEARCH_MIN_QUERY_LENGTH,
3327
3815
  SEARCH_EMPTY_COPY,
3328
3816
  SEARCH_SORT_RELEVANCE,
@@ -3344,6 +3832,7 @@ export {
3344
3832
  composeSearchPublicPath2 as composeSearchPublicPath,
3345
3833
  countFacetChoices,
3346
3834
  countOptionLabel,
3835
+ createClient,
3347
3836
  createGaragemClient,
3348
3837
  defaultPhoneCountry,
3349
3838
  displayPathLocation,
@@ -3364,6 +3853,7 @@ export {
3364
3853
  getListings,
3365
3854
  getNeighborhoodSummary,
3366
3855
  getSearchUi,
3856
+ getSimilarByPhoto,
3367
3857
  getSimilarListings,
3368
3858
  getSite,
3369
3859
  hasShowcaseLeadsPostUrl,
@@ -3388,8 +3878,10 @@ export {
3388
3878
  listingLookupKey,
3389
3879
  listingMapsHref,
3390
3880
  listingMediaOverlays,
3881
+ listingPhotoGroups,
3391
3882
  listingPublicPath,
3392
3883
  listingValues,
3884
+ listingVisualHighlights,
3393
3885
  marketExportsAvailableAt,
3394
3886
  marketPositionLabel,
3395
3887
  mergeAppliedSearchQueryIntoSearch2 as mergeAppliedSearchQueryIntoSearch,
@@ -3407,6 +3899,7 @@ export {
3407
3899
  pathFiltersToQueryFilters,
3408
3900
  pathLocationToFilterInput,
3409
3901
  phoneCountrySearchValue,
3902
+ photoRoomLabel,
3410
3903
  photoSearchUrl,
3411
3904
  priceBandLabel,
3412
3905
  publicSearchHref,
@@ -3435,7 +3928,10 @@ export {
3435
3928
  studioListingCardInstruction,
3436
3929
  studioListingDetailInstruction,
3437
3930
  studioMarketInstruction,
3931
+ studioPhotoInstruction,
3932
+ studioPhotoInstructionFor,
3438
3933
  studioPhotoSearchInstruction,
3934
+ studioPublishableKeyInstruction,
3439
3935
  studioSdkPinInstruction,
3440
3936
  studioSearchInstruction,
3441
3937
  studioSearchLandmarkInstruction,