@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 +260 -28
- package/dist/index.d.mts +488 -150
- package/dist/index.d.ts +488 -150
- package/dist/index.js +882 -36
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +857 -36
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +46 -2
- package/dist/react.d.ts +46 -2
- package/dist/react.js +334 -14
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +332 -14
- package/dist/react.mjs.map +1 -1
- package/dist/{search-engine-CtnLzmwW.d.mts → types-photo-search-CmGRj6my.d.mts} +229 -1
- package/dist/{search-engine-CtnLzmwW.d.ts → types-photo-search-CmGRj6my.d.ts} +229 -1
- package/package.json +2 -1
- package/src/client.ts +23 -0
- package/src/fetchers-market.ts +216 -0
- package/src/fetchers-photo-search.ts +101 -0
- package/src/fetchers-photos.ts +98 -0
- package/src/fetchers.ts +92 -29
- package/src/index.ts +92 -2
- package/src/internal/sdk-http.ts +122 -0
- package/src/leads.ts +34 -3
- package/src/listing-photos.ts +312 -0
- package/src/market-labels.ts +51 -0
- package/src/photo-search-cover.ts +90 -0
- package/src/react/index.ts +8 -0
- package/src/react/types.ts +5 -0
- package/src/react/use-public-photo-search.ts +165 -0
- package/src/react/use-public-search.ts +23 -5
- package/src/resolve-site-id.ts +3 -0
- package/src/studio-contract.ts +178 -3
- package/src/types-market.ts +138 -0
- package/src/types-photo-search.ts +55 -0
- package/src/types-photos.ts +46 -0
- package/src/types.ts +18 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Market-data fetchers for the public site.
|
|
3
|
+
*
|
|
4
|
+
* Requires the IPTU module: every call answers `{ available: false, reason }`
|
|
5
|
+
* unless the site's organization holds `iptu_itbi_integration`, the city
|
|
6
|
+
* is covered and the integration is configured. Render nothing in that
|
|
7
|
+
* case. A rate-limited call (HTTP 429) also comes back as
|
|
8
|
+
* `available: false` with `reason: "rate_limited"` instead of throwing, so
|
|
9
|
+
* a block can stay hidden without a try/catch; other non-2xx responses
|
|
10
|
+
* throw `GaragemSdkError` like the rest of the SDK.
|
|
11
|
+
*/
|
|
12
|
+
import { GaragemSdkError, callJson, type FetchLike } from "./fetchers";
|
|
13
|
+
import { listingLookupKey } from "./listing-path";
|
|
14
|
+
import { coerceSiteId, normalizeBaseUrl } from "./internal/url";
|
|
15
|
+
import type { RequestNextOptions } from "./types";
|
|
16
|
+
import type {
|
|
17
|
+
ListingMarketPosition,
|
|
18
|
+
NeighborhoodSummary,
|
|
19
|
+
NeighborhoodSummaryQuery,
|
|
20
|
+
PriceEstimate,
|
|
21
|
+
PriceEstimateInput,
|
|
22
|
+
} from "./types-market";
|
|
23
|
+
|
|
24
|
+
interface MarketBaseOptions {
|
|
25
|
+
/** Garagem API base URL. Defaults to `https://app.garagem.ai`. */
|
|
26
|
+
baseUrl?: string;
|
|
27
|
+
/** Override the fetch implementation (testing, edge runtimes, retries). */
|
|
28
|
+
fetch?: FetchLike;
|
|
29
|
+
/** Next.js App Router caching hints. Ignored elsewhere. */
|
|
30
|
+
next?: RequestNextOptions;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface GetNeighborhoodSummaryOptions extends MarketBaseOptions {
|
|
34
|
+
siteId: string;
|
|
35
|
+
query: NeighborhoodSummaryQuery;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface GetListingMarketPositionOptions extends MarketBaseOptions {
|
|
39
|
+
siteId: string;
|
|
40
|
+
/** Accepts a code, UUID, or `id-{code}` URL segment. */
|
|
41
|
+
listingId: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RequestPriceEstimateOptions extends MarketBaseOptions {
|
|
45
|
+
siteId: string;
|
|
46
|
+
input: PriceEstimateInput;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const RATE_LIMITED_MESSAGE =
|
|
50
|
+
"Muitas consultas em pouco tempo. Tente novamente em instantes.";
|
|
51
|
+
|
|
52
|
+
function isRateLimited(error: unknown): boolean {
|
|
53
|
+
return error instanceof GaragemSdkError && error.status === 429;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* P25 / P50 / P75 price per m² and sample size for a neighborhood.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* const summary = await getNeighborhoodSummary({
|
|
61
|
+
* siteId,
|
|
62
|
+
* query: { city: "São Paulo", neighborhood: "Moema" },
|
|
63
|
+
* next: { revalidate: 900 },
|
|
64
|
+
* });
|
|
65
|
+
* if (summary.available) render(summary.pricePerSqmFormatted.p50);
|
|
66
|
+
*/
|
|
67
|
+
export async function getNeighborhoodSummary(
|
|
68
|
+
options: GetNeighborhoodSummaryOptions
|
|
69
|
+
): Promise<NeighborhoodSummary> {
|
|
70
|
+
const { query, baseUrl, fetch: fetchImpl, next } = options;
|
|
71
|
+
const siteId = await coerceSiteId(options.siteId);
|
|
72
|
+
if (!query?.city?.trim() || !query?.neighborhood?.trim()) {
|
|
73
|
+
throw new TypeError(
|
|
74
|
+
"getNeighborhoodSummary: `query.city` and `query.neighborhood` are required"
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
const base = normalizeBaseUrl(baseUrl);
|
|
78
|
+
const params = new URLSearchParams();
|
|
79
|
+
params.set("city", query.city.trim());
|
|
80
|
+
params.set("neighborhood", query.neighborhood.trim());
|
|
81
|
+
if (query.propertyType) params.set("propertyType", query.propertyType);
|
|
82
|
+
if (query.type) params.set("type", query.type);
|
|
83
|
+
const url = `${base}/api/sites/${encodeURIComponent(siteId)}/market/neighborhood-summary?${params.toString()}`;
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
return await callJson<NeighborhoodSummary>(
|
|
87
|
+
url,
|
|
88
|
+
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
89
|
+
fetchImpl ?? fetch
|
|
90
|
+
);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (!isRateLimited(error)) throw error;
|
|
93
|
+
return {
|
|
94
|
+
available: false,
|
|
95
|
+
reason: "rate_limited",
|
|
96
|
+
city: query.city,
|
|
97
|
+
neighborhood: query.neighborhood,
|
|
98
|
+
propertyType: query.propertyType ?? null,
|
|
99
|
+
type: query.type ?? "sale",
|
|
100
|
+
months: 12,
|
|
101
|
+
pricePerSqmCents: { p25: null, p50: null, p75: null },
|
|
102
|
+
pricePerSqmFormatted: { p25: "—", p50: "—", p75: "—" },
|
|
103
|
+
sampleSize: null,
|
|
104
|
+
message: RATE_LIMITED_MESSAGE,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The listing's price per m² vs the neighborhood median, computed
|
|
111
|
+
* server-side from the public listing and the neighborhood summary.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* const position = await getListingMarketPosition({ siteId, listingId });
|
|
115
|
+
* const label = marketPositionLabel(position); // "8% abaixo da mediana do bairro"
|
|
116
|
+
*/
|
|
117
|
+
export async function getListingMarketPosition(
|
|
118
|
+
options: GetListingMarketPositionOptions
|
|
119
|
+
): Promise<ListingMarketPosition> {
|
|
120
|
+
const { listingId: rawListingId, baseUrl, fetch: fetchImpl, next } = options;
|
|
121
|
+
const siteId = await coerceSiteId(options.siteId);
|
|
122
|
+
const listingId = listingLookupKey(rawListingId ?? "");
|
|
123
|
+
if (!listingId || listingId === "undefined" || listingId === "null") {
|
|
124
|
+
throw new TypeError("getListingMarketPosition: `listingId` is required");
|
|
125
|
+
}
|
|
126
|
+
const base = normalizeBaseUrl(baseUrl);
|
|
127
|
+
const url = `${base}/api/sites/${encodeURIComponent(siteId)}/listings/${encodeURIComponent(
|
|
128
|
+
listingId
|
|
129
|
+
)}/market-position`;
|
|
130
|
+
|
|
131
|
+
try {
|
|
132
|
+
return await callJson<ListingMarketPosition>(
|
|
133
|
+
url,
|
|
134
|
+
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
135
|
+
fetchImpl ?? fetch
|
|
136
|
+
);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (!isRateLimited(error)) throw error;
|
|
139
|
+
return {
|
|
140
|
+
available: false,
|
|
141
|
+
reason: "rate_limited",
|
|
142
|
+
listingId,
|
|
143
|
+
city: null,
|
|
144
|
+
neighborhood: null,
|
|
145
|
+
months: 12,
|
|
146
|
+
listingPricePerSqmCents: null,
|
|
147
|
+
listingPricePerSqmFormatted: "—",
|
|
148
|
+
medianPricePerSqmCents: null,
|
|
149
|
+
medianPricePerSqmFormatted: "—",
|
|
150
|
+
percentVsMedian: null,
|
|
151
|
+
band: null,
|
|
152
|
+
sampleSize: null,
|
|
153
|
+
message: RATE_LIMITED_MESSAGE,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Trimmed automated valuation (estimate, range, confidence) for
|
|
160
|
+
* visitor-entered characteristics. Never returns comparables.
|
|
161
|
+
*
|
|
162
|
+
* Limited per IP and per site; a limited call answers
|
|
163
|
+
* `reason: "rate_limited"`.
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* const estimate = await requestPriceEstimate({
|
|
167
|
+
* siteId,
|
|
168
|
+
* input: { city: "sp", neighborhood: "Moema", areaSqm: 80, bedrooms: 2 },
|
|
169
|
+
* });
|
|
170
|
+
*/
|
|
171
|
+
export async function requestPriceEstimate(
|
|
172
|
+
options: RequestPriceEstimateOptions
|
|
173
|
+
): Promise<PriceEstimate> {
|
|
174
|
+
const { input, baseUrl, fetch: fetchImpl, next } = options;
|
|
175
|
+
const siteId = await coerceSiteId(options.siteId);
|
|
176
|
+
if (!input?.city?.trim() || typeof input.areaSqm !== "number") {
|
|
177
|
+
throw new TypeError(
|
|
178
|
+
"requestPriceEstimate: `input.city` and `input.areaSqm` are required"
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
const base = normalizeBaseUrl(baseUrl);
|
|
182
|
+
const url = `${base}/api/sites/${encodeURIComponent(siteId)}/market/estimate`;
|
|
183
|
+
|
|
184
|
+
try {
|
|
185
|
+
return await callJson<PriceEstimate>(
|
|
186
|
+
url,
|
|
187
|
+
{
|
|
188
|
+
method: "POST",
|
|
189
|
+
headers: {
|
|
190
|
+
Accept: "application/json",
|
|
191
|
+
"Content-Type": "application/json",
|
|
192
|
+
},
|
|
193
|
+
body: JSON.stringify(input),
|
|
194
|
+
next,
|
|
195
|
+
},
|
|
196
|
+
fetchImpl ?? fetch
|
|
197
|
+
);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (!isRateLimited(error)) throw error;
|
|
200
|
+
return {
|
|
201
|
+
available: false,
|
|
202
|
+
reason: "rate_limited",
|
|
203
|
+
city: input.city,
|
|
204
|
+
neighborhood: input.neighborhood ?? null,
|
|
205
|
+
estimatedPriceCents: null,
|
|
206
|
+
estimatedPriceFormatted: "—",
|
|
207
|
+
rangeLowCents: null,
|
|
208
|
+
rangeHighCents: null,
|
|
209
|
+
rangeLowFormatted: "—",
|
|
210
|
+
rangeHighFormatted: "—",
|
|
211
|
+
confidenceLabel: null,
|
|
212
|
+
sampleSize: null,
|
|
213
|
+
message: RATE_LIMITED_MESSAGE,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "Imóveis com fotos parecidas" fetcher.
|
|
3
|
+
*
|
|
4
|
+
* Self-contained beside `./fetchers`: same base-URL / fetch / `next`
|
|
5
|
+
* conventions, positional ids so a gallery click can call
|
|
6
|
+
* `getSimilarByPhoto(siteId, listing.id, photo.id)` directly.
|
|
7
|
+
*/
|
|
8
|
+
import { callJson, type FetchLike } from "./fetchers";
|
|
9
|
+
import { coerceSiteId, normalizeBaseUrl } from "./internal/url";
|
|
10
|
+
import { listingLookupKey } from "./listing-path";
|
|
11
|
+
import type { RequestNextOptions } from "./types";
|
|
12
|
+
import type { SimilarByPhotoItem, SimilarByPhotoResult } from "./types-photos";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Loose 8-4-4-4-12 hex, matching the public API's `isUuid(..., "loose")`.
|
|
16
|
+
* `getListing` also emits `image-N` (no UUID in `image_ids`) and `external-N`
|
|
17
|
+
* (video/tour). Those are gallery keys, not media ids.
|
|
18
|
+
*/
|
|
19
|
+
const MEDIA_UUID_RE =
|
|
20
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
21
|
+
|
|
22
|
+
const HIDDEN_SIMILAR_PHOTOS: SimilarByPhotoResult = {
|
|
23
|
+
available: false,
|
|
24
|
+
items: [],
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export interface GetSimilarByPhotoOptions {
|
|
28
|
+
/** Garagem API base URL. Defaults to `https://app.garagem.ai`. */
|
|
29
|
+
baseUrl?: string;
|
|
30
|
+
/** Override the fetch implementation (testing, edge runtimes, retries). */
|
|
31
|
+
fetch?: FetchLike;
|
|
32
|
+
/** Next.js App Router caching hints. Ignored elsewhere. */
|
|
33
|
+
next?: RequestNextOptions;
|
|
34
|
+
/** Max similar listings to return (API default 6, cap 12). */
|
|
35
|
+
limit?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Listings whose public photos look like one photo of `listingId`.
|
|
40
|
+
*
|
|
41
|
+
* `available` is `false` when the site's tenant has no image search, and
|
|
42
|
+
* when `mediaId` is not a media UUID (`image-N`, `external-N`, or any other
|
|
43
|
+
* gallery key `getListing` assigned). That case returns locally, without a
|
|
44
|
+
* request, so a page that passes `photo.id` hides the block instead of
|
|
45
|
+
* throwing. Items carry the public card model plus the photo that matched.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* const { available, items } = await getSimilarByPhoto(
|
|
49
|
+
* siteId,
|
|
50
|
+
* listing.id,
|
|
51
|
+
* photo.id,
|
|
52
|
+
* { limit: 6, next: { revalidate: 300 } }
|
|
53
|
+
* );
|
|
54
|
+
*/
|
|
55
|
+
export async function getSimilarByPhoto(
|
|
56
|
+
siteId: string,
|
|
57
|
+
listingId: string,
|
|
58
|
+
mediaId: string,
|
|
59
|
+
options: GetSimilarByPhotoOptions = {}
|
|
60
|
+
): Promise<SimilarByPhotoResult> {
|
|
61
|
+
const { baseUrl, fetch: fetchImpl, next, limit } = options;
|
|
62
|
+
const resolvedSiteId = await coerceSiteId(siteId);
|
|
63
|
+
const lookupId = listingLookupKey(listingId ?? "");
|
|
64
|
+
if (!lookupId || lookupId === "undefined" || lookupId === "null") {
|
|
65
|
+
throw new TypeError("getSimilarByPhoto: `listingId` is required");
|
|
66
|
+
}
|
|
67
|
+
const photoId = typeof mediaId === "string" ? mediaId.trim() : "";
|
|
68
|
+
if (!photoId) {
|
|
69
|
+
throw new TypeError("getSimilarByPhoto: `mediaId` is required");
|
|
70
|
+
}
|
|
71
|
+
// A synthetic gallery id 400s on the API; `callJson` would throw and the
|
|
72
|
+
// listing page that follows the README would fail instead of hiding.
|
|
73
|
+
if (!MEDIA_UUID_RE.test(photoId)) {
|
|
74
|
+
return HIDDEN_SIMILAR_PHOTOS;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const base = normalizeBaseUrl(baseUrl);
|
|
78
|
+
const params = new URLSearchParams({ mediaId: photoId });
|
|
79
|
+
if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) {
|
|
80
|
+
params.set("limit", String(Math.floor(limit)));
|
|
81
|
+
}
|
|
82
|
+
const url = `${base}/api/sites/${encodeURIComponent(resolvedSiteId)}/listings/${encodeURIComponent(
|
|
83
|
+
lookupId
|
|
84
|
+
)}/similar-photos?${params.toString()}`;
|
|
85
|
+
|
|
86
|
+
const data = await callJson<{
|
|
87
|
+
available?: boolean;
|
|
88
|
+
items?: SimilarByPhotoItem[];
|
|
89
|
+
}>(
|
|
90
|
+
url,
|
|
91
|
+
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
92
|
+
fetchImpl ?? fetch
|
|
93
|
+
);
|
|
94
|
+
return {
|
|
95
|
+
available: data.available !== false,
|
|
96
|
+
items: Array.isArray(data.items) ? data.items : [],
|
|
97
|
+
};
|
|
98
|
+
}
|
package/src/fetchers.ts
CHANGED
|
@@ -16,6 +16,11 @@ import type {
|
|
|
16
16
|
Site,
|
|
17
17
|
} from "./types";
|
|
18
18
|
import { listingLookupKey } from "./listing-path";
|
|
19
|
+
import {
|
|
20
|
+
parseSdkErrorBody,
|
|
21
|
+
retryAfterFromResponse,
|
|
22
|
+
withPublishableKeyHeader,
|
|
23
|
+
} from "./internal/sdk-http";
|
|
19
24
|
import {
|
|
20
25
|
buildListingFiltersQuery,
|
|
21
26
|
coerceSiteId,
|
|
@@ -36,6 +41,11 @@ interface BaseOptions {
|
|
|
36
41
|
* understand them.
|
|
37
42
|
*/
|
|
38
43
|
next?: RequestNextOptions;
|
|
44
|
+
/**
|
|
45
|
+
* Site publishable key (`pk_live_…`) from Configurações → Sites → API
|
|
46
|
+
* pública. Not a secret. Omit it and the request stays anonymous.
|
|
47
|
+
*/
|
|
48
|
+
publishableKey?: string;
|
|
39
49
|
}
|
|
40
50
|
|
|
41
51
|
export interface GetListingsOptions extends BaseOptions {
|
|
@@ -110,17 +120,15 @@ interface FetchInit extends RequestInit {
|
|
|
110
120
|
export async function callJson<T>(
|
|
111
121
|
url: string,
|
|
112
122
|
init: FetchInit,
|
|
113
|
-
fetchImpl: FetchLike
|
|
123
|
+
fetchImpl: FetchLike,
|
|
124
|
+
publishableKey?: string
|
|
114
125
|
): Promise<T> {
|
|
115
|
-
const response = await fetchImpl(
|
|
126
|
+
const response = await fetchImpl(
|
|
127
|
+
url,
|
|
128
|
+
withPublishableKeyHeader(init, publishableKey)
|
|
129
|
+
);
|
|
116
130
|
if (!response.ok) {
|
|
117
|
-
|
|
118
|
-
throw new GaragemSdkError(
|
|
119
|
-
`Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${
|
|
120
|
-
text ? ` — ${text.slice(0, 200)}` : ""
|
|
121
|
-
}`,
|
|
122
|
-
{ status: response.status, url }
|
|
123
|
-
);
|
|
131
|
+
throw await readGaragemSdkError(response, url);
|
|
124
132
|
}
|
|
125
133
|
return (await response.json()) as T;
|
|
126
134
|
}
|
|
@@ -129,14 +137,56 @@ export async function callJson<T>(
|
|
|
129
137
|
export class GaragemSdkError extends Error {
|
|
130
138
|
readonly status: number;
|
|
131
139
|
readonly url: string;
|
|
132
|
-
|
|
140
|
+
/** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
|
|
141
|
+
readonly reason: string | null;
|
|
142
|
+
/**
|
|
143
|
+
* Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
|
|
144
|
+
* or the body's `retryAfterSeconds`. `null` when the response has neither.
|
|
145
|
+
*/
|
|
146
|
+
readonly retryAfter: number | null;
|
|
147
|
+
constructor(
|
|
148
|
+
message: string,
|
|
149
|
+
info: {
|
|
150
|
+
status: number;
|
|
151
|
+
url: string;
|
|
152
|
+
reason?: string | null;
|
|
153
|
+
retryAfter?: number | null;
|
|
154
|
+
}
|
|
155
|
+
) {
|
|
133
156
|
super(message);
|
|
134
157
|
this.name = "GaragemSdkError";
|
|
135
158
|
this.status = info.status;
|
|
136
159
|
this.url = info.url;
|
|
160
|
+
this.reason = info.reason ?? null;
|
|
161
|
+
this.retryAfter = info.retryAfter ?? null;
|
|
137
162
|
}
|
|
138
163
|
}
|
|
139
164
|
|
|
165
|
+
/** Build a {@link GaragemSdkError} from a non-2xx response (reads the body). */
|
|
166
|
+
export async function readGaragemSdkError(
|
|
167
|
+
response: Response,
|
|
168
|
+
url: string
|
|
169
|
+
): Promise<GaragemSdkError> {
|
|
170
|
+
const text = await response.text().catch(() => "");
|
|
171
|
+
const parsed = parseSdkErrorBody(text);
|
|
172
|
+
const retryAfter =
|
|
173
|
+
response.status === 429
|
|
174
|
+
? retryAfterFromResponse(response, parsed.retryAfterSeconds)
|
|
175
|
+
: parsed.retryAfterSeconds;
|
|
176
|
+
const detail = parsed.summary;
|
|
177
|
+
return new GaragemSdkError(
|
|
178
|
+
`Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${
|
|
179
|
+
detail ? ` — ${detail}` : ""
|
|
180
|
+
}`,
|
|
181
|
+
{
|
|
182
|
+
status: response.status,
|
|
183
|
+
url,
|
|
184
|
+
reason: parsed.reason,
|
|
185
|
+
retryAfter,
|
|
186
|
+
}
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
140
190
|
/**
|
|
141
191
|
* Fetch a paginated list of listings for a given site.
|
|
142
192
|
*
|
|
@@ -160,7 +210,8 @@ export async function getListings(
|
|
|
160
210
|
const data = await callJson<{ listings?: Listing[]; total?: number }>(
|
|
161
211
|
url,
|
|
162
212
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
163
|
-
fetchImpl ?? fetch
|
|
213
|
+
fetchImpl ?? fetch,
|
|
214
|
+
options.publishableKey
|
|
164
215
|
);
|
|
165
216
|
return {
|
|
166
217
|
listings: data.listings ?? [],
|
|
@@ -189,7 +240,8 @@ export async function getListing(
|
|
|
189
240
|
return callJson<ListingDetail>(
|
|
190
241
|
url,
|
|
191
242
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
192
|
-
fetchImpl ?? fetch
|
|
243
|
+
fetchImpl ?? fetch,
|
|
244
|
+
options.publishableKey
|
|
193
245
|
);
|
|
194
246
|
}
|
|
195
247
|
|
|
@@ -224,17 +276,20 @@ export async function getSite(options: GetSiteOptions): Promise<Site | null> {
|
|
|
224
276
|
const url = `${base}/api/sites/resolve?${params.toString()}`;
|
|
225
277
|
|
|
226
278
|
const f = fetchImpl ?? fetch;
|
|
227
|
-
const response = await f(
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
279
|
+
const response = await f(
|
|
280
|
+
url,
|
|
281
|
+
withPublishableKeyHeader(
|
|
282
|
+
{
|
|
283
|
+
method: "GET",
|
|
284
|
+
headers: { Accept: "application/json" },
|
|
285
|
+
next,
|
|
286
|
+
},
|
|
287
|
+
options.publishableKey
|
|
288
|
+
) as FetchInit
|
|
289
|
+
);
|
|
232
290
|
if (response.status === 404) return null;
|
|
233
291
|
if (!response.ok) {
|
|
234
|
-
throw
|
|
235
|
-
`Garagem SDK: getSite failed (${response.status}) for ${url}`,
|
|
236
|
-
{ status: response.status, url }
|
|
237
|
-
);
|
|
292
|
+
throw await readGaragemSdkError(response, url);
|
|
238
293
|
}
|
|
239
294
|
const data = (await response.json()) as {
|
|
240
295
|
id: string;
|
|
@@ -295,7 +350,8 @@ export async function searchListings<TDocument = Record<string, unknown>>(
|
|
|
295
350
|
body: JSON.stringify(params),
|
|
296
351
|
next,
|
|
297
352
|
},
|
|
298
|
-
fetchImpl ?? fetch
|
|
353
|
+
fetchImpl ?? fetch,
|
|
354
|
+
options.publishableKey
|
|
299
355
|
);
|
|
300
356
|
}
|
|
301
357
|
|
|
@@ -313,7 +369,8 @@ export async function getSearchUi(
|
|
|
313
369
|
return callJson<SearchUi>(
|
|
314
370
|
url,
|
|
315
371
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
316
|
-
fetchImpl ?? fetch
|
|
372
|
+
fetchImpl ?? fetch,
|
|
373
|
+
options.publishableKey
|
|
317
374
|
);
|
|
318
375
|
}
|
|
319
376
|
|
|
@@ -339,7 +396,8 @@ export async function queryListings(
|
|
|
339
396
|
body: JSON.stringify(params ?? {}),
|
|
340
397
|
next,
|
|
341
398
|
},
|
|
342
|
-
fetchImpl ?? fetch
|
|
399
|
+
fetchImpl ?? fetch,
|
|
400
|
+
options.publishableKey
|
|
343
401
|
);
|
|
344
402
|
}
|
|
345
403
|
|
|
@@ -375,7 +433,8 @@ export async function getSimilarListings(
|
|
|
375
433
|
const data = await callJson<{ listings?: Listing[]; total?: number }>(
|
|
376
434
|
url,
|
|
377
435
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
378
|
-
fetchImpl ?? fetch
|
|
436
|
+
fetchImpl ?? fetch,
|
|
437
|
+
options.publishableKey
|
|
379
438
|
);
|
|
380
439
|
return {
|
|
381
440
|
listings: data.listings ?? [],
|
|
@@ -394,7 +453,8 @@ export async function getCmsCollections(
|
|
|
394
453
|
const data = await callJson<{ collections?: CmsCollection[] }>(
|
|
395
454
|
url,
|
|
396
455
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
397
|
-
fetchImpl ?? fetch
|
|
456
|
+
fetchImpl ?? fetch,
|
|
457
|
+
options.publishableKey
|
|
398
458
|
);
|
|
399
459
|
return data.collections ?? [];
|
|
400
460
|
}
|
|
@@ -415,7 +475,8 @@ export async function getCmsCollection(
|
|
|
415
475
|
const data = await callJson<{ collection?: CmsCollection } | CmsCollection>(
|
|
416
476
|
url,
|
|
417
477
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
418
|
-
fetchImpl ?? fetch
|
|
478
|
+
fetchImpl ?? fetch,
|
|
479
|
+
options.publishableKey
|
|
419
480
|
);
|
|
420
481
|
if (
|
|
421
482
|
data &&
|
|
@@ -460,7 +521,8 @@ export async function getCmsEntries(
|
|
|
460
521
|
const data = await callJson<Partial<CmsEntriesResult>>(
|
|
461
522
|
url,
|
|
462
523
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
463
|
-
fetchImpl ?? fetch
|
|
524
|
+
fetchImpl ?? fetch,
|
|
525
|
+
options.publishableKey
|
|
464
526
|
);
|
|
465
527
|
return {
|
|
466
528
|
entries: data.entries ?? [],
|
|
@@ -489,7 +551,8 @@ export async function getCmsEntry(
|
|
|
489
551
|
const data = await callJson<{ entry?: CmsEntry } | CmsEntry>(
|
|
490
552
|
url,
|
|
491
553
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
492
|
-
fetchImpl ?? fetch
|
|
554
|
+
fetchImpl ?? fetch,
|
|
555
|
+
options.publishableKey
|
|
493
556
|
);
|
|
494
557
|
if (data && typeof data === "object" && "entry" in data && data.entry) {
|
|
495
558
|
return data.entry;
|