@suiteop/storefront 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/astro-content-model.cjs +4 -4
- package/dist/astro-content-model.js +3 -3
- package/dist/astro.cjs +1 -1
- package/dist/astro.d.cts +14 -0
- package/dist/astro.d.ts +14 -0
- package/dist/astro.js +1 -1
- package/dist/checkout.cjs +3 -3
- package/dist/checkout.js +2 -2
- package/dist/{chunk-UQWQPTHO.js → chunk-26HFUROE.js} +1 -1
- package/dist/{chunk-7ZAI36LH.js → chunk-5PBR3IP6.js} +1 -1
- package/dist/{chunk-W5K7IDYN.js → chunk-5QO273QX.js} +1 -1
- package/dist/chunk-6AGNQD7J.js +6 -0
- package/dist/chunk-7FVBUJSF.cjs +19 -0
- package/dist/chunk-IGZVNTD2.cjs +21 -0
- package/dist/{chunk-KKMRPFSY.js → chunk-LCEUS25M.js} +2 -2
- package/dist/{chunk-EVSAMV5K.cjs → chunk-LI7MQZUZ.cjs} +1 -1
- package/dist/{chunk-J5FZ4WDQ.cjs → chunk-OGVX5IEI.cjs} +1 -1
- package/dist/{chunk-A43EXKPY.js → chunk-SCCDAZRA.js} +1 -1
- package/dist/{chunk-JF245QUY.cjs → chunk-TGG3EO2D.cjs} +1 -1
- package/dist/{chunk-PIOB72OP.cjs → chunk-TS7VLM6W.cjs} +3 -3
- package/dist/chunk-UDOZ3H5K.js +9 -0
- package/dist/{chunk-UMCI4YBN.cjs → chunk-XHR5XI3C.cjs} +2 -2
- package/dist/{client-D-M-Bn27.d.cts → client-BW-ELwHu.d.cts} +74 -1
- package/dist/{client-BSAVBRr8.d.ts → client-CCtoE6vX.d.ts} +74 -1
- package/dist/components.cjs +2 -2
- package/dist/components.js +1 -1
- package/dist/config.cjs +3 -3
- package/dist/config.js +3 -3
- package/dist/content.cjs +10 -10
- package/dist/content.d.cts +2 -2
- package/dist/content.d.ts +2 -2
- package/dist/content.js +3 -3
- package/dist/{errors-B80Ivdr8.d.ts → errors-5JYsbYj1.d.cts} +20 -4
- package/dist/{errors-C07dmqcZ.d.cts → errors-DPMLuWdA.d.ts} +20 -4
- package/dist/index.cjs +26 -26
- package/dist/index.d.cts +55 -3
- package/dist/index.d.ts +55 -3
- package/dist/index.js +5 -5
- package/dist/react.cjs +6 -6
- package/dist/react.d.cts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/react.js +7 -7
- package/package.json +1 -1
- package/dist/chunk-7OTUJPMU.js +0 -6
- package/dist/chunk-A6QQYLBV.cjs +0 -21
- package/dist/chunk-BPUS64M7.js +0 -9
- package/dist/chunk-HE4R7P2A.cjs +0 -19
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,34 @@
|
|
|
2
2
|
|
|
3
3
|
Hand-written per release. Tag `storefront-sdk@<version>` on `main` publishes it.
|
|
4
4
|
|
|
5
|
+
## 0.8.0
|
|
6
|
+
|
|
7
|
+
- `suiteop dev` proxies the checkout's locale catalogs (`/checkout/v1/i18n/<locale>.<hash>.json`)
|
|
8
|
+
to the site's host with the bundle, so a non-English checkout shows its own language locally
|
|
9
|
+
instead of falling back to English. Hosted sites are unchanged.
|
|
10
|
+
- `listings.list()` returns `unchecked` on a dated search: how many stays matched every other
|
|
11
|
+
filter but whose calendar was too stale to judge the dates. They are left out unjudged, never
|
|
12
|
+
as taken, so an empty page with `unchecked > 0` means "couldn't check", not "fully booked".
|
|
13
|
+
Absent without dates and from an older API.
|
|
14
|
+
- The build manifest declares `dynamicLocales`: the non-default locales whose i18n fallback is the
|
|
15
|
+
default locale itself, under `routing.fallbackType: 'rewrite'`, the only setup that serves a
|
|
16
|
+
dynamic route at `/<locale>/…`. The platform lists translated dynamic pages and their hreflang
|
|
17
|
+
alternates only for those locales; a build from an older SDK, or a site without the rewrite
|
|
18
|
+
fallback, gets its dynamic pages in the default locale only. It also declares `defaultLocale`,
|
|
19
|
+
so a site with no indexable prerendered page still gets its translated pages listed.
|
|
20
|
+
- `pms_unavailable` (503) joins the error codes: the listing's PMS did not answer in time, or its
|
|
21
|
+
credentials are failing, so availability and prices are unknown right now (`details.reason`:
|
|
22
|
+
`timeout`, `credentials_failing`, `provider_unreachable`). Show it as "availability unknown",
|
|
23
|
+
never as the dates being taken. An older SDK reads it as a plain `StorefrontError` with that code.
|
|
24
|
+
- A GET that answers `pms_unavailable` is no longer retried: the API already waited out the PMS,
|
|
25
|
+
so a retry only doubled the wait before the site could show "availability unknown".
|
|
26
|
+
|
|
27
|
+
## 0.7.1
|
|
28
|
+
|
|
29
|
+
- `site.get()` returns `accountUrl`: the guest portal's rewards page, for an "Account" link, while
|
|
30
|
+
the org runs a loyalty program. Null otherwise, and absent from an older API. An SDK before 0.7.1
|
|
31
|
+
drops it.
|
|
32
|
+
|
|
5
33
|
## 0.7.0
|
|
6
34
|
|
|
7
35
|
- `checkoutSessions.extensions(id, { locale })` reads the custom fields and upsell offers a
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('./chunk-
|
|
5
|
-
require('./chunk-
|
|
3
|
+
var chunkTS7VLM6W_cjs = require('./chunk-TS7VLM6W.cjs');
|
|
4
|
+
require('./chunk-IGZVNTD2.cjs');
|
|
5
|
+
require('./chunk-OGVX5IEI.cjs');
|
|
6
6
|
require('./chunk-EHQFWSP6.cjs');
|
|
7
7
|
var definition = require('virtual:suiteop/content');
|
|
8
8
|
|
|
@@ -10,7 +10,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
10
10
|
|
|
11
11
|
var definition__default = /*#__PURE__*/_interopDefault(definition);
|
|
12
12
|
|
|
13
|
-
var prerender=true;function GET(){return new Response(`${JSON.stringify(
|
|
13
|
+
var prerender=true;function GET(){return new Response(`${JSON.stringify(chunkTS7VLM6W_cjs.parseContentModel(definition__default.default))}
|
|
14
14
|
`,{headers:{"content-type":"application/json"}})}
|
|
15
15
|
|
|
16
16
|
exports.GET = GET;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { parseContentModel } from './chunk-
|
|
2
|
-
import './chunk-
|
|
3
|
-
import './chunk-
|
|
1
|
+
import { parseContentModel } from './chunk-LCEUS25M.js';
|
|
2
|
+
import './chunk-6AGNQD7J.js';
|
|
3
|
+
import './chunk-5QO273QX.js';
|
|
4
4
|
import './chunk-IBCBDAGY.js';
|
|
5
5
|
import definition from 'virtual:suiteop/content';
|
|
6
6
|
|
package/dist/astro.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var zod = require('zod');
|
|
4
4
|
|
|
5
|
-
var SOURCES=[[/^\/listing\/\[[^\]/]+\]$/,"listings"],[/^\/building\/\[[^\]/]+\]$/,"buildings"],[/^\/area\/\[[^\]/]+\]$/,"locations"]];var DECLARABLE_SOURCE=/^(listings|buildings|locations|guides|page|collection:[a-z][a-z0-9_]{0,39})$/;var ERROR_PAGES=new Set(["404","500"]);function normalizePath(pathname){const withSlash=pathname.startsWith("/")?pathname:`/${pathname}`;const trimmed=withSlash.replace(/\/+$/,"").replace(/\/index(\.html)?$/,"");return trimmed===""?"/":trimmed}var ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function decodeEntities(text){return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(whole,ref)=>{if(ref[0]==="#"){const code=ref[1]==="x"||ref[1]==="X"?parseInt(ref.slice(2),16):Number(ref.slice(1));return Number.isFinite(code)&&code>0&&code<=1114111?String.fromCodePoint(code):whole}return ENTITIES[ref.toLowerCase()]??whole})}function metaContent(html,name){for(const[tag]of html.matchAll(/<meta\b[^>]*>/gi)){const attr=key=>new RegExp(`\\b${key}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"i").exec(tag);const tagName=attr("name");if((tagName?.[1]??tagName?.[2])?.toLowerCase()!==name)continue;const content=attr("content");return decodeEntities(content?.[1]??content?.[2]??"")}return null}function localeOf(path,config){const first=path.split("/")[1]??"";return first!==config.defaultLocale&&config.locales.includes(first)?first:config.defaultLocale}function isErrorPage(path,locale,config){const rest=locale===config.defaultLocale?path:path.slice(locale.length+1);return ERROR_PAGES.has(rest.replace(/^\//,""))}async function buildSiteManifest(input){const now=input.now.toISOString();const pages=[];const seen=new Set;for(const pathname of input.pages){const path=normalizePath(pathname);if(seen.has(path))continue;seen.add(path);const locale=localeOf(path,input.config);if(isErrorPage(path,locale,input.config))continue;const html=await input.readHtml(pathname);if(!html)continue;if(/\bnoindex\b/i.test(metaContent(html,"robots")??""))continue;const title=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1];const lastmodRaw=metaContent(html,"suiteop:lastmod");const lastmodMs=lastmodRaw?Date.parse(lastmodRaw):Number.NaN;pages.push({path,locale,title:title?decodeEntities(title.trim()):"",lastmod:Number.isNaN(lastmodMs)?now:new Date(lastmodMs).toISOString()});}pages.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);const dynamicRoutes=[];for(const pattern of input.dynamicRoutes){const source=input.declaredRoutes?.[pattern]??SOURCES.find(([re])=>re.test(pattern))?.[1];if(source&&!dynamicRoutes.some(r=>r.pattern===pattern)){dynamicRoutes.push({pattern,source});}}return {version:1,generatedAt:now,pages,dynamicRoutes}}var sameOriginPath=zod.z.string().regex(/^\/(?![/\\])/);var siteContextSchema=zod.z.object({siteId:zod.z.string().min(1),orgId:zod.z.string().min(1),region:zod.z.enum(["us","eu","apac"]),environment:zod.z.enum(["live","test"]),publishableKey:zod.z.string().regex(/^pk_(live|test)_/),country:zod.z.string().nullable().optional(),apiBasePath:sameOriginPath,apiBaseUrl:zod.z.url({protocol:/^https$/}).nullable().optional(),apiHeaders:zod.z.record(zod.z.string().regex(/^x-suiteop-[a-z0-9-]+$/),zod.z.string()).optional()});function getSiteContext(locals){const props=locals.cfContext?.props;if(typeof props!=="object"||props===null)return null;const parsed=siteContextSchema.safeParse(props);if(!parsed.success)return null;const p=parsed.data;return {...p,country:p.country??null,apiBaseUrl:p.apiBaseUrl??null,apiHeaders:p.apiHeaders??{}}}var SITE_MANIFEST_PATH="_suiteop/manifest.json";var CONTENT_MODEL_PATH="_suiteop/content-model.json";var CONTENT_MODULE_ID="virtual:suiteop/content";var RESOLVED_CONTENT_MODULE_ID=`\0${CONTENT_MODULE_ID}`;function devProxy(env){const apiOrigin=env["SUITEOP_API_ORIGIN"];const edgeOrigin=env["SUITEOP_EDGE_ORIGIN"];const proxy={};if(apiOrigin){proxy["/api/storefront/v1"]={target:apiOrigin,changeOrigin:true,...edgeOrigin?{headers:{origin:edgeOrigin}}:{}};}if(edgeOrigin){proxy["^/checkout/(manifest\\.json|v\\d+(\\.[0-9a-f]+)?\\.js)$"]={target:edgeOrigin,changeOrigin:true};}return proxy}function contentModulePlugin(file){return {name:"@suiteop/storefront:content",resolveId:id=>id===CONTENT_MODULE_ID?RESOLVED_CONTENT_MODULE_ID:void 0,load:id=>id===RESOLVED_CONTENT_MODULE_ID?`export { default } from ${JSON.stringify(file)}`:void 0}}function suiteop(options={}){for(const[pattern,source]of Object.entries(options.routes??{})){if(!DECLARABLE_SOURCE.test(source)){throw new Error(`suiteop(): route ${pattern} has source "${source}"; use listings, buildings, locations, guides, page or collection:<key>.`)}if(source==="page"&&pattern.includes("[")){throw new Error(`suiteop(): route ${pattern} has a parameter, so it is not one page.`)}}let i18n={locales:[],defaultLocale:"en"};let format="directory";let onDemandRoutes=[];return {name:"@suiteop/storefront",hooks:{"astro:config:setup":({command,config,updateConfig,injectRoute})=>{if(options.content){const file=decodeURIComponent(new URL(options.content,config.root).pathname);updateConfig({vite:{plugins:[contentModulePlugin(file)]}});injectRoute({pattern:`/${CONTENT_MODEL_PATH}`,entrypoint:"@suiteop/storefront/astro/content-model",prerender:true});}if(command==="dev"&&process.env["SUITEOP_DEV_PROXY"]==="1"){updateConfig({vite:{server:{proxy:devProxy(process.env),strictPort:true}}});}},"astro:config:done":({config})=>{format=config.build.format;if(config.i18n){i18n={locales:config.i18n.locales.map(l=>typeof l==="string"?l:l.path),defaultLocale:config.i18n.defaultLocale};}},"astro:routes:resolved":({routes})=>{onDemandRoutes=routes.filter(r=>r.type==="page"&&!r.isPrerendered&&r.origin==="project").map(r=>r.pattern);},"astro:build:done":async({dir,pages,logger})=>{const{mkdir,writeFile}=await import('node:fs/promises');const built=await builtHtmlPaths(dir);const all=new Set([...pages.map(p=>`/${p.pathname}`),...built]);const manifest=await buildSiteManifest({pages:[...all],dynamicRoutes:onDemandRoutes,declaredRoutes:options.routes,readHtml:pathname=>readBuiltHtml(dir,pathname,format),now:new Date,config:i18n});const target=new URL(SITE_MANIFEST_PATH,dir);await mkdir(new URL(".",target),{recursive:true});await writeFile(target,`${JSON.stringify(manifest)}
|
|
5
|
+
var SOURCES=[[/^\/listing\/\[[^\]/]+\]$/,"listings"],[/^\/building\/\[[^\]/]+\]$/,"buildings"],[/^\/area\/\[[^\]/]+\]$/,"locations"]];var DECLARABLE_SOURCE=/^(listings|buildings|locations|guides|page|collection:[a-z][a-z0-9_]{0,39})$/;var ERROR_PAGES=new Set(["404","500"]);function normalizePath(pathname){const withSlash=pathname.startsWith("/")?pathname:`/${pathname}`;const trimmed=withSlash.replace(/\/+$/,"").replace(/\/index(\.html)?$/,"");return trimmed===""?"/":trimmed}var ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function decodeEntities(text){return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(whole,ref)=>{if(ref[0]==="#"){const code=ref[1]==="x"||ref[1]==="X"?parseInt(ref.slice(2),16):Number(ref.slice(1));return Number.isFinite(code)&&code>0&&code<=1114111?String.fromCodePoint(code):whole}return ENTITIES[ref.toLowerCase()]??whole})}function metaContent(html,name){for(const[tag]of html.matchAll(/<meta\b[^>]*>/gi)){const attr=key=>new RegExp(`\\b${key}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"i").exec(tag);const tagName=attr("name");if((tagName?.[1]??tagName?.[2])?.toLowerCase()!==name)continue;const content=attr("content");return decodeEntities(content?.[1]??content?.[2]??"")}return null}function localeOf(path,config){const first=path.split("/")[1]??"";return first!==config.defaultLocale&&config.locales.includes(first)?first:config.defaultLocale}function isErrorPage(path,locale,config){const rest=locale===config.defaultLocale?path:path.slice(locale.length+1);return ERROR_PAGES.has(rest.replace(/^\//,""))}async function buildSiteManifest(input){const now=input.now.toISOString();const pages=[];const seen=new Set;for(const pathname of input.pages){const path=normalizePath(pathname);if(seen.has(path))continue;seen.add(path);const locale=localeOf(path,input.config);if(isErrorPage(path,locale,input.config))continue;const html=await input.readHtml(pathname);if(!html)continue;if(/\bnoindex\b/i.test(metaContent(html,"robots")??""))continue;const title=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1];const lastmodRaw=metaContent(html,"suiteop:lastmod");const lastmodMs=lastmodRaw?Date.parse(lastmodRaw):Number.NaN;pages.push({path,locale,title:title?decodeEntities(title.trim()):"",lastmod:Number.isNaN(lastmodMs)?now:new Date(lastmodMs).toISOString()});}pages.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);const dynamicRoutes=[];for(const pattern of input.dynamicRoutes){const source=input.declaredRoutes?.[pattern]??SOURCES.find(([re])=>re.test(pattern))?.[1];if(source&&!dynamicRoutes.some(r=>r.pattern===pattern)){dynamicRoutes.push({pattern,source});}}return {version:1,generatedAt:now,pages,dynamicRoutes,dynamicLocales:dynamicLocales(input.config),defaultLocale:input.config.defaultLocale}}function dynamicLocales(config){const{fallback={},defaultLocale}=config;return config.locales.filter(l=>l!==defaultLocale&&fallback[l]===defaultLocale)}var sameOriginPath=zod.z.string().regex(/^\/(?![/\\])/);var siteContextSchema=zod.z.object({siteId:zod.z.string().min(1),orgId:zod.z.string().min(1),region:zod.z.enum(["us","eu","apac"]),environment:zod.z.enum(["live","test"]),publishableKey:zod.z.string().regex(/^pk_(live|test)_/),country:zod.z.string().nullable().optional(),apiBasePath:sameOriginPath,apiBaseUrl:zod.z.url({protocol:/^https$/}).nullable().optional(),apiHeaders:zod.z.record(zod.z.string().regex(/^x-suiteop-[a-z0-9-]+$/),zod.z.string()).optional()});function getSiteContext(locals){const props=locals.cfContext?.props;if(typeof props!=="object"||props===null)return null;const parsed=siteContextSchema.safeParse(props);if(!parsed.success)return null;const p=parsed.data;return {...p,country:p.country??null,apiBaseUrl:p.apiBaseUrl??null,apiHeaders:p.apiHeaders??{}}}var SITE_MANIFEST_PATH="_suiteop/manifest.json";var CONTENT_MODEL_PATH="_suiteop/content-model.json";var CONTENT_MODULE_ID="virtual:suiteop/content";var RESOLVED_CONTENT_MODULE_ID=`\0${CONTENT_MODULE_ID}`;function devProxy(env){const apiOrigin=env["SUITEOP_API_ORIGIN"];const edgeOrigin=env["SUITEOP_EDGE_ORIGIN"];const proxy={};if(apiOrigin){proxy["/api/storefront/v1"]={target:apiOrigin,changeOrigin:true,...edgeOrigin?{headers:{origin:edgeOrigin}}:{}};}if(edgeOrigin){proxy["^/checkout/(manifest\\.json|v\\d+(\\.[0-9a-f]+)?\\.js|v\\d+/i18n/[a-z]+\\.[0-9a-f]+\\.json)$"]={target:edgeOrigin,changeOrigin:true};}return proxy}function contentModulePlugin(file){return {name:"@suiteop/storefront:content",resolveId:id=>id===CONTENT_MODULE_ID?RESOLVED_CONTENT_MODULE_ID:void 0,load:id=>id===RESOLVED_CONTENT_MODULE_ID?`export { default } from ${JSON.stringify(file)}`:void 0}}function suiteop(options={}){for(const[pattern,source]of Object.entries(options.routes??{})){if(!DECLARABLE_SOURCE.test(source)){throw new Error(`suiteop(): route ${pattern} has source "${source}"; use listings, buildings, locations, guides, page or collection:<key>.`)}if(source==="page"&&pattern.includes("[")){throw new Error(`suiteop(): route ${pattern} has a parameter, so it is not one page.`)}}let i18n={locales:[],defaultLocale:"en"};let format="directory";let onDemandRoutes=[];return {name:"@suiteop/storefront",hooks:{"astro:config:setup":({command,config,updateConfig,injectRoute})=>{if(options.content){const file=decodeURIComponent(new URL(options.content,config.root).pathname);updateConfig({vite:{plugins:[contentModulePlugin(file)]}});injectRoute({pattern:`/${CONTENT_MODEL_PATH}`,entrypoint:"@suiteop/storefront/astro/content-model",prerender:true});}if(command==="dev"&&process.env["SUITEOP_DEV_PROXY"]==="1"){updateConfig({vite:{server:{proxy:devProxy(process.env),strictPort:true}}});}},"astro:config:done":({config})=>{format=config.build.format;if(config.i18n){i18n={locales:config.i18n.locales.map(l=>typeof l==="string"?l:l.path),defaultLocale:config.i18n.defaultLocale,...typeof config.i18n.routing==="object"&&config.i18n.routing.fallbackType==="rewrite"&&{fallback:config.i18n.fallback}};}},"astro:routes:resolved":({routes})=>{onDemandRoutes=routes.filter(r=>r.type==="page"&&!r.isPrerendered&&r.origin==="project").map(r=>r.pattern);},"astro:build:done":async({dir,pages,logger})=>{const{mkdir,writeFile}=await import('node:fs/promises');const built=await builtHtmlPaths(dir);const all=new Set([...pages.map(p=>`/${p.pathname}`),...built]);const manifest=await buildSiteManifest({pages:[...all],dynamicRoutes:onDemandRoutes,declaredRoutes:options.routes,readHtml:pathname=>readBuiltHtml(dir,pathname,format),now:new Date,config:i18n});const target=new URL(SITE_MANIFEST_PATH,dir);await mkdir(new URL(".",target),{recursive:true});await writeFile(target,`${JSON.stringify(manifest)}
|
|
6
6
|
`);logger.info(`suiteop manifest: ${manifest.pages.length} pages, ${manifest.dynamicRoutes.length} dynamic routes`);}}}}async function builtHtmlPaths(dir){const{readdir}=await import('node:fs/promises');const{fileURLToPath}=await import('node:url');const entries=await readdir(fileURLToPath(dir),{recursive:true,withFileTypes:true});const paths=[];for(const entry of entries){if(!entry.isFile()||!entry.name.endsWith(".html"))continue;const rel=`${entry.parentPath}/${entry.name}`.slice(fileURLToPath(dir).length).replace(/\\/g,"/").replace(/^\/+/,"");if(/^(_astro|_suiteop)\//.test(rel))continue;paths.push(`/${rel.replace(/(^|\/)index\.html$/,"$1").replace(/\.html$/,"")}`);}return paths}async function readBuiltHtml(dir,pathname,format){const{readFile}=await import('node:fs/promises');const base=pathname.replace(/^\/+/,"").replace(/\/+$/,"");const candidates=base===""?["index.html"]:format==="file"?[`${base}.html`,`${base}/index.html`]:[`${base}/index.html`,`${base}.html`];for(const candidate of candidates){try{return await readFile(new URL(candidate,dir),"utf8")}catch(err){if(err.code!=="ENOENT")throw err}}return null}
|
|
7
7
|
|
|
8
8
|
exports.CONTENT_MODEL_PATH = CONTENT_MODEL_PATH;
|
package/dist/astro.d.cts
CHANGED
|
@@ -27,6 +27,14 @@ interface SiteManifest {
|
|
|
27
27
|
pattern: string;
|
|
28
28
|
source: SiteManifestSource;
|
|
29
29
|
}[];
|
|
30
|
+
/**
|
|
31
|
+
* The non-default locales every unprefixed dynamic route is also served in (`/<locale>/…`),
|
|
32
|
+
* through the site's i18n `fallbackType: 'rewrite'`. Empty without that fallback: the platform
|
|
33
|
+
* then lists dynamic pages in the default locale only.
|
|
34
|
+
*/
|
|
35
|
+
dynamicLocales: string[];
|
|
36
|
+
/** The site's default locale, the language of its unprefixed paths. */
|
|
37
|
+
defaultLocale: string;
|
|
30
38
|
}
|
|
31
39
|
interface BuildSiteManifestInput {
|
|
32
40
|
/** Pathnames of the prerendered pages, as the build reports them. */
|
|
@@ -45,6 +53,8 @@ interface BuildSiteManifestInput {
|
|
|
45
53
|
config: {
|
|
46
54
|
locales: readonly string[];
|
|
47
55
|
defaultLocale: string;
|
|
56
|
+
/** Locales a missing page is rewritten from: `i18n.fallback` under `fallbackType: 'rewrite'`. */
|
|
57
|
+
fallback?: Readonly<Record<string, string>>;
|
|
48
58
|
};
|
|
49
59
|
}
|
|
50
60
|
declare function buildSiteManifest(input: BuildSiteManifestInput): Promise<SiteManifest>;
|
|
@@ -120,6 +130,10 @@ interface ConfigDoneOptions {
|
|
|
120
130
|
i18n?: {
|
|
121
131
|
locales: (string | I18nLocale)[];
|
|
122
132
|
defaultLocale: string;
|
|
133
|
+
fallback?: Record<string, string>;
|
|
134
|
+
routing?: 'manual' | {
|
|
135
|
+
fallbackType?: 'redirect' | 'rewrite';
|
|
136
|
+
};
|
|
123
137
|
} | undefined;
|
|
124
138
|
build: {
|
|
125
139
|
format: 'file' | 'directory' | 'preserve';
|
package/dist/astro.d.ts
CHANGED
|
@@ -27,6 +27,14 @@ interface SiteManifest {
|
|
|
27
27
|
pattern: string;
|
|
28
28
|
source: SiteManifestSource;
|
|
29
29
|
}[];
|
|
30
|
+
/**
|
|
31
|
+
* The non-default locales every unprefixed dynamic route is also served in (`/<locale>/…`),
|
|
32
|
+
* through the site's i18n `fallbackType: 'rewrite'`. Empty without that fallback: the platform
|
|
33
|
+
* then lists dynamic pages in the default locale only.
|
|
34
|
+
*/
|
|
35
|
+
dynamicLocales: string[];
|
|
36
|
+
/** The site's default locale, the language of its unprefixed paths. */
|
|
37
|
+
defaultLocale: string;
|
|
30
38
|
}
|
|
31
39
|
interface BuildSiteManifestInput {
|
|
32
40
|
/** Pathnames of the prerendered pages, as the build reports them. */
|
|
@@ -45,6 +53,8 @@ interface BuildSiteManifestInput {
|
|
|
45
53
|
config: {
|
|
46
54
|
locales: readonly string[];
|
|
47
55
|
defaultLocale: string;
|
|
56
|
+
/** Locales a missing page is rewritten from: `i18n.fallback` under `fallbackType: 'rewrite'`. */
|
|
57
|
+
fallback?: Readonly<Record<string, string>>;
|
|
48
58
|
};
|
|
49
59
|
}
|
|
50
60
|
declare function buildSiteManifest(input: BuildSiteManifestInput): Promise<SiteManifest>;
|
|
@@ -120,6 +130,10 @@ interface ConfigDoneOptions {
|
|
|
120
130
|
i18n?: {
|
|
121
131
|
locales: (string | I18nLocale)[];
|
|
122
132
|
defaultLocale: string;
|
|
133
|
+
fallback?: Record<string, string>;
|
|
134
|
+
routing?: 'manual' | {
|
|
135
|
+
fallbackType?: 'redirect' | 'rewrite';
|
|
136
|
+
};
|
|
123
137
|
} | undefined;
|
|
124
138
|
build: {
|
|
125
139
|
format: 'file' | 'directory' | 'preserve';
|
package/dist/astro.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
|
|
3
|
-
var SOURCES=[[/^\/listing\/\[[^\]/]+\]$/,"listings"],[/^\/building\/\[[^\]/]+\]$/,"buildings"],[/^\/area\/\[[^\]/]+\]$/,"locations"]];var DECLARABLE_SOURCE=/^(listings|buildings|locations|guides|page|collection:[a-z][a-z0-9_]{0,39})$/;var ERROR_PAGES=new Set(["404","500"]);function normalizePath(pathname){const withSlash=pathname.startsWith("/")?pathname:`/${pathname}`;const trimmed=withSlash.replace(/\/+$/,"").replace(/\/index(\.html)?$/,"");return trimmed===""?"/":trimmed}var ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function decodeEntities(text){return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(whole,ref)=>{if(ref[0]==="#"){const code=ref[1]==="x"||ref[1]==="X"?parseInt(ref.slice(2),16):Number(ref.slice(1));return Number.isFinite(code)&&code>0&&code<=1114111?String.fromCodePoint(code):whole}return ENTITIES[ref.toLowerCase()]??whole})}function metaContent(html,name){for(const[tag]of html.matchAll(/<meta\b[^>]*>/gi)){const attr=key=>new RegExp(`\\b${key}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"i").exec(tag);const tagName=attr("name");if((tagName?.[1]??tagName?.[2])?.toLowerCase()!==name)continue;const content=attr("content");return decodeEntities(content?.[1]??content?.[2]??"")}return null}function localeOf(path,config){const first=path.split("/")[1]??"";return first!==config.defaultLocale&&config.locales.includes(first)?first:config.defaultLocale}function isErrorPage(path,locale,config){const rest=locale===config.defaultLocale?path:path.slice(locale.length+1);return ERROR_PAGES.has(rest.replace(/^\//,""))}async function buildSiteManifest(input){const now=input.now.toISOString();const pages=[];const seen=new Set;for(const pathname of input.pages){const path=normalizePath(pathname);if(seen.has(path))continue;seen.add(path);const locale=localeOf(path,input.config);if(isErrorPage(path,locale,input.config))continue;const html=await input.readHtml(pathname);if(!html)continue;if(/\bnoindex\b/i.test(metaContent(html,"robots")??""))continue;const title=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1];const lastmodRaw=metaContent(html,"suiteop:lastmod");const lastmodMs=lastmodRaw?Date.parse(lastmodRaw):Number.NaN;pages.push({path,locale,title:title?decodeEntities(title.trim()):"",lastmod:Number.isNaN(lastmodMs)?now:new Date(lastmodMs).toISOString()});}pages.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);const dynamicRoutes=[];for(const pattern of input.dynamicRoutes){const source=input.declaredRoutes?.[pattern]??SOURCES.find(([re])=>re.test(pattern))?.[1];if(source&&!dynamicRoutes.some(r=>r.pattern===pattern)){dynamicRoutes.push({pattern,source});}}return {version:1,generatedAt:now,pages,dynamicRoutes}}var sameOriginPath=z.string().regex(/^\/(?![/\\])/);var siteContextSchema=z.object({siteId:z.string().min(1),orgId:z.string().min(1),region:z.enum(["us","eu","apac"]),environment:z.enum(["live","test"]),publishableKey:z.string().regex(/^pk_(live|test)_/),country:z.string().nullable().optional(),apiBasePath:sameOriginPath,apiBaseUrl:z.url({protocol:/^https$/}).nullable().optional(),apiHeaders:z.record(z.string().regex(/^x-suiteop-[a-z0-9-]+$/),z.string()).optional()});function getSiteContext(locals){const props=locals.cfContext?.props;if(typeof props!=="object"||props===null)return null;const parsed=siteContextSchema.safeParse(props);if(!parsed.success)return null;const p=parsed.data;return {...p,country:p.country??null,apiBaseUrl:p.apiBaseUrl??null,apiHeaders:p.apiHeaders??{}}}var SITE_MANIFEST_PATH="_suiteop/manifest.json";var CONTENT_MODEL_PATH="_suiteop/content-model.json";var CONTENT_MODULE_ID="virtual:suiteop/content";var RESOLVED_CONTENT_MODULE_ID=`\0${CONTENT_MODULE_ID}`;function devProxy(env){const apiOrigin=env["SUITEOP_API_ORIGIN"];const edgeOrigin=env["SUITEOP_EDGE_ORIGIN"];const proxy={};if(apiOrigin){proxy["/api/storefront/v1"]={target:apiOrigin,changeOrigin:true,...edgeOrigin?{headers:{origin:edgeOrigin}}:{}};}if(edgeOrigin){proxy["^/checkout/(manifest\\.json|v\\d+(\\.[0-9a-f]+)?\\.js)$"]={target:edgeOrigin,changeOrigin:true};}return proxy}function contentModulePlugin(file){return {name:"@suiteop/storefront:content",resolveId:id=>id===CONTENT_MODULE_ID?RESOLVED_CONTENT_MODULE_ID:void 0,load:id=>id===RESOLVED_CONTENT_MODULE_ID?`export { default } from ${JSON.stringify(file)}`:void 0}}function suiteop(options={}){for(const[pattern,source]of Object.entries(options.routes??{})){if(!DECLARABLE_SOURCE.test(source)){throw new Error(`suiteop(): route ${pattern} has source "${source}"; use listings, buildings, locations, guides, page or collection:<key>.`)}if(source==="page"&&pattern.includes("[")){throw new Error(`suiteop(): route ${pattern} has a parameter, so it is not one page.`)}}let i18n={locales:[],defaultLocale:"en"};let format="directory";let onDemandRoutes=[];return {name:"@suiteop/storefront",hooks:{"astro:config:setup":({command,config,updateConfig,injectRoute})=>{if(options.content){const file=decodeURIComponent(new URL(options.content,config.root).pathname);updateConfig({vite:{plugins:[contentModulePlugin(file)]}});injectRoute({pattern:`/${CONTENT_MODEL_PATH}`,entrypoint:"@suiteop/storefront/astro/content-model",prerender:true});}if(command==="dev"&&process.env["SUITEOP_DEV_PROXY"]==="1"){updateConfig({vite:{server:{proxy:devProxy(process.env),strictPort:true}}});}},"astro:config:done":({config})=>{format=config.build.format;if(config.i18n){i18n={locales:config.i18n.locales.map(l=>typeof l==="string"?l:l.path),defaultLocale:config.i18n.defaultLocale};}},"astro:routes:resolved":({routes})=>{onDemandRoutes=routes.filter(r=>r.type==="page"&&!r.isPrerendered&&r.origin==="project").map(r=>r.pattern);},"astro:build:done":async({dir,pages,logger})=>{const{mkdir,writeFile}=await import('node:fs/promises');const built=await builtHtmlPaths(dir);const all=new Set([...pages.map(p=>`/${p.pathname}`),...built]);const manifest=await buildSiteManifest({pages:[...all],dynamicRoutes:onDemandRoutes,declaredRoutes:options.routes,readHtml:pathname=>readBuiltHtml(dir,pathname,format),now:new Date,config:i18n});const target=new URL(SITE_MANIFEST_PATH,dir);await mkdir(new URL(".",target),{recursive:true});await writeFile(target,`${JSON.stringify(manifest)}
|
|
3
|
+
var SOURCES=[[/^\/listing\/\[[^\]/]+\]$/,"listings"],[/^\/building\/\[[^\]/]+\]$/,"buildings"],[/^\/area\/\[[^\]/]+\]$/,"locations"]];var DECLARABLE_SOURCE=/^(listings|buildings|locations|guides|page|collection:[a-z][a-z0-9_]{0,39})$/;var ERROR_PAGES=new Set(["404","500"]);function normalizePath(pathname){const withSlash=pathname.startsWith("/")?pathname:`/${pathname}`;const trimmed=withSlash.replace(/\/+$/,"").replace(/\/index(\.html)?$/,"");return trimmed===""?"/":trimmed}var ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function decodeEntities(text){return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(whole,ref)=>{if(ref[0]==="#"){const code=ref[1]==="x"||ref[1]==="X"?parseInt(ref.slice(2),16):Number(ref.slice(1));return Number.isFinite(code)&&code>0&&code<=1114111?String.fromCodePoint(code):whole}return ENTITIES[ref.toLowerCase()]??whole})}function metaContent(html,name){for(const[tag]of html.matchAll(/<meta\b[^>]*>/gi)){const attr=key=>new RegExp(`\\b${key}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"i").exec(tag);const tagName=attr("name");if((tagName?.[1]??tagName?.[2])?.toLowerCase()!==name)continue;const content=attr("content");return decodeEntities(content?.[1]??content?.[2]??"")}return null}function localeOf(path,config){const first=path.split("/")[1]??"";return first!==config.defaultLocale&&config.locales.includes(first)?first:config.defaultLocale}function isErrorPage(path,locale,config){const rest=locale===config.defaultLocale?path:path.slice(locale.length+1);return ERROR_PAGES.has(rest.replace(/^\//,""))}async function buildSiteManifest(input){const now=input.now.toISOString();const pages=[];const seen=new Set;for(const pathname of input.pages){const path=normalizePath(pathname);if(seen.has(path))continue;seen.add(path);const locale=localeOf(path,input.config);if(isErrorPage(path,locale,input.config))continue;const html=await input.readHtml(pathname);if(!html)continue;if(/\bnoindex\b/i.test(metaContent(html,"robots")??""))continue;const title=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1];const lastmodRaw=metaContent(html,"suiteop:lastmod");const lastmodMs=lastmodRaw?Date.parse(lastmodRaw):Number.NaN;pages.push({path,locale,title:title?decodeEntities(title.trim()):"",lastmod:Number.isNaN(lastmodMs)?now:new Date(lastmodMs).toISOString()});}pages.sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);const dynamicRoutes=[];for(const pattern of input.dynamicRoutes){const source=input.declaredRoutes?.[pattern]??SOURCES.find(([re])=>re.test(pattern))?.[1];if(source&&!dynamicRoutes.some(r=>r.pattern===pattern)){dynamicRoutes.push({pattern,source});}}return {version:1,generatedAt:now,pages,dynamicRoutes,dynamicLocales:dynamicLocales(input.config),defaultLocale:input.config.defaultLocale}}function dynamicLocales(config){const{fallback={},defaultLocale}=config;return config.locales.filter(l=>l!==defaultLocale&&fallback[l]===defaultLocale)}var sameOriginPath=z.string().regex(/^\/(?![/\\])/);var siteContextSchema=z.object({siteId:z.string().min(1),orgId:z.string().min(1),region:z.enum(["us","eu","apac"]),environment:z.enum(["live","test"]),publishableKey:z.string().regex(/^pk_(live|test)_/),country:z.string().nullable().optional(),apiBasePath:sameOriginPath,apiBaseUrl:z.url({protocol:/^https$/}).nullable().optional(),apiHeaders:z.record(z.string().regex(/^x-suiteop-[a-z0-9-]+$/),z.string()).optional()});function getSiteContext(locals){const props=locals.cfContext?.props;if(typeof props!=="object"||props===null)return null;const parsed=siteContextSchema.safeParse(props);if(!parsed.success)return null;const p=parsed.data;return {...p,country:p.country??null,apiBaseUrl:p.apiBaseUrl??null,apiHeaders:p.apiHeaders??{}}}var SITE_MANIFEST_PATH="_suiteop/manifest.json";var CONTENT_MODEL_PATH="_suiteop/content-model.json";var CONTENT_MODULE_ID="virtual:suiteop/content";var RESOLVED_CONTENT_MODULE_ID=`\0${CONTENT_MODULE_ID}`;function devProxy(env){const apiOrigin=env["SUITEOP_API_ORIGIN"];const edgeOrigin=env["SUITEOP_EDGE_ORIGIN"];const proxy={};if(apiOrigin){proxy["/api/storefront/v1"]={target:apiOrigin,changeOrigin:true,...edgeOrigin?{headers:{origin:edgeOrigin}}:{}};}if(edgeOrigin){proxy["^/checkout/(manifest\\.json|v\\d+(\\.[0-9a-f]+)?\\.js|v\\d+/i18n/[a-z]+\\.[0-9a-f]+\\.json)$"]={target:edgeOrigin,changeOrigin:true};}return proxy}function contentModulePlugin(file){return {name:"@suiteop/storefront:content",resolveId:id=>id===CONTENT_MODULE_ID?RESOLVED_CONTENT_MODULE_ID:void 0,load:id=>id===RESOLVED_CONTENT_MODULE_ID?`export { default } from ${JSON.stringify(file)}`:void 0}}function suiteop(options={}){for(const[pattern,source]of Object.entries(options.routes??{})){if(!DECLARABLE_SOURCE.test(source)){throw new Error(`suiteop(): route ${pattern} has source "${source}"; use listings, buildings, locations, guides, page or collection:<key>.`)}if(source==="page"&&pattern.includes("[")){throw new Error(`suiteop(): route ${pattern} has a parameter, so it is not one page.`)}}let i18n={locales:[],defaultLocale:"en"};let format="directory";let onDemandRoutes=[];return {name:"@suiteop/storefront",hooks:{"astro:config:setup":({command,config,updateConfig,injectRoute})=>{if(options.content){const file=decodeURIComponent(new URL(options.content,config.root).pathname);updateConfig({vite:{plugins:[contentModulePlugin(file)]}});injectRoute({pattern:`/${CONTENT_MODEL_PATH}`,entrypoint:"@suiteop/storefront/astro/content-model",prerender:true});}if(command==="dev"&&process.env["SUITEOP_DEV_PROXY"]==="1"){updateConfig({vite:{server:{proxy:devProxy(process.env),strictPort:true}}});}},"astro:config:done":({config})=>{format=config.build.format;if(config.i18n){i18n={locales:config.i18n.locales.map(l=>typeof l==="string"?l:l.path),defaultLocale:config.i18n.defaultLocale,...typeof config.i18n.routing==="object"&&config.i18n.routing.fallbackType==="rewrite"&&{fallback:config.i18n.fallback}};}},"astro:routes:resolved":({routes})=>{onDemandRoutes=routes.filter(r=>r.type==="page"&&!r.isPrerendered&&r.origin==="project").map(r=>r.pattern);},"astro:build:done":async({dir,pages,logger})=>{const{mkdir,writeFile}=await import('node:fs/promises');const built=await builtHtmlPaths(dir);const all=new Set([...pages.map(p=>`/${p.pathname}`),...built]);const manifest=await buildSiteManifest({pages:[...all],dynamicRoutes:onDemandRoutes,declaredRoutes:options.routes,readHtml:pathname=>readBuiltHtml(dir,pathname,format),now:new Date,config:i18n});const target=new URL(SITE_MANIFEST_PATH,dir);await mkdir(new URL(".",target),{recursive:true});await writeFile(target,`${JSON.stringify(manifest)}
|
|
4
4
|
`);logger.info(`suiteop manifest: ${manifest.pages.length} pages, ${manifest.dynamicRoutes.length} dynamic routes`);}}}}async function builtHtmlPaths(dir){const{readdir}=await import('node:fs/promises');const{fileURLToPath}=await import('node:url');const entries=await readdir(fileURLToPath(dir),{recursive:true,withFileTypes:true});const paths=[];for(const entry of entries){if(!entry.isFile()||!entry.name.endsWith(".html"))continue;const rel=`${entry.parentPath}/${entry.name}`.slice(fileURLToPath(dir).length).replace(/\\/g,"/").replace(/^\/+/,"");if(/^(_astro|_suiteop)\//.test(rel))continue;paths.push(`/${rel.replace(/(^|\/)index\.html$/,"$1").replace(/\.html$/,"")}`);}return paths}async function readBuiltHtml(dir,pathname,format){const{readFile}=await import('node:fs/promises');const base=pathname.replace(/^\/+/,"").replace(/\/+$/,"");const candidates=base===""?["index.html"]:format==="file"?[`${base}.html`,`${base}/index.html`]:[`${base}/index.html`,`${base}.html`];for(const candidate of candidates){try{return await readFile(new URL(candidate,dir),"utf8")}catch(err){if(err.code!=="ENOENT")throw err}}return null}
|
|
5
5
|
|
|
6
6
|
export { CONTENT_MODEL_PATH, SITE_MANIFEST_PATH, buildSiteManifest, contentModulePlugin, devProxy, getSiteContext, suiteop };
|
package/dist/checkout.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('./chunk-
|
|
3
|
+
var chunkXHR5XI3C_cjs = require('./chunk-XHR5XI3C.cjs');
|
|
4
|
+
require('./chunk-OGVX5IEI.cjs');
|
|
5
5
|
require('./chunk-EHQFWSP6.cjs');
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
Object.defineProperty(exports, "loadCheckout", {
|
|
10
10
|
enumerable: true,
|
|
11
|
-
get: function () { return
|
|
11
|
+
get: function () { return chunkXHR5XI3C_cjs.loadCheckout; }
|
|
12
12
|
});
|
package/dist/checkout.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { loadCheckout } from './chunk-
|
|
2
|
-
import './chunk-
|
|
1
|
+
export { loadCheckout } from './chunk-5PBR3IP6.js';
|
|
2
|
+
import './chunk-5QO273QX.js';
|
|
3
3
|
import './chunk-IBCBDAGY.js';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var REGIONS=["us","eu","apac","demo"];var BE_BOOKING_REQUEST_STATUSES=["inquiry","processing","confirmed","failed","expired","pending_pms_sync","pending_payment","authorized","reserved","cancelled"];var STOREFRONT_KEY_ENVIRONMENTS=["live","test"];var GOOGLE_FONTS=["inter","montserrat","poppins","raleway","nunito","work_sans","mulish","barlow","jost","bitter","archivo","public_sans","gantari","anybody","lato","playfair_display","karla","reddit_sans","overpass","roboto","open_sans","merriweather","outfit"];var STOREFRONT_FONTS=[...GOOGLE_FONTS,"fraunces","dm_sans","cormorant_garamond","eb_garamond","lora","crimson_pro","source_serif_4","ibm_plex_serif","manrope","plus_jakarta_sans","space_grotesk","ibm_plex_sans","libre_franklin","josefin_sans"];var STOREFRONT_FONT_FAMILIES={inter:"Inter",montserrat:"Montserrat",poppins:"Poppins",raleway:"Raleway",nunito:"Nunito",work_sans:"Work Sans",mulish:"Mulish",barlow:"Barlow",jost:"Jost",bitter:"Bitter",archivo:"Archivo",public_sans:"Public Sans",gantari:"Gantari",anybody:"Anybody",lato:"Lato",playfair_display:"Playfair Display",karla:"Karla",reddit_sans:"Reddit Sans",overpass:"Overpass",roboto:"Roboto",open_sans:"Open Sans",merriweather:"Merriweather",outfit:"Outfit",fraunces:"Fraunces",dm_sans:"DM Sans",cormorant_garamond:"Cormorant Garamond",eb_garamond:"EB Garamond",lora:"Lora",crimson_pro:"Crimson Pro",source_serif_4:"Source Serif 4",ibm_plex_serif:"IBM Plex Serif",manrope:"Manrope",plus_jakarta_sans:"Plus Jakarta Sans",space_grotesk:"Space Grotesk",ibm_plex_sans:"IBM Plex Sans",libre_franklin:"Libre Franklin",josefin_sans:"Josefin Sans"};
|
|
1
|
+
var REGIONS=["us","eu","apac","demo"];var BE_BOOKING_REQUEST_STATUSES=["inquiry","processing","confirmed","failed","expired","pending_pms_sync","pending_payment","authorized","reserved","cancelled"];var STOREFRONT_KEY_ENVIRONMENTS=["live","test"];var GOOGLE_FONTS=["inter","montserrat","poppins","raleway","nunito","work_sans","mulish","barlow","jost","bitter","archivo","public_sans","gantari","anybody","lato","playfair_display","karla","reddit_sans","overpass","roboto","open_sans","merriweather","outfit"];var STOREFRONT_FONTS=[...GOOGLE_FONTS,"fraunces","dm_sans","cormorant_garamond","eb_garamond","lora","crimson_pro","source_serif_4","ibm_plex_serif","manrope","plus_jakarta_sans","space_grotesk","ibm_plex_sans","libre_franklin","josefin_sans"];var STOREFRONT_FONT_FAMILIES={inter:"Inter",montserrat:"Montserrat",poppins:"Poppins",raleway:"Raleway",nunito:"Nunito",work_sans:"Work Sans",mulish:"Mulish",barlow:"Barlow",jost:"Jost",bitter:"Bitter",archivo:"Archivo",public_sans:"Public Sans",gantari:"Gantari",anybody:"Anybody",lato:"Lato",playfair_display:"Playfair Display",karla:"Karla",reddit_sans:"Reddit Sans",overpass:"Overpass",roboto:"Roboto",open_sans:"Open Sans",merriweather:"Merriweather",outfit:"Outfit",fraunces:"Fraunces",dm_sans:"DM Sans",cormorant_garamond:"Cormorant Garamond",eb_garamond:"EB Garamond",lora:"Lora",crimson_pro:"Crimson Pro",source_serif_4:"Source Serif 4",ibm_plex_serif:"IBM Plex Serif",manrope:"Manrope",plus_jakarta_sans:"Plus Jakarta Sans",space_grotesk:"Space Grotesk",ibm_plex_sans:"IBM Plex Sans",libre_franklin:"Libre Franklin",josefin_sans:"Josefin Sans"};var INFORMATION_ONLY_REQUIREMENT_TYPES=["guidance"];new Set(INFORMATION_ONLY_REQUIREMENT_TYPES);
|
|
2
2
|
|
|
3
3
|
export { BE_BOOKING_REQUEST_STATUSES, REGIONS, STOREFRONT_FONTS, STOREFRONT_FONT_FAMILIES, STOREFRONT_KEY_ENVIRONMENTS };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { StorefrontError } from './chunk-
|
|
1
|
+
import { StorefrontError } from './chunk-5QO273QX.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 { withStayRules, storefrontGuestsSchema, storefrontDateSchema } from './chunk-IBCBDAGY.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
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","bookings_closed","extras_invalid","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)}}
|
|
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","pms_unavailable","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","bookings_closed","extras_invalid","offer_code_refused","loyalty_points_invalid","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
5
|
|
|
6
6
|
export { PriceChangedError, RateLimitedError, STOREFRONT_ERROR_CODES, StorefrontConfigError, StorefrontError, StorefrontNetworkError, StorefrontTimeoutError, WrongRegionError, errorFromResponse, storefrontQuoteSchema };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { withStayRules, storefrontDateSchema } from './chunk-IBCBDAGY.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
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 storefrontIdSchema=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(),mapEmbedToken:z.string().nullish(),countryCode:z.string().nullish(),bookingsOpen:z.boolean().optional(),accountUrl: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(),fromPriceMinor:z.number().int().nonnegative().nullish(),currency:z.string().nullish()});var storefrontImageSchema=z.object({url:z.string(),alt:z.string().nullable(),width:z.number().int().nullable(),height:z.number().int().nullable()});var storefrontListingSchema=storefrontListingSummarySchema.extend({buildingSlug:z.string(),buildingAddress:z.unknown(),description:z.string().nullable(),amenities:z.array(z.string()),pictures:z.unknown(),images:z.array(storefrontImageSchema).optional(),rooms:z.unknown(),houseRules:z.string().nullable(),checkInTime:z.string().nullable(),checkOutTime:z.string().nullable(),beds:z.number().nullable(),countryCode:z.string().nullish(),reviewCount:z.number().int().nonnegative().nullish(),reviewRating:z.number().nullish()});var STOREFRONT_LISTING_SORTS=["recommended","price_asc","price_desc","rating"];var asList=value=>value===void 0?void 0:Array.isArray(value)?value:[value];var boundsSchema=z.string().transform(value=>value.split(",").map(part=>part.trim()===""?NaN:Number(part))).pipe(z.tuple([z.number().min(-90).max(90),z.number().min(-180).max(180),z.number().min(-90).max(90),z.number().min(-180).max(180)]).refine(([swLat,,neLat])=>swLat<=neLat)).transform(([swLat,swLng,neLat,neLng])=>({swLat,swLng,neLat,neLng}));var listingsStaySchema=withStayRules(z.object({checkIn:storefrontDateSchema,checkOut:storefrontDateSchema}));z.object({location:z.preprocess(value=>asList(value)?.flatMap(v=>typeof v==="string"?v.split(","):[v]),z.array(z.string().trim().min(1).max(200)).min(1).max(50).optional()).optional(),building:z.uuid().optional(),guests:z.coerce.number().int().min(1).max(100).optional(),bedrooms:z.coerce.number().int().min(0).max(50).optional(),currency:z.string().trim().regex(/^[A-Za-z]{3}$/).transform(value=>value.toLowerCase()).optional(),priceMin:z.coerce.number().int().min(0).optional(),priceMax:z.coerce.number().int().min(0).optional(),amenities:z.preprocess(asList,z.array(z.string().trim().min(1).max(200)).min(1).max(30).optional()).optional(),bounds:boundsSchema.optional(),checkIn:storefrontDateSchema.optional(),checkOut:storefrontDateSchema.optional(),sort:z.enum(STOREFRONT_LISTING_SORTS).optional(),facets:z.enum(["0","1","true","false"]).transform(value=>value==="1"||value==="true").optional(),limit:z.coerce.number().int().min(1).max(100).default(50),offset:z.coerce.number().int().min(0).max(1e4).default(0)}).refine(q=>q.currency!==void 0||q.priceMin===void 0&&q.priceMax===void 0,{path:["currency"],message:"validation.required"}).refine(q=>q.priceMin===void 0||q.priceMax===void 0||q.priceMin<=q.priceMax,{path:["priceMax"],message:"validation.invalid"}).superRefine((q,ctx)=>{if(q.checkIn===void 0&&q.checkOut===void 0)return;if(q.checkIn===void 0||q.checkOut===void 0){const path=q.checkIn===void 0?"checkIn":"checkOut";ctx.addIssue({code:"custom",path:[path],message:"validation.required"});return}const stay=listingsStaySchema.safeParse({checkIn:q.checkIn,checkOut:q.checkOut});for(const issue of stay.error?.issues??[]){ctx.addIssue({code:"custom",path:issue.path,message:issue.message});}});var storefrontListingFacetsSchema=z.object({total:z.number().int(),areas:z.array(z.object({id:z.uuid(),slug:z.string().nullable(),count:z.number().int()})),bedrooms:z.array(z.object({bedrooms:z.number().int(),count:z.number().int()})),price:z.object({min:z.number().int(),max:z.number().int(),currency:z.string().nullable(),buckets:z.array(z.number().int()).length(24)}).nullable()});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(),name:z.string().nullish(),description:z.string().nullish(),imageUrl:z.string().nullish(),images:z.array(storefrontImageSchema).nullish(),sortOrder:z.number().int().nullish(),listingCount:z.number().int().nullish(),fields:z.record(z.string(),z.record(z.string(),z.unknown())).nullish()});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(),name:z.string().nullish(),description:z.string().nullish(),imageUrl:z.string().nullish(),images:z.array(storefrontImageSchema).nullish(),buildingCount:z.number().int().nullish(),fields:z.record(z.string(),z.record(z.string(),z.unknown())).nullish()});z.object({locale:z.string().max(35).optional().catch(void 0)});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)});var storefrontContentRefSchema=z.object({kind:z.string(),id:z.uuid(),slug:z.string().nullable()});var storefrontContentItemSchema=z.object({id:z.uuid(),type:z.string(),slug:z.string().nullable(),publishedAt:z.string().nullable(),updatedAt:z.string(),sortOrder:z.number().int(),fields:z.record(z.string(),z.unknown())});var storefrontContentFieldDefSchema=z.object({key:z.string(),type:z.string()}).catchall(z.unknown());var storefrontContentModelSchema=z.object({version:z.number().int(),types:z.array(z.object({key:z.string(),kind:z.string(),fields:z.array(storefrontContentFieldDefSchema)}).catchall(z.unknown()))});z.object({limit:z.coerce.number().int().min(1).max(100).default(20),offset:z.coerce.number().int().min(0).max(1e4).default(0),locale:z.string().max(35).optional().catch(void 0)});z.string().regex(/^[a-z][a-z0-9_]{0,39}$/);z.string().min(1).max(120).regex(/^[a-z0-9-]+$/);
|
|
5
|
+
|
|
6
|
+
export { requiredTrimmedEmailField, storefrontBuildingSchema, storefrontContactResultSchema, storefrontContentItemSchema, storefrontContentModelSchema, storefrontContentRefSchema, storefrontIdSchema, storefrontImageSchema, storefrontListingFacetsSchema, storefrontListingSchema, storefrontListingSummarySchema, storefrontLocationSchema, storefrontReviewSchema, storefrontSiteSchema };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkTGG3EO2D_cjs = require('./chunk-TGG3EO2D.cjs');
|
|
4
|
+
var chunkIGZVNTD2_cjs = require('./chunk-IGZVNTD2.cjs');
|
|
5
|
+
var chunkOGVX5IEI_cjs = require('./chunk-OGVX5IEI.cjs');
|
|
6
|
+
var chunkEHQFWSP6_cjs = require('./chunk-EHQFWSP6.cjs');
|
|
7
|
+
var zod = require('zod');
|
|
8
|
+
|
|
9
|
+
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 so=t.soChannel??null;const socialSource=source!==null&&(SOCIAL_SOURCES.has(source)||isSocialHost(source))||!!(external&&isSocialHost(external))||so==="social";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"||so==="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&&!so&&!t.soSend)return result("direct");return result("referral",source??external??so)}var MARKETING_TOUCH_CHANNELS=["email","sms","social","phone","qr"];function latestCampaignTouch(touches){let latest=null;for(const touch of touches){if(!touch?.soSend||Number.isNaN(Date.parse(touch.ts)))continue;if(!latest||Date.parse(touch.ts)>Date.parse(latest.ts))latest=touch;}return latest}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 NOTIFICATION_TYPES=["task_assigned","task_collaborator","task_commented","task_mentioned","task_completed","task_assignee_changed","task_triage","property_changed","notification_sent","guest_manual_review","check_in_changed","check_out_changed","date_changed","noise_alert","upsell_requested","custom","temperature_alert","reservation_created","reservation_cancelled","device_offline","battery_low","lock_jammed","member_invited","integration_disconnected","task_short_window","daily_digest_morning","daily_digest_evening","guest_message","precheck_notification","co2_alert","humidity_alert","blacklist_match","reservation_review","inbox_response_overdue","inbox_response_escalated","inbox_escalated","inbox_escalation_unassigned","payment_disputed","payment_failed","deposit_renewal_failed","deposit_renewal_fallback_charged","deposit_auto_refund_failed","inbox_agent_needs_help","internal_message","workflow_notification","camera_motion","doorbell_press","time_off_requested","time_off_reviewed","time_off_cancelled","fee_pricing_alert","integration_link_replacement_requested","integration_reconnect_after_move","guest_issue_aging","support_reply","feedback_request_updated","feedback_request_resolved","lifecycle","door_code_failed","telephony_registration_status","availability_changed","telephony_port_status","telephony_filing_status","airbnb_resolution_paid","airbnb_payment_submitted","airbnb_booking_request","door_alarm","voice_missed","task_follow_up_ready","stay_file_uploaded","task_follow_up_released","task_day_planned","task_auto_assign_failed","door_code_removal_stalled","sign_in_approval_requested","burst_summary","water_leak","knowledge_learning_done","task_offered"];var CRITICAL_NOTIFICATION_TYPES=new Set(["door_code_failed","door_code_removal_stalled","lock_jammed","door_alarm","noise_alert","water_leak","temperature_alert","humidity_alert","co2_alert","camera_motion","doorbell_press","guest_manual_review","blacklist_match","reservation_review","guest_message","voice_missed","inbox_escalated","inbox_escalation_unassigned","inbox_response_escalated","inbox_agent_needs_help","payment_failed","payment_disputed","deposit_renewal_failed","deposit_renewal_fallback_charged","deposit_auto_refund_failed","integration_disconnected","task_short_window","burst_summary"]);Object.fromEntries(NOTIFICATION_TYPES.map(t=>[t,CRITICAL_NOTIFICATION_TYPES.has(t)?"critical":"normal"]));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","dzd","ils","pln","twd","sek","sar"];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),soSend:zod.z.uuid().nullable().default(null),soChannel:zod.z.enum(MARKETING_TOUCH_CHANNELS).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(),campaign:attributionTouchSchema.nullable().optional(),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(),preview:zod.z.literal(true).optional()});function withoutClickIds(touch){return {...touch,gclid:null,gbraid:null,wbraid:null,fbclid:null,msclkid:null,paidClick:paidClickOf(touch)}}var MAX_CHECKOUT_CUSTOM_FIELDS=10;var MAX_CHECKOUT_UPSELLS=12;var MAX_CHECKOUT_UPSELL_QUANTITY=50;var MAX_CHECKOUT_FIELD_LENGTH=2e3;var MAX_FIELD_KEY_LENGTH=40;var BOOKING_UPSELL_CHARGE_TYPES=["fixed_price","price_per_quantity","price_per_night","price_per_guest_per_night","free"];var localizedTextSchema=zod.z.object({default:zod.z.string().trim().min(1,"validation.required").max(200,"validation.max_length"),translations:zod.z.record(zod.z.string().min(2).max(10),zod.z.string().max(200,"validation.max_length")).optional()});var fieldKeySchema=zod.z.string().regex(new RegExp(`^[a-z][a-z0-9_]{0,${MAX_FIELD_KEY_LENGTH-1}}$`),"validation.storefront.extensions_invalid_key").refine(key=>!(key in Object.prototype),"validation.storefront.extensions_invalid_key");var boundSchema=zod.z.number({error:"validation.number_required"}).int("validation.integer_required");var fieldBase={key:fieldKeySchema,label:localizedTextSchema,required:zod.z.boolean()};var customFieldDefSchema=zod.z.discriminatedUnion("type",[zod.z.object({type:zod.z.enum(["text","textarea"]),...fieldBase,maxLength:zod.z.number({error:"validation.number_required"}).int("validation.integer_required").min(1,"validation.too_small").max(MAX_CHECKOUT_FIELD_LENGTH,"validation.too_large").default(500)}),zod.z.object({type:zod.z.literal("select"),...fieldBase,options:zod.z.array(zod.z.object({value:zod.z.string().max(64).refine(value=>value.trim()!=="","validation.required"),label:localizedTextSchema})).min(1,"validation.storefront.extensions_select_needs_options").max(30,"validation.too_large").refine(options=>new Set(options.map(o=>o.value)).size===options.length,{message:"validation.storefront.extensions_duplicate_option"})}),zod.z.object({type:zod.z.literal("checkbox"),...fieldBase}),zod.z.object({type:zod.z.literal("number"),...fieldBase,min:boundSchema.optional(),max:boundSchema.optional()}),zod.z.object({type:zod.z.literal("date"),...fieldBase})]);zod.z.object({customFields:zod.z.array(customFieldDefSchema).max(MAX_CHECKOUT_CUSTOM_FIELDS,"validation.too_large").superRefine((fields,ctx)=>{const seen=new Set;fields.forEach((field,index)=>{if(seen.has(field.key)){ctx.addIssue({code:"custom",path:[index,"key"],message:"validation.storefront.extensions_duplicate_key"});}seen.add(field.key);if(field.type==="number"&&field.min!=null&&field.max!=null&&field.min>field.max){ctx.addIssue({code:"custom",path:[index,"max"],message:"validation.storefront.extensions_number_range_invalid"});}});}).default([]),upsells:zod.z.object({portalUpsellIds:zod.z.array(zod.z.uuid()).max(MAX_CHECKOUT_UPSELLS,"validation.too_large").refine(ids=>new Set(ids).size===ids.length,{message:"validation.storefront.extensions_duplicate_upsell"}).default([])}).default({portalUpsellIds:[]})});var checkoutExtrasInputSchema=zod.z.object({customFields:zod.z.record(zod.z.string().max(MAX_FIELD_KEY_LENGTH),zod.z.union([zod.z.string().max(MAX_CHECKOUT_FIELD_LENGTH),zod.z.number(),zod.z.boolean()])).refine(values=>Object.keys(values).length<=MAX_CHECKOUT_CUSTOM_FIELDS,{message:"validation.too_large"}).default({}),upsells:zod.z.array(zod.z.object({portalUpsellId:zod.z.uuid(),quantity:zod.z.number().int().min(1).max(MAX_CHECKOUT_UPSELL_QUANTITY)})).max(MAX_CHECKOUT_UPSELLS).default([])});var upsellOfferSchema=zod.z.object({portalUpsellId:zod.z.uuid(),title:zod.z.string(),description:zod.z.string().nullable(),imageUrl:zod.z.string().nullable(),chargeType:zod.z.enum(BOOKING_UPSELL_CHARGE_TYPES),unitMinor:zod.z.number().int(),minQuantity:zod.z.number().int(),maxQuantity:zod.z.number().int(),quantifierLabel:zod.z.string().nullable(),currency:zod.z.string().length(3),taxRateBasisPoints:zod.z.number().int().nullable().optional()});zod.z.object({locale:zod.z.string().max(35).optional().catch(void 0)});var checkoutLoyaltyOfferSchema=zod.z.object({programName:zod.z.string(),pointValueMinor:zod.z.number().int(),minPoints:zod.z.number().int().nullable(),maxPoints:zod.z.number().int().nullable(),pointsStep:zod.z.number().int().positive(),stayMaxPoints:zod.z.number().int().nonnegative()});var checkoutExtensionsSchema=zod.z.object({customFields:zod.z.array(customFieldDefSchema),upsellOffers:zod.z.array(upsellOfferSchema),codeEntry:zod.z.literal(true).optional(),loyalty:checkoutLoyaltyOfferSchema.optional()});var checkoutSessionExtrasSchema=zod.z.object({lines:zod.z.array(zod.z.object({portalUpsellId:zod.z.uuid().nullable(),title:zod.z.string(),quantity:zod.z.number().int(),totalMinor:zod.z.number().int(),taxMinor:zod.z.number().int().optional()})),extrasTotalMinor:zod.z.number().int(),heldTotalMinor:zod.z.number().int()});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(chunkTGG3EO2D_cjs.BE_BOOKING_REQUEST_STATUSES);var bookingRequestStatusResponseSchema=chunkEHQFWSP6_cjs.openEnum(chunkTGG3EO2D_cjs.BE_BOOKING_REQUEST_STATUSES);var checkoutDiscountSchema=zod.z.object({code:zod.z.string(),amountMinor:zod.z.number().int()});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),discount:checkoutDiscountSchema.optional()});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(),extras:checkoutExtrasInputSchema.optional(),hostSessionId:zod.z.uuid().optional(),code:zod.z.string().trim().min(1).max(64).optional(),loyalty:zod.z.object({memberToken:zod.z.string().min(1).max(4096),points:zod.z.number().int().min(1).max(1e6)}).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(),extras:checkoutSessionExtrasSchema.optional(),extrasSessionId:zod.z.uuid().optional(),smsOptIn:zod.z.object({brand:zod.z.string(),termsUrl:zod.z.url()}).optional(),loyalty:zod.z.object({points:zod.z.number().int(),discountMinor:zod.z.number().int()}).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:chunkIGZVNTD2_cjs.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),smsStay:zod.z.boolean().optional()}).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(),lines:zod.z.array(zod.z.object({title:zod.z.string(),quantity:zod.z.number().int(),totalMinor:zod.z.number().int()})).optional()});zod.z.enum(chunkTGG3EO2D_cjs.STOREFRONT_KEY_ENVIRONMENTS);var STOREFRONT_KEY_RE=new RegExp(`^pk_(${chunkTGG3EO2D_cjs.STOREFRONT_KEY_ENVIRONMENTS.join("|")})_(${chunkTGG3EO2D_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 TAG_LOADED_KINDS=["ga4","google_ads","meta","gtm","tiktok","microsoft_ads"];var TAG_LOADED_ID_RE=/^[A-Za-z0-9_-]{1,64}$/;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:chunkEHQFWSP6_cjs.storefrontDateSchema.optional(),checkOut:chunkEHQFWSP6_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")}),zod.z.object({...base,name:zod.z.literal("tag_loaded"),tag:zod.z.enum(TAG_LOADED_KINDS),tagId:zod.z.string().regex(TAG_LOADED_ID_RE).optional()})]);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 storefrontGuideItemSchema=zod.z.object({id:zod.z.uuid(),title:zod.z.string().nullable(),description:zod.z.string().nullable(),address:zod.z.string().nullable(),latitude:zod.z.number().nullable(),longitude:zod.z.number().nullable(),googleMapsUrl:zod.z.string().nullable(),websiteUrl:zod.z.string().nullable(),imageUrl:zod.z.string().nullable(),categories:zod.z.array(zod.z.string()),priceLevel:zod.z.number().int().min(1).max(4).nullable(),rating:zod.z.number().nullable(),ratingsCount:zod.z.number().int().nullable()});var storefrontGuideSchema=zod.z.object({id:zod.z.uuid(),name:zod.z.string(),category:zod.z.string().nullable(),coverImageUrl:zod.z.string().nullable(),items:zod.z.array(storefrontGuideItemSchema)});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(),campaign:attributionTouchSchema.nullable().optional()});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);const campaign=held?.campaign??null;if(!held||!(clicked(held.first)||clicked(held.last)||clicked(campaign)))return null;return serializeAttributionCookie({first:held.first&&withoutClickIds(held.first),last:held.last&&withoutClickIds(held.last),...campaign?{campaign:withoutClickIds(campaign)}:{}})??`${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;const campaign=latestCampaignTouch([touch,stored?.campaign,stored?.last,stored?.first]);return {first:stored?.first??touch,last:pageIsLast?touch:stored?.last??null,...campaign?{campaign}:{},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 chunkOGVX5IEI_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 chunkOGVX5IEI_cjs.StorefrontConfigError("Invalid SuiteOp publishable key: expected pk_{live|test}_{us|eu|apac}_ followed by 24 letters or digits.")}if(parsed.region==="demo"){throw new chunkOGVX5IEI_cjs.StorefrontConfigError("Invalid SuiteOp publishable key: expected pk_{live|test}_{us|eu|apac}_ followed by 24 letters or digits.")}return {environment:parsed.environment,region:parsed.region}}function defaultApiOrigin({environment,region}){return environment==="live"?`https://api-${region}.suiteop.com`:`https://api-${region}-staging.suiteop.com`}var SDK_VERSION="0.8.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(Array.isArray(value))for(const item of value)params.append(key,item);else 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 chunkOGVX5IEI_cjs.StorefrontNetworkError||err instanceof chunkOGVX5IEI_cjs.StorefrontError&&err.status>=500&&err.code!=="pms_unavailable"}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 chunkOGVX5IEI_cjs.StorefrontTimeoutError(spec.timeoutMs);throw new chunkOGVX5IEI_cjs.StorefrontNetworkError(err)}const body=parseJson(text);if(!response.ok)throw chunkOGVX5IEI_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 chunkOGVX5IEI_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 chunkOGVX5IEI_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 chunkOGVX5IEI_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 chunkOGVX5IEI_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 SLUG_OR_ID=/^[a-z0-9-]{1,120}$/;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(chunkIGZVNTD2_cjs.storefrontSiteSchema,"/site",opts)},listings:{async list(query,opts){const res=await transport.send({method:"GET",path:"/listings",query:{location:typeof query?.location==="string"?query.location:query?.location?.length?query.location.join(","):void 0,building:query?.building,guests:query?.guests,bedrooms:query?.bedrooms,currency:query?.currency,priceMin:query?.priceMin,priceMax:query?.priceMax,amenities:query?.amenities,bounds:typeof query?.bounds==="string"?query.bounds:query?.bounds?.join(","),checkIn:query?.checkIn,checkOut:query?.checkOut,sort:query?.sort,facets:query?.facets?1:void 0,limit:query?.limit,offset:query?.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(zod.z.array(chunkIGZVNTD2_cjs.storefrontListingSummarySchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);const facets=res.meta["facets"]===void 0?void 0:validate(chunkIGZVNTD2_cjs.storefrontListingFacetsSchema,res.meta["facets"],res);const unchecked=res.meta["unchecked"];return {items,...pagination,...facets?{facets}:{},...typeof unchecked==="number"&&Number.isInteger(unchecked)&&unchecked>=0?{unchecked}:{}}},get:(id,opts)=>get(chunkIGZVNTD2_cjs.storefrontListingSchema,`/listings/${seg(id)}`,opts)},buildings:{list:opts=>get(zod.z.array(chunkIGZVNTD2_cjs.storefrontBuildingSchema),"/buildings",opts),get:(id,opts)=>get(chunkIGZVNTD2_cjs.storefrontBuildingSchema,`/buildings/${seg(id)}`,opts),async availability(id,query,opts){const res=await transport.send({method:"GET",path:`/buildings/${seg(id)}/availability`,query:{checkIn:query.checkIn,checkOut:query.checkOut,guests:query.guests,limit:query.limit,offset:query.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(zod.z.array(chunkEHQFWSP6_cjs.storefrontUnitAvailabilitySchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);return {items,...pagination}}},locations:{list:opts=>get(zod.z.array(chunkIGZVNTD2_cjs.storefrontLocationSchema),"/locations",opts)},guides:{list:opts=>get(zod.z.array(storefrontGuideSchema),"/guides",opts),async get(id,opts){if(!chunkIGZVNTD2_cjs.storefrontIdSchema.safeParse(id).success)return null;try{return await get(storefrontGuideSchema,`/guides/${seg(id)}`,opts)}catch(err){if(err instanceof chunkOGVX5IEI_cjs.StorefrontError&&err.status===404)return null;throw err}}},contentModel:{get:opts=>get(chunkIGZVNTD2_cjs.storefrontContentModelSchema,"/content-model",opts)},collections:{async list(key2,query,opts){const res=await transport.send({method:"GET",path:`/collections/${seg(key2)}/items`,query:{limit:query?.limit,offset:query?.offset},timeoutMs:readTimeoutMs,signal:opts?.signal});const items=validate(zod.z.array(chunkIGZVNTD2_cjs.storefrontContentItemSchema),res.data,res);const pagination=validate(paginationSchema,res.meta["pagination"],res);return {items,...pagination}},async get(key2,slugOrId,opts){if(!SLUG_OR_ID.test(slugOrId))return null;try{return await get(chunkIGZVNTD2_cjs.storefrontContentItemSchema,`/collections/${seg(key2)}/items/${seg(slugOrId)}`,opts)}catch(err){if(err instanceof chunkOGVX5IEI_cjs.StorefrontError&&err.status===404)return null;throw err}}},sections:{get:(key2,opts)=>get(chunkIGZVNTD2_cjs.storefrontContentItemSchema,`/sections/${seg(key2)}`,opts)},amenities:{list:opts=>get(zod.z.array(zod.z.string()),"/amenities",opts)},reviews:{list:(query,opts)=>get(zod.z.array(chunkIGZVNTD2_cjs.storefrontReviewSchema),"/reviews",opts,{listingId:query?.listingId,limit:query?.limit,offset:query?.offset})},availability:{get:(listingId,stay,opts)=>get(chunkEHQFWSP6_cjs.storefrontAvailabilitySchema,`/listings/${seg(listingId)}/availability`,opts,{checkIn:stay.checkIn,checkOut:stay.checkOut,guests:stay.guests})},calendar:{get:(listingId,range,opts)=>get(chunkEHQFWSP6_cjs.storefrontCalendarSchema,`/listings/${seg(listingId)}/calendar`,opts,{from:range.from,to:range.to})},quotes:{create:(input,opts)=>post(chunkOGVX5IEI_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 chunkOGVX5IEI_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),extensions:(id,opts)=>get(checkoutExtensionsSchema,`/checkout-sessions/${seg(id)}/extensions`,opts,{locale:opts?.locale}),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 chunkOGVX5IEI_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(chunkIGZVNTD2_cjs.storefrontContactResultSchema,"/contact",input,opts);}}}}
|
|
10
|
+
|
|
11
|
+
exports.SDK_VERSION = SDK_VERSION;
|
|
12
|
+
exports.STOREFRONT_API_PATH = STOREFRONT_API_PATH;
|
|
13
|
+
exports.STOREFRONT_API_VERSION = STOREFRONT_API_VERSION;
|
|
14
|
+
exports.analyticsFor = analyticsFor;
|
|
15
|
+
exports.createAnalytics = createAnalytics;
|
|
16
|
+
exports.createStorefrontClient = createStorefrontClient;
|
|
17
|
+
exports.getAttribution = getAttribution;
|
|
18
|
+
exports.parsePublishableKey = parsePublishableKey;
|
|
19
|
+
exports.trackPurchasePixel = trackPurchasePixel;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkEHQFWSP6_cjs = require('./chunk-EHQFWSP6.cjs');
|
|
4
|
+
var zod = require('zod');
|
|
5
|
+
|
|
6
|
+
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 storefrontIdSchema=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(),mapEmbedToken:zod.z.string().nullish(),countryCode:zod.z.string().nullish(),bookingsOpen:zod.z.boolean().optional(),accountUrl: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(),fromPriceMinor:zod.z.number().int().nonnegative().nullish(),currency:zod.z.string().nullish()});var storefrontImageSchema=zod.z.object({url:zod.z.string(),alt:zod.z.string().nullable(),width:zod.z.number().int().nullable(),height:zod.z.number().int().nullable()});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(),images:zod.z.array(storefrontImageSchema).optional(),rooms:zod.z.unknown(),houseRules:zod.z.string().nullable(),checkInTime:zod.z.string().nullable(),checkOutTime:zod.z.string().nullable(),beds:zod.z.number().nullable(),countryCode:zod.z.string().nullish(),reviewCount:zod.z.number().int().nonnegative().nullish(),reviewRating:zod.z.number().nullish()});var STOREFRONT_LISTING_SORTS=["recommended","price_asc","price_desc","rating"];var asList=value=>value===void 0?void 0:Array.isArray(value)?value:[value];var boundsSchema=zod.z.string().transform(value=>value.split(",").map(part=>part.trim()===""?NaN:Number(part))).pipe(zod.z.tuple([zod.z.number().min(-90).max(90),zod.z.number().min(-180).max(180),zod.z.number().min(-90).max(90),zod.z.number().min(-180).max(180)]).refine(([swLat,,neLat])=>swLat<=neLat)).transform(([swLat,swLng,neLat,neLng])=>({swLat,swLng,neLat,neLng}));var listingsStaySchema=chunkEHQFWSP6_cjs.withStayRules(zod.z.object({checkIn:chunkEHQFWSP6_cjs.storefrontDateSchema,checkOut:chunkEHQFWSP6_cjs.storefrontDateSchema}));zod.z.object({location:zod.z.preprocess(value=>asList(value)?.flatMap(v=>typeof v==="string"?v.split(","):[v]),zod.z.array(zod.z.string().trim().min(1).max(200)).min(1).max(50).optional()).optional(),building:zod.z.uuid().optional(),guests:zod.z.coerce.number().int().min(1).max(100).optional(),bedrooms:zod.z.coerce.number().int().min(0).max(50).optional(),currency:zod.z.string().trim().regex(/^[A-Za-z]{3}$/).transform(value=>value.toLowerCase()).optional(),priceMin:zod.z.coerce.number().int().min(0).optional(),priceMax:zod.z.coerce.number().int().min(0).optional(),amenities:zod.z.preprocess(asList,zod.z.array(zod.z.string().trim().min(1).max(200)).min(1).max(30).optional()).optional(),bounds:boundsSchema.optional(),checkIn:chunkEHQFWSP6_cjs.storefrontDateSchema.optional(),checkOut:chunkEHQFWSP6_cjs.storefrontDateSchema.optional(),sort:zod.z.enum(STOREFRONT_LISTING_SORTS).optional(),facets:zod.z.enum(["0","1","true","false"]).transform(value=>value==="1"||value==="true").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)}).refine(q=>q.currency!==void 0||q.priceMin===void 0&&q.priceMax===void 0,{path:["currency"],message:"validation.required"}).refine(q=>q.priceMin===void 0||q.priceMax===void 0||q.priceMin<=q.priceMax,{path:["priceMax"],message:"validation.invalid"}).superRefine((q,ctx)=>{if(q.checkIn===void 0&&q.checkOut===void 0)return;if(q.checkIn===void 0||q.checkOut===void 0){const path=q.checkIn===void 0?"checkIn":"checkOut";ctx.addIssue({code:"custom",path:[path],message:"validation.required"});return}const stay=listingsStaySchema.safeParse({checkIn:q.checkIn,checkOut:q.checkOut});for(const issue of stay.error?.issues??[]){ctx.addIssue({code:"custom",path:issue.path,message:issue.message});}});var storefrontListingFacetsSchema=zod.z.object({total:zod.z.number().int(),areas:zod.z.array(zod.z.object({id:zod.z.uuid(),slug:zod.z.string().nullable(),count:zod.z.number().int()})),bedrooms:zod.z.array(zod.z.object({bedrooms:zod.z.number().int(),count:zod.z.number().int()})),price:zod.z.object({min:zod.z.number().int(),max:zod.z.number().int(),currency:zod.z.string().nullable(),buckets:zod.z.array(zod.z.number().int()).length(24)}).nullable()});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(),name:zod.z.string().nullish(),description:zod.z.string().nullish(),imageUrl:zod.z.string().nullish(),images:zod.z.array(storefrontImageSchema).nullish(),sortOrder:zod.z.number().int().nullish(),listingCount:zod.z.number().int().nullish(),fields:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),zod.z.unknown())).nullish()});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(),name:zod.z.string().nullish(),description:zod.z.string().nullish(),imageUrl:zod.z.string().nullish(),images:zod.z.array(storefrontImageSchema).nullish(),buildingCount:zod.z.number().int().nullish(),fields:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),zod.z.unknown())).nullish()});zod.z.object({locale:zod.z.string().max(35).optional().catch(void 0)});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)});var storefrontContentRefSchema=zod.z.object({kind:zod.z.string(),id:zod.z.uuid(),slug:zod.z.string().nullable()});var storefrontContentItemSchema=zod.z.object({id:zod.z.uuid(),type:zod.z.string(),slug:zod.z.string().nullable(),publishedAt:zod.z.string().nullable(),updatedAt:zod.z.string(),sortOrder:zod.z.number().int(),fields:zod.z.record(zod.z.string(),zod.z.unknown())});var storefrontContentFieldDefSchema=zod.z.object({key:zod.z.string(),type:zod.z.string()}).catchall(zod.z.unknown());var storefrontContentModelSchema=zod.z.object({version:zod.z.number().int(),types:zod.z.array(zod.z.object({key:zod.z.string(),kind:zod.z.string(),fields:zod.z.array(storefrontContentFieldDefSchema)}).catchall(zod.z.unknown()))});zod.z.object({limit:zod.z.coerce.number().int().min(1).max(100).default(20),offset:zod.z.coerce.number().int().min(0).max(1e4).default(0),locale:zod.z.string().max(35).optional().catch(void 0)});zod.z.string().regex(/^[a-z][a-z0-9_]{0,39}$/);zod.z.string().min(1).max(120).regex(/^[a-z0-9-]+$/);
|
|
7
|
+
|
|
8
|
+
exports.requiredTrimmedEmailField = requiredTrimmedEmailField;
|
|
9
|
+
exports.storefrontBuildingSchema = storefrontBuildingSchema;
|
|
10
|
+
exports.storefrontContactResultSchema = storefrontContactResultSchema;
|
|
11
|
+
exports.storefrontContentItemSchema = storefrontContentItemSchema;
|
|
12
|
+
exports.storefrontContentModelSchema = storefrontContentModelSchema;
|
|
13
|
+
exports.storefrontContentRefSchema = storefrontContentRefSchema;
|
|
14
|
+
exports.storefrontIdSchema = storefrontIdSchema;
|
|
15
|
+
exports.storefrontImageSchema = storefrontImageSchema;
|
|
16
|
+
exports.storefrontListingFacetsSchema = storefrontListingFacetsSchema;
|
|
17
|
+
exports.storefrontListingSchema = storefrontListingSchema;
|
|
18
|
+
exports.storefrontListingSummarySchema = storefrontListingSummarySchema;
|
|
19
|
+
exports.storefrontLocationSchema = storefrontLocationSchema;
|
|
20
|
+
exports.storefrontReviewSchema = storefrontReviewSchema;
|
|
21
|
+
exports.storefrontSiteSchema = storefrontSiteSchema;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { storefrontContentRefSchema, storefrontImageSchema } from './chunk-
|
|
2
|
-
import { StorefrontError } from './chunk-
|
|
1
|
+
import { storefrontContentRefSchema, storefrontImageSchema } from './chunk-6AGNQD7J.js';
|
|
2
|
+
import { StorefrontError } from './chunk-5QO273QX.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
|
|
5
5
|
var CONTENT_FIELD_TYPES=["text","rich_text","image","gallery","number","boolean","date","option","link","reference","references"];var CONTENT_TYPE_KINDS=["collection","section","fields"];var CONTENT_SUBJECT_KINDS=["building","area"];var CONTENT_REFERENCE_KINDS=["listing","building","area"];var MAX_CONTENT_TYPES=40;var MAX_CONTENT_FIELDS=40;var contentKeySchema=z.string().regex(/^[a-z][a-z0-9_]{0,39}$/,"validation.invalid_format");var contentLocalizedSchema=z.union([z.string().min(1).max(120),z.record(z.string().min(2).max(35),z.string().min(1).max(120))]);var COLLECTION_TARGET=/^collection:[a-z][a-z0-9_]{0,39}$/;var contentReferenceTargetSchema=z.union([z.enum(CONTENT_REFERENCE_KINDS),z.string().regex(COLLECTION_TARGET,"validation.invalid_format")]);var TEXT_TYPES=new Set(["text","rich_text"]);var LIST_TYPES=new Set(["gallery","references"]);var REFERENCE_TYPES=new Set(["reference","references"]);var contentFieldSchema=z.object({key:contentKeySchema,type:z.enum(CONTENT_FIELD_TYPES),label:contentLocalizedSchema,help:contentLocalizedSchema.optional(),required:z.boolean().default(false),translatable:z.boolean().optional(),maxLength:z.number().int().min(1).max(6e4).optional(),options:z.array(z.object({value:contentKeySchema,label:contentLocalizedSchema})).min(1).max(50).optional(),to:contentReferenceTargetSchema.optional(),max:z.number().int().min(1).max(100).optional(),removed:z.boolean().optional()}).superRefine((field2,ctx)=>{if(field2.type==="option"&&!field2.options?.length){ctx.addIssue({code:"custom",path:["options"],message:"validation.required"});}if(field2.options&&new Set(field2.options.map(o=>o.value)).size!==field2.options.length){ctx.addIssue({code:"custom",path:["options"],message:"validation.invalid"});}if(REFERENCE_TYPES.has(field2.type)&&!field2.to){ctx.addIssue({code:"custom",path:["to"],message:"validation.required"});}if(field2.maxLength!==void 0&&!TEXT_TYPES.has(field2.type)){ctx.addIssue({code:"custom",path:["maxLength"],message:"validation.invalid"});}if(field2.max!==void 0&&!LIST_TYPES.has(field2.type)){ctx.addIssue({code:"custom",path:["max"],message:"validation.invalid"});}});var contentTypeSchema=z.object({key:contentKeySchema,kind:z.enum(CONTENT_TYPE_KINDS),label:contentLocalizedSchema,description:contentLocalizedSchema.optional(),attachesTo:z.enum(CONTENT_SUBJECT_KINDS).optional(),titleField:contentKeySchema.optional(),routable:z.boolean().default(false),drafts:z.boolean().default(false),order:z.enum(["manual","newest"]).default("manual"),fields:z.array(contentFieldSchema).min(1).max(MAX_CONTENT_FIELDS)}).superRefine((type,ctx)=>{const keys=type.fields.map(f=>f.key);keys.forEach((key,i)=>{if(keys.indexOf(key)!==i){ctx.addIssue({code:"custom",path:["fields",i,"key"],message:"validation.invalid"});}});if(type.kind==="fields"!==(type.attachesTo!==void 0)){ctx.addIssue({code:"custom",path:["attachesTo"],message:"validation.invalid"});}if(type.kind==="collection"){const title=type.fields.find(f=>f.key===type.titleField);if(!title||title.type!=="text"){ctx.addIssue({code:"custom",path:["titleField"],message:"validation.invalid"});}}else if(type.titleField!==void 0){ctx.addIssue({code:"custom",path:["titleField"],message:"validation.invalid"});}});var contentModelSchema=z.object({version:z.literal(1),types:z.array(contentTypeSchema).max(MAX_CONTENT_TYPES)}).superRefine((model,ctx)=>{const keys=model.types.map(t=>t.key);const collections=new Set(model.types.filter(t=>t.kind==="collection").map(t=>t.key));model.types.forEach((type,i)=>{if(keys.indexOf(type.key)!==i){ctx.addIssue({code:"custom",path:["types",i,"key"],message:"validation.invalid"});}type.fields.forEach((field2,j)=>{const target=field2.to?.startsWith("collection:")?field2.to.slice(11):null;if(target!==null&&!collections.has(target)){ctx.addIssue({code:"custom",path:["types",i,"fields",j,"to"],message:"validation.invalid"});}});});});function defineContent(definition){return definition}var field={text:o=>({...o,type:"text"}),richText:o=>({...o,type:"rich_text"}),image:o=>({...o,type:"image"}),gallery:o=>({...o,type:"gallery"}),number:o=>({...o,type:"number"}),boolean:o=>({...o,type:"boolean"}),date:o=>({...o,type:"date"}),option:o=>({...o,type:"option"}),link:o=>({...o,type:"link"}),reference:o=>({...o,type:"reference"}),references:o=>({...o,type:"references"})};var optionOf=choice=>typeof choice==="string"?{value:choice,label:choice}:choice;function toContentModel(definition){return {version:1,types:Object.entries(definition).map(([key,type])=>({...type,key,fields:Object.entries(type.fields).map(([fieldKey,f])=>f.type==="option"?{...f,key:fieldKey,options:f.options.map(optionOf)}:{...f,key:fieldKey})}))}}function parseContentModel(definition){const parsed=contentModelSchema.safeParse(toContentModel(definition));if(parsed.success)return parsed.data;const problems=parsed.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`);throw new Error(`Invalid SuiteOp content model:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var CDN_IMAGE_ORIGIN="https://cdn.suiteop.com";var CDN_IMAGE_HOST="cdn.suiteop.com";var TRANSFORM_SEGMENT="/cdn-cgi/image/";var ORG_SCOPED_KEY=/^(booking-engine\/)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\//;var CDN_IMAGE_WIDTHS=[320,640,1080,1600];function cdnObjectKey(url){if(url.includes(TRANSFORM_SEGMENT))return void 0;let parsed;try{parsed=new URL(url);}catch{return void 0}if(parsed.protocol!=="https:"||parsed.host!==CDN_IMAGE_HOST)return void 0;if(parsed.username||parsed.password)return void 0;const key=parsed.pathname.slice(1);if(!ORG_SCOPED_KEY.test(key)||parsed.search||parsed.hash)return void 0;return key}function cdnImageUrl(url,width){if(!url)return void 0;const key=cdnObjectKey(url);if(key===void 0)return url;return `${CDN_IMAGE_ORIGIN}${TRANSFORM_SEGMENT}width=${width},format=auto,quality=80/${key}`}function cdnImageSrcSet(url,widths=CDN_IMAGE_WIDTHS){if(!url||cdnObjectKey(url)===void 0)return void 0;return widths.map(w=>`${cdnImageUrl(url,w)} ${w}w`).join(", ")}function cdnImageProps(url,width,sizes){const srcSet=cdnImageSrcSet(url);if(!srcSet)return {src:url??void 0};return {src:
|
|
3
|
+
var CDN_IMAGE_ORIGIN="https://cdn.suiteop.com";var CDN_IMAGE_HOST="cdn.suiteop.com";var TRANSFORM_SEGMENT="/cdn-cgi/image/";var ORG_SCOPED_KEY=/^(booking-engine\/)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\//;var CDN_IMAGE_WIDTHS=[320,640,1080,1600];function cdnObjectKey(url){if(url.includes(TRANSFORM_SEGMENT))return void 0;let parsed;try{parsed=new URL(url);}catch{return void 0}if(parsed.protocol!=="https:"||parsed.host!==CDN_IMAGE_HOST)return void 0;if(parsed.username||parsed.password)return void 0;const key=parsed.pathname.slice(1);if(!ORG_SCOPED_KEY.test(key)||parsed.search||parsed.hash)return void 0;return key}function cdnImageUrl(url,width){if(!url)return void 0;const key=cdnObjectKey(url);if(key===void 0)return url;return `${CDN_IMAGE_ORIGIN}${TRANSFORM_SEGMENT}width=${width},format=auto,quality=80/${key}`}var GUESTY_UPLOAD=/^https:\/\/assets\.guesty\.com\/image\/upload\/(v\d+\/[^?#]+)$/;function thumbnailImageUrl(url,width){if(!url)return void 0;const guesty=GUESTY_UPLOAD.exec(url);if(guesty){return `https://assets.guesty.com/image/upload/w_${width},c_limit,f_auto,q_auto/${guesty[1]}`}return cdnImageUrl(url,width)}function cdnImageSrcSet(url,widths=CDN_IMAGE_WIDTHS){if(!url||cdnObjectKey(url)===void 0)return void 0;return widths.map(w=>`${cdnImageUrl(url,w)} ${w}w`).join(", ")}function guestyImageSrcSet(url){if(!url||!GUESTY_UPLOAD.test(url))return void 0;return CDN_IMAGE_WIDTHS.map(w=>`${thumbnailImageUrl(url,w)} ${w}w`).join(", ")}function cdnImageProps(url,width,sizes){const srcSet=cdnImageSrcSet(url)??guestyImageSrcSet(url);if(!srcSet)return {src:url??void 0};return {src:thumbnailImageUrl(url,width),srcSet,sizes}}
|
|
4
4
|
|
|
5
5
|
exports.CDN_IMAGE_WIDTHS = CDN_IMAGE_WIDTHS;
|
|
6
6
|
exports.cdnImageProps = cdnImageProps;
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
var chunkEHQFWSP6_cjs = require('./chunk-EHQFWSP6.cjs');
|
|
4
4
|
var zod = require('zod');
|
|
5
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()});chunkEHQFWSP6_cjs.withStayRules(zod.z.object({listingId:zod.z.uuid({message:"validation.storefront.listing_invalid"}),checkIn:chunkEHQFWSP6_cjs.storefrontDateSchema,checkOut:chunkEHQFWSP6_cjs.storefrontDateSchema,guests:chunkEHQFWSP6_cjs.storefrontGuestsSchema}));var storefrontQuoteSchema=zod.z.object({quoteRef:zod.z.string(),propertyId:zod.z.uuid(),checkIn:chunkEHQFWSP6_cjs.storefrontDateSchema,checkOut:chunkEHQFWSP6_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","bookings_closed","extras_invalid","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)}}
|
|
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()});chunkEHQFWSP6_cjs.withStayRules(zod.z.object({listingId:zod.z.uuid({message:"validation.storefront.listing_invalid"}),checkIn:chunkEHQFWSP6_cjs.storefrontDateSchema,checkOut:chunkEHQFWSP6_cjs.storefrontDateSchema,guests:chunkEHQFWSP6_cjs.storefrontGuestsSchema}));var storefrontQuoteSchema=zod.z.object({quoteRef:zod.z.string(),propertyId:zod.z.uuid(),checkIn:chunkEHQFWSP6_cjs.storefrontDateSchema,checkOut:chunkEHQFWSP6_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","pms_unavailable","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","bookings_closed","extras_invalid","offer_code_refused","loyalty_points_invalid","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
7
|
|
|
8
8
|
exports.PriceChangedError = PriceChangedError;
|
|
9
9
|
exports.RateLimitedError = RateLimitedError;
|