@suiteop/storefront 0.1.0 → 0.1.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/CHANGELOG.md CHANGED
@@ -2,7 +2,12 @@
2
2
 
3
3
  Hand-written per release. Tag `storefront-sdk@<version>` on `main` publishes it.
4
4
 
5
- ## 0.1.0 — unreleased
5
+ ## 0.1.1
6
+
7
+ - The published `package.json` no longer carries the repository's own build scripts. No API
8
+ change.
9
+
10
+ ## 0.1.0
6
11
 
7
12
  - `createStorefrontClient`: site, listings, buildings, locations, amenities, reviews,
8
13
  availability, calendar, quotes, checkout sessions (create / get / confirm), bookings, contact.
@@ -15,7 +20,9 @@ Hand-written per release. Tag `storefront-sdk@<version>` on `main` publishes it.
15
20
  `<suiteop-checkout>` element, loaded from the storefront host with Subresource Integrity.
16
21
  - `getAttribution()`: the page's first-party attribution (`so_attr` first/last touch, GA and Meta
17
22
  browser ids, consent); `checkoutSessions.create` attaches it unless the caller passes its own
18
- `attribution` (or `null`).
23
+ `attribution` (or `null`). On a site running an A/B split between two deployments it also carries
24
+ the visitor's variant (`experiment: { id, variant }`, from the edge's `__so_exp` cookie, under
25
+ analytics consent).
19
26
  - `@suiteop/storefront/config`: `defineSuiteOpConfig` validates a site's `suiteop.config.ts`
20
27
  (theme, navigation, languages, SEO defaults).
21
28
  - `@suiteop/storefront/astro`: the `suiteop()` Astro integration — writes the site manifest to
@@ -18,7 +18,7 @@ declare const storefrontCalendarDaySchema: z.ZodObject<{
18
18
  minNights: z.ZodNullable<z.ZodNumber>;
19
19
  closedToArrival: z.ZodOptional<z.ZodBoolean>;
20
20
  closedToDeparture: z.ZodOptional<z.ZodBoolean>;
21
- status: z.ZodType<(string & {}) | "available" | "blocked" | "booked", unknown, z.core.$ZodTypeInternals<(string & {}) | "available" | "blocked" | "booked", unknown>>;
21
+ status: z.ZodType<"blocked" | "available" | "booked" | (string & {}), unknown, z.core.$ZodTypeInternals<"blocked" | "available" | "booked" | (string & {}), unknown>>;
22
22
  }, z.core.$strip>;
23
23
  type StorefrontCalendarDay = z.infer<typeof storefrontCalendarDaySchema>;
24
24
  declare const storefrontCalendarSchema: z.ZodObject<{
@@ -31,7 +31,7 @@ declare const storefrontCalendarSchema: z.ZodObject<{
31
31
  minNights: z.ZodNullable<z.ZodNumber>;
32
32
  closedToArrival: z.ZodOptional<z.ZodBoolean>;
33
33
  closedToDeparture: z.ZodOptional<z.ZodBoolean>;
34
- status: z.ZodType<(string & {}) | "available" | "blocked" | "booked", unknown, z.core.$ZodTypeInternals<(string & {}) | "available" | "blocked" | "booked", unknown>>;
34
+ status: z.ZodType<"blocked" | "available" | "booked" | (string & {}), unknown, z.core.$ZodTypeInternals<"blocked" | "available" | "booked" | (string & {}), unknown>>;
35
35
  }, z.core.$strip>>;
36
36
  }, z.core.$strip>;
37
37
  type StorefrontCalendar = z.infer<typeof storefrontCalendarSchema>;
@@ -18,7 +18,7 @@ declare const storefrontCalendarDaySchema: z.ZodObject<{
18
18
  minNights: z.ZodNullable<z.ZodNumber>;
19
19
  closedToArrival: z.ZodOptional<z.ZodBoolean>;
20
20
  closedToDeparture: z.ZodOptional<z.ZodBoolean>;
21
- status: z.ZodType<(string & {}) | "available" | "blocked" | "booked", unknown, z.core.$ZodTypeInternals<(string & {}) | "available" | "blocked" | "booked", unknown>>;
21
+ status: z.ZodType<"blocked" | "available" | "booked" | (string & {}), unknown, z.core.$ZodTypeInternals<"blocked" | "available" | "booked" | (string & {}), unknown>>;
22
22
  }, z.core.$strip>;
23
23
  type StorefrontCalendarDay = z.infer<typeof storefrontCalendarDaySchema>;
24
24
  declare const storefrontCalendarSchema: z.ZodObject<{
@@ -31,7 +31,7 @@ declare const storefrontCalendarSchema: z.ZodObject<{
31
31
  minNights: z.ZodNullable<z.ZodNumber>;
32
32
  closedToArrival: z.ZodOptional<z.ZodBoolean>;
33
33
  closedToDeparture: z.ZodOptional<z.ZodBoolean>;
34
- status: z.ZodType<(string & {}) | "available" | "blocked" | "booked", unknown, z.core.$ZodTypeInternals<(string & {}) | "available" | "blocked" | "booked", unknown>>;
34
+ status: z.ZodType<"blocked" | "available" | "booked" | (string & {}), unknown, z.core.$ZodTypeInternals<"blocked" | "available" | "booked" | (string & {}), unknown>>;
35
35
  }, z.core.$strip>>;
36
36
  }, z.core.$strip>;
37
37
  type StorefrontCalendar = z.infer<typeof storefrontCalendarSchema>;
package/dist/checkout.cjs CHANGED
@@ -1,12 +1,12 @@
1
1
  'use strict';
2
2
 
3
- var chunkTBADVD2J_cjs = require('./chunk-TBADVD2J.cjs');
4
- require('./chunk-T2GQ3DOZ.cjs');
3
+ var chunkRDREYP27_cjs = require('./chunk-RDREYP27.cjs');
4
+ require('./chunk-XIAAWHAY.cjs');
5
5
  require('./chunk-LVFRVNT3.cjs');
6
6
 
7
7
 
8
8
 
9
9
  Object.defineProperty(exports, "loadCheckout", {
10
10
  enumerable: true,
11
- get: function () { return chunkTBADVD2J_cjs.loadCheckout; }
11
+ get: function () { return chunkRDREYP27_cjs.loadCheckout; }
12
12
  });
package/dist/checkout.js CHANGED
@@ -1,3 +1,3 @@
1
- export { loadCheckout } from './chunk-ZYDFRRFU.js';
2
- import './chunk-NNZZWGM2.js';
1
+ export { loadCheckout } from './chunk-YFTWGF3L.js';
2
+ import './chunk-UACP7BZ7.js';
3
3
  import './chunk-6NFURJXI.js';
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ var chunkXIAAWHAY_cjs = require('./chunk-XIAAWHAY.cjs');
4
+ var chunkLVFRVNT3_cjs = require('./chunk-LVFRVNT3.cjs');
5
+ var chunkAIQUVZEI_cjs = require('./chunk-AIQUVZEI.cjs');
6
+ var zod = require('zod');
7
+
8
+ var STOREFRONT_CHANNELS=["ai_assistant","paid_search","paid_social","organic_search","organic_social","email","referral","direct"];var AI_ASSISTANT_HOSTS={"chatgpt.com":"chatgpt","chat.openai.com":"chatgpt","perplexity.ai":"perplexity","gemini.google.com":"gemini","copilot.microsoft.com":"copilot","claude.ai":"claude"};var AI_ASSISTANT_SOURCES={"chatgpt.com":"chatgpt",perplexity:"perplexity","perplexity.ai":"perplexity",gemini:"gemini",copilot:"copilot","claude.ai":"claude"};var PAID_CLICKS=["google","microsoft","meta"];var PAID_MEDIUMS=new Set(["cpc","ppc","paid","paidsearch","sem"]);var EMAIL_RE=/newsletter|mailchimp|klaviyo/;var SEARCH_SUFFIXES=["bing.com","duckduckgo.com","search.yahoo.com","baidu.com","ecosia.org","search.brave.com"];var SEARCH_ANY_TLD_RE=/^(?:www\.)?(?:google|yandex)\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SUFFIXES=["facebook.com","instagram.com","t.co","x.com","twitter.com","linkedin.com","tiktok.com","youtube.com","reddit.com"];var SOCIAL_ANY_TLD_RE=/(?:^|\.)pinterest\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SOURCES=new Set(["facebook","fb","instagram","ig","meta","twitter","x","linkedin","pinterest","tiktok","youtube","reddit"]);var clean=value=>{const v=value?.trim().toLowerCase();return v?v:null};var hostOf=value=>clean(value)?.replace(/\.$/,"")??null;var hostMatches=(host,suffix)=>host===suffix||host.endsWith(`.${suffix}`);var bareHost=host=>host.replace(/^www\./,"");function aiLabel(host,source){if(host){const suffix=Object.keys(AI_ASSISTANT_HOSTS).find(s=>hostMatches(host,s));if(suffix)return AI_ASSISTANT_HOSTS[suffix]}return source&&Object.hasOwn(AI_ASSISTANT_SOURCES,source)?AI_ASSISTANT_SOURCES[source]:null}var isSearchHost=host=>SEARCH_ANY_TLD_RE.test(host)||SEARCH_SUFFIXES.some(s=>hostMatches(host,s));var isSocialHost=host=>SOCIAL_ANY_TLD_RE.test(host)||SOCIAL_SUFFIXES.some(s=>hostMatches(host,s));function paidClickOf(t){const medium=clean(t.utmMedium);if(t.fbclid&&medium!==null&&PAID_MEDIUMS.has(medium))return "meta";if(t.gclid||t.gbraid||t.wbraid)return "google";if(t.msclkid)return "microsoft";if(t.fbclid)return "meta";return t.paidClick??null}function classifyChannel(t){const source=clean(t.utmSource);const medium=clean(t.utmMedium);const site=bareHost(hostOf(t.siteHost)??"");const ref=hostOf(t.referrerHost);const external=ref&&bareHost(ref)!==site?ref:null;const result=(channel,label=null)=>({channel,source:label??source??external,medium});const socialSource=source!==null&&(SOCIAL_SOURCES.has(source)||isSocialHost(source))||!!(external&&isSocialHost(external));const paidMedium=medium!==null&&PAID_MEDIUMS.has(medium);const searchClick=t.gclid||t.gbraid||t.wbraid||t.msclkid||t.paidClick==="google"||t.paidClick==="microsoft";const metaClick=t.fbclid||t.paidClick==="meta";if(searchClick||paidMedium){return result(socialSource||metaClick&&paidMedium?"paid_social":"paid_search")}if(medium==="email"||EMAIL_RE.test(source??"")||EMAIL_RE.test(medium??"")){return result("email")}const ai=aiLabel(external,source);if(ai)return result("ai_assistant",ai);if(external&&isSearchHost(external))return result("organic_search");if(socialSource||metaClick)return result("organic_social");const anyUtm=[source,medium,t.utmCampaign,t.utmTerm,t.utmContent].some(v=>clean(v??null));if(!external&&!anyUtm)return result("direct");return result("referral")}var consentStateSchema=zod.z.object({analytics:zod.z.boolean(),ads:zod.z.boolean(),source:zod.z.enum(["default","user"]),region:zod.z.enum(["restricted","other"]),decidedAt:zod.z.iso.datetime().max(40).nullable()});function isSafePrivacyUrl(value){if([...value].some(ch=>/\s/.test(ch)||ch.charCodeAt(0)<32))return false;if(value.startsWith("/"))return !value.startsWith("//")&&!value.startsWith("/\\");if(!value.startsWith("https://")||!URL.canParse(value))return false;const url=new URL(value);return url.hostname!==""&&url.username===""&&url.password===""}var STOREFRONT_CONSENT_MODES=["regional","strict"];var modeField=zod.z.enum(STOREFRONT_CONSENT_MODES);var privacyPolicyUrlField=zod.z.string().trim().max(2048,"validation.storefront.privacy_policy_url_invalid").refine(isSafePrivacyUrl,"validation.storefront.privacy_policy_url_invalid").nullable();zod.z.object({mode:modeField.default("regional"),privacyPolicyUrl:privacyPolicyUrlField.default(null)});zod.z.object({siteId:zod.z.uuid(),consentSettings:zod.z.object({mode:modeField.optional(),privacyPolicyUrl:privacyPolicyUrlField.optional()})});var ACTIVE_RESERVATION_STATUSES=["confirmed","reserved","awaiting_payment"];new Set(ACTIVE_RESERVATION_STATUSES);var SCHEDULABLE_RESERVATION_STATUSES=[...ACTIVE_RESERVATION_STATUSES,"blocked"];new Set(SCHEDULABLE_RESERVATION_STATUSES);var VOLATILE_SYNC_STATUSES=["pending","pending_deletion","failed_deletion"];new Set(VOLATILE_SYNC_STATUSES);var CURRENCIES=["usd","eur","aud","gbp","cad","chf","cny","jpy","nzd","nok","mxn","thb","bgn","aed","inr","rub","brl","zar","sgd","hkd","xcd","xof","clp","dkk","try","bnd","xcg","shp","fkp","idr","ron","czk"];var ZERO_DECIMAL_CURRENCY_CODES=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);new Set(CURRENCIES.filter(code=>ZERO_DECIMAL_CURRENCY_CODES.has(code)));var LIVE_PAYMENT_INTENT_STATUS_LIST=["succeeded","processing","requires_capture","refunded","disputed","reversed"];new Set(LIVE_PAYMENT_INTENT_STATUS_LIST);var BE_SITE_EXPERIMENT_VARIANTS=["a","b"];var ACTIVE_MIGRATION_RUN_STATUSES=["running","writing","finalizing","rolling_back"];new Set(ACTIVE_MIGRATION_RUN_STATUSES.filter(status=>status!=="rolling_back"));var experimentVariantSchema=zod.z.enum(BE_SITE_EXPERIMENT_VARIANTS);var experimentAssignmentSchema=zod.z.object({id:zod.z.uuid(),variant:experimentVariantSchema});zod.z.object({siteId:zod.z.uuid()});zod.z.object({siteId:zod.z.uuid(),deploymentBId:zod.z.uuid("validation.storefront.experiment_variant_required"),splitBPercent:zod.z.number("validation.storefront.experiment_split_range").int("validation.storefront.experiment_split_range").min(1,"validation.storefront.experiment_split_range").max(99,"validation.storefront.experiment_split_range")});zod.z.object({id:zod.z.uuid(),winner:experimentVariantSchema.nullable()});zod.z.object({id:zod.z.uuid()});var clickId=zod.z.string().min(1).max(512).regex(/^[\w.\-~]+$/);var storable=value=>!value.includes("\0")&&!/\p{Surrogate}/u.test(value);var utm=zod.z.string().max(150).refine(storable).nullable();var attributionTouchSchema=zod.z.object({ts:zod.z.iso.datetime().max(40),landingPath:zod.z.string().max(512).regex(/^\/[^?#]*$/).refine(storable),referrerHost:zod.z.string().max(253).regex(/^[a-z0-9.-]+$/).nullable(),utmSource:utm,utmMedium:utm,utmCampaign:utm,utmTerm:utm,utmContent:utm,gclid:clickId.nullable(),gbraid:clickId.nullable(),wbraid:clickId.nullable(),fbclid:clickId.nullable(),msclkid:clickId.nullable(),paidClick:zod.z.enum(PAID_CLICKS).nullable().default(null)});var attributionIdsSchema=zod.z.object({gaClientId:zod.z.string().max(64).regex(/^\d+\.\d+$/).nullable(),gaSessionId:zod.z.string().max(32).regex(/^\d+$/).nullable(),fbp:zod.z.string().max(128).regex(/^fb\.\d\.\d+\.\d+$/).nullable(),fbc:zod.z.string().max(600).regex(/^fb\.\d\.\d+\.[\w-]+$/).nullable()});var storefrontAttributionInputSchema=zod.z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable(),ids:attributionIdsSchema,consent:consentStateSchema,experiment:experimentAssignmentSchema.optional()});var STORED_ATTRIBUTION_CHANNELS=[...STOREFRONT_CHANNELS,"ai_agent_mcp"];storefrontAttributionInputSchema.extend({firstChannel:zod.z.enum(STORED_ATTRIBUTION_CHANNELS).nullable(),lastChannel:zod.z.enum(STORED_ATTRIBUTION_CHANNELS),userAgent:zod.z.string().max(512).nullable(),capturedAt:zod.z.iso.datetime()});function withoutClickIds(touch){return {...touch,gclid:null,gbraid:null,wbraid:null,fbclid:null,msclkid:null,paidClick:paidClickOf(touch)}}var emailField=zod.z.string().trim().toLowerCase().pipe(zod.z.email("validation.email_invalid"));zod.z.string().trim().min(1,"validation.email_required").pipe(emailField);var trimmedEmailField=zod.z.string().trim().pipe(zod.z.email("validation.email_invalid"));var requiredTrimmedEmailField=zod.z.string().trim().min(1,"validation.email_required").pipe(trimmedEmailField);zod.z.string().nullish().transform((raw,ctx)=>{if(raw===void 0)return void 0;const trimmed=(raw??"").trim().toLowerCase();if(!trimmed)return null;if(!zod.z.email().safeParse(trimmed).success){ctx.addIssue({code:"custom",message:"validation.email_invalid"});return zod.z.NEVER}return trimmed});var amountMinor=zod.z.number().int().positive();var currency=zod.z.string().length(3);var chargedByHost=zod.z.literal("host");var checkoutMountDescriptorKnownSchema=zod.z.discriminatedUnion("provider",[zod.z.object({provider:zod.z.literal("stripe"),publishableKey:zod.z.string().min(1),stripeAccountId:zod.z.string().nullable(),clientSecret:zod.z.string().min(1),amountMinor,currency}),zod.z.object({provider:zod.z.literal("juspay"),publishableKey:zod.z.string().min(1),providerBaseUrl:zod.z.url(),clientSecret:zod.z.string().min(1),profileId:zod.z.string().min(1),amountMinor,currency}),zod.z.object({provider:zod.z.literal("guesty_pay"),guestyPartnerId:zod.z.string().min(1),paymentProviderId:zod.z.string().min(1),externalListingId:zod.z.string().min(1),pmsQuoteId:zod.z.string().nullable(),amountMinor,currency,chargedBy:chargedByHost.optional()}),zod.z.object({provider:zod.z.literal("pms_stripe"),publishableKey:zod.z.string().min(1),stripeAccountId:zod.z.string().min(1),clientSecret:zod.z.string().min(1),amountMinor,currency,chargedBy:chargedByHost})]);var KNOWN_MOUNT_PROVIDERS=["stripe","juspay","guesty_pay","pms_stripe"];var checkoutMountDescriptorSchema=zod.z.union([checkoutMountDescriptorKnownSchema,zod.z.object({provider:zod.z.string().refine(p=>!KNOWN_MOUNT_PROVIDERS.includes(p))}).loose()]);zod.z.enum(chunkAIQUVZEI_cjs.BE_BOOKING_REQUEST_STATUSES);var bookingRequestStatusResponseSchema=chunkLVFRVNT3_cjs.openEnum(chunkAIQUVZEI_cjs.BE_BOOKING_REQUEST_STATUSES);var checkoutSessionQuoteSchema=zod.z.object({listingId:zod.z.uuid(),checkIn:zod.z.iso.date(),checkOut:zod.z.iso.date(),guests:zod.z.number().int().positive(),ratePlanId:zod.z.string(),totalMinor:zod.z.number().int(),currency:zod.z.string().length(3)});zod.z.object({quoteRef:zod.z.string().min(1).max(4096),ratePlanId:zod.z.string().min(1).max(200).optional(),attribution:zod.z.custom().optional()});var checkoutSessionSchema=zod.z.object({id:zod.z.uuid(),status:bookingRequestStatusResponseSchema,quote:checkoutSessionQuoteSchema,mount:checkoutMountDescriptorSchema.nullable(),chargedBy:chargedByHost.optional(),guestSaved:zod.z.literal(true).optional(),expiresAt:zod.z.iso.datetime()});var storefrontGuestInputSchema=zod.z.object({firstName:zod.z.string().trim().min(1,"validation.first_name_required").max(100),lastName:zod.z.string().trim().min(1,"validation.last_name_required").max(100),email:requiredTrimmedEmailField,phone:zod.z.string().trim().min(1,"validation.phone_required").max(40)});var storefrontConsentsSchema=zod.z.object({emailMarketing:zod.z.boolean().default(false),smsMarketing:zod.z.boolean().default(false)}).default({emailMarketing:false,smsMarketing:false});var confirmCheckoutSessionInputSchema=zod.z.object({quoteRef:zod.z.string().min(1).max(4096),guest:storefrontGuestInputSchema,consents:storefrontConsentsSchema,paymentMethodId:zod.z.string().min(1).max(255).optional(),language:zod.z.string().max(35).optional().catch(void 0)});confirmCheckoutSessionInputSchema.pick({quoteRef:true,guest:true,consents:true,language:true});zod.z.object({saved:zod.z.boolean()});var bookingResultSchema=zod.z.object({bookingRequestId:zod.z.uuid(),confirmationToken:zod.z.string(),status:bookingRequestStatusResponseSchema,confirmationCode:zod.z.string().nullable()});var storefrontBookingSchema=zod.z.object({id:zod.z.uuid(),status:bookingRequestStatusResponseSchema,propertyId:zod.z.uuid().nullable(),checkIn:zod.z.iso.date().nullable(),checkOut:zod.z.iso.date().nullable(),guestCount:zod.z.number().int().nullable(),guestFirstName:zod.z.string().nullable(),totalMinor:zod.z.number().int().nullable(),currency:zod.z.string().nullable(),confirmationCode:zod.z.string().nullable()});zod.z.uuid();var storefrontSiteSchema=zod.z.object({id:zod.z.uuid(),name:zod.z.string(),slug:zod.z.string(),isActive:zod.z.boolean(),enableWebChat:zod.z.boolean(),mapEmbedHost:zod.z.string().nullable(),countryCode:zod.z.string().nullish()});var storefrontListingSummarySchema=zod.z.object({id:zod.z.uuid(),buildingId:zod.z.uuid(),sortOrder:zod.z.number().int(),name:zod.z.string(),coverImageUrl:zod.z.string().nullable(),city:zod.z.string().nullable(),state:zod.z.string().nullable(),bedroomCount:zod.z.number().int().nullable(),bathroomCount:zod.z.number().nullable(),maxGuests:zod.z.number().int().nullable(),averageRating:zod.z.number().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),bookable:zod.z.boolean()});var storefrontListingSchema=storefrontListingSummarySchema.extend({buildingSlug:zod.z.string(),buildingAddress:zod.z.unknown(),description:zod.z.string().nullable(),amenities:zod.z.array(zod.z.string()),pictures:zod.z.unknown(),rooms:zod.z.unknown(),houseRules:zod.z.string().nullable(),checkInTime:zod.z.string().nullable(),checkOutTime:zod.z.string().nullable(),beds:zod.z.number().nullable(),fromPriceMinor:zod.z.number().int().nonnegative().nullish(),currency:zod.z.string().nullish(),countryCode:zod.z.string().nullish()});zod.z.object({location:zod.z.string().trim().min(1).max(200).optional(),building:zod.z.uuid().optional(),limit:zod.z.coerce.number().int().min(1).max(100).default(50),offset:zod.z.coerce.number().int().min(0).max(1e4).default(0)});var storefrontBuildingSchema=zod.z.object({id:zod.z.uuid(),locationId:zod.z.uuid().nullable(),nameId:zod.z.uuid().nullable(),descriptionId:zod.z.uuid().nullable(),slug:zod.z.string(),imageId:zod.z.uuid().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),address:zod.z.unknown()});var storefrontLocationSchema=zod.z.object({id:zod.z.uuid(),type:zod.z.string(),parentId:zod.z.uuid().nullable(),nameId:zod.z.uuid().nullable(),slug:zod.z.string().nullable(),imageId:zod.z.uuid().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),address:zod.z.unknown(),sortOrder:zod.z.number().int()});var storefrontReviewSchema=zod.z.object({id:zod.z.uuid(),listingId:zod.z.uuid().nullable(),reviewedAt:zod.z.string().nullable(),rating:zod.z.number().nullable(),publicReview:zod.z.string(),source:zod.z.string().nullable()});zod.z.object({listingId:zod.z.uuid().optional(),limit:zod.z.coerce.number().int().min(1).max(100).default(20),offset:zod.z.coerce.number().int().min(0).max(1e4).default(0)});zod.z.object({name:zod.z.string().trim().min(1,"validation.name_required").max(200,"validation.name_max_length"),email:requiredTrimmedEmailField,subject:zod.z.string().trim().min(1,"validation.title_required").max(300,"validation.title_max_length"),message:zod.z.string().trim().min(10,"validation.message_min_length").max(1e4,"validation.message_max_length")});var storefrontContactResultSchema=zod.z.object({sent:zod.z.literal(true)});zod.z.enum(chunkAIQUVZEI_cjs.STOREFRONT_KEY_ENVIRONMENTS);var STOREFRONT_KEY_RE=new RegExp(`^pk_(${chunkAIQUVZEI_cjs.STOREFRONT_KEY_ENVIRONMENTS.join("|")})_(${chunkAIQUVZEI_cjs.REGIONS.join("|")})_[0-9A-Za-z]{24}$`);function parseStorefrontKey(token){const match=STOREFRONT_KEY_RE.exec(token);if(!match)return null;return {environment:match[1],region:match[2]}}var ORIGIN_HOST_RE=/^(?:[a-z0-9-]+\.)*[a-z0-9-]+$|^\[[0-9a-f:.]+\]$/;function parseUrl(value){try{return new URL(value)}catch{return null}}zod.z.string().refine(value=>{const url=parseUrl(value);if(!url)return false;return (url.protocol==="https:"||url.protocol==="http:")&&url.origin===value&&ORIGIN_HOST_RE.test(url.hostname)},"validation.storefront.origin_invalid");var CLIENT_CONVERSION_EVENT_NAMES=["begin_checkout","generate_lead","sign_up"];var STOREFRONT_EVENT_PATH_MAX=512;var base={eventId:zod.z.uuid(),ts:zod.z.number().int(),path:zod.z.string().max(STOREFRONT_EVENT_PATH_MAX),referrerHost:zod.z.string().max(253).nullable()};var currency2=zod.z.string().length(3).regex(/^[a-z]{3}$/);var storefrontClientEventSchema=zod.z.discriminatedUnion("name",[zod.z.object({...base,name:zod.z.literal("page_view")}),zod.z.object({...base,name:zod.z.literal("view_search_results"),checkIn:chunkLVFRVNT3_cjs.storefrontDateSchema.optional(),checkOut:chunkLVFRVNT3_cjs.storefrontDateSchema.optional(),guests:zod.z.number().int().min(1).max(50).optional(),locationId:zod.z.uuid().optional()}),zod.z.object({...base,name:zod.z.literal("view_item_list"),listName:zod.z.string().max(64),itemCount:zod.z.number().int().min(0).max(500)}),zod.z.object({...base,name:zod.z.literal("view_item"),listingId:zod.z.uuid()}),zod.z.object({...base,name:zod.z.literal("view_quote"),listingId:zod.z.uuid(),valueMinor:zod.z.number().int().nonnegative(),currency:currency2,nights:zod.z.number().int().min(1).max(365)}),zod.z.object({...base,name:zod.z.literal("begin_checkout"),checkoutSessionId:zod.z.uuid()}),zod.z.object({...base,name:zod.z.literal("add_payment_info"),checkoutSessionId:zod.z.uuid()}),zod.z.object({...base,name:zod.z.literal("generate_lead"),formId:zod.z.string().max(64).optional()}),zod.z.object({...base,name:zod.z.literal("sign_up"),method:zod.z.literal("newsletter")})]);var STOREFRONT_EVENT_BATCH_MAX=20;zod.z.object({events:zod.z.array(storefrontClientEventSchema).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});zod.z.object({events:zod.z.array(zod.z.object({eventId:zod.z.uuid(),name:zod.z.enum(CLIENT_CONVERSION_EVENT_NAMES),occurredAt:zod.z.iso.datetime(),pageUrl:zod.z.url({protocol:/^https?$/}).max(2048),checkoutSessionId:zod.z.uuid().nullable(),userAgent:zod.z.string().max(512).nullable(),attribution:storefrontAttributionInputSchema.nullable()})).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});var EXPERIMENT_COOKIE="__so_exp";var COOKIE_RE=/(?:^|;\s*)__so_exp=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(a|b)(?:\s*;|\s*$)/;function readExperimentCookie(cookies){const match=COOKIE_RE.exec(cookies??"");return match?{id:match[1],variant:match[2]}:null}var ATTRIBUTION_COOKIE="so_attr";var ATTRIBUTION_COOKIE_MAX_AGE_SECONDS=90*24*60*60;var COOKIE_SCOPE="Path=/; SameSite=Lax; Secure";var ATTRIBUTION_COOKIE_ATTRIBUTES=`Max-Age=${ATTRIBUTION_COOKIE_MAX_AGE_SECONDS}; ${COOKIE_SCOPE}`;var ATTRIBUTION_COOKIE_MAX_BYTES=3584;var attributionCookieSchema=zod.z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable()});function toBase64Url(text){let binary="";for(const byte of new TextEncoder().encode(text))binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64Url(value){const binary=atob(value.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(binary,ch=>ch.charCodeAt(0)))}function encodeAttributionCookie(value){const encoded=toBase64Url(JSON.stringify(value));return encoded.length>ATTRIBUTION_COOKIE_MAX_BYTES?null:encoded}function serializeAttributionCookie(value){const encoded=encodeAttributionCookie(value);return encoded===null?null:`${ATTRIBUTION_COOKIE}=${encoded}; ${ATTRIBUTION_COOKIE_ATTRIBUTES}`}function decodeAttributionCookie(value){if(!value)return null;return attributionCookieSchema.parse(JSON.parse(fromBase64Url(value)))}function expiredAttributionCookies(cookies,consent){const revoked=[...consent.analytics?[]:[ATTRIBUTION_COOKIE,EXPERIMENT_COOKIE],...consent.ads?[]:["_fbc","_fbp"]];return revoked.filter(name=>readCookie(cookies,name)!==null).map(name=>`${name}=; Max-Age=0; ${COOKIE_SCOPE}`)}function strippedAttributionCookie(held){const clicked=t=>t!==null&&[t.gclid,t.gbraid,t.wbraid,t.fbclid,t.msclkid].some(id=>id!==null);if(!held||!(clicked(held.first)||clicked(held.last)))return null;return serializeAttributionCookie({first:held.first&&withoutClickIds(held.first),last:held.last&&withoutClickIds(held.last)})??`${ATTRIBUTION_COOKIE}=; Max-Age=0; ${COOKIE_SCOPE}`}function readCookie(header,name){if(!header)return null;for(const part of header.split(";")){const eq=part.indexOf("=");if(eq!==-1&&part.slice(0,eq).trim()===name)return part.slice(eq+1).trim()}return null}var MalformedCookieError=class extends Error{constructor(name){super(`${name} is malformed`);this.name="MalformedAttributionError";}};var NO_IDS={gaClientId:null,gaSessionId:null,fbp:null,fbc:null};function matchCookie(cookies,name,re,report){const value=name?readCookie(cookies,name):null;if(!value)return null;const match=re.exec(value);if(!match){report(new MalformedCookieError(name),name);return null}return match.slice(1).filter(Boolean).join(".")}function browserIdsFromCookies(cookies,consent,report){const sessionCookie=cookies.split(";").map(part=>part.split("=")[0].trim()).find(name=>name.startsWith("_ga_"))??null;const ga=consent.analytics;const ads=consent.ads;const ids={gaClientId:ga?matchCookie(cookies,"_ga",/^GA\d\.\d+\.(\d+)\.(\d+)$/,report):null,gaSessionId:ga?matchCookie(cookies,sessionCookie,/^(?:GS1\.\d+\.(\d+)\.|GS2\.\d+\.s(\d+)(?:\$|$))/,report):null,fbp:ads?matchCookie(cookies,"_fbp",/^(fb\.\d\.\d+\.\d+)$/,report):null,fbc:ads?matchCookie(cookies,"_fbc",/^(fb\.\d\.\d+\.[\w-]+)$/,report):null};const parsed=attributionIdsSchema.safeParse(ids);if(parsed.success)return parsed.data;report(parsed.error,"ids");return NO_IDS}var isDirect=touch=>classifyChannel({...touch,siteHost:globalThis.location?.hostname??""}).channel==="direct";var TOUCH_ELEMENT_ID="__suiteop_touch";var CONSENT_EVENT="suiteop:consent";var DENIED={analytics:false,ads:false,source:"default",region:"restricted",decidedAt:null};var defaultReport=(err,where)=>{console.warn(`[suiteop] ignored malformed attribution input (${where})`,err);};function pageConsent(){const read=globalThis.__suiteop?.consent?.get;const parsed=consentStateSchema.safeParse(typeof read==="function"?read():null);return parsed.success?parsed.data:DENIED}function pageTouch(report){const text=document.getElementById(TOUCH_ELEMENT_ID)?.textContent;if(!text)return null;try{return attributionTouchSchema.parse(JSON.parse(text))}catch(err){report(err,TOUCH_ELEMENT_ID);return null}}function storedCookie(cookies,report){try{return decodeAttributionCookie(readCookie(cookies,ATTRIBUTION_COOKIE))}catch(err){report(err,ATTRIBUTION_COOKIE);return null}}function getAttribution(opts={}){if(typeof document==="undefined")return null;const report=opts.report??defaultReport;const cookies=document.cookie;const consent=pageConsent();const stored=consent.analytics?storedCookie(cookies,report):null;const touch=pageTouch(report);const pageIsLast=touch!==null&&!(stored?.last&&(isDirect(touch)||Date.parse(stored.last.ts)>Date.parse(touch.ts)));const experiment=consent.analytics?readExperimentCookie(cookies):null;return {first:stored?.first??touch,last:pageIsLast?touch:stored?.last??null,ids:browserIdsFromCookies(cookies,consent,report),consent,...experiment?{experiment}:{}}}function watchAttributionConsent(opts={}){if(typeof window==="undefined")return ()=>{};const report=opts.report??defaultReport;const persist=consent=>{if(readCookie(document.cookie,ATTRIBUTION_COOKIE))return;const touch=pageTouch(report);if(!touch)return;const kept=consent.ads?touch:withoutClickIds(touch);const cookie=serializeAttributionCookie({first:kept,last:kept});if(cookie)document.cookie=cookie;};const withdraw=consent=>{for(const cookie of expiredAttributionCookies(document.cookie,consent)){document.cookie=cookie;}if(consent.analytics&&!consent.ads){const stripped=strippedAttributionCookie(storedCookie(document.cookie,report));if(stripped)document.cookie=stripped;}};const initial=pageConsent();let analytics=initial.analytics;if(initial.source==="user")withdraw(initial);if(analytics)persist(initial);const onConsent=event=>{const next=consentStateSchema.safeParse(event.detail);if(!next.success)return;const granted=!analytics&&next.data.analytics;analytics=next.data.analytics;withdraw(next.data);if(granted)persist(next.data);};window.addEventListener(CONSENT_EVENT,onConsent);return ()=>window.removeEventListener(CONSENT_EVENT,onConsent)}var EVENTS_ENDPOINT="/_suiteop/events";var FLUSH_INTERVAL_MS=2e3;var FLUSH_AT_EVENTS=10;var defaultReport2=err=>{console.warn("[suiteop] storefront events could not be sent",err);};function hostOf2(url){try{return new URL(url).hostname||null}catch{return null}}var META_EVENTS={begin_checkout:"InitiateCheckout",generate_lead:"Lead",sign_up:"CompleteRegistration",view_item:"ViewContent",view_search_results:"Search",add_payment_info:"AddPaymentInfo"};var GTAG_SKIP=new Set(["page_view","purchase"]);function mirrorToTags(event){const w=window;if(typeof w.gtag!=="function"&&typeof w.fbq!=="function")return;const consent=pageConsent();const{name,eventId,ts:_ts,path:_path,referrerHost:_ref,...params}=event;if(consent.analytics&&typeof w.gtag==="function"&&!GTAG_SKIP.has(name)){w.gtag("event",name,params);}const metaName=META_EVENTS[name];if(consent.ads&&typeof w.fbq==="function"&&metaName){w.fbq("track",metaName,{},{eventID:eventId});}}function trackPurchasePixel(booking){if(typeof window==="undefined")return;const fbq=window.fbq;if(typeof fbq!=="function"||!pageConsent().ads)return;const amount=typeof booking.totalMinor==="number"&&booking.currency?{value:booking.totalMinor/100,currency:booking.currency.toUpperCase()}:{};fbq("track","Purchase",amount,{eventID:booking.bookingRequestId});}var NOOP={track(){},pageView(){},flush(){},dispose(){}};function createAnalytics(opts){if(typeof window==="undefined")return NOOP;const report=opts.report??defaultReport2;const url=`${EVENTS_ENDPOINT}?key=${encodeURIComponent(opts.publishableKey)}`;let queue=[];let timer=null;let landing=true;let lastViewedHref=null;let disabled=false;let reported=false;const fail=err=>{if(reported)return;reported=true;report(err);};const send=(events,beacon)=>{const body=JSON.stringify({events});if(beacon&&typeof navigator.sendBeacon==="function"&&navigator.sendBeacon(url,body)){return}fetch(url,{method:"POST",body,keepalive:true,credentials:"same-origin",headers:{"content-type":"application/json"}}).then(response=>{if(response.status===404)disabled=true;else if(!response.ok)fail(new Error(`storefront events answered ${response.status}`));}).catch(fail);};const flush=({beacon=false}={})=>{if(timer)clearTimeout(timer);timer=null;if(disabled||queue.length===0)return;const pending=queue;queue=[];for(let i=0;i<pending.length;i+=STOREFRONT_EVENT_BATCH_MAX){send(pending.slice(i,i+STOREFRONT_EVENT_BATCH_MAX),beacon);}};const enqueue=(event,referrerHost)=>{const full={...event,eventId:crypto.randomUUID(),ts:Date.now(),path:location.pathname.slice(0,STOREFRONT_EVENT_PATH_MAX),referrerHost};try{mirrorToTags(full);}catch(err){fail(err);}if(disabled)return;queue.push(full);if(queue.length>=FLUSH_AT_EVENTS)flush();else timer??=setTimeout(()=>flush(),FLUSH_INTERVAL_MS);};const pageView=()=>{if(location.href===lastViewedHref)return;lastViewedHref=location.href;const referrerHost=landing?hostOf2(document.referrer):location.hostname;landing=false;enqueue({name:"page_view"},referrerHost);};const onPageHide=()=>flush({beacon:true});const onPageShow=event=>{if(!event.persisted)return;lastViewedHref=null;pageView();};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);return {track:event=>enqueue(event,location.hostname),pageView,flush,dispose:()=>{flush({beacon:true});window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);}}}var shared=new Map;function analyticsFor(publishableKey){let instance=shared.get(publishableKey);if(!instance){instance=createAnalytics({publishableKey});if(instance!==NOOP)shared.set(publishableKey,instance);}return instance}function parsePublishableKey(key){if(typeof key==="string"&&key.trim().startsWith("sk_")){throw new chunkXIAAWHAY_cjs.StorefrontConfigError("A SuiteOp secret key (sk_\u2026) was passed as the publishable key. Secret keys must never be used in a browser or shipped in site code \u2014 revoke it now, then use a publishable key (pk_live_\u2026 / pk_test_\u2026) from the site settings.")}const parsed=typeof key==="string"?parseStorefrontKey(key.trim()):null;if(!parsed){throw new chunkXIAAWHAY_cjs.StorefrontConfigError("Invalid SuiteOp publishable key: expected pk_{live|test}_{us|eu|apac}_ followed by 24 letters or digits.")}return parsed}function defaultApiOrigin({environment,region}){return environment==="live"?`https://api-${region}.suiteop.com`:`https://api-${region}-staging.suiteop.com`}var SDK_VERSION="0.1.1";var STOREFRONT_API_VERSION="2026-09-27";var GET_RETRY_JITTER_MS=300;function buildUrl(base2,spec){const params=new URLSearchParams;for(const[key,value]of Object.entries(spec.query??{})){if(value!==void 0&&value!==null)params.set(key,String(value));}const search=params.toString();return `${base2}${spec.path}${search?`?${search}`:""}`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason);const onAbort=()=>{clearTimeout(timer);reject(signal?.reason);};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve();},ms);signal?.addEventListener("abort",onAbort,{once:true});})}function parseJson(text){if(!text)return void 0;try{return JSON.parse(text)}catch{return void 0}}function isRetryable(err){return err instanceof chunkXIAAWHAY_cjs.StorefrontNetworkError||err instanceof chunkXIAAWHAY_cjs.StorefrontError&&err.status>=500}function createTransport(opts){async function attempt(spec){const controller=new AbortController;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;controller.abort(new DOMException("The request timed out","TimeoutError"));},spec.timeoutMs);const onCallerAbort=()=>controller.abort(spec.signal?.reason);if(spec.signal?.aborted)onCallerAbort();else spec.signal?.addEventListener("abort",onCallerAbort,{once:true});try{let response;let text;try{response=await opts.fetch(buildUrl(opts.baseUrl(),spec),{method:spec.method,headers:{...opts.headers,...spec.body===void 0?{}:{"Content-Type":"application/json"},...spec.headers},body:spec.body===void 0?void 0:JSON.stringify(spec.body),signal:controller.signal});text=await response.text();}catch(err){if(spec.signal?.aborted)throw spec.signal.reason;if(timedOut)throw new chunkXIAAWHAY_cjs.StorefrontTimeoutError(spec.timeoutMs);throw new chunkXIAAWHAY_cjs.StorefrontNetworkError(err)}const body=parseJson(text);if(!response.ok)throw chunkXIAAWHAY_cjs.errorFromResponse(response,body);const envelope=body;const meta=envelope?.meta??{};const requestId=typeof meta["requestId"]==="string"?meta["requestId"]:response.headers.get("x-request-id");if(!envelope||typeof envelope!=="object"||!("data"in envelope)){throw new chunkXIAAWHAY_cjs.StorefrontError({status:response.status,code:"invalid_response",message:"The Storefront API answered without a data envelope",requestId})}return {status:response.status,requestId,data:envelope.data,meta}}finally{clearTimeout(timer);spec.signal?.removeEventListener("abort",onCallerAbort);}}return {async send(spec){try{return await attempt(spec)}catch(err){if(spec.method!=="GET"||!isRetryable(err))throw err;await sleep(Math.random()*GET_RETRY_JITTER_MS,spec.signal);return attempt(spec)}}}}var STOREFRONT_API_PATH="/api/storefront/v1";var READ_TIMEOUT_MS=1e4;var WRITE_TIMEOUT_MS=2e4;function resolveBaseUrl(baseUrl,origin){if(baseUrl===void 0)return `${origin}${STOREFRONT_API_PATH}`;if(baseUrl==="same-origin"){const pageOrigin=globalThis.location?.origin;if(!pageOrigin||pageOrigin==="null"){throw new chunkXIAAWHAY_cjs.StorefrontConfigError("baseUrl 'same-origin' needs a page origin; pass an explicit baseUrl outside a browser.")}return `${pageOrigin}${STOREFRONT_API_PATH}`}let url;try{url=new URL(baseUrl);}catch{throw new chunkXIAAWHAY_cjs.StorefrontConfigError(`baseUrl must be an absolute URL or 'same-origin'.`)}const path=url.pathname.replace(/\/+$/,"");return `${url.origin}${path.endsWith(STOREFRONT_API_PATH)?path:`${path}${STOREFRONT_API_PATH}`}`}function uuidV4(){const c=globalThis.crypto;if(typeof c.randomUUID==="function")return c.randomUUID();const b=c.getRandomValues(new Uint8Array(16));b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=Array.from(b,x=>x.toString(16).padStart(2,"0")).join("");return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function validate(schema,value,res){const parsed=schema.safeParse(value);if(parsed.success)return parsed.data;throw new chunkXIAAWHAY_cjs.StorefrontError({status:res.status,code:"invalid_response",message:"The Storefront API answered a shape this SDK version does not understand",requestId:res.requestId,details:{issues:parsed.error.issues.map(i=>({path:i.path,code:i.code}))}})}var paginationSchema=zod.z.object({total:zod.z.number().int(),limit:zod.z.number().int(),offset:zod.z.number().int()});var seg=value=>encodeURIComponent(value);var slotOf=(quoteRef,ratePlanId)=>`${quoteRef}\0${ratePlanId??""}`;var RELEASED_SESSION_STATUSES=new Set(["expired","cancelled"]);var KEY_BOUND_ELSEWHERE="idempotency_key_reused";function endsSession(err){return err.code==="session_expired"||err.details["requiresNewSession"]===true}var attributionWatched=false;function createStorefrontClient(options){const key=parsePublishableKey(options.publishableKey);const baseUrl=resolveBaseUrl(options.baseUrl,defaultApiOrigin(key));const transport=createTransport({baseUrl:()=>baseUrl,fetch:(input,init)=>(options.fetch??globalThis.fetch)(input,init),headers:{Authorization:`Bearer ${options.publishableKey.trim()}`,Accept:"application/json","X-SuiteOp-SDK":`storefront-js/${SDK_VERSION}`,"X-SuiteOp-Api-Version":STOREFRONT_API_VERSION,...options.locale?{"Accept-Language":options.locale}:{}}});const keySlots=new Map;const sessionSlots=new Map;const release=(slot,key2)=>{if(keySlots.get(slot)===key2)keySlots.delete(slot);};const releaseSession=id=>{const entry=sessionSlots.get(id);if(!entry)return;sessionSlots.delete(id);release(...entry);};if(!attributionWatched&&typeof window!=="undefined"){attributionWatched=true;watchAttributionConsent();}const readTimeoutMs=options.timeoutMs??READ_TIMEOUT_MS;const writeTimeoutMs=options.timeoutMs??WRITE_TIMEOUT_MS;async function get(schema,path,opts,query){const res=await transport.send({method:"GET",path,query,timeoutMs:readTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}async function post(schema,path,body,opts,headers){const res=await transport.send({method:"POST",path,body,headers,timeoutMs:writeTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}return {publishableKey:options.publishableKey.trim(),baseUrl,site:{get:opts=>get(storefrontSiteSchema,"/site",opts)},listings:{async list(query,opts){const res=await transport.send({method:"GET",path:"/listings",query:{location:query?.location,building:query?.building,limit:query?.limit,offset:query?.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(zod.z.array(storefrontListingSummarySchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);return {items,...pagination}},get:(id,opts)=>get(storefrontListingSchema,`/listings/${seg(id)}`,opts)},buildings:{list:opts=>get(zod.z.array(storefrontBuildingSchema),"/buildings",opts),get:(id,opts)=>get(storefrontBuildingSchema,`/buildings/${seg(id)}`,opts)},locations:{list:opts=>get(zod.z.array(storefrontLocationSchema),"/locations",opts)},amenities:{list:opts=>get(zod.z.array(zod.z.string()),"/amenities",opts)},reviews:{list:(query,opts)=>get(zod.z.array(storefrontReviewSchema),"/reviews",opts,{listingId:query?.listingId,limit:query?.limit,offset:query?.offset})},availability:{get:(listingId,stay,opts)=>get(chunkLVFRVNT3_cjs.storefrontAvailabilitySchema,`/listings/${seg(listingId)}/availability`,opts,{checkIn:stay.checkIn,checkOut:stay.checkOut,guests:stay.guests})},calendar:{get:(listingId,range,opts)=>get(chunkLVFRVNT3_cjs.storefrontCalendarSchema,`/listings/${seg(listingId)}/calendar`,opts,{from:range.from,to:range.to})},quotes:{create:(input,opts)=>post(chunkXIAAWHAY_cjs.storefrontQuoteSchema,"/quotes",input,opts)},checkoutSessions:{async create(input,opts){const slot=slotOf(input.quoteRef,input.ratePlanId);const idempotencyKey=opts?.idempotencyKey??keySlots.get(slot)??uuidV4();keySlots.set(slot,idempotencyKey);const attribution=input.attribution===void 0?getAttribution():input.attribution;const body=attribution?{...input,attribution}:input;try{const created=await post(checkoutSessionSchema,"/checkout-sessions",body,opts,{"Idempotency-Key":idempotencyKey});if(RELEASED_SESSION_STATUSES.has(created.status))release(slot,idempotencyKey);else sessionSlots.set(created.id,[slot,idempotencyKey]);return {...created,idempotencyKey}}catch(err){if(err instanceof chunkXIAAWHAY_cjs.StorefrontError){err.details["idempotencyKey"]=idempotencyKey;if(err.code===KEY_BOUND_ELSEWHERE)release(slot,idempotencyKey);}throw err}},get:(id,opts)=>get(checkoutSessionSchema,`/checkout-sessions/${seg(id)}`,opts),async confirm(id,input,opts){try{const result=await post(bookingResultSchema,`/checkout-sessions/${seg(id)}/confirm`,input,opts);return result}catch(err){if(err instanceof chunkXIAAWHAY_cjs.StorefrontError&&endsSession(err)){releaseSession(id);}throw err}},forget(quoteRef,ratePlanId){keySlots.delete(slotOf(quoteRef,ratePlanId));}},bookings:{get:(token,opts)=>get(storefrontBookingSchema,`/bookings/${seg(token)}`,opts)},contact:{async create(input,opts){await post(storefrontContactResultSchema,"/contact",input,opts);}}}}
9
+
10
+ exports.SDK_VERSION = SDK_VERSION;
11
+ exports.STOREFRONT_API_PATH = STOREFRONT_API_PATH;
12
+ exports.STOREFRONT_API_VERSION = STOREFRONT_API_VERSION;
13
+ exports.analyticsFor = analyticsFor;
14
+ exports.createAnalytics = createAnalytics;
15
+ exports.createStorefrontClient = createStorefrontClient;
16
+ exports.getAttribution = getAttribution;
17
+ exports.parsePublishableKey = parsePublishableKey;
18
+ exports.trackPurchasePixel = trackPurchasePixel;
@@ -1,8 +1,8 @@
1
- import { StorefrontConfigError, StorefrontError, storefrontQuoteSchema, StorefrontTimeoutError, StorefrontNetworkError, errorFromResponse } from './chunk-NNZZWGM2.js';
1
+ import { StorefrontConfigError, StorefrontError, storefrontQuoteSchema, StorefrontTimeoutError, StorefrontNetworkError, errorFromResponse } from './chunk-UACP7BZ7.js';
2
2
  import { openEnum, storefrontDateSchema, storefrontCalendarSchema, storefrontAvailabilitySchema } from './chunk-6NFURJXI.js';
3
3
  import { BE_BOOKING_REQUEST_STATUSES, STOREFRONT_KEY_ENVIRONMENTS, REGIONS } from './chunk-SK5TD73J.js';
4
4
  import { z } from 'zod';
5
5
 
6
- var STOREFRONT_CHANNELS=["ai_assistant","paid_search","paid_social","organic_search","organic_social","email","referral","direct"];var AI_ASSISTANT_HOSTS={"chatgpt.com":"chatgpt","chat.openai.com":"chatgpt","perplexity.ai":"perplexity","gemini.google.com":"gemini","copilot.microsoft.com":"copilot","claude.ai":"claude"};var AI_ASSISTANT_SOURCES={"chatgpt.com":"chatgpt",perplexity:"perplexity","perplexity.ai":"perplexity",gemini:"gemini",copilot:"copilot","claude.ai":"claude"};var PAID_CLICKS=["google","microsoft","meta"];var PAID_MEDIUMS=new Set(["cpc","ppc","paid","paidsearch","sem"]);var EMAIL_RE=/newsletter|mailchimp|klaviyo/;var SEARCH_SUFFIXES=["bing.com","duckduckgo.com","search.yahoo.com","baidu.com","ecosia.org","search.brave.com"];var SEARCH_ANY_TLD_RE=/^(?:www\.)?(?:google|yandex)\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SUFFIXES=["facebook.com","instagram.com","t.co","x.com","twitter.com","linkedin.com","tiktok.com","youtube.com","reddit.com"];var SOCIAL_ANY_TLD_RE=/(?:^|\.)pinterest\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SOURCES=new Set(["facebook","fb","instagram","ig","meta","twitter","x","linkedin","pinterest","tiktok","youtube","reddit"]);var clean=value=>{const v=value?.trim().toLowerCase();return v?v:null};var hostOf=value=>clean(value)?.replace(/\.$/,"")??null;var hostMatches=(host,suffix)=>host===suffix||host.endsWith(`.${suffix}`);var bareHost=host=>host.replace(/^www\./,"");function aiLabel(host,source){if(host){const suffix=Object.keys(AI_ASSISTANT_HOSTS).find(s=>hostMatches(host,s));if(suffix)return AI_ASSISTANT_HOSTS[suffix]}return source&&Object.hasOwn(AI_ASSISTANT_SOURCES,source)?AI_ASSISTANT_SOURCES[source]:null}var isSearchHost=host=>SEARCH_ANY_TLD_RE.test(host)||SEARCH_SUFFIXES.some(s=>hostMatches(host,s));var isSocialHost=host=>SOCIAL_ANY_TLD_RE.test(host)||SOCIAL_SUFFIXES.some(s=>hostMatches(host,s));function paidClickOf(t){const medium=clean(t.utmMedium);if(t.fbclid&&medium!==null&&PAID_MEDIUMS.has(medium))return "meta";if(t.gclid||t.gbraid||t.wbraid)return "google";if(t.msclkid)return "microsoft";if(t.fbclid)return "meta";return t.paidClick??null}function classifyChannel(t){const source=clean(t.utmSource);const medium=clean(t.utmMedium);const site=bareHost(hostOf(t.siteHost)??"");const ref=hostOf(t.referrerHost);const external=ref&&bareHost(ref)!==site?ref:null;const result=(channel,label=null)=>({channel,source:label??source??external,medium});const socialSource=source!==null&&(SOCIAL_SOURCES.has(source)||isSocialHost(source))||!!(external&&isSocialHost(external));const paidMedium=medium!==null&&PAID_MEDIUMS.has(medium);const searchClick=t.gclid||t.gbraid||t.wbraid||t.msclkid||t.paidClick==="google"||t.paidClick==="microsoft";const metaClick=t.fbclid||t.paidClick==="meta";if(searchClick||paidMedium){return result(socialSource||metaClick&&paidMedium?"paid_social":"paid_search")}if(medium==="email"||EMAIL_RE.test(source??"")||EMAIL_RE.test(medium??"")){return result("email")}const ai=aiLabel(external,source);if(ai)return result("ai_assistant",ai);if(external&&isSearchHost(external))return result("organic_search");if(socialSource||metaClick)return result("organic_social");const anyUtm=[source,medium,t.utmCampaign,t.utmTerm,t.utmContent].some(v=>clean(v??null));if(!external&&!anyUtm)return result("direct");return result("referral")}var consentStateSchema=z.object({analytics:z.boolean(),ads:z.boolean(),source:z.enum(["default","user"]),region:z.enum(["restricted","other"]),decidedAt:z.iso.datetime().max(40).nullable()});function isSafePrivacyUrl(value){if([...value].some(ch=>/\s/.test(ch)||ch.charCodeAt(0)<32))return false;if(value.startsWith("/"))return !value.startsWith("//")&&!value.startsWith("/\\");if(!value.startsWith("https://")||!URL.canParse(value))return false;const url=new URL(value);return url.hostname!==""&&url.username===""&&url.password===""}var STOREFRONT_CONSENT_MODES=["regional","strict"];var modeField=z.enum(STOREFRONT_CONSENT_MODES);var privacyPolicyUrlField=z.string().trim().max(2048,"validation.storefront.privacy_policy_url_invalid").refine(isSafePrivacyUrl,"validation.storefront.privacy_policy_url_invalid").nullable();z.object({mode:modeField.default("regional"),privacyPolicyUrl:privacyPolicyUrlField.default(null)});z.object({siteId:z.uuid(),consentSettings:z.object({mode:modeField.optional(),privacyPolicyUrl:privacyPolicyUrlField.optional()})});var clickId=z.string().min(1).max(512).regex(/^[\w.\-~]+$/);var storable=value=>!value.includes("\0")&&!/\p{Surrogate}/u.test(value);var utm=z.string().max(150).refine(storable).nullable();var attributionTouchSchema=z.object({ts:z.iso.datetime().max(40),landingPath:z.string().max(512).regex(/^\/[^?#]*$/).refine(storable),referrerHost:z.string().max(253).regex(/^[a-z0-9.-]+$/).nullable(),utmSource:utm,utmMedium:utm,utmCampaign:utm,utmTerm:utm,utmContent:utm,gclid:clickId.nullable(),gbraid:clickId.nullable(),wbraid:clickId.nullable(),fbclid:clickId.nullable(),msclkid:clickId.nullable(),paidClick:z.enum(PAID_CLICKS).nullable().default(null)});var attributionIdsSchema=z.object({gaClientId:z.string().max(64).regex(/^\d+\.\d+$/).nullable(),gaSessionId:z.string().max(32).regex(/^\d+$/).nullable(),fbp:z.string().max(128).regex(/^fb\.\d\.\d+\.\d+$/).nullable(),fbc:z.string().max(600).regex(/^fb\.\d\.\d+\.[\w-]+$/).nullable()});var storefrontAttributionInputSchema=z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable(),ids:attributionIdsSchema,consent:consentStateSchema});var STORED_ATTRIBUTION_CHANNELS=[...STOREFRONT_CHANNELS,"ai_agent_mcp"];storefrontAttributionInputSchema.extend({firstChannel:z.enum(STORED_ATTRIBUTION_CHANNELS).nullable(),lastChannel:z.enum(STORED_ATTRIBUTION_CHANNELS),userAgent:z.string().max(512).nullable(),capturedAt:z.iso.datetime()});function withoutClickIds(touch){return {...touch,gclid:null,gbraid:null,wbraid:null,fbclid:null,msclkid:null,paidClick:paidClickOf(touch)}}var emailField=z.string().trim().toLowerCase().pipe(z.email("validation.email_invalid"));z.string().trim().min(1,"validation.email_required").pipe(emailField);var trimmedEmailField=z.string().trim().pipe(z.email("validation.email_invalid"));var requiredTrimmedEmailField=z.string().trim().min(1,"validation.email_required").pipe(trimmedEmailField);z.string().nullish().transform((raw,ctx)=>{if(raw===void 0)return void 0;const trimmed=(raw??"").trim().toLowerCase();if(!trimmed)return null;if(!z.email().safeParse(trimmed).success){ctx.addIssue({code:"custom",message:"validation.email_invalid"});return z.NEVER}return trimmed});var amountMinor=z.number().int().positive();var currency=z.string().length(3);var chargedByHost=z.literal("host");var checkoutMountDescriptorKnownSchema=z.discriminatedUnion("provider",[z.object({provider:z.literal("stripe"),publishableKey:z.string().min(1),stripeAccountId:z.string().nullable(),clientSecret:z.string().min(1),amountMinor,currency}),z.object({provider:z.literal("juspay"),publishableKey:z.string().min(1),providerBaseUrl:z.url(),clientSecret:z.string().min(1),profileId:z.string().min(1),amountMinor,currency}),z.object({provider:z.literal("guesty_pay"),guestyPartnerId:z.string().min(1),paymentProviderId:z.string().min(1),externalListingId:z.string().min(1),pmsQuoteId:z.string().nullable(),amountMinor,currency,chargedBy:chargedByHost.optional()}),z.object({provider:z.literal("pms_stripe"),publishableKey:z.string().min(1),stripeAccountId:z.string().min(1),clientSecret:z.string().min(1),amountMinor,currency,chargedBy:chargedByHost})]);var KNOWN_MOUNT_PROVIDERS=["stripe","juspay","guesty_pay","pms_stripe"];var checkoutMountDescriptorSchema=z.union([checkoutMountDescriptorKnownSchema,z.object({provider:z.string().refine(p=>!KNOWN_MOUNT_PROVIDERS.includes(p))}).loose()]);z.enum(BE_BOOKING_REQUEST_STATUSES);var bookingRequestStatusResponseSchema=openEnum(BE_BOOKING_REQUEST_STATUSES);var checkoutSessionQuoteSchema=z.object({listingId:z.uuid(),checkIn:z.iso.date(),checkOut:z.iso.date(),guests:z.number().int().positive(),ratePlanId:z.string(),totalMinor:z.number().int(),currency:z.string().length(3)});z.object({quoteRef:z.string().min(1).max(4096),ratePlanId:z.string().min(1).max(200).optional(),attribution:z.custom().optional()});var checkoutSessionSchema=z.object({id:z.uuid(),status:bookingRequestStatusResponseSchema,quote:checkoutSessionQuoteSchema,mount:checkoutMountDescriptorSchema.nullable(),chargedBy:chargedByHost.optional(),expiresAt:z.iso.datetime()});var storefrontGuestInputSchema=z.object({firstName:z.string().trim().min(1,"validation.first_name_required").max(100),lastName:z.string().trim().min(1,"validation.last_name_required").max(100),email:requiredTrimmedEmailField,phone:z.string().trim().min(1,"validation.phone_required").max(40)});var storefrontConsentsSchema=z.object({emailMarketing:z.boolean().default(false),smsMarketing:z.boolean().default(false)}).default({emailMarketing:false,smsMarketing:false});z.object({quoteRef:z.string().min(1).max(4096),guest:storefrontGuestInputSchema,consents:storefrontConsentsSchema,paymentMethodId:z.string().min(1).max(255).optional(),language:z.string().max(35).optional().catch(void 0)});var bookingResultSchema=z.object({bookingRequestId:z.uuid(),confirmationToken:z.string(),status:bookingRequestStatusResponseSchema,confirmationCode:z.string().nullable()});var storefrontBookingSchema=z.object({id:z.uuid(),status:bookingRequestStatusResponseSchema,propertyId:z.uuid().nullable(),checkIn:z.iso.date().nullable(),checkOut:z.iso.date().nullable(),guestCount:z.number().int().nullable(),guestFirstName:z.string().nullable(),totalMinor:z.number().int().nullable(),currency:z.string().nullable(),confirmationCode:z.string().nullable()});z.uuid();var storefrontSiteSchema=z.object({id:z.uuid(),name:z.string(),slug:z.string(),isActive:z.boolean(),enableWebChat:z.boolean(),mapEmbedHost:z.string().nullable(),countryCode:z.string().nullish()});var storefrontListingSummarySchema=z.object({id:z.uuid(),buildingId:z.uuid(),sortOrder:z.number().int(),name:z.string(),coverImageUrl:z.string().nullable(),city:z.string().nullable(),state:z.string().nullable(),bedroomCount:z.number().int().nullable(),bathroomCount:z.number().nullable(),maxGuests:z.number().int().nullable(),averageRating:z.number().nullable(),latitude:z.number().nullable(),longitude:z.number().nullable(),bookable:z.boolean()});var storefrontListingSchema=storefrontListingSummarySchema.extend({buildingSlug:z.string(),buildingAddress:z.unknown(),description:z.string().nullable(),amenities:z.array(z.string()),pictures:z.unknown(),rooms:z.unknown(),houseRules:z.string().nullable(),checkInTime:z.string().nullable(),checkOutTime:z.string().nullable(),beds:z.number().nullable(),fromPriceMinor:z.number().int().nonnegative().nullish(),currency:z.string().nullish(),countryCode:z.string().nullish()});z.object({location:z.string().trim().min(1).max(200).optional(),building:z.uuid().optional(),limit:z.coerce.number().int().min(1).max(100).default(50),offset:z.coerce.number().int().min(0).max(1e4).default(0)});var storefrontBuildingSchema=z.object({id:z.uuid(),locationId:z.uuid().nullable(),nameId:z.uuid().nullable(),descriptionId:z.uuid().nullable(),slug:z.string(),imageId:z.uuid().nullable(),latitude:z.number().nullable(),longitude:z.number().nullable(),address:z.unknown()});var storefrontLocationSchema=z.object({id:z.uuid(),type:z.string(),parentId:z.uuid().nullable(),nameId:z.uuid().nullable(),slug:z.string().nullable(),imageId:z.uuid().nullable(),latitude:z.number().nullable(),longitude:z.number().nullable(),address:z.unknown(),sortOrder:z.number().int()});var storefrontReviewSchema=z.object({id:z.uuid(),listingId:z.uuid().nullable(),reviewedAt:z.string().nullable(),rating:z.number().nullable(),publicReview:z.string(),source:z.string().nullable()});z.object({listingId:z.uuid().optional(),limit:z.coerce.number().int().min(1).max(100).default(20),offset:z.coerce.number().int().min(0).max(1e4).default(0)});z.object({name:z.string().trim().min(1,"validation.name_required").max(200,"validation.name_max_length"),email:requiredTrimmedEmailField,subject:z.string().trim().min(1,"validation.title_required").max(300,"validation.title_max_length"),message:z.string().trim().min(10,"validation.message_min_length").max(1e4,"validation.message_max_length")});var storefrontContactResultSchema=z.object({sent:z.literal(true)});z.enum(STOREFRONT_KEY_ENVIRONMENTS);var STOREFRONT_KEY_RE=new RegExp(`^pk_(${STOREFRONT_KEY_ENVIRONMENTS.join("|")})_(${REGIONS.join("|")})_[0-9A-Za-z]{24}$`);function parseStorefrontKey(token){const match=STOREFRONT_KEY_RE.exec(token);if(!match)return null;return {environment:match[1],region:match[2]}}var ORIGIN_HOST_RE=/^(?:[a-z0-9-]+\.)*[a-z0-9-]+$|^\[[0-9a-f:.]+\]$/;function parseUrl(value){try{return new URL(value)}catch{return null}}z.string().refine(value=>{const url=parseUrl(value);if(!url)return false;return (url.protocol==="https:"||url.protocol==="http:")&&url.origin===value&&ORIGIN_HOST_RE.test(url.hostname)},"validation.storefront.origin_invalid");var CLIENT_CONVERSION_EVENT_NAMES=["begin_checkout","generate_lead","sign_up"];var STOREFRONT_EVENT_PATH_MAX=512;var base={eventId:z.uuid(),ts:z.number().int(),path:z.string().max(STOREFRONT_EVENT_PATH_MAX),referrerHost:z.string().max(253).nullable()};var currency2=z.string().length(3).regex(/^[a-z]{3}$/);var storefrontClientEventSchema=z.discriminatedUnion("name",[z.object({...base,name:z.literal("page_view")}),z.object({...base,name:z.literal("view_search_results"),checkIn:storefrontDateSchema.optional(),checkOut:storefrontDateSchema.optional(),guests:z.number().int().min(1).max(50).optional(),locationId:z.uuid().optional()}),z.object({...base,name:z.literal("view_item_list"),listName:z.string().max(64),itemCount:z.number().int().min(0).max(500)}),z.object({...base,name:z.literal("view_item"),listingId:z.uuid()}),z.object({...base,name:z.literal("view_quote"),listingId:z.uuid(),valueMinor:z.number().int().nonnegative(),currency:currency2,nights:z.number().int().min(1).max(365)}),z.object({...base,name:z.literal("begin_checkout"),checkoutSessionId:z.uuid()}),z.object({...base,name:z.literal("add_payment_info"),checkoutSessionId:z.uuid()}),z.object({...base,name:z.literal("generate_lead"),formId:z.string().max(64).optional()}),z.object({...base,name:z.literal("sign_up"),method:z.literal("newsletter")})]);var STOREFRONT_EVENT_BATCH_MAX=20;z.object({events:z.array(storefrontClientEventSchema).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});z.object({events:z.array(z.object({eventId:z.uuid(),name:z.enum(CLIENT_CONVERSION_EVENT_NAMES),occurredAt:z.iso.datetime(),pageUrl:z.url({protocol:/^https?$/}).max(2048),checkoutSessionId:z.uuid().nullable(),userAgent:z.string().max(512).nullable(),attribution:storefrontAttributionInputSchema.nullable()})).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});var ATTRIBUTION_COOKIE="so_attr";var ATTRIBUTION_COOKIE_MAX_AGE_SECONDS=90*24*60*60;var COOKIE_SCOPE="Path=/; SameSite=Lax; Secure";var ATTRIBUTION_COOKIE_ATTRIBUTES=`Max-Age=${ATTRIBUTION_COOKIE_MAX_AGE_SECONDS}; ${COOKIE_SCOPE}`;var ATTRIBUTION_COOKIE_MAX_BYTES=3584;var attributionCookieSchema=z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable()});function toBase64Url(text){let binary="";for(const byte of new TextEncoder().encode(text))binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64Url(value){const binary=atob(value.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(binary,ch=>ch.charCodeAt(0)))}function encodeAttributionCookie(value){const encoded=toBase64Url(JSON.stringify(value));return encoded.length>ATTRIBUTION_COOKIE_MAX_BYTES?null:encoded}function serializeAttributionCookie(value){const encoded=encodeAttributionCookie(value);return encoded===null?null:`${ATTRIBUTION_COOKIE}=${encoded}; ${ATTRIBUTION_COOKIE_ATTRIBUTES}`}function decodeAttributionCookie(value){if(!value)return null;return attributionCookieSchema.parse(JSON.parse(fromBase64Url(value)))}function expiredAttributionCookies(cookies,consent){const revoked=[...consent.analytics?[]:[ATTRIBUTION_COOKIE],...consent.ads?[]:["_fbc","_fbp"]];return revoked.filter(name=>readCookie(cookies,name)!==null).map(name=>`${name}=; Max-Age=0; ${COOKIE_SCOPE}`)}function strippedAttributionCookie(held){const clicked=t=>t!==null&&[t.gclid,t.gbraid,t.wbraid,t.fbclid,t.msclkid].some(id=>id!==null);if(!held||!(clicked(held.first)||clicked(held.last)))return null;return serializeAttributionCookie({first:held.first&&withoutClickIds(held.first),last:held.last&&withoutClickIds(held.last)})??`${ATTRIBUTION_COOKIE}=; Max-Age=0; ${COOKIE_SCOPE}`}function readCookie(header,name){if(!header)return null;for(const part of header.split(";")){const eq=part.indexOf("=");if(eq!==-1&&part.slice(0,eq).trim()===name)return part.slice(eq+1).trim()}return null}var MalformedCookieError=class extends Error{constructor(name){super(`${name} is malformed`);this.name="MalformedAttributionError";}};var NO_IDS={gaClientId:null,gaSessionId:null,fbp:null,fbc:null};function matchCookie(cookies,name,re,report){const value=name?readCookie(cookies,name):null;if(!value)return null;const match=re.exec(value);if(!match){report(new MalformedCookieError(name),name);return null}return match.slice(1).filter(Boolean).join(".")}function browserIdsFromCookies(cookies,consent,report){const sessionCookie=cookies.split(";").map(part=>part.split("=")[0].trim()).find(name=>name.startsWith("_ga_"))??null;const ga=consent.analytics;const ads=consent.ads;const ids={gaClientId:ga?matchCookie(cookies,"_ga",/^GA\d\.\d+\.(\d+)\.(\d+)$/,report):null,gaSessionId:ga?matchCookie(cookies,sessionCookie,/^(?:GS1\.\d+\.(\d+)\.|GS2\.\d+\.s(\d+)(?:\$|$))/,report):null,fbp:ads?matchCookie(cookies,"_fbp",/^(fb\.\d\.\d+\.\d+)$/,report):null,fbc:ads?matchCookie(cookies,"_fbc",/^(fb\.\d\.\d+\.[\w-]+)$/,report):null};const parsed=attributionIdsSchema.safeParse(ids);if(parsed.success)return parsed.data;report(parsed.error,"ids");return NO_IDS}var isDirect=touch=>classifyChannel({...touch,siteHost:globalThis.location?.hostname??""}).channel==="direct";var TOUCH_ELEMENT_ID="__suiteop_touch";var CONSENT_EVENT="suiteop:consent";var DENIED={analytics:false,ads:false,source:"default",region:"restricted",decidedAt:null};var defaultReport=(err,where)=>{console.warn(`[suiteop] ignored malformed attribution input (${where})`,err);};function pageConsent(){const read=globalThis.__suiteop?.consent?.get;const parsed=consentStateSchema.safeParse(typeof read==="function"?read():null);return parsed.success?parsed.data:DENIED}function pageTouch(report){const text=document.getElementById(TOUCH_ELEMENT_ID)?.textContent;if(!text)return null;try{return attributionTouchSchema.parse(JSON.parse(text))}catch(err){report(err,TOUCH_ELEMENT_ID);return null}}function storedCookie(cookies,report){try{return decodeAttributionCookie(readCookie(cookies,ATTRIBUTION_COOKIE))}catch(err){report(err,ATTRIBUTION_COOKIE);return null}}function getAttribution(opts={}){if(typeof document==="undefined")return null;const report=opts.report??defaultReport;const cookies=document.cookie;const consent=pageConsent();const stored=consent.analytics?storedCookie(cookies,report):null;const touch=pageTouch(report);const pageIsLast=touch!==null&&!(stored?.last&&(isDirect(touch)||Date.parse(stored.last.ts)>Date.parse(touch.ts)));return {first:stored?.first??touch,last:pageIsLast?touch:stored?.last??null,ids:browserIdsFromCookies(cookies,consent,report),consent}}function watchAttributionConsent(opts={}){if(typeof window==="undefined")return ()=>{};const report=opts.report??defaultReport;const persist=consent=>{if(readCookie(document.cookie,ATTRIBUTION_COOKIE))return;const touch=pageTouch(report);if(!touch)return;const kept=consent.ads?touch:withoutClickIds(touch);const cookie=serializeAttributionCookie({first:kept,last:kept});if(cookie)document.cookie=cookie;};const withdraw=consent=>{for(const cookie of expiredAttributionCookies(document.cookie,consent)){document.cookie=cookie;}if(consent.analytics&&!consent.ads){const stripped=strippedAttributionCookie(storedCookie(document.cookie,report));if(stripped)document.cookie=stripped;}};const initial=pageConsent();let analytics=initial.analytics;if(initial.source==="user")withdraw(initial);if(analytics)persist(initial);const onConsent=event=>{const next=consentStateSchema.safeParse(event.detail);if(!next.success)return;const granted=!analytics&&next.data.analytics;analytics=next.data.analytics;withdraw(next.data);if(granted)persist(next.data);};window.addEventListener(CONSENT_EVENT,onConsent);return ()=>window.removeEventListener(CONSENT_EVENT,onConsent)}var EVENTS_ENDPOINT="/_suiteop/events";var FLUSH_INTERVAL_MS=2e3;var FLUSH_AT_EVENTS=10;var defaultReport2=err=>{console.warn("[suiteop] storefront events could not be sent",err);};function hostOf2(url){try{return new URL(url).hostname||null}catch{return null}}var META_EVENTS={begin_checkout:"InitiateCheckout",generate_lead:"Lead",sign_up:"CompleteRegistration",view_item:"ViewContent",view_search_results:"Search",add_payment_info:"AddPaymentInfo"};var GTAG_SKIP=new Set(["page_view","purchase"]);function mirrorToTags(event){const w=window;if(typeof w.gtag!=="function"&&typeof w.fbq!=="function")return;const consent=pageConsent();const{name,eventId,ts:_ts,path:_path,referrerHost:_ref,...params}=event;if(consent.analytics&&typeof w.gtag==="function"&&!GTAG_SKIP.has(name)){w.gtag("event",name,params);}const metaName=META_EVENTS[name];if(consent.ads&&typeof w.fbq==="function"&&metaName){w.fbq("track",metaName,{},{eventID:eventId});}}function trackPurchasePixel(booking){if(typeof window==="undefined")return;const fbq=window.fbq;if(typeof fbq!=="function"||!pageConsent().ads)return;const amount=typeof booking.totalMinor==="number"&&booking.currency?{value:booking.totalMinor/100,currency:booking.currency.toUpperCase()}:{};fbq("track","Purchase",amount,{eventID:booking.bookingRequestId});}var NOOP={track(){},pageView(){},flush(){},dispose(){}};function createAnalytics(opts){if(typeof window==="undefined")return NOOP;const report=opts.report??defaultReport2;const url=`${EVENTS_ENDPOINT}?key=${encodeURIComponent(opts.publishableKey)}`;let queue=[];let timer=null;let landing=true;let lastViewedHref=null;let disabled=false;let reported=false;const fail=err=>{if(reported)return;reported=true;report(err);};const send=(events,beacon)=>{const body=JSON.stringify({events});if(beacon&&typeof navigator.sendBeacon==="function"&&navigator.sendBeacon(url,body)){return}fetch(url,{method:"POST",body,keepalive:true,credentials:"same-origin",headers:{"content-type":"application/json"}}).then(response=>{if(response.status===404)disabled=true;else if(!response.ok)fail(new Error(`storefront events answered ${response.status}`));}).catch(fail);};const flush=({beacon=false}={})=>{if(timer)clearTimeout(timer);timer=null;if(disabled||queue.length===0)return;const pending=queue;queue=[];for(let i=0;i<pending.length;i+=STOREFRONT_EVENT_BATCH_MAX){send(pending.slice(i,i+STOREFRONT_EVENT_BATCH_MAX),beacon);}};const enqueue=(event,referrerHost)=>{const full={...event,eventId:crypto.randomUUID(),ts:Date.now(),path:location.pathname.slice(0,STOREFRONT_EVENT_PATH_MAX),referrerHost};try{mirrorToTags(full);}catch(err){fail(err);}if(disabled)return;queue.push(full);if(queue.length>=FLUSH_AT_EVENTS)flush();else timer??=setTimeout(()=>flush(),FLUSH_INTERVAL_MS);};const pageView=()=>{if(location.href===lastViewedHref)return;lastViewedHref=location.href;const referrerHost=landing?hostOf2(document.referrer):location.hostname;landing=false;enqueue({name:"page_view"},referrerHost);};const onPageHide=()=>flush({beacon:true});const onPageShow=event=>{if(!event.persisted)return;lastViewedHref=null;pageView();};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);return {track:event=>enqueue(event,location.hostname),pageView,flush,dispose:()=>{flush({beacon:true});window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);}}}var shared=new Map;function analyticsFor(publishableKey){let instance=shared.get(publishableKey);if(!instance){instance=createAnalytics({publishableKey});if(instance!==NOOP)shared.set(publishableKey,instance);}return instance}function parsePublishableKey(key){if(typeof key==="string"&&key.trim().startsWith("sk_")){throw new StorefrontConfigError("A SuiteOp secret key (sk_\u2026) was passed as the publishable key. Secret keys must never be used in a browser or shipped in site code \u2014 revoke it now, then use a publishable key (pk_live_\u2026 / pk_test_\u2026) from the site settings.")}const parsed=typeof key==="string"?parseStorefrontKey(key.trim()):null;if(!parsed){throw new StorefrontConfigError("Invalid SuiteOp publishable key: expected pk_{live|test}_{us|eu|apac}_ followed by 24 letters or digits.")}return parsed}function defaultApiOrigin({environment,region}){return environment==="live"?`https://api-${region}.suiteop.com`:`https://api-${region}-staging.suiteop.com`}var SDK_VERSION="0.1.0";var STOREFRONT_API_VERSION="2026-09-27";var GET_RETRY_JITTER_MS=300;function buildUrl(base2,spec){const params=new URLSearchParams;for(const[key,value]of Object.entries(spec.query??{})){if(value!==void 0&&value!==null)params.set(key,String(value));}const search=params.toString();return `${base2}${spec.path}${search?`?${search}`:""}`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason);const onAbort=()=>{clearTimeout(timer);reject(signal?.reason);};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve();},ms);signal?.addEventListener("abort",onAbort,{once:true});})}function parseJson(text){if(!text)return void 0;try{return JSON.parse(text)}catch{return void 0}}function isRetryable(err){return err instanceof StorefrontNetworkError||err instanceof StorefrontError&&err.status>=500}function createTransport(opts){async function attempt(spec){const controller=new AbortController;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;controller.abort(new DOMException("The request timed out","TimeoutError"));},spec.timeoutMs);const onCallerAbort=()=>controller.abort(spec.signal?.reason);if(spec.signal?.aborted)onCallerAbort();else spec.signal?.addEventListener("abort",onCallerAbort,{once:true});try{let response;let text;try{response=await opts.fetch(buildUrl(opts.baseUrl(),spec),{method:spec.method,headers:{...opts.headers,...spec.body===void 0?{}:{"Content-Type":"application/json"},...spec.headers},body:spec.body===void 0?void 0:JSON.stringify(spec.body),signal:controller.signal});text=await response.text();}catch(err){if(spec.signal?.aborted)throw spec.signal.reason;if(timedOut)throw new StorefrontTimeoutError(spec.timeoutMs);throw new StorefrontNetworkError(err)}const body=parseJson(text);if(!response.ok)throw errorFromResponse(response,body);const envelope=body;const meta=envelope?.meta??{};const requestId=typeof meta["requestId"]==="string"?meta["requestId"]:response.headers.get("x-request-id");if(!envelope||typeof envelope!=="object"||!("data"in envelope)){throw new StorefrontError({status:response.status,code:"invalid_response",message:"The Storefront API answered without a data envelope",requestId})}return {status:response.status,requestId,data:envelope.data,meta}}finally{clearTimeout(timer);spec.signal?.removeEventListener("abort",onCallerAbort);}}return {async send(spec){try{return await attempt(spec)}catch(err){if(spec.method!=="GET"||!isRetryable(err))throw err;await sleep(Math.random()*GET_RETRY_JITTER_MS,spec.signal);return attempt(spec)}}}}var STOREFRONT_API_PATH="/api/storefront/v1";var READ_TIMEOUT_MS=1e4;var WRITE_TIMEOUT_MS=2e4;function resolveBaseUrl(baseUrl,origin){if(baseUrl===void 0)return `${origin}${STOREFRONT_API_PATH}`;if(baseUrl==="same-origin"){const pageOrigin=globalThis.location?.origin;if(!pageOrigin||pageOrigin==="null"){throw new StorefrontConfigError("baseUrl 'same-origin' needs a page origin; pass an explicit baseUrl outside a browser.")}return `${pageOrigin}${STOREFRONT_API_PATH}`}let url;try{url=new URL(baseUrl);}catch{throw new StorefrontConfigError(`baseUrl must be an absolute URL or 'same-origin'.`)}const path=url.pathname.replace(/\/+$/,"");return `${url.origin}${path.endsWith(STOREFRONT_API_PATH)?path:`${path}${STOREFRONT_API_PATH}`}`}function uuidV4(){const c=globalThis.crypto;if(typeof c.randomUUID==="function")return c.randomUUID();const b=c.getRandomValues(new Uint8Array(16));b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=Array.from(b,x=>x.toString(16).padStart(2,"0")).join("");return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function validate(schema,value,res){const parsed=schema.safeParse(value);if(parsed.success)return parsed.data;throw new StorefrontError({status:res.status,code:"invalid_response",message:"The Storefront API answered a shape this SDK version does not understand",requestId:res.requestId,details:{issues:parsed.error.issues.map(i=>({path:i.path,code:i.code}))}})}var paginationSchema=z.object({total:z.number().int(),limit:z.number().int(),offset:z.number().int()});var seg=value=>encodeURIComponent(value);var slotOf=(quoteRef,ratePlanId)=>`${quoteRef}\0${ratePlanId??""}`;var RELEASED_SESSION_STATUSES=new Set(["expired","cancelled"]);var KEY_BOUND_ELSEWHERE="idempotency_key_reused";function endsSession(err){return err.code==="session_expired"||err.details["requiresNewSession"]===true}var attributionWatched=false;function createStorefrontClient(options){const key=parsePublishableKey(options.publishableKey);const baseUrl=resolveBaseUrl(options.baseUrl,defaultApiOrigin(key));const transport=createTransport({baseUrl:()=>baseUrl,fetch:(input,init)=>(options.fetch??globalThis.fetch)(input,init),headers:{Authorization:`Bearer ${options.publishableKey.trim()}`,Accept:"application/json","X-SuiteOp-SDK":`storefront-js/${SDK_VERSION}`,"X-SuiteOp-Api-Version":STOREFRONT_API_VERSION,...options.locale?{"Accept-Language":options.locale}:{}}});const keySlots=new Map;const sessionSlots=new Map;const release=(slot,key2)=>{if(keySlots.get(slot)===key2)keySlots.delete(slot);};const releaseSession=id=>{const entry=sessionSlots.get(id);if(!entry)return;sessionSlots.delete(id);release(...entry);};if(!attributionWatched&&typeof window!=="undefined"){attributionWatched=true;watchAttributionConsent();}const readTimeoutMs=options.timeoutMs??READ_TIMEOUT_MS;const writeTimeoutMs=options.timeoutMs??WRITE_TIMEOUT_MS;async function get(schema,path,opts,query){const res=await transport.send({method:"GET",path,query,timeoutMs:readTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}async function post(schema,path,body,opts,headers){const res=await transport.send({method:"POST",path,body,headers,timeoutMs:writeTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}return {publishableKey:options.publishableKey.trim(),baseUrl,site:{get:opts=>get(storefrontSiteSchema,"/site",opts)},listings:{async list(query,opts){const res=await transport.send({method:"GET",path:"/listings",query:{location:query?.location,building:query?.building,limit:query?.limit,offset:query?.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(z.array(storefrontListingSummarySchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);return {items,...pagination}},get:(id,opts)=>get(storefrontListingSchema,`/listings/${seg(id)}`,opts)},buildings:{list:opts=>get(z.array(storefrontBuildingSchema),"/buildings",opts),get:(id,opts)=>get(storefrontBuildingSchema,`/buildings/${seg(id)}`,opts)},locations:{list:opts=>get(z.array(storefrontLocationSchema),"/locations",opts)},amenities:{list:opts=>get(z.array(z.string()),"/amenities",opts)},reviews:{list:(query,opts)=>get(z.array(storefrontReviewSchema),"/reviews",opts,{listingId:query?.listingId,limit:query?.limit,offset:query?.offset})},availability:{get:(listingId,stay,opts)=>get(storefrontAvailabilitySchema,`/listings/${seg(listingId)}/availability`,opts,{checkIn:stay.checkIn,checkOut:stay.checkOut,guests:stay.guests})},calendar:{get:(listingId,range,opts)=>get(storefrontCalendarSchema,`/listings/${seg(listingId)}/calendar`,opts,{from:range.from,to:range.to})},quotes:{create:(input,opts)=>post(storefrontQuoteSchema,"/quotes",input,opts)},checkoutSessions:{async create(input,opts){const slot=slotOf(input.quoteRef,input.ratePlanId);const idempotencyKey=opts?.idempotencyKey??keySlots.get(slot)??uuidV4();keySlots.set(slot,idempotencyKey);const attribution=input.attribution===void 0?getAttribution():input.attribution;const body=attribution?{...input,attribution}:input;try{const created=await post(checkoutSessionSchema,"/checkout-sessions",body,opts,{"Idempotency-Key":idempotencyKey});if(RELEASED_SESSION_STATUSES.has(created.status))release(slot,idempotencyKey);else sessionSlots.set(created.id,[slot,idempotencyKey]);return {...created,idempotencyKey}}catch(err){if(err instanceof StorefrontError){err.details["idempotencyKey"]=idempotencyKey;if(err.code===KEY_BOUND_ELSEWHERE)release(slot,idempotencyKey);}throw err}},get:(id,opts)=>get(checkoutSessionSchema,`/checkout-sessions/${seg(id)}`,opts),async confirm(id,input,opts){try{const result=await post(bookingResultSchema,`/checkout-sessions/${seg(id)}/confirm`,input,opts);return result}catch(err){if(err instanceof StorefrontError&&endsSession(err)){releaseSession(id);}throw err}},forget(quoteRef,ratePlanId){keySlots.delete(slotOf(quoteRef,ratePlanId));}},bookings:{get:(token,opts)=>get(storefrontBookingSchema,`/bookings/${seg(token)}`,opts)},contact:{async create(input,opts){await post(storefrontContactResultSchema,"/contact",input,opts);}}}}
6
+ var STOREFRONT_CHANNELS=["ai_assistant","paid_search","paid_social","organic_search","organic_social","email","referral","direct"];var AI_ASSISTANT_HOSTS={"chatgpt.com":"chatgpt","chat.openai.com":"chatgpt","perplexity.ai":"perplexity","gemini.google.com":"gemini","copilot.microsoft.com":"copilot","claude.ai":"claude"};var AI_ASSISTANT_SOURCES={"chatgpt.com":"chatgpt",perplexity:"perplexity","perplexity.ai":"perplexity",gemini:"gemini",copilot:"copilot","claude.ai":"claude"};var PAID_CLICKS=["google","microsoft","meta"];var PAID_MEDIUMS=new Set(["cpc","ppc","paid","paidsearch","sem"]);var EMAIL_RE=/newsletter|mailchimp|klaviyo/;var SEARCH_SUFFIXES=["bing.com","duckduckgo.com","search.yahoo.com","baidu.com","ecosia.org","search.brave.com"];var SEARCH_ANY_TLD_RE=/^(?:www\.)?(?:google|yandex)\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SUFFIXES=["facebook.com","instagram.com","t.co","x.com","twitter.com","linkedin.com","tiktok.com","youtube.com","reddit.com"];var SOCIAL_ANY_TLD_RE=/(?:^|\.)pinterest\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SOURCES=new Set(["facebook","fb","instagram","ig","meta","twitter","x","linkedin","pinterest","tiktok","youtube","reddit"]);var clean=value=>{const v=value?.trim().toLowerCase();return v?v:null};var hostOf=value=>clean(value)?.replace(/\.$/,"")??null;var hostMatches=(host,suffix)=>host===suffix||host.endsWith(`.${suffix}`);var bareHost=host=>host.replace(/^www\./,"");function aiLabel(host,source){if(host){const suffix=Object.keys(AI_ASSISTANT_HOSTS).find(s=>hostMatches(host,s));if(suffix)return AI_ASSISTANT_HOSTS[suffix]}return source&&Object.hasOwn(AI_ASSISTANT_SOURCES,source)?AI_ASSISTANT_SOURCES[source]:null}var isSearchHost=host=>SEARCH_ANY_TLD_RE.test(host)||SEARCH_SUFFIXES.some(s=>hostMatches(host,s));var isSocialHost=host=>SOCIAL_ANY_TLD_RE.test(host)||SOCIAL_SUFFIXES.some(s=>hostMatches(host,s));function paidClickOf(t){const medium=clean(t.utmMedium);if(t.fbclid&&medium!==null&&PAID_MEDIUMS.has(medium))return "meta";if(t.gclid||t.gbraid||t.wbraid)return "google";if(t.msclkid)return "microsoft";if(t.fbclid)return "meta";return t.paidClick??null}function classifyChannel(t){const source=clean(t.utmSource);const medium=clean(t.utmMedium);const site=bareHost(hostOf(t.siteHost)??"");const ref=hostOf(t.referrerHost);const external=ref&&bareHost(ref)!==site?ref:null;const result=(channel,label=null)=>({channel,source:label??source??external,medium});const socialSource=source!==null&&(SOCIAL_SOURCES.has(source)||isSocialHost(source))||!!(external&&isSocialHost(external));const paidMedium=medium!==null&&PAID_MEDIUMS.has(medium);const searchClick=t.gclid||t.gbraid||t.wbraid||t.msclkid||t.paidClick==="google"||t.paidClick==="microsoft";const metaClick=t.fbclid||t.paidClick==="meta";if(searchClick||paidMedium){return result(socialSource||metaClick&&paidMedium?"paid_social":"paid_search")}if(medium==="email"||EMAIL_RE.test(source??"")||EMAIL_RE.test(medium??"")){return result("email")}const ai=aiLabel(external,source);if(ai)return result("ai_assistant",ai);if(external&&isSearchHost(external))return result("organic_search");if(socialSource||metaClick)return result("organic_social");const anyUtm=[source,medium,t.utmCampaign,t.utmTerm,t.utmContent].some(v=>clean(v??null));if(!external&&!anyUtm)return result("direct");return result("referral")}var consentStateSchema=z.object({analytics:z.boolean(),ads:z.boolean(),source:z.enum(["default","user"]),region:z.enum(["restricted","other"]),decidedAt:z.iso.datetime().max(40).nullable()});function isSafePrivacyUrl(value){if([...value].some(ch=>/\s/.test(ch)||ch.charCodeAt(0)<32))return false;if(value.startsWith("/"))return !value.startsWith("//")&&!value.startsWith("/\\");if(!value.startsWith("https://")||!URL.canParse(value))return false;const url=new URL(value);return url.hostname!==""&&url.username===""&&url.password===""}var STOREFRONT_CONSENT_MODES=["regional","strict"];var modeField=z.enum(STOREFRONT_CONSENT_MODES);var privacyPolicyUrlField=z.string().trim().max(2048,"validation.storefront.privacy_policy_url_invalid").refine(isSafePrivacyUrl,"validation.storefront.privacy_policy_url_invalid").nullable();z.object({mode:modeField.default("regional"),privacyPolicyUrl:privacyPolicyUrlField.default(null)});z.object({siteId:z.uuid(),consentSettings:z.object({mode:modeField.optional(),privacyPolicyUrl:privacyPolicyUrlField.optional()})});var ACTIVE_RESERVATION_STATUSES=["confirmed","reserved","awaiting_payment"];new Set(ACTIVE_RESERVATION_STATUSES);var SCHEDULABLE_RESERVATION_STATUSES=[...ACTIVE_RESERVATION_STATUSES,"blocked"];new Set(SCHEDULABLE_RESERVATION_STATUSES);var VOLATILE_SYNC_STATUSES=["pending","pending_deletion","failed_deletion"];new Set(VOLATILE_SYNC_STATUSES);var CURRENCIES=["usd","eur","aud","gbp","cad","chf","cny","jpy","nzd","nok","mxn","thb","bgn","aed","inr","rub","brl","zar","sgd","hkd","xcd","xof","clp","dkk","try","bnd","xcg","shp","fkp","idr","ron","czk"];var ZERO_DECIMAL_CURRENCY_CODES=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);new Set(CURRENCIES.filter(code=>ZERO_DECIMAL_CURRENCY_CODES.has(code)));var LIVE_PAYMENT_INTENT_STATUS_LIST=["succeeded","processing","requires_capture","refunded","disputed","reversed"];new Set(LIVE_PAYMENT_INTENT_STATUS_LIST);var BE_SITE_EXPERIMENT_VARIANTS=["a","b"];var ACTIVE_MIGRATION_RUN_STATUSES=["running","writing","finalizing","rolling_back"];new Set(ACTIVE_MIGRATION_RUN_STATUSES.filter(status=>status!=="rolling_back"));var experimentVariantSchema=z.enum(BE_SITE_EXPERIMENT_VARIANTS);var experimentAssignmentSchema=z.object({id:z.uuid(),variant:experimentVariantSchema});z.object({siteId:z.uuid()});z.object({siteId:z.uuid(),deploymentBId:z.uuid("validation.storefront.experiment_variant_required"),splitBPercent:z.number("validation.storefront.experiment_split_range").int("validation.storefront.experiment_split_range").min(1,"validation.storefront.experiment_split_range").max(99,"validation.storefront.experiment_split_range")});z.object({id:z.uuid(),winner:experimentVariantSchema.nullable()});z.object({id:z.uuid()});var clickId=z.string().min(1).max(512).regex(/^[\w.\-~]+$/);var storable=value=>!value.includes("\0")&&!/\p{Surrogate}/u.test(value);var utm=z.string().max(150).refine(storable).nullable();var attributionTouchSchema=z.object({ts:z.iso.datetime().max(40),landingPath:z.string().max(512).regex(/^\/[^?#]*$/).refine(storable),referrerHost:z.string().max(253).regex(/^[a-z0-9.-]+$/).nullable(),utmSource:utm,utmMedium:utm,utmCampaign:utm,utmTerm:utm,utmContent:utm,gclid:clickId.nullable(),gbraid:clickId.nullable(),wbraid:clickId.nullable(),fbclid:clickId.nullable(),msclkid:clickId.nullable(),paidClick:z.enum(PAID_CLICKS).nullable().default(null)});var attributionIdsSchema=z.object({gaClientId:z.string().max(64).regex(/^\d+\.\d+$/).nullable(),gaSessionId:z.string().max(32).regex(/^\d+$/).nullable(),fbp:z.string().max(128).regex(/^fb\.\d\.\d+\.\d+$/).nullable(),fbc:z.string().max(600).regex(/^fb\.\d\.\d+\.[\w-]+$/).nullable()});var storefrontAttributionInputSchema=z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable(),ids:attributionIdsSchema,consent:consentStateSchema,experiment:experimentAssignmentSchema.optional()});var STORED_ATTRIBUTION_CHANNELS=[...STOREFRONT_CHANNELS,"ai_agent_mcp"];storefrontAttributionInputSchema.extend({firstChannel:z.enum(STORED_ATTRIBUTION_CHANNELS).nullable(),lastChannel:z.enum(STORED_ATTRIBUTION_CHANNELS),userAgent:z.string().max(512).nullable(),capturedAt:z.iso.datetime()});function withoutClickIds(touch){return {...touch,gclid:null,gbraid:null,wbraid:null,fbclid:null,msclkid:null,paidClick:paidClickOf(touch)}}var emailField=z.string().trim().toLowerCase().pipe(z.email("validation.email_invalid"));z.string().trim().min(1,"validation.email_required").pipe(emailField);var trimmedEmailField=z.string().trim().pipe(z.email("validation.email_invalid"));var requiredTrimmedEmailField=z.string().trim().min(1,"validation.email_required").pipe(trimmedEmailField);z.string().nullish().transform((raw,ctx)=>{if(raw===void 0)return void 0;const trimmed=(raw??"").trim().toLowerCase();if(!trimmed)return null;if(!z.email().safeParse(trimmed).success){ctx.addIssue({code:"custom",message:"validation.email_invalid"});return z.NEVER}return trimmed});var amountMinor=z.number().int().positive();var currency=z.string().length(3);var chargedByHost=z.literal("host");var checkoutMountDescriptorKnownSchema=z.discriminatedUnion("provider",[z.object({provider:z.literal("stripe"),publishableKey:z.string().min(1),stripeAccountId:z.string().nullable(),clientSecret:z.string().min(1),amountMinor,currency}),z.object({provider:z.literal("juspay"),publishableKey:z.string().min(1),providerBaseUrl:z.url(),clientSecret:z.string().min(1),profileId:z.string().min(1),amountMinor,currency}),z.object({provider:z.literal("guesty_pay"),guestyPartnerId:z.string().min(1),paymentProviderId:z.string().min(1),externalListingId:z.string().min(1),pmsQuoteId:z.string().nullable(),amountMinor,currency,chargedBy:chargedByHost.optional()}),z.object({provider:z.literal("pms_stripe"),publishableKey:z.string().min(1),stripeAccountId:z.string().min(1),clientSecret:z.string().min(1),amountMinor,currency,chargedBy:chargedByHost})]);var KNOWN_MOUNT_PROVIDERS=["stripe","juspay","guesty_pay","pms_stripe"];var checkoutMountDescriptorSchema=z.union([checkoutMountDescriptorKnownSchema,z.object({provider:z.string().refine(p=>!KNOWN_MOUNT_PROVIDERS.includes(p))}).loose()]);z.enum(BE_BOOKING_REQUEST_STATUSES);var bookingRequestStatusResponseSchema=openEnum(BE_BOOKING_REQUEST_STATUSES);var checkoutSessionQuoteSchema=z.object({listingId:z.uuid(),checkIn:z.iso.date(),checkOut:z.iso.date(),guests:z.number().int().positive(),ratePlanId:z.string(),totalMinor:z.number().int(),currency:z.string().length(3)});z.object({quoteRef:z.string().min(1).max(4096),ratePlanId:z.string().min(1).max(200).optional(),attribution:z.custom().optional()});var checkoutSessionSchema=z.object({id:z.uuid(),status:bookingRequestStatusResponseSchema,quote:checkoutSessionQuoteSchema,mount:checkoutMountDescriptorSchema.nullable(),chargedBy:chargedByHost.optional(),guestSaved:z.literal(true).optional(),expiresAt:z.iso.datetime()});var storefrontGuestInputSchema=z.object({firstName:z.string().trim().min(1,"validation.first_name_required").max(100),lastName:z.string().trim().min(1,"validation.last_name_required").max(100),email:requiredTrimmedEmailField,phone:z.string().trim().min(1,"validation.phone_required").max(40)});var storefrontConsentsSchema=z.object({emailMarketing:z.boolean().default(false),smsMarketing:z.boolean().default(false)}).default({emailMarketing:false,smsMarketing:false});var confirmCheckoutSessionInputSchema=z.object({quoteRef:z.string().min(1).max(4096),guest:storefrontGuestInputSchema,consents:storefrontConsentsSchema,paymentMethodId:z.string().min(1).max(255).optional(),language:z.string().max(35).optional().catch(void 0)});confirmCheckoutSessionInputSchema.pick({quoteRef:true,guest:true,consents:true,language:true});z.object({saved:z.boolean()});var bookingResultSchema=z.object({bookingRequestId:z.uuid(),confirmationToken:z.string(),status:bookingRequestStatusResponseSchema,confirmationCode:z.string().nullable()});var storefrontBookingSchema=z.object({id:z.uuid(),status:bookingRequestStatusResponseSchema,propertyId:z.uuid().nullable(),checkIn:z.iso.date().nullable(),checkOut:z.iso.date().nullable(),guestCount:z.number().int().nullable(),guestFirstName:z.string().nullable(),totalMinor:z.number().int().nullable(),currency:z.string().nullable(),confirmationCode:z.string().nullable()});z.uuid();var storefrontSiteSchema=z.object({id:z.uuid(),name:z.string(),slug:z.string(),isActive:z.boolean(),enableWebChat:z.boolean(),mapEmbedHost:z.string().nullable(),countryCode:z.string().nullish()});var storefrontListingSummarySchema=z.object({id:z.uuid(),buildingId:z.uuid(),sortOrder:z.number().int(),name:z.string(),coverImageUrl:z.string().nullable(),city:z.string().nullable(),state:z.string().nullable(),bedroomCount:z.number().int().nullable(),bathroomCount:z.number().nullable(),maxGuests:z.number().int().nullable(),averageRating:z.number().nullable(),latitude:z.number().nullable(),longitude:z.number().nullable(),bookable:z.boolean()});var storefrontListingSchema=storefrontListingSummarySchema.extend({buildingSlug:z.string(),buildingAddress:z.unknown(),description:z.string().nullable(),amenities:z.array(z.string()),pictures:z.unknown(),rooms:z.unknown(),houseRules:z.string().nullable(),checkInTime:z.string().nullable(),checkOutTime:z.string().nullable(),beds:z.number().nullable(),fromPriceMinor:z.number().int().nonnegative().nullish(),currency:z.string().nullish(),countryCode:z.string().nullish()});z.object({location:z.string().trim().min(1).max(200).optional(),building:z.uuid().optional(),limit:z.coerce.number().int().min(1).max(100).default(50),offset:z.coerce.number().int().min(0).max(1e4).default(0)});var storefrontBuildingSchema=z.object({id:z.uuid(),locationId:z.uuid().nullable(),nameId:z.uuid().nullable(),descriptionId:z.uuid().nullable(),slug:z.string(),imageId:z.uuid().nullable(),latitude:z.number().nullable(),longitude:z.number().nullable(),address:z.unknown()});var storefrontLocationSchema=z.object({id:z.uuid(),type:z.string(),parentId:z.uuid().nullable(),nameId:z.uuid().nullable(),slug:z.string().nullable(),imageId:z.uuid().nullable(),latitude:z.number().nullable(),longitude:z.number().nullable(),address:z.unknown(),sortOrder:z.number().int()});var storefrontReviewSchema=z.object({id:z.uuid(),listingId:z.uuid().nullable(),reviewedAt:z.string().nullable(),rating:z.number().nullable(),publicReview:z.string(),source:z.string().nullable()});z.object({listingId:z.uuid().optional(),limit:z.coerce.number().int().min(1).max(100).default(20),offset:z.coerce.number().int().min(0).max(1e4).default(0)});z.object({name:z.string().trim().min(1,"validation.name_required").max(200,"validation.name_max_length"),email:requiredTrimmedEmailField,subject:z.string().trim().min(1,"validation.title_required").max(300,"validation.title_max_length"),message:z.string().trim().min(10,"validation.message_min_length").max(1e4,"validation.message_max_length")});var storefrontContactResultSchema=z.object({sent:z.literal(true)});z.enum(STOREFRONT_KEY_ENVIRONMENTS);var STOREFRONT_KEY_RE=new RegExp(`^pk_(${STOREFRONT_KEY_ENVIRONMENTS.join("|")})_(${REGIONS.join("|")})_[0-9A-Za-z]{24}$`);function parseStorefrontKey(token){const match=STOREFRONT_KEY_RE.exec(token);if(!match)return null;return {environment:match[1],region:match[2]}}var ORIGIN_HOST_RE=/^(?:[a-z0-9-]+\.)*[a-z0-9-]+$|^\[[0-9a-f:.]+\]$/;function parseUrl(value){try{return new URL(value)}catch{return null}}z.string().refine(value=>{const url=parseUrl(value);if(!url)return false;return (url.protocol==="https:"||url.protocol==="http:")&&url.origin===value&&ORIGIN_HOST_RE.test(url.hostname)},"validation.storefront.origin_invalid");var CLIENT_CONVERSION_EVENT_NAMES=["begin_checkout","generate_lead","sign_up"];var STOREFRONT_EVENT_PATH_MAX=512;var base={eventId:z.uuid(),ts:z.number().int(),path:z.string().max(STOREFRONT_EVENT_PATH_MAX),referrerHost:z.string().max(253).nullable()};var currency2=z.string().length(3).regex(/^[a-z]{3}$/);var storefrontClientEventSchema=z.discriminatedUnion("name",[z.object({...base,name:z.literal("page_view")}),z.object({...base,name:z.literal("view_search_results"),checkIn:storefrontDateSchema.optional(),checkOut:storefrontDateSchema.optional(),guests:z.number().int().min(1).max(50).optional(),locationId:z.uuid().optional()}),z.object({...base,name:z.literal("view_item_list"),listName:z.string().max(64),itemCount:z.number().int().min(0).max(500)}),z.object({...base,name:z.literal("view_item"),listingId:z.uuid()}),z.object({...base,name:z.literal("view_quote"),listingId:z.uuid(),valueMinor:z.number().int().nonnegative(),currency:currency2,nights:z.number().int().min(1).max(365)}),z.object({...base,name:z.literal("begin_checkout"),checkoutSessionId:z.uuid()}),z.object({...base,name:z.literal("add_payment_info"),checkoutSessionId:z.uuid()}),z.object({...base,name:z.literal("generate_lead"),formId:z.string().max(64).optional()}),z.object({...base,name:z.literal("sign_up"),method:z.literal("newsletter")})]);var STOREFRONT_EVENT_BATCH_MAX=20;z.object({events:z.array(storefrontClientEventSchema).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});z.object({events:z.array(z.object({eventId:z.uuid(),name:z.enum(CLIENT_CONVERSION_EVENT_NAMES),occurredAt:z.iso.datetime(),pageUrl:z.url({protocol:/^https?$/}).max(2048),checkoutSessionId:z.uuid().nullable(),userAgent:z.string().max(512).nullable(),attribution:storefrontAttributionInputSchema.nullable()})).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});var EXPERIMENT_COOKIE="__so_exp";var COOKIE_RE=/(?:^|;\s*)__so_exp=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(a|b)(?:\s*;|\s*$)/;function readExperimentCookie(cookies){const match=COOKIE_RE.exec(cookies??"");return match?{id:match[1],variant:match[2]}:null}var ATTRIBUTION_COOKIE="so_attr";var ATTRIBUTION_COOKIE_MAX_AGE_SECONDS=90*24*60*60;var COOKIE_SCOPE="Path=/; SameSite=Lax; Secure";var ATTRIBUTION_COOKIE_ATTRIBUTES=`Max-Age=${ATTRIBUTION_COOKIE_MAX_AGE_SECONDS}; ${COOKIE_SCOPE}`;var ATTRIBUTION_COOKIE_MAX_BYTES=3584;var attributionCookieSchema=z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable()});function toBase64Url(text){let binary="";for(const byte of new TextEncoder().encode(text))binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64Url(value){const binary=atob(value.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(binary,ch=>ch.charCodeAt(0)))}function encodeAttributionCookie(value){const encoded=toBase64Url(JSON.stringify(value));return encoded.length>ATTRIBUTION_COOKIE_MAX_BYTES?null:encoded}function serializeAttributionCookie(value){const encoded=encodeAttributionCookie(value);return encoded===null?null:`${ATTRIBUTION_COOKIE}=${encoded}; ${ATTRIBUTION_COOKIE_ATTRIBUTES}`}function decodeAttributionCookie(value){if(!value)return null;return attributionCookieSchema.parse(JSON.parse(fromBase64Url(value)))}function expiredAttributionCookies(cookies,consent){const revoked=[...consent.analytics?[]:[ATTRIBUTION_COOKIE,EXPERIMENT_COOKIE],...consent.ads?[]:["_fbc","_fbp"]];return revoked.filter(name=>readCookie(cookies,name)!==null).map(name=>`${name}=; Max-Age=0; ${COOKIE_SCOPE}`)}function strippedAttributionCookie(held){const clicked=t=>t!==null&&[t.gclid,t.gbraid,t.wbraid,t.fbclid,t.msclkid].some(id=>id!==null);if(!held||!(clicked(held.first)||clicked(held.last)))return null;return serializeAttributionCookie({first:held.first&&withoutClickIds(held.first),last:held.last&&withoutClickIds(held.last)})??`${ATTRIBUTION_COOKIE}=; Max-Age=0; ${COOKIE_SCOPE}`}function readCookie(header,name){if(!header)return null;for(const part of header.split(";")){const eq=part.indexOf("=");if(eq!==-1&&part.slice(0,eq).trim()===name)return part.slice(eq+1).trim()}return null}var MalformedCookieError=class extends Error{constructor(name){super(`${name} is malformed`);this.name="MalformedAttributionError";}};var NO_IDS={gaClientId:null,gaSessionId:null,fbp:null,fbc:null};function matchCookie(cookies,name,re,report){const value=name?readCookie(cookies,name):null;if(!value)return null;const match=re.exec(value);if(!match){report(new MalformedCookieError(name),name);return null}return match.slice(1).filter(Boolean).join(".")}function browserIdsFromCookies(cookies,consent,report){const sessionCookie=cookies.split(";").map(part=>part.split("=")[0].trim()).find(name=>name.startsWith("_ga_"))??null;const ga=consent.analytics;const ads=consent.ads;const ids={gaClientId:ga?matchCookie(cookies,"_ga",/^GA\d\.\d+\.(\d+)\.(\d+)$/,report):null,gaSessionId:ga?matchCookie(cookies,sessionCookie,/^(?:GS1\.\d+\.(\d+)\.|GS2\.\d+\.s(\d+)(?:\$|$))/,report):null,fbp:ads?matchCookie(cookies,"_fbp",/^(fb\.\d\.\d+\.\d+)$/,report):null,fbc:ads?matchCookie(cookies,"_fbc",/^(fb\.\d\.\d+\.[\w-]+)$/,report):null};const parsed=attributionIdsSchema.safeParse(ids);if(parsed.success)return parsed.data;report(parsed.error,"ids");return NO_IDS}var isDirect=touch=>classifyChannel({...touch,siteHost:globalThis.location?.hostname??""}).channel==="direct";var TOUCH_ELEMENT_ID="__suiteop_touch";var CONSENT_EVENT="suiteop:consent";var DENIED={analytics:false,ads:false,source:"default",region:"restricted",decidedAt:null};var defaultReport=(err,where)=>{console.warn(`[suiteop] ignored malformed attribution input (${where})`,err);};function pageConsent(){const read=globalThis.__suiteop?.consent?.get;const parsed=consentStateSchema.safeParse(typeof read==="function"?read():null);return parsed.success?parsed.data:DENIED}function pageTouch(report){const text=document.getElementById(TOUCH_ELEMENT_ID)?.textContent;if(!text)return null;try{return attributionTouchSchema.parse(JSON.parse(text))}catch(err){report(err,TOUCH_ELEMENT_ID);return null}}function storedCookie(cookies,report){try{return decodeAttributionCookie(readCookie(cookies,ATTRIBUTION_COOKIE))}catch(err){report(err,ATTRIBUTION_COOKIE);return null}}function getAttribution(opts={}){if(typeof document==="undefined")return null;const report=opts.report??defaultReport;const cookies=document.cookie;const consent=pageConsent();const stored=consent.analytics?storedCookie(cookies,report):null;const touch=pageTouch(report);const pageIsLast=touch!==null&&!(stored?.last&&(isDirect(touch)||Date.parse(stored.last.ts)>Date.parse(touch.ts)));const experiment=consent.analytics?readExperimentCookie(cookies):null;return {first:stored?.first??touch,last:pageIsLast?touch:stored?.last??null,ids:browserIdsFromCookies(cookies,consent,report),consent,...experiment?{experiment}:{}}}function watchAttributionConsent(opts={}){if(typeof window==="undefined")return ()=>{};const report=opts.report??defaultReport;const persist=consent=>{if(readCookie(document.cookie,ATTRIBUTION_COOKIE))return;const touch=pageTouch(report);if(!touch)return;const kept=consent.ads?touch:withoutClickIds(touch);const cookie=serializeAttributionCookie({first:kept,last:kept});if(cookie)document.cookie=cookie;};const withdraw=consent=>{for(const cookie of expiredAttributionCookies(document.cookie,consent)){document.cookie=cookie;}if(consent.analytics&&!consent.ads){const stripped=strippedAttributionCookie(storedCookie(document.cookie,report));if(stripped)document.cookie=stripped;}};const initial=pageConsent();let analytics=initial.analytics;if(initial.source==="user")withdraw(initial);if(analytics)persist(initial);const onConsent=event=>{const next=consentStateSchema.safeParse(event.detail);if(!next.success)return;const granted=!analytics&&next.data.analytics;analytics=next.data.analytics;withdraw(next.data);if(granted)persist(next.data);};window.addEventListener(CONSENT_EVENT,onConsent);return ()=>window.removeEventListener(CONSENT_EVENT,onConsent)}var EVENTS_ENDPOINT="/_suiteop/events";var FLUSH_INTERVAL_MS=2e3;var FLUSH_AT_EVENTS=10;var defaultReport2=err=>{console.warn("[suiteop] storefront events could not be sent",err);};function hostOf2(url){try{return new URL(url).hostname||null}catch{return null}}var META_EVENTS={begin_checkout:"InitiateCheckout",generate_lead:"Lead",sign_up:"CompleteRegistration",view_item:"ViewContent",view_search_results:"Search",add_payment_info:"AddPaymentInfo"};var GTAG_SKIP=new Set(["page_view","purchase"]);function mirrorToTags(event){const w=window;if(typeof w.gtag!=="function"&&typeof w.fbq!=="function")return;const consent=pageConsent();const{name,eventId,ts:_ts,path:_path,referrerHost:_ref,...params}=event;if(consent.analytics&&typeof w.gtag==="function"&&!GTAG_SKIP.has(name)){w.gtag("event",name,params);}const metaName=META_EVENTS[name];if(consent.ads&&typeof w.fbq==="function"&&metaName){w.fbq("track",metaName,{},{eventID:eventId});}}function trackPurchasePixel(booking){if(typeof window==="undefined")return;const fbq=window.fbq;if(typeof fbq!=="function"||!pageConsent().ads)return;const amount=typeof booking.totalMinor==="number"&&booking.currency?{value:booking.totalMinor/100,currency:booking.currency.toUpperCase()}:{};fbq("track","Purchase",amount,{eventID:booking.bookingRequestId});}var NOOP={track(){},pageView(){},flush(){},dispose(){}};function createAnalytics(opts){if(typeof window==="undefined")return NOOP;const report=opts.report??defaultReport2;const url=`${EVENTS_ENDPOINT}?key=${encodeURIComponent(opts.publishableKey)}`;let queue=[];let timer=null;let landing=true;let lastViewedHref=null;let disabled=false;let reported=false;const fail=err=>{if(reported)return;reported=true;report(err);};const send=(events,beacon)=>{const body=JSON.stringify({events});if(beacon&&typeof navigator.sendBeacon==="function"&&navigator.sendBeacon(url,body)){return}fetch(url,{method:"POST",body,keepalive:true,credentials:"same-origin",headers:{"content-type":"application/json"}}).then(response=>{if(response.status===404)disabled=true;else if(!response.ok)fail(new Error(`storefront events answered ${response.status}`));}).catch(fail);};const flush=({beacon=false}={})=>{if(timer)clearTimeout(timer);timer=null;if(disabled||queue.length===0)return;const pending=queue;queue=[];for(let i=0;i<pending.length;i+=STOREFRONT_EVENT_BATCH_MAX){send(pending.slice(i,i+STOREFRONT_EVENT_BATCH_MAX),beacon);}};const enqueue=(event,referrerHost)=>{const full={...event,eventId:crypto.randomUUID(),ts:Date.now(),path:location.pathname.slice(0,STOREFRONT_EVENT_PATH_MAX),referrerHost};try{mirrorToTags(full);}catch(err){fail(err);}if(disabled)return;queue.push(full);if(queue.length>=FLUSH_AT_EVENTS)flush();else timer??=setTimeout(()=>flush(),FLUSH_INTERVAL_MS);};const pageView=()=>{if(location.href===lastViewedHref)return;lastViewedHref=location.href;const referrerHost=landing?hostOf2(document.referrer):location.hostname;landing=false;enqueue({name:"page_view"},referrerHost);};const onPageHide=()=>flush({beacon:true});const onPageShow=event=>{if(!event.persisted)return;lastViewedHref=null;pageView();};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);return {track:event=>enqueue(event,location.hostname),pageView,flush,dispose:()=>{flush({beacon:true});window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);}}}var shared=new Map;function analyticsFor(publishableKey){let instance=shared.get(publishableKey);if(!instance){instance=createAnalytics({publishableKey});if(instance!==NOOP)shared.set(publishableKey,instance);}return instance}function parsePublishableKey(key){if(typeof key==="string"&&key.trim().startsWith("sk_")){throw new StorefrontConfigError("A SuiteOp secret key (sk_\u2026) was passed as the publishable key. Secret keys must never be used in a browser or shipped in site code \u2014 revoke it now, then use a publishable key (pk_live_\u2026 / pk_test_\u2026) from the site settings.")}const parsed=typeof key==="string"?parseStorefrontKey(key.trim()):null;if(!parsed){throw new StorefrontConfigError("Invalid SuiteOp publishable key: expected pk_{live|test}_{us|eu|apac}_ followed by 24 letters or digits.")}return parsed}function defaultApiOrigin({environment,region}){return environment==="live"?`https://api-${region}.suiteop.com`:`https://api-${region}-staging.suiteop.com`}var SDK_VERSION="0.1.1";var STOREFRONT_API_VERSION="2026-09-27";var GET_RETRY_JITTER_MS=300;function buildUrl(base2,spec){const params=new URLSearchParams;for(const[key,value]of Object.entries(spec.query??{})){if(value!==void 0&&value!==null)params.set(key,String(value));}const search=params.toString();return `${base2}${spec.path}${search?`?${search}`:""}`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason);const onAbort=()=>{clearTimeout(timer);reject(signal?.reason);};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve();},ms);signal?.addEventListener("abort",onAbort,{once:true});})}function parseJson(text){if(!text)return void 0;try{return JSON.parse(text)}catch{return void 0}}function isRetryable(err){return err instanceof StorefrontNetworkError||err instanceof StorefrontError&&err.status>=500}function createTransport(opts){async function attempt(spec){const controller=new AbortController;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;controller.abort(new DOMException("The request timed out","TimeoutError"));},spec.timeoutMs);const onCallerAbort=()=>controller.abort(spec.signal?.reason);if(spec.signal?.aborted)onCallerAbort();else spec.signal?.addEventListener("abort",onCallerAbort,{once:true});try{let response;let text;try{response=await opts.fetch(buildUrl(opts.baseUrl(),spec),{method:spec.method,headers:{...opts.headers,...spec.body===void 0?{}:{"Content-Type":"application/json"},...spec.headers},body:spec.body===void 0?void 0:JSON.stringify(spec.body),signal:controller.signal});text=await response.text();}catch(err){if(spec.signal?.aborted)throw spec.signal.reason;if(timedOut)throw new StorefrontTimeoutError(spec.timeoutMs);throw new StorefrontNetworkError(err)}const body=parseJson(text);if(!response.ok)throw errorFromResponse(response,body);const envelope=body;const meta=envelope?.meta??{};const requestId=typeof meta["requestId"]==="string"?meta["requestId"]:response.headers.get("x-request-id");if(!envelope||typeof envelope!=="object"||!("data"in envelope)){throw new StorefrontError({status:response.status,code:"invalid_response",message:"The Storefront API answered without a data envelope",requestId})}return {status:response.status,requestId,data:envelope.data,meta}}finally{clearTimeout(timer);spec.signal?.removeEventListener("abort",onCallerAbort);}}return {async send(spec){try{return await attempt(spec)}catch(err){if(spec.method!=="GET"||!isRetryable(err))throw err;await sleep(Math.random()*GET_RETRY_JITTER_MS,spec.signal);return attempt(spec)}}}}var STOREFRONT_API_PATH="/api/storefront/v1";var READ_TIMEOUT_MS=1e4;var WRITE_TIMEOUT_MS=2e4;function resolveBaseUrl(baseUrl,origin){if(baseUrl===void 0)return `${origin}${STOREFRONT_API_PATH}`;if(baseUrl==="same-origin"){const pageOrigin=globalThis.location?.origin;if(!pageOrigin||pageOrigin==="null"){throw new StorefrontConfigError("baseUrl 'same-origin' needs a page origin; pass an explicit baseUrl outside a browser.")}return `${pageOrigin}${STOREFRONT_API_PATH}`}let url;try{url=new URL(baseUrl);}catch{throw new StorefrontConfigError(`baseUrl must be an absolute URL or 'same-origin'.`)}const path=url.pathname.replace(/\/+$/,"");return `${url.origin}${path.endsWith(STOREFRONT_API_PATH)?path:`${path}${STOREFRONT_API_PATH}`}`}function uuidV4(){const c=globalThis.crypto;if(typeof c.randomUUID==="function")return c.randomUUID();const b=c.getRandomValues(new Uint8Array(16));b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=Array.from(b,x=>x.toString(16).padStart(2,"0")).join("");return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function validate(schema,value,res){const parsed=schema.safeParse(value);if(parsed.success)return parsed.data;throw new StorefrontError({status:res.status,code:"invalid_response",message:"The Storefront API answered a shape this SDK version does not understand",requestId:res.requestId,details:{issues:parsed.error.issues.map(i=>({path:i.path,code:i.code}))}})}var paginationSchema=z.object({total:z.number().int(),limit:z.number().int(),offset:z.number().int()});var seg=value=>encodeURIComponent(value);var slotOf=(quoteRef,ratePlanId)=>`${quoteRef}\0${ratePlanId??""}`;var RELEASED_SESSION_STATUSES=new Set(["expired","cancelled"]);var KEY_BOUND_ELSEWHERE="idempotency_key_reused";function endsSession(err){return err.code==="session_expired"||err.details["requiresNewSession"]===true}var attributionWatched=false;function createStorefrontClient(options){const key=parsePublishableKey(options.publishableKey);const baseUrl=resolveBaseUrl(options.baseUrl,defaultApiOrigin(key));const transport=createTransport({baseUrl:()=>baseUrl,fetch:(input,init)=>(options.fetch??globalThis.fetch)(input,init),headers:{Authorization:`Bearer ${options.publishableKey.trim()}`,Accept:"application/json","X-SuiteOp-SDK":`storefront-js/${SDK_VERSION}`,"X-SuiteOp-Api-Version":STOREFRONT_API_VERSION,...options.locale?{"Accept-Language":options.locale}:{}}});const keySlots=new Map;const sessionSlots=new Map;const release=(slot,key2)=>{if(keySlots.get(slot)===key2)keySlots.delete(slot);};const releaseSession=id=>{const entry=sessionSlots.get(id);if(!entry)return;sessionSlots.delete(id);release(...entry);};if(!attributionWatched&&typeof window!=="undefined"){attributionWatched=true;watchAttributionConsent();}const readTimeoutMs=options.timeoutMs??READ_TIMEOUT_MS;const writeTimeoutMs=options.timeoutMs??WRITE_TIMEOUT_MS;async function get(schema,path,opts,query){const res=await transport.send({method:"GET",path,query,timeoutMs:readTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}async function post(schema,path,body,opts,headers){const res=await transport.send({method:"POST",path,body,headers,timeoutMs:writeTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}return {publishableKey:options.publishableKey.trim(),baseUrl,site:{get:opts=>get(storefrontSiteSchema,"/site",opts)},listings:{async list(query,opts){const res=await transport.send({method:"GET",path:"/listings",query:{location:query?.location,building:query?.building,limit:query?.limit,offset:query?.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(z.array(storefrontListingSummarySchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);return {items,...pagination}},get:(id,opts)=>get(storefrontListingSchema,`/listings/${seg(id)}`,opts)},buildings:{list:opts=>get(z.array(storefrontBuildingSchema),"/buildings",opts),get:(id,opts)=>get(storefrontBuildingSchema,`/buildings/${seg(id)}`,opts)},locations:{list:opts=>get(z.array(storefrontLocationSchema),"/locations",opts)},amenities:{list:opts=>get(z.array(z.string()),"/amenities",opts)},reviews:{list:(query,opts)=>get(z.array(storefrontReviewSchema),"/reviews",opts,{listingId:query?.listingId,limit:query?.limit,offset:query?.offset})},availability:{get:(listingId,stay,opts)=>get(storefrontAvailabilitySchema,`/listings/${seg(listingId)}/availability`,opts,{checkIn:stay.checkIn,checkOut:stay.checkOut,guests:stay.guests})},calendar:{get:(listingId,range,opts)=>get(storefrontCalendarSchema,`/listings/${seg(listingId)}/calendar`,opts,{from:range.from,to:range.to})},quotes:{create:(input,opts)=>post(storefrontQuoteSchema,"/quotes",input,opts)},checkoutSessions:{async create(input,opts){const slot=slotOf(input.quoteRef,input.ratePlanId);const idempotencyKey=opts?.idempotencyKey??keySlots.get(slot)??uuidV4();keySlots.set(slot,idempotencyKey);const attribution=input.attribution===void 0?getAttribution():input.attribution;const body=attribution?{...input,attribution}:input;try{const created=await post(checkoutSessionSchema,"/checkout-sessions",body,opts,{"Idempotency-Key":idempotencyKey});if(RELEASED_SESSION_STATUSES.has(created.status))release(slot,idempotencyKey);else sessionSlots.set(created.id,[slot,idempotencyKey]);return {...created,idempotencyKey}}catch(err){if(err instanceof StorefrontError){err.details["idempotencyKey"]=idempotencyKey;if(err.code===KEY_BOUND_ELSEWHERE)release(slot,idempotencyKey);}throw err}},get:(id,opts)=>get(checkoutSessionSchema,`/checkout-sessions/${seg(id)}`,opts),async confirm(id,input,opts){try{const result=await post(bookingResultSchema,`/checkout-sessions/${seg(id)}/confirm`,input,opts);return result}catch(err){if(err instanceof StorefrontError&&endsSession(err)){releaseSession(id);}throw err}},forget(quoteRef,ratePlanId){keySlots.delete(slotOf(quoteRef,ratePlanId));}},bookings:{get:(token,opts)=>get(storefrontBookingSchema,`/bookings/${seg(token)}`,opts)},contact:{async create(input,opts){await post(storefrontContactResultSchema,"/contact",input,opts);}}}}
7
7
 
8
8
  export { SDK_VERSION, STOREFRONT_API_PATH, STOREFRONT_API_VERSION, analyticsFor, createAnalytics, createStorefrontClient, getAttribution, parsePublishableKey, trackPurchasePixel };
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkT2GQ3DOZ_cjs = require('./chunk-T2GQ3DOZ.cjs');
3
+ var chunkXIAAWHAY_cjs = require('./chunk-XIAAWHAY.cjs');
4
4
  var zod = require('zod');
5
5
 
6
- var TAG="suiteop-checkout";var manifestSchema=zod.z.object({v1:zod.z.object({path:zod.z.string().regex(/^\/checkout\/v1\.[0-9a-f]{12}\.js$/),integrity:zod.z.string().regex(/^sha384-[A-Za-z0-9+/]+={0,2}$/)})});var loads=new Map;var requested=new Map;function scriptUrl(url){const n=requested.get(url)??0;requested.set(url,n+1);return n===0?url:`${url}?retry=${n}`}function unavailable(message,cause){return new chunkT2GQ3DOZ_cjs.StorefrontError({status:0,code:"checkout_unavailable",message,cause})}async function fetchEntry(origin,fresh){const res=await fetch(`${origin}/checkout/manifest.json`,{cache:fresh?"no-store":"default",credentials:"omit"});if(!res.ok)throw unavailable(`The checkout manifest answered ${res.status}`);const parsed=manifestSchema.safeParse(await res.json());if(!parsed.success)throw unavailable("The checkout manifest has no usable v1 entry");return parsed.data.v1}function inject(src,integrity){const script=document.createElement("script");script.type="module";script.src=src;script.integrity=integrity;script.crossOrigin="anonymous";const ready=new Promise((resolve,reject)=>{script.addEventListener("error",()=>reject(unavailable(`${src} failed to load`)),{once:true});script.addEventListener("load",()=>customElements.get(TAG)?resolve():reject(unavailable(`${src} defined no <${TAG}>`)),{once:true});void customElements.whenDefined(TAG).then(()=>resolve());});document.head.append(script);return [script,ready]}async function load(origin){if(customElements.get(TAG))return;for(const fresh of [false,true]){try{const entry=await fetchEntry(origin,fresh);const[script,ready]=inject(scriptUrl(`${origin}${entry.path}`),entry.integrity);try{return await ready}catch(err){script.remove();if(fresh)throw err}}catch(err){if(err instanceof chunkT2GQ3DOZ_cjs.StorefrontError)throw err;throw unavailable("The checkout bundle could not be loaded",err)}}}function loadCheckout(options={}){if(typeof window==="undefined"||typeof document==="undefined")return Promise.resolve();let origin;try{origin=new URL(options.origin??window.location.origin).origin;}catch(err){return Promise.reject(unavailable("loadCheckout: origin must be an absolute URL",err))}const key=`${origin}|v${options.major??1}`;const existing=loads.get(key);if(existing)return existing;const loading=load(origin);loads.set(key,loading);loading.catch(()=>{if(loads.get(key)===loading)loads.delete(key);});return loading}
6
+ var TAG="suiteop-checkout";var manifestSchema=zod.z.object({v1:zod.z.object({path:zod.z.string().regex(/^\/checkout\/v1\.[0-9a-f]{12}\.js$/),integrity:zod.z.string().regex(/^sha384-[A-Za-z0-9+/]+={0,2}$/)})});var loads=new Map;var requested=new Map;function scriptUrl(url){const n=requested.get(url)??0;requested.set(url,n+1);return n===0?url:`${url}?retry=${n}`}function unavailable(message,cause){return new chunkXIAAWHAY_cjs.StorefrontError({status:0,code:"checkout_unavailable",message,cause})}async function fetchEntry(origin,fresh){const res=await fetch(`${origin}/checkout/manifest.json`,{cache:fresh?"no-store":"default",credentials:"omit"});if(!res.ok)throw unavailable(`The checkout manifest answered ${res.status}`);const parsed=manifestSchema.safeParse(await res.json());if(!parsed.success)throw unavailable("The checkout manifest has no usable v1 entry");return parsed.data.v1}function inject(src,integrity){const script=document.createElement("script");script.type="module";script.src=src;script.integrity=integrity;script.crossOrigin="anonymous";const ready=new Promise((resolve,reject)=>{script.addEventListener("error",()=>reject(unavailable(`${src} failed to load`)),{once:true});script.addEventListener("load",()=>customElements.get(TAG)?resolve():reject(unavailable(`${src} defined no <${TAG}>`)),{once:true});void customElements.whenDefined(TAG).then(()=>resolve());});document.head.append(script);return [script,ready]}async function load(origin){if(customElements.get(TAG))return;for(const fresh of [false,true]){try{const entry=await fetchEntry(origin,fresh);const[script,ready]=inject(scriptUrl(`${origin}${entry.path}`),entry.integrity);try{return await ready}catch(err){script.remove();if(fresh)throw err}}catch(err){if(err instanceof chunkXIAAWHAY_cjs.StorefrontError)throw err;throw unavailable("The checkout bundle could not be loaded",err)}}}function loadCheckout(options={}){if(typeof window==="undefined"||typeof document==="undefined")return Promise.resolve();let origin;try{origin=new URL(options.origin??window.location.origin).origin;}catch(err){return Promise.reject(unavailable("loadCheckout: origin must be an absolute URL",err))}const key=`${origin}|v${options.major??1}`;const existing=loads.get(key);if(existing)return existing;const loading=load(origin);loads.set(key,loading);loading.catch(()=>{if(loads.get(key)===loading)loads.delete(key);});return loading}
7
7
 
8
8
  exports.loadCheckout = loadCheckout;
@@ -0,0 +1,6 @@
1
+ import { withStayRules, storefrontGuestsSchema, storefrontDateSchema } from './chunk-6NFURJXI.js';
2
+ import { z } from 'zod';
3
+
4
+ var storefrontRatePlanQuoteSchema=z.object({ratePlanId:z.string(),name:z.string(),accommodationMinor:z.number().int(),feesMinor:z.number().int(),taxesMinor:z.number().int(),totalMinor:z.number().int().positive(),currency:z.string().regex(/^[a-z]{3}$/),cancellationPolicy:z.string().nullable(),cancellationFee:z.unknown().optional(),quoteRef:z.string()});withStayRules(z.object({listingId:z.uuid({message:"validation.storefront.listing_invalid"}),checkIn:storefrontDateSchema,checkOut:storefrontDateSchema,guests:storefrontGuestsSchema}));var storefrontQuoteSchema=z.object({quoteRef:z.string(),propertyId:z.uuid(),checkIn:storefrontDateSchema,checkOut:storefrontDateSchema,guests:z.number().int().positive(),ratePlans:z.array(storefrontRatePlanQuoteSchema).min(1),expiresAt:z.iso.datetime()});var STOREFRONT_ERROR_CODES=["wrong_region","origin_not_allowed","origin_required","site_archived","not_bookable","quote_invalid","quote_expired","price_changed","currency_unsupported","payment_declined","session_expired","rate_limited","contact_not_configured","payment_account_unavailable","idempotency_key_required","idempotency_key_reused","payment_mode_unsupported","payment_not_authorized","payment_method_required","site_not_published","preview_read_only","UNAUTHORIZED","VALIDATION_ERROR","NOT_FOUND","site_not_found","upstream_timeout","timeout","network","invalid_response","internal_error","checkout_unavailable"];var StorefrontError=class extends Error{name="StorefrontError";status;type;code;requestId;details;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause});this.status=init.status;this.code=init.code;this.type=init.type??init.code;this.requestId=init.requestId??null;this.details=init.details??{};}};var PriceChangedError=class extends StorefrontError{name="PriceChangedError";quote;requiresNewSession;constructor(init){super(init);const raw=this.details["quote"];const parsed=storefrontQuoteSchema.safeParse(raw);this.quote=parsed.success?parsed.data:null;this.requiresNewSession=this.details["requiresNewSession"]===true||raw!=null&&!parsed.success;}};var WrongRegionError=class extends StorefrontError{name="WrongRegionError";region;baseUrl;constructor(init){super(init);const{region,baseUrl}=this.details;this.region=region==="us"||region==="eu"||region==="apac"?region:null;this.baseUrl=typeof baseUrl==="string"?baseUrl:null;}};var RateLimitedError=class extends StorefrontError{name="RateLimitedError";retryAfterSec;scope;constructor(init){super(init);this.retryAfterSec=init.retryAfterSec;const{scope}=this.details;this.scope=scope==="key"||scope==="ip"||scope==="pms"?scope:null;}};var StorefrontTimeoutError=class extends StorefrontError{name="StorefrontTimeoutError";constructor(timeoutMs,requestId=null){super({status:0,code:"timeout",message:`No response within ${timeoutMs} ms`,requestId});}};var StorefrontNetworkError=class extends StorefrontError{name="StorefrontNetworkError";constructor(cause){super({status:0,code:"network",message:"The Storefront API could not be reached",cause});}};var StorefrontConfigError=class extends Error{name="StorefrontConfigError"};function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function parseRetryAfter(header){if(header===null)return null;const seconds=Number(header);if(Number.isFinite(seconds)&&seconds>=0)return Math.ceil(seconds);const at=Date.parse(header);return Number.isNaN(at)?null:Math.max(0,Math.ceil((at-Date.now())/1e3))}function errorFromResponse(response,body){const headerRequestId=response.headers.get("x-request-id");const wire=isRecord(body)&&isRecord(body["error"])?body["error"]:null;const meta=isRecord(body)&&isRecord(body["meta"])?body["meta"]:null;const requestId=typeof meta?.["requestId"]==="string"?meta["requestId"]:headerRequestId;if(!wire||typeof wire["code"]!=="string"){return new StorefrontError({status:response.status,code:"internal_error",message:`The Storefront API answered ${response.status}`,requestId})}const init={status:response.status,code:wire["code"],type:typeof wire["type"]==="string"?wire["type"]:wire["code"],message:typeof wire["message"]==="string"?wire["message"]:wire["code"],requestId,details:isRecord(wire["details"])?wire["details"]:{}};switch(init.code){case "price_changed":return new PriceChangedError(init);case "wrong_region":return new WrongRegionError(init);case "rate_limited":return new RateLimitedError({...init,retryAfterSec:parseRetryAfter(response.headers.get("retry-after"))??parseRetryAfter(typeof init.details?.["retryAfterSeconds"]==="number"?String(init.details["retryAfterSeconds"]):null)});default:return new StorefrontError(init)}}
5
+
6
+ export { PriceChangedError, RateLimitedError, STOREFRONT_ERROR_CODES, StorefrontConfigError, StorefrontError, StorefrontNetworkError, StorefrontTimeoutError, WrongRegionError, errorFromResponse, storefrontQuoteSchema };
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ var chunkLVFRVNT3_cjs = require('./chunk-LVFRVNT3.cjs');
4
+ var zod = require('zod');
5
+
6
+ var storefrontRatePlanQuoteSchema=zod.z.object({ratePlanId:zod.z.string(),name:zod.z.string(),accommodationMinor:zod.z.number().int(),feesMinor:zod.z.number().int(),taxesMinor:zod.z.number().int(),totalMinor:zod.z.number().int().positive(),currency:zod.z.string().regex(/^[a-z]{3}$/),cancellationPolicy:zod.z.string().nullable(),cancellationFee:zod.z.unknown().optional(),quoteRef:zod.z.string()});chunkLVFRVNT3_cjs.withStayRules(zod.z.object({listingId:zod.z.uuid({message:"validation.storefront.listing_invalid"}),checkIn:chunkLVFRVNT3_cjs.storefrontDateSchema,checkOut:chunkLVFRVNT3_cjs.storefrontDateSchema,guests:chunkLVFRVNT3_cjs.storefrontGuestsSchema}));var storefrontQuoteSchema=zod.z.object({quoteRef:zod.z.string(),propertyId:zod.z.uuid(),checkIn:chunkLVFRVNT3_cjs.storefrontDateSchema,checkOut:chunkLVFRVNT3_cjs.storefrontDateSchema,guests:zod.z.number().int().positive(),ratePlans:zod.z.array(storefrontRatePlanQuoteSchema).min(1),expiresAt:zod.z.iso.datetime()});var STOREFRONT_ERROR_CODES=["wrong_region","origin_not_allowed","origin_required","site_archived","not_bookable","quote_invalid","quote_expired","price_changed","currency_unsupported","payment_declined","session_expired","rate_limited","contact_not_configured","payment_account_unavailable","idempotency_key_required","idempotency_key_reused","payment_mode_unsupported","payment_not_authorized","payment_method_required","site_not_published","preview_read_only","UNAUTHORIZED","VALIDATION_ERROR","NOT_FOUND","site_not_found","upstream_timeout","timeout","network","invalid_response","internal_error","checkout_unavailable"];var StorefrontError=class extends Error{name="StorefrontError";status;type;code;requestId;details;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause});this.status=init.status;this.code=init.code;this.type=init.type??init.code;this.requestId=init.requestId??null;this.details=init.details??{};}};var PriceChangedError=class extends StorefrontError{name="PriceChangedError";quote;requiresNewSession;constructor(init){super(init);const raw=this.details["quote"];const parsed=storefrontQuoteSchema.safeParse(raw);this.quote=parsed.success?parsed.data:null;this.requiresNewSession=this.details["requiresNewSession"]===true||raw!=null&&!parsed.success;}};var WrongRegionError=class extends StorefrontError{name="WrongRegionError";region;baseUrl;constructor(init){super(init);const{region,baseUrl}=this.details;this.region=region==="us"||region==="eu"||region==="apac"?region:null;this.baseUrl=typeof baseUrl==="string"?baseUrl:null;}};var RateLimitedError=class extends StorefrontError{name="RateLimitedError";retryAfterSec;scope;constructor(init){super(init);this.retryAfterSec=init.retryAfterSec;const{scope}=this.details;this.scope=scope==="key"||scope==="ip"||scope==="pms"?scope:null;}};var StorefrontTimeoutError=class extends StorefrontError{name="StorefrontTimeoutError";constructor(timeoutMs,requestId=null){super({status:0,code:"timeout",message:`No response within ${timeoutMs} ms`,requestId});}};var StorefrontNetworkError=class extends StorefrontError{name="StorefrontNetworkError";constructor(cause){super({status:0,code:"network",message:"The Storefront API could not be reached",cause});}};var StorefrontConfigError=class extends Error{name="StorefrontConfigError"};function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function parseRetryAfter(header){if(header===null)return null;const seconds=Number(header);if(Number.isFinite(seconds)&&seconds>=0)return Math.ceil(seconds);const at=Date.parse(header);return Number.isNaN(at)?null:Math.max(0,Math.ceil((at-Date.now())/1e3))}function errorFromResponse(response,body){const headerRequestId=response.headers.get("x-request-id");const wire=isRecord(body)&&isRecord(body["error"])?body["error"]:null;const meta=isRecord(body)&&isRecord(body["meta"])?body["meta"]:null;const requestId=typeof meta?.["requestId"]==="string"?meta["requestId"]:headerRequestId;if(!wire||typeof wire["code"]!=="string"){return new StorefrontError({status:response.status,code:"internal_error",message:`The Storefront API answered ${response.status}`,requestId})}const init={status:response.status,code:wire["code"],type:typeof wire["type"]==="string"?wire["type"]:wire["code"],message:typeof wire["message"]==="string"?wire["message"]:wire["code"],requestId,details:isRecord(wire["details"])?wire["details"]:{}};switch(init.code){case "price_changed":return new PriceChangedError(init);case "wrong_region":return new WrongRegionError(init);case "rate_limited":return new RateLimitedError({...init,retryAfterSec:parseRetryAfter(response.headers.get("retry-after"))??parseRetryAfter(typeof init.details?.["retryAfterSeconds"]==="number"?String(init.details["retryAfterSeconds"]):null)});default:return new StorefrontError(init)}}
7
+
8
+ exports.PriceChangedError = PriceChangedError;
9
+ exports.RateLimitedError = RateLimitedError;
10
+ exports.STOREFRONT_ERROR_CODES = STOREFRONT_ERROR_CODES;
11
+ exports.StorefrontConfigError = StorefrontConfigError;
12
+ exports.StorefrontError = StorefrontError;
13
+ exports.StorefrontNetworkError = StorefrontNetworkError;
14
+ exports.StorefrontTimeoutError = StorefrontTimeoutError;
15
+ exports.WrongRegionError = WrongRegionError;
16
+ exports.errorFromResponse = errorFromResponse;
17
+ exports.storefrontQuoteSchema = storefrontQuoteSchema;
@@ -1,4 +1,4 @@
1
- import { StorefrontError } from './chunk-NNZZWGM2.js';
1
+ import { StorefrontError } from './chunk-UACP7BZ7.js';
2
2
  import { z } from 'zod';
3
3
 
4
4
  var TAG="suiteop-checkout";var manifestSchema=z.object({v1:z.object({path:z.string().regex(/^\/checkout\/v1\.[0-9a-f]{12}\.js$/),integrity:z.string().regex(/^sha384-[A-Za-z0-9+/]+={0,2}$/)})});var loads=new Map;var requested=new Map;function scriptUrl(url){const n=requested.get(url)??0;requested.set(url,n+1);return n===0?url:`${url}?retry=${n}`}function unavailable(message,cause){return new StorefrontError({status:0,code:"checkout_unavailable",message,cause})}async function fetchEntry(origin,fresh){const res=await fetch(`${origin}/checkout/manifest.json`,{cache:fresh?"no-store":"default",credentials:"omit"});if(!res.ok)throw unavailable(`The checkout manifest answered ${res.status}`);const parsed=manifestSchema.safeParse(await res.json());if(!parsed.success)throw unavailable("The checkout manifest has no usable v1 entry");return parsed.data.v1}function inject(src,integrity){const script=document.createElement("script");script.type="module";script.src=src;script.integrity=integrity;script.crossOrigin="anonymous";const ready=new Promise((resolve,reject)=>{script.addEventListener("error",()=>reject(unavailable(`${src} failed to load`)),{once:true});script.addEventListener("load",()=>customElements.get(TAG)?resolve():reject(unavailable(`${src} defined no <${TAG}>`)),{once:true});void customElements.whenDefined(TAG).then(()=>resolve());});document.head.append(script);return [script,ready]}async function load(origin){if(customElements.get(TAG))return;for(const fresh of [false,true]){try{const entry=await fetchEntry(origin,fresh);const[script,ready]=inject(scriptUrl(`${origin}${entry.path}`),entry.integrity);try{return await ready}catch(err){script.remove();if(fresh)throw err}}catch(err){if(err instanceof StorefrontError)throw err;throw unavailable("The checkout bundle could not be loaded",err)}}}function loadCheckout(options={}){if(typeof window==="undefined"||typeof document==="undefined")return Promise.resolve();let origin;try{origin=new URL(options.origin??window.location.origin).origin;}catch(err){return Promise.reject(unavailable("loadCheckout: origin must be an absolute URL",err))}const key=`${origin}|v${options.major??1}`;const existing=loads.get(key);if(existing)return existing;const loading=load(origin);loads.set(key,loading);loading.catch(()=>{if(loads.get(key)===loading)loads.delete(key);});return loading}
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { b as StorefrontCalendarDay } from './availability-CYvqeJ6X.cjs';
3
+ import { b as StorefrontCalendarDay } from './availability-CnzmxuV3.cjs';
4
4
  import 'zod';
5
5
 
6
6
  declare const defaultLabels: {
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { b as StorefrontCalendarDay } from './availability-CYvqeJ6X.js';
3
+ import { b as StorefrontCalendarDay } from './availability-CnzmxuV3.js';
4
4
  import 'zod';
5
5
 
6
6
  declare const defaultLabels: {
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { d as StorefrontStay, S as StorefrontAvailability, c as StorefrontCalendarQuery, a as StorefrontCalendar } from './availability-CYvqeJ6X.cjs';
2
+ import { d as StorefrontStay, S as StorefrontAvailability, c as StorefrontCalendarQuery, a as StorefrontCalendar } from './availability-CnzmxuV3.js';
3
3
 
4
4
  declare const storefrontGuestInputSchema: z.ZodObject<{
5
5
  firstName: z.ZodString;
@@ -27,13 +27,13 @@ type ConfirmCheckoutSessionInput = z.infer<typeof confirmCheckoutSessionInputSch
27
27
  declare const bookingResultSchema: z.ZodObject<{
28
28
  bookingRequestId: z.ZodUUID;
29
29
  confirmationToken: z.ZodString;
30
- status: z.ZodType<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown, z.core.$ZodTypeInternals<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown>>;
30
+ status: z.ZodType<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown, z.core.$ZodTypeInternals<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown>>;
31
31
  confirmationCode: z.ZodNullable<z.ZodString>;
32
32
  }, z.core.$strip>;
33
33
  type BookingResult = z.infer<typeof bookingResultSchema>;
34
34
  declare const storefrontBookingSchema: z.ZodObject<{
35
35
  id: z.ZodUUID;
36
- status: z.ZodType<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown, z.core.$ZodTypeInternals<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown>>;
36
+ status: z.ZodType<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown, z.core.$ZodTypeInternals<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown>>;
37
37
  propertyId: z.ZodNullable<z.ZodUUID>;
38
38
  checkIn: z.ZodNullable<z.ZodISODate>;
39
39
  checkOut: z.ZodNullable<z.ZodISODate>;
@@ -242,6 +242,10 @@ declare const createCheckoutSessionInputSchema: z.ZodObject<{
242
242
  region: "restricted" | "other";
243
243
  decidedAt: string | null;
244
244
  };
245
+ experiment?: {
246
+ id: string;
247
+ variant: "a" | "b";
248
+ } | undefined;
245
249
  } | null, {
246
250
  first: {
247
251
  ts: string;
@@ -288,12 +292,16 @@ declare const createCheckoutSessionInputSchema: z.ZodObject<{
288
292
  region: "restricted" | "other";
289
293
  decidedAt: string | null;
290
294
  };
295
+ experiment?: {
296
+ id: string;
297
+ variant: "a" | "b";
298
+ } | undefined;
291
299
  } | null>>;
292
300
  }, z.core.$strip>;
293
301
  type CreateCheckoutSessionInput = z.infer<typeof createCheckoutSessionInputSchema>;
294
302
  declare const checkoutSessionSchema: z.ZodObject<{
295
303
  id: z.ZodUUID;
296
- status: z.ZodType<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown, z.core.$ZodTypeInternals<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown>>;
304
+ status: z.ZodType<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown, z.core.$ZodTypeInternals<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown>>;
297
305
  quote: z.ZodObject<{
298
306
  listingId: z.ZodUUID;
299
307
  checkIn: z.ZodISODate;
@@ -339,6 +347,7 @@ declare const checkoutSessionSchema: z.ZodObject<{
339
347
  provider: z.ZodString;
340
348
  }, z.core.$loose>]>>;
341
349
  chargedBy: z.ZodOptional<z.ZodLiteral<"host">>;
350
+ guestSaved: z.ZodOptional<z.ZodLiteral<true>>;
342
351
  expiresAt: z.ZodISODateTime;
343
352
  }, z.core.$strip>;
344
353
  type CheckoutSession = z.infer<typeof checkoutSessionSchema>;
@@ -550,7 +559,7 @@ interface StorefrontClient {
550
559
  }
551
560
  declare function createStorefrontClient(options: StorefrontClientOptions): StorefrontClient;
552
561
 
553
- declare const STOREFRONT_ERROR_CODES: readonly ["wrong_region", "origin_not_allowed", "origin_required", "site_archived", "not_bookable", "quote_invalid", "quote_expired", "price_changed", "currency_unsupported", "payment_declined", "session_expired", "rate_limited", "contact_not_configured", "payment_account_unavailable", "idempotency_key_required", "idempotency_key_reused", "payment_mode_unsupported", "payment_not_authorized", "payment_method_required", "site_not_published", "UNAUTHORIZED", "VALIDATION_ERROR", "NOT_FOUND", "site_not_found", "upstream_timeout", "timeout", "network", "invalid_response", "internal_error", "checkout_unavailable"];
562
+ declare const STOREFRONT_ERROR_CODES: readonly ["wrong_region", "origin_not_allowed", "origin_required", "site_archived", "not_bookable", "quote_invalid", "quote_expired", "price_changed", "currency_unsupported", "payment_declined", "session_expired", "rate_limited", "contact_not_configured", "payment_account_unavailable", "idempotency_key_required", "idempotency_key_reused", "payment_mode_unsupported", "payment_not_authorized", "payment_method_required", "site_not_published", "preview_read_only", "UNAUTHORIZED", "VALIDATION_ERROR", "NOT_FOUND", "site_not_found", "upstream_timeout", "timeout", "network", "invalid_response", "internal_error", "checkout_unavailable"];
554
563
  type StorefrontErrorCode = (typeof STOREFRONT_ERROR_CODES)[number];
555
564
  type StorefrontRegion = 'us' | 'eu' | 'apac';
556
565
  interface StorefrontErrorInit {
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { d as StorefrontStay, S as StorefrontAvailability, c as StorefrontCalendarQuery, a as StorefrontCalendar } from './availability-CYvqeJ6X.js';
2
+ import { d as StorefrontStay, S as StorefrontAvailability, c as StorefrontCalendarQuery, a as StorefrontCalendar } from './availability-CnzmxuV3.cjs';
3
3
 
4
4
  declare const storefrontGuestInputSchema: z.ZodObject<{
5
5
  firstName: z.ZodString;
@@ -27,13 +27,13 @@ type ConfirmCheckoutSessionInput = z.infer<typeof confirmCheckoutSessionInputSch
27
27
  declare const bookingResultSchema: z.ZodObject<{
28
28
  bookingRequestId: z.ZodUUID;
29
29
  confirmationToken: z.ZodString;
30
- status: z.ZodType<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown, z.core.$ZodTypeInternals<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown>>;
30
+ status: z.ZodType<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown, z.core.$ZodTypeInternals<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown>>;
31
31
  confirmationCode: z.ZodNullable<z.ZodString>;
32
32
  }, z.core.$strip>;
33
33
  type BookingResult = z.infer<typeof bookingResultSchema>;
34
34
  declare const storefrontBookingSchema: z.ZodObject<{
35
35
  id: z.ZodUUID;
36
- status: z.ZodType<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown, z.core.$ZodTypeInternals<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown>>;
36
+ status: z.ZodType<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown, z.core.$ZodTypeInternals<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown>>;
37
37
  propertyId: z.ZodNullable<z.ZodUUID>;
38
38
  checkIn: z.ZodNullable<z.ZodISODate>;
39
39
  checkOut: z.ZodNullable<z.ZodISODate>;
@@ -242,6 +242,10 @@ declare const createCheckoutSessionInputSchema: z.ZodObject<{
242
242
  region: "restricted" | "other";
243
243
  decidedAt: string | null;
244
244
  };
245
+ experiment?: {
246
+ id: string;
247
+ variant: "a" | "b";
248
+ } | undefined;
245
249
  } | null, {
246
250
  first: {
247
251
  ts: string;
@@ -288,12 +292,16 @@ declare const createCheckoutSessionInputSchema: z.ZodObject<{
288
292
  region: "restricted" | "other";
289
293
  decidedAt: string | null;
290
294
  };
295
+ experiment?: {
296
+ id: string;
297
+ variant: "a" | "b";
298
+ } | undefined;
291
299
  } | null>>;
292
300
  }, z.core.$strip>;
293
301
  type CreateCheckoutSessionInput = z.infer<typeof createCheckoutSessionInputSchema>;
294
302
  declare const checkoutSessionSchema: z.ZodObject<{
295
303
  id: z.ZodUUID;
296
- status: z.ZodType<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown, z.core.$ZodTypeInternals<(string & {}) | "inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled", unknown>>;
304
+ status: z.ZodType<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown, z.core.$ZodTypeInternals<"inquiry" | "processing" | "confirmed" | "failed" | "expired" | "pending_pms_sync" | "pending_payment" | "authorized" | "reserved" | "cancelled" | (string & {}), unknown>>;
297
305
  quote: z.ZodObject<{
298
306
  listingId: z.ZodUUID;
299
307
  checkIn: z.ZodISODate;
@@ -339,6 +347,7 @@ declare const checkoutSessionSchema: z.ZodObject<{
339
347
  provider: z.ZodString;
340
348
  }, z.core.$loose>]>>;
341
349
  chargedBy: z.ZodOptional<z.ZodLiteral<"host">>;
350
+ guestSaved: z.ZodOptional<z.ZodLiteral<true>>;
342
351
  expiresAt: z.ZodISODateTime;
343
352
  }, z.core.$strip>;
344
353
  type CheckoutSession = z.infer<typeof checkoutSessionSchema>;
@@ -550,7 +559,7 @@ interface StorefrontClient {
550
559
  }
551
560
  declare function createStorefrontClient(options: StorefrontClientOptions): StorefrontClient;
552
561
 
553
- declare const STOREFRONT_ERROR_CODES: readonly ["wrong_region", "origin_not_allowed", "origin_required", "site_archived", "not_bookable", "quote_invalid", "quote_expired", "price_changed", "currency_unsupported", "payment_declined", "session_expired", "rate_limited", "contact_not_configured", "payment_account_unavailable", "idempotency_key_required", "idempotency_key_reused", "payment_mode_unsupported", "payment_not_authorized", "payment_method_required", "site_not_published", "UNAUTHORIZED", "VALIDATION_ERROR", "NOT_FOUND", "site_not_found", "upstream_timeout", "timeout", "network", "invalid_response", "internal_error", "checkout_unavailable"];
562
+ declare const STOREFRONT_ERROR_CODES: readonly ["wrong_region", "origin_not_allowed", "origin_required", "site_archived", "not_bookable", "quote_invalid", "quote_expired", "price_changed", "currency_unsupported", "payment_declined", "session_expired", "rate_limited", "contact_not_configured", "payment_account_unavailable", "idempotency_key_required", "idempotency_key_reused", "payment_mode_unsupported", "payment_not_authorized", "payment_method_required", "site_not_published", "preview_read_only", "UNAUTHORIZED", "VALIDATION_ERROR", "NOT_FOUND", "site_not_found", "upstream_timeout", "timeout", "network", "invalid_response", "internal_error", "checkout_unavailable"];
554
563
  type StorefrontErrorCode = (typeof STOREFRONT_ERROR_CODES)[number];
555
564
  type StorefrontRegion = 'us' | 'eu' | 'apac';
556
565
  interface StorefrontErrorInit {
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkAI6STRZP_cjs = require('./chunk-AI6STRZP.cjs');
4
- var chunkT2GQ3DOZ_cjs = require('./chunk-T2GQ3DOZ.cjs');
3
+ var chunkGIIXCS6X_cjs = require('./chunk-GIIXCS6X.cjs');
4
+ var chunkXIAAWHAY_cjs = require('./chunk-XIAAWHAY.cjs');
5
5
  require('./chunk-LVFRVNT3.cjs');
6
6
  require('./chunk-AIQUVZEI.cjs');
7
7
 
@@ -9,69 +9,69 @@ require('./chunk-AIQUVZEI.cjs');
9
9
 
10
10
  Object.defineProperty(exports, "SDK_VERSION", {
11
11
  enumerable: true,
12
- get: function () { return chunkAI6STRZP_cjs.SDK_VERSION; }
12
+ get: function () { return chunkGIIXCS6X_cjs.SDK_VERSION; }
13
13
  });
14
14
  Object.defineProperty(exports, "STOREFRONT_API_PATH", {
15
15
  enumerable: true,
16
- get: function () { return chunkAI6STRZP_cjs.STOREFRONT_API_PATH; }
16
+ get: function () { return chunkGIIXCS6X_cjs.STOREFRONT_API_PATH; }
17
17
  });
18
18
  Object.defineProperty(exports, "STOREFRONT_API_VERSION", {
19
19
  enumerable: true,
20
- get: function () { return chunkAI6STRZP_cjs.STOREFRONT_API_VERSION; }
20
+ get: function () { return chunkGIIXCS6X_cjs.STOREFRONT_API_VERSION; }
21
21
  });
22
22
  Object.defineProperty(exports, "analyticsFor", {
23
23
  enumerable: true,
24
- get: function () { return chunkAI6STRZP_cjs.analyticsFor; }
24
+ get: function () { return chunkGIIXCS6X_cjs.analyticsFor; }
25
25
  });
26
26
  Object.defineProperty(exports, "createAnalytics", {
27
27
  enumerable: true,
28
- get: function () { return chunkAI6STRZP_cjs.createAnalytics; }
28
+ get: function () { return chunkGIIXCS6X_cjs.createAnalytics; }
29
29
  });
30
30
  Object.defineProperty(exports, "createStorefrontClient", {
31
31
  enumerable: true,
32
- get: function () { return chunkAI6STRZP_cjs.createStorefrontClient; }
32
+ get: function () { return chunkGIIXCS6X_cjs.createStorefrontClient; }
33
33
  });
34
34
  Object.defineProperty(exports, "getAttribution", {
35
35
  enumerable: true,
36
- get: function () { return chunkAI6STRZP_cjs.getAttribution; }
36
+ get: function () { return chunkGIIXCS6X_cjs.getAttribution; }
37
37
  });
38
38
  Object.defineProperty(exports, "parsePublishableKey", {
39
39
  enumerable: true,
40
- get: function () { return chunkAI6STRZP_cjs.parsePublishableKey; }
40
+ get: function () { return chunkGIIXCS6X_cjs.parsePublishableKey; }
41
41
  });
42
42
  Object.defineProperty(exports, "trackPurchasePixel", {
43
43
  enumerable: true,
44
- get: function () { return chunkAI6STRZP_cjs.trackPurchasePixel; }
44
+ get: function () { return chunkGIIXCS6X_cjs.trackPurchasePixel; }
45
45
  });
46
46
  Object.defineProperty(exports, "PriceChangedError", {
47
47
  enumerable: true,
48
- get: function () { return chunkT2GQ3DOZ_cjs.PriceChangedError; }
48
+ get: function () { return chunkXIAAWHAY_cjs.PriceChangedError; }
49
49
  });
50
50
  Object.defineProperty(exports, "RateLimitedError", {
51
51
  enumerable: true,
52
- get: function () { return chunkT2GQ3DOZ_cjs.RateLimitedError; }
52
+ get: function () { return chunkXIAAWHAY_cjs.RateLimitedError; }
53
53
  });
54
54
  Object.defineProperty(exports, "STOREFRONT_ERROR_CODES", {
55
55
  enumerable: true,
56
- get: function () { return chunkT2GQ3DOZ_cjs.STOREFRONT_ERROR_CODES; }
56
+ get: function () { return chunkXIAAWHAY_cjs.STOREFRONT_ERROR_CODES; }
57
57
  });
58
58
  Object.defineProperty(exports, "StorefrontConfigError", {
59
59
  enumerable: true,
60
- get: function () { return chunkT2GQ3DOZ_cjs.StorefrontConfigError; }
60
+ get: function () { return chunkXIAAWHAY_cjs.StorefrontConfigError; }
61
61
  });
62
62
  Object.defineProperty(exports, "StorefrontError", {
63
63
  enumerable: true,
64
- get: function () { return chunkT2GQ3DOZ_cjs.StorefrontError; }
64
+ get: function () { return chunkXIAAWHAY_cjs.StorefrontError; }
65
65
  });
66
66
  Object.defineProperty(exports, "StorefrontNetworkError", {
67
67
  enumerable: true,
68
- get: function () { return chunkT2GQ3DOZ_cjs.StorefrontNetworkError; }
68
+ get: function () { return chunkXIAAWHAY_cjs.StorefrontNetworkError; }
69
69
  });
70
70
  Object.defineProperty(exports, "StorefrontTimeoutError", {
71
71
  enumerable: true,
72
- get: function () { return chunkT2GQ3DOZ_cjs.StorefrontTimeoutError; }
72
+ get: function () { return chunkXIAAWHAY_cjs.StorefrontTimeoutError; }
73
73
  });
74
74
  Object.defineProperty(exports, "WrongRegionError", {
75
75
  enumerable: true,
76
- get: function () { return chunkT2GQ3DOZ_cjs.WrongRegionError; }
76
+ get: function () { return chunkXIAAWHAY_cjs.WrongRegionError; }
77
77
  });
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { S as StorefrontRegion } from './errors-B3sinzJq.cjs';
2
- export { A as AnalyticsOptions, a as AnalyticsReporter, B as BookingResult, C as CheckoutMountDescriptor, b as CheckoutSession, c as ConfirmCheckoutSessionInput, d as ConfirmCheckoutSessionRequest, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, P as Page, h as PriceChangedError, R as RateLimitedError, i as RequestOptions, j as STOREFRONT_API_PATH, k as STOREFRONT_ERROR_CODES, l as StorefrontAnalytics, m as StorefrontBooking, n as StorefrontBuilding, o as StorefrontClient, p as StorefrontClientOptions, q as StorefrontConfigError, r as StorefrontContactInput, s as StorefrontError, t as StorefrontErrorCode, u as StorefrontErrorInit, v as StorefrontGuestInput, w as StorefrontListing, x as StorefrontListingSummary, y as StorefrontListingsQuery, z as StorefrontLocation, D as StorefrontNetworkError, E as StorefrontQuote, F as StorefrontQuoteInput, G as StorefrontRatePlanQuote, H as StorefrontReview, I as StorefrontReviewsQuery, J as StorefrontSite, K as StorefrontTimeoutError, T as TrackEvent, W as WrongRegionError, L as analyticsFor, M as createAnalytics, N as createStorefrontClient, O as trackPurchasePixel } from './errors-B3sinzJq.cjs';
1
+ import { S as StorefrontRegion } from './errors-y-BiaVAk.cjs';
2
+ export { A as AnalyticsOptions, a as AnalyticsReporter, B as BookingResult, C as CheckoutMountDescriptor, b as CheckoutSession, c as ConfirmCheckoutSessionInput, d as ConfirmCheckoutSessionRequest, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, P as Page, h as PriceChangedError, R as RateLimitedError, i as RequestOptions, j as STOREFRONT_API_PATH, k as STOREFRONT_ERROR_CODES, l as StorefrontAnalytics, m as StorefrontBooking, n as StorefrontBuilding, o as StorefrontClient, p as StorefrontClientOptions, q as StorefrontConfigError, r as StorefrontContactInput, s as StorefrontError, t as StorefrontErrorCode, u as StorefrontErrorInit, v as StorefrontGuestInput, w as StorefrontListing, x as StorefrontListingSummary, y as StorefrontListingsQuery, z as StorefrontLocation, D as StorefrontNetworkError, E as StorefrontQuote, F as StorefrontQuoteInput, G as StorefrontRatePlanQuote, H as StorefrontReview, I as StorefrontReviewsQuery, J as StorefrontSite, K as StorefrontTimeoutError, T as TrackEvent, W as WrongRegionError, L as analyticsFor, M as createAnalytics, N as createStorefrontClient, O as trackPurchasePixel } from './errors-y-BiaVAk.cjs';
3
3
  import { z } from 'zod';
4
- export { S as StorefrontAvailability, a as StorefrontCalendar, b as StorefrontCalendarDay, c as StorefrontCalendarQuery, d as StorefrontStay, e as StorefrontUnavailableReason } from './availability-CYvqeJ6X.cjs';
4
+ export { S as StorefrontAvailability, a as StorefrontCalendar, b as StorefrontCalendarDay, c as StorefrontCalendarQuery, d as StorefrontStay, e as StorefrontUnavailableReason } from './availability-CnzmxuV3.cjs';
5
5
 
6
6
  declare const attributionTouchSchema: z.ZodObject<{
7
7
  ts: z.ZodISODateTime;
@@ -91,6 +91,13 @@ declare const storefrontAttributionInputSchema: z.ZodObject<{
91
91
  }>;
92
92
  decidedAt: z.ZodNullable<z.ZodISODateTime>;
93
93
  }, z.core.$strip>;
94
+ experiment: z.ZodOptional<z.ZodObject<{
95
+ id: z.ZodUUID;
96
+ variant: z.ZodEnum<{
97
+ a: "a";
98
+ b: "b";
99
+ }>;
100
+ }, z.core.$strip>>;
94
101
  }, z.core.$strip>;
95
102
  type StorefrontAttributionInput = z.infer<typeof storefrontAttributionInputSchema>;
96
103
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { S as StorefrontRegion } from './errors-DPtiZNoK.js';
2
- export { A as AnalyticsOptions, a as AnalyticsReporter, B as BookingResult, C as CheckoutMountDescriptor, b as CheckoutSession, c as ConfirmCheckoutSessionInput, d as ConfirmCheckoutSessionRequest, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, P as Page, h as PriceChangedError, R as RateLimitedError, i as RequestOptions, j as STOREFRONT_API_PATH, k as STOREFRONT_ERROR_CODES, l as StorefrontAnalytics, m as StorefrontBooking, n as StorefrontBuilding, o as StorefrontClient, p as StorefrontClientOptions, q as StorefrontConfigError, r as StorefrontContactInput, s as StorefrontError, t as StorefrontErrorCode, u as StorefrontErrorInit, v as StorefrontGuestInput, w as StorefrontListing, x as StorefrontListingSummary, y as StorefrontListingsQuery, z as StorefrontLocation, D as StorefrontNetworkError, E as StorefrontQuote, F as StorefrontQuoteInput, G as StorefrontRatePlanQuote, H as StorefrontReview, I as StorefrontReviewsQuery, J as StorefrontSite, K as StorefrontTimeoutError, T as TrackEvent, W as WrongRegionError, L as analyticsFor, M as createAnalytics, N as createStorefrontClient, O as trackPurchasePixel } from './errors-DPtiZNoK.js';
1
+ import { S as StorefrontRegion } from './errors-Bp_jmXbA.js';
2
+ export { A as AnalyticsOptions, a as AnalyticsReporter, B as BookingResult, C as CheckoutMountDescriptor, b as CheckoutSession, c as ConfirmCheckoutSessionInput, d as ConfirmCheckoutSessionRequest, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, P as Page, h as PriceChangedError, R as RateLimitedError, i as RequestOptions, j as STOREFRONT_API_PATH, k as STOREFRONT_ERROR_CODES, l as StorefrontAnalytics, m as StorefrontBooking, n as StorefrontBuilding, o as StorefrontClient, p as StorefrontClientOptions, q as StorefrontConfigError, r as StorefrontContactInput, s as StorefrontError, t as StorefrontErrorCode, u as StorefrontErrorInit, v as StorefrontGuestInput, w as StorefrontListing, x as StorefrontListingSummary, y as StorefrontListingsQuery, z as StorefrontLocation, D as StorefrontNetworkError, E as StorefrontQuote, F as StorefrontQuoteInput, G as StorefrontRatePlanQuote, H as StorefrontReview, I as StorefrontReviewsQuery, J as StorefrontSite, K as StorefrontTimeoutError, T as TrackEvent, W as WrongRegionError, L as analyticsFor, M as createAnalytics, N as createStorefrontClient, O as trackPurchasePixel } from './errors-Bp_jmXbA.js';
3
3
  import { z } from 'zod';
4
- export { S as StorefrontAvailability, a as StorefrontCalendar, b as StorefrontCalendarDay, c as StorefrontCalendarQuery, d as StorefrontStay, e as StorefrontUnavailableReason } from './availability-CYvqeJ6X.js';
4
+ export { S as StorefrontAvailability, a as StorefrontCalendar, b as StorefrontCalendarDay, c as StorefrontCalendarQuery, d as StorefrontStay, e as StorefrontUnavailableReason } from './availability-CnzmxuV3.js';
5
5
 
6
6
  declare const attributionTouchSchema: z.ZodObject<{
7
7
  ts: z.ZodISODateTime;
@@ -91,6 +91,13 @@ declare const storefrontAttributionInputSchema: z.ZodObject<{
91
91
  }>;
92
92
  decidedAt: z.ZodNullable<z.ZodISODateTime>;
93
93
  }, z.core.$strip>;
94
+ experiment: z.ZodOptional<z.ZodObject<{
95
+ id: z.ZodUUID;
96
+ variant: z.ZodEnum<{
97
+ a: "a";
98
+ b: "b";
99
+ }>;
100
+ }, z.core.$strip>>;
94
101
  }, z.core.$strip>;
95
102
  type StorefrontAttributionInput = z.infer<typeof storefrontAttributionInputSchema>;
96
103
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { SDK_VERSION, STOREFRONT_API_PATH, STOREFRONT_API_VERSION, analyticsFor, createAnalytics, createStorefrontClient, getAttribution, parsePublishableKey, trackPurchasePixel } from './chunk-MJA3R7NP.js';
2
- export { PriceChangedError, RateLimitedError, STOREFRONT_ERROR_CODES, StorefrontConfigError, StorefrontError, StorefrontNetworkError, StorefrontTimeoutError, WrongRegionError } from './chunk-NNZZWGM2.js';
1
+ export { SDK_VERSION, STOREFRONT_API_PATH, STOREFRONT_API_VERSION, analyticsFor, createAnalytics, createStorefrontClient, getAttribution, parsePublishableKey, trackPurchasePixel } from './chunk-LIBKUMJV.js';
2
+ export { PriceChangedError, RateLimitedError, STOREFRONT_ERROR_CODES, StorefrontConfigError, StorefrontError, StorefrontNetworkError, StorefrontTimeoutError, WrongRegionError } from './chunk-UACP7BZ7.js';
3
3
  import './chunk-6NFURJXI.js';
4
4
  import './chunk-SK5TD73J.js';
package/dist/react.cjs CHANGED
@@ -1,14 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var chunkAI6STRZP_cjs = require('./chunk-AI6STRZP.cjs');
4
- var chunkTBADVD2J_cjs = require('./chunk-TBADVD2J.cjs');
5
- var chunkT2GQ3DOZ_cjs = require('./chunk-T2GQ3DOZ.cjs');
3
+ var chunkGIIXCS6X_cjs = require('./chunk-GIIXCS6X.cjs');
4
+ var chunkRDREYP27_cjs = require('./chunk-RDREYP27.cjs');
5
+ var chunkXIAAWHAY_cjs = require('./chunk-XIAAWHAY.cjs');
6
6
  require('./chunk-LVFRVNT3.cjs');
7
7
  require('./chunk-AIQUVZEI.cjs');
8
8
  var react = require('react');
9
9
  var jsxRuntime = require('react/jsx-runtime');
10
10
 
11
- var SuiteOpContext=react.createContext(null);var ASTRO_PAGE_LOAD="astro:page-load";function SuiteOpProvider({client,children}){const value=react.useMemo(()=>({client,requests:new Map,analytics:chunkAI6STRZP_cjs.analyticsFor(client.publishableKey)}),[client]);const{analytics}=value;react.useEffect(()=>{const onPageLoad=()=>analytics.pageView();onPageLoad();document.addEventListener(ASTRO_PAGE_LOAD,onPageLoad);return ()=>document.removeEventListener(ASTRO_PAGE_LOAD,onPageLoad)},[analytics]);return jsxRuntime.jsx(SuiteOpContext.Provider,{value,children})}function useTrack(){const{analytics}=useSuiteOpContext("useTrack");return analytics.track}function useSuiteOpContext(hookName){const value=react.useContext(SuiteOpContext);if(!value)throw new chunkT2GQ3DOZ_cjs.StorefrontConfigError(`${hookName} must be used inside <SuiteOpProvider>`);return value}function useStorefrontClient(){return useSuiteOpContext("useStorefrontClient").client}var SHARED_TTL_MS=3e4;function toStorefrontError(err){if(err instanceof chunkT2GQ3DOZ_cjs.StorefrontError)return err;return new chunkT2GQ3DOZ_cjs.StorefrontError({status:0,code:"internal_error",message:err instanceof Error?err.message:"Unexpected error",cause:err})}function acquire(requests,key,run){const now=Date.now();for(const[k,entry2]of requests){if(entry2.refs===0&&entry2.settledAt!==null&&now-entry2.settledAt>=SHARED_TTL_MS){requests.delete(k);}}const cached=requests.get(key);if(cached&&(cached.settledAt===null||now-cached.settledAt<SHARED_TTL_MS)){cached.refs+=1;return cached}const controller=new AbortController;const entry={promise:Promise.resolve(),controller,refs:1,settledAt:null};entry.promise=run({signal:controller.signal}).then(data=>{entry.settledAt=Date.now();return data},err=>{if(requests.get(key)===entry)requests.delete(key);throw err});requests.set(key,entry);return entry}function release(requests,key,entry){entry.refs-=1;queueMicrotask(()=>{if(entry.refs>0||entry.settledAt!==null)return;entry.controller.abort();if(requests.get(key)===entry)requests.delete(key);});}function useSharedRead(hookName,key,run){const{requests}=useSuiteOpContext(hookName);const[current,setCurrent]=react.useState(null);const runRef=react.useRef(run);runRef.current=run;react.useEffect(()=>{if(key===null)return;let active=true;const entry=acquire(requests,key,opts=>runRef.current(opts));entry.promise.then(data=>{if(active)setCurrent({key,state:{status:"success",data}});},err=>{if(active&&!entry.controller.signal.aborted){setCurrent({key,state:{status:"error",error:toStorefrontError(err)}});}});return ()=>{active=false;release(requests,key,entry);}},[requests,key]);if(key===null)return {status:"idle"};return current?.key===key?current.state:{status:"loading"}}function useListing(id){const{client}=useSuiteOpContext("useListing");return useSharedRead("useListing",id===null?null:`listing:${id}`,opts=>client.listings.get(id,opts))}function useAvailability(listingId,stay){const{client}=useSuiteOpContext("useAvailability");const key=listingId===null||stay===null?null:`availability:${JSON.stringify([listingId,stay.checkIn,stay.checkOut,stay.guests])}`;return useSharedRead("useAvailability",key,opts=>client.availability.get(listingId,stay,opts))}function useMutationState(){const[state,setState]=react.useState({status:"idle"});const seq=react.useRef(0);const track=react.useCallback(async(work,onError)=>{const mine=++seq.current;setState({status:"loading"});try{const data=await work();if(mine===seq.current)setState({status:"success",data});return data}catch(err){if(mine===seq.current){onError?.(err);setState({status:"error",error:toStorefrontError(err)});}throw err}},[]);return {state,track}}function useQuote(){const{client}=useSuiteOpContext("useQuote");const{state,track}=useMutationState();const quote=react.useCallback(input=>track(()=>client.quotes.create(input)),[client,track]);return {quote,state}}function useCheckoutSession(){const{client}=useSuiteOpContext("useCheckoutSession");const{state,track}=useMutationState();const[priceChanged,setPriceChanged]=react.useState(null);const create=react.useCallback((input,opts)=>{setPriceChanged(null);return track(()=>client.checkoutSessions.create(input,opts),err=>{if(err instanceof chunkT2GQ3DOZ_cjs.PriceChangedError)setPriceChanged(err.quote);})},[client,track]);return {create,session:state,priceChanged}}var EVENTS={"suiteop-checkout:ready":h=>h.onReady?.(),"suiteop-checkout:confirmed":(h,detail)=>h.onComplete(detail),"suiteop-checkout:pending":(h,detail)=>h.onPending?.(detail),"suiteop-checkout:error":(h,detail)=>{const error=detail;if(error.code==="price_changed"&&h.onPriceChanged)h.onPriceChanged();else h.onError?.(error);}};function SuiteOpCheckout(props){const client=useStorefrontClient();const ref=react.useRef(null);const handlers=react.useRef(props);handlers.current=props;react.useEffect(()=>{let active=true;chunkTBADVD2J_cjs.loadCheckout({origin:props.checkoutOrigin}).catch(err=>{if(!active)return;const code=err instanceof chunkT2GQ3DOZ_cjs.StorefrontError?err.code:"checkout_unavailable";handlers.current.onError?.({code,requiresNewSession:false});});return ()=>{active=false;}},[props.checkoutOrigin]);react.useEffect(()=>{const element=ref.current;if(!element)return;const listeners=Object.entries(EVENTS).map(([type,handle])=>{const listener=event=>handle(handlers.current,event.detail);element.addEventListener(type,listener);return [type,listener]});return ()=>{for(const[type,listener]of listeners)element.removeEventListener(type,listener);}},[]);const apiBase=client.baseUrl.endsWith(chunkAI6STRZP_cjs.STOREFRONT_API_PATH)?client.baseUrl.slice(0,-chunkAI6STRZP_cjs.STOREFRONT_API_PATH.length):client.baseUrl;return react.createElement("suiteop-checkout",{ref,class:props.className,"session-id":props.checkoutSessionId,"quote-ref":props.quoteRef,"idempotency-key":props.idempotencyKey,"api-base":apiBase,"publishable-key":client.publishableKey,locale:props.locale})}
11
+ var SuiteOpContext=react.createContext(null);var ASTRO_PAGE_LOAD="astro:page-load";function SuiteOpProvider({client,children}){const value=react.useMemo(()=>({client,requests:new Map,analytics:chunkGIIXCS6X_cjs.analyticsFor(client.publishableKey)}),[client]);const{analytics}=value;react.useEffect(()=>{const onPageLoad=()=>analytics.pageView();onPageLoad();document.addEventListener(ASTRO_PAGE_LOAD,onPageLoad);return ()=>document.removeEventListener(ASTRO_PAGE_LOAD,onPageLoad)},[analytics]);return jsxRuntime.jsx(SuiteOpContext.Provider,{value,children})}function useTrack(){const{analytics}=useSuiteOpContext("useTrack");return analytics.track}function useSuiteOpContext(hookName){const value=react.useContext(SuiteOpContext);if(!value)throw new chunkXIAAWHAY_cjs.StorefrontConfigError(`${hookName} must be used inside <SuiteOpProvider>`);return value}function useStorefrontClient(){return useSuiteOpContext("useStorefrontClient").client}var SHARED_TTL_MS=3e4;function toStorefrontError(err){if(err instanceof chunkXIAAWHAY_cjs.StorefrontError)return err;return new chunkXIAAWHAY_cjs.StorefrontError({status:0,code:"internal_error",message:err instanceof Error?err.message:"Unexpected error",cause:err})}function acquire(requests,key,run){const now=Date.now();for(const[k,entry2]of requests){if(entry2.refs===0&&entry2.settledAt!==null&&now-entry2.settledAt>=SHARED_TTL_MS){requests.delete(k);}}const cached=requests.get(key);if(cached&&(cached.settledAt===null||now-cached.settledAt<SHARED_TTL_MS)){cached.refs+=1;return cached}const controller=new AbortController;const entry={promise:Promise.resolve(),controller,refs:1,settledAt:null};entry.promise=run({signal:controller.signal}).then(data=>{entry.settledAt=Date.now();return data},err=>{if(requests.get(key)===entry)requests.delete(key);throw err});requests.set(key,entry);return entry}function release(requests,key,entry){entry.refs-=1;queueMicrotask(()=>{if(entry.refs>0||entry.settledAt!==null)return;entry.controller.abort();if(requests.get(key)===entry)requests.delete(key);});}function useSharedRead(hookName,key,run){const{requests}=useSuiteOpContext(hookName);const[current,setCurrent]=react.useState(null);const runRef=react.useRef(run);runRef.current=run;react.useEffect(()=>{if(key===null)return;let active=true;const entry=acquire(requests,key,opts=>runRef.current(opts));entry.promise.then(data=>{if(active)setCurrent({key,state:{status:"success",data}});},err=>{if(active&&!entry.controller.signal.aborted){setCurrent({key,state:{status:"error",error:toStorefrontError(err)}});}});return ()=>{active=false;release(requests,key,entry);}},[requests,key]);if(key===null)return {status:"idle"};return current?.key===key?current.state:{status:"loading"}}function useListing(id){const{client}=useSuiteOpContext("useListing");return useSharedRead("useListing",id===null?null:`listing:${id}`,opts=>client.listings.get(id,opts))}function useAvailability(listingId,stay){const{client}=useSuiteOpContext("useAvailability");const key=listingId===null||stay===null?null:`availability:${JSON.stringify([listingId,stay.checkIn,stay.checkOut,stay.guests])}`;return useSharedRead("useAvailability",key,opts=>client.availability.get(listingId,stay,opts))}function useMutationState(){const[state,setState]=react.useState({status:"idle"});const seq=react.useRef(0);const track=react.useCallback(async(work,onError)=>{const mine=++seq.current;setState({status:"loading"});try{const data=await work();if(mine===seq.current)setState({status:"success",data});return data}catch(err){if(mine===seq.current){onError?.(err);setState({status:"error",error:toStorefrontError(err)});}throw err}},[]);return {state,track}}function useQuote(){const{client}=useSuiteOpContext("useQuote");const{state,track}=useMutationState();const quote=react.useCallback(input=>track(()=>client.quotes.create(input)),[client,track]);return {quote,state}}function useCheckoutSession(){const{client}=useSuiteOpContext("useCheckoutSession");const{state,track}=useMutationState();const[priceChanged,setPriceChanged]=react.useState(null);const create=react.useCallback((input,opts)=>{setPriceChanged(null);return track(()=>client.checkoutSessions.create(input,opts),err=>{if(err instanceof chunkXIAAWHAY_cjs.PriceChangedError)setPriceChanged(err.quote);})},[client,track]);return {create,session:state,priceChanged}}var EVENTS={"suiteop-checkout:ready":h=>h.onReady?.(),"suiteop-checkout:confirmed":(h,detail)=>h.onComplete(detail),"suiteop-checkout:pending":(h,detail)=>h.onPending?.(detail),"suiteop-checkout:error":(h,detail)=>{const error=detail;if(error.code==="price_changed"&&h.onPriceChanged)h.onPriceChanged();else h.onError?.(error);}};function SuiteOpCheckout(props){const client=useStorefrontClient();const ref=react.useRef(null);const handlers=react.useRef(props);handlers.current=props;react.useEffect(()=>{let active=true;chunkRDREYP27_cjs.loadCheckout({origin:props.checkoutOrigin}).catch(err=>{if(!active)return;const code=err instanceof chunkXIAAWHAY_cjs.StorefrontError?err.code:"checkout_unavailable";handlers.current.onError?.({code,requiresNewSession:false});});return ()=>{active=false;}},[props.checkoutOrigin]);react.useEffect(()=>{const element=ref.current;if(!element)return;const listeners=Object.entries(EVENTS).map(([type,handle])=>{const listener=event=>handle(handlers.current,event.detail);element.addEventListener(type,listener);return [type,listener]});return ()=>{for(const[type,listener]of listeners)element.removeEventListener(type,listener);}},[]);const apiBase=client.baseUrl.endsWith(chunkGIIXCS6X_cjs.STOREFRONT_API_PATH)?client.baseUrl.slice(0,-chunkGIIXCS6X_cjs.STOREFRONT_API_PATH.length):client.baseUrl;return react.createElement("suiteop-checkout",{ref,class:props.className,"session-id":props.checkoutSessionId,"quote-ref":props.quoteRef,"idempotency-key":props.idempotencyKey,"api-base":apiBase,"publishable-key":client.publishableKey,locale:props.locale})}
12
12
 
13
13
  exports.SuiteOpCheckout = SuiteOpCheckout;
14
14
  exports.SuiteOpProvider = SuiteOpProvider;
package/dist/react.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as StorefrontStay, S as StorefrontAvailability } from './availability-CYvqeJ6X.cjs';
2
- import { s as StorefrontError, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, E as StorefrontQuote, w as StorefrontListing, F as StorefrontQuoteInput, o as StorefrontClient, T as TrackEvent, B as BookingResult } from './errors-B3sinzJq.cjs';
1
+ import { d as StorefrontStay, S as StorefrontAvailability } from './availability-CnzmxuV3.cjs';
2
+ import { s as StorefrontError, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, E as StorefrontQuote, w as StorefrontListing, F as StorefrontQuoteInput, o as StorefrontClient, T as TrackEvent, B as BookingResult } from './errors-y-BiaVAk.cjs';
3
3
  import * as react from 'react';
4
4
  import { ReactNode, JSX } from 'react';
5
5
  import 'zod';
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as StorefrontStay, S as StorefrontAvailability } from './availability-CYvqeJ6X.js';
2
- import { s as StorefrontError, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, E as StorefrontQuote, w as StorefrontListing, F as StorefrontQuoteInput, o as StorefrontClient, T as TrackEvent, B as BookingResult } from './errors-DPtiZNoK.js';
1
+ import { d as StorefrontStay, S as StorefrontAvailability } from './availability-CnzmxuV3.js';
2
+ import { s as StorefrontError, e as CreateCheckoutSessionInput, f as CreateCheckoutSessionOptions, g as CreatedCheckoutSession, E as StorefrontQuote, w as StorefrontListing, F as StorefrontQuoteInput, o as StorefrontClient, T as TrackEvent, B as BookingResult } from './errors-Bp_jmXbA.js';
3
3
  import * as react from 'react';
4
4
  import { ReactNode, JSX } from 'react';
5
5
  import 'zod';
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
- import { analyticsFor, STOREFRONT_API_PATH } from './chunk-MJA3R7NP.js';
2
- import { loadCheckout } from './chunk-ZYDFRRFU.js';
3
- import { StorefrontConfigError, PriceChangedError, StorefrontError } from './chunk-NNZZWGM2.js';
1
+ import { analyticsFor, STOREFRONT_API_PATH } from './chunk-LIBKUMJV.js';
2
+ import { loadCheckout } from './chunk-YFTWGF3L.js';
3
+ import { StorefrontConfigError, PriceChangedError, StorefrontError } from './chunk-UACP7BZ7.js';
4
4
  import './chunk-6NFURJXI.js';
5
5
  import './chunk-SK5TD73J.js';
6
6
  import { createContext, useMemo, useEffect, useContext, useCallback, useState, useRef, createElement } from 'react';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suiteop/storefront",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Typed client, React hooks and headless components for the SuiteOp Storefront API.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://developer.suiteop.com",
@@ -83,10 +83,6 @@
83
83
  "publishConfig": {
84
84
  "access": "public"
85
85
  },
86
- "scripts": {
87
- "prepack": "node scripts/pack-manifest.mjs strip",
88
- "postpack": "node scripts/pack-manifest.mjs restore"
89
- },
90
86
  "dependencies": {
91
87
  "zod": "^4.4.3"
92
88
  },
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkT2GQ3DOZ_cjs = require('./chunk-T2GQ3DOZ.cjs');
4
- var chunkLVFRVNT3_cjs = require('./chunk-LVFRVNT3.cjs');
5
- var chunkAIQUVZEI_cjs = require('./chunk-AIQUVZEI.cjs');
6
- var zod = require('zod');
7
-
8
- var STOREFRONT_CHANNELS=["ai_assistant","paid_search","paid_social","organic_search","organic_social","email","referral","direct"];var AI_ASSISTANT_HOSTS={"chatgpt.com":"chatgpt","chat.openai.com":"chatgpt","perplexity.ai":"perplexity","gemini.google.com":"gemini","copilot.microsoft.com":"copilot","claude.ai":"claude"};var AI_ASSISTANT_SOURCES={"chatgpt.com":"chatgpt",perplexity:"perplexity","perplexity.ai":"perplexity",gemini:"gemini",copilot:"copilot","claude.ai":"claude"};var PAID_CLICKS=["google","microsoft","meta"];var PAID_MEDIUMS=new Set(["cpc","ppc","paid","paidsearch","sem"]);var EMAIL_RE=/newsletter|mailchimp|klaviyo/;var SEARCH_SUFFIXES=["bing.com","duckduckgo.com","search.yahoo.com","baidu.com","ecosia.org","search.brave.com"];var SEARCH_ANY_TLD_RE=/^(?:www\.)?(?:google|yandex)\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SUFFIXES=["facebook.com","instagram.com","t.co","x.com","twitter.com","linkedin.com","tiktok.com","youtube.com","reddit.com"];var SOCIAL_ANY_TLD_RE=/(?:^|\.)pinterest\.[a-z]{2,3}(?:\.[a-z]{2})?$/;var SOCIAL_SOURCES=new Set(["facebook","fb","instagram","ig","meta","twitter","x","linkedin","pinterest","tiktok","youtube","reddit"]);var clean=value=>{const v=value?.trim().toLowerCase();return v?v:null};var hostOf=value=>clean(value)?.replace(/\.$/,"")??null;var hostMatches=(host,suffix)=>host===suffix||host.endsWith(`.${suffix}`);var bareHost=host=>host.replace(/^www\./,"");function aiLabel(host,source){if(host){const suffix=Object.keys(AI_ASSISTANT_HOSTS).find(s=>hostMatches(host,s));if(suffix)return AI_ASSISTANT_HOSTS[suffix]}return source&&Object.hasOwn(AI_ASSISTANT_SOURCES,source)?AI_ASSISTANT_SOURCES[source]:null}var isSearchHost=host=>SEARCH_ANY_TLD_RE.test(host)||SEARCH_SUFFIXES.some(s=>hostMatches(host,s));var isSocialHost=host=>SOCIAL_ANY_TLD_RE.test(host)||SOCIAL_SUFFIXES.some(s=>hostMatches(host,s));function paidClickOf(t){const medium=clean(t.utmMedium);if(t.fbclid&&medium!==null&&PAID_MEDIUMS.has(medium))return "meta";if(t.gclid||t.gbraid||t.wbraid)return "google";if(t.msclkid)return "microsoft";if(t.fbclid)return "meta";return t.paidClick??null}function classifyChannel(t){const source=clean(t.utmSource);const medium=clean(t.utmMedium);const site=bareHost(hostOf(t.siteHost)??"");const ref=hostOf(t.referrerHost);const external=ref&&bareHost(ref)!==site?ref:null;const result=(channel,label=null)=>({channel,source:label??source??external,medium});const socialSource=source!==null&&(SOCIAL_SOURCES.has(source)||isSocialHost(source))||!!(external&&isSocialHost(external));const paidMedium=medium!==null&&PAID_MEDIUMS.has(medium);const searchClick=t.gclid||t.gbraid||t.wbraid||t.msclkid||t.paidClick==="google"||t.paidClick==="microsoft";const metaClick=t.fbclid||t.paidClick==="meta";if(searchClick||paidMedium){return result(socialSource||metaClick&&paidMedium?"paid_social":"paid_search")}if(medium==="email"||EMAIL_RE.test(source??"")||EMAIL_RE.test(medium??"")){return result("email")}const ai=aiLabel(external,source);if(ai)return result("ai_assistant",ai);if(external&&isSearchHost(external))return result("organic_search");if(socialSource||metaClick)return result("organic_social");const anyUtm=[source,medium,t.utmCampaign,t.utmTerm,t.utmContent].some(v=>clean(v??null));if(!external&&!anyUtm)return result("direct");return result("referral")}var consentStateSchema=zod.z.object({analytics:zod.z.boolean(),ads:zod.z.boolean(),source:zod.z.enum(["default","user"]),region:zod.z.enum(["restricted","other"]),decidedAt:zod.z.iso.datetime().max(40).nullable()});function isSafePrivacyUrl(value){if([...value].some(ch=>/\s/.test(ch)||ch.charCodeAt(0)<32))return false;if(value.startsWith("/"))return !value.startsWith("//")&&!value.startsWith("/\\");if(!value.startsWith("https://")||!URL.canParse(value))return false;const url=new URL(value);return url.hostname!==""&&url.username===""&&url.password===""}var STOREFRONT_CONSENT_MODES=["regional","strict"];var modeField=zod.z.enum(STOREFRONT_CONSENT_MODES);var privacyPolicyUrlField=zod.z.string().trim().max(2048,"validation.storefront.privacy_policy_url_invalid").refine(isSafePrivacyUrl,"validation.storefront.privacy_policy_url_invalid").nullable();zod.z.object({mode:modeField.default("regional"),privacyPolicyUrl:privacyPolicyUrlField.default(null)});zod.z.object({siteId:zod.z.uuid(),consentSettings:zod.z.object({mode:modeField.optional(),privacyPolicyUrl:privacyPolicyUrlField.optional()})});var clickId=zod.z.string().min(1).max(512).regex(/^[\w.\-~]+$/);var storable=value=>!value.includes("\0")&&!/\p{Surrogate}/u.test(value);var utm=zod.z.string().max(150).refine(storable).nullable();var attributionTouchSchema=zod.z.object({ts:zod.z.iso.datetime().max(40),landingPath:zod.z.string().max(512).regex(/^\/[^?#]*$/).refine(storable),referrerHost:zod.z.string().max(253).regex(/^[a-z0-9.-]+$/).nullable(),utmSource:utm,utmMedium:utm,utmCampaign:utm,utmTerm:utm,utmContent:utm,gclid:clickId.nullable(),gbraid:clickId.nullable(),wbraid:clickId.nullable(),fbclid:clickId.nullable(),msclkid:clickId.nullable(),paidClick:zod.z.enum(PAID_CLICKS).nullable().default(null)});var attributionIdsSchema=zod.z.object({gaClientId:zod.z.string().max(64).regex(/^\d+\.\d+$/).nullable(),gaSessionId:zod.z.string().max(32).regex(/^\d+$/).nullable(),fbp:zod.z.string().max(128).regex(/^fb\.\d\.\d+\.\d+$/).nullable(),fbc:zod.z.string().max(600).regex(/^fb\.\d\.\d+\.[\w-]+$/).nullable()});var storefrontAttributionInputSchema=zod.z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable(),ids:attributionIdsSchema,consent:consentStateSchema});var STORED_ATTRIBUTION_CHANNELS=[...STOREFRONT_CHANNELS,"ai_agent_mcp"];storefrontAttributionInputSchema.extend({firstChannel:zod.z.enum(STORED_ATTRIBUTION_CHANNELS).nullable(),lastChannel:zod.z.enum(STORED_ATTRIBUTION_CHANNELS),userAgent:zod.z.string().max(512).nullable(),capturedAt:zod.z.iso.datetime()});function withoutClickIds(touch){return {...touch,gclid:null,gbraid:null,wbraid:null,fbclid:null,msclkid:null,paidClick:paidClickOf(touch)}}var emailField=zod.z.string().trim().toLowerCase().pipe(zod.z.email("validation.email_invalid"));zod.z.string().trim().min(1,"validation.email_required").pipe(emailField);var trimmedEmailField=zod.z.string().trim().pipe(zod.z.email("validation.email_invalid"));var requiredTrimmedEmailField=zod.z.string().trim().min(1,"validation.email_required").pipe(trimmedEmailField);zod.z.string().nullish().transform((raw,ctx)=>{if(raw===void 0)return void 0;const trimmed=(raw??"").trim().toLowerCase();if(!trimmed)return null;if(!zod.z.email().safeParse(trimmed).success){ctx.addIssue({code:"custom",message:"validation.email_invalid"});return zod.z.NEVER}return trimmed});var amountMinor=zod.z.number().int().positive();var currency=zod.z.string().length(3);var chargedByHost=zod.z.literal("host");var checkoutMountDescriptorKnownSchema=zod.z.discriminatedUnion("provider",[zod.z.object({provider:zod.z.literal("stripe"),publishableKey:zod.z.string().min(1),stripeAccountId:zod.z.string().nullable(),clientSecret:zod.z.string().min(1),amountMinor,currency}),zod.z.object({provider:zod.z.literal("juspay"),publishableKey:zod.z.string().min(1),providerBaseUrl:zod.z.url(),clientSecret:zod.z.string().min(1),profileId:zod.z.string().min(1),amountMinor,currency}),zod.z.object({provider:zod.z.literal("guesty_pay"),guestyPartnerId:zod.z.string().min(1),paymentProviderId:zod.z.string().min(1),externalListingId:zod.z.string().min(1),pmsQuoteId:zod.z.string().nullable(),amountMinor,currency,chargedBy:chargedByHost.optional()}),zod.z.object({provider:zod.z.literal("pms_stripe"),publishableKey:zod.z.string().min(1),stripeAccountId:zod.z.string().min(1),clientSecret:zod.z.string().min(1),amountMinor,currency,chargedBy:chargedByHost})]);var KNOWN_MOUNT_PROVIDERS=["stripe","juspay","guesty_pay","pms_stripe"];var checkoutMountDescriptorSchema=zod.z.union([checkoutMountDescriptorKnownSchema,zod.z.object({provider:zod.z.string().refine(p=>!KNOWN_MOUNT_PROVIDERS.includes(p))}).loose()]);zod.z.enum(chunkAIQUVZEI_cjs.BE_BOOKING_REQUEST_STATUSES);var bookingRequestStatusResponseSchema=chunkLVFRVNT3_cjs.openEnum(chunkAIQUVZEI_cjs.BE_BOOKING_REQUEST_STATUSES);var checkoutSessionQuoteSchema=zod.z.object({listingId:zod.z.uuid(),checkIn:zod.z.iso.date(),checkOut:zod.z.iso.date(),guests:zod.z.number().int().positive(),ratePlanId:zod.z.string(),totalMinor:zod.z.number().int(),currency:zod.z.string().length(3)});zod.z.object({quoteRef:zod.z.string().min(1).max(4096),ratePlanId:zod.z.string().min(1).max(200).optional(),attribution:zod.z.custom().optional()});var checkoutSessionSchema=zod.z.object({id:zod.z.uuid(),status:bookingRequestStatusResponseSchema,quote:checkoutSessionQuoteSchema,mount:checkoutMountDescriptorSchema.nullable(),chargedBy:chargedByHost.optional(),expiresAt:zod.z.iso.datetime()});var storefrontGuestInputSchema=zod.z.object({firstName:zod.z.string().trim().min(1,"validation.first_name_required").max(100),lastName:zod.z.string().trim().min(1,"validation.last_name_required").max(100),email:requiredTrimmedEmailField,phone:zod.z.string().trim().min(1,"validation.phone_required").max(40)});var storefrontConsentsSchema=zod.z.object({emailMarketing:zod.z.boolean().default(false),smsMarketing:zod.z.boolean().default(false)}).default({emailMarketing:false,smsMarketing:false});zod.z.object({quoteRef:zod.z.string().min(1).max(4096),guest:storefrontGuestInputSchema,consents:storefrontConsentsSchema,paymentMethodId:zod.z.string().min(1).max(255).optional(),language:zod.z.string().max(35).optional().catch(void 0)});var bookingResultSchema=zod.z.object({bookingRequestId:zod.z.uuid(),confirmationToken:zod.z.string(),status:bookingRequestStatusResponseSchema,confirmationCode:zod.z.string().nullable()});var storefrontBookingSchema=zod.z.object({id:zod.z.uuid(),status:bookingRequestStatusResponseSchema,propertyId:zod.z.uuid().nullable(),checkIn:zod.z.iso.date().nullable(),checkOut:zod.z.iso.date().nullable(),guestCount:zod.z.number().int().nullable(),guestFirstName:zod.z.string().nullable(),totalMinor:zod.z.number().int().nullable(),currency:zod.z.string().nullable(),confirmationCode:zod.z.string().nullable()});zod.z.uuid();var storefrontSiteSchema=zod.z.object({id:zod.z.uuid(),name:zod.z.string(),slug:zod.z.string(),isActive:zod.z.boolean(),enableWebChat:zod.z.boolean(),mapEmbedHost:zod.z.string().nullable(),countryCode:zod.z.string().nullish()});var storefrontListingSummarySchema=zod.z.object({id:zod.z.uuid(),buildingId:zod.z.uuid(),sortOrder:zod.z.number().int(),name:zod.z.string(),coverImageUrl:zod.z.string().nullable(),city:zod.z.string().nullable(),state:zod.z.string().nullable(),bedroomCount:zod.z.number().int().nullable(),bathroomCount:zod.z.number().nullable(),maxGuests:zod.z.number().int().nullable(),averageRating:zod.z.number().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),bookable:zod.z.boolean()});var storefrontListingSchema=storefrontListingSummarySchema.extend({buildingSlug:zod.z.string(),buildingAddress:zod.z.unknown(),description:zod.z.string().nullable(),amenities:zod.z.array(zod.z.string()),pictures:zod.z.unknown(),rooms:zod.z.unknown(),houseRules:zod.z.string().nullable(),checkInTime:zod.z.string().nullable(),checkOutTime:zod.z.string().nullable(),beds:zod.z.number().nullable(),fromPriceMinor:zod.z.number().int().nonnegative().nullish(),currency:zod.z.string().nullish(),countryCode:zod.z.string().nullish()});zod.z.object({location:zod.z.string().trim().min(1).max(200).optional(),building:zod.z.uuid().optional(),limit:zod.z.coerce.number().int().min(1).max(100).default(50),offset:zod.z.coerce.number().int().min(0).max(1e4).default(0)});var storefrontBuildingSchema=zod.z.object({id:zod.z.uuid(),locationId:zod.z.uuid().nullable(),nameId:zod.z.uuid().nullable(),descriptionId:zod.z.uuid().nullable(),slug:zod.z.string(),imageId:zod.z.uuid().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),address:zod.z.unknown()});var storefrontLocationSchema=zod.z.object({id:zod.z.uuid(),type:zod.z.string(),parentId:zod.z.uuid().nullable(),nameId:zod.z.uuid().nullable(),slug:zod.z.string().nullable(),imageId:zod.z.uuid().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),address:zod.z.unknown(),sortOrder:zod.z.number().int()});var storefrontReviewSchema=zod.z.object({id:zod.z.uuid(),listingId:zod.z.uuid().nullable(),reviewedAt:zod.z.string().nullable(),rating:zod.z.number().nullable(),publicReview:zod.z.string(),source:zod.z.string().nullable()});zod.z.object({listingId:zod.z.uuid().optional(),limit:zod.z.coerce.number().int().min(1).max(100).default(20),offset:zod.z.coerce.number().int().min(0).max(1e4).default(0)});zod.z.object({name:zod.z.string().trim().min(1,"validation.name_required").max(200,"validation.name_max_length"),email:requiredTrimmedEmailField,subject:zod.z.string().trim().min(1,"validation.title_required").max(300,"validation.title_max_length"),message:zod.z.string().trim().min(10,"validation.message_min_length").max(1e4,"validation.message_max_length")});var storefrontContactResultSchema=zod.z.object({sent:zod.z.literal(true)});zod.z.enum(chunkAIQUVZEI_cjs.STOREFRONT_KEY_ENVIRONMENTS);var STOREFRONT_KEY_RE=new RegExp(`^pk_(${chunkAIQUVZEI_cjs.STOREFRONT_KEY_ENVIRONMENTS.join("|")})_(${chunkAIQUVZEI_cjs.REGIONS.join("|")})_[0-9A-Za-z]{24}$`);function parseStorefrontKey(token){const match=STOREFRONT_KEY_RE.exec(token);if(!match)return null;return {environment:match[1],region:match[2]}}var ORIGIN_HOST_RE=/^(?:[a-z0-9-]+\.)*[a-z0-9-]+$|^\[[0-9a-f:.]+\]$/;function parseUrl(value){try{return new URL(value)}catch{return null}}zod.z.string().refine(value=>{const url=parseUrl(value);if(!url)return false;return (url.protocol==="https:"||url.protocol==="http:")&&url.origin===value&&ORIGIN_HOST_RE.test(url.hostname)},"validation.storefront.origin_invalid");var CLIENT_CONVERSION_EVENT_NAMES=["begin_checkout","generate_lead","sign_up"];var STOREFRONT_EVENT_PATH_MAX=512;var base={eventId:zod.z.uuid(),ts:zod.z.number().int(),path:zod.z.string().max(STOREFRONT_EVENT_PATH_MAX),referrerHost:zod.z.string().max(253).nullable()};var currency2=zod.z.string().length(3).regex(/^[a-z]{3}$/);var storefrontClientEventSchema=zod.z.discriminatedUnion("name",[zod.z.object({...base,name:zod.z.literal("page_view")}),zod.z.object({...base,name:zod.z.literal("view_search_results"),checkIn:chunkLVFRVNT3_cjs.storefrontDateSchema.optional(),checkOut:chunkLVFRVNT3_cjs.storefrontDateSchema.optional(),guests:zod.z.number().int().min(1).max(50).optional(),locationId:zod.z.uuid().optional()}),zod.z.object({...base,name:zod.z.literal("view_item_list"),listName:zod.z.string().max(64),itemCount:zod.z.number().int().min(0).max(500)}),zod.z.object({...base,name:zod.z.literal("view_item"),listingId:zod.z.uuid()}),zod.z.object({...base,name:zod.z.literal("view_quote"),listingId:zod.z.uuid(),valueMinor:zod.z.number().int().nonnegative(),currency:currency2,nights:zod.z.number().int().min(1).max(365)}),zod.z.object({...base,name:zod.z.literal("begin_checkout"),checkoutSessionId:zod.z.uuid()}),zod.z.object({...base,name:zod.z.literal("add_payment_info"),checkoutSessionId:zod.z.uuid()}),zod.z.object({...base,name:zod.z.literal("generate_lead"),formId:zod.z.string().max(64).optional()}),zod.z.object({...base,name:zod.z.literal("sign_up"),method:zod.z.literal("newsletter")})]);var STOREFRONT_EVENT_BATCH_MAX=20;zod.z.object({events:zod.z.array(storefrontClientEventSchema).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});zod.z.object({events:zod.z.array(zod.z.object({eventId:zod.z.uuid(),name:zod.z.enum(CLIENT_CONVERSION_EVENT_NAMES),occurredAt:zod.z.iso.datetime(),pageUrl:zod.z.url({protocol:/^https?$/}).max(2048),checkoutSessionId:zod.z.uuid().nullable(),userAgent:zod.z.string().max(512).nullable(),attribution:storefrontAttributionInputSchema.nullable()})).min(1).max(STOREFRONT_EVENT_BATCH_MAX)});var ATTRIBUTION_COOKIE="so_attr";var ATTRIBUTION_COOKIE_MAX_AGE_SECONDS=90*24*60*60;var COOKIE_SCOPE="Path=/; SameSite=Lax; Secure";var ATTRIBUTION_COOKIE_ATTRIBUTES=`Max-Age=${ATTRIBUTION_COOKIE_MAX_AGE_SECONDS}; ${COOKIE_SCOPE}`;var ATTRIBUTION_COOKIE_MAX_BYTES=3584;var attributionCookieSchema=zod.z.object({first:attributionTouchSchema.nullable(),last:attributionTouchSchema.nullable()});function toBase64Url(text){let binary="";for(const byte of new TextEncoder().encode(text))binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64Url(value){const binary=atob(value.replace(/-/g,"+").replace(/_/g,"/"));return new TextDecoder().decode(Uint8Array.from(binary,ch=>ch.charCodeAt(0)))}function encodeAttributionCookie(value){const encoded=toBase64Url(JSON.stringify(value));return encoded.length>ATTRIBUTION_COOKIE_MAX_BYTES?null:encoded}function serializeAttributionCookie(value){const encoded=encodeAttributionCookie(value);return encoded===null?null:`${ATTRIBUTION_COOKIE}=${encoded}; ${ATTRIBUTION_COOKIE_ATTRIBUTES}`}function decodeAttributionCookie(value){if(!value)return null;return attributionCookieSchema.parse(JSON.parse(fromBase64Url(value)))}function expiredAttributionCookies(cookies,consent){const revoked=[...consent.analytics?[]:[ATTRIBUTION_COOKIE],...consent.ads?[]:["_fbc","_fbp"]];return revoked.filter(name=>readCookie(cookies,name)!==null).map(name=>`${name}=; Max-Age=0; ${COOKIE_SCOPE}`)}function strippedAttributionCookie(held){const clicked=t=>t!==null&&[t.gclid,t.gbraid,t.wbraid,t.fbclid,t.msclkid].some(id=>id!==null);if(!held||!(clicked(held.first)||clicked(held.last)))return null;return serializeAttributionCookie({first:held.first&&withoutClickIds(held.first),last:held.last&&withoutClickIds(held.last)})??`${ATTRIBUTION_COOKIE}=; Max-Age=0; ${COOKIE_SCOPE}`}function readCookie(header,name){if(!header)return null;for(const part of header.split(";")){const eq=part.indexOf("=");if(eq!==-1&&part.slice(0,eq).trim()===name)return part.slice(eq+1).trim()}return null}var MalformedCookieError=class extends Error{constructor(name){super(`${name} is malformed`);this.name="MalformedAttributionError";}};var NO_IDS={gaClientId:null,gaSessionId:null,fbp:null,fbc:null};function matchCookie(cookies,name,re,report){const value=name?readCookie(cookies,name):null;if(!value)return null;const match=re.exec(value);if(!match){report(new MalformedCookieError(name),name);return null}return match.slice(1).filter(Boolean).join(".")}function browserIdsFromCookies(cookies,consent,report){const sessionCookie=cookies.split(";").map(part=>part.split("=")[0].trim()).find(name=>name.startsWith("_ga_"))??null;const ga=consent.analytics;const ads=consent.ads;const ids={gaClientId:ga?matchCookie(cookies,"_ga",/^GA\d\.\d+\.(\d+)\.(\d+)$/,report):null,gaSessionId:ga?matchCookie(cookies,sessionCookie,/^(?:GS1\.\d+\.(\d+)\.|GS2\.\d+\.s(\d+)(?:\$|$))/,report):null,fbp:ads?matchCookie(cookies,"_fbp",/^(fb\.\d\.\d+\.\d+)$/,report):null,fbc:ads?matchCookie(cookies,"_fbc",/^(fb\.\d\.\d+\.[\w-]+)$/,report):null};const parsed=attributionIdsSchema.safeParse(ids);if(parsed.success)return parsed.data;report(parsed.error,"ids");return NO_IDS}var isDirect=touch=>classifyChannel({...touch,siteHost:globalThis.location?.hostname??""}).channel==="direct";var TOUCH_ELEMENT_ID="__suiteop_touch";var CONSENT_EVENT="suiteop:consent";var DENIED={analytics:false,ads:false,source:"default",region:"restricted",decidedAt:null};var defaultReport=(err,where)=>{console.warn(`[suiteop] ignored malformed attribution input (${where})`,err);};function pageConsent(){const read=globalThis.__suiteop?.consent?.get;const parsed=consentStateSchema.safeParse(typeof read==="function"?read():null);return parsed.success?parsed.data:DENIED}function pageTouch(report){const text=document.getElementById(TOUCH_ELEMENT_ID)?.textContent;if(!text)return null;try{return attributionTouchSchema.parse(JSON.parse(text))}catch(err){report(err,TOUCH_ELEMENT_ID);return null}}function storedCookie(cookies,report){try{return decodeAttributionCookie(readCookie(cookies,ATTRIBUTION_COOKIE))}catch(err){report(err,ATTRIBUTION_COOKIE);return null}}function getAttribution(opts={}){if(typeof document==="undefined")return null;const report=opts.report??defaultReport;const cookies=document.cookie;const consent=pageConsent();const stored=consent.analytics?storedCookie(cookies,report):null;const touch=pageTouch(report);const pageIsLast=touch!==null&&!(stored?.last&&(isDirect(touch)||Date.parse(stored.last.ts)>Date.parse(touch.ts)));return {first:stored?.first??touch,last:pageIsLast?touch:stored?.last??null,ids:browserIdsFromCookies(cookies,consent,report),consent}}function watchAttributionConsent(opts={}){if(typeof window==="undefined")return ()=>{};const report=opts.report??defaultReport;const persist=consent=>{if(readCookie(document.cookie,ATTRIBUTION_COOKIE))return;const touch=pageTouch(report);if(!touch)return;const kept=consent.ads?touch:withoutClickIds(touch);const cookie=serializeAttributionCookie({first:kept,last:kept});if(cookie)document.cookie=cookie;};const withdraw=consent=>{for(const cookie of expiredAttributionCookies(document.cookie,consent)){document.cookie=cookie;}if(consent.analytics&&!consent.ads){const stripped=strippedAttributionCookie(storedCookie(document.cookie,report));if(stripped)document.cookie=stripped;}};const initial=pageConsent();let analytics=initial.analytics;if(initial.source==="user")withdraw(initial);if(analytics)persist(initial);const onConsent=event=>{const next=consentStateSchema.safeParse(event.detail);if(!next.success)return;const granted=!analytics&&next.data.analytics;analytics=next.data.analytics;withdraw(next.data);if(granted)persist(next.data);};window.addEventListener(CONSENT_EVENT,onConsent);return ()=>window.removeEventListener(CONSENT_EVENT,onConsent)}var EVENTS_ENDPOINT="/_suiteop/events";var FLUSH_INTERVAL_MS=2e3;var FLUSH_AT_EVENTS=10;var defaultReport2=err=>{console.warn("[suiteop] storefront events could not be sent",err);};function hostOf2(url){try{return new URL(url).hostname||null}catch{return null}}var META_EVENTS={begin_checkout:"InitiateCheckout",generate_lead:"Lead",sign_up:"CompleteRegistration",view_item:"ViewContent",view_search_results:"Search",add_payment_info:"AddPaymentInfo"};var GTAG_SKIP=new Set(["page_view","purchase"]);function mirrorToTags(event){const w=window;if(typeof w.gtag!=="function"&&typeof w.fbq!=="function")return;const consent=pageConsent();const{name,eventId,ts:_ts,path:_path,referrerHost:_ref,...params}=event;if(consent.analytics&&typeof w.gtag==="function"&&!GTAG_SKIP.has(name)){w.gtag("event",name,params);}const metaName=META_EVENTS[name];if(consent.ads&&typeof w.fbq==="function"&&metaName){w.fbq("track",metaName,{},{eventID:eventId});}}function trackPurchasePixel(booking){if(typeof window==="undefined")return;const fbq=window.fbq;if(typeof fbq!=="function"||!pageConsent().ads)return;const amount=typeof booking.totalMinor==="number"&&booking.currency?{value:booking.totalMinor/100,currency:booking.currency.toUpperCase()}:{};fbq("track","Purchase",amount,{eventID:booking.bookingRequestId});}var NOOP={track(){},pageView(){},flush(){},dispose(){}};function createAnalytics(opts){if(typeof window==="undefined")return NOOP;const report=opts.report??defaultReport2;const url=`${EVENTS_ENDPOINT}?key=${encodeURIComponent(opts.publishableKey)}`;let queue=[];let timer=null;let landing=true;let lastViewedHref=null;let disabled=false;let reported=false;const fail=err=>{if(reported)return;reported=true;report(err);};const send=(events,beacon)=>{const body=JSON.stringify({events});if(beacon&&typeof navigator.sendBeacon==="function"&&navigator.sendBeacon(url,body)){return}fetch(url,{method:"POST",body,keepalive:true,credentials:"same-origin",headers:{"content-type":"application/json"}}).then(response=>{if(response.status===404)disabled=true;else if(!response.ok)fail(new Error(`storefront events answered ${response.status}`));}).catch(fail);};const flush=({beacon=false}={})=>{if(timer)clearTimeout(timer);timer=null;if(disabled||queue.length===0)return;const pending=queue;queue=[];for(let i=0;i<pending.length;i+=STOREFRONT_EVENT_BATCH_MAX){send(pending.slice(i,i+STOREFRONT_EVENT_BATCH_MAX),beacon);}};const enqueue=(event,referrerHost)=>{const full={...event,eventId:crypto.randomUUID(),ts:Date.now(),path:location.pathname.slice(0,STOREFRONT_EVENT_PATH_MAX),referrerHost};try{mirrorToTags(full);}catch(err){fail(err);}if(disabled)return;queue.push(full);if(queue.length>=FLUSH_AT_EVENTS)flush();else timer??=setTimeout(()=>flush(),FLUSH_INTERVAL_MS);};const pageView=()=>{if(location.href===lastViewedHref)return;lastViewedHref=location.href;const referrerHost=landing?hostOf2(document.referrer):location.hostname;landing=false;enqueue({name:"page_view"},referrerHost);};const onPageHide=()=>flush({beacon:true});const onPageShow=event=>{if(!event.persisted)return;lastViewedHref=null;pageView();};window.addEventListener("pagehide",onPageHide);window.addEventListener("pageshow",onPageShow);return {track:event=>enqueue(event,location.hostname),pageView,flush,dispose:()=>{flush({beacon:true});window.removeEventListener("pagehide",onPageHide);window.removeEventListener("pageshow",onPageShow);}}}var shared=new Map;function analyticsFor(publishableKey){let instance=shared.get(publishableKey);if(!instance){instance=createAnalytics({publishableKey});if(instance!==NOOP)shared.set(publishableKey,instance);}return instance}function parsePublishableKey(key){if(typeof key==="string"&&key.trim().startsWith("sk_")){throw new chunkT2GQ3DOZ_cjs.StorefrontConfigError("A SuiteOp secret key (sk_\u2026) was passed as the publishable key. Secret keys must never be used in a browser or shipped in site code \u2014 revoke it now, then use a publishable key (pk_live_\u2026 / pk_test_\u2026) from the site settings.")}const parsed=typeof key==="string"?parseStorefrontKey(key.trim()):null;if(!parsed){throw new chunkT2GQ3DOZ_cjs.StorefrontConfigError("Invalid SuiteOp publishable key: expected pk_{live|test}_{us|eu|apac}_ followed by 24 letters or digits.")}return parsed}function defaultApiOrigin({environment,region}){return environment==="live"?`https://api-${region}.suiteop.com`:`https://api-${region}-staging.suiteop.com`}var SDK_VERSION="0.1.0";var STOREFRONT_API_VERSION="2026-09-27";var GET_RETRY_JITTER_MS=300;function buildUrl(base2,spec){const params=new URLSearchParams;for(const[key,value]of Object.entries(spec.query??{})){if(value!==void 0&&value!==null)params.set(key,String(value));}const search=params.toString();return `${base2}${spec.path}${search?`?${search}`:""}`}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason);const onAbort=()=>{clearTimeout(timer);reject(signal?.reason);};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve();},ms);signal?.addEventListener("abort",onAbort,{once:true});})}function parseJson(text){if(!text)return void 0;try{return JSON.parse(text)}catch{return void 0}}function isRetryable(err){return err instanceof chunkT2GQ3DOZ_cjs.StorefrontNetworkError||err instanceof chunkT2GQ3DOZ_cjs.StorefrontError&&err.status>=500}function createTransport(opts){async function attempt(spec){const controller=new AbortController;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;controller.abort(new DOMException("The request timed out","TimeoutError"));},spec.timeoutMs);const onCallerAbort=()=>controller.abort(spec.signal?.reason);if(spec.signal?.aborted)onCallerAbort();else spec.signal?.addEventListener("abort",onCallerAbort,{once:true});try{let response;let text;try{response=await opts.fetch(buildUrl(opts.baseUrl(),spec),{method:spec.method,headers:{...opts.headers,...spec.body===void 0?{}:{"Content-Type":"application/json"},...spec.headers},body:spec.body===void 0?void 0:JSON.stringify(spec.body),signal:controller.signal});text=await response.text();}catch(err){if(spec.signal?.aborted)throw spec.signal.reason;if(timedOut)throw new chunkT2GQ3DOZ_cjs.StorefrontTimeoutError(spec.timeoutMs);throw new chunkT2GQ3DOZ_cjs.StorefrontNetworkError(err)}const body=parseJson(text);if(!response.ok)throw chunkT2GQ3DOZ_cjs.errorFromResponse(response,body);const envelope=body;const meta=envelope?.meta??{};const requestId=typeof meta["requestId"]==="string"?meta["requestId"]:response.headers.get("x-request-id");if(!envelope||typeof envelope!=="object"||!("data"in envelope)){throw new chunkT2GQ3DOZ_cjs.StorefrontError({status:response.status,code:"invalid_response",message:"The Storefront API answered without a data envelope",requestId})}return {status:response.status,requestId,data:envelope.data,meta}}finally{clearTimeout(timer);spec.signal?.removeEventListener("abort",onCallerAbort);}}return {async send(spec){try{return await attempt(spec)}catch(err){if(spec.method!=="GET"||!isRetryable(err))throw err;await sleep(Math.random()*GET_RETRY_JITTER_MS,spec.signal);return attempt(spec)}}}}var STOREFRONT_API_PATH="/api/storefront/v1";var READ_TIMEOUT_MS=1e4;var WRITE_TIMEOUT_MS=2e4;function resolveBaseUrl(baseUrl,origin){if(baseUrl===void 0)return `${origin}${STOREFRONT_API_PATH}`;if(baseUrl==="same-origin"){const pageOrigin=globalThis.location?.origin;if(!pageOrigin||pageOrigin==="null"){throw new chunkT2GQ3DOZ_cjs.StorefrontConfigError("baseUrl 'same-origin' needs a page origin; pass an explicit baseUrl outside a browser.")}return `${pageOrigin}${STOREFRONT_API_PATH}`}let url;try{url=new URL(baseUrl);}catch{throw new chunkT2GQ3DOZ_cjs.StorefrontConfigError(`baseUrl must be an absolute URL or 'same-origin'.`)}const path=url.pathname.replace(/\/+$/,"");return `${url.origin}${path.endsWith(STOREFRONT_API_PATH)?path:`${path}${STOREFRONT_API_PATH}`}`}function uuidV4(){const c=globalThis.crypto;if(typeof c.randomUUID==="function")return c.randomUUID();const b=c.getRandomValues(new Uint8Array(16));b[6]=b[6]&15|64;b[8]=b[8]&63|128;const hex=Array.from(b,x=>x.toString(16).padStart(2,"0")).join("");return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function validate(schema,value,res){const parsed=schema.safeParse(value);if(parsed.success)return parsed.data;throw new chunkT2GQ3DOZ_cjs.StorefrontError({status:res.status,code:"invalid_response",message:"The Storefront API answered a shape this SDK version does not understand",requestId:res.requestId,details:{issues:parsed.error.issues.map(i=>({path:i.path,code:i.code}))}})}var paginationSchema=zod.z.object({total:zod.z.number().int(),limit:zod.z.number().int(),offset:zod.z.number().int()});var seg=value=>encodeURIComponent(value);var slotOf=(quoteRef,ratePlanId)=>`${quoteRef}\0${ratePlanId??""}`;var RELEASED_SESSION_STATUSES=new Set(["expired","cancelled"]);var KEY_BOUND_ELSEWHERE="idempotency_key_reused";function endsSession(err){return err.code==="session_expired"||err.details["requiresNewSession"]===true}var attributionWatched=false;function createStorefrontClient(options){const key=parsePublishableKey(options.publishableKey);const baseUrl=resolveBaseUrl(options.baseUrl,defaultApiOrigin(key));const transport=createTransport({baseUrl:()=>baseUrl,fetch:(input,init)=>(options.fetch??globalThis.fetch)(input,init),headers:{Authorization:`Bearer ${options.publishableKey.trim()}`,Accept:"application/json","X-SuiteOp-SDK":`storefront-js/${SDK_VERSION}`,"X-SuiteOp-Api-Version":STOREFRONT_API_VERSION,...options.locale?{"Accept-Language":options.locale}:{}}});const keySlots=new Map;const sessionSlots=new Map;const release=(slot,key2)=>{if(keySlots.get(slot)===key2)keySlots.delete(slot);};const releaseSession=id=>{const entry=sessionSlots.get(id);if(!entry)return;sessionSlots.delete(id);release(...entry);};if(!attributionWatched&&typeof window!=="undefined"){attributionWatched=true;watchAttributionConsent();}const readTimeoutMs=options.timeoutMs??READ_TIMEOUT_MS;const writeTimeoutMs=options.timeoutMs??WRITE_TIMEOUT_MS;async function get(schema,path,opts,query){const res=await transport.send({method:"GET",path,query,timeoutMs:readTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}async function post(schema,path,body,opts,headers){const res=await transport.send({method:"POST",path,body,headers,timeoutMs:writeTimeoutMs,signal:opts?.signal});return validate(schema,res.data,res)}return {publishableKey:options.publishableKey.trim(),baseUrl,site:{get:opts=>get(storefrontSiteSchema,"/site",opts)},listings:{async list(query,opts){const res=await transport.send({method:"GET",path:"/listings",query:{location:query?.location,building:query?.building,limit:query?.limit,offset:query?.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(zod.z.array(storefrontListingSummarySchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);return {items,...pagination}},get:(id,opts)=>get(storefrontListingSchema,`/listings/${seg(id)}`,opts)},buildings:{list:opts=>get(zod.z.array(storefrontBuildingSchema),"/buildings",opts),get:(id,opts)=>get(storefrontBuildingSchema,`/buildings/${seg(id)}`,opts)},locations:{list:opts=>get(zod.z.array(storefrontLocationSchema),"/locations",opts)},amenities:{list:opts=>get(zod.z.array(zod.z.string()),"/amenities",opts)},reviews:{list:(query,opts)=>get(zod.z.array(storefrontReviewSchema),"/reviews",opts,{listingId:query?.listingId,limit:query?.limit,offset:query?.offset})},availability:{get:(listingId,stay,opts)=>get(chunkLVFRVNT3_cjs.storefrontAvailabilitySchema,`/listings/${seg(listingId)}/availability`,opts,{checkIn:stay.checkIn,checkOut:stay.checkOut,guests:stay.guests})},calendar:{get:(listingId,range,opts)=>get(chunkLVFRVNT3_cjs.storefrontCalendarSchema,`/listings/${seg(listingId)}/calendar`,opts,{from:range.from,to:range.to})},quotes:{create:(input,opts)=>post(chunkT2GQ3DOZ_cjs.storefrontQuoteSchema,"/quotes",input,opts)},checkoutSessions:{async create(input,opts){const slot=slotOf(input.quoteRef,input.ratePlanId);const idempotencyKey=opts?.idempotencyKey??keySlots.get(slot)??uuidV4();keySlots.set(slot,idempotencyKey);const attribution=input.attribution===void 0?getAttribution():input.attribution;const body=attribution?{...input,attribution}:input;try{const created=await post(checkoutSessionSchema,"/checkout-sessions",body,opts,{"Idempotency-Key":idempotencyKey});if(RELEASED_SESSION_STATUSES.has(created.status))release(slot,idempotencyKey);else sessionSlots.set(created.id,[slot,idempotencyKey]);return {...created,idempotencyKey}}catch(err){if(err instanceof chunkT2GQ3DOZ_cjs.StorefrontError){err.details["idempotencyKey"]=idempotencyKey;if(err.code===KEY_BOUND_ELSEWHERE)release(slot,idempotencyKey);}throw err}},get:(id,opts)=>get(checkoutSessionSchema,`/checkout-sessions/${seg(id)}`,opts),async confirm(id,input,opts){try{const result=await post(bookingResultSchema,`/checkout-sessions/${seg(id)}/confirm`,input,opts);return result}catch(err){if(err instanceof chunkT2GQ3DOZ_cjs.StorefrontError&&endsSession(err)){releaseSession(id);}throw err}},forget(quoteRef,ratePlanId){keySlots.delete(slotOf(quoteRef,ratePlanId));}},bookings:{get:(token,opts)=>get(storefrontBookingSchema,`/bookings/${seg(token)}`,opts)},contact:{async create(input,opts){await post(storefrontContactResultSchema,"/contact",input,opts);}}}}
9
-
10
- exports.SDK_VERSION = SDK_VERSION;
11
- exports.STOREFRONT_API_PATH = STOREFRONT_API_PATH;
12
- exports.STOREFRONT_API_VERSION = STOREFRONT_API_VERSION;
13
- exports.analyticsFor = analyticsFor;
14
- exports.createAnalytics = createAnalytics;
15
- exports.createStorefrontClient = createStorefrontClient;
16
- exports.getAttribution = getAttribution;
17
- exports.parsePublishableKey = parsePublishableKey;
18
- exports.trackPurchasePixel = trackPurchasePixel;
@@ -1,6 +0,0 @@
1
- import { withStayRules, storefrontGuestsSchema, storefrontDateSchema } from './chunk-6NFURJXI.js';
2
- import { z } from 'zod';
3
-
4
- var storefrontRatePlanQuoteSchema=z.object({ratePlanId:z.string(),name:z.string(),accommodationMinor:z.number().int(),feesMinor:z.number().int(),taxesMinor:z.number().int(),totalMinor:z.number().int().positive(),currency:z.string().regex(/^[a-z]{3}$/),cancellationPolicy:z.string().nullable(),cancellationFee:z.unknown().optional(),quoteRef:z.string()});withStayRules(z.object({listingId:z.uuid({message:"validation.storefront.listing_invalid"}),checkIn:storefrontDateSchema,checkOut:storefrontDateSchema,guests:storefrontGuestsSchema}));var storefrontQuoteSchema=z.object({quoteRef:z.string(),propertyId:z.uuid(),checkIn:storefrontDateSchema,checkOut:storefrontDateSchema,guests:z.number().int().positive(),ratePlans:z.array(storefrontRatePlanQuoteSchema).min(1),expiresAt:z.iso.datetime()});var STOREFRONT_ERROR_CODES=["wrong_region","origin_not_allowed","origin_required","site_archived","not_bookable","quote_invalid","quote_expired","price_changed","currency_unsupported","payment_declined","session_expired","rate_limited","contact_not_configured","payment_account_unavailable","idempotency_key_required","idempotency_key_reused","payment_mode_unsupported","payment_not_authorized","payment_method_required","site_not_published","UNAUTHORIZED","VALIDATION_ERROR","NOT_FOUND","site_not_found","upstream_timeout","timeout","network","invalid_response","internal_error","checkout_unavailable"];var StorefrontError=class extends Error{name="StorefrontError";status;type;code;requestId;details;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause});this.status=init.status;this.code=init.code;this.type=init.type??init.code;this.requestId=init.requestId??null;this.details=init.details??{};}};var PriceChangedError=class extends StorefrontError{name="PriceChangedError";quote;requiresNewSession;constructor(init){super(init);const raw=this.details["quote"];const parsed=storefrontQuoteSchema.safeParse(raw);this.quote=parsed.success?parsed.data:null;this.requiresNewSession=this.details["requiresNewSession"]===true||raw!=null&&!parsed.success;}};var WrongRegionError=class extends StorefrontError{name="WrongRegionError";region;baseUrl;constructor(init){super(init);const{region,baseUrl}=this.details;this.region=region==="us"||region==="eu"||region==="apac"?region:null;this.baseUrl=typeof baseUrl==="string"?baseUrl:null;}};var RateLimitedError=class extends StorefrontError{name="RateLimitedError";retryAfterSec;scope;constructor(init){super(init);this.retryAfterSec=init.retryAfterSec;const{scope}=this.details;this.scope=scope==="key"||scope==="ip"||scope==="pms"?scope:null;}};var StorefrontTimeoutError=class extends StorefrontError{name="StorefrontTimeoutError";constructor(timeoutMs,requestId=null){super({status:0,code:"timeout",message:`No response within ${timeoutMs} ms`,requestId});}};var StorefrontNetworkError=class extends StorefrontError{name="StorefrontNetworkError";constructor(cause){super({status:0,code:"network",message:"The Storefront API could not be reached",cause});}};var StorefrontConfigError=class extends Error{name="StorefrontConfigError"};function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function parseRetryAfter(header){if(header===null)return null;const seconds=Number(header);if(Number.isFinite(seconds)&&seconds>=0)return Math.ceil(seconds);const at=Date.parse(header);return Number.isNaN(at)?null:Math.max(0,Math.ceil((at-Date.now())/1e3))}function errorFromResponse(response,body){const headerRequestId=response.headers.get("x-request-id");const wire=isRecord(body)&&isRecord(body["error"])?body["error"]:null;const meta=isRecord(body)&&isRecord(body["meta"])?body["meta"]:null;const requestId=typeof meta?.["requestId"]==="string"?meta["requestId"]:headerRequestId;if(!wire||typeof wire["code"]!=="string"){return new StorefrontError({status:response.status,code:"internal_error",message:`The Storefront API answered ${response.status}`,requestId})}const init={status:response.status,code:wire["code"],type:typeof wire["type"]==="string"?wire["type"]:wire["code"],message:typeof wire["message"]==="string"?wire["message"]:wire["code"],requestId,details:isRecord(wire["details"])?wire["details"]:{}};switch(init.code){case "price_changed":return new PriceChangedError(init);case "wrong_region":return new WrongRegionError(init);case "rate_limited":return new RateLimitedError({...init,retryAfterSec:parseRetryAfter(response.headers.get("retry-after"))??parseRetryAfter(typeof init.details?.["retryAfterSeconds"]==="number"?String(init.details["retryAfterSeconds"]):null)});default:return new StorefrontError(init)}}
5
-
6
- export { PriceChangedError, RateLimitedError, STOREFRONT_ERROR_CODES, StorefrontConfigError, StorefrontError, StorefrontNetworkError, StorefrontTimeoutError, WrongRegionError, errorFromResponse, storefrontQuoteSchema };
@@ -1,17 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkLVFRVNT3_cjs = require('./chunk-LVFRVNT3.cjs');
4
- var zod = require('zod');
5
-
6
- var storefrontRatePlanQuoteSchema=zod.z.object({ratePlanId:zod.z.string(),name:zod.z.string(),accommodationMinor:zod.z.number().int(),feesMinor:zod.z.number().int(),taxesMinor:zod.z.number().int(),totalMinor:zod.z.number().int().positive(),currency:zod.z.string().regex(/^[a-z]{3}$/),cancellationPolicy:zod.z.string().nullable(),cancellationFee:zod.z.unknown().optional(),quoteRef:zod.z.string()});chunkLVFRVNT3_cjs.withStayRules(zod.z.object({listingId:zod.z.uuid({message:"validation.storefront.listing_invalid"}),checkIn:chunkLVFRVNT3_cjs.storefrontDateSchema,checkOut:chunkLVFRVNT3_cjs.storefrontDateSchema,guests:chunkLVFRVNT3_cjs.storefrontGuestsSchema}));var storefrontQuoteSchema=zod.z.object({quoteRef:zod.z.string(),propertyId:zod.z.uuid(),checkIn:chunkLVFRVNT3_cjs.storefrontDateSchema,checkOut:chunkLVFRVNT3_cjs.storefrontDateSchema,guests:zod.z.number().int().positive(),ratePlans:zod.z.array(storefrontRatePlanQuoteSchema).min(1),expiresAt:zod.z.iso.datetime()});var STOREFRONT_ERROR_CODES=["wrong_region","origin_not_allowed","origin_required","site_archived","not_bookable","quote_invalid","quote_expired","price_changed","currency_unsupported","payment_declined","session_expired","rate_limited","contact_not_configured","payment_account_unavailable","idempotency_key_required","idempotency_key_reused","payment_mode_unsupported","payment_not_authorized","payment_method_required","site_not_published","UNAUTHORIZED","VALIDATION_ERROR","NOT_FOUND","site_not_found","upstream_timeout","timeout","network","invalid_response","internal_error","checkout_unavailable"];var StorefrontError=class extends Error{name="StorefrontError";status;type;code;requestId;details;constructor(init){super(init.message,init.cause===void 0?void 0:{cause:init.cause});this.status=init.status;this.code=init.code;this.type=init.type??init.code;this.requestId=init.requestId??null;this.details=init.details??{};}};var PriceChangedError=class extends StorefrontError{name="PriceChangedError";quote;requiresNewSession;constructor(init){super(init);const raw=this.details["quote"];const parsed=storefrontQuoteSchema.safeParse(raw);this.quote=parsed.success?parsed.data:null;this.requiresNewSession=this.details["requiresNewSession"]===true||raw!=null&&!parsed.success;}};var WrongRegionError=class extends StorefrontError{name="WrongRegionError";region;baseUrl;constructor(init){super(init);const{region,baseUrl}=this.details;this.region=region==="us"||region==="eu"||region==="apac"?region:null;this.baseUrl=typeof baseUrl==="string"?baseUrl:null;}};var RateLimitedError=class extends StorefrontError{name="RateLimitedError";retryAfterSec;scope;constructor(init){super(init);this.retryAfterSec=init.retryAfterSec;const{scope}=this.details;this.scope=scope==="key"||scope==="ip"||scope==="pms"?scope:null;}};var StorefrontTimeoutError=class extends StorefrontError{name="StorefrontTimeoutError";constructor(timeoutMs,requestId=null){super({status:0,code:"timeout",message:`No response within ${timeoutMs} ms`,requestId});}};var StorefrontNetworkError=class extends StorefrontError{name="StorefrontNetworkError";constructor(cause){super({status:0,code:"network",message:"The Storefront API could not be reached",cause});}};var StorefrontConfigError=class extends Error{name="StorefrontConfigError"};function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function parseRetryAfter(header){if(header===null)return null;const seconds=Number(header);if(Number.isFinite(seconds)&&seconds>=0)return Math.ceil(seconds);const at=Date.parse(header);return Number.isNaN(at)?null:Math.max(0,Math.ceil((at-Date.now())/1e3))}function errorFromResponse(response,body){const headerRequestId=response.headers.get("x-request-id");const wire=isRecord(body)&&isRecord(body["error"])?body["error"]:null;const meta=isRecord(body)&&isRecord(body["meta"])?body["meta"]:null;const requestId=typeof meta?.["requestId"]==="string"?meta["requestId"]:headerRequestId;if(!wire||typeof wire["code"]!=="string"){return new StorefrontError({status:response.status,code:"internal_error",message:`The Storefront API answered ${response.status}`,requestId})}const init={status:response.status,code:wire["code"],type:typeof wire["type"]==="string"?wire["type"]:wire["code"],message:typeof wire["message"]==="string"?wire["message"]:wire["code"],requestId,details:isRecord(wire["details"])?wire["details"]:{}};switch(init.code){case "price_changed":return new PriceChangedError(init);case "wrong_region":return new WrongRegionError(init);case "rate_limited":return new RateLimitedError({...init,retryAfterSec:parseRetryAfter(response.headers.get("retry-after"))??parseRetryAfter(typeof init.details?.["retryAfterSeconds"]==="number"?String(init.details["retryAfterSeconds"]):null)});default:return new StorefrontError(init)}}
7
-
8
- exports.PriceChangedError = PriceChangedError;
9
- exports.RateLimitedError = RateLimitedError;
10
- exports.STOREFRONT_ERROR_CODES = STOREFRONT_ERROR_CODES;
11
- exports.StorefrontConfigError = StorefrontConfigError;
12
- exports.StorefrontError = StorefrontError;
13
- exports.StorefrontNetworkError = StorefrontNetworkError;
14
- exports.StorefrontTimeoutError = StorefrontTimeoutError;
15
- exports.WrongRegionError = WrongRegionError;
16
- exports.errorFromResponse = errorFromResponse;
17
- exports.storefrontQuoteSchema = storefrontQuoteSchema;