@garagem-ai/site-sdk 0.7.0 → 0.9.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 +329 -31
- package/dist/index.d.mts +305 -44
- package/dist/index.d.ts +305 -44
- package/dist/index.js +1282 -34
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1233 -34
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +29 -2
- package/dist/react.d.ts +29 -2
- package/dist/react.js +639 -26
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +638 -26
- package/dist/react.mjs.map +1 -1
- package/dist/{types-photo-search-OeONNDxl.d.mts → types-photo-search-D88oevZv.d.mts} +400 -1
- package/dist/{types-photo-search-OeONNDxl.d.ts → types-photo-search-D88oevZv.d.ts} +400 -1
- package/package.json +1 -1
- package/src/client.ts +23 -0
- package/src/fetchers-photos.ts +98 -0
- package/src/fetchers.ts +96 -30
- package/src/index.ts +120 -2
- package/src/internal/sdk-http.ts +122 -0
- package/src/leads.ts +34 -3
- package/src/listing-photos.ts +312 -0
- package/src/map-search.ts +487 -0
- package/src/maps.ts +743 -0
- package/src/react/index.ts +2 -0
- package/src/react/types.ts +5 -0
- package/src/react/use-map-search.ts +101 -0
- package/src/react/use-public-search.ts +23 -5
- package/src/resolve-site-id.ts +3 -0
- package/src/studio-contract.ts +120 -0
- package/src/types-maps.ts +275 -0
- package/src/types-photos.ts +46 -0
- package/src/types.ts +23 -0
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 {
|
|
@@ -67,6 +77,8 @@ export interface GetSearchUiOptions extends BaseOptions {
|
|
|
67
77
|
export interface QueryListingsOptions extends BaseOptions {
|
|
68
78
|
siteId: string;
|
|
69
79
|
params?: QueryListingsParams;
|
|
80
|
+
/** Aborts the listings request. Stale map pans use this. */
|
|
81
|
+
signal?: AbortSignal;
|
|
70
82
|
}
|
|
71
83
|
|
|
72
84
|
export interface GetSimilarListingsOptions extends BaseOptions {
|
|
@@ -110,17 +122,15 @@ interface FetchInit extends RequestInit {
|
|
|
110
122
|
export async function callJson<T>(
|
|
111
123
|
url: string,
|
|
112
124
|
init: FetchInit,
|
|
113
|
-
fetchImpl: FetchLike
|
|
125
|
+
fetchImpl: FetchLike,
|
|
126
|
+
publishableKey?: string
|
|
114
127
|
): Promise<T> {
|
|
115
|
-
const response = await fetchImpl(
|
|
128
|
+
const response = await fetchImpl(
|
|
129
|
+
url,
|
|
130
|
+
withPublishableKeyHeader(init, publishableKey)
|
|
131
|
+
);
|
|
116
132
|
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
|
-
);
|
|
133
|
+
throw await readGaragemSdkError(response, url);
|
|
124
134
|
}
|
|
125
135
|
return (await response.json()) as T;
|
|
126
136
|
}
|
|
@@ -129,14 +139,56 @@ export async function callJson<T>(
|
|
|
129
139
|
export class GaragemSdkError extends Error {
|
|
130
140
|
readonly status: number;
|
|
131
141
|
readonly url: string;
|
|
132
|
-
|
|
142
|
+
/** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
|
|
143
|
+
readonly reason: string | null;
|
|
144
|
+
/**
|
|
145
|
+
* Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
|
|
146
|
+
* or the body's `retryAfterSeconds`. `null` when the response has neither.
|
|
147
|
+
*/
|
|
148
|
+
readonly retryAfter: number | null;
|
|
149
|
+
constructor(
|
|
150
|
+
message: string,
|
|
151
|
+
info: {
|
|
152
|
+
status: number;
|
|
153
|
+
url: string;
|
|
154
|
+
reason?: string | null;
|
|
155
|
+
retryAfter?: number | null;
|
|
156
|
+
}
|
|
157
|
+
) {
|
|
133
158
|
super(message);
|
|
134
159
|
this.name = "GaragemSdkError";
|
|
135
160
|
this.status = info.status;
|
|
136
161
|
this.url = info.url;
|
|
162
|
+
this.reason = info.reason ?? null;
|
|
163
|
+
this.retryAfter = info.retryAfter ?? null;
|
|
137
164
|
}
|
|
138
165
|
}
|
|
139
166
|
|
|
167
|
+
/** Build a {@link GaragemSdkError} from a non-2xx response (reads the body). */
|
|
168
|
+
export async function readGaragemSdkError(
|
|
169
|
+
response: Response,
|
|
170
|
+
url: string
|
|
171
|
+
): Promise<GaragemSdkError> {
|
|
172
|
+
const text = await response.text().catch(() => "");
|
|
173
|
+
const parsed = parseSdkErrorBody(text);
|
|
174
|
+
const retryAfter =
|
|
175
|
+
response.status === 429
|
|
176
|
+
? retryAfterFromResponse(response, parsed.retryAfterSeconds)
|
|
177
|
+
: parsed.retryAfterSeconds;
|
|
178
|
+
const detail = parsed.summary;
|
|
179
|
+
return new GaragemSdkError(
|
|
180
|
+
`Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${
|
|
181
|
+
detail ? ` — ${detail}` : ""
|
|
182
|
+
}`,
|
|
183
|
+
{
|
|
184
|
+
status: response.status,
|
|
185
|
+
url,
|
|
186
|
+
reason: parsed.reason,
|
|
187
|
+
retryAfter,
|
|
188
|
+
}
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
140
192
|
/**
|
|
141
193
|
* Fetch a paginated list of listings for a given site.
|
|
142
194
|
*
|
|
@@ -160,7 +212,8 @@ export async function getListings(
|
|
|
160
212
|
const data = await callJson<{ listings?: Listing[]; total?: number }>(
|
|
161
213
|
url,
|
|
162
214
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
163
|
-
fetchImpl ?? fetch
|
|
215
|
+
fetchImpl ?? fetch,
|
|
216
|
+
options.publishableKey
|
|
164
217
|
);
|
|
165
218
|
return {
|
|
166
219
|
listings: data.listings ?? [],
|
|
@@ -189,7 +242,8 @@ export async function getListing(
|
|
|
189
242
|
return callJson<ListingDetail>(
|
|
190
243
|
url,
|
|
191
244
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
192
|
-
fetchImpl ?? fetch
|
|
245
|
+
fetchImpl ?? fetch,
|
|
246
|
+
options.publishableKey
|
|
193
247
|
);
|
|
194
248
|
}
|
|
195
249
|
|
|
@@ -224,17 +278,20 @@ export async function getSite(options: GetSiteOptions): Promise<Site | null> {
|
|
|
224
278
|
const url = `${base}/api/sites/resolve?${params.toString()}`;
|
|
225
279
|
|
|
226
280
|
const f = fetchImpl ?? fetch;
|
|
227
|
-
const response = await f(
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
281
|
+
const response = await f(
|
|
282
|
+
url,
|
|
283
|
+
withPublishableKeyHeader(
|
|
284
|
+
{
|
|
285
|
+
method: "GET",
|
|
286
|
+
headers: { Accept: "application/json" },
|
|
287
|
+
next,
|
|
288
|
+
},
|
|
289
|
+
options.publishableKey
|
|
290
|
+
) as FetchInit
|
|
291
|
+
);
|
|
232
292
|
if (response.status === 404) return null;
|
|
233
293
|
if (!response.ok) {
|
|
234
|
-
throw
|
|
235
|
-
`Garagem SDK: getSite failed (${response.status}) for ${url}`,
|
|
236
|
-
{ status: response.status, url }
|
|
237
|
-
);
|
|
294
|
+
throw await readGaragemSdkError(response, url);
|
|
238
295
|
}
|
|
239
296
|
const data = (await response.json()) as {
|
|
240
297
|
id: string;
|
|
@@ -295,7 +352,8 @@ export async function searchListings<TDocument = Record<string, unknown>>(
|
|
|
295
352
|
body: JSON.stringify(params),
|
|
296
353
|
next,
|
|
297
354
|
},
|
|
298
|
-
fetchImpl ?? fetch
|
|
355
|
+
fetchImpl ?? fetch,
|
|
356
|
+
options.publishableKey
|
|
299
357
|
);
|
|
300
358
|
}
|
|
301
359
|
|
|
@@ -313,7 +371,8 @@ export async function getSearchUi(
|
|
|
313
371
|
return callJson<SearchUi>(
|
|
314
372
|
url,
|
|
315
373
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
316
|
-
fetchImpl ?? fetch
|
|
374
|
+
fetchImpl ?? fetch,
|
|
375
|
+
options.publishableKey
|
|
317
376
|
);
|
|
318
377
|
}
|
|
319
378
|
|
|
@@ -324,7 +383,7 @@ export async function getSearchUi(
|
|
|
324
383
|
export async function queryListings(
|
|
325
384
|
options: QueryListingsOptions
|
|
326
385
|
): Promise<QueryListingsResult> {
|
|
327
|
-
const { params, baseUrl, fetch: fetchImpl, next } = options;
|
|
386
|
+
const { params, baseUrl, fetch: fetchImpl, next, signal } = options;
|
|
328
387
|
const siteId = await coerceSiteId(options.siteId);
|
|
329
388
|
const base = normalizeBaseUrl(baseUrl);
|
|
330
389
|
const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
|
|
@@ -338,8 +397,10 @@ export async function queryListings(
|
|
|
338
397
|
},
|
|
339
398
|
body: JSON.stringify(params ?? {}),
|
|
340
399
|
next,
|
|
400
|
+
signal,
|
|
341
401
|
},
|
|
342
|
-
fetchImpl ?? fetch
|
|
402
|
+
fetchImpl ?? fetch,
|
|
403
|
+
options.publishableKey
|
|
343
404
|
);
|
|
344
405
|
}
|
|
345
406
|
|
|
@@ -375,7 +436,8 @@ export async function getSimilarListings(
|
|
|
375
436
|
const data = await callJson<{ listings?: Listing[]; total?: number }>(
|
|
376
437
|
url,
|
|
377
438
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
378
|
-
fetchImpl ?? fetch
|
|
439
|
+
fetchImpl ?? fetch,
|
|
440
|
+
options.publishableKey
|
|
379
441
|
);
|
|
380
442
|
return {
|
|
381
443
|
listings: data.listings ?? [],
|
|
@@ -394,7 +456,8 @@ export async function getCmsCollections(
|
|
|
394
456
|
const data = await callJson<{ collections?: CmsCollection[] }>(
|
|
395
457
|
url,
|
|
396
458
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
397
|
-
fetchImpl ?? fetch
|
|
459
|
+
fetchImpl ?? fetch,
|
|
460
|
+
options.publishableKey
|
|
398
461
|
);
|
|
399
462
|
return data.collections ?? [];
|
|
400
463
|
}
|
|
@@ -415,7 +478,8 @@ export async function getCmsCollection(
|
|
|
415
478
|
const data = await callJson<{ collection?: CmsCollection } | CmsCollection>(
|
|
416
479
|
url,
|
|
417
480
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
418
|
-
fetchImpl ?? fetch
|
|
481
|
+
fetchImpl ?? fetch,
|
|
482
|
+
options.publishableKey
|
|
419
483
|
);
|
|
420
484
|
if (
|
|
421
485
|
data &&
|
|
@@ -460,7 +524,8 @@ export async function getCmsEntries(
|
|
|
460
524
|
const data = await callJson<Partial<CmsEntriesResult>>(
|
|
461
525
|
url,
|
|
462
526
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
463
|
-
fetchImpl ?? fetch
|
|
527
|
+
fetchImpl ?? fetch,
|
|
528
|
+
options.publishableKey
|
|
464
529
|
);
|
|
465
530
|
return {
|
|
466
531
|
entries: data.entries ?? [],
|
|
@@ -489,7 +554,8 @@ export async function getCmsEntry(
|
|
|
489
554
|
const data = await callJson<{ entry?: CmsEntry } | CmsEntry>(
|
|
490
555
|
url,
|
|
491
556
|
{ method: "GET", headers: { Accept: "application/json" }, next },
|
|
492
|
-
fetchImpl ?? fetch
|
|
557
|
+
fetchImpl ?? fetch,
|
|
558
|
+
options.publishableKey
|
|
493
559
|
);
|
|
494
560
|
if (data && typeof data === "object" && "entry" in data && data.entry) {
|
|
495
561
|
return data.entry;
|
package/src/index.ts
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
*
|
|
12
12
|
* 2. Client object (binds defaults):
|
|
13
13
|
*
|
|
14
|
-
* import {
|
|
15
|
-
* const garagem =
|
|
14
|
+
* import { createClient } from "@garagem-ai/site-sdk";
|
|
15
|
+
* const garagem = createClient({ siteId: "abc", publishableKey: "pk_live_…" });
|
|
16
16
|
* const { listings } = await garagem.getListings();
|
|
17
17
|
*
|
|
18
18
|
* Works in Node, Edge runtimes, Cloudflare Workers, Bun, Deno and the
|
|
@@ -257,23 +257,141 @@ export {
|
|
|
257
257
|
studioLeadInstruction,
|
|
258
258
|
studioListingCardInstruction,
|
|
259
259
|
studioListingDetailInstruction,
|
|
260
|
+
studioPhotoInstruction,
|
|
261
|
+
studioPhotoInstructionFor,
|
|
260
262
|
studioSearchInstruction,
|
|
261
263
|
studioSearchLandmarkInstruction,
|
|
264
|
+
studioPublishableKeyInstruction,
|
|
262
265
|
studioPhotoSearchInstruction,
|
|
263
266
|
isPhotoSearchOnPin,
|
|
264
267
|
studioSdkPinInstruction,
|
|
265
268
|
studioSiteWidthCss,
|
|
266
269
|
hasShowcaseLeadsPostUrl,
|
|
270
|
+
mapsExportsPublished,
|
|
271
|
+
studioMapsInstruction,
|
|
267
272
|
unavailableReactImports,
|
|
268
273
|
type StudioSdkContract,
|
|
269
274
|
} from "./studio-contract";
|
|
270
275
|
|
|
271
276
|
export {
|
|
277
|
+
createClient,
|
|
272
278
|
createGaragemClient,
|
|
273
279
|
type CreateGaragemClientOptions,
|
|
274
280
|
type GaragemClient,
|
|
275
281
|
} from "./client";
|
|
276
282
|
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
// Maps (maps.fndn.ai): static map / street view URLs, boundary layers,
|
|
285
|
+
// travel time, and friendly map search. See src/maps.ts, src/map-search.ts,
|
|
286
|
+
// and src/types-maps.ts.
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
export {
|
|
289
|
+
DEFAULT_MAPS_BASE_URL,
|
|
290
|
+
MAPS_MAX_IMAGE_EDGE,
|
|
291
|
+
MAPS_SITE_HEADER,
|
|
292
|
+
boundaryCitySlug,
|
|
293
|
+
boundaryLayerId,
|
|
294
|
+
boundaryLayerUrl,
|
|
295
|
+
clearTravelTimeCache,
|
|
296
|
+
coarsenCoordinates,
|
|
297
|
+
coordinateDecimals,
|
|
298
|
+
createTravelTimeCache,
|
|
299
|
+
getBoundaryLayer,
|
|
300
|
+
listingCoordinates,
|
|
301
|
+
listingStaticMapUrl,
|
|
302
|
+
listingStreetViewAvailable,
|
|
303
|
+
listingStreetViewMetadataUrl,
|
|
304
|
+
listingStreetViewUrl,
|
|
305
|
+
maxZoomForCoordinates,
|
|
306
|
+
neighborhoodBoundaryLayer,
|
|
307
|
+
neighborhoodBoundaryUrl,
|
|
308
|
+
normalizeMapsBaseUrl,
|
|
309
|
+
resolveTravelDestination,
|
|
310
|
+
travelTimeCacheKey,
|
|
311
|
+
travelTimeFromListing,
|
|
312
|
+
travelTimesFromListing,
|
|
313
|
+
} from "./maps";
|
|
314
|
+
export {
|
|
315
|
+
MAP_POLYGON_MAX_VERTICES,
|
|
316
|
+
MAP_SEARCH_DEFAULT_PAGE_SIZE,
|
|
317
|
+
MAP_SEARCH_MAX_PAGE_SIZE,
|
|
318
|
+
MAP_VIEWPORT_DEBOUNCE_MS,
|
|
319
|
+
capMapPage,
|
|
320
|
+
capMapPageSize,
|
|
321
|
+
clusterPins,
|
|
322
|
+
isMapBounds,
|
|
323
|
+
isMapPolygon,
|
|
324
|
+
mapClusterCellDegrees,
|
|
325
|
+
mapSearchPins,
|
|
326
|
+
searchListingsInBounds,
|
|
327
|
+
searchListingsInPolygon,
|
|
328
|
+
} from "./map-search";
|
|
329
|
+
export type {
|
|
330
|
+
MapBoundsSearchOptions,
|
|
331
|
+
MapPolygonSearchOptions,
|
|
332
|
+
MapSearchResult,
|
|
333
|
+
} from "./map-search";
|
|
334
|
+
export type {
|
|
335
|
+
BoundaryCity,
|
|
336
|
+
BoundaryFeature,
|
|
337
|
+
BoundaryFeatureCollection,
|
|
338
|
+
BoundaryGeometry,
|
|
339
|
+
BoundaryLayer,
|
|
340
|
+
BoundaryLayerOptions,
|
|
341
|
+
BoundaryLayerUrlKind,
|
|
342
|
+
BoundarySourceLayer,
|
|
343
|
+
ListingWithLocation,
|
|
344
|
+
MapsBaseOptions,
|
|
345
|
+
MapsCoordinates,
|
|
346
|
+
MapsFetchOptions,
|
|
347
|
+
NeighborhoodBoundary,
|
|
348
|
+
NeighborhoodBoundaryOptions,
|
|
349
|
+
StaticMapOptions,
|
|
350
|
+
StaticMapStyle,
|
|
351
|
+
StreetViewAvailability,
|
|
352
|
+
StreetViewAvailabilityOptions,
|
|
353
|
+
StreetViewOptions,
|
|
354
|
+
TravelDestination,
|
|
355
|
+
TravelMode,
|
|
356
|
+
TravelTime,
|
|
357
|
+
TravelTimeCache,
|
|
358
|
+
TravelTimeCacheOptions,
|
|
359
|
+
TravelTimeElement,
|
|
360
|
+
TravelTimeOptions,
|
|
361
|
+
TravelTimesOptions,
|
|
362
|
+
MapBounds,
|
|
363
|
+
MapPin,
|
|
364
|
+
MapPinCluster,
|
|
365
|
+
MapPolygon,
|
|
366
|
+
} from "./types-maps";
|
|
367
|
+
// ---------------------------------------------------------------------------
|
|
368
|
+
// End maps block
|
|
369
|
+
|
|
370
|
+
// ---------------------------------------------------------------------------
|
|
371
|
+
// Photo intelligence: captions / room groups on `ListingDetail.media` and
|
|
372
|
+
// "imóveis com fotos parecidas" (`getSimilarByPhoto`). Self-contained block.
|
|
373
|
+
// ---------------------------------------------------------------------------
|
|
374
|
+
export type {
|
|
375
|
+
ListingPhotoGroup,
|
|
376
|
+
SimilarByPhotoItem,
|
|
377
|
+
SimilarByPhotoResult,
|
|
378
|
+
SimilarPhotoMatch,
|
|
379
|
+
} from "./types-photos";
|
|
380
|
+
|
|
381
|
+
export {
|
|
382
|
+
getSimilarByPhoto,
|
|
383
|
+
type GetSimilarByPhotoOptions,
|
|
384
|
+
} from "./fetchers-photos";
|
|
385
|
+
|
|
386
|
+
export {
|
|
387
|
+
PHOTO_GROUP_OTHER_KEY,
|
|
388
|
+
PHOTO_GROUP_OTHER_LABEL,
|
|
389
|
+
listingPhotoGroups,
|
|
390
|
+
listingVisualHighlights,
|
|
391
|
+
photoRoomLabel,
|
|
392
|
+
type ListingVisualHighlightsOptions,
|
|
393
|
+
} from "./listing-photos";
|
|
394
|
+
|
|
277
395
|
// ---------------------------------------------------------------------------
|
|
278
396
|
// Market data (requires the IPTU module — `iptu_itbi_integration`).
|
|
279
397
|
// Self-contained block: fetchers, headless pt-BR labels and types. Every
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publishable-key header and error parsing shared by the SDK fetchers.
|
|
3
|
+
*
|
|
4
|
+
* The key is an identifier (`pk_live_…`), not a secret. Foundation accepts
|
|
5
|
+
* it as `X-Garagem-Publishable-Key` or `Authorization: Bearer pk_live_…`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const PUBLISHABLE_KEY_HEADER = "X-Garagem-Publishable-Key";
|
|
9
|
+
|
|
10
|
+
export function publishableKeyHeaders(
|
|
11
|
+
publishableKey?: string | null
|
|
12
|
+
): Record<string, string> {
|
|
13
|
+
const key = publishableKey?.trim();
|
|
14
|
+
if (!key) return {};
|
|
15
|
+
return { [PUBLISHABLE_KEY_HEADER]: key };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Merge the publishable-key header into a plain-object `fetch` init. */
|
|
19
|
+
export function withPublishableKeyHeader<T extends { headers?: HeadersInit }>(
|
|
20
|
+
init: T,
|
|
21
|
+
publishableKey?: string | null
|
|
22
|
+
): T {
|
|
23
|
+
const extra = publishableKeyHeaders(publishableKey);
|
|
24
|
+
if (Object.keys(extra).length === 0) return init;
|
|
25
|
+
const current = init.headers;
|
|
26
|
+
const base = plainHeaders(current);
|
|
27
|
+
return { ...init, headers: { ...base, ...extra } };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function plainHeaders(
|
|
31
|
+
headers: HeadersInit | undefined
|
|
32
|
+
): Record<string, string> {
|
|
33
|
+
const out: Record<string, string> = {};
|
|
34
|
+
if (!headers) return out;
|
|
35
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
36
|
+
headers.forEach((value, name) => {
|
|
37
|
+
out[name] = value;
|
|
38
|
+
});
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(headers)) {
|
|
42
|
+
for (const pair of headers) {
|
|
43
|
+
out[String(pair[0])] = String(pair[1]);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
// `HeadersInit` stays a union after the class/array checks in some lib
|
|
48
|
+
// targets. Copy string entries only so the result is always a plain record.
|
|
49
|
+
for (const [name, value] of Object.entries(
|
|
50
|
+
headers as Record<string, unknown>
|
|
51
|
+
)) {
|
|
52
|
+
if (typeof value === "string") out[name] = value;
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ParsedSdkErrorBody {
|
|
58
|
+
reason: string | null;
|
|
59
|
+
retryAfterSeconds: number | null;
|
|
60
|
+
/** Short human text from `error` or the raw body. */
|
|
61
|
+
summary: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function finiteNonNegative(value: unknown): number | null {
|
|
65
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
if (typeof value === "string" && value.trim()) {
|
|
69
|
+
const parsed = Number(value);
|
|
70
|
+
if (Number.isFinite(parsed) && parsed >= 0) return parsed;
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function parseSdkErrorBody(text: string): ParsedSdkErrorBody {
|
|
76
|
+
const raw = text ? text.slice(0, 200) : "";
|
|
77
|
+
if (!text) {
|
|
78
|
+
return { reason: null, retryAfterSeconds: null, summary: "" };
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const body = JSON.parse(text) as unknown;
|
|
82
|
+
if (!body || typeof body !== "object") {
|
|
83
|
+
return { reason: null, retryAfterSeconds: null, summary: raw };
|
|
84
|
+
}
|
|
85
|
+
const record = body as Record<string, unknown>;
|
|
86
|
+
const reason =
|
|
87
|
+
typeof record.reason === "string" && record.reason ? record.reason : null;
|
|
88
|
+
const retryAfterSeconds = finiteNonNegative(
|
|
89
|
+
record.retryAfterSeconds ?? record.retryAfter
|
|
90
|
+
);
|
|
91
|
+
const errorText =
|
|
92
|
+
typeof record.error === "string" && record.error ? record.error : raw;
|
|
93
|
+
return {
|
|
94
|
+
reason,
|
|
95
|
+
retryAfterSeconds,
|
|
96
|
+
summary: errorText.slice(0, 200),
|
|
97
|
+
};
|
|
98
|
+
} catch {
|
|
99
|
+
return { reason: null, retryAfterSeconds: null, summary: raw };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Seconds the caller should wait. The `Retry-After` header wins (delta
|
|
105
|
+
* seconds, or an HTTP date). Otherwise the JSON `retryAfterSeconds`.
|
|
106
|
+
*/
|
|
107
|
+
export function retryAfterFromResponse(
|
|
108
|
+
response: { headers: { get(name: string): string | null } },
|
|
109
|
+
bodySeconds: number | null,
|
|
110
|
+
nowMs: number = Date.now()
|
|
111
|
+
): number | null {
|
|
112
|
+
const header = response.headers.get("Retry-After")?.trim();
|
|
113
|
+
if (header) {
|
|
114
|
+
const delta = finiteNonNegative(header);
|
|
115
|
+
if (delta != null) return delta;
|
|
116
|
+
const at = Date.parse(header);
|
|
117
|
+
if (Number.isFinite(at)) {
|
|
118
|
+
return Math.max(0, Math.ceil((at - nowMs) / 1000));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return bodySeconds;
|
|
122
|
+
}
|
package/src/leads.ts
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { callJson, type FetchLike } from "./fetchers";
|
|
7
|
+
import {
|
|
8
|
+
parseSdkErrorBody,
|
|
9
|
+
publishableKeyHeaders,
|
|
10
|
+
retryAfterFromResponse,
|
|
11
|
+
} from "./internal/sdk-http";
|
|
7
12
|
import { coerceSiteId, normalizeBaseUrl } from "./internal/url";
|
|
8
13
|
import { isValidPhone, toE164 } from "./phone";
|
|
9
14
|
import { resolvePublicSiteId } from "./resolve-site-id";
|
|
@@ -48,6 +53,8 @@ export type GetLeadUiOptions = {
|
|
|
48
53
|
baseUrl?: string;
|
|
49
54
|
fetch?: FetchLike;
|
|
50
55
|
next?: RequestNextOptions;
|
|
56
|
+
/** Site publishable key (`pk_live_…`). Not a secret. */
|
|
57
|
+
publishableKey?: string;
|
|
51
58
|
};
|
|
52
59
|
|
|
53
60
|
function browserHost(): string {
|
|
@@ -63,6 +70,7 @@ async function resolveLeadSiteId(input: {
|
|
|
63
70
|
siteId?: unknown;
|
|
64
71
|
baseUrl?: string;
|
|
65
72
|
fetch?: FetchLike;
|
|
73
|
+
publishableKey?: string;
|
|
66
74
|
}): Promise<string> {
|
|
67
75
|
try {
|
|
68
76
|
return await coerceSiteId(input.siteId);
|
|
@@ -73,6 +81,7 @@ async function resolveLeadSiteId(input: {
|
|
|
73
81
|
host,
|
|
74
82
|
baseUrl: input.baseUrl,
|
|
75
83
|
fetch: input.fetch,
|
|
84
|
+
publishableKey: input.publishableKey,
|
|
76
85
|
});
|
|
77
86
|
}
|
|
78
87
|
}
|
|
@@ -88,6 +97,8 @@ type LeadSubmitBase = LeadContact & {
|
|
|
88
97
|
siteId?: string | Promise<string>;
|
|
89
98
|
baseUrl?: string;
|
|
90
99
|
fetch?: FetchLike;
|
|
100
|
+
/** Site publishable key (`pk_live_…`). Not a secret. */
|
|
101
|
+
publishableKey?: string;
|
|
91
102
|
listingId: string;
|
|
92
103
|
/**
|
|
93
104
|
* Active listing modality (`sale` | `rental` | `rent`). Always pass
|
|
@@ -115,6 +126,7 @@ export type LeadSubmitErrorCode =
|
|
|
115
126
|
| "invalid_listing_id"
|
|
116
127
|
| "invalid_contact"
|
|
117
128
|
| "invalid_slot"
|
|
129
|
+
| "unauthorized"
|
|
118
130
|
| "rate_limited"
|
|
119
131
|
| "not_found"
|
|
120
132
|
| "http"
|
|
@@ -124,6 +136,8 @@ export class LeadSubmitError extends Error {
|
|
|
124
136
|
readonly code: LeadSubmitErrorCode;
|
|
125
137
|
readonly status?: number;
|
|
126
138
|
readonly retryAfterSeconds?: number;
|
|
139
|
+
/** Seconds to wait. Same value as `retryAfterSeconds`; `null` when unset. */
|
|
140
|
+
readonly retryAfter: number | null;
|
|
127
141
|
|
|
128
142
|
constructor(
|
|
129
143
|
message: string,
|
|
@@ -140,6 +154,7 @@ export class LeadSubmitError extends Error {
|
|
|
140
154
|
if (info.retryAfterSeconds != null) {
|
|
141
155
|
this.retryAfterSeconds = info.retryAfterSeconds;
|
|
142
156
|
}
|
|
157
|
+
this.retryAfter = info.retryAfterSeconds ?? null;
|
|
143
158
|
}
|
|
144
159
|
}
|
|
145
160
|
|
|
@@ -187,7 +202,8 @@ export async function getLeadUi(options: GetLeadUiOptions): Promise<LeadUi> {
|
|
|
187
202
|
headers: { Accept: "application/json" },
|
|
188
203
|
next: options.next,
|
|
189
204
|
},
|
|
190
|
-
options.fetch ?? fetch
|
|
205
|
+
options.fetch ?? fetch,
|
|
206
|
+
options.publishableKey
|
|
191
207
|
);
|
|
192
208
|
}
|
|
193
209
|
|
|
@@ -286,6 +302,7 @@ async function postSiteLead(input: {
|
|
|
286
302
|
siteId?: string | Promise<string>;
|
|
287
303
|
baseUrl?: string;
|
|
288
304
|
fetch?: FetchLike;
|
|
305
|
+
publishableKey?: string;
|
|
289
306
|
body: SiteSdkLeadBody;
|
|
290
307
|
}): Promise<LeadSubmitResult> {
|
|
291
308
|
const siteId = await resolveLeadSiteId(input);
|
|
@@ -299,6 +316,7 @@ async function postSiteLead(input: {
|
|
|
299
316
|
headers: {
|
|
300
317
|
Accept: "application/json",
|
|
301
318
|
"Content-Type": "application/json",
|
|
319
|
+
...publishableKeyHeaders(input.publishableKey),
|
|
302
320
|
},
|
|
303
321
|
body: JSON.stringify(input.body),
|
|
304
322
|
});
|
|
@@ -317,12 +335,23 @@ async function postSiteLead(input: {
|
|
|
317
335
|
return { ok: true, status: 202, id };
|
|
318
336
|
}
|
|
319
337
|
|
|
320
|
-
|
|
338
|
+
if (response.status === 401) {
|
|
339
|
+
throw new LeadSubmitError("Garagem SDK: invalid publishable key.", {
|
|
340
|
+
code: "unauthorized",
|
|
341
|
+
status: 401,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
321
344
|
if (response.status === 429) {
|
|
345
|
+
const text = await response.text().catch(() => "");
|
|
346
|
+
const parsed = parseSdkErrorBody(text);
|
|
347
|
+
const retryAfter = retryAfterFromResponse(
|
|
348
|
+
response,
|
|
349
|
+
parsed.retryAfterSeconds
|
|
350
|
+
);
|
|
322
351
|
throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
|
|
323
352
|
code: "rate_limited",
|
|
324
353
|
status: 429,
|
|
325
|
-
|
|
354
|
+
...(retryAfter != null ? { retryAfterSeconds: retryAfter } : {}),
|
|
326
355
|
});
|
|
327
356
|
}
|
|
328
357
|
if (response.status === 404) {
|
|
@@ -383,6 +412,7 @@ export async function submitVisitLead(
|
|
|
383
412
|
siteId: input.siteId,
|
|
384
413
|
baseUrl: input.baseUrl,
|
|
385
414
|
fetch: input.fetch,
|
|
415
|
+
publishableKey: input.publishableKey,
|
|
386
416
|
body: {
|
|
387
417
|
source: "site-sdk",
|
|
388
418
|
leadType: "visit",
|
|
@@ -404,6 +434,7 @@ export async function submitContactLead(
|
|
|
404
434
|
siteId: input.siteId,
|
|
405
435
|
baseUrl: input.baseUrl,
|
|
406
436
|
fetch: input.fetch,
|
|
437
|
+
publishableKey: input.publishableKey,
|
|
407
438
|
body: {
|
|
408
439
|
source: "site-sdk",
|
|
409
440
|
leadType: "contact",
|