@garagem-ai/site-sdk 0.4.2 → 0.4.3

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/dist/index.mjs CHANGED
@@ -314,6 +314,352 @@ async function getCmsEntry(options) {
314
314
  return data;
315
315
  }
316
316
 
317
+ // src/schedule.ts
318
+ var VISIT_TIME_ZONE = "America/Sao_Paulo";
319
+ var HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
320
+ var YMD_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
321
+ var WEEKDAY_SHORT = {
322
+ Sun: 0,
323
+ Mon: 1,
324
+ Tue: 2,
325
+ Wed: 3,
326
+ Thu: 4,
327
+ Fri: 5,
328
+ Sat: 6
329
+ };
330
+ function pad2(value) {
331
+ return String(value).padStart(2, "0");
332
+ }
333
+ function parseHHmm(value) {
334
+ const match = HHMM_RE.exec(value);
335
+ if (!match) return null;
336
+ return { hour: Number(match[1]), minute: Number(match[2]) };
337
+ }
338
+ function minutesOfDay(hhmm) {
339
+ const parsed = parseHHmm(hhmm);
340
+ if (!parsed) return null;
341
+ return parsed.hour * 60 + parsed.minute;
342
+ }
343
+ function expandVisitTimeSlots(hours) {
344
+ const start = minutesOfDay(hours.start);
345
+ const end = minutesOfDay(hours.end);
346
+ if (start == null || end == null || start > end) return [];
347
+ const slots = [];
348
+ for (let minutes = start; minutes <= end; minutes += 60) {
349
+ const hour = Math.floor(minutes / 60);
350
+ const minute = minutes % 60;
351
+ slots.push(`${pad2(hour)}:${pad2(minute)}`);
352
+ }
353
+ return slots;
354
+ }
355
+ function unionSorted(left, right) {
356
+ return Array.from(/* @__PURE__ */ new Set([...left, ...right])).sort();
357
+ }
358
+ function expandVisitSchedule(config) {
359
+ const weekendHours = config.weekend ?? (config.saturday || config.sunday ? config.weekday : null);
360
+ const weekdayTimeSlots = expandVisitTimeSlots(config.weekday);
361
+ const weekendTimeSlots = weekendHours ? expandVisitTimeSlots(weekendHours) : [];
362
+ const disabledDays = [];
363
+ if (!config.sunday) disabledDays.push(0);
364
+ if (!config.saturday) disabledDays.push(6);
365
+ return {
366
+ ...config,
367
+ weekend: weekendHours,
368
+ disabledDays,
369
+ weekdayTimeSlots,
370
+ weekendTimeSlots,
371
+ timeSlots: unionSorted(weekdayTimeSlots, weekendTimeSlots)
372
+ };
373
+ }
374
+ var STUDIO_DEFAULT_VISIT_SCHEDULE = expandVisitSchedule(
375
+ {
376
+ timeZone: VISIT_TIME_ZONE,
377
+ saturday: false,
378
+ sunday: false,
379
+ weekday: { start: "06:00", end: "22:00" },
380
+ weekend: null,
381
+ minHoursAhead: 2
382
+ }
383
+ );
384
+ function zonedParts(date, timeZone) {
385
+ const parts = new Intl.DateTimeFormat("en-US", {
386
+ timeZone,
387
+ weekday: "short",
388
+ year: "numeric",
389
+ month: "2-digit",
390
+ day: "2-digit",
391
+ hour: "2-digit",
392
+ minute: "2-digit",
393
+ hourCycle: "h23"
394
+ }).formatToParts(date);
395
+ const get = (type) => parts.find((part) => part.type === type)?.value ?? "";
396
+ const weekday = WEEKDAY_SHORT[get("weekday")] ?? 0;
397
+ return {
398
+ year: Number(get("year")),
399
+ month: Number(get("month")),
400
+ day: Number(get("day")),
401
+ hour: Number(get("hour")),
402
+ minute: Number(get("minute")),
403
+ weekday
404
+ };
405
+ }
406
+ function calendarYmd(date, timeZone) {
407
+ const parts = zonedParts(date, timeZone);
408
+ return `${parts.year}-${pad2(parts.month)}-${pad2(parts.day)}`;
409
+ }
410
+ function parseYmd(value) {
411
+ const match = YMD_RE.exec(value);
412
+ if (!match) return null;
413
+ const year = Number(match[1]);
414
+ const month = Number(match[2]);
415
+ const day = Number(match[3]);
416
+ const utc = new Date(Date.UTC(year, month - 1, day));
417
+ if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
418
+ return null;
419
+ }
420
+ return { year, month, day };
421
+ }
422
+ function toCalendarYmd(date, timeZone) {
423
+ if (typeof date === "string") {
424
+ return parseYmd(date) ? date : null;
425
+ }
426
+ if (date instanceof Date && Number.isFinite(date.getTime())) {
427
+ return calendarYmd(date, timeZone);
428
+ }
429
+ return null;
430
+ }
431
+ function weekdayOfYmd(ymd, timeZone) {
432
+ const parsed = parseYmd(ymd);
433
+ if (!parsed) return null;
434
+ const utcNoonish = new Date(
435
+ Date.UTC(parsed.year, parsed.month - 1, parsed.day, 15, 0, 0)
436
+ );
437
+ return zonedParts(utcNoonish, timeZone).weekday;
438
+ }
439
+ function slotsForDate(schedule, date, now = /* @__PURE__ */ new Date()) {
440
+ const timeZone = schedule.timeZone;
441
+ const ymd = toCalendarYmd(date, timeZone);
442
+ if (!ymd) return [];
443
+ const weekday = weekdayOfYmd(ymd, timeZone);
444
+ if (weekday == null) return [];
445
+ if (weekday === 0 && !schedule.sunday) return [];
446
+ if (weekday === 6 && !schedule.saturday) return [];
447
+ const base = weekday === 0 || weekday === 6 ? schedule.weekendTimeSlots : schedule.weekdayTimeSlots;
448
+ const today = calendarYmd(now, timeZone);
449
+ if (ymd < today) return [];
450
+ if (ymd !== today) return [...base];
451
+ const nowParts = zonedParts(now, timeZone);
452
+ const cutoff = nowParts.hour * 60 + nowParts.minute + schedule.minHoursAhead * 60;
453
+ return base.filter((slot) => {
454
+ const minutes = minutesOfDay(slot);
455
+ return minutes != null && minutes >= cutoff;
456
+ });
457
+ }
458
+ function isVisitSlotAllowed(schedule, visitDate, visitTime, now = /* @__PURE__ */ new Date()) {
459
+ return slotsForDate(schedule, visitDate, now).includes(visitTime);
460
+ }
461
+
462
+ // src/leads.ts
463
+ var LeadSubmitError = class extends Error {
464
+ code;
465
+ status;
466
+ retryAfterSeconds;
467
+ constructor(message, info) {
468
+ super(message);
469
+ this.name = "LeadSubmitError";
470
+ this.code = info.code;
471
+ if (info.status != null) this.status = info.status;
472
+ if (info.retryAfterSeconds != null) {
473
+ this.retryAfterSeconds = info.retryAfterSeconds;
474
+ }
475
+ }
476
+ };
477
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
478
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
479
+ var MESSAGE_MAX = 2e3;
480
+ var CONTACT_FIELDS = [
481
+ { id: "name", required: true },
482
+ { id: "email", required: false },
483
+ { id: "phone", required: false },
484
+ { id: "message", required: false }
485
+ ];
486
+ function studioDefaultLeadUi() {
487
+ return {
488
+ defaultVariant: "visit",
489
+ timeZone: "America/Sao_Paulo",
490
+ variants: {
491
+ visit: {
492
+ ctaLabel: "Agendar visita",
493
+ requireDateTime: true,
494
+ schedule: STUDIO_DEFAULT_VISIT_SCHEDULE,
495
+ fields: CONTACT_FIELDS
496
+ },
497
+ contact: {
498
+ ctaLabel: "Fale conosco",
499
+ requireDateTime: false,
500
+ whatsappPhone: null,
501
+ fields: CONTACT_FIELDS
502
+ }
503
+ }
504
+ };
505
+ }
506
+ async function getLeadUi(options) {
507
+ const siteId = await coerceSiteId(options.siteId);
508
+ const url = `${normalizeBaseUrl(options.baseUrl)}/api/sites/${encodeURIComponent(siteId)}/leads/ui`;
509
+ return callJson(
510
+ url,
511
+ {
512
+ method: "GET",
513
+ headers: { Accept: "application/json" },
514
+ next: options.next
515
+ },
516
+ options.fetch ?? fetch
517
+ );
518
+ }
519
+ function assertListingId(listingId) {
520
+ if (!UUID_RE.test(listingId.trim())) {
521
+ throw new LeadSubmitError(
522
+ "Garagem SDK: listingId must be the listing UUID, not a path or code.",
523
+ { code: "invalid_listing_id" }
524
+ );
525
+ }
526
+ }
527
+ function normalizeContact(input) {
528
+ const name = input.name.trim();
529
+ if (name.length < 2 || name.length > 200) {
530
+ throw new LeadSubmitError("Garagem SDK: name is required.", {
531
+ code: "invalid_contact"
532
+ });
533
+ }
534
+ const email = input.email?.trim() || void 0;
535
+ const phone = input.phone?.trim() || void 0;
536
+ if (!email && !phone) {
537
+ throw new LeadSubmitError("Garagem SDK: email and/or phone is required.", {
538
+ code: "invalid_contact"
539
+ });
540
+ }
541
+ if (email && !EMAIL_RE.test(email)) {
542
+ throw new LeadSubmitError("Garagem SDK: email is invalid.", {
543
+ code: "invalid_contact"
544
+ });
545
+ }
546
+ if (phone && (phone.length < 5 || phone.length > 40)) {
547
+ throw new LeadSubmitError("Garagem SDK: phone is invalid.", {
548
+ code: "invalid_contact"
549
+ });
550
+ }
551
+ const message = input.message?.trim() || void 0;
552
+ if (message && message.length > MESSAGE_MAX) {
553
+ throw new LeadSubmitError("Garagem SDK: message is too long.", {
554
+ code: "invalid_contact"
555
+ });
556
+ }
557
+ return {
558
+ name,
559
+ ...email ? { email } : {},
560
+ ...phone ? { phone } : {},
561
+ ...message ? { message } : {}
562
+ };
563
+ }
564
+ async function postSiteLead(input) {
565
+ const siteId = await coerceSiteId(input.siteId);
566
+ const base = normalizeBaseUrl(input.baseUrl);
567
+ const url = `${base}/api/webhooks/sites/${encodeURIComponent(siteId)}/leads`;
568
+ const f = input.fetch ?? fetch;
569
+ let response;
570
+ try {
571
+ response = await f(url, {
572
+ method: "POST",
573
+ headers: {
574
+ Accept: "application/json",
575
+ "Content-Type": "application/json"
576
+ },
577
+ body: JSON.stringify(input.body)
578
+ });
579
+ } catch (error) {
580
+ throw new LeadSubmitError(
581
+ error instanceof Error ? error.message : "Garagem SDK: network error.",
582
+ { code: "network" }
583
+ );
584
+ }
585
+ if (response.status === 202) {
586
+ const data = await response.json().catch(() => ({}));
587
+ const id = typeof data.id === "string" && data.id ? data.id : "";
588
+ return { ok: true, status: 202, id };
589
+ }
590
+ const retryAfter = Number(response.headers.get("Retry-After") ?? "");
591
+ if (response.status === 429) {
592
+ throw new LeadSubmitError("Garagem SDK: too many lead submissions.", {
593
+ code: "rate_limited",
594
+ status: 429,
595
+ retryAfterSeconds: Number.isFinite(retryAfter) ? retryAfter : void 0
596
+ });
597
+ }
598
+ if (response.status === 404) {
599
+ throw new LeadSubmitError("Garagem SDK: listing or site not found.", {
600
+ code: "not_found",
601
+ status: 404
602
+ });
603
+ }
604
+ throw new LeadSubmitError(
605
+ `Garagem SDK: lead submit failed (${response.status}).`,
606
+ { code: "http", status: response.status }
607
+ );
608
+ }
609
+ function leadPostContext(input) {
610
+ assertListingId(input.listingId);
611
+ return {
612
+ listingId: input.listingId.trim(),
613
+ contact: normalizeContact(input),
614
+ extras: {
615
+ ...input.visitorId ? { visitorId: input.visitorId } : {},
616
+ ...input.brokerRef ? { brokerRef: input.brokerRef } : {},
617
+ ...input.referrer ? { referrer: input.referrer } : {}
618
+ }
619
+ };
620
+ }
621
+ async function submitVisitLead(input) {
622
+ const prepared = leadPostContext(input);
623
+ const schedule = input.schedule ?? STUDIO_DEFAULT_VISIT_SCHEDULE;
624
+ if (!isVisitSlotAllowed(schedule, input.visitDate, input.visitTime)) {
625
+ throw new LeadSubmitError(
626
+ "Garagem SDK: visitDate/visitTime is outside the published schedule.",
627
+ { code: "invalid_slot" }
628
+ );
629
+ }
630
+ return postSiteLead({
631
+ siteId: input.siteId,
632
+ baseUrl: input.baseUrl,
633
+ fetch: input.fetch,
634
+ body: {
635
+ source: "site-sdk",
636
+ leadType: "visit",
637
+ ...prepared.contact,
638
+ propertyId: prepared.listingId,
639
+ listingId: prepared.listingId,
640
+ visitDate: input.visitDate,
641
+ visitTime: input.visitTime,
642
+ ...prepared.extras
643
+ }
644
+ });
645
+ }
646
+ async function submitContactLead(input) {
647
+ const prepared = leadPostContext(input);
648
+ return postSiteLead({
649
+ siteId: input.siteId,
650
+ baseUrl: input.baseUrl,
651
+ fetch: input.fetch,
652
+ body: {
653
+ source: "site-sdk",
654
+ leadType: "contact",
655
+ ...prepared.contact,
656
+ propertyId: prepared.listingId,
657
+ listingId: prepared.listingId,
658
+ ...prepared.extras
659
+ }
660
+ });
661
+ }
662
+
317
663
  // src/presentation.ts
318
664
  var SEARCH_CSS_VARS = {
319
665
  cardRadius: "--garagem-listing-card-radius",
@@ -1206,10 +1552,10 @@ var STUDIO_SDK_CONTRACT = {
1206
1552
  /**
1207
1553
  * Exact pin for generated Studio sites. Must be ≥ `selfInjectSince` so
1208
1554
  * prompts that skip the layout chrome tag match the tarball v0 installs.
1209
- * This PR’s changeset publishes that tarball as 0.4.2 — do not generate
1555
+ * This PR’s changeset publishes that tarball as 0.4.3 — do not generate
1210
1556
  * against this floor until Version Packages is on npm.
1211
1557
  */
1212
- minNpmVersion: "0.4.2",
1558
+ minNpmVersion: "0.4.3",
1213
1559
  /** First release where ListingCard and ResultsSkeleton inject the sheet. */
1214
1560
  selfInjectSince: "0.4.2",
1215
1561
  chromeStrategy: "self-inject",
@@ -1230,9 +1576,24 @@ var STUDIO_SDK_CONTRACT = {
1230
1576
  SearchPageFallback: "0.4.1",
1231
1577
  SearchChromeStyles: "0.4.1"
1232
1578
  },
1233
- forbiddenImports: ["@garagem-ai/site-sdk/react/search.css"]
1579
+ forbiddenImports: ["@garagem-ai/site-sdk/react/search.css"],
1580
+ leadStrategy: "visit-default",
1581
+ leadExports: [
1582
+ "getLeadUi",
1583
+ "submitVisitLead",
1584
+ "submitContactLead",
1585
+ "slotsForDate",
1586
+ "expandVisitSchedule",
1587
+ "expandVisitTimeSlots",
1588
+ "isVisitSlotAllowed",
1589
+ "STUDIO_DEFAULT_VISIT_SCHEDULE"
1590
+ ]
1234
1591
  };
1235
1592
  var REACT_SDK_NAMED_IMPORT_RE = /(?:^|[\n;])\s*import\s+(?!type\b)(?:type\s+)?\{([^}]+)\}\s+from\s+['"]@garagem-ai\/site-sdk\/react['"]/g;
1593
+ var SHOWCASE_LEADS_POST_URL_RE = /\/api\/sites\/[^\s"']*\/leads(?!\/ui)/;
1594
+ function hasShowcaseLeadsPostUrl(text) {
1595
+ return SHOWCASE_LEADS_POST_URL_RE.test(text);
1596
+ }
1236
1597
  function coerceNpmVersion(raw) {
1237
1598
  if (typeof raw !== "string") return null;
1238
1599
  const match = raw.trim().match(/(\d+)\.(\d+)\.(\d+)/);
@@ -1287,6 +1648,10 @@ function studioSdkPinInstruction() {
1287
1648
  const names = STUDIO_SDK_CONTRACT.reactExports.join(", ");
1288
1649
  return `In \`package.json\` set \`"@garagem-ai/site-sdk": "${version}"\` (exact). Import only these \`${STUDIO_SDK_PACKAGE}/react\` names: ${names}.`;
1289
1650
  }
1651
+ function studioLeadInstruction() {
1652
+ const names = STUDIO_SDK_CONTRACT.leadExports.join(", ");
1653
+ return `Listing-detail visit/contact leads: import ${names} from \`${STUDIO_SDK_PACKAGE}\` (the main package, not \`/react\`). Call \`submitVisitLead\` / \`submitContactLead\` \u2014 never concatenate a leads webhook URL and never POST the Showcase demo leads route.`;
1654
+ }
1290
1655
  function studioChromeInstruction() {
1291
1656
  const injectors = compareSemver(
1292
1657
  STUDIO_SDK_CONTRACT.minNpmVersion,
@@ -1306,6 +1671,12 @@ function studioCodegenContractViolations(text) {
1306
1671
  violations.push(name);
1307
1672
  }
1308
1673
  }
1674
+ if (hasShowcaseLeadsPostUrl(text)) {
1675
+ violations.push("showcase-leads-url");
1676
+ }
1677
+ if (/\btype\s*=\s*["']date["']/.test(text)) {
1678
+ violations.push("native-date-input");
1679
+ }
1309
1680
  return violations;
1310
1681
  }
1311
1682
 
@@ -1437,18 +1808,45 @@ function createGaragemClient(options = {}) {
1437
1808
  const merged = mergeNext(next);
1438
1809
  if (merged !== void 0) opts.next = merged;
1439
1810
  return getCmsEntry(opts);
1811
+ },
1812
+ async getLeadUi({ siteId, next } = {}) {
1813
+ const opts = withDefaults({
1814
+ siteId: resolveSiteId(siteId)
1815
+ });
1816
+ const merged = mergeNext(next);
1817
+ if (merged !== void 0) opts.next = merged;
1818
+ return getLeadUi(opts);
1819
+ },
1820
+ async submitVisitLead(args) {
1821
+ return submitVisitLead(
1822
+ withDefaults({
1823
+ ...args,
1824
+ siteId: resolveSiteId(args.siteId)
1825
+ })
1826
+ );
1827
+ },
1828
+ async submitContactLead(args) {
1829
+ return submitContactLead(
1830
+ withDefaults({
1831
+ ...args,
1832
+ siteId: resolveSiteId(args.siteId)
1833
+ })
1834
+ );
1440
1835
  }
1441
1836
  };
1442
1837
  }
1443
1838
  export {
1444
1839
  FORBIDDEN_SEARCH_QUERY_KEYS,
1445
1840
  GaragemSdkError,
1841
+ LeadSubmitError,
1446
1842
  SEARCH_CSS_RECIPE,
1447
1843
  SEARCH_CSS_VARS,
1448
1844
  SEARCH_SORT_RELEVANCE,
1845
+ STUDIO_DEFAULT_VISIT_SCHEDULE,
1449
1846
  STUDIO_SDK_CONTRACT,
1450
1847
  STUDIO_SDK_PACKAGE,
1451
1848
  TOOLBAR_PRIMARY_FILTER_IDS,
1849
+ VISIT_TIME_ZONE,
1452
1850
  applyPathFilter,
1453
1851
  buildQueryListingsParams,
1454
1852
  canonicalizeSearchHref,
@@ -1461,6 +1859,8 @@ export {
1461
1859
  countOptionLabel,
1462
1860
  createGaragemClient,
1463
1861
  displayPathLocation,
1862
+ expandVisitSchedule,
1863
+ expandVisitTimeSlots,
1464
1864
  formatAreaM2,
1465
1865
  formatGroupedInteger,
1466
1866
  formatListingPrice,
@@ -1468,16 +1868,19 @@ export {
1468
1868
  getCmsCollections,
1469
1869
  getCmsEntries,
1470
1870
  getCmsEntry,
1871
+ getLeadUi,
1471
1872
  getListing,
1472
1873
  getListings,
1473
1874
  getSearchUi,
1474
1875
  getSimilarListings,
1475
1876
  getSite,
1877
+ hasShowcaseLeadsPostUrl,
1476
1878
  hrefForAppliedChange,
1477
1879
  hrefForPathFilters,
1478
1880
  hrefWithExplicitPage,
1479
1881
  isListingDetailPath,
1480
1882
  isStudioPreviewHost,
1883
+ isVisitSlotAllowed,
1481
1884
  listingBusinessLabel,
1482
1885
  listingLocationLabel,
1483
1886
  listingLookupKey,
@@ -1502,9 +1905,14 @@ export {
1502
1905
  searchResultsHeading,
1503
1906
  searchSortOptions,
1504
1907
  serializeAppliedSearchQuery2 as serializeAppliedSearchQuery,
1908
+ slotsForDate,
1505
1909
  studioChromeInstruction,
1506
1910
  studioCodegenContractViolations,
1911
+ studioDefaultLeadUi,
1912
+ studioLeadInstruction,
1507
1913
  studioSdkPinInstruction,
1914
+ submitContactLead,
1915
+ submitVisitLead,
1508
1916
  toListingCardModel,
1509
1917
  toolbarFilterIds,
1510
1918
  unavailableReactImports,