@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.
@@ -49,9 +49,20 @@ interface ListingMedia {
49
49
  type: string;
50
50
  category: string;
51
51
  src: string;
52
+ /** Caption-based alt for photos with analysis; generic `"<title> - Foto N"` otherwise. */
52
53
  alt?: string;
54
+ /** AI caption, falling back to the broker description. Photos only; absent when unanalyzed. */
53
55
  caption?: string;
54
56
  order?: number;
57
+ /**
58
+ * Room the photo shows, free text from the analysis (`sala`, `quarto`,
59
+ * `cozinha`, …). Group with `listingPhotoGroups`.
60
+ */
61
+ roomType?: string;
62
+ /** `interior` | `facade` | `building_exterior` | `amenity` | `view` | `floorplan` | `other`. */
63
+ sceneType?: string;
64
+ /** Visual highlights named for this photo. Aggregate with `listingVisualHighlights`. */
65
+ features?: string[];
55
66
  }
56
67
  /**
57
68
  * Minimum information needed to render a listing on a grid or card.
@@ -268,6 +279,18 @@ interface QueryListingsParams {
268
279
  q?: string;
269
280
  filters?: QueryListingsFilters;
270
281
  location?: QueryListingsLocation | QueryListingsLocation[];
282
+ /**
283
+ * Map viewport. The server builds a `coordinates:(…)` polygon from these
284
+ * numbers. Ignored when `polygon` is also set.
285
+ */
286
+ bounds?: {
287
+ north: number;
288
+ south: number;
289
+ east: number;
290
+ west: number;
291
+ };
292
+ /** Drawn area as `[lat, lng]` pairs, not GeoJSON `[lng, lat]`. */
293
+ polygon?: Array<[number, number]>;
271
294
  }
272
295
  interface QueryListingsResult {
273
296
  listings: Listing[];
@@ -409,6 +432,11 @@ interface BaseOptions {
409
432
  * understand them.
410
433
  */
411
434
  next?: RequestNextOptions;
435
+ /**
436
+ * Site publishable key (`pk_live_…`) from Configurações → Sites → API
437
+ * pública. Not a secret. Omit it and the request stays anonymous.
438
+ */
439
+ publishableKey?: string;
412
440
  }
413
441
  interface GetListingsOptions extends BaseOptions {
414
442
  siteId: string;
@@ -434,6 +462,8 @@ interface GetSearchUiOptions extends BaseOptions {
434
462
  interface QueryListingsOptions extends BaseOptions {
435
463
  siteId: string;
436
464
  params?: QueryListingsParams;
465
+ /** Aborts the listings request. Stale map pans use this. */
466
+ signal?: AbortSignal;
437
467
  }
438
468
  interface GetSimilarListingsOptions extends BaseOptions {
439
469
  siteId: string;
@@ -463,9 +493,18 @@ interface GetCmsEntryOptions extends BaseOptions {
463
493
  declare class GaragemSdkError extends Error {
464
494
  readonly status: number;
465
495
  readonly url: string;
496
+ /** Machine reason from the JSON body (`invalid_publishable_key`, `rate_limited`, …). */
497
+ readonly reason: string | null;
498
+ /**
499
+ * Seconds to wait before retrying. Set on HTTP 429 from `Retry-After`
500
+ * or the body's `retryAfterSeconds`. `null` when the response has neither.
501
+ */
502
+ readonly retryAfter: number | null;
466
503
  constructor(message: string, info: {
467
504
  status: number;
468
505
  url: string;
506
+ reason?: string | null;
507
+ retryAfter?: number | null;
469
508
  });
470
509
  }
471
510
  /**
@@ -543,6 +582,46 @@ declare function getCmsEntries(options: GetCmsEntriesOptions): Promise<CmsEntrie
543
582
  /** Fetch one published CMS entry by slug. */
544
583
  declare function getCmsEntry(options: GetCmsEntryOptions): Promise<CmsEntry>;
545
584
 
585
+ /** Fields every listing card must have — no JSX. */
586
+ type ListingCardModel = {
587
+ href: string;
588
+ title: string;
589
+ businessType: ListingBusinessType;
590
+ businessLabel: string;
591
+ priceVisibility: ListingPriceVisibility;
592
+ price: number | null;
593
+ priceLabel: string;
594
+ pricePeriod: string | null;
595
+ locationLabel: string;
596
+ propertyType: string | null;
597
+ coverSrc: string | null;
598
+ coverAlt: string;
599
+ bedrooms: number | null;
600
+ bathrooms: number | null;
601
+ parkingSpaces: number | null;
602
+ areaM2: number | null;
603
+ };
604
+ declare function listingLocationLabel(location: {
605
+ neighborhood?: string | null;
606
+ city?: string | null;
607
+ state?: string | null;
608
+ }): string;
609
+ declare function toListingCardModel(listing: Pick<Listing, "id" | "listingCode" | "path" | "title" | "businessType" | "price" | "currency" | "priceVisibility" | "coverImage"> & {
610
+ property?: {
611
+ type?: string | null;
612
+ bedrooms?: number | null;
613
+ bathrooms?: number | null;
614
+ parkingSpaces?: number | null;
615
+ usableArea?: number | null;
616
+ totalArea?: number | null;
617
+ };
618
+ location?: {
619
+ neighborhood?: string | null;
620
+ city?: string | null;
621
+ state?: string | null;
622
+ };
623
+ }): ListingCardModel;
624
+
546
625
  /** Query keys that must never encode filters (Editor/Studio path contract). */
547
626
  declare const FORBIDDEN_SEARCH_QUERY_KEYS: readonly ["tipo", "quartos", "tipo-imovel", "banheiros", "vagas"];
548
627
  /** Default option: omit `ordenar` (API has no relevance token). */
@@ -624,6 +703,326 @@ type SearchChromeModel = {
624
703
  };
625
704
  declare function searchChromeModel(schema: SearchUi | null, pathFilters: SearchPathFilters, locationNames?: LocationNameTables | null): SearchChromeModel;
626
705
 
706
+ /**
707
+ * Types for the maps.fndn.ai helpers (`./maps`). Everything here works on
708
+ * the coordinates the public listings API already returns — those are
709
+ * masked per site (≈100 m by default) and the helpers never add precision.
710
+ */
711
+
712
+ /** `{ lat, lng }` pair as returned on `listing.location.coordinates`. */
713
+ interface MapsCoordinates {
714
+ lat: number;
715
+ lng: number;
716
+ }
717
+ /**
718
+ * Anything carrying a public listing location: `Listing`, `ListingDetail`,
719
+ * a card model, or a bare `{ location: { coordinates } }`.
720
+ */
721
+ type ListingWithLocation = {
722
+ location?: {
723
+ coordinates?: MapsCoordinates | null;
724
+ } | null;
725
+ } | null | undefined;
726
+ interface MapsBaseOptions {
727
+ /** maps.fndn.ai origin. Defaults to `https://maps.fndn.ai`. */
728
+ mapsBaseUrl?: string;
729
+ /**
730
+ * Site id (or publishable key) used to meter this site's usage on
731
+ * maps.fndn.ai. Sent as the `site` query param on image URLs and as the
732
+ * `X-Garagem-Site` header on fetches. Optional today; it only labels
733
+ * metrics and the per-site rate limit, it is not authentication.
734
+ */
735
+ siteId?: string;
736
+ }
737
+ interface MapsFetchOptions extends MapsBaseOptions {
738
+ /** Override the fetch implementation (testing, edge runtimes, retries). */
739
+ fetch?: FetchLike;
740
+ }
741
+ /** Google Static Maps map type. `style` is the SDK-facing alias. */
742
+ type StaticMapStyle = "roadmap" | "satellite" | "terrain" | "hybrid";
743
+ interface StaticMapOptions extends MapsBaseOptions {
744
+ /** Pixels, 1–640 (Google Static Maps ceiling). Default 600. */
745
+ width?: number;
746
+ /** Pixels, 1–640. Default 300. */
747
+ height?: number;
748
+ /**
749
+ * 1–21. Default 15. Capped by the coordinate precision the API applied:
750
+ * a ≈100 m masked point is never rendered above zoom 16, so the pin does
751
+ * not pretend to know the exact building. See `maxZoomForCoordinates`.
752
+ */
753
+ zoom?: number;
754
+ /** 1 or 2 (retina). Default 2. */
755
+ scale?: 1 | 2;
756
+ /** Map style. Default roadmap. */
757
+ style?: StaticMapStyle;
758
+ /** Marker color (Google color name or `0xRRGGBB`). Default red. */
759
+ markerColor?: string;
760
+ /** Hide points of interest. Default false. */
761
+ hidePoi?: boolean;
762
+ /**
763
+ * Max decimal places to send. Only ever *reduces* precision (e.g. send
764
+ * 2 decimals ≈ 1 km for a neighbourhood teaser); it cannot recover
765
+ * precision the API removed.
766
+ */
767
+ maxDecimals?: number;
768
+ }
769
+ interface StreetViewOptions extends MapsBaseOptions {
770
+ /** Pixels, 1–640. Default 640. */
771
+ width?: number;
772
+ /** Pixels, 1–640. Default 640. */
773
+ height?: number;
774
+ /** Field of view in degrees, 10–120. Default 90. */
775
+ fov?: number;
776
+ /** Compass heading 0–360. Default 0. */
777
+ heading?: number;
778
+ /** Camera pitch -90–90. Default 10. */
779
+ pitch?: number;
780
+ /** See `StaticMapOptions.maxDecimals`. */
781
+ maxDecimals?: number;
782
+ }
783
+ interface StreetViewAvailabilityOptions extends MapsFetchOptions {
784
+ /** See `StaticMapOptions.maxDecimals`. */
785
+ maxDecimals?: number;
786
+ }
787
+ interface StreetViewAvailability {
788
+ /** `true` when Google has a panorama near the (masked) coordinates. */
789
+ available: boolean;
790
+ /** Google metadata status: `OK`, `ZERO_RESULTS`, `ERROR`, … */
791
+ status: string;
792
+ /** Panorama id when available. */
793
+ panoId?: string;
794
+ /** Capture date (`YYYY-MM`) when available. */
795
+ date?: string;
796
+ /** maps.fndn.ai metadata URL that was queried. */
797
+ url: string;
798
+ }
799
+ /** Cities with boundary layers on maps.fndn.ai. Other slugs pass through. */
800
+ type BoundaryCity = "sao_paulo" | "rio_de_janeiro" | (string & {});
801
+ type BoundaryLayerUrlKind =
802
+ /** `GET /v1/layers/:id` — layer descriptor JSON. */
803
+ "layer"
804
+ /** TileJSON for MapLibre `addSource({ type: "vector", url })`. */
805
+ | "tilejson"
806
+ /** `{z}/{x}/{y}` vector tile template. */
807
+ | "tiles"
808
+ /** Whole-city GeoJSON FeatureCollection. */
809
+ | "geojson";
810
+ interface BoundaryLayerOptions extends MapsBaseOptions {
811
+ kind?: BoundaryLayerUrlKind;
812
+ }
813
+ interface BoundarySourceLayer {
814
+ id: string;
815
+ label: string;
816
+ minzoom?: number;
817
+ maxzoom?: number;
818
+ }
819
+ /** Subset of the maps.fndn.ai `/v1/layers/:id` descriptor the SDK exposes. */
820
+ interface BoundaryLayer {
821
+ id: string;
822
+ name: string;
823
+ description: string;
824
+ city?: string;
825
+ /** `{z}/{x}/{y}` template. */
826
+ tiles: string;
827
+ tilejson: string;
828
+ /** Whole-city GeoJSON, when published. */
829
+ geojson?: string;
830
+ sourceLayers: BoundarySourceLayer[];
831
+ minzoom: number;
832
+ maxzoom: number;
833
+ attribution?: string;
834
+ available: boolean;
835
+ }
836
+ /** Minimal GeoJSON shapes so the SDK does not depend on `@types/geojson`. */
837
+ interface BoundaryGeometry {
838
+ type: string;
839
+ coordinates: unknown;
840
+ }
841
+ interface BoundaryFeature {
842
+ type: "Feature";
843
+ properties: Record<string, unknown> & {
844
+ name?: string;
845
+ level?: string;
846
+ };
847
+ geometry: BoundaryGeometry | null;
848
+ [key: string]: unknown;
849
+ }
850
+ interface BoundaryFeatureCollection {
851
+ type: "FeatureCollection";
852
+ features: BoundaryFeature[];
853
+ count?: number;
854
+ source?: string;
855
+ }
856
+ interface NeighborhoodBoundaryOptions extends MapsFetchOptions {
857
+ /**
858
+ * Boundary dataset. Default `listaaberta` (SP districts / RJ
859
+ * neighbourhoods with IPTU stats); `osm` covers more cities.
860
+ */
861
+ source?: "listaaberta" | "osm" | "all";
862
+ }
863
+ interface NeighborhoodBoundary {
864
+ city: string;
865
+ neighborhood: string;
866
+ /** The matched outline, or `null` when nothing matched. */
867
+ feature: BoundaryFeature | null;
868
+ /** Every candidate when the name matched more than one feature. */
869
+ candidates: BoundaryFeature[];
870
+ /** GeoJSON URL that was queried (safe to pass to MapLibre `data`). */
871
+ url: string;
872
+ /** Vector tile template for the city's boundary layer. */
873
+ tiles: string;
874
+ }
875
+ type TravelMode = "driving" | "walking" | "bicycling" | "transit";
876
+ /** Coordinates, or a free-text address geocoded on maps.fndn.ai first. */
877
+ type TravelDestination = MapsCoordinates | string;
878
+ interface TravelTimeOptions extends MapsFetchOptions {
879
+ /** Default `driving`. */
880
+ mode?: TravelMode;
881
+ /** Client-side cache. Defaults to a module-level LRU; pass `null` to skip. */
882
+ cache?: TravelTimeCache | null;
883
+ /** See `StaticMapOptions.maxDecimals`. */
884
+ maxDecimals?: number;
885
+ }
886
+ interface TravelTime {
887
+ /** Rounded travel time in minutes (minimum 1 when a route exists). */
888
+ minutes: number;
889
+ seconds: number;
890
+ distanceMeters: number;
891
+ /** Distance rounded to one decimal. */
892
+ distanceKm: number;
893
+ mode: TravelMode;
894
+ origin: MapsCoordinates;
895
+ destination: MapsCoordinates;
896
+ /** `true` when served from the client-side cache. */
897
+ cached: boolean;
898
+ }
899
+ interface TravelTimesOptions extends MapsFetchOptions {
900
+ /** See `StaticMapOptions.maxDecimals`. */
901
+ maxDecimals?: number;
902
+ }
903
+ /** One route-matrix element; `null` when Google found no route. */
904
+ interface TravelTimeElement {
905
+ minutes: number;
906
+ seconds: number;
907
+ destination: MapsCoordinates;
908
+ }
909
+ interface TravelTimeCacheOptions {
910
+ /** Default 200 entries. */
911
+ maxEntries?: number;
912
+ /** Default 15 minutes. */
913
+ ttlMs?: number;
914
+ }
915
+ interface TravelTimeCache {
916
+ get(key: string): TravelTime | undefined;
917
+ set(key: string, value: TravelTime): void;
918
+ clear(): void;
919
+ readonly size: number;
920
+ }
921
+ /** Viewport rectangle in degrees. `east` must be greater than `west`. */
922
+ interface MapBounds {
923
+ north: number;
924
+ south: number;
925
+ east: number;
926
+ west: number;
927
+ }
928
+ /** `[lat, lng]` vertices. Not GeoJSON `[lng, lat]`. */
929
+ type MapPolygon = Array<[number, number]>;
930
+ /** Pin plotted from a public listing. Coordinates are already masked. */
931
+ interface MapPin {
932
+ id: string;
933
+ lat: number;
934
+ lng: number;
935
+ price: number | null;
936
+ coverImage: string | null;
937
+ }
938
+ /** One grid cell. `count === 1` keeps the pin's own coordinates. */
939
+ interface MapPinCluster {
940
+ id: string;
941
+ lat: number;
942
+ lng: number;
943
+ count: number;
944
+ pinIds: string[];
945
+ pin: MapPin | null;
946
+ }
947
+
948
+ /**
949
+ * Map search on top of the friendly public listings route.
950
+ *
951
+ * Bounds and polygons are structured numbers. The server (see
952
+ * `@garagem/site-search` `map-geo.ts`) turns them into one allowlisted
953
+ * `coordinates:(…)` clause. This module never sends `filter_by`,
954
+ * `vector_query`, or `nl_query`.
955
+ *
956
+ * Pins copy `listing.location.coordinates` as the API returned them.
957
+ * Those values are already masked. Nothing here adds precision.
958
+ */
959
+
960
+ /** Matches `FRIENDLY_SEARCH_MAX_LIMIT` on the public listings route. */
961
+ declare const MAP_SEARCH_MAX_PAGE_SIZE = 100;
962
+ declare const MAP_SEARCH_DEFAULT_PAGE_SIZE = 100;
963
+ /** Same pause Foundation's `/imoveis` map uses before a viewport search. */
964
+ declare const MAP_VIEWPORT_DEBOUNCE_MS = 400;
965
+ /** Keep aligned with `MAP_GEO_MAX_VERTICES` in `@garagem/site-search`. */
966
+ declare const MAP_POLYGON_MAX_VERTICES = 64;
967
+ interface MapSearchRequest {
968
+ baseUrl?: string;
969
+ fetch?: FetchLike;
970
+ signal?: AbortSignal;
971
+ /**
972
+ * Same `pk_live_…` as `queryListings`. Without it the viewport search
973
+ * spends the anonymous listings budget.
974
+ */
975
+ publishableKey?: string;
976
+ /** Next.js fetch cache hints, forwarded to `queryListings`. */
977
+ next?: RequestNextOptions;
978
+ /** Friendly list query. A moved map must keep these, not only `filters`. */
979
+ q?: string;
980
+ sort?: string;
981
+ location?: QueryListingsParams["location"];
982
+ filters?: QueryListingsFilters;
983
+ page?: number;
984
+ pageSize?: number;
985
+ /** Client hint for `clusterPins`. Not sent to the server. */
986
+ zoom?: number;
987
+ }
988
+ interface MapBoundsSearchOptions extends MapSearchRequest {
989
+ bounds: MapBounds;
990
+ }
991
+ interface MapPolygonSearchOptions extends MapSearchRequest {
992
+ polygon: MapPolygon;
993
+ }
994
+ interface MapSearchResult {
995
+ pins: MapPin[];
996
+ cards: ListingCardModel[];
997
+ listings: Listing[];
998
+ page: number;
999
+ pageSize: number;
1000
+ total: number;
1001
+ totalPages: number;
1002
+ }
1003
+ interface MapSearchSubscription extends MapSearchRequest {
1004
+ siteId: string;
1005
+ bounds?: MapBounds | null;
1006
+ polygon?: MapPolygon | null;
1007
+ }
1008
+ declare function capMapPageSize(value: number | undefined): number;
1009
+ declare function capMapPage(value: number | undefined): number;
1010
+ /** Rectangle the server will accept. `false` when it crosses the antimeridian. */
1011
+ declare function isMapBounds(bounds: MapBounds | null | undefined): bounds is MapBounds;
1012
+ declare function isMapPolygon(polygon: MapPolygon | null | undefined): polygon is MapPolygon;
1013
+ /** Pins from public listings. Coordinates are copied, never sharpened. */
1014
+ declare function mapSearchPins(listings: readonly Listing[]): MapPin[];
1015
+ declare function searchListingsInBounds(siteId: string, options: MapBoundsSearchOptions): Promise<MapSearchResult>;
1016
+ declare function searchListingsInPolygon(siteId: string, options: MapPolygonSearchOptions): Promise<MapSearchResult>;
1017
+ /** Degrees per grid cell: a quarter of one world tile at this zoom. */
1018
+ declare function mapClusterCellDegrees(zoom: number): number;
1019
+ /**
1020
+ * Headless grid cluster. A cell with one pin keeps that pin's coordinates.
1021
+ * A group centroid is rounded back to the coarsest member so clustering
1022
+ * cannot invent extra decimals.
1023
+ */
1024
+ declare function clusterPins(pins: readonly MapPin[], zoom: number): MapPinCluster[];
1025
+
627
1026
  /**
628
1027
  * "Busca pelo que as fotos mostram": search a site's catalog by what the
629
1028
  * public photos show (`GET /api/sites/{siteId}/search/photos`).
@@ -674,4 +1073,4 @@ type ListingWithMatchedPhoto = Listing & {
674
1073
  matchedPhoto: MatchedListingPhoto | null;
675
1074
  };
676
1075
 
677
- export { type SearchPathLocation as $, type AppliedSearchQuery as A, type GetCmsCollectionOptions as B, type CmsCollection as C, type GetCmsCollectionsOptions as D, type GetCmsEntriesOptions as E, type FetchLike as F, GaragemSdkError as G, type GetCmsEntryOptions as H, type GetListingOptions as I, type GetListingsOptions as J, type GetSearchUiOptions as K, type ListingDetail as L, type MatchedListingPhoto as M, type GetSimilarListingsOptions as N, type GetSiteOptions as O, type PhotoSearchParams as P, type QueryListingsFilters as Q, type RequestNextOptions as R, type SearchPathFilters as S, type ListingPropertySummary as T, type LocationNameTables as U, type QueryListingsLocation as V, type QueryListingsOptions as W, SEARCH_EMPTY_COPY as X, SEARCH_SORT_RELEVANCE as Y, type SearchChromeModel as Z, type SearchListingsOptions as _, type ListingLocation as a, type SearchUiFilter as a0, type SearchUiOption as a1, TOOLBAR_PRIMARY_FILTER_IDS as a2, applyPathFilter as a3, buildQueryListingsParams as a4, canonicalizeSearchHref as a5, clearStagedPathFilters as a6, countFacetChoices as a7, countOptionLabel as a8, displayPathLocation as a9, visibleSearchFilters as aA, getCmsCollection as aa, getCmsCollections as ab, getCmsEntries as ac, getCmsEntry as ad, getListing as ae, getListings as af, getSearchUi as ag, getSimilarListings as ah, getSite as ai, hrefForAppliedChange as aj, hrefForPathFilters as ak, hrefWithExplicitPage as al, isListingDetailPath as am, paginationPages as an, pathFilterHasOption as ao, pathFilterValue as ap, publicSearchHref as aq, queryListings as ar, rangeDraftFromPath as as, readPublicSearch as at, searchChromeModel as au, searchHrefUsesLegacyFilterQuery as av, searchListings as aw, searchResultsHeading as ax, searchSortOptions as ay, toolbarFilterIds as az, type ListingMedia as b, type ListingBusinessType as c, type ListingPriceVisibility as d, type Listing as e, type SearchUiDictionary as f, type AppliedSearchChange as g, type ListingFilters as h, type ListingsResult as i, type Site as j, type SearchListingsParams as k, type SearchListingsResult as l, type SearchUi as m, type QueryListingsParams as n, type QueryListingsResult as o, type SimilarListingsResult as p, type CmsEntriesResult as q, type CmsEntry as r, type PhotoSearchResult as s, type PhotoSearchItem as t, type ListingWithMatchedPhoto as u, type CmsEntryStatus as v, type CmsFieldDefinition as w, type CmsFieldType as x, type CmsSeoData as y, FORBIDDEN_SEARCH_QUERY_KEYS as z };
1076
+ export { type CmsEntryStatus as $, type AppliedSearchQuery as A, type BoundaryCity as B, type CmsCollection as C, type TravelMode as D, type TravelTimeOptions as E, type FetchLike as F, type TravelTime as G, type TravelTimesOptions as H, type TravelTimeElement as I, type Listing as J, type PhotoSearchResult as K, type ListingDetail as L, type MapsCoordinates as M, type NeighborhoodBoundaryOptions as N, type PhotoSearchItem as O, type PhotoSearchParams as P, type QueryListingsFilters as Q, type RequestNextOptions as R, type SearchPathFilters as S, type TravelTimeCacheOptions as T, type ListingWithMatchedPhoto as U, type MatchedListingPhoto as V, type BoundaryFeature as W, type BoundaryFeatureCollection as X, type BoundaryGeometry as Y, type BoundaryLayerUrlKind as Z, type BoundarySourceLayer as _, type ListingLocation as a, hrefWithExplicitPage as a$, type CmsFieldDefinition as a0, type CmsFieldType as a1, type CmsSeoData as a2, FORBIDDEN_SEARCH_QUERY_KEYS as a3, GaragemSdkError as a4, type GetCmsCollectionOptions as a5, type GetCmsCollectionsOptions as a6, type GetCmsEntriesOptions as a7, type GetCmsEntryOptions as a8, type GetListingOptions as a9, type SearchListingsOptions as aA, type SearchPathLocation as aB, type SearchUiFilter as aC, type SearchUiOption as aD, type StaticMapStyle as aE, TOOLBAR_PRIMARY_FILTER_IDS as aF, applyPathFilter as aG, buildQueryListingsParams as aH, canonicalizeSearchHref as aI, capMapPage as aJ, capMapPageSize as aK, clearStagedPathFilters as aL, clusterPins as aM, countFacetChoices as aN, countOptionLabel as aO, displayPathLocation as aP, getCmsCollection as aQ, getCmsCollections as aR, getCmsEntries as aS, getCmsEntry as aT, getListing as aU, getListings as aV, getSearchUi as aW, getSimilarListings as aX, getSite as aY, hrefForAppliedChange as aZ, hrefForPathFilters as a_, type GetListingsOptions as aa, type GetSearchUiOptions as ab, type GetSimilarListingsOptions as ac, type GetSiteOptions as ad, type ListingBusinessType as ae, type ListingCardModel as af, type ListingPriceVisibility as ag, type ListingPropertySummary as ah, type LocationNameTables as ai, MAP_POLYGON_MAX_VERTICES as aj, MAP_SEARCH_DEFAULT_PAGE_SIZE as ak, MAP_SEARCH_MAX_PAGE_SIZE as al, MAP_VIEWPORT_DEBOUNCE_MS as am, type MapBounds as an, type MapBoundsSearchOptions as ao, type MapPin as ap, type MapPinCluster as aq, type MapPolygon as ar, type MapPolygonSearchOptions as as, type MapSearchResult as at, type MapsBaseOptions as au, type QueryListingsLocation as av, type QueryListingsOptions as aw, SEARCH_EMPTY_COPY as ax, SEARCH_SORT_RELEVANCE as ay, type SearchChromeModel as az, type ListingMedia as b, isListingDetailPath as b0, isMapBounds as b1, isMapPolygon as b2, listingLocationLabel as b3, mapClusterCellDegrees as b4, mapSearchPins as b5, paginationPages as b6, pathFilterHasOption as b7, pathFilterValue as b8, publicSearchHref as b9, queryListings as ba, rangeDraftFromPath as bb, readPublicSearch as bc, searchChromeModel as bd, searchHrefUsesLegacyFilterQuery as be, searchListings as bf, searchListingsInBounds as bg, searchListingsInPolygon as bh, searchResultsHeading as bi, searchSortOptions as bj, toListingCardModel as bk, toolbarFilterIds as bl, visibleSearchFilters as bm, type MapSearchSubscription as bn, type SearchUiDictionary as c, type AppliedSearchChange as d, type ListingFilters as e, type ListingsResult as f, type Site as g, type SearchListingsParams as h, type SearchListingsResult as i, type SearchUi as j, type QueryListingsParams as k, type QueryListingsResult as l, type SimilarListingsResult as m, type CmsEntriesResult as n, type CmsEntry as o, type BoundaryLayerOptions as p, type TravelTimeCache as q, type MapsFetchOptions as r, type BoundaryLayer as s, type ListingWithLocation as t, type StaticMapOptions as u, type StreetViewAvailabilityOptions as v, type StreetViewAvailability as w, type StreetViewOptions as x, type NeighborhoodBoundary as y, type TravelDestination as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@garagem-ai/site-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "private": false,
5
5
  "description": "Typed, runtime-agnostic SDK for building custom real estate sites against the Garagem platform. Drop into any Next.js (or other JS) project to fetch listings, sites and CMS data.",
6
6
  "main": "./dist/index.js",
package/src/client.ts CHANGED
@@ -55,6 +55,12 @@ export interface CreateGaragemClientOptions {
55
55
  baseUrl?: string;
56
56
  /** Pre-bind a site so each call doesn't repeat it. */
57
57
  siteId?: string;
58
+ /**
59
+ * Publishable key (`pk_live_…`) from the site's API pública settings.
60
+ * Sent as `X-Garagem-Publishable-Key` on every request. Not a secret.
61
+ * Omit it to keep the anonymous per-IP budget.
62
+ */
63
+ publishableKey?: string;
58
64
  /** Custom fetch implementation. */
59
65
  fetch?: FetchLike;
60
66
  /** Default Next.js caching hints applied to every request. */
@@ -187,14 +193,22 @@ export function createGaragemClient(
187
193
  baseUrl?: string;
188
194
  fetch?: FetchLike;
189
195
  next?: RequestNextOptions;
196
+ publishableKey?: string;
190
197
  } => {
191
198
  const out: T & {
192
199
  baseUrl?: string;
193
200
  fetch?: FetchLike;
194
201
  next?: RequestNextOptions;
202
+ publishableKey?: string;
195
203
  } = { ...opts };
196
204
  if (options.baseUrl !== undefined) out.baseUrl = options.baseUrl;
197
205
  if (options.fetch !== undefined) out.fetch = options.fetch;
206
+ if (
207
+ options.publishableKey !== undefined &&
208
+ out.publishableKey === undefined
209
+ ) {
210
+ out.publishableKey = options.publishableKey;
211
+ }
198
212
  return out;
199
213
  };
200
214
 
@@ -227,6 +241,9 @@ export function createGaragemClient(
227
241
  if (domain !== undefined) opts.domain = domain;
228
242
  if (options.baseUrl !== undefined) opts.baseUrl = options.baseUrl;
229
243
  if (options.fetch !== undefined) opts.fetch = options.fetch;
244
+ if (options.publishableKey !== undefined) {
245
+ opts.publishableKey = options.publishableKey;
246
+ }
230
247
  const merged = mergeNext(next);
231
248
  if (merged !== undefined) opts.next = merged;
232
249
  return getSite(opts);
@@ -339,3 +356,9 @@ export function createGaragemClient(
339
356
  },
340
357
  };
341
358
  }
359
+
360
+ /**
361
+ * Alias of {@link createGaragemClient}. `createClient({ publishableKey })`
362
+ * binds the key the same way.
363
+ */
364
+ export const createClient = createGaragemClient;
@@ -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
+ }