@garagem-ai/site-sdk 0.6.1 → 0.7.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.
@@ -0,0 +1,101 @@
1
+ import { callJson, type FetchLike } from "./fetchers";
2
+ import { coerceSiteId, normalizeBaseUrl } from "./internal/url";
3
+ import type { RequestNextOptions } from "./types";
4
+ import type {
5
+ PhotoSearchItem,
6
+ PhotoSearchParams,
7
+ PhotoSearchResult,
8
+ } from "./types-photo-search";
9
+
10
+ export interface SearchListingPhotosOptions {
11
+ /** Garagem API base URL. Defaults to `https://app.garagem.ai`. */
12
+ baseUrl?: string;
13
+ /** Override the fetch implementation (testing, edge runtimes, retries). */
14
+ fetch?: FetchLike;
15
+ /** Next.js App Router caching hints. Ignored on other runtimes. */
16
+ next?: RequestNextOptions;
17
+ }
18
+
19
+ /** Shortest query the API will embed; shorter text returns the empty result locally. */
20
+ export const PHOTO_SEARCH_MIN_QUERY_LENGTH = 3;
21
+
22
+ const EMPTY_RESULT: PhotoSearchResult = {
23
+ available: true,
24
+ items: [],
25
+ total: 0,
26
+ page: 1,
27
+ limit: 12,
28
+ };
29
+
30
+ function positiveInt(value: number | undefined): number | null {
31
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1) {
32
+ return null;
33
+ }
34
+ return Math.floor(value);
35
+ }
36
+
37
+ /** Build the request URL (exported for tests and custom transports). */
38
+ export function photoSearchUrl(
39
+ siteId: string,
40
+ params: PhotoSearchParams,
41
+ baseUrl?: string
42
+ ): string {
43
+ const search = new URLSearchParams();
44
+ search.set("q", params.q.trim());
45
+ const limit = positiveInt(params.limit);
46
+ if (limit != null) search.set("limit", String(limit));
47
+ const page = positiveInt(params.page);
48
+ if (page != null) search.set("page", String(page));
49
+ return `${normalizeBaseUrl(baseUrl)}/api/sites/${encodeURIComponent(
50
+ siteId
51
+ )}/search/photos?${search.toString()}`;
52
+ }
53
+
54
+ /**
55
+ * Search a site's listings by what their public photos show.
56
+ *
57
+ * Returns `{ available: false, items: [] }` (not an error) when the tenant
58
+ * has not enabled photo search, so a site can hide the control. Queries
59
+ * shorter than {@link PHOTO_SEARCH_MIN_QUERY_LENGTH} resolve locally to an
60
+ * empty result without a request.
61
+ *
62
+ * @example
63
+ * const result = await searchListingPhotos("abc", { q: "varanda gourmet" });
64
+ * const cards = applyMatchedPhotoCover(
65
+ * result.items.map((item) => item.listing),
66
+ * result
67
+ * );
68
+ */
69
+ export async function searchListingPhotos(
70
+ siteId: string,
71
+ params: PhotoSearchParams,
72
+ options: SearchListingPhotosOptions = {}
73
+ ): Promise<PhotoSearchResult> {
74
+ const q = (params?.q ?? "").trim();
75
+ const limit = positiveInt(params?.limit) ?? EMPTY_RESULT.limit;
76
+ if (q.length < PHOTO_SEARCH_MIN_QUERY_LENGTH) {
77
+ return { ...EMPTY_RESULT, limit, page: positiveInt(params?.page) ?? 1 };
78
+ }
79
+ const resolvedSiteId = await coerceSiteId(siteId);
80
+ const url = photoSearchUrl(resolvedSiteId, { ...params, q }, options.baseUrl);
81
+ const data = await callJson<Partial<PhotoSearchResult>>(
82
+ url,
83
+ {
84
+ method: "GET",
85
+ headers: { Accept: "application/json" },
86
+ next: options.next,
87
+ },
88
+ options.fetch ?? fetch
89
+ );
90
+ const items: PhotoSearchItem[] = Array.isArray(data.items) ? data.items : [];
91
+ return {
92
+ available: data.available !== false,
93
+ items,
94
+ total: typeof data.total === "number" ? data.total : items.length,
95
+ page:
96
+ typeof data.page === "number"
97
+ ? data.page
98
+ : (positiveInt(params.page) ?? 1),
99
+ limit: typeof data.limit === "number" ? data.limit : limit,
100
+ };
101
+ }
package/src/index.ts CHANGED
@@ -259,6 +259,8 @@ export {
259
259
  studioListingDetailInstruction,
260
260
  studioSearchInstruction,
261
261
  studioSearchLandmarkInstruction,
262
+ studioPhotoSearchInstruction,
263
+ isPhotoSearchOnPin,
262
264
  studioSdkPinInstruction,
263
265
  studioSiteWidthCss,
264
266
  hasShowcaseLeadsPostUrl,
@@ -271,3 +273,62 @@ export {
271
273
  type CreateGaragemClientOptions,
272
274
  type GaragemClient,
273
275
  } from "./client";
276
+
277
+ // ---------------------------------------------------------------------------
278
+ // Market data (requires the IPTU module — `iptu_itbi_integration`).
279
+ // Self-contained block: fetchers, headless pt-BR labels and types. Every
280
+ // helper answers `available: false` for tenants without the module.
281
+ // ---------------------------------------------------------------------------
282
+ export {
283
+ getListingMarketPosition,
284
+ getNeighborhoodSummary,
285
+ requestPriceEstimate,
286
+ type GetListingMarketPositionOptions,
287
+ type GetNeighborhoodSummaryOptions,
288
+ type RequestPriceEstimateOptions,
289
+ } from "./fetchers-market";
290
+
291
+ export { marketPositionLabel, priceBandLabel } from "./market-labels";
292
+
293
+ export type {
294
+ ListingMarketPosition,
295
+ MarketListingType,
296
+ MarketPriceBand,
297
+ MarketPropertyType,
298
+ MarketUnavailableReason,
299
+ NeighborhoodSummary,
300
+ NeighborhoodSummaryQuery,
301
+ PriceEstimate,
302
+ PriceEstimateConfidence,
303
+ PriceEstimateInput,
304
+ } from "./types-market";
305
+
306
+ export {
307
+ marketExportsAvailableAt,
308
+ studioMarketInstruction,
309
+ } from "./studio-contract";
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // Photo search ("busca pelo que as fotos mostram"): search a site's catalog by
313
+ // what the public photos show and use the matched photo as the card cover.
314
+ // Self-contained block — the React hook lives on `@garagem-ai/site-sdk/react`.
315
+ // ---------------------------------------------------------------------------
316
+ export {
317
+ PHOTO_SEARCH_MIN_QUERY_LENGTH,
318
+ photoSearchUrl,
319
+ searchListingPhotos,
320
+ type SearchListingPhotosOptions,
321
+ } from "./fetchers-photo-search";
322
+ export {
323
+ MATCHED_PHOTO_COVER_MAX_DISTANCE,
324
+ applyMatchedPhotoCover,
325
+ resolveMatchedCoverPhoto,
326
+ type ApplyMatchedPhotoCoverOptions,
327
+ } from "./photo-search-cover";
328
+ export type {
329
+ ListingWithMatchedPhoto,
330
+ MatchedListingPhoto,
331
+ PhotoSearchItem,
332
+ PhotoSearchParams,
333
+ PhotoSearchResult,
334
+ } from "./types-photo-search";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Headless pt-BR labels for the market-data blocks. Every helper returns
3
+ * `null` when there is nothing to say (unavailable, missing numbers), so a
4
+ * component can `label && <p>{label}</p>` without re-checking `available`.
5
+ */
6
+ import type { ListingMarketPosition, MarketPriceBand } from "./types-market";
7
+
8
+ /**
9
+ * "8% abaixo da mediana do bairro" / "12% acima da mediana do bairro" /
10
+ * "Na mediana do bairro". `null` when the position is unavailable.
11
+ */
12
+ export function marketPositionLabel(
13
+ position:
14
+ | Pick<ListingMarketPosition, "available" | "percentVsMedian">
15
+ | null
16
+ | undefined
17
+ ): string | null {
18
+ if (!position?.available) return null;
19
+ const percent = position.percentVsMedian;
20
+ if (percent == null || !Number.isFinite(percent)) return null;
21
+ const rounded = Math.round(percent);
22
+ if (rounded === 0) return "Na mediana do bairro";
23
+ const magnitude = Math.abs(rounded);
24
+ return rounded < 0
25
+ ? `${magnitude}% abaixo da mediana do bairro`
26
+ : `${magnitude}% acima da mediana do bairro`;
27
+ }
28
+
29
+ const BAND_LABELS: Record<MarketPriceBand, string> = {
30
+ below_range: "Abaixo da faixa do bairro",
31
+ lower_range: "Na faixa do bairro, abaixo da mediana",
32
+ upper_range: "Na faixa do bairro, acima da mediana",
33
+ above_range: "Acima da faixa do bairro",
34
+ };
35
+
36
+ /**
37
+ * Quartile band copy. Accepts the band itself or a position; `null` when
38
+ * the band is missing or the position is unavailable.
39
+ */
40
+ export function priceBandLabel(
41
+ input:
42
+ | MarketPriceBand
43
+ | Pick<ListingMarketPosition, "available" | "band">
44
+ | null
45
+ | undefined
46
+ ): string | null {
47
+ if (!input) return null;
48
+ if (typeof input === "string") return BAND_LABELS[input] ?? null;
49
+ if (!input.available || !input.band) return null;
50
+ return BAND_LABELS[input.band] ?? null;
51
+ }
@@ -0,0 +1,90 @@
1
+ import type { Listing } from "./types";
2
+ import type {
3
+ ListingWithMatchedPhoto,
4
+ MatchedListingPhoto,
5
+ PhotoSearchItem,
6
+ PhotoSearchResult,
7
+ } from "./types-photo-search";
8
+
9
+ /**
10
+ * Largest vector distance a photo may have and still replace the cover.
11
+ * Mirrors the CRM "Foto que combina com a busca" threshold
12
+ * (`MATCHED_PHOTO_COVER_MAX_DISTANCE` in apps/foundation); keyword matches
13
+ * (`distance: null`) are exact caption / room-type matches and always win.
14
+ */
15
+ export const MATCHED_PHOTO_COVER_MAX_DISTANCE = 0.4;
16
+
17
+ export interface ApplyMatchedPhotoCoverOptions {
18
+ /** Override {@link MATCHED_PHOTO_COVER_MAX_DISTANCE}. `Infinity` accepts every match. */
19
+ maxDistance?: number;
20
+ }
21
+
22
+ /**
23
+ * The photo that replaces a card cover, or `null` to keep the card's own
24
+ * cover: keyword matches as-is, vector matches only within `maxDistance`.
25
+ */
26
+ export function resolveMatchedCoverPhoto(
27
+ photo: MatchedListingPhoto | null | undefined,
28
+ maxDistance: number = MATCHED_PHOTO_COVER_MAX_DISTANCE
29
+ ): MatchedListingPhoto | null {
30
+ if (!photo || !photo.src) return null;
31
+ if (photo.distance == null) return photo;
32
+ if (!Number.isFinite(photo.distance)) return null;
33
+ return photo.distance <= maxDistance ? photo : null;
34
+ }
35
+
36
+ function itemsOf(
37
+ photoResults:
38
+ | PhotoSearchResult
39
+ | ReadonlyArray<PhotoSearchItem>
40
+ | null
41
+ | undefined
42
+ ): ReadonlyArray<PhotoSearchItem> {
43
+ if (!photoResults) return [];
44
+ return Array.isArray(photoResults)
45
+ ? photoResults
46
+ : ((photoResults as PhotoSearchResult).items ?? []);
47
+ }
48
+
49
+ /**
50
+ * Headless mirror of the CRM cover switch: for every card whose listing has
51
+ * a photo-search match, swap `coverImage` for the matched photo and attach
52
+ * it as `matchedPhoto`. Cards without a match (or whose match is too far)
53
+ * keep their cover with `matchedPhoto: null`. Order is preserved — pass
54
+ * `result.items.map((item) => item.listing)` to render the photo-search
55
+ * page nearest-first, or the regular search page to only swap covers.
56
+ *
57
+ * @example
58
+ * const cards = applyMatchedPhotoCover(search.listings, photos.items);
59
+ * cards.map((card) => <Card model={toListingCardModel(card)} badge={card.matchedPhoto} />)
60
+ */
61
+ export function applyMatchedPhotoCover<T extends Listing>(
62
+ cards: ReadonlyArray<T>,
63
+ photoResults:
64
+ | PhotoSearchResult
65
+ | ReadonlyArray<PhotoSearchItem>
66
+ | null
67
+ | undefined,
68
+ options: ApplyMatchedPhotoCoverOptions = {}
69
+ ): Array<T & ListingWithMatchedPhoto> {
70
+ const maxDistance = options.maxDistance ?? MATCHED_PHOTO_COVER_MAX_DISTANCE;
71
+ const photoByListingId = new Map<string, MatchedListingPhoto>();
72
+ for (const item of itemsOf(photoResults)) {
73
+ const id = item?.listing?.id;
74
+ if (!id || photoByListingId.has(id)) continue;
75
+ const photo = resolveMatchedCoverPhoto(item.matchedPhoto, maxDistance);
76
+ if (photo) photoByListingId.set(id, photo);
77
+ }
78
+ return cards.map((card) => {
79
+ const photo = photoByListingId.get(card.id) ?? null;
80
+ if (!photo) return { ...card, matchedPhoto: null };
81
+ return {
82
+ ...card,
83
+ coverImage: {
84
+ src: photo.src,
85
+ alt: photo.alt || card.coverImage?.alt || card.title,
86
+ },
87
+ matchedPhoto: photo,
88
+ };
89
+ });
90
+ }
@@ -7,3 +7,11 @@ export type {
7
7
  SiteIdInput,
8
8
  UsePublicSearchOptions,
9
9
  } from "./types";
10
+
11
+ // --- Photo search ("busca pelo que as fotos mostram") ----------------------
12
+ export {
13
+ PHOTO_SEARCH_DEBOUNCE_MS,
14
+ usePublicPhotoSearch,
15
+ type PublicPhotoSearchState,
16
+ type UsePublicPhotoSearchOptions,
17
+ } from "./use-public-photo-search";
@@ -0,0 +1,165 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+
5
+ import type { FetchLike } from "../fetchers";
6
+ import {
7
+ PHOTO_SEARCH_MIN_QUERY_LENGTH,
8
+ searchListingPhotos,
9
+ } from "../fetchers-photo-search";
10
+ import { coerceSiteId } from "../internal/url";
11
+ import { applyMatchedPhotoCover } from "../photo-search-cover";
12
+ import type {
13
+ ListingWithMatchedPhoto,
14
+ PhotoSearchItem,
15
+ PhotoSearchResult,
16
+ } from "../types-photo-search";
17
+ import type { SiteIdInput } from "./types";
18
+
19
+ /** Same debounce as the CRM "Foto que combina com a busca" evidence lane. */
20
+ export const PHOTO_SEARCH_DEBOUNCE_MS = 400;
21
+
22
+ export type UsePublicPhotoSearchOptions = {
23
+ siteId: SiteIdInput;
24
+ baseUrl?: string;
25
+ /**
26
+ * The text to search by (usually the main search box). The hook trims it,
27
+ * debounces requests and ignores responses that arrive out of order.
28
+ */
29
+ query: string;
30
+ /** Listings per page (API default 12, cap 24). */
31
+ limit?: number;
32
+ /** 1-based page. */
33
+ page?: number;
34
+ /** `false` pauses the hook and clears its results (e.g. a hidden panel). */
35
+ enabled?: boolean;
36
+ /** Milliseconds to wait after the last `query` change. Default 400. */
37
+ debounceMs?: number;
38
+ /** Override the fetch implementation (testing, retries). */
39
+ fetch?: FetchLike;
40
+ };
41
+
42
+ export type PublicPhotoSearchState = {
43
+ /** `false` once the API says the tenant has no photo search: hide the UI. */
44
+ available: boolean;
45
+ /** Nearest-first matches, each with its card and matched photo. */
46
+ items: PhotoSearchItem[];
47
+ /** `items` as cards with the matched photo already applied as cover. */
48
+ listings: ListingWithMatchedPhoto[];
49
+ total: number;
50
+ page: number;
51
+ limit: number;
52
+ /** A request is in flight (or scheduled by the debounce). */
53
+ loading: boolean;
54
+ error: Error | null;
55
+ /** The trimmed query the current `items` answer (`""` before the first result). */
56
+ query: string;
57
+ };
58
+
59
+ const EMPTY: PhotoSearchResult = {
60
+ available: true,
61
+ items: [],
62
+ total: 0,
63
+ page: 1,
64
+ limit: 12,
65
+ };
66
+
67
+ async function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {
68
+ const value = typeof siteId === "function" ? siteId() : siteId;
69
+ return coerceSiteId(value);
70
+ }
71
+
72
+ export function usePublicPhotoSearch(
73
+ options: UsePublicPhotoSearchOptions
74
+ ): PublicPhotoSearchState {
75
+ const {
76
+ siteId,
77
+ baseUrl,
78
+ limit,
79
+ page,
80
+ enabled = true,
81
+ debounceMs = PHOTO_SEARCH_DEBOUNCE_MS,
82
+ fetch: fetchImpl,
83
+ } = options;
84
+ const query = (options.query ?? "").trim();
85
+ const searchable = enabled && query.length >= PHOTO_SEARCH_MIN_QUERY_LENGTH;
86
+
87
+ const siteIdRef = useRef(siteId);
88
+ siteIdRef.current = siteId;
89
+ const siteIdToken = typeof siteId === "string" ? siteId : null;
90
+ const fetchRef = useRef(fetchImpl);
91
+ fetchRef.current = fetchImpl;
92
+ const requestRef = useRef(0);
93
+
94
+ const [result, setResult] = useState<PhotoSearchResult>(EMPTY);
95
+ const [answered, setAnswered] = useState("");
96
+ const [loading, setLoading] = useState(searchable);
97
+ const [error, setError] = useState<Error | null>(null);
98
+
99
+ useEffect(() => {
100
+ const requestId = ++requestRef.current;
101
+ if (!searchable) {
102
+ setResult(EMPTY);
103
+ setAnswered("");
104
+ setLoading(false);
105
+ setError(null);
106
+ return;
107
+ }
108
+ setLoading(true);
109
+ let active = true;
110
+ let timer: ReturnType<typeof setTimeout> | null = null;
111
+ const run = () => {
112
+ void (async () => {
113
+ try {
114
+ const id = await resolveSiteIdInput(siteIdRef.current);
115
+ const next = await searchListingPhotos(
116
+ id,
117
+ { q: query, limit, page },
118
+ { baseUrl, fetch: fetchRef.current }
119
+ );
120
+ if (!active || requestId !== requestRef.current) return;
121
+ setResult(next);
122
+ setAnswered(query);
123
+ setError(null);
124
+ } catch (caught) {
125
+ if (!active || requestId !== requestRef.current) return;
126
+ setResult(EMPTY);
127
+ setAnswered(query);
128
+ setError(
129
+ caught instanceof Error ? caught : new Error(String(caught))
130
+ );
131
+ } finally {
132
+ if (active && requestId === requestRef.current) setLoading(false);
133
+ }
134
+ })();
135
+ };
136
+ // `0` means no wait. A zero-delay timer still yields a macrotask.
137
+ if (debounceMs <= 0) run();
138
+ else timer = setTimeout(run, debounceMs);
139
+ return () => {
140
+ active = false;
141
+ if (timer != null) clearTimeout(timer);
142
+ };
143
+ }, [searchable, query, limit, page, baseUrl, siteIdToken, debounceMs]);
144
+
145
+ const listings = useMemo(
146
+ () =>
147
+ applyMatchedPhotoCover(
148
+ result.items.map((item) => item.listing),
149
+ result.items
150
+ ),
151
+ [result.items]
152
+ );
153
+
154
+ return {
155
+ available: result.available,
156
+ items: result.items,
157
+ listings,
158
+ total: result.total,
159
+ page: result.page,
160
+ limit: result.limit,
161
+ loading,
162
+ error,
163
+ query: answered,
164
+ };
165
+ }
@@ -36,7 +36,9 @@ export const STUDIO_SDK_CONTRACT = {
36
36
  * “never import”) — v0 copies the identifier and the preview ESM loader
37
37
  * throws FatalRendererError.
38
38
  */
39
- optionalReactExports: {} as Record<string, string>,
39
+ optionalReactExports: {
40
+ usePublicPhotoSearch: "0.7.0",
41
+ } as Record<string, string>,
40
42
  /**
41
43
  * Former `/react` chrome (including card/skeleton inject). Completeness
42
44
  * flags imports as mismatch (not in `reactExports`). Prompts must not
@@ -121,10 +123,49 @@ export const STUDIO_SDK_CONTRACT = {
121
123
  "searchChromeModel",
122
124
  "rangeDraftFromPath",
123
125
  ] as const,
126
+ /**
127
+ * Market-data helpers (neighborhood price summary, listing market
128
+ * position, visitor price estimate, pt-BR labels). They ship in
129
+ * `marketExportsSince` and are prompt-safe only once `minNpmVersion`
130
+ * reaches that release; below it `studioCodegenContractViolations` flags
131
+ * the names and `studioMarketInstruction()` tells Studio not to generate
132
+ * the blocks at all. Every helper answers `available: false` unless the
133
+ * site's organization holds the IPTU module (`iptu_itbi_integration`)
134
+ * and the city is covered — generated sites render these blocks
135
+ * conditionally and never show cadastral or transaction data.
136
+ */
137
+ marketExports: [
138
+ "getNeighborhoodSummary",
139
+ "getListingMarketPosition",
140
+ "requestPriceEstimate",
141
+ "marketPositionLabel",
142
+ "priceBandLabel",
143
+ ] as const,
144
+ marketExportsSince: "0.7.0",
145
+ /**
146
+ * Photo search ("busca pelo que as fotos mostram"): main-package helpers
147
+ * that ship together with the `/react` hook listed in
148
+ * `optionalReactExports` (`usePublicPhotoSearch`). Prompt-safe only once
149
+ * `minNpmVersion` reaches `photoSearchSince` — `studioPhotoSearchInstruction`
150
+ * and the Studio guidance print nothing before that, and
151
+ * `studioCodegenContractViolations` flags the names until then.
152
+ */
153
+ photoSearchExports: [
154
+ "searchListingPhotos",
155
+ "applyMatchedPhotoCover",
156
+ ] as const,
157
+ photoSearchSince: "0.7.0",
124
158
  } as const;
125
159
 
126
160
  export type StudioSdkContract = typeof STUDIO_SDK_CONTRACT;
127
161
 
162
+ /** Whether the pinned tarball carries the photo-search surface. */
163
+ export function isPhotoSearchOnPin(
164
+ pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
165
+ ): boolean {
166
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.photoSearchSince) >= 0;
167
+ }
168
+
128
169
  /**
129
170
  * Global Studio content width. Mirrors Editor default `7xl` / `px-4`
130
171
  * without the Marca picker — v0 sites are not `@garagem/ui`.
@@ -231,7 +272,7 @@ export function unavailableReactImports(source: string, pin: string): string[] {
231
272
 
232
273
  export function studioSdkPinInstruction(): string {
233
274
  const version = STUDIO_SDK_CONTRACT.minNpmVersion;
234
- const names = STUDIO_SDK_CONTRACT.reactExports.join(", ");
275
+ const names = [...reactExportsAvailableAt(version)].join(", ");
235
276
  return `In \`package.json\` set \`"@garagem-ai/site-sdk": "${version}"\` (exact). Import only these \`${STUDIO_SDK_PACKAGE}/react\` names: ${names}.`;
236
277
  }
237
278
 
@@ -261,6 +302,46 @@ export function studioSearchInstruction(): string {
261
302
  return `Search: import ${reactNames} from \`${STUDIO_SDK_PACKAGE}/react\`. From \`${STUDIO_SDK_PACKAGE}\` import ${libNames}. Prefetch \`getSearchUi\` + \`queryListings\` on the server page. \`const search = usePublicSearch({ siteId, baseUrl: GARAGEM_API_BASE, search: searchFromServer, initial })\` where \`searchFromServer\` is \`new URLSearchParams(await searchParams).toString()\` — never shorthand \`{ search }\` beside \`const search =\` (temporal dead zone). Do not wrap this UI in \`<Suspense>\` and do not add a route \`loading\` file — heading and cards are ordinary elements in the document, visible with JavaScript off. Compose the page UI in the app — do not paste a canonical search TSX. Required chrome (design is free; omit none): query (\`qDraft\` / \`setQDraft\` / form \`preventDefault\` + \`submitQuery\`), heading (count span FIRST then h1 from \`searchResultsHeading(search.pathFilters, search.schema?.dictionary, search.locationNames)\` — never \`searchResultsHeading({})\`), toolbar (\`toolbarFilterIds\` + \`applyFilter\`; range “Atualizar” on that toolbar item only) vs sheet (\`visibleSearchFilters\` extras, \`stageFilter\`, one footer \`applyStaged\`), sort (\`searchSortOptions\` + \`setSort\`; first option id is \`""\` / “Mais relevantes” — map **only** that empty id to Select sentinel \`"relevancia"\` (\`opt.id || "relevancia"\`), never \`SelectItem value=""\` and never give “Mais recentes” (\`id: "recentes"\`, \`?ordenar=recentes\`) that sentinel; on change \`setSort(id === "relevancia" ? "" : id)\` so recentes stays recentes. Closed trigger shows the option \`.label\`, never \`{search.applied.sort}\`), grid (\`listings.map\` + the site listing-card module; listing-card-skeleton only for a slot whose content is still unknown, never as a Suspense fallback; do not \`throw\` in that chrome), pagination (\`paginationPages\` + \`hrefWithExplicitPage\`). Never interpolate \`schema\`, \`pathFilters\`, or a filter object as a React child. \`queryListings\` key is \`params\`. The URL is the document. Count text is \`{search.total}\` only. Heading is one row; font size lives on the container and the span and h1 use \`font-size: inherit\`. Sort trigger shows the option label (“Mais relevantes” when \`ordenar\` is absent), chevron at the end, same height as the toolbar controls. Toolbar ranges open a Popover form (not DropdownMenu — Menu typeahead swallows digit keys) whose submit calls \`applyFilter\`; the popup clips and the two inputs stay inside (\`min-w-0\`, no \`w-64\`). Reset min/max drafts when the popover opens and when the applied path range changes. The sheet omits toolbar ids (price, bedrooms) so Preço is never a heading without inputs. Sheet DialogContent uses \`h-[min(640px,85dvh)]\` (not max-h alone) so the body ScrollArea can move. Tipo de imóvel, características and comodidades each use a nested ScrollArea with \`h-56 overflow-hidden\` (viewport \`h-full\`). Area is two inputs in schema order with no “Aplicar”; the footer stages then applyStaged. Never read \`staged[filter.id]\` — path keys are \`bedrooms\` / \`listingType\` / \`bathrooms\`. Bedrooms Select reads \`pathFilters.bedrooms\` so \`/imoveis/4-quartos\` checks \`"4"\` and shows the same trigger dot as price. Bathrooms and parking pressed state uses \`pathFilterHasOption\`. Limpar keeps location plus toolbar price and bedrooms via \`clearStagedPathFilters\` and \`toolbarFilterIds\`; do not call \`clearStaged\` for that button. It enables only when staged has a path filter other than location and those kept toolbar ids. Each multi-select \`stageFilter\` value is one option id, never a concatenated slug; \`checked\` uses \`pathFilterHasOption\`. Listing type does not pass the clicked id: no path value shows every checkbox checked, unchecking one stages the other option's id, and the last box stays checked. Price inputs use formatGroupedInteger. The closed price and bedrooms triggers keep the filter label plus a dot when set — never the literal range. Empty price calls applyFilter(id, undefined); never send 0 or 1000000000. Area is a plain integer (not that mask). The results button stageFilter property_area_total with both drafts, then applyStaged. Never send 0 or 100000. Count buttons pass the option id (\`"2"\`), never the label \`"2+"\`. Property type, features, and amenities render in pt-BR label order. Do not set \`[data-slot="search-sort"] { flex-direction: column }\` in a \`<style>\` tag; that selector is row so the chevron sits beside the label. Empty copy: ${JSON.stringify(SEARCH_EMPTY_COPY)}`;
262
303
  }
263
304
 
305
+ /** True when the pinned tarball ships the market-data helpers. */
306
+ export function marketExportsAvailableAt(pin: string): boolean {
307
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.marketExportsSince) >= 0;
308
+ }
309
+
310
+ /**
311
+ * Market-data blocks (neighborhood price summary, listing market position,
312
+ * visitor price estimate). Names appear only when the pin ships them; below
313
+ * that pin the instruction carries no identifiers (v0 copies any it sees).
314
+ */
315
+ export function studioMarketInstruction(
316
+ pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
317
+ ): string {
318
+ if (!marketExportsAvailableAt(pin)) {
319
+ return `Market data (neighborhood price summary, listing market position, visitor price estimate): NOT available on this SDK pin. Do not generate these blocks and do not invent a local price index. **IPTU module required.** These blocks exist only for a site whose organization holds the IPTU module (\`iptu_itbi_integration\`); without it every helper answers \`{ available: false }\` (HTTP 200) and the section must not render — omit the heading too. Even when the module is on, the payload is aggregates and a trimmed estimate only: never show cadastral ids, IPTU lookups, ITBI transactions, comparables, or unit inventory.`;
320
+ }
321
+ const [summary, position, estimate, positionLabel, bandLabel] =
322
+ STUDIO_SDK_CONTRACT.marketExports;
323
+ const names = STUDIO_SDK_CONTRACT.marketExports.join(", ");
324
+ return `Market data: import ${names} from \`${STUDIO_SDK_PACKAGE}\`. **IPTU module required.** Every helper returns \`{ available: false, reason }\` (HTTP 200, never a throw) unless the site's organization has the IPTU module (\`iptu_itbi_integration\`) and the city is covered — most sites get \`available: false\`. ALWAYS render these blocks conditionally: \`if (!result.available) return null\` (omit the whole section, heading included); never a placeholder, never “dados indisponíveis”, never a local fallback number. The payloads carry only aggregates and a trimmed estimate — never render, request, or invent cadastral ids, IPTU lookups, ITBI transactions, comparables, or addresses from market data. Reasons are codes (\`module_not_enabled\`, \`city_unsupported\`, \`no_data\`, \`rate_limited\`, …) — do not print them. Three blocks (all optional, design is free):
325
+ - Neighborhood summary (listing detail, optionally search heading): \`const summary = await ${summary}({ siteId, baseUrl: GARAGEM_API_BASE, query: { city: listing.location.city, neighborhood: listing.location.neighborhood } })\`. Render \`summary.pricePerSqmFormatted.p25\` / \`.p50\` / \`.p75\` (strings, already \`R$ X/m²\`) and \`summary.sampleSize\` (“com base em N vendas”); omit the sample line when null.
326
+ - Listing market position (listing detail, near the price): \`const position = await ${position}({ siteId, baseUrl: GARAGEM_API_BASE, listingId: listing.id })\`. Copy comes from the helpers only: \`${positionLabel}(position)\` (“8% abaixo da mediana do bairro”) and \`${bandLabel}(position)\` (“Na faixa do bairro, abaixo da mediana”); both return \`null\` when unavailable — hide the line on \`null\`. Show \`position.listingPricePerSqmFormatted\` vs \`position.medianPricePerSqmFormatted\` if a comparison row is wanted. Do not compute the percent in the app.
327
+ - Visitor price estimate (\`/anunciar\` or a dedicated page, client component): a form with city, bairro, área (m²), quartos, vagas, tipo; on submit \`const estimate = await ${estimate}({ siteId, baseUrl: GARAGEM_API_BASE, input: { city, neighborhood, areaSqm, bedrooms, parkingSpots, propertyType } })\`. Render \`estimate.estimatedPriceFormatted\` with the range \`estimate.rangeLowFormatted\` – \`estimate.rangeHighFormatted\` and \`estimate.confidenceLabel\` mapped to pt-BR (alta / média / baixa). When \`available\` is false show \`estimate.message\` (pt-BR, already written) and the contact CTA. It is rate limited per visitor — disable the submit while pending. Never call it on page load.
328
+ Fetch on the server page (\`next: { revalidate: 900 }\`) for the summary and position; the estimate is a user action. Resolve \`siteId\` the same way as every other SDK call.`;
329
+ }
330
+
331
+ /**
332
+ * Photo search ("busca pelo que as fotos mostram") codegen instruction.
333
+ * Empty until the pinned tarball ships the surface (`photoSearchSince`), so
334
+ * no prompt names an identifier v0 cannot import.
335
+ */
336
+ export function studioPhotoSearchInstruction(
337
+ pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
338
+ ): string {
339
+ if (!isPhotoSearchOnPin(pin)) return "";
340
+ const hook = "usePublicPhotoSearch";
341
+ const [fetcher, cover] = STUDIO_SDK_CONTRACT.photoSearchExports;
342
+ return `Photo search (optional, same page as \`/imoveis\`): visitors can search by what the photos show ("varanda gourmet com churrasqueira"). From \`${STUDIO_SDK_PACKAGE}/react\` import ${hook}; from \`${STUDIO_SDK_PACKAGE}\` import ${fetcher} (server) and ${cover}. Client: \`const photos = ${hook}({ siteId, baseUrl: GARAGEM_API_BASE, query: search.qDraft, enabled: photoMode })\` where \`photoMode\` is a toggle beside the search box ("Buscar pelas fotos"). When \`photos.available === false\` do not render that toggle and keep the regular \`usePublicSearch\` results — the tenant has no photo lane. When it is on and \`photos.query\` is non-empty, render \`photos.listings\` (nearest first, cover already swapped, \`card.matchedPhoto\` for a small "Combina com a busca" badge) through the site listing-card module instead of \`search.listings\`; while \`photos.loading\` keep the previous cards. Fall back to the regular search results whenever \`photos.items\` is empty or \`photos.error\` is set. To only swap covers on the regular grid, \`${cover}(search.listings, photos.items)\` keeps the grid order and attaches \`matchedPhoto\`. Server pages use \`${fetcher}(siteId, { q, limit, page }, { baseUrl })\`. Cost: every distinct query costs one embedding on the Garagem side (results are cached ten minutes per site and query, and uncached queries are rate limited per visitor and per site), so never call it on every keystroke without the hook's debounce and never for the empty query.`;
343
+ }
344
+
264
345
  export function studioChromeInstruction(): string {
265
346
  return `Card, skeleton, and search chrome markup are app-owned. Never \`import "${STUDIO_SDK_CONTRACT.forbiddenImports[0]}"\` — v0 preview cannot load npm CSS. Do not mount an SDK stylesheet. Theme with site tokens and \`--radius\` in \`app/globals.css\`.`;
266
347
  }
@@ -275,7 +356,13 @@ function mentionsExportName(text: string, name: string): boolean {
275
356
  */
276
357
  export function studioCodegenContractViolations(text: string): string[] {
277
358
  const violations: string[] = [];
278
- for (const name of Object.keys(STUDIO_SDK_CONTRACT.optionalReactExports)) {
359
+ for (const [name, since] of Object.entries(
360
+ STUDIO_SDK_CONTRACT.optionalReactExports
361
+ )) {
362
+ // Prompt-safe once the pinned tarball carries the name (same rule as
363
+ // `reactExportsAvailableAt`); before that v0 would copy an import the
364
+ // preview ESM loader cannot resolve.
365
+ if (compareSemver(STUDIO_SDK_CONTRACT.minNpmVersion, since) >= 0) continue;
279
366
  if (mentionsExportName(text, name)) violations.push(name);
280
367
  }
281
368
  for (const name of STUDIO_SDK_CONTRACT.retiredReactExports) {
@@ -293,7 +380,21 @@ export function studioCodegenContractViolations(text: string): string[] {
293
380
  violations.push(name);
294
381
  }
295
382
  }
383
+ if (!isPhotoSearchOnPin()) {
384
+ for (const name of STUDIO_SDK_CONTRACT.photoSearchExports) {
385
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
386
+ violations.push(name);
387
+ }
388
+ }
389
+ }
296
390
  const pin = STUDIO_SDK_CONTRACT.minNpmVersion;
391
+ if (!marketExportsAvailableAt(pin)) {
392
+ for (const name of STUDIO_SDK_CONTRACT.marketExports) {
393
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
394
+ violations.push(name);
395
+ }
396
+ }
397
+ }
297
398
  const available = reactExportsAvailableAt(pin);
298
399
  for (const name of parseReactSdkNamedImports(text)) {
299
400
  if (!available.has(name) && !violations.includes(name)) {