@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.js CHANGED
@@ -30,6 +30,8 @@ __export(src_exports, {
30
30
  MATCHED_PHOTO_COVER_MAX_DISTANCE: () => MATCHED_PHOTO_COVER_MAX_DISTANCE,
31
31
  MAX_NATIONAL_PHONE_DIGITS: () => MAX_NATIONAL_PHONE_DIGITS,
32
32
  PHONE_COUNTRIES: () => PHONE_COUNTRIES,
33
+ PHOTO_GROUP_OTHER_KEY: () => PHOTO_GROUP_OTHER_KEY,
34
+ PHOTO_GROUP_OTHER_LABEL: () => PHOTO_GROUP_OTHER_LABEL,
33
35
  PHOTO_SEARCH_MIN_QUERY_LENGTH: () => PHOTO_SEARCH_MIN_QUERY_LENGTH,
34
36
  SEARCH_EMPTY_COPY: () => SEARCH_EMPTY_COPY,
35
37
  SEARCH_SORT_RELEVANCE: () => SEARCH_SORT_RELEVANCE,
@@ -51,6 +53,7 @@ __export(src_exports, {
51
53
  composeSearchPublicPath: () => composeSearchPublicPath2,
52
54
  countFacetChoices: () => countFacetChoices,
53
55
  countOptionLabel: () => countOptionLabel,
56
+ createClient: () => createClient,
54
57
  createGaragemClient: () => createGaragemClient,
55
58
  defaultPhoneCountry: () => defaultPhoneCountry,
56
59
  displayPathLocation: () => displayPathLocation,
@@ -71,6 +74,7 @@ __export(src_exports, {
71
74
  getListings: () => getListings,
72
75
  getNeighborhoodSummary: () => getNeighborhoodSummary,
73
76
  getSearchUi: () => getSearchUi,
77
+ getSimilarByPhoto: () => getSimilarByPhoto,
74
78
  getSimilarListings: () => getSimilarListings,
75
79
  getSite: () => getSite,
76
80
  hasShowcaseLeadsPostUrl: () => hasShowcaseLeadsPostUrl,
@@ -95,8 +99,10 @@ __export(src_exports, {
95
99
  listingLookupKey: () => listingLookupKey,
96
100
  listingMapsHref: () => listingMapsHref,
97
101
  listingMediaOverlays: () => listingMediaOverlays,
102
+ listingPhotoGroups: () => listingPhotoGroups,
98
103
  listingPublicPath: () => listingPublicPath,
99
104
  listingValues: () => listingValues,
105
+ listingVisualHighlights: () => listingVisualHighlights,
100
106
  marketExportsAvailableAt: () => marketExportsAvailableAt,
101
107
  marketPositionLabel: () => marketPositionLabel,
102
108
  mergeAppliedSearchQueryIntoSearch: () => mergeAppliedSearchQueryIntoSearch2,
@@ -114,6 +120,7 @@ __export(src_exports, {
114
120
  pathFiltersToQueryFilters: () => pathFiltersToQueryFilters,
115
121
  pathLocationToFilterInput: () => pathLocationToFilterInput,
116
122
  phoneCountrySearchValue: () => phoneCountrySearchValue,
123
+ photoRoomLabel: () => photoRoomLabel,
117
124
  photoSearchUrl: () => photoSearchUrl,
118
125
  priceBandLabel: () => priceBandLabel,
119
126
  publicSearchHref: () => publicSearchHref,
@@ -142,7 +149,10 @@ __export(src_exports, {
142
149
  studioListingCardInstruction: () => studioListingCardInstruction,
143
150
  studioListingDetailInstruction: () => studioListingDetailInstruction,
144
151
  studioMarketInstruction: () => studioMarketInstruction,
152
+ studioPhotoInstruction: () => studioPhotoInstruction,
153
+ studioPhotoInstructionFor: () => studioPhotoInstructionFor,
145
154
  studioPhotoSearchInstruction: () => studioPhotoSearchInstruction,
155
+ studioPublishableKeyInstruction: () => studioPublishableKeyInstruction,
146
156
  studioSdkPinInstruction: () => studioSdkPinInstruction,
147
157
  studioSearchInstruction: () => studioSearchInstruction,
148
158
  studioSearchLandmarkInstruction: () => studioSearchLandmarkInstruction,
@@ -172,6 +182,90 @@ function listingPublicPath(listing) {
172
182
  return `/imoveis/id-${identity}`;
173
183
  }
174
184
 
185
+ // src/internal/sdk-http.ts
186
+ var PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
187
+ function publishableKeyHeaders(publishableKey) {
188
+ const key = publishableKey?.trim();
189
+ if (!key) return {};
190
+ return { [PUBLISHABLE_KEY_HEADER]: key };
191
+ }
192
+ function withPublishableKeyHeader(init, publishableKey) {
193
+ const extra = publishableKeyHeaders(publishableKey);
194
+ if (Object.keys(extra).length === 0) return init;
195
+ const current = init.headers;
196
+ const base = plainHeaders(current);
197
+ return { ...init, headers: { ...base, ...extra } };
198
+ }
199
+ function plainHeaders(headers) {
200
+ const out = {};
201
+ if (!headers) return out;
202
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
203
+ headers.forEach((value, name) => {
204
+ out[name] = value;
205
+ });
206
+ return out;
207
+ }
208
+ if (Array.isArray(headers)) {
209
+ for (const pair of headers) {
210
+ out[String(pair[0])] = String(pair[1]);
211
+ }
212
+ return out;
213
+ }
214
+ for (const [name, value] of Object.entries(
215
+ headers
216
+ )) {
217
+ if (typeof value === "string") out[name] = value;
218
+ }
219
+ return out;
220
+ }
221
+ function finiteNonNegative(value) {
222
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
223
+ return value;
224
+ }
225
+ if (typeof value === "string" && value.trim()) {
226
+ const parsed = Number(value);
227
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
228
+ }
229
+ return null;
230
+ }
231
+ function parseSdkErrorBody(text) {
232
+ const raw = text ? text.slice(0, 200) : "";
233
+ if (!text) {
234
+ return { reason: null, retryAfterSeconds: null, summary: "" };
235
+ }
236
+ try {
237
+ const body = JSON.parse(text);
238
+ if (!body || typeof body !== "object") {
239
+ return { reason: null, retryAfterSeconds: null, summary: raw };
240
+ }
241
+ const record = body;
242
+ const reason = typeof record.reason === "string" && record.reason ? record.reason : null;
243
+ const retryAfterSeconds = finiteNonNegative(
244
+ record.retryAfterSeconds ?? record.retryAfter
245
+ );
246
+ const errorText = typeof record.error === "string" && record.error ? record.error : raw;
247
+ return {
248
+ reason,
249
+ retryAfterSeconds,
250
+ summary: errorText.slice(0, 200)
251
+ };
252
+ } catch {
253
+ return { reason: null, retryAfterSeconds: null, summary: raw };
254
+ }
255
+ }
256
+ function retryAfterFromResponse(response, bodySeconds, nowMs = Date.now()) {
257
+ const header = response.headers.get("Retry-After")?.trim();
258
+ if (header) {
259
+ const delta = finiteNonNegative(header);
260
+ if (delta != null) return delta;
261
+ const at = Date.parse(header);
262
+ if (Number.isFinite(at)) {
263
+ return Math.max(0, Math.ceil((at - nowMs) / 1e3));
264
+ }
265
+ }
266
+ return bodySeconds;
267
+ }
268
+
175
269
  // src/internal/url.ts
176
270
  var DEFAULT_BASE_URL = "https://app.garagem.ai";
177
271
  var DEFAULT_RESOLVE_BASE_URL = "https://cdn.fndn.ai/site";
@@ -206,27 +300,50 @@ function buildListingFiltersQuery(filters) {
206
300
  }
207
301
 
208
302
  // src/fetchers.ts
209
- async function callJson(url, init, fetchImpl) {
210
- const response = await fetchImpl(url, init);
303
+ async function callJson(url, init, fetchImpl, publishableKey) {
304
+ const response = await fetchImpl(
305
+ url,
306
+ withPublishableKeyHeader(init, publishableKey)
307
+ );
211
308
  if (!response.ok) {
212
- const text = await response.text().catch(() => "");
213
- throw new GaragemSdkError(
214
- `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text ? ` \u2014 ${text.slice(0, 200)}` : ""}`,
215
- { status: response.status, url }
216
- );
309
+ throw await readGaragemSdkError(response, url);
217
310
  }
218
311
  return await response.json();
219
312
  }
220
313
  var GaragemSdkError = class extends Error {
221
314
  status;
222
315
  url;
316
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
317
+ reason;
318
+ /**
319
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
320
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
321
+ */
322
+ retryAfter;
223
323
  constructor(message, info) {
224
324
  super(message);
225
325
  this.name = "GaragemSdkError";
226
326
  this.status = info.status;
227
327
  this.url = info.url;
328
+ this.reason = info.reason ?? null;
329
+ this.retryAfter = info.retryAfter ?? null;
228
330
  }
229
331
  };
332
+ async function readGaragemSdkError(response, url) {
333
+ const text = await response.text().catch(() => "");
334
+ const parsed = parseSdkErrorBody(text);
335
+ const retryAfter = response.status === 429 ? retryAfterFromResponse(response, parsed.retryAfterSeconds) : parsed.retryAfterSeconds;
336
+ const detail = parsed.summary;
337
+ return new GaragemSdkError(
338
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${detail ? ` \u2014 ${detail}` : ""}`,
339
+ {
340
+ status: response.status,
341
+ url,
342
+ reason: parsed.reason,
343
+ retryAfter
344
+ }
345
+ );
346
+ }
230
347
  async function getListings(options) {
231
348
  const { filters, baseUrl, fetch: fetchImpl, next } = options;
232
349
  const siteId = await coerceSiteId(options.siteId);
@@ -237,7 +354,8 @@ async function getListings(options) {
237
354
  const data = await callJson(
238
355
  url,
239
356
  { method: "GET", headers: { Accept: "application/json" }, next },
240
- fetchImpl ?? fetch
357
+ fetchImpl ?? fetch,
358
+ options.publishableKey
241
359
  );
242
360
  return {
243
361
  listings: data.listings ?? [],
@@ -258,7 +376,8 @@ async function getListing(options) {
258
376
  return callJson(
259
377
  url,
260
378
  { method: "GET", headers: { Accept: "application/json" }, next },
261
- fetchImpl ?? fetch
379
+ fetchImpl ?? fetch,
380
+ options.publishableKey
262
381
  );
263
382
  }
264
383
  async function getSite(options) {
@@ -280,17 +399,20 @@ async function getSite(options) {
280
399
  if (domain) params.set("domain", domain);
281
400
  const url = `${base}/api/sites/resolve?${params.toString()}`;
282
401
  const f = fetchImpl ?? fetch;
283
- const response = await f(url, {
284
- method: "GET",
285
- headers: { Accept: "application/json" },
286
- next
287
- });
402
+ const response = await f(
403
+ url,
404
+ withPublishableKeyHeader(
405
+ {
406
+ method: "GET",
407
+ headers: { Accept: "application/json" },
408
+ next
409
+ },
410
+ options.publishableKey
411
+ )
412
+ );
288
413
  if (response.status === 404) return null;
289
414
  if (!response.ok) {
290
- throw new GaragemSdkError(
291
- `Garagem SDK: getSite failed (${response.status}) for ${url}`,
292
- { status: response.status, url }
293
- );
415
+ throw await readGaragemSdkError(response, url);
294
416
  }
295
417
  const data = await response.json();
296
418
  return {
@@ -318,7 +440,8 @@ async function searchListings(options) {
318
440
  body: JSON.stringify(params),
319
441
  next
320
442
  },
321
- fetchImpl ?? fetch
443
+ fetchImpl ?? fetch,
444
+ options.publishableKey
322
445
  );
323
446
  }
324
447
  async function getSearchUi(options) {
@@ -329,7 +452,8 @@ async function getSearchUi(options) {
329
452
  return callJson(
330
453
  url,
331
454
  { method: "GET", headers: { Accept: "application/json" }, next },
332
- fetchImpl ?? fetch
455
+ fetchImpl ?? fetch,
456
+ options.publishableKey
333
457
  );
334
458
  }
335
459
  async function queryListings(options) {
@@ -348,7 +472,8 @@ async function queryListings(options) {
348
472
  body: JSON.stringify(params ?? {}),
349
473
  next
350
474
  },
351
- fetchImpl ?? fetch
475
+ fetchImpl ?? fetch,
476
+ options.publishableKey
352
477
  );
353
478
  }
354
479
  async function getSimilarListings(options) {
@@ -376,7 +501,8 @@ async function getSimilarListings(options) {
376
501
  const data = await callJson(
377
502
  url,
378
503
  { method: "GET", headers: { Accept: "application/json" }, next },
379
- fetchImpl ?? fetch
504
+ fetchImpl ?? fetch,
505
+ options.publishableKey
380
506
  );
381
507
  return {
382
508
  listings: data.listings ?? [],
@@ -391,7 +517,8 @@ async function getCmsCollections(options) {
391
517
  const data = await callJson(
392
518
  url,
393
519
  { method: "GET", headers: { Accept: "application/json" }, next },
394
- fetchImpl ?? fetch
520
+ fetchImpl ?? fetch,
521
+ options.publishableKey
395
522
  );
396
523
  return data.collections ?? [];
397
524
  }
@@ -408,7 +535,8 @@ async function getCmsCollection(options) {
408
535
  const data = await callJson(
409
536
  url,
410
537
  { method: "GET", headers: { Accept: "application/json" }, next },
411
- fetchImpl ?? fetch
538
+ fetchImpl ?? fetch,
539
+ options.publishableKey
412
540
  );
413
541
  if (data && typeof data === "object" && "collection" in data && data.collection) {
414
542
  return data.collection;
@@ -443,7 +571,8 @@ async function getCmsEntries(options) {
443
571
  const data = await callJson(
444
572
  url,
445
573
  { method: "GET", headers: { Accept: "application/json" }, next },
446
- fetchImpl ?? fetch
574
+ fetchImpl ?? fetch,
575
+ options.publishableKey
447
576
  );
448
577
  return {
449
578
  entries: data.entries ?? [],
@@ -468,7 +597,8 @@ async function getCmsEntry(options) {
468
597
  const data = await callJson(
469
598
  url,
470
599
  { method: "GET", headers: { Accept: "application/json" }, next },
471
- fetchImpl ?? fetch
600
+ fetchImpl ?? fetch,
601
+ options.publishableKey
472
602
  );
473
603
  if (data && typeof data === "object" && "entry" in data && data.entry) {
474
604
  return data.entry;
@@ -999,7 +1129,8 @@ async function resolvePublicSiteId(options) {
999
1129
  const site = await getSite({
1000
1130
  domain: host,
1001
1131
  baseUrl: options.baseUrl,
1002
- fetch: options.fetch
1132
+ fetch: options.fetch,
1133
+ publishableKey: options.publishableKey
1003
1134
  });
1004
1135
  if (site?.id) return site.id;
1005
1136
  throw new GaragemSdkError(
@@ -1028,7 +1159,8 @@ async function resolveLeadSiteId(input) {
1028
1159
  return resolvePublicSiteId({
1029
1160
  host,
1030
1161
  baseUrl: input.baseUrl,
1031
- fetch: input.fetch
1162
+ fetch: input.fetch,
1163
+ publishableKey: input.publishableKey
1032
1164
  });
1033
1165
  }
1034
1166
  }
@@ -1036,6 +1168,8 @@ var LeadSubmitError = class extends Error {
1036
1168
  code;
1037
1169
  status;
1038
1170
  retryAfterSeconds;
1171
+ /** Seconds to wait. Same value as `retryAfterSeconds`; `null` when unset. */
1172
+ retryAfter;
1039
1173
  constructor(message, info) {
1040
1174
  super(message);
1041
1175
  this.name = "LeadSubmitError";
@@ -1044,6 +1178,7 @@ var LeadSubmitError = class extends Error {
1044
1178
  if (info.retryAfterSeconds != null) {
1045
1179
  this.retryAfterSeconds = info.retryAfterSeconds;
1046
1180
  }
1181
+ this.retryAfter = info.retryAfterSeconds ?? null;
1047
1182
  }
1048
1183
  };
1049
1184
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -1085,7 +1220,8 @@ async function getLeadUi(options) {
1085
1220
  headers: { Accept: "application/json" },
1086
1221
  next: options.next
1087
1222
  },
1088
- options.fetch ?? fetch
1223
+ options.fetch ?? fetch,
1224
+ options.publishableKey
1089
1225
  );
1090
1226
  }
1091
1227
  function assertListingId(listingId) {
@@ -1158,7 +1294,8 @@ async function postSiteLead(input) {
1158
1294
  method: "POST",
1159
1295
  headers: {
1160
1296
  Accept: "application/json",
1161
- "Content-Type": "application/json"
1297
+ "Content-Type": "application/json",
1298
+ ...publishableKeyHeaders(input.publishableKey)
1162
1299
  },
1163
1300
  body: JSON.stringify(input.body)
1164
1301
  });
@@ -1173,12 +1310,23 @@ async function postSiteLead(input) {
1173
1310
  const id = typeof data.id === "string" && data.id ? data.id : "";
1174
1311
  return { ok: true, status: 202, id };
1175
1312
  }
1176
- const retryAfter = Number(response.headers.get("Retry-After") ?? "");
1313
+ if (response.status === 401) {
1314
+ throw new LeadSubmitError("Garagem SDK: invalid publishable key.", {
1315
+ code: "unauthorized",
1316
+ status: 401
1317
+ });
1318
+ }
1177
1319
  if (response.status === 429) {
1320
+ const text = await response.text().catch(() => "");
1321
+ const parsed = parseSdkErrorBody(text);
1322
+ const retryAfter = retryAfterFromResponse(
1323
+ response,
1324
+ parsed.retryAfterSeconds
1325
+ );
1178
1326
  throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
1179
1327
  code: "rate_limited",
1180
1328
  status: 429,
1181
- retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : void 0
1329
+ ...retryAfter != null ? { retryAfterSeconds: retryAfter } : {}
1182
1330
  });
1183
1331
  }
1184
1332
  if (response.status === 404) {
@@ -1222,6 +1370,7 @@ async function submitVisitLead(input) {
1222
1370
  siteId: input.siteId,
1223
1371
  baseUrl: input.baseUrl,
1224
1372
  fetch: input.fetch,
1373
+ publishableKey: input.publishableKey,
1225
1374
  body: {
1226
1375
  source: "site-sdk",
1227
1376
  leadType: "visit",
@@ -1240,6 +1389,7 @@ async function submitContactLead(input) {
1240
1389
  siteId: input.siteId,
1241
1390
  baseUrl: input.baseUrl,
1242
1391
  fetch: input.fetch,
1392
+ publishableKey: input.publishableKey,
1243
1393
  body: {
1244
1394
  source: "site-sdk",
1245
1395
  leadType: "contact",
@@ -2829,6 +2979,29 @@ var STUDIO_SDK_CONTRACT = {
2829
2979
  */
2830
2980
  unpublishedPhoneExports: [],
2831
2981
  amenityExports: ["listingAmenityGroups"],
2982
+ /**
2983
+ * Prompt-safe photo helpers on `minNpmVersion`. Empty until the release
2984
+ * that carries `getSimilarByPhoto` / `listingPhotoGroups` /
2985
+ * `listingVisualHighlights` is on npm; then bump the pin, move the names
2986
+ * here from `unpublishedPhotoExports`, and `studioPhotoInstruction()`
2987
+ * starts teaching the gallery-by-room, highlight chips, and
2988
+ * "imóveis com fotos parecidas" blocks. The caption-based `media[].alt` /
2989
+ * `media[].caption` fields are API data (not tarball exports) and are
2990
+ * documented regardless of the pin.
2991
+ */
2992
+ photoExports: [],
2993
+ /**
2994
+ * Photo helpers in the repo but not on `minNpmVersion`. Prompts,
2995
+ * completeness, and repair text must not mention these until the pin
2996
+ * bumps — v0 installs the pin and the ESM loader throws on missing named
2997
+ * exports.
2998
+ */
2999
+ unpublishedPhotoExports: [
3000
+ "getSimilarByPhoto",
3001
+ "listingPhotoGroups",
3002
+ "listingVisualHighlights",
3003
+ "photoRoomLabel"
3004
+ ],
2832
3005
  /**
2833
3006
  * Names already on the pinned npm tarball (`minNpmVersion`) — safe for
2834
3007
  * Studio prompts and completeness. Includes `visibleSearchFilters` +
@@ -2972,6 +3145,9 @@ function unavailableReactImports(source, pin) {
2972
3145
  }
2973
3146
  return missing;
2974
3147
  }
3148
+ function studioPublishableKeyInstruction() {
3149
+ 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.`;
3150
+ }
2975
3151
  function studioSdkPinInstruction() {
2976
3152
  const version = STUDIO_SDK_CONTRACT.minNpmVersion;
2977
3153
  const names = [...reactExportsAvailableAt(version)].join(", ");
@@ -2990,6 +3166,31 @@ function studioListingDetailInstruction() {
2990
3166
  const names = STUDIO_SDK_CONTRACT.listingDetailExports.join(", ");
2991
3167
  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.`;
2992
3168
  }
3169
+ function studioPhotoInstructionFor(published) {
3170
+ const has = (name) => published.includes(name);
3171
+ const parts = [
3172
+ `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.`
3173
+ ];
3174
+ if (has("listingPhotoGroups")) {
3175
+ parts.push(
3176
+ `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.`
3177
+ );
3178
+ }
3179
+ if (has("listingVisualHighlights")) {
3180
+ parts.push(
3181
+ `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.`
3182
+ );
3183
+ }
3184
+ if (has("getSimilarByPhoto")) {
3185
+ parts.push(
3186
+ `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\`.`
3187
+ );
3188
+ }
3189
+ return parts.join(" ");
3190
+ }
3191
+ function studioPhotoInstruction() {
3192
+ return studioPhotoInstructionFor(STUDIO_SDK_CONTRACT.photoExports);
3193
+ }
2993
3194
  function studioAmenityInstruction() {
2994
3195
  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".`;
2995
3196
  }
@@ -3048,6 +3249,11 @@ function studioCodegenContractViolations(text) {
3048
3249
  violations.push(name);
3049
3250
  }
3050
3251
  }
3252
+ for (const name of STUDIO_SDK_CONTRACT.unpublishedPhotoExports) {
3253
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
3254
+ violations.push(name);
3255
+ }
3256
+ }
3051
3257
  if (!isPhotoSearchOnPin()) {
3052
3258
  for (const name of STUDIO_SDK_CONTRACT.photoSearchExports) {
3053
3259
  if (mentionsExportName(text, name) && !violations.includes(name)) {
@@ -3097,6 +3303,9 @@ function createGaragemClient(options = {}) {
3097
3303
  const out = { ...opts };
3098
3304
  if (options.baseUrl !== void 0) out.baseUrl = options.baseUrl;
3099
3305
  if (options.fetch !== void 0) out.fetch = options.fetch;
3306
+ if (options.publishableKey !== void 0 && out.publishableKey === void 0) {
3307
+ out.publishableKey = options.publishableKey;
3308
+ }
3100
3309
  return out;
3101
3310
  };
3102
3311
  return {
@@ -3125,6 +3334,9 @@ function createGaragemClient(options = {}) {
3125
3334
  if (domain !== void 0) opts.domain = domain;
3126
3335
  if (options.baseUrl !== void 0) opts.baseUrl = options.baseUrl;
3127
3336
  if (options.fetch !== void 0) opts.fetch = options.fetch;
3337
+ if (options.publishableKey !== void 0) {
3338
+ opts.publishableKey = options.publishableKey;
3339
+ }
3128
3340
  const merged = mergeNext(next);
3129
3341
  if (merged !== void 0) opts.next = merged;
3130
3342
  return getSite(opts);
@@ -3233,6 +3445,290 @@ function createGaragemClient(options = {}) {
3233
3445
  }
3234
3446
  };
3235
3447
  }
3448
+ var createClient = createGaragemClient;
3449
+
3450
+ // src/fetchers-photos.ts
3451
+ 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;
3452
+ var HIDDEN_SIMILAR_PHOTOS = {
3453
+ available: false,
3454
+ items: []
3455
+ };
3456
+ async function getSimilarByPhoto(siteId, listingId, mediaId, options = {}) {
3457
+ const { baseUrl, fetch: fetchImpl, next, limit } = options;
3458
+ const resolvedSiteId = await coerceSiteId(siteId);
3459
+ const lookupId = listingLookupKey(listingId ?? "");
3460
+ if (!lookupId || lookupId === "undefined" || lookupId === "null") {
3461
+ throw new TypeError("getSimilarByPhoto: `listingId` is required");
3462
+ }
3463
+ const photoId = typeof mediaId === "string" ? mediaId.trim() : "";
3464
+ if (!photoId) {
3465
+ throw new TypeError("getSimilarByPhoto: `mediaId` is required");
3466
+ }
3467
+ if (!MEDIA_UUID_RE.test(photoId)) {
3468
+ return HIDDEN_SIMILAR_PHOTOS;
3469
+ }
3470
+ const base = normalizeBaseUrl(baseUrl);
3471
+ const params = new URLSearchParams({ mediaId: photoId });
3472
+ if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) {
3473
+ params.set("limit", String(Math.floor(limit)));
3474
+ }
3475
+ const url = `${base}/api/sites/${encodeURIComponent(resolvedSiteId)}/listings/${encodeURIComponent(
3476
+ lookupId
3477
+ )}/similar-photos?${params.toString()}`;
3478
+ const data = await callJson(
3479
+ url,
3480
+ { method: "GET", headers: { Accept: "application/json" }, next },
3481
+ fetchImpl ?? fetch
3482
+ );
3483
+ return {
3484
+ available: data.available !== false,
3485
+ items: Array.isArray(data.items) ? data.items : []
3486
+ };
3487
+ }
3488
+
3489
+ // src/listing-photos.ts
3490
+ var PHOTO_GROUP_OTHER_KEY = "outros";
3491
+ var PHOTO_GROUP_OTHER_LABEL = "Outras fotos";
3492
+ function normalizeRoomLabel(value) {
3493
+ return value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
3494
+ }
3495
+ var ROOM_GROUPS = [
3496
+ {
3497
+ key: "fachada",
3498
+ label: "Fachada",
3499
+ members: [
3500
+ "fachada",
3501
+ "exterior",
3502
+ "frente",
3503
+ "facade",
3504
+ "fachada do predio",
3505
+ "predio",
3506
+ "building exterior",
3507
+ "area externa do predio"
3508
+ ]
3509
+ },
3510
+ {
3511
+ key: "sala",
3512
+ label: "Sala",
3513
+ members: [
3514
+ "sala",
3515
+ "sala de estar",
3516
+ "living",
3517
+ "estar",
3518
+ "sala de tv",
3519
+ "living room",
3520
+ "sala de estar e jantar",
3521
+ "sala integrada"
3522
+ ]
3523
+ },
3524
+ {
3525
+ key: "sala de jantar",
3526
+ label: "Sala de jantar",
3527
+ members: ["sala de jantar", "jantar", "dining room", "copa jantar"]
3528
+ },
3529
+ {
3530
+ key: "cozinha",
3531
+ label: "Cozinha",
3532
+ members: [
3533
+ "cozinha",
3534
+ "copa",
3535
+ "copa cozinha",
3536
+ "cozinha americana",
3537
+ "kitchen"
3538
+ ]
3539
+ },
3540
+ {
3541
+ key: "quarto",
3542
+ label: "Quartos",
3543
+ members: [
3544
+ "quarto",
3545
+ "dormitorio",
3546
+ "suite",
3547
+ "suite master",
3548
+ "quarto de casal",
3549
+ "quarto de solteiro",
3550
+ "quarto infantil",
3551
+ "bedroom",
3552
+ "master bedroom"
3553
+ ]
3554
+ },
3555
+ {
3556
+ key: "banheiro",
3557
+ label: "Banheiros",
3558
+ members: [
3559
+ "banheiro",
3560
+ "lavabo",
3561
+ "wc",
3562
+ "toalete",
3563
+ "bathroom",
3564
+ "banheiro social",
3565
+ "banheiro da suite"
3566
+ ]
3567
+ },
3568
+ {
3569
+ key: "varanda",
3570
+ label: "Varanda",
3571
+ members: ["varanda", "sacada", "terraco", "balcony", "terrace"]
3572
+ },
3573
+ {
3574
+ key: "area gourmet",
3575
+ label: "\xC1rea gourmet",
3576
+ members: [
3577
+ "area gourmet",
3578
+ "varanda gourmet",
3579
+ "espaco gourmet",
3580
+ "churrasqueira",
3581
+ "gourmet",
3582
+ "terraco gourmet"
3583
+ ]
3584
+ },
3585
+ {
3586
+ key: "closet",
3587
+ label: "Closet",
3588
+ members: ["closet", "closet da suite", "walk in closet"]
3589
+ },
3590
+ {
3591
+ key: "escritorio",
3592
+ label: "Escrit\xF3rio",
3593
+ members: ["escritorio", "home office", "office"]
3594
+ },
3595
+ {
3596
+ key: "area de servico",
3597
+ label: "\xC1rea de servi\xE7o",
3598
+ members: ["area de servico", "lavanderia", "laundry", "servico"]
3599
+ },
3600
+ { key: "despensa", label: "Despensa", members: ["despensa", "pantry"] },
3601
+ {
3602
+ key: "corredor",
3603
+ label: "Corredor",
3604
+ members: ["corredor", "circulacao", "hallway"]
3605
+ },
3606
+ {
3607
+ key: "hall",
3608
+ label: "Hall",
3609
+ members: [
3610
+ "hall",
3611
+ "hall de entrada",
3612
+ "entrada",
3613
+ "recepcao",
3614
+ "lobby",
3615
+ "portaria"
3616
+ ]
3617
+ },
3618
+ {
3619
+ key: "garagem",
3620
+ label: "Garagem",
3621
+ members: [
3622
+ "garagem",
3623
+ "vaga",
3624
+ "vagas",
3625
+ "estacionamento",
3626
+ "garage",
3627
+ "vaga de garagem"
3628
+ ]
3629
+ },
3630
+ {
3631
+ key: "piscina",
3632
+ label: "Piscina",
3633
+ members: ["piscina", "pool", "piscina do condominio"]
3634
+ },
3635
+ {
3636
+ key: "academia",
3637
+ label: "Academia",
3638
+ members: ["academia", "fitness", "gym", "espaco fitness"]
3639
+ },
3640
+ {
3641
+ key: "salao de festas",
3642
+ label: "Sal\xE3o de festas",
3643
+ members: ["salao de festas", "festas", "salao", "party room"]
3644
+ },
3645
+ {
3646
+ key: "playground",
3647
+ label: "Playground",
3648
+ members: ["playground", "brinquedoteca", "espaco kids"]
3649
+ },
3650
+ {
3651
+ key: "jardim",
3652
+ label: "Jardim",
3653
+ members: ["jardim", "quintal", "area externa", "garden", "backyard"]
3654
+ },
3655
+ {
3656
+ key: "vista",
3657
+ label: "Vista",
3658
+ members: ["vista", "view", "vista da varanda"]
3659
+ },
3660
+ {
3661
+ key: "planta",
3662
+ label: "Planta",
3663
+ members: ["planta", "planta baixa", "floorplan", "floor plan"]
3664
+ }
3665
+ ];
3666
+ var GROUP_BY_MEMBER = /* @__PURE__ */ new Map();
3667
+ for (const group of ROOM_GROUPS) {
3668
+ for (const member of group.members) {
3669
+ GROUP_BY_MEMBER.set(member, { key: group.key, label: group.label });
3670
+ }
3671
+ }
3672
+ var NON_ROOM_LABELS = /* @__PURE__ */ new Set(["", "outro", "outros", "other", "unknown"]);
3673
+ function capitalize(value) {
3674
+ return value.charAt(0).toUpperCase() + value.slice(1);
3675
+ }
3676
+ function photoRoomLabel(roomType) {
3677
+ const raw = (roomType ?? "").trim();
3678
+ const normalized = normalizeRoomLabel(raw);
3679
+ if (NON_ROOM_LABELS.has(normalized)) {
3680
+ return { key: PHOTO_GROUP_OTHER_KEY, label: PHOTO_GROUP_OTHER_LABEL };
3681
+ }
3682
+ const known = GROUP_BY_MEMBER.get(normalized);
3683
+ if (known) return known;
3684
+ return { key: normalized, label: capitalize(raw) };
3685
+ }
3686
+ function isPhoto(item) {
3687
+ return (item.type || "image") === "image" && typeof item.src === "string";
3688
+ }
3689
+ function listingPhotoGroups(listing) {
3690
+ const groups = /* @__PURE__ */ new Map();
3691
+ const photos = [...listing.media ?? []].filter(isPhoto).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
3692
+ for (const photo of photos) {
3693
+ const { key, label } = photoRoomLabel(photo.roomType);
3694
+ const group = groups.get(key);
3695
+ if (group) {
3696
+ group.photos.push(photo);
3697
+ } else {
3698
+ groups.set(key, { key, label, photos: [photo] });
3699
+ }
3700
+ }
3701
+ const ordered = [...groups.values()];
3702
+ const otherIndex = ordered.findIndex((g) => g.key === PHOTO_GROUP_OTHER_KEY);
3703
+ if (otherIndex >= 0 && otherIndex !== ordered.length - 1) {
3704
+ const [other] = ordered.splice(otherIndex, 1);
3705
+ ordered.push(other);
3706
+ }
3707
+ return ordered;
3708
+ }
3709
+ function listingVisualHighlights(listing, options) {
3710
+ const limit = Math.max(0, Math.floor(options?.limit ?? 8));
3711
+ if (limit === 0) return [];
3712
+ const counts = /* @__PURE__ */ new Map();
3713
+ let seen = 0;
3714
+ for (const item of listing.media ?? []) {
3715
+ if (!isPhoto(item) || !Array.isArray(item.features)) continue;
3716
+ for (const feature of item.features) {
3717
+ if (typeof feature !== "string") continue;
3718
+ const text = feature.trim();
3719
+ if (!text) continue;
3720
+ const key = normalizeRoomLabel(text);
3721
+ if (!key) continue;
3722
+ const entry = counts.get(key);
3723
+ if (entry) {
3724
+ entry.count += 1;
3725
+ } else {
3726
+ counts.set(key, { text, count: 1, seen: seen++ });
3727
+ }
3728
+ }
3729
+ }
3730
+ return [...counts.values()].sort((a, b) => b.count - a.count || a.seen - b.seen).slice(0, limit).map((entry) => entry.text);
3731
+ }
3236
3732
 
3237
3733
  // src/fetchers-market.ts
3238
3734
  var RATE_LIMITED_MESSAGE = "Muitas consultas em pouco tempo. Tente novamente em instantes.";
@@ -3480,6 +3976,8 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3480
3976
  MATCHED_PHOTO_COVER_MAX_DISTANCE,
3481
3977
  MAX_NATIONAL_PHONE_DIGITS,
3482
3978
  PHONE_COUNTRIES,
3979
+ PHOTO_GROUP_OTHER_KEY,
3980
+ PHOTO_GROUP_OTHER_LABEL,
3483
3981
  PHOTO_SEARCH_MIN_QUERY_LENGTH,
3484
3982
  SEARCH_EMPTY_COPY,
3485
3983
  SEARCH_SORT_RELEVANCE,
@@ -3501,6 +3999,7 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3501
3999
  composeSearchPublicPath,
3502
4000
  countFacetChoices,
3503
4001
  countOptionLabel,
4002
+ createClient,
3504
4003
  createGaragemClient,
3505
4004
  defaultPhoneCountry,
3506
4005
  displayPathLocation,
@@ -3521,6 +4020,7 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3521
4020
  getListings,
3522
4021
  getNeighborhoodSummary,
3523
4022
  getSearchUi,
4023
+ getSimilarByPhoto,
3524
4024
  getSimilarListings,
3525
4025
  getSite,
3526
4026
  hasShowcaseLeadsPostUrl,
@@ -3545,8 +4045,10 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3545
4045
  listingLookupKey,
3546
4046
  listingMapsHref,
3547
4047
  listingMediaOverlays,
4048
+ listingPhotoGroups,
3548
4049
  listingPublicPath,
3549
4050
  listingValues,
4051
+ listingVisualHighlights,
3550
4052
  marketExportsAvailableAt,
3551
4053
  marketPositionLabel,
3552
4054
  mergeAppliedSearchQueryIntoSearch,
@@ -3564,6 +4066,7 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3564
4066
  pathFiltersToQueryFilters,
3565
4067
  pathLocationToFilterInput,
3566
4068
  phoneCountrySearchValue,
4069
+ photoRoomLabel,
3567
4070
  photoSearchUrl,
3568
4071
  priceBandLabel,
3569
4072
  publicSearchHref,
@@ -3592,7 +4095,10 @@ function applyMatchedPhotoCover(cards, photoResults, options = {}) {
3592
4095
  studioListingCardInstruction,
3593
4096
  studioListingDetailInstruction,
3594
4097
  studioMarketInstruction,
4098
+ studioPhotoInstruction,
4099
+ studioPhotoInstructionFor,
3595
4100
  studioPhotoSearchInstruction,
4101
+ studioPublishableKeyInstruction,
3596
4102
  studioSdkPinInstruction,
3597
4103
  studioSearchInstruction,
3598
4104
  studioSearchLandmarkInstruction,