@garagem-ai/site-sdk 0.11.1 → 0.12.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@garagem-ai/site-sdk",
3
- "version": "0.11.1",
3
+ "version": "0.12.1",
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/index.ts CHANGED
@@ -82,6 +82,18 @@ export {
82
82
  type SearchListingsOptions,
83
83
  } from "./fetchers";
84
84
 
85
+ export { getShareLink, type GetShareLinkOptions } from "./share";
86
+
87
+ export type {
88
+ ShareEntityType,
89
+ ShareLinkError,
90
+ ShareLinkErrorReason,
91
+ ShareLinkResult,
92
+ ShareLinkSuccess,
93
+ ShareLinkToken,
94
+ ShareListingEntity,
95
+ } from "./types-share";
96
+
85
97
  export {
86
98
  STUDIO_DEFAULT_VISIT_SCHEDULE,
87
99
  VISIT_TIME_ZONE,
@@ -286,7 +298,9 @@ export {
286
298
  studioPhotoSearchInstruction,
287
299
  isPhotoSearchOnPin,
288
300
  isSellerLeadOnPin,
301
+ isShareLinkOnPin,
289
302
  studioSellerLeadSdkInstruction,
303
+ studioShareLinkInstruction,
290
304
  studioSdkPinInstruction,
291
305
  studioSiteWidthCss,
292
306
  hasShowcaseLeadsPostUrl,
package/src/share.ts ADDED
@@ -0,0 +1,114 @@
1
+ import type { RequestNextOptions } from "./types";
2
+ import type { ShareLinkResult } from "./types-share";
3
+ import { withPublishableKeyHeader } from "./internal/sdk-http";
4
+ import { normalizeBaseUrl } from "./internal/url";
5
+ import { GaragemSdkError, type FetchLike } from "./fetchers";
6
+
7
+ export interface GetShareLinkOptions {
8
+ /** The `{token}` from a `/p/{token}` (or `/s`, `/i`, `/r`, `/c`) URL. */
9
+ token: string;
10
+ /** Password for a password-protected share. Sends a POST when present,
11
+ * a GET otherwise — matches the Foundation route's contract. */
12
+ password?: string;
13
+ /** Garagem API base URL. Defaults to `https://app.garagem.ai`. */
14
+ baseUrl?: string;
15
+ /** Override the fetch implementation (testing, edge runtimes, retries). */
16
+ fetch?: FetchLike;
17
+ /** Next.js App Router caching hints. Ignored on runtimes that don't
18
+ * understand them. Share links are per-visitor and often
19
+ * password/expiry-gated — avoid caching this call in production unless
20
+ * you know the token is long-lived and public. */
21
+ next?: RequestNextOptions;
22
+ /**
23
+ * Site publishable key (`pk_live_…`) from Configurações → Sites → API
24
+ * pública. Not a secret. Omit it and the request stays anonymous.
25
+ */
26
+ publishableKey?: string;
27
+ }
28
+
29
+ interface RawShareErrorBody {
30
+ error?: string;
31
+ reason?: string;
32
+ listingCode?: string;
33
+ site?: Record<string, unknown>;
34
+ }
35
+
36
+ interface ShareFetchInit extends RequestInit {
37
+ next?: RequestNextOptions;
38
+ }
39
+
40
+ /**
41
+ * Resolve a share-link token (`/p/{token}` and friends) against Foundation's
42
+ * public share-link API.
43
+ *
44
+ * Unlike {@link import("./fetchers").getListing}, this does **not** throw on
45
+ * a 401/403/404/410 — those are expected, UI-relevant outcomes for a share
46
+ * page (password gate, expired link, not found), returned as
47
+ * `{ ok: false, reason, ... }` so the caller can branch instead of catching.
48
+ * Genuine transport/5xx failures still throw {@link GaragemSdkError}.
49
+ *
50
+ * @example
51
+ * const result = await getShareLink({ token });
52
+ * if (!result.ok && result.reason === "password_required") {
53
+ * // render a password form, then retry with `password`
54
+ * }
55
+ * if (!result.ok) {
56
+ * // "not_found" | "inactive" | "expired" | other -> not-available state
57
+ * }
58
+ * // result.ok === true: result.entity (today's raw shape — see
59
+ * // types-share.ts doc for the planned normalized `listing` field)
60
+ */
61
+ export async function getShareLink(
62
+ options: GetShareLinkOptions
63
+ ): Promise<ShareLinkResult> {
64
+ const { token, password, baseUrl, fetch: fetchImpl, next } = options;
65
+ if (!token || !token.trim()) {
66
+ throw new TypeError("getShareLink: `token` is required");
67
+ }
68
+ const base = normalizeBaseUrl(baseUrl);
69
+ const url = `${base}/api/sites/share/${encodeURIComponent(token)}`;
70
+ const doFetch = fetchImpl ?? fetch;
71
+
72
+ const baseInit: ShareFetchInit = password
73
+ ? {
74
+ method: "POST",
75
+ headers: {
76
+ Accept: "application/json",
77
+ "Content-Type": "application/json",
78
+ },
79
+ body: JSON.stringify({ password }),
80
+ next,
81
+ }
82
+ : { method: "GET", headers: { Accept: "application/json" }, next };
83
+
84
+ const init = withPublishableKeyHeader(baseInit, options.publishableKey);
85
+
86
+ const response = await doFetch(url, init);
87
+
88
+ if (response.ok) {
89
+ return { ok: true, ...(await response.json()) } as ShareLinkResult;
90
+ }
91
+
92
+ // Foundation's own "this token is bad" responses (404/410/401/403) are
93
+ // well-formed JSON errors, not transport failures — surface them as data.
94
+ const EXPECTED_STATUSES = new Set([400, 401, 403, 404, 410]);
95
+ if (EXPECTED_STATUSES.has(response.status)) {
96
+ const body = (await response.json().catch(() => ({}))) as RawShareErrorBody;
97
+ return {
98
+ ok: false,
99
+ status: response.status,
100
+ reason: body.reason ?? null,
101
+ message: body.error ?? "Share link unavailable",
102
+ ...(body.listingCode ? { listingCode: body.listingCode } : {}),
103
+ ...(body.site ? { site: body.site } : {}),
104
+ };
105
+ }
106
+
107
+ const text = await response.text().catch(() => "");
108
+ throw new GaragemSdkError(
109
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${
110
+ text ? ` — ${text.slice(0, 200)}` : ""
111
+ }`,
112
+ { status: response.status, url }
113
+ );
114
+ }
@@ -24,10 +24,11 @@ export const STUDIO_SDK_CONTRACT = {
24
24
  * (`useMapSearch`, `searchListingsInBounds`) shipped in 0.9.0 — 0.7.0
25
25
  * does not export them. Property registration shipped in 0.10.0.
26
26
  * Weighted map buckets (`map.buckets`, clustered by the hook) shipped
27
- * in 0.11.0. Search filter helpers (`visibleSearchFilters` /
27
+ * in 0.11.0. Share links (`getShareLink`, `/p/[token]`) shipped in
28
+ * 0.12.0. Search filter helpers (`visibleSearchFilters` /
28
29
  * `toolbarFilterIds`) shipped in 0.4.12 and remain on this pin.
29
30
  */
30
- minNpmVersion: "0.11.0",
31
+ minNpmVersion: "0.12.0",
31
32
  /** Historical: older tarballs inject card CSS when those components mount. */
32
33
  selfInjectSince: "0.4.2",
33
34
  chromeStrategy: "app-owned" as const,
@@ -227,6 +228,14 @@ export const STUDIO_SDK_CONTRACT = {
227
228
  "isValidName",
228
229
  ] as const,
229
230
  sellerLeadSince: "0.10.0",
231
+ /**
232
+ * Share-link page (`/p/[token]`). Prompt-safe only once `minNpmVersion`
233
+ * reaches `shareLinkSince`. Below it `studioShareLinkInstruction` prints
234
+ * nothing and `studioCodegenContractViolations` flags `getShareLink` —
235
+ * v0 installs the pin and copies any identifier it sees.
236
+ */
237
+ shareExports: ["getShareLink"] as const,
238
+ shareLinkSince: "0.12.0",
230
239
  } as const;
231
240
 
232
241
  export type StudioSdkContract = typeof STUDIO_SDK_CONTRACT;
@@ -238,6 +247,25 @@ export function isSellerLeadOnPin(
238
247
  return compareSemver(pin, STUDIO_SDK_CONTRACT.sellerLeadSince) >= 0;
239
248
  }
240
249
 
250
+ /** Whether the pinned tarball exports `getShareLink`. */
251
+ export function isShareLinkOnPin(
252
+ pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
253
+ ): boolean {
254
+ return compareSemver(pin, STUDIO_SDK_CONTRACT.shareLinkSince) >= 0;
255
+ }
256
+
257
+ /**
258
+ * Native `/p/[token]` page. Empty below `shareLinkSince`, so the current
259
+ * Studio prompt does not mention `getShareLink`.
260
+ */
261
+ export function studioShareLinkInstruction(
262
+ pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
263
+ ): string {
264
+ if (!isShareLinkOnPin(pin)) return "";
265
+ const name = STUDIO_SDK_CONTRACT.shareExports[0];
266
+ return `Share links (\`/p/[token]\`): add a server page \`app/p/[token]/page.tsx\`. Read \`token\` from the route params and \`const result = await ${name}({ token, baseUrl: GARAGEM_API_BASE })\`. When \`result.ok\` is false and \`result.reason\` is \`password_required\` or \`password_invalid\`, render a password form and submit \`getShareLink({ token, password, baseUrl: GARAGEM_API_BASE })\`. For \`not_found\`, \`inactive\`, or \`expired\`, say the link is no longer available — do not render a generic framework 404. When \`result.ok\` and \`result.listing\` is set, render that listing with the same listing-detail module \`/imoveis\` already uses (\`listingDetailModel\` and the site gallery). Do not invent a second listing layout and do not proxy the page to another host.`;
267
+ }
268
+
241
269
  /**
242
270
  * Fixed SDK half of the property-registration page. The configured fields
243
271
  * and photo options come from the Studio onboarding block. Empty below
@@ -600,6 +628,13 @@ export function studioCodegenContractViolations(text: string): string[] {
600
628
  }
601
629
  }
602
630
  }
631
+ if (!isShareLinkOnPin()) {
632
+ for (const name of STUDIO_SDK_CONTRACT.shareExports) {
633
+ if (mentionsExportName(text, name) && !violations.includes(name)) {
634
+ violations.push(name);
635
+ }
636
+ }
637
+ }
603
638
  const pin = STUDIO_SDK_CONTRACT.minNpmVersion;
604
639
  if (!marketExportsAvailableAt(pin)) {
605
640
  for (const name of STUDIO_SDK_CONTRACT.marketExports) {
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Types for the public Share Link API (`GET`/`POST /api/sites/share/{token}`).
3
+ *
4
+ * This mirrors `resolveShareToken()` in Foundation
5
+ * (`apps/foundation/os/domain/sites/public/share-token.ts`) — treat it as a
6
+ * public contract (additive changes only), but note it is **today's raw
7
+ * shape**, not the friendly `Listing`/`ListingDetail` contract `getListing`
8
+ * returns. Field-visibility masking (price/address/agent redaction per the
9
+ * tenant's sharing config) is already applied server-side before you see
10
+ * this payload — do not try to "fix" a hidden price or address.
11
+ *
12
+ * For `entityType === "listing"`, `listing` is the same shape `getListing`
13
+ * returns. Render that. `entity` stays the raw Foundation payload.
14
+ */
15
+
16
+ import type { ListingDetail } from "./types";
17
+
18
+ /** Entity kinds a share token can point at. Only `"listing"` is typed in
19
+ * detail today; the rest pass through as raw records pending follow-up
20
+ * work. */
21
+ export type ShareEntityType =
22
+ | "listing"
23
+ | "shortlist"
24
+ | "seller_report"
25
+ | "visit_itinerary"
26
+ | "pricing_tool"
27
+ | "visit_survey"
28
+ | "form"
29
+ | (string & {});
30
+
31
+ /** Why `getShareLink` failed. Maps 1:1 to `resolveShareToken`'s reasons. */
32
+ export type ShareLinkErrorReason =
33
+ | "not_found"
34
+ | "inactive"
35
+ | "expired"
36
+ | "password_required"
37
+ | "password_invalid"
38
+ | (string & {});
39
+
40
+ /** Raw listing + property fields for a `listing`-type share token.
41
+ * Foundation-internal column names — distinct from the public `Listing`
42
+ * type's field names (e.g. `parkingSpots` here vs. `parkingSpaces` there).
43
+ * See the module doc: a normalized, `ListingDetail`-shaped field is
44
+ * planned as an additive follow-up. */
45
+ export interface ShareListingEntity {
46
+ listing: {
47
+ id: string;
48
+ title: string;
49
+ description: string | null;
50
+ price: number | null;
51
+ currency: string | null;
52
+ priceVisibility: string | null;
53
+ listingType: string | null;
54
+ listingCode: string | null;
55
+ stage: string | null;
56
+ status: string | null;
57
+ visibility: string | null;
58
+ createdAt: string | null;
59
+ publishedAt: string | null;
60
+ propertyId: string | null;
61
+ isPrimaryMarket: boolean | null;
62
+ typologyId: string | null;
63
+ };
64
+ property: Record<string, unknown> | null;
65
+ media: Array<{
66
+ id: string;
67
+ src: string;
68
+ alt?: string;
69
+ type: "image" | "video" | "tour";
70
+ category?: string;
71
+ order?: number;
72
+ isPrimary?: boolean;
73
+ entityType?: string;
74
+ }>;
75
+ [key: string]: unknown;
76
+ }
77
+
78
+ /** Share-token metadata echoed back on a successful resolve. */
79
+ export interface ShareLinkToken {
80
+ entityType: ShareEntityType;
81
+ entityId: string;
82
+ [key: string]: unknown;
83
+ }
84
+
85
+ /** Successful `getShareLink` result. */
86
+ export interface ShareLinkSuccess {
87
+ ok: true;
88
+ /** `entity` is typed for `entityType === "listing"`; narrow with a type
89
+ * guard (`result.token.entityType === "listing"`) before reading
90
+ * listing-specific fields on other entity types. */
91
+ token: ShareLinkToken;
92
+ entity: ShareListingEntity | Record<string, unknown>;
93
+ branding?: Record<string, unknown>;
94
+ agentInfo?: Record<string, unknown>;
95
+ tenantConfig?: Record<string, unknown>;
96
+ site?: Record<string, unknown>;
97
+ shareDisplayConfig?: Record<string, unknown>;
98
+ requestConfig?: Record<string, unknown>;
99
+ offerForm?: Record<string, unknown>;
100
+ tenantId: string;
101
+ /**
102
+ * Present for `entityType === "listing"` once Foundation attaches the
103
+ * public `getListing` shape. Render this with the same listing-detail
104
+ * module as `/imoveis`. Absent on older payloads and on other entity types.
105
+ */
106
+ listing?: ListingDetail;
107
+ }
108
+
109
+ /** Failed `getShareLink` result. Branch UI on `reason`, not just `status`.
110
+ * `listingCode` / `site` are present on some errors (e.g. `password_required`
111
+ * for a listing share) so a password gate can still show which listing it's
112
+ * for. */
113
+ export interface ShareLinkError {
114
+ ok: false;
115
+ status: number;
116
+ reason: ShareLinkErrorReason | null;
117
+ message: string;
118
+ listingCode?: string;
119
+ site?: Record<string, unknown>;
120
+ }
121
+
122
+ export type ShareLinkResult = ShareLinkSuccess | ShareLinkError;