@garagem-ai/site-sdk 0.6.1 → 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/README.md CHANGED
@@ -54,25 +54,27 @@ raw escape hatch when you need full control.
54
54
 
55
55
  ### Friendly layer (recommended for most use cases)
56
56
 
57
- | API | Description |
58
- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
- | `getListings({ siteId, filters?, next? })` | Paginated listings for a site, with simple `filters` (`city`, `businessType`, `propertyType`, `neighborhood`, `minPrice`, `maxPrice`, `limit`, `offset`) |
60
- | `getListing({ siteId, listingId, next? })` | Full detail of a single listing |
61
- | `getSimilarListings({ siteId, listingId, limit?, next? })` | Similar listings carousel (same card shape as `getListings`) |
62
- | `getSite({ siteId? \| domain?, next? })` | Public site profile (returns `null` if unknown) |
63
- | `getCmsCollections({ siteId })` | List CMS collections |
64
- | `getCmsCollection({ siteId, slug })` | One CMS collection schema |
65
- | `getCmsEntries({ siteId, collection, limit?, offset? })` | Published CMS entries only |
66
- | `getCmsEntry({ siteId, collection, slug })` | One published CMS entry |
67
- | `getSearchUi({ siteId, next? })` | Tenant search schema (filters, slugs) |
68
- | `getLeadUi({ siteId, next? })` | Visit-default lead dialog schema (weekday hours, Sat/Sun flags) |
69
- | `submitVisitLead({ siteId, listingId, … })` | POST a visit lead (`listing.id` UUID; civil `visitDate` or `Date`/ISO instant normalized in the schedule timezone) |
70
- | `submitContactLead({ siteId, listingId, … })` | POST a contact lead (no date/time) |
71
- | `slotsForDate` / `normalizeVisitDate` / `expandVisitSchedule` | Pure schedule helpers (`America/Sao_Paulo`, default Mon–Fri 06:00–22:00) |
72
- | `listingDetailModel(listing)` | Listing-detail blocks: breadcrumb, location + Maps href, `description` string + toggle label, video/tour overlays. Studio pages map `facts` / `values` via `.label` / `.text` leaves. |
73
- | `listingDetailFieldsModel(listing, dictionary?)` | Facts, values, and amenity groups that are safe to render: every row has a real label + text; missing condo/IPTU/empty groups are omitted. |
74
- | `listingAmenityGroups(listing, dictionary?)` | Unit / building amenity labels (`Comodidades`, `Comodidades do condomínio`). Reads `propertyFeatures` + `buildingAmenities` (works when `building` is null). Tenant `getSearchUi().dictionary` first, then the SDK fallback. Studio pages call this helper directly. |
75
- | `resolvePublicSiteId({ host?, fallback? })` | Preview uses `fallback` (`GARAGEM_SITE_ID`); live hosts resolve via `getSite({ domain })` |
57
+ | API | Description |
58
+ | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
+ | `getListings({ siteId, filters?, next? })` | Paginated listings for a site, with simple `filters` (`city`, `businessType`, `propertyType`, `neighborhood`, `minPrice`, `maxPrice`, `limit`, `offset`) |
60
+ | `getListing({ siteId, listingId, next? })` | Full detail of a single listing |
61
+ | `getSimilarListings({ siteId, listingId, limit?, next? })` | Similar listings carousel (same card shape as `getListings`) |
62
+ | `getSimilarByPhoto(siteId, listingId, mediaId, options?)` | "Imóveis com fotos parecidas": listings whose public photos look like one gallery photo. `available: false` when the tenant has no image search — hide the block. |
63
+ | `listingPhotoGroups(listing)` / `listingVisualHighlights(listing)` | Gallery grouped by room (`Sala`, `Quartos`, `Cozinha`, … from each photo's `roomType`) and the deduped visual highlights the photo analysis named most often. |
64
+ | `getSite({ siteId? \| domain?, next? })` | Public site profile (returns `null` if unknown) |
65
+ | `getCmsCollections({ siteId })` | List CMS collections |
66
+ | `getCmsCollection({ siteId, slug })` | One CMS collection schema |
67
+ | `getCmsEntries({ siteId, collection, limit?, offset? })` | Published CMS entries only |
68
+ | `getCmsEntry({ siteId, collection, slug })` | One published CMS entry |
69
+ | `getSearchUi({ siteId, next? })` | Tenant search schema (filters, slugs) |
70
+ | `getLeadUi({ siteId, next? })` | Visit-default lead dialog schema (weekday hours, Sat/Sun flags) |
71
+ | `submitVisitLead({ siteId, listingId, … })` | POST a visit lead (`listing.id` UUID; civil `visitDate` or `Date`/ISO instant normalized in the schedule timezone) |
72
+ | `submitContactLead({ siteId, listingId, … })` | POST a contact lead (no date/time) |
73
+ | `slotsForDate` / `normalizeVisitDate` / `expandVisitSchedule` | Pure schedule helpers (`America/Sao_Paulo`, default Mon–Fri 06:00–22:00) |
74
+ | `listingDetailModel(listing)` | Listing-detail blocks: breadcrumb, location + Maps href, `description` string + toggle label, video/tour overlays. Studio pages map `facts` / `values` via `.label` / `.text` leaves. |
75
+ | `listingDetailFieldsModel(listing, dictionary?)` | Facts, values, and amenity groups that are safe to render: every row has a real label + text; missing condo/IPTU/empty groups are omitted. |
76
+ | `listingAmenityGroups(listing, dictionary?)` | Unit / building amenity labels (`Comodidades`, `Comodidades do condomínio`). Reads `propertyFeatures` + `buildingAmenities` (works when `building` is null). Tenant `getSearchUi().dictionary` first, then the SDK fallback. Studio pages call this helper directly. |
77
+ | `resolvePublicSiteId({ host?, fallback? })` | Preview uses `fallback` (`GARAGEM_SITE_ID`); live hosts resolve via `getSite({ domain })` |
76
78
 
77
79
  ### Advanced layer (when the friendly one isn't enough)
78
80
 
@@ -82,19 +84,67 @@ raw escape hatch when you need full control.
82
84
 
83
85
  ### Cross-cutting
84
86
 
85
- | API | Description |
86
- | ------------------------------ | ----------------------------------------------------- |
87
- | `createGaragemClient(options)` | Pre-bind `baseUrl`, `siteId`, `fetch`, `next` |
88
- | `GaragemSdkError` | Thrown on non-2xx responses; carries `status` + `url` |
87
+ | API | Description |
88
+ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
89
+ | `createGaragemClient(options)` / `createClient(options)` | Pre-bind `baseUrl`, `siteId`, `publishableKey`, `fetch`, `next` |
90
+ | `GaragemSdkError` | Thrown on non-2xx responses; `status`, `url`, `reason`, `retryAfter` (seconds, set on 429) |
89
91
 
90
92
  All fetchers accept:
91
93
 
94
+ - `publishableKey` — optional `pk_live_…` from the site's API pública
95
+ settings. See [Publishable keys & rate limits](#publishable-keys--rate-limits).
92
96
  - `baseUrl` — data fetchers default to `https://app.garagem.ai`; `getSite`
93
97
  defaults to `https://cdn.fndn.ai/site` so production resolution traverses the
94
98
  tenant-locator edge. Override for a custom proxy or staging.
95
99
  - `fetch` — custom fetch implementation (testing, retries, edge runtimes).
96
100
  - `next: { revalidate, tags }` — forwarded directly to the underlying `fetch` for Next.js App Router caching. Ignored on runtimes that don't understand it.
97
101
 
102
+ ## Market data (IPTU module required)
103
+
104
+ Neighborhood price summary, listing market position, and a visitor price
105
+ estimate. **Every helper is a no-op unless the site's organization has the
106
+ IPTU module** (`iptu_itbi_integration`) and the city is covered. There is
107
+ no error status for that case: the call returns HTTP 200 with
108
+ `{ available: false, reason }`. Render the block only when `available` is
109
+ true; otherwise render nothing (no placeholder, no local fallback number).
110
+
111
+ The payloads are aggregates and a trimmed estimate. They never include
112
+ cadastral ids, IPTU lookups, ITBI transactions, comparables, or unit
113
+ inventory. Do not request or invent those fields.
114
+
115
+ | API | Description |
116
+ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
117
+ | `getNeighborhoodSummary({ siteId, query, next? })` | P25 / P50 / P75 price per m² and sample size for a neighborhood. `query` is `{ city, neighborhood, propertyType?, type? }`. `type: "rent"` answers `listing_type_unsupported` (sale only). Cache with `next: { revalidate: 900 }`. |
118
+ | `getListingMarketPosition({ siteId, listingId, next? })` | The listing's public price per m² versus the neighborhood median (`percentVsMedian`, `band`). Copy comes from `marketPositionLabel` / `priceBandLabel` (both return `null` when unavailable). |
119
+ | `requestPriceEstimate({ siteId, input })` | Trimmed estimate for visitor-entered characteristics (`city`, `areaSqm`, optional neighborhood, bedrooms, parking, property type). Rate limited per visitor. Call it from a submit handler, not on page load. |
120
+ | `marketPositionLabel(position)` | pt-BR line such as `8% abaixo da mediana do bairro`. |
121
+ | `priceBandLabel(position)` | pt-BR quartile line such as `Na faixa do bairro, abaixo da mediana`. |
122
+
123
+ `reason` is a code (`module_not_enabled`, `city_unsupported`, `no_data`,
124
+ `rate_limited`, …). Do not print it. When `available` is false, `message`
125
+ is already pt-BR and is only for the estimate form's empty state.
126
+
127
+ ```ts
128
+ import {
129
+ getListingMarketPosition,
130
+ getNeighborhoodSummary,
131
+ marketPositionLabel,
132
+ } from "@garagem-ai/site-sdk";
133
+
134
+ const summary = await getNeighborhoodSummary({
135
+ siteId,
136
+ query: { city: "São Paulo", neighborhood: "Moema" },
137
+ next: { revalidate: 900 },
138
+ });
139
+
140
+ if (summary.available) {
141
+ summary.pricePerSqmFormatted.p50; // "R$ 10.870,00/m²"
142
+ }
143
+
144
+ const position = await getListingMarketPosition({ siteId, listingId });
145
+ const label = marketPositionLabel(position); // null when the module is off
146
+ ```
147
+
98
148
  ## Similar listings example
99
149
 
100
150
  ```tsx
@@ -128,6 +178,91 @@ export default async function ListingPage({
128
178
  }
129
179
  ```
130
180
 
181
+ ## Photo captions, room groups and "imóveis com fotos parecidas"
182
+
183
+ Every photo on `getListing().media` carries the platform's photo analysis when
184
+ the tenant has it: `caption` (AI caption, falling back to the broker's own
185
+ description), `roomType`, `sceneType`, `features`, and an `alt` built from the
186
+ caption. Nothing here calls a model at request time — it is read with the
187
+ listing and cached like the rest of the detail. Photos without analysis keep
188
+ the generic `"<title> - Foto N"` alt and omit the other fields.
189
+
190
+ ```tsx
191
+ import {
192
+ getListing,
193
+ getSimilarByPhoto,
194
+ listingPhotoGroups,
195
+ listingVisualHighlights,
196
+ } from "@garagem-ai/site-sdk";
197
+
198
+ export default async function ListingPage({
199
+ params,
200
+ }: {
201
+ params: Promise<{ id: string }>;
202
+ }) {
203
+ const { id } = await params;
204
+ const siteId = process.env.GARAGEM_SITE_ID!;
205
+ const listing = await getListing({ siteId, listingId: id });
206
+
207
+ // "Sala (3) · Quartos (4) · Cozinha (2)" — pt-BR labels, `Outras fotos` last.
208
+ // With no analysis at all you get a single `Outras fotos` group: keep the
209
+ // flat gallery when `groups.length <= 1`.
210
+ const groups = listingPhotoGroups(listing);
211
+ // ["piso de madeira", "pé-direito alto", "vista livre"]
212
+ const highlights = listingVisualHighlights(listing, { limit: 6 });
213
+
214
+ // Listings whose public photos look like the cover photo.
215
+ const cover = listing.media.find((m) => m.type === "image");
216
+ const similar = cover
217
+ ? await getSimilarByPhoto(siteId, listing.id, cover.id, {
218
+ limit: 6,
219
+ next: { revalidate: 300 },
220
+ })
221
+ : { available: false, items: [] };
222
+
223
+ return (
224
+ <>
225
+ <ul>
226
+ {highlights.map((h) => (
227
+ <li key={h}>{h}</li>
228
+ ))}
229
+ </ul>
230
+ {groups.map((group) => (
231
+ <section key={group.key}>
232
+ <h2>
233
+ {group.label} ({group.photos.length})
234
+ </h2>
235
+ {group.photos.map((photo) => (
236
+ <img key={photo.id} src={photo.src} alt={photo.alt} />
237
+ ))}
238
+ </section>
239
+ ))}
240
+ {similar.available && similar.items.length > 0 && (
241
+ <section>
242
+ <h2>Imóveis com fotos parecidas</h2>
243
+ {similar.items.map(({ listing: l, matchedPhoto }) => (
244
+ <a key={l.id} href={l.path}>
245
+ <img src={matchedPhoto.src} alt={matchedPhoto.alt} />
246
+ {l.title}
247
+ </a>
248
+ ))}
249
+ </section>
250
+ )}
251
+ </>
252
+ );
253
+ }
254
+ ```
255
+
256
+ `getSimilarByPhoto` returns `{ available, items }`. `available` is `false`
257
+ when the site's tenant has not enabled image search, and when `photo.id` is
258
+ not a media UUID — `getListing` uses `image-N` when Typesense has no id for
259
+ that photo and `external-N` for video or tour. That returns locally, without
260
+ a request, so the example above hides the section instead of throwing. Items
261
+ are `{ listing, matchedPhoto: { id, src, alt, caption, distance } }` with the
262
+ same card shape as `getListings`. Only public photos of public, active
263
+ listings are compared; the reference listing (and its sale/rental twin) is
264
+ never returned. `limit` defaults to 6 and caps at 12.
265
+
131
266
  ## CMS example
132
267
 
133
268
  ```tsx
@@ -244,12 +379,64 @@ Works wherever `fetch` is available:
244
379
  - Edge runtime (Vercel Edge, Cloudflare Workers, Deno)
245
380
  - Browsers (use carefully — see "Public keys" below)
246
381
 
247
- ## Public keys & rate limiting (roadmap)
382
+ ## Publishable keys & rate limits
248
383
 
249
- Today every fetcher is anonymous. As the SDK approaches public launch we'll
250
- add **publishable keys** with per-tenant rate limits and a domain allowlist —
251
- no breaking changes to the call sites, just an additional `publishableKey`
252
- option on `createGaragemClient`.
384
+ Calls to `/api/sites/{siteId}/*` stay anonymous when you pass no key. A
385
+ **publishable key** (`pk_live_…`) is not a secret: it ships in the browser
386
+ bundle and only tells Foundation which site to meter. Create or rotate it
387
+ in Garagem at **Configurações → Sites → the site → API pública**
388
+ (`/configuracoes/sites/[siteId]`). Copy it into the client:
389
+
390
+ ```ts
391
+ import { createClient } from "@garagem-ai/site-sdk";
392
+
393
+ export const garagem = createClient({
394
+ siteId: process.env.NEXT_PUBLIC_GARAGEM_SITE_ID,
395
+ publishableKey: process.env.NEXT_PUBLIC_GARAGEM_PUBLISHABLE_KEY,
396
+ });
397
+ ```
398
+
399
+ `createClient` is an alias of `createGaragemClient`. The same
400
+ `publishableKey` option exists on every fetcher (`getListings`,
401
+ `getListing`, `getSite`, `getSearchUi`, `queryListings`, `searchListings`,
402
+ the CMS helpers, `getLeadUi`, `submitVisitLead`, `submitContactLead`) and
403
+ on `usePublicSearch`. The SDK sends it as `X-Garagem-Publishable-Key`.
404
+ `Authorization: Bearer pk_live_…` is accepted too. A blank value is treated
405
+ as no key.
406
+
407
+ ### Compatibility
408
+
409
+ | Request | Result |
410
+ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
411
+ | Site has no key, request has no key | Served. Anonymous per-IP budget. |
412
+ | Site has a key, request has no key | Served. Stricter anonymous per-IP budget (older bundles keep working). |
413
+ | Request key matches this site | Served. Shared per-site budget. |
414
+ | Request key is present but wrong | **401** `GaragemSdkError` with `reason: "invalid_publishable_key"`. A key never opens another site. |
415
+ | Browser `Origin` / `Referer` not on the site allowlist | **403** `reason: "origin_not_allowed"`. Empty allowlist means any origin. Requests with neither header (server-to-server, RSC) are not origin-checked. |
416
+ | Budget exceeded | **429** `reason: "rate_limited"`. `error.retryAfter` is seconds (also the `Retry-After` header). |
417
+
418
+ Lead POST (`submitVisitLead` / `submitContactLead`) throws `LeadSubmitError`
419
+ instead: `code: "unauthorized"` on 401, `code: "rate_limited"` on 429, with
420
+ `retryAfter` and `retryAfterSeconds`.
421
+
422
+ ### Defaults (hits per 60 seconds)
423
+
424
+ | Bucket | With key | No key configured | Key configured, request omitted it |
425
+ | ------------------------------------------------------------------------ | -------: | ----------------: | ---------------------------------: |
426
+ | `listings` (index, CMS entry lists) | 600 | 120 | 30 |
427
+ | `search` | 600 | 120 | 30 |
428
+ | `detail` (listing, similar, CMS entry) | 1200 | 300 | 60 |
429
+ | `config` (search UI, lead UI, locations, public config, CMS collections) | 300 | 120 | 30 |
430
+
431
+ Responses include `RateLimit-Limit`, `RateLimit-Remaining`,
432
+ `RateLimit-Reset`, and `RateLimit-Policy` (`{limit};w=60`). `Retry-After`
433
+ is added on a deny. The limiter is shared across Foundation instances in
434
+ the cell (cell-local Valkey). If that cache is down, the same window is
435
+ enforced in memory on the instance that handled the request.
436
+
437
+ First-party traffic from the Garagem site proxy is exempt. Set
438
+ `PUBLIC_SITE_RATE_LIMIT_MODE=observe` to count without denying, or `off`
439
+ to skip metering. Key and origin checks still run in both modes.
253
440
 
254
441
  ## Search UI (`@garagem-ai/site-sdk/react`)
255
442
 
@@ -284,6 +471,51 @@ SEO stable: count `<span data-slot="search-heading-count">` first, then
284
471
  `<h1 data-slot="search-heading-title">`. Hit count is never inside
285
472
  `<h1>`.
286
473
 
474
+ ## Photo search ("busca pelo que as fotos mostram")
475
+
476
+ Search a site's public catalog by what the photos show, and use the photo
477
+ that matched as the card cover. The tenant gate is `available`: when photo
478
+ search is off, the API answers `200` with `{ available: false, items: [] }`
479
+ so the site hides the control and keeps the regular search.
480
+
481
+ ```ts
482
+ import {
483
+ applyMatchedPhotoCover,
484
+ searchListingPhotos,
485
+ } from "@garagem-ai/site-sdk";
486
+
487
+ const photos = await searchListingPhotos("abc-123", {
488
+ q: "varanda gourmet com churrasqueira",
489
+ limit: 12,
490
+ page: 1,
491
+ });
492
+
493
+ if (!photos.available) {
494
+ // Regular search. Do not show an empty photo-search state.
495
+ }
496
+
497
+ // Nearest first, cover already chosen by the API.
498
+ const cards = applyMatchedPhotoCover(
499
+ photos.items.map((item) => item.listing),
500
+ photos
501
+ );
502
+ // cards[i].coverImage is the matched photo; cards[i].matchedPhoto is set.
503
+ ```
504
+
505
+ On the client, `usePublicPhotoSearch` from `@garagem-ai/site-sdk/react`
506
+ debounces the search box (default 400ms) and returns `listings` with the
507
+ cover already swapped. Pass `enabled: false` while the toggle is off.
508
+ `photos.listings` when the toggle is on and `photos.available` is true;
509
+ otherwise the regular `usePublicSearch` results. A keyword match
510
+ (`distance: null`) always replaces the cover; a vector match replaces it
511
+ only within `MATCHED_PHOTO_COVER_MAX_DISTANCE` (0.4), the same threshold as
512
+ the CRM "Foto que combina com a busca" switch.
513
+
514
+ Each distinct query costs one text embedding on the Garagem side. Results
515
+ are cached for ten minutes per site and query, and uncached queries are
516
+ rate limited per visitor and per site. Queries shorter than three characters
517
+ resolve locally and do not hit the API.
518
+
287
519
  ## What's NOT in this release
288
520
 
289
521
  - CMS writes / drafts (editor + CMS worker only).