@weaverse/hydrogen 5.22.1 → 5.24.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/main.tsx","../src/components/index.ts","../src/hooks/translation-context.tsx","../src/hooks/use-weaverse-data-context.ts","../src/seo.ts","../src/types.ts","../src/utils/studio-script-src.ts","../src/utils/index.ts","../src/utils/translation-store.ts","../src/utils/pick-weaverse-data.ts","../src/utils/studio-request-info.ts","../src/utils/is-same-loader-payload.ts","../src/utils/sync-reused-instance.ts","../src/utils/use-theme-settings-store.ts","../src/utils/use-studio.ts","../src/WeaverseHydrogenRoot.tsx","../src/utils/normalize-page-url.ts","../src/weaverse-client.ts","../src/index.ts"],"names":["jsx","createSchema","createContext","useSafeExternalStore","useMemo","useContext","useMatches","schema","isValidSchema","window","type","children","data","isBrowser","useRouteLoaderData","useRef","useEffect","useLocation","loadScript","useRevalidator","useNavigation","useNavigate","WeaverseItemStore","Weaverse","memo","jsxs","Fragment","WeaverseRoot","useLoaderData","ErrorBoundary","Suspense","Await","createWithCache","CacheCustom","hydrogen_getSelectedProductOptions"],"mappings":";;;;;;;;;;;AAQA,SAAS,KAAK,KAAA,EAAgE;AAC5E,EAAA,IAAI,EAAE,QAAA,EAAU,uBAAA,EAAyB,GAAG,MAAK,GAAI,KAAA;AAErD,EAAA,uBACEA,cAAA;AAAA,IAAC,KAAA;AAAA,IAAA;AAAA,MACE,GAAG,IAAA;AAAA,MAEJ,QAAA;AAAA,MAEA,uBAAA,EAAyB,WAAW,MAAA,GAAY;AAAA;AAAA,GAClD;AAEJ;AAEA,IAAO,YAAA,GAAQ,IAAA;AAER,IAAI,SAAqBC,qBAAA,CAAa;AAAA,EAC3C,IAAA,EAAM,MAAA;AAAA,EACN,KAAA,EAAO;AACT,CAAC,CAAA;;;ACvBM,IAAI,iBAAA,GAAyC;AAAA,EAClD;AAAA,IACE,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AAA;AAAA,EAGA,mBAAA,GAAsB,OAAO,IAAA,KAAgC;AAC3D,IAAA,MAAM,EAAE,IAAA,GAAO,EAAC,EAAG,IAAA,EAAM,IAAG,GAAI,IAAA;AAChC,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,gBAAA,CAAiB,GAAA,CAAI,IAAI,CAAA;AAChD,IAAA,MAAM,SAAS,SAAA,EAAW,MAAA;AAC1B,IAAA,IAAI,OAAO,MAAA,KAAW,UAAA,IAAc,SAAA,EAAW;AAC7C,MAAA,IAAI;AACF,QAAA,OAAO;AAAA,UACL,GAAG,IAAA;AAAA,UACH,UAAA,EAAY,MAAM,OAAA,CAAQ,OAAA;AAAA,YACxB,MAAA,CAAO;AAAA,cACL,IAAA,EAAM,EAAE,GAAG,sBAAA,CAAuB,UAAU,MAAM,CAAA,EAAG,GAAG,IAAA,EAAK;AAAA,cAC7D,QAAA,EAAU;AAAA,aACX;AAAA;AACH,SACF;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,IAAA,CAAK,gCAAA,EAA6B,IAAA,EAAM,EAAA,EAAI,KAAK,CAAA;AACzD,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AACF;;;AC5sCO,SAAS,0BACd,OAAA,EACuB;AACvB,EAAA,IAAI,OAAA,GAAUC,mCAAmC,OAAO,CAAA;AACxD,EAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,IACb,CAAC,EAAE,IAAA,EAAK,KAAM,SAAS,cAAA,IAAkB,CAAC,IAAA,CAAK,UAAA,CAAW,UAAU;AAAA,GACtE;AACF","file":"index.js","sourcesContent":["import { createSchema, type SchemaType } from '@weaverse/schema'\nimport type { HTMLAttributes } from 'react'\nimport type { HydrogenComponentProps } from '../types'\n\n/*\n Main is the default Weaverse component that is used to render the main content.\n This component wraps all the sections/components inside a Weaverse page.\n*/\nfunction Main(props: HydrogenComponentProps & HTMLAttributes<HTMLDivElement>) {\n let { children, dangerouslySetInnerHTML, ...rest } = props\n\n return (\n <div\n {...rest}\n // biome-ignore lint/correctness/noChildrenProp: <explanation>\n children={children}\n // biome-ignore lint/security/noDangerouslySetInnerHtmlWithChildren: <explanation>\n dangerouslySetInnerHTML={children ? undefined : dangerouslySetInnerHTML}\n />\n )\n}\n\nexport default Main\n\nexport let schema: SchemaType = createSchema({\n type: 'main',\n title: 'Main',\n})\n","import type { HydrogenComponent } from '../types'\nimport MainComponent, { schema as mainSchema } from './main'\n\n/** Built-in components required to render the root of every Weaverse page. */\nexport let defaultComponents: HydrogenComponent[] = [\n {\n default: MainComponent,\n schema: mainSchema,\n },\n]\n","import { useSafeExternalStore } from '@weaverse/react'\nimport { createContext, type ReactNode, useContext, useMemo } from 'react'\nimport type { TranslationStore } from '../utils/translation-store'\n\n/**\n * Traverse a nested object by dot-path.\n *\n * @example\n * getNestedKey({ cart: { title: 'Cart' } }, 'cart.title') // => 'Cart'\n * getNestedKey({}, 'cart.title', 'fallback') // => 'fallback'\n */\nexport function getNestedKey(\n obj: Record<string, unknown>,\n path: string,\n fallback?: string\n): string | undefined {\n const keys = path.split('.')\n let current: unknown = obj\n\n for (const key of keys) {\n if (current == null || typeof current !== 'object') {\n return fallback\n }\n current = (current as Record<string, unknown>)[key]\n }\n\n if (typeof current === 'string') {\n return current\n }\n\n return fallback\n}\n\n/**\n * Replace `{{variable}}` patterns in a string with provided values.\n *\n * @example\n * interpolate('Hello {{name}}!', { name: 'World' }) // => 'Hello World!'\n * interpolate('-{{percentage}}% Off', { percentage: 15 }) // => '-15% Off'\n */\nexport function interpolate(\n template: string,\n variables?: Record<string, string | number>\n): string {\n if (!variables) {\n return template\n }\n\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key: string) => {\n const value = variables[key]\n return value === undefined ? match : String(value)\n })\n}\n\n// ---------------------------------------------------------------------------\n// Context & Provider\n// ---------------------------------------------------------------------------\n\n/**\n * Signature for a translation function.\n */\nexport type TranslateFunction = (\n key: string,\n variables?: Record<string, string | number>\n) => string\n\n/** Translation function, stores, and locale overrides exposed by the provider. */\nexport type TranslationValue = {\n /**\n * Translate a key with optional variable interpolation.\n *\n * Priority chain (highest wins):\n * 1. External `t` (passed into `withWeaverse` / `TranslationProvider`)\n * 2. `merchantOverrides` (DB overrides for the current locale + design overrides)\n * 3. `staticContent` (theme default JSON)\n * 4. The key itself (fallback)\n *\n * @example\n * t('cart.title') // => \"Cart\"\n * t('badge.sale', { percentage: 15 }) // => \"-15% Off\"\n */\n t: TranslateFunction\n /** Exposed for useStudio to attach to weaverse.internal. Null in production. */\n translationStore: TranslationStore | null\n /**\n * @deprecated Use {@link TranslationValue.translationStore} instead. Kept as a\n * backward-compatible alias pointing at the same store instance.\n */\n themeTextStore: TranslationStore | null\n /** Active-locale translated keys loaded from the storefront API. */\n merchantOverrides: Record<string, unknown> | null\n}\n\nconst TranslationContext = createContext<TranslationValue | null>(null)\nTranslationContext.displayName = 'WeaverseTranslationContext'\n\n/** Inputs accepted by {@link TranslationProvider}. */\nexport type TranslationProviderProps = {\n /** Theme-provided default-locale translation content. */\n staticContent: Record<string, unknown>\n /** Active-locale translations published by the merchant. */\n merchantOverrides?: Record<string, unknown>\n /**\n * Optional external translation function.\n * When provided it becomes the **highest-priority** source:\n * if it returns a non-empty string that differs from the raw key,\n * that value is used; otherwise the internal resolution chain continues.\n */\n t?: TranslateFunction\n /** Optional store for live design-mode text overrides from the builder. */\n translationStore?: TranslationStore | null\n /**\n * @deprecated Use {@link TranslationProviderProps.translationStore} instead.\n * Still accepted for backward compatibility; ignored when `translationStore`\n * is also provided.\n */\n themeTextStore?: TranslationStore | null\n /** React content that can consume the translation context. */\n children: ReactNode\n}\n\n/**\n * Build the `t()` translation function over a fixed set of sources.\n *\n * Resolution order, highest priority first:\n * 1. `externalT` – host i18n (e.g. Shopify), unless it echoes the key\n * 2. `designOverrides` – live design-mode edits, flat dot-path keys\n * 3. `merchantOverrides` – locale overrides from the API, nested\n * 4. `staticContent` – the theme's default locale JSON\n * 5. the key itself\n *\n * Design overrides are looked up per-key (own properties only) rather than\n * merged into `merchantOverrides`: a flat key like `cart.title` must override\n * exactly that leaf without wiping sibling keys (`cart.subtitle`), and a\n * per-key own-property lookup never builds nested objects from\n * merchant-controlled keys, so it cannot pollute `Object.prototype`.\n */\nexport function createTranslate(sources: {\n staticContent: Record<string, unknown>\n merchantOverrides?: Record<string, unknown>\n designOverrides?: Record<string, string>\n externalT?: TranslateFunction\n}): TranslateFunction {\n const { staticContent, merchantOverrides, designOverrides, externalT } =\n sources\n return (key, variables) => {\n // Priority 1: external t (e.g. Shopify i18n, third-party library).\n if (externalT) {\n const external = externalT(key, variables)\n // Accept the external value unless it echoed the key unchanged.\n if (external && external !== key) {\n return external\n }\n }\n\n // Priority 2: live design-mode override (flat, keyed by exact dot-path,\n // own properties only so inherited keys never resolve to functions).\n const design =\n designOverrides && Object.hasOwn(designOverrides, key)\n ? designOverrides[key]\n : undefined\n // Priority 3: merchant overrides (nested). Priority 4: static content.\n const override = merchantOverrides\n ? getNestedKey(merchantOverrides, key)\n : undefined\n const staticValue = getNestedKey(staticContent, key)\n\n // Priority 5: the key itself as the final fallback.\n const raw = design ?? override ?? staticValue ?? key\n return interpolate(raw, variables)\n }\n}\n\n// No-op fallback for useSafeExternalStore when store is null (production).\n// Module-level constants — stable references, zero allocation per render.\nconst EMPTY: Record<string, string> = {}\nconst NOOP_SUBSCRIBE = () => () => {}\nconst NOOP_SNAPSHOT = () => EMPTY\n\n/**\n * Provider that wraps the app to expose the `t()` function.\n *\n * - `staticContent` – the theme's default locale JSON (from themeSchema.i18n)\n * - `merchantOverrides` – locale-specific overrides fetched from the API\n * - `translationStore` – optional store for live design-mode text overrides\n * (the deprecated `themeTextStore` prop is accepted as a fallback)\n */\nexport function TranslationProvider({\n staticContent,\n merchantOverrides,\n t: externalT,\n translationStore,\n themeTextStore,\n children,\n}: TranslationProviderProps) {\n // Canonical store, falling back to the deprecated `themeTextStore` prop.\n const store = translationStore ?? themeTextStore ?? null\n\n // Subscribe to design-mode overrides. No-op when store is null (production).\n const designOverrides = useSafeExternalStore(\n store?.subscribe ?? NOOP_SUBSCRIBE,\n store?.getSnapshot ?? NOOP_SNAPSHOT,\n store?.getServerSnapshot ?? NOOP_SNAPSHOT\n )\n\n const value = useMemo<TranslationValue>(\n () => ({\n t: createTranslate({\n staticContent,\n merchantOverrides,\n designOverrides,\n externalT,\n }),\n translationStore: store,\n // Deprecated alias — same instance, kept for backward compatibility.\n themeTextStore: store,\n merchantOverrides: merchantOverrides ?? null,\n }),\n [staticContent, merchantOverrides, designOverrides, externalT, store]\n )\n\n return (\n <TranslationContext.Provider value={value}>\n {children}\n </TranslationContext.Provider>\n )\n}\n\n/**\n * Hook to access the translation `t()` function.\n *\n * Must be used inside a component wrapped by `withWeaverse` or `TranslationProvider`.\n *\n * @example\n * ```tsx\n * function CartTitle() {\n * const { t } = useTranslation()\n * return <h2>{t('cart.title')}</h2>\n * }\n * ```\n */\nexport function useTranslation(): TranslationValue {\n const ctx = useContext(TranslationContext)\n if (!ctx) {\n throw new Error(\n 'useTranslation must be used within <TranslationProvider>. Wrap your app with withWeaverse().'\n )\n }\n return ctx\n}\n\n// ---------------------------------------------------------------------------\n// Deprecated aliases (backward compatibility — kept exported indefinitely)\n// ---------------------------------------------------------------------------\n\n/**\n * Legacy name for {@link TranslationProvider}.\n * @deprecated Use {@link TranslationProvider} instead.\n */\nexport const ThemeTextProvider = TranslationProvider\n/**\n * Legacy name for {@link useTranslation}.\n * @deprecated Use {@link useTranslation} instead.\n */\nexport const useThemeText = useTranslation\n/**\n * Legacy name for {@link TranslationValue}.\n * @deprecated Use {@link TranslationValue} instead.\n */\nexport type ThemeTextValue = TranslationValue\n/**\n * Legacy name for {@link TranslationProviderProps}.\n * @deprecated Use {@link TranslationProviderProps} instead.\n */\nexport type ThemeTextProviderProps = TranslationProviderProps\n","import { type UIMatch, useMatches } from 'react-router'\n\n/** Loader data indexed by React Router's conventional route identifiers. */\nexport interface RouteKeyedDataContext {\n /** Root route loader data, when the root loader returned an object. */\n root?: Record<string, unknown>\n /** Loader data for a non-root route keyed by its route identifier. */\n [routeKey: `routes/${string}`]: Record<string, unknown>\n}\n\n/**\n * Flat loader-data map keyed by React Router route ID.\n * Use route IDs such as `root` or `routes/products.$handle` in data bindings.\n */\nexport type WeaverseDataContext = RouteKeyedDataContext &\n Record<string, unknown>\n\n/**\n * Creates flat route-keyed structure from matches\n * Target: {root: {...rootData}, \"routes/product\": {...productData}}\n * Eliminates all duplication by using route IDs as keys\n */\nfunction createFlatDataContext(\n matches: UIMatch<unknown, unknown>[]\n): WeaverseDataContext {\n const context: WeaverseDataContext = {}\n\n // Process matches from root to leaf, creating route-keyed structure\n for (const match of matches) {\n if (match.data && typeof match.data === 'object') {\n // Use route ID as key (e.g., \"root\", \"routes/product\")\n context[match.id] = match.data\n }\n }\n\n return context\n}\n\n/**\n * Hook to get flat route-keyed data context from matches\n * Returns: {root: {...}, \"routes/xxx\": {...}}\n * No more useLoaderData dependency - everything comes from matches\n */\nexport function useWeaverseDataContext(): WeaverseDataContext {\n const matches = useMatches()\n\n // Create flat route-keyed structure - eliminates duplication\n return createFlatDataContext(matches)\n}\n\n/**\n * Helper function to create flat route-keyed data context from useMatches() result\n * Returns: {root: {...}, \"routes/xxx\": {...}}\n */\nexport function createWeaverseDataContext(\n matches: UIMatch<unknown, unknown>[]\n): WeaverseDataContext {\n // Create flat route-keyed structure - clean and efficient\n return createFlatDataContext(matches)\n}\n\n/**\n * Type guard to check if data is WeaverseDataContext (simplified)\n */\nexport function isWeaverseDataContext(\n data: unknown\n): data is WeaverseDataContext {\n return data !== null && typeof data === 'object'\n}\n","import type { PageSEOData } from '@weaverse/schema'\nimport type { MetaDescriptor } from 'react-router'\nimport type { HydrogenPageData, WeaverseLoaderData } from './types'\n\n/** Object containing an optional Weaverse page for SEO extraction. */\nexport interface WeaverseSeoPageContainer {\n /** Page whose published SEO fields should be formatted. */\n page?: HydrogenPageData | null\n}\n\n/** Input accepted by {@link getWeaverseSeoMeta}. */\nexport type WeaverseSeoInput =\n | WeaverseLoaderData\n | HydrogenPageData\n | WeaverseSeoPageContainer\n | null\n | undefined\n\n/**\n * Convert a Weaverse page-level SEO payload into React Router\n * `MetaDescriptor[]`. Pure, synchronous, tree-shakeable — does not fetch.\n *\n * Behavior:\n * - `title` → top-level `{ title }` descriptor.\n * - `description` / `keywords` → `<meta name=\"...\">`.\n * - `canonicalUrl` → `<link rel=\"canonical\">`.\n * - `openGraph.*` → `<meta property=\"og:*\">`. `og:type` defaults to\n * `'website'` when any other OG field is present.\n * - `twitter.*` → `<meta name=\"twitter:*\">`. `twitter:card` defaults to\n * `'summary'` when any other Twitter field is present.\n * - `robots` is always emitted (defaults to `'index,follow'`) so themes\n * stacking multiple SEO sources have a deterministic last word on\n * indexing for Weaverse-managed pages.\n * - Empty strings / missing fields are filtered before return so empty\n * descriptors don't override earlier sources (e.g. Hydrogen\n * `getSeoMeta`).\n */\nexport function formatMetaDescriptors(\n seo: PageSEOData | null | undefined\n): MetaDescriptor[] {\n if (!seo) {\n return [{ name: 'robots', content: 'index,follow' }]\n }\n\n let descriptors: MetaDescriptor[] = []\n\n if (seo.title) {\n descriptors.push({ title: seo.title })\n }\n if (seo.description) {\n descriptors.push({ name: 'description', content: seo.description })\n }\n if (seo.keywords) {\n descriptors.push({ name: 'keywords', content: seo.keywords })\n }\n if (seo.canonicalUrl) {\n descriptors.push({\n tagName: 'link',\n rel: 'canonical',\n href: seo.canonicalUrl,\n })\n }\n\n let og = seo.openGraph\n if (og && (og.title || og.description || og.image || og.type)) {\n if (og.title) {\n descriptors.push({ property: 'og:title', content: og.title })\n }\n if (og.description) {\n descriptors.push({ property: 'og:description', content: og.description })\n }\n if (og.image) {\n descriptors.push({ property: 'og:image', content: og.image })\n }\n descriptors.push({ property: 'og:type', content: og.type || 'website' })\n }\n\n let tw = seo.twitter\n if (tw && (tw.title || tw.description || tw.image || tw.cardType)) {\n descriptors.push({\n name: 'twitter:card',\n content: tw.cardType || 'summary',\n })\n if (tw.title) {\n descriptors.push({ name: 'twitter:title', content: tw.title })\n }\n if (tw.description) {\n descriptors.push({ name: 'twitter:description', content: tw.description })\n }\n if (tw.image) {\n descriptors.push({ name: 'twitter:image', content: tw.image })\n }\n }\n\n let index = seo.robots?.index !== false\n let follow = seo.robots?.follow !== false\n descriptors.push({\n name: 'robots',\n content: `${index ? 'index' : 'noindex'},${follow ? 'follow' : 'nofollow'}`,\n })\n\n return descriptors\n}\n\n/**\n * Convenience accessor: pull `page.seo` out of a `WeaverseLoaderData`\n * (or `HydrogenPageData`) and emit `MetaDescriptor[]`. Null-safe.\n *\n * @example\n * ```ts\n * export const meta: MetaFunction<typeof loader> = ({ data }) => {\n * return getWeaverseSeoMeta(data?.weaverseData)\n * }\n * ```\n */\nexport function getWeaverseSeoMeta(data: WeaverseSeoInput): MetaDescriptor[] {\n if (!data) {\n return formatMetaDescriptors(null)\n }\n let page =\n 'items' in data && 'id' in data\n ? (data as HydrogenPageData)\n : ((data as WeaverseSeoPageContainer).page ?? null)\n return formatMetaDescriptors(page?.seo ?? null)\n}\n","import type {\n CachingStrategy,\n HydrogenContext,\n I18nBase,\n} from '@shopify/hydrogen'\nimport type {\n AppLoadContext,\n LoaderFunctionArgs as RemixOxygenLoaderArgs,\n} from '@shopify/remix-oxygen'\nimport type {\n ElementData,\n PositionInputValue,\n WeaverseCoreParams,\n WeaverseElement,\n WeaverseImage,\n WeaverseProjectDataType,\n WeaverseResourcePickerData,\n WeaverseVideo,\n} from '@weaverse/react'\nimport type {\n // Enhanced type exports from schema package\n BasicInput,\n ComponentAvailabilityContext,\n ComponentGroup,\n HeadingInput,\n InputType,\n InspectorGroup,\n PageSEOData,\n PageType,\n Resolvable,\n ComponentPresets as SchemaComponentPresets,\n SchemaType,\n SchemaValidationIssue,\n SchemaValidationResult,\n} from '@weaverse/schema'\nimport { isValidSchema } from '@weaverse/schema'\nimport type * as React from 'react'\nimport type { ForwardRefExoticComponent } from 'react'\nimport type { NavigateFunction } from 'react-router'\nimport type { TranslationStore } from './utils/translation-store'\nimport type { ThemeSettingsStore } from './utils/use-theme-settings-store'\nimport type { WeaverseHydrogen } from './WeaverseHydrogenRoot'\nimport type { WeaverseClient } from './weaverse-client'\n\n// Re-export CachingStrategy from Hydrogen for convenience\nexport type { CachingStrategy } from '@shopify/hydrogen'\n// Re-export types from schema for backward compatibility and convenience\nexport type {\n // Enhanced type exports\n BasicInput,\n ComponentAvailabilityContext,\n ComponentGroup,\n HeadingInput,\n InputType,\n InspectorGroup,\n PageType,\n PositionInputValue,\n Resolvable,\n SchemaValidationIssue,\n SchemaValidationResult,\n WeaverseImage,\n WeaverseVideo,\n}\n\n/** Arguments passed to a component's server-side loader. */\nexport type ComponentLoaderArgs<T = any, _E = any> = {\n /** Persisted component data merged with schema defaults. */\n data: T\n /** Request-scoped client available to the component loader. */\n weaverse: WeaverseClient\n}\n\n/** Application load context initialized with a request-scoped Weaverse client. */\nexport interface WeaverseRouteAppLoadContext extends AppLoadContext {\n /** Client used to load Weaverse content for the current request. */\n weaverse: WeaverseClient\n}\n\n/** React Router loader arguments whose app context includes the Weaverse client. */\nexport interface RouteLoaderArgs extends RemixOxygenLoaderArgs {\n /** Request-scoped application context with the initialized Weaverse client. */\n context: WeaverseRouteAppLoadContext\n}\n\n/** Primitive value accepted in a component's persisted data. */\nexport type ComponentDataValue = string | number | boolean | undefined | null\n\n/** Reference to a direct child component instance. */\nexport interface HydrogenChildComponentReference {\n /** Unique identifier of the child component instance. */\n id: string\n}\n\n/** Serialized component instance returned in a Weaverse page. */\nexport interface HydrogenComponentData extends ElementData {\n /** References to direct child component instances. */\n children?: HydrogenChildComponentReference[]\n /** ISO timestamp recording when the component instance was created. */\n createdAt?: string\n /** Persisted component setting values and structured payloads. */\n data?: Record<string, ComponentDataValue | Record<string, unknown>>\n /** ISO timestamp recording soft deletion, when applicable. */\n deletedAt?: string\n /** Unique component instance identifier. */\n id: string\n /** Registered component type used to select its renderer. */\n type: string\n /** ISO timestamp recording the latest component update. */\n updatedAt?: string\n}\n\n/**\n * Optimized: Use Zod-inferred SchemaType directly instead of extending\n * This ensures perfect type consistency with the schema validation\n */\nexport type HydrogenComponentSchema = SchemaType\n\n/** Props supplied by Weaverse when rendering a registered Hydrogen component. */\nexport interface HydrogenComponentProps<L = any> extends WeaverseElement {\n /** Rendered child component instances. */\n children?: React.JSX.Element[]\n /** Optional CSS class passed through by the renderer. */\n className?: string\n /** Result returned by the component's server-side loader. */\n loaderData?: L\n}\n\n/** Normalized request details attached to loader data for Studio navigation. */\nexport type WeaverseLoaderRequestInfo = {\n /** URL search string, including the leading question mark when present. */\n search: string\n /** Storefront request pathname. */\n pathname: string\n /** Parsed request query parameters. */\n queries: {\n /** Query parameter value keyed by parameter name. */\n [key: string]: string | boolean\n }\n /** Locale used to load the page. */\n i18n: WeaverseI18n\n}\n\n/** Published theme setting values keyed by schema setting name. */\nexport type HydrogenThemeSettings = {\n /** Published theme setting value keyed by schema setting name. */\n [key: string]: any\n}\n\n/** Project metadata returned with a Weaverse page payload. */\nexport type HydrogenProjectType = {\n /** Unique Weaverse project identifier. */\n id: string\n /** Identifier of the Shopify shop connected to the project. */\n weaverseShopId: string\n /** Human-readable project name. */\n name: string\n /** Additional project metadata returned by the content API. */\n [key: string]: any\n}\n\n/** Runtime services and project metadata exposed to Weaverse integrations. */\nexport type WeaverseInternal = {\n /** Route assignment for the rendered Weaverse page. */\n pageAssignment: HydrogenPageAssignment\n /** Metadata for the active Weaverse project. */\n project: HydrogenProjectType\n /** React Router navigation function, attached in design mode. */\n navigate: NavigateFunction\n /** Revalidates the active React Router data routes. */\n revalidate: () => void\n /** Mutable theme settings store used by Studio. */\n themeSettingsStore: ThemeSettingsStore\n /** Mutable translation store used by Studio, when translations are enabled. */\n translationStore?: TranslationStore | null\n /** @deprecated Use translationStore instead. */\n themeTextStore?: TranslationStore | null\n /** Active-locale merchant translation overrides. */\n merchantOverrides?: Record<string, unknown> | null\n}\n\n/**\n * Optimized: Use direct type alias to maintain consistency\n */\nexport type HydrogenComponentPresets = SchemaComponentPresets\n\n/** Registered runtime definition for a Hydrogen component type. */\nexport type HydrogenElement = {\n /** React renderer for this registered component type. */\n Component:\n | ForwardRefExoticComponent<HydrogenComponentProps>\n | ((props: HydrogenComponentProps) => React.JSX.Element)\n /** Unique component type matching the component schema. */\n type: string\n /** Component schema used for settings, defaults, and availability. */\n schema?: HydrogenComponentSchema\n /** Optional data loader function for server-side data fetching. */\n loader?: (args: ComponentLoaderArgs) => Promise<unknown>\n}\n\n/** Initialization parameters for a request-scoped {@link WeaverseHydrogen} runtime. */\nexport interface WeaverseHydrogenParams\n extends Omit<WeaverseCoreParams, 'ItemConstructor'> {\n /** Page content used to initialize component instances. */\n data: HydrogenPageData\n /** Route loader data made available to component data bindings. */\n dataContext?: Record<string, unknown> | null\n /** Runtime services and metadata available to integrations. */\n internal: Partial<WeaverseInternal>\n /** Whether the page is running inside the visual editor. */\n isDesignMode?: boolean\n /** Whether a component preview is being rendered. */\n isPreviewMode?: boolean\n /** Whether a saved page revision is being previewed. */\n isRevisionPreview?: boolean\n /** Identifier of the page being rendered. */\n pageId: string\n /** Identifier of the Weaverse project supplying content. */\n projectId: string\n /** Normalized URL and locale information for this request. */\n requestInfo: WeaverseLoaderRequestInfo\n /** Component type requested by section preview mode. */\n sectionType?: string\n /** Base URL used for public Weaverse API requests. */\n weaverseApiBase: string\n /**\n * API key read from environment/configuration for storefront requests or\n * supplied by Studio requests while editing and previewing.\n */\n weaverseApiKey: string\n /** Origin used for Weaverse Studio assets and editor communication. */\n weaverseHost: string\n /**\n * Public data API origin. Keep `weaverseHost` for Studio scripts/editor\n * assets; point this at the Cloudflare proxy (`https://api.weaverse.io`)\n * when edge caching is enabled.\n */\n weaversePublicApiBase?: string\n /** Optional Studio asset version used by preview integrations. */\n weaverseVersion?: string\n}\n\n/** Export shape for a renderable component, its schema, and optional loader. */\nexport type HydrogenComponent<T extends HydrogenComponentProps = any> = {\n /** React renderer exported by the component module. */\n default: ForwardRefExoticComponent<T> | ((props: T) => React.JSX.Element)\n /** Schema exported by the component module. */\n schema: HydrogenComponentSchema\n /** Optional data loader function for server-side data fetching. */\n loader?: (args: ComponentLoaderArgs) => Promise<unknown>\n}\n\n/** Weaverse Studio query parameters recognized by the Hydrogen runtime. */\nexport type WeaverseStudioQueries = {\n /** Project identifier selected by Studio for this request. */\n weaverseProjectId: string\n /** API key passed by Studio for design and preview requests. */\n weaverseApiKey: string\n /** Studio origin serving editor assets and APIs. */\n weaverseHost: string\n /** Studio asset version requested by the editor. */\n weaverseVersion: string\n /** Whether the request is for the visual editor. */\n isDesignMode: boolean\n /** Whether the request renders a component preview. */\n isPreviewMode?: boolean\n /** Component type requested for section preview. */\n sectionType?: string\n}\n\n/** Storefront-safe environment values exposed with theme settings. */\nexport type PublicEnv = {\n /** Public Shopify storefront domain. */\n PUBLIC_STORE_DOMAIN: string\n /** Public Storefront API access token. */\n PUBLIC_STOREFRONT_API_TOKEN: string\n}\n\n/** Resolved project, API endpoint, and rendering-mode configuration. */\nexport type WeaverseProjectConfigs = {\n /** Identifier of the Weaverse project supplying content. */\n projectId: string\n /** Origin used for Studio assets and editor communication. */\n weaverseHost: string\n /** Base URL used for public Weaverse content API requests. */\n weaverseApiBase: string\n /** Explicit public data API origin, when separately configured. */\n weaversePublicApiBase?: string\n /**\n * API key read from environment/configuration for storefront requests or\n * supplied by Studio requests while editing and previewing.\n */\n weaverseApiKey: string\n /** Optional Studio asset version. */\n weaverseVersion?: string\n /** Whether the request is running inside the visual editor. */\n isDesignMode?: boolean\n /** Whether the request renders a component preview. */\n isPreviewMode?: boolean\n /** Whether the request previews a saved page revision. */\n isRevisionPreview?: boolean\n /** Component type requested for section preview. */\n sectionType?: string\n /** Storefront-safe environment values exposed with theme settings. */\n publicEnv?: PublicEnv\n}\n\n/** Assignment describing which project page handles a storefront route. */\nexport type HydrogenPageAssignment = {\n /** Project identifier owning the assigned page. */\n projectId: string\n /** Storefront page type matched by the assignment. */\n type: PageType\n /** Route or resource handle matched by the assignment. */\n handle: string\n /** Locale matched by the assignment. */\n locale: string\n /** Inheritance details when the assignment comes from another project. */\n meta?: {\n /** Whether the assignment was inherited. */\n inherited: boolean\n /** Project identifier where the assignment originated. */\n sourceProjectId: string\n /** Number of inheritance levels traversed. */\n depth: number\n }\n}\n\n/** Complete payload returned by {@link WeaverseClient.loadPage}. */\nexport type WeaverseLoaderData = {\n /** Resolved runtime configuration and normalized request details. */\n configs: Omit<WeaverseProjectConfigs, 'publicEnv'> & {\n /** Normalized URL and locale information for the request. */\n requestInfo: WeaverseLoaderRequestInfo\n }\n /** Published page content to render. */\n page: HydrogenPageData\n /** Metadata for the project supplying the page. */\n project: HydrogenProjectType\n /** Route assignment that selected the page, when available. */\n pageAssignment?: HydrogenPageAssignment\n}\n\n/** Published Weaverse page content consumed by the Hydrogen renderer. */\nexport interface HydrogenPageData extends WeaverseProjectDataType {\n /** Internal cache identifier attached by the content API when available. */\n __cacheId?: string\n /** Unique page identifier. */\n id: string\n /** Serialized component instances belonging to the page. */\n items: HydrogenComponentData[]\n /** Human-readable page name. */\n name: string\n /**\n * Page-level SEO metadata published by Weaverse Builder. `null` when\n * the page has no `PageSeo` row; absent on revision snapshots that\n * predate the SEO feature. Themes should treat both as \"no Weaverse\n * override\".\n */\n seo?: PageSEOData | null\n /** Additional page fields supplied by the content API. */\n [key: string]: any\n}\n\n/** Locale metadata used when requesting localized Weaverse content. */\nexport type WeaverseI18n = I18nBase & {\n /** Human-readable locale label displayed in Studio. */\n label?: string\n /** Locale path prefix used by the storefront router. */\n pathPrefix?: string\n /** Additional locale metadata supplied by the storefront. */\n [key: string]: any\n}\n\n/** Theme metadata, global settings, and localization configuration. */\nexport type HydrogenThemeSchema = {\n /** Theme identity, author, and support metadata. */\n info: {\n /** Human-readable theme name. */\n name: string\n /** Theme version displayed in Studio. */\n version: string\n /** Theme author name. */\n author: string\n /** URL of the theme author's profile image. */\n authorProfilePhoto: string\n /** URL of the theme documentation. */\n documentationUrl: string\n /** URL where merchants can request theme support. */\n supportUrl: string\n }\n /** @deprecated Use settings instead. */\n inspector?: InspectorGroup[]\n /**\n * Store-wide defaults for the Media Manager gallery. Mirrors\n * `MediaInputConfigs` in `@weaverse/schema`, which documents the fields.\n *\n * Deliberately a sibling of `settings` rather than an entry inside it:\n * `settings` renders as merchant-editable controls in Studio, and these\n * rules are meant to be fixed by the theme author. An individual `image` or\n * `video` input can still override them through its own `configs`.\n *\n * Note: duplicated instead of imported because this package pins the\n * published `@weaverse/schema`, which does not export the type yet. Replace\n * with the shared type once schema ships it.\n */\n media?: {\n /** Filename prefixes hidden from the Media Manager gallery. */\n excludeFilenamePrefixes?: string[]\n /** Hide files used in products. Matches usage, not origin. */\n excludeProductFiles?: boolean\n }\n /** Groups of global theme settings exposed in Studio. */\n settings?: InspectorGroup[]\n /** Theme localization configuration. */\n i18n?: {\n /** Strategy used to encode the locale in storefront URLs. */\n urlStructure: 'url-path' | 'subdomain' | 'top-level-domain'\n /** Locale used when no localized route is selected. */\n defaultLocale: WeaverseI18n\n /** Locales enabled for the connected Shopify shop. */\n shopLocales: WeaverseI18n[]\n /** Default-locale static translation content. */\n staticContent?: Record<string, unknown>\n /** Enable the translation UI in the builder. */\n translation?: boolean\n }\n}\n\n/** Request body sent to the Weaverse project content endpoint. */\nexport type FetchProjectRequestBody = {\n /** Identifier of the project to load. */\n projectId: string\n /** Normalized storefront URL being resolved. */\n url: string\n /** Storefront locale for localized content. */\n i18n?: WeaverseI18n\n /** Optional route-specific page lookup parameters. */\n params?: {\n /** Storefront page type to load. */\n type?: PageType\n /** Locale override for this page lookup. */\n locale?: string\n /** Resource or custom-page handle to load. */\n handle?: string\n }\n /** Whether draft editor content should be returned. */\n isDesignMode?: boolean\n}\n\n/** Project content response before it is normalized into loader data. */\nexport type FetchProjectPayload = {\n /** Published or draft page content; absent when no page matches. */\n page?: HydrogenPageData\n /** Project metadata; absent in some error responses. */\n project?: HydrogenProjectType\n /** Assignment that selected the page, when one matched. */\n pageAssignment?: HydrogenPageAssignment\n /** API error message, when the request could not be fulfilled. */\n error?: string\n /** Additional fields returned by compatible API versions. */\n [key: string]: any\n}\n\n/**\n * Project identifier value - can be static string or dynamic function.\n *\n * **Static String**: Direct project ID reference\n * ```ts\n * 'project-abc-123'\n * ```\n *\n * **Synchronous Function**: Returns project ID based on request context\n * ```ts\n * () => {\n * const host = new URL(request.url).hostname\n * return PROJECT_MAP[host] || 'default-project'\n * }\n * ```\n *\n * **Asynchronous Function**: Async project resolution (must be awaited before passing)\n * ```ts\n * async () => {\n * return await database.getProjectId(userId)\n * }\n * ```\n */\nexport type ProjectIdValue = string | (() => string) | (() => Promise<string>)\n\n/**\n * Type guard for detecting function-based projectId.\n *\n * Used internally by WeaverseClient constructor to determine\n * if projectId needs evaluation or can be used directly.\n */\nexport function isProjectIdFunction(\n projectId: ProjectIdValue | undefined\n): projectId is (() => string) | (() => Promise<string>) {\n return typeof projectId === 'function'\n}\n\n/**\n * Extended WeaverseClient constructor arguments supporting multi-project architecture.\n *\n * @example Static project (existing pattern - backward compatible)\n * ```ts\n * const weaverse = new WeaverseClient({\n * ...hydrogenContext,\n * projectId: 'project-default-123'\n * })\n * ```\n *\n * @example Dynamic project selection (new capability)\n * ```ts\n * const weaverse = new WeaverseClient({\n * ...hydrogenContext,\n * projectId: () => {\n * const origin = new URL(request.url).origin\n * if (origin === 'https://mystore.se') return process.env.WEAVERSE_PROJECT_SWEDEN!\n * if (origin === 'https://mystore.fr') return process.env.WEAVERSE_PROJECT_FRANCE!\n * return process.env.WEAVERSE_PROJECT_ID!\n * }\n * })\n * ```\n *\n * **Priority Chain** (highest to lowest):\n * 1. URL query parameter: `?weaverseProjectId=...` (design mode, preview mode)\n * 2. Function result (if function provided)\n * 3. Explicit string value (if string provided)\n * 4. Environment variable: `WEAVERSE_PROJECT_ID` (Hydrogen env or process.env)\n * 5. Empty string (triggers validation error in methods)\n *\n * **Function Requirements**:\n * - Must return non-empty string\n * - Can access request via closure for routing decisions\n * - Evaluated once per WeaverseClient instance (request-scoped)\n * - Async functions must be awaited before passing to constructor\n * - Should handle edge cases (missing headers, invalid domains, etc.)\n *\n * **Request Context Access**:\n * Functions access request via closure from constructor arguments.\n */\nexport type WeaverseClientArgs = HydrogenContext & {\n /**\n * React components registered with Weaverse CMS.\n * Each component must have a schema defining its properties and settings.\n */\n components: HydrogenComponent[]\n\n /**\n * Theme schema defining global theme settings (colors, fonts, layouts).\n * Used to generate default theme configuration and validate theme data.\n */\n themeSchema: HydrogenThemeSchema\n\n /**\n * Incoming HTTP request object from React Router loader.\n * Provides access to URL, headers, cookies for dynamic routing decisions.\n */\n request: Request\n\n /**\n * Hydrogen cache instance for content caching.\n *Supports multi-tenant caching with project-specific cache keys.\n */\n cache: Cache\n\n /**\n * Project identifier for loading content from Weaverse CMS.\n *\n * **Value Types**:\n * - Static string: 'project-123' (existing usage)\n * - Synchronous function: () => determineProject(request)\n * - Asynchronous function: async () => await getProject(request) (must be awaited)\n *\n * **Backward Compatibility**:\n * - Optional parameter (defaults to environment variable)\n * - Existing code without projectId continues to work unchanged\n *\n * **Cache Isolation**:\n * ProjectId is included in cache keys to prevent cross-project content pollution.\n * Each project's content is cached separately, ensuring multi-tenant isolation.\n */\n projectId?: ProjectIdValue\n\n /**\n * Fetch timeout in milliseconds for API requests.\n * Defaults to 10000ms (10 seconds) if not specified.\n * Useful for adjusting based on network conditions or deployment environment.\n *\n * @default 10000\n * @example\n * ```typescript\n * new WeaverseClient({\n * // ... other args\n * fetchTimeoutMs: 5000 // 5 second timeout\n * })\n * ```\n */\n fetchTimeoutMs?: number\n}\n\n/** Product selected through a Weaverse resource-picker setting. */\nexport type WeaverseProduct = WeaverseResourcePickerData\n/** Collection selected through a Weaverse resource-picker setting. */\nexport type WeaverseCollection = WeaverseResourcePickerData\n/** Blog selected through a Weaverse resource-picker setting. */\nexport type WeaverseBlog = WeaverseResourcePickerData\n/** Article selected through a Weaverse resource-picker setting. */\nexport type WeaverseArticle = WeaverseResourcePickerData\n/** Metaobject selected through a Weaverse resource-picker setting. */\nexport type WeaverseMetaObject = WeaverseResourcePickerData\n\n/** Response returned by Hydrogen's cached fetch helper. */\nexport type WithCacheFetchResponse<T> = {\n /** Parsed response payload. */\n data: T\n /** Underlying Fetch API response. */\n response: Response\n}\n\n/** Theme configuration returned by the Weaverse project API. */\nexport type ThemeSettingsResponse = {\n /** Published theme setting values. */\n theme?: HydrogenThemeSettings\n /** Theme schema included for Studio editing. */\n schema?: HydrogenThemeSchema\n /** Storefront-safe environment values included in design mode. */\n publicEnv?: PublicEnv\n /** Theme's default locale JSON from `themeSchema.i18n.staticContent`. */\n staticContent?: Record<string, unknown>\n /** Locale-specific merchant overrides from the API. */\n merchantOverrides?: Record<string, unknown>\n /** Diagnostic message when loading fell back to schema defaults. */\n _error?: string\n /** Whether remote theme settings failed to load. */\n _loadFailed?: boolean\n}\n\n/**\n * Legacy data-or-error response shape retained for compatibility.\n *\n * The client's current direct-fetch implementation uses\n * {@link WithCacheFetchResponse} internally instead of returning this shape.\n */\nexport type DirectFetchResponse<T = unknown> = {\n /** Parsed payload when the legacy request succeeded. */\n data?: T\n /** Error message when the legacy request failed. */\n error?: string\n}\n\n/** Predicate used to decide whether a fetched response may be cached. */\nexport type CacheResponseValidator<T = unknown> = (\n response: WithCacheFetchResponse<T> | T\n) => boolean\n\n/** Error raised by Weaverse requests with a stable code and optional context. */\nexport class WeaverseError extends Error {\n /** Machine-readable error code. */\n public readonly code: string\n /** HTTP status associated with the failure, when available. */\n public readonly statusCode?: number\n /** Structured diagnostic details for logging and error handling. */\n public readonly context?: Record<string, unknown>\n\n /** Creates a Weaverse request error with a stable code and diagnostics. */\n constructor(\n message: string,\n code = 'WEAVERSE_ERROR',\n statusCode?: number,\n context?: Record<string, unknown>\n ) {\n super(message)\n this.name = 'WeaverseError'\n this.code = code\n this.statusCode = statusCode\n this.context = context\n\n // Maintains proper stack trace for where our error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, WeaverseError)\n }\n }\n}\n\n/**\n * Validation result type for project ID validation.\n * Returns validation status with optional error message.\n */\nexport type ProjectIdValidationResult = {\n /** Whether the project identifier passed validation. */\n valid: boolean\n /** Validation error message when `valid` is false. */\n error?: string\n}\n\n/** Published custom page entry suitable for sitemap generation. */\nexport interface CustomPageEntry {\n /** Suggested sitemap update frequency. */\n changeFrequency?: 'daily' | 'weekly' | 'monthly'\n /** Weaverse custom page handle. */\n handle: string\n /** ISO timestamp of the latest published update. */\n lastModified: string\n /** Locale code, or `null` for the project's default locale. */\n locale: string | null\n /** Storefront path for the custom page. */\n path: string\n /** Optional sitemap priority from zero to one. */\n priority?: number\n}\n\n/**\n * Type guards for response validation\n */\n\nexport function isWithCacheFetchResponse<T>(\n response: unknown\n): response is WithCacheFetchResponse<T> {\n return (\n typeof response === 'object' &&\n response !== null &&\n 'data' in response &&\n 'response' in response\n )\n}\n\n/** Checks whether a value contains the required project response fields. */\nexport function isFetchProjectPayload(\n payload: unknown\n): payload is FetchProjectPayload {\n return (\n typeof payload === 'object' &&\n payload !== null &&\n 'page' in payload &&\n 'project' in payload &&\n 'pageAssignment' in payload\n )\n}\n\n/** Response containing an error message returned by a Weaverse request. */\nexport interface WeaverseErrorResponse {\n /** Human-readable request failure message. */\n error: string\n}\n\n/** Checks whether a response contains a string error message. */\nexport function hasError(response: unknown): response is WeaverseErrorResponse {\n return (\n typeof response === 'object' &&\n response !== null &&\n 'error' in response &&\n typeof (response as Record<string, unknown>).error === 'string'\n )\n}\n\n/** Checks whether a value contains a theme settings object. */\nexport function isThemeSettingsResponse(\n data: unknown\n): data is ThemeSettingsResponse {\n if (typeof data !== 'object' || data === null) {\n return false\n }\n\n const record = data as Record<string, unknown>\n return (\n 'theme' in record &&\n typeof record.theme === 'object' &&\n record.theme !== null\n )\n}\n\n/**\n * Enhanced type utilities for better development experience\n */\nexport type HydrogenSchemaValidationResult =\n SchemaValidationResult<HydrogenComponentSchema>\n\n/**\n * Type guard to check if a schema is valid.\n * Leverages validation from @weaverse/schema package which provides\n * comprehensive Zod-based validation with the ElementSchema.\n *\n * @param schema - Unknown value to validate\n * @returns True if schema is a valid HydrogenComponentSchema\n *\n * @example\n * ```typescript\n * if (isValidHydrogenSchema(userInput)) {\n * // userInput is now typed as HydrogenComponentSchema\n * console.log(userInput.type)\n * }\n * ```\n */\nexport function isValidHydrogenSchema(\n schema: unknown\n): schema is HydrogenComponentSchema {\n // Use the comprehensive validation from @weaverse/schema package\n return isValidSchema(schema)\n}\n\n/** Type-safe component schema authoring options. */\nexport type CreateHydrogenSchemaOptions = {\n /** Human-readable component title displayed in Studio. */\n title: string\n /** Unique component type used for registration and persisted items. */\n type: string\n /** Maximum number of instances allowed in the containing scope. */\n limit?: number\n /** Inspector groups defining editable component settings. */\n settings?: InspectorGroup[]\n /** Component types allowed as direct children. */\n childTypes?: string[]\n /**\n * Legacy page and placement availability restrictions.\n *\n * @deprecated Use `enabled` instead. Convert the arrays to checks in an\n * `enabled` resolver, for example:\n * `enabled: ({page, group}) => pages.includes(page.type) &&\n * (groups.includes('*') || groups.includes(group))`.\n */\n enabledOn?: {\n /** Page types where the component can be inserted. */\n pages?: PageType[]\n /** Placement groups where the component can be inserted; `*` allows all. */\n groups?: ('*' | 'header' | 'footer' | 'body')[]\n }\n /** Static or context-aware component availability rule. */\n enabled?: Resolvable<boolean, ComponentAvailabilityContext>\n /** Default component data and optional nested component presets. */\n presets?: {\n /** Components inserted as children by the preset. */\n children?: SchemaComponentPresets[]\n /** Additional default setting value keyed by setting name. */\n [key: string]: any\n }\n}\n\n// Extended window interface for hydrogen-specific globals\ndeclare global {\n interface Window {\n __weaverse?: WeaverseHydrogen\n __weaverses?: Record<string, WeaverseHydrogen>\n __weaverseThemeSettingsStore?: ThemeSettingsStore\n }\n}\n\n/** Browser bridge exposed by Weaverse Studio in design and preview modes. */\nexport interface WeaverseStudio {\n /** Connects Studio to a newly created Hydrogen runtime. */\n init: (weaverse: WeaverseHydrogen) => void\n /** Refreshes Studio after the active runtime configuration changes. */\n refreshStudio: (params: WeaverseHydrogenParams) => void\n}\n\n/** Browser window after the Weaverse Studio bridge has initialized. */\nexport interface WeaverseStudioWindow extends Window {\n /** Studio bridge used to initialize and refresh the Hydrogen runtime. */\n weaverseStudio: WeaverseStudio\n}\n\n/** Checks whether the browser window exposes the Weaverse Studio bridge. */\nexport function hasWeaverseStudio(\n window: Window\n): window is WeaverseStudioWindow {\n return 'weaverseStudio' in window && typeof window.weaverseStudio === 'object'\n}\n\ndeclare module '@shopify/remix-oxygen' {\n interface AppLoadContext {\n weaverse: WeaverseClient\n }\n}\n\ndeclare module '@shopify/hydrogen' {\n interface HydrogenEnv {\n CUSTOM_COLLECTION_BANNER_METAFIELD: string\n JUDGEME_PRIVATE_API_TOKEN: string\n KLAVIYO_PRIVATE_API_TOKEN: string\n METAOBJECT_COLOR_NAME_KEY: string\n METAOBJECT_COLOR_VALUE_KEY: string\n METAOBJECT_COLORS_TYPE: string\n PUBLIC_GOOGLE_GTM_ID: string\n PUBLIC_SHOPIFY_INBOX_SHOP_ID: string\n PUBLIC_STORE_DOMAIN: string\n PUBLIC_STOREFRONT_API_TOKEN: string\n WEAVERSE_API_KEY: string\n WEAVERSE_HOST?: string\n WEAVERSE_PROJECT_ID: string\n WEAVERSE_PUBLIC_API_BASE?: string\n }\n}\n\n/**\n * Parameters for loadPage method supporting route-level project override.\n *\n * @example Basic usage (uses client-level project)\n * ```ts\n * const weaverseData = await weaverse.loadPage({\n * type: 'PRODUCT',\n * handle: params.productHandle\n * })\n * ```\n *\n * @example Route-level project override\n * ```ts\n * export async function loader({ params, context }: LoaderFunctionArgs) {\n * const { weaverse } = context\n *\n * // Use special campaign project for this route only\n * const weaverseData = await weaverse.loadPage({\n * type: 'PRODUCT',\n * handle: params.productHandle,\n * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN // Override\n * })\n *\n * return { weaverseData }\n * }\n * ```\n */\nexport type LoadPageParams = {\n /**\n * Page type to load from Weaverse CMS.\n *\n * Determines which template to use for rendering the page.\n * Falls back to 'INDEX' if not specified or if page type doesn't exist.\n *\n * @default 'INDEX'\n */\n type?: PageType\n\n /**\n * Locale for internationalization.\n *\n * Format: IETF BCP 47 language tag (e.g., 'en-US', 'fr-FR', 'de-DE')\n * Used to load locale-specific content and translations.\n */\n locale?: string\n\n /**\n * Page handle for dynamic pages.\n *\n * Identifies specific resource within page type:\n * - Product handle: 'red-sneakers'\n * - Collection handle: 'summer-sale'\n * - Page handle: 'about-us'\n * - Article handle: 'how-to-style-sneakers'\n */\n handle?: string\n\n /**\n * Cache strategy override for this specific page load.\n *\n * Overrides default cache strategy for special use cases:\n * - Fresh content for checkout pages (no cache)\n * - Long-lived cache for static pages (1 hour+)\n * - Short-lived cache for frequently updated content (5 minutes)\n */\n strategy?: CachingStrategy\n\n /**\n * Optional project override for this specific page load.\n *\n * **Precedence**: Route-level projectId takes precedence over client-level projectId.\n *\n * **Use Cases**:\n * - Campaign landing pages with custom content\n * - VIP customer experiences with dedicated projects\n * - A/B testing specific pages without changing global config\n * - Seasonal promotions with limited-time content\n *\n * **Validation**:\n * - Must be non-empty string\n * - Validated before API call\n * - Falls back to client-level projectId if undefined\n * - Does NOT support function (string only)\n *\n * **Cache Isolation**:\n * Override projectId is included in cache key, ensuring separate caches\n * for different projects even on the same route.\n *\n * @example Campaign page override\n * ```ts\n * const campaignData = await weaverse.loadPage({\n * type: 'PAGE',\n * handle: 'summer-sale',\n * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN\n * })\n * ```\n */\n projectId?: string\n}\n\n// ─── Translation sidecar types (design mode) ─────────────────────────\n\n/** A single translated field for one item. */\nexport interface TranslationMapEntry {\n /** Source-locale value used to detect subsequent content changes. */\n originalValue: string\n /** Localized value rendered for the target locale. */\n translatedValue: string\n}\n\n/** Per-item translation fields, keyed by field name */\nexport type TranslationItemEntry = {\n /** Translation entry keyed by component field name. */\n [key: string]: TranslationMapEntry\n}\n\n/**\n * Translation map sent from the builder alongside page data in design mode.\n * Keyed by item ID, each value maps field names to translation entries.\n */\nexport type TranslationMap = {\n /** Translated fields keyed by component instance identifier. */\n [itemId: string]: TranslationItemEntry\n}\n\n/** A single translation entry for save payloads. */\nexport interface TranslationEntry {\n /** Marks an existing translation for deletion. */\n deleted?: boolean\n /** Identifier of the component instance owning the field. */\n itemId: string\n /** Dot-path to the translated component field. */\n key: string\n /** Source-locale value used to detect content changes. */\n originalValue: string\n /** Localized value to persist. */\n translatedValue: string\n}\n\n/** Result of collecting translation changes for the save flow */\nexport type TranslationChanges = {\n /** Builder language identifier receiving the changes. */\n languageId: string\n /** Translation entries to create, update, or delete. */\n entries: TranslationEntry[]\n}\n","/** Rendering mode and host details used to select a Studio bridge script. */\nexport interface StudioMode {\n /** Whether the storefront is running inside the visual editor. */\n isDesignMode?: boolean\n /** Whether a component preview is being rendered. */\n isPreviewMode?: boolean\n /** Whether a saved page revision is being previewed. */\n isRevisionPreview?: boolean\n /** Trusted origin serving Studio bridge assets. */\n weaverseHost: string\n /** Studio asset version appended to the script URL. */\n weaverseVersion: string\n}\n\nconst DEFAULT_WEAVERSE_HOST = 'https://studio.weaverse.io'\n\n/**\n * Weaverse-controlled apex domains the Studio bridge may be served from\n * (matched on the host itself and any subdomain).\n */\nconst TRUSTED_STUDIO_DOMAINS = ['weaverse.io', 'weaverse.dev']\n\nfunction isLoopbackHostname(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname.endsWith('.localhost')\n )\n}\n\nexport interface TrustedStudioHostOptions {\n /**\n * Also trust loopback hosts (`localhost` / `127.0.0.1` / `*.localhost`) over\n * http or https.\n *\n * Only safe when the **storefront itself** is loopback (genuine local-builder\n * dev). A production https page can still load a loopback script — loopback is\n * a \"potentially trustworthy\" origin and is not blocked as mixed content — so\n * honoring a query-supplied loopback host on a public storefront would let a\n * crafted link run whatever a visitor's local service serves inside the\n * storefront origin. MUST stay off on the server, where it is an SSRF vector\n * for page/theme fetches.\n */\n allowLoopback?: boolean\n}\n\n/**\n * Whether `host` is an origin we trust to serve the Studio bridge script (or,\n * server-side, to resolve page/theme data).\n *\n * The bridge executes inside the storefront document and the host can drive\n * server-side fetches, so a host taken from an attacker-controllable source —\n * e.g. a crafted `?weaverseHost=` query — is both an XSS and an SSRF vector.\n * Callers MUST reject untrusted hosts before acting on them. Trusts\n * `weaverse.io`/`weaverse.dev` and their subdomains over https; loopback is\n * opt-in (see {@link TrustedStudioHostOptions.allowLoopback}).\n */\nexport function isTrustedStudioHost(\n host: string,\n options?: TrustedStudioHostOptions\n): boolean {\n let parsed: URL\n try {\n parsed = new URL(host)\n } catch {\n return false\n }\n let { hostname, protocol } = parsed\n // Loopback (opt-in) is the only place http is allowed — a local builder\n // serves the bridge over http and there is no cleartext-downgrade risk to a\n // private address. Every other trusted host must be https so server-side\n // page/theme fetches are never downgraded to cleartext.\n if (options?.allowLoopback && isLoopbackHostname(hostname)) {\n return protocol === 'http:' || protocol === 'https:'\n }\n if (protocol !== 'https:') {\n return false\n }\n return TRUSTED_STUDIO_DOMAINS.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`)\n )\n}\n\n/**\n * Build the Studio bridge script URL for the current mode, or `null` when the\n * storefront is not being previewed inside Weaverse Studio.\n *\n * This is the single gate that keeps the bridge off production storefronts:\n * a normal visitor's URL carries none of the design/preview markers, so the\n * result is `null` and no script is ever requested.\n *\n * Shared by the page-scoped `useStudio` (which also binds the page for\n * editing) and the root-level `useStudioConnect` (which only needs the script\n * to load so Studio's `checkWeaversePage()` handshake can answer on routes\n * with no Weaverse content).\n */\nexport function getStudioScriptSrc(mode: StudioMode): string | null {\n let {\n isDesignMode,\n isPreviewMode,\n isRevisionPreview,\n weaverseHost,\n weaverseVersion,\n } = mode\n let base = `${weaverseHost}/static/studio/hydrogen`\n let version = `?v=${weaverseVersion}`\n if (isRevisionPreview || isPreviewMode) {\n return `${base}/preview.js${version}`\n }\n if (isDesignMode) {\n return `${base}/index.js${version}`\n }\n return null\n}\n\n/**\n * Resolve the Studio bridge script URL from a URL query string — the markers\n * Studio attaches when it drives the preview iframe (`isDesignMode`,\n * `isPreviewMode`, `__revisionId`, `weaverseHost`, `weaverseVersion`) — or\n * `null` outside Studio.\n *\n * `storefrontHostname` is the document's own hostname: a loopback Studio host\n * is only honored when the storefront itself is loopback (genuine local-builder\n * dev), so a crafted public link can't load a script from a visitor's loopback\n * service into the storefront origin.\n *\n * The `weaverseHost` query is attacker-controllable, so a host that is not a\n * {@link isTrustedStudioHost trusted origin} resolves to `null` (no bridge) —\n * it is never silently replaced with production Studio, which would otherwise\n * inject the wrong bridge for self-hosted/staging deployments. Such deployments\n * (a non-`weaverse.io` `WEAVERSE_HOST`) therefore don't load the root bridge on\n * content-less routes; the page-scoped {@link getStudioScriptSrc} via\n * `useStudio` still uses the configured host on content routes.\n *\n * Pure (no DOM) so the root-level connect's production gate stays unit-testable\n * and needs no loader data.\n */\nexport function resolveStudioScriptSrc(\n search: string,\n storefrontHostname = ''\n): string | null {\n let params = new URLSearchParams(search)\n // Match the server's getRequestQueries(), which keeps the LAST value of a\n // duplicated key. Studio appends its own control params, so a pre-existing\n // (stale/untrusted) `weaverseHost` earlier in the URL must not win here, or\n // the root bridge would be skipped while the loader uses the later host.\n let last = (key: string) => params.getAll(key).at(-1)\n let host = last('weaverseHost')\n if (host) {\n let allowLoopback = isLoopbackHostname(storefrontHostname)\n if (!isTrustedStudioHost(host, { allowLoopback })) {\n return null\n }\n }\n return getStudioScriptSrc({\n isDesignMode: last('isDesignMode') === 'true',\n isPreviewMode: last('isPreviewMode') === 'true',\n isRevisionPreview: params.has('__revisionId'),\n weaverseHost: host || DEFAULT_WEAVERSE_HOST,\n weaverseVersion: last('weaverseVersion') || '',\n })\n}\n","import type { HydrogenEnv } from '@shopify/hydrogen'\nimport type {\n HydrogenComponent,\n HydrogenComponentSchema,\n HydrogenThemeSchema,\n WeaverseLoaderData,\n WeaverseProjectConfigs,\n WeaverseStudioQueries,\n} from '../types'\nimport { isTrustedStudioHost } from './studio-script-src'\n\n// Track warned types to avoid spam\nlet warnedTypes = new Set<string>()\n\nfunction logOnce(type: string, message: string) {\n if (!warnedTypes.has(type)) {\n console.warn(message)\n warnedTypes.add(type)\n }\n}\n\nfunction deepMergeArrays<T>(target: T[], source: T[]): T[] {\n return [...target, ...source]\n}\n\nfunction mergeInspectorSettings(\n settings: any[],\n inspector: any[],\n type: string\n): any[] {\n if (!inspector?.length) {\n return settings\n }\n if (!settings?.length) {\n return inspector\n }\n\n // Log collision notice\n console.info(\n `Schema \"${type}\": Both 'settings' and 'inspector' found. Using 'settings' with 'inspector' as fallback.`\n )\n\n return deepMergeArrays(settings, inspector)\n}\n\n/** Options for extracting query parameters from a request URL. */\nexport interface RequestQueryOptions {\n /** Query parameter names to include; all parameters are included when omitted. */\n allowedKeys?: string[]\n}\n\n/**\n * Extract and parse query parameters from a request URL.\n * Supports optional allowlist for security-sensitive applications.\n *\n * @param request - The incoming request\n * @param options - Optional configuration\n * @param options.allowedKeys - If provided, only these keys will be extracted\n * @returns Parsed query parameters with type coercion for booleans\n *\n * @example\n * ```typescript\n * // Extract all params\n * const queries = getRequestQueries(request)\n *\n * // Extract only allowed params (security-sensitive)\n * const queries = getRequestQueries(request, {\n * allowedKeys: ['weaverseProjectId', 'weaverseHost']\n * })\n * ```\n */\nexport function getRequestQueries<T = Record<string, string | boolean>>(\n request: Request,\n options?: RequestQueryOptions\n): T {\n let url = new URL(request.url)\n let queries: Record<string, unknown> = {}\n\n for (let [key, value] of url.searchParams.entries()) {\n // If allowlist provided, skip non-allowed keys\n if (options?.allowedKeys && !options.allowedKeys.includes(key)) {\n continue\n }\n\n // Type-safe conversion for known boolean patterns\n if (value === 'true') {\n queries[key] = true\n } else if (value === 'false') {\n queries[key] = false\n } else {\n queries[key] = value\n }\n }\n\n return queries as T\n}\n\n/**\n * Resolves project, endpoint, and Studio mode configuration for a request.\n * URL-provided Studio values take precedence over environment defaults.\n */\nexport function getWeaverseConfigs(\n request: Request,\n env: HydrogenEnv\n): WeaverseProjectConfigs {\n let queries = getRequestQueries<WeaverseStudioQueries>(request)\n let {\n WEAVERSE_PROJECT_ID,\n WEAVERSE_API_KEY,\n WEAVERSE_HOST,\n WEAVERSE_PUBLIC_API_BASE,\n PUBLIC_STORE_DOMAIN,\n PUBLIC_STOREFRONT_API_TOKEN,\n } = env || {}\n let envFromProcess = (typeof process !== 'undefined' && process.env) || {}\n let {\n weaverseProjectId,\n weaverseHost,\n isDesignMode,\n isPreviewMode,\n sectionType,\n weaverseVersion,\n weaverseApiKey,\n } = queries\n\n let url = new URL(request.url)\n let isRevisionPreview = url.searchParams.has('__revisionId')\n let configuredWeaverseHost = WEAVERSE_HOST || envFromProcess.WEAVERSE_HOST\n // `weaverseHost` arrives from the request URL (Studio drives the preview\n // iframe with it), so it is attacker-controllable; only honor it when it is a\n // trusted Weaverse origin, otherwise fall back to the env/default host. This\n // stops a crafted `?weaverseHost=` from pointing Studio scripts or data reads\n // at an arbitrary origin.\n let trustedUrlHost =\n typeof weaverseHost === 'string' && isTrustedStudioHost(weaverseHost)\n ? weaverseHost\n : ''\n let resolvedWeaverseHost =\n trustedUrlHost || configuredWeaverseHost || 'https://studio.weaverse.io'\n // Public data reads default to the edge proxy, but an explicit custom\n // WEAVERSE_HOST (staging/self-hosted Weaverse) must stay the API base so\n // those deployments don't fetch page/config data from the production proxy.\n let resolvedWeaverseApiBase = trustedUrlHost\n ? trustedUrlHost\n : WEAVERSE_PUBLIC_API_BASE ||\n envFromProcess.WEAVERSE_PUBLIC_API_BASE ||\n (configuredWeaverseHost &&\n configuredWeaverseHost !== 'https://studio.weaverse.io'\n ? configuredWeaverseHost\n : 'https://api.weaverse.io')\n\n return {\n projectId:\n weaverseProjectId ||\n WEAVERSE_PROJECT_ID ||\n envFromProcess.WEAVERSE_PROJECT_ID ||\n '',\n weaverseHost: resolvedWeaverseHost,\n weaverseApiBase: resolvedWeaverseApiBase,\n weaversePublicApiBase: resolvedWeaverseApiBase,\n weaverseApiKey:\n weaverseApiKey ||\n WEAVERSE_API_KEY ||\n envFromProcess.WEAVERSE_API_KEY ||\n '',\n weaverseVersion: weaverseVersion || '',\n isDesignMode,\n isPreviewMode,\n isRevisionPreview,\n sectionType: sectionType || '',\n publicEnv: {\n PUBLIC_STORE_DOMAIN: PUBLIC_STORE_DOMAIN || '',\n PUBLIC_STOREFRONT_API_TOKEN: PUBLIC_STOREFRONT_API_TOKEN || '',\n },\n }\n}\n\n/**\n * Cache for generateDataFromSchema results using WeakMap.\n * WeakMap allows garbage collection when schema objects are no longer referenced.\n */\nconst schemaDefaultsCache = new WeakMap<\n HydrogenComponentSchema | HydrogenThemeSchema,\n Record<string, any>\n>()\n\n/**\n * Generate default data from component or theme schema.\n * Results are memoized using WeakMap for performance.\n *\n * @param schema - Component or theme schema\n * @returns Default data object extracted from schema inputs\n */\nexport function generateDataFromSchema(\n schema: HydrogenComponentSchema | HydrogenThemeSchema\n) {\n // Check cache first for performance\n const cached = schemaDefaultsCache.get(schema)\n if (cached) {\n return cached\n }\n\n let data: Record<string, any> = {}\n\n // Handle migration from inspector to settings\n let inspectorGroups: any[] = []\n\n // Type guard to check if it's a component schema\n const isComponentSchema = (\n s: HydrogenComponentSchema | HydrogenThemeSchema\n ): s is HydrogenComponentSchema => 'type' in s && typeof s.type === 'string'\n\n if (isComponentSchema(schema)) {\n // Handle HydrogenComponentSchema\n if (schema.settings) {\n inspectorGroups = schema.settings\n }\n\n if (schema.inspector) {\n if (schema.settings?.length) {\n // Both exist - merge with settings taking priority\n inspectorGroups = mergeInspectorSettings(\n schema.settings,\n schema.inspector,\n schema.type || 'unknown'\n )\n } else {\n // Only inspector exists - use it but warn about deprecation\n inspectorGroups = schema.inspector\n if (schema.type) {\n logOnce(\n schema.type,\n `⚠️ Schema \"${schema.type}\": The 'inspector' property is deprecated. Please use 'settings' instead.`\n )\n }\n }\n }\n } else {\n // Handle HydrogenThemeSchema\n if (schema.settings) {\n inspectorGroups = schema.settings\n }\n\n if (schema.inspector) {\n if (schema.settings?.length) {\n // Both exist - merge with settings taking priority\n inspectorGroups = mergeInspectorSettings(\n schema.settings,\n schema.inspector,\n 'Theme Schema'\n )\n } else {\n // Only inspector exists - use it but warn about deprecation\n inspectorGroups = schema.inspector\n logOnce(\n 'ThemeSchema',\n `⚠️ Theme Schema: The 'inspector' property is deprecated. Please use 'settings' instead.`\n )\n }\n }\n }\n\n if (inspectorGroups?.length) {\n for (let group of inspectorGroups) {\n for (let input of group.inputs) {\n let { name, defaultValue } = input\n if (name && defaultValue !== null && defaultValue !== undefined) {\n data[name] = defaultValue\n }\n }\n }\n }\n\n // Cache the result before returning\n schemaDefaultsCache.set(schema, data)\n\n return data\n}\n\nfunction recursivelyAddDataItem(\n type: string,\n components: HydrogenComponent<any>[],\n items: any[],\n initData?: object\n) {\n let component = components.find((c) => c.schema.type === type)\n if (!component) {\n return\n }\n let childIds = []\n let id = crypto.randomUUID()\n let { children, ...data } = component.schema?.presets || {}\n if (children) {\n for (let c of children) {\n let { type, children, ...data } = c\n let childId = recursivelyAddDataItem(type, components, items, data)\n childIds.push({ id: childId } as never)\n }\n }\n items.push({\n data: { ...data, ...initData },\n id,\n type,\n children: childIds,\n })\n return id\n}\n\n/** Creates synthetic loader data for previewing one registered component type. */\nexport function getPreviewData(\n type: string,\n components: HydrogenComponent[],\n weaverseHost: string\n) {\n let items = []\n return {\n project: { id: 'x', weaverseShopId: 'shop-id', name: 'Section Preview' },\n configs: {\n projectId: 'x',\n weaverseHost,\n isDesignMode: false,\n isPreviewMode: true,\n requestInfo: {\n i18n: {\n label: 'United States (USD $)',\n language: 'EN',\n country: 'US',\n currency: 'USD',\n pathPrefix: '',\n },\n queries: {},\n pathname: '/',\n search: '',\n },\n },\n page: {\n id: 'weaverse-preview-page',\n name: 'Preview section',\n rootId: '1',\n items: [\n {\n data: {},\n id: '1',\n type: 'main',\n children: [{ id: recursivelyAddDataItem(type, components, items) }],\n },\n ...items,\n ],\n },\n } as unknown as WeaverseLoaderData\n}\n","/**\n * Minimal mutable store for design-mode static text overrides.\n *\n * useSyncExternalStore-compatible. Passed into TranslationProvider which\n * subscribes internally and merges overrides into merchantOverrides.\n * The studio bridge calls updateOverrides() via weaverse.internal.translationStore\n * (also exposed as the deprecated weaverse.internal.themeTextStore alias).\n *\n * Shape: flat Record<string, string> — dot-notation keys map to values\n * (e.g. \"cart.title\" → \"Shopping Cart\").\n */\nexport class TranslationStore {\n /** Current flat translation overrides keyed by dot-path. */\n overrides: Record<string, string> = {}\n private listeners: Set<() => void> = new Set()\n\n /** Replaces all overrides and notifies subscribers. */\n setOverrides = (overrides: Record<string, string>) => {\n this.overrides = { ...overrides }\n this.emit()\n }\n\n /** Merges changed overrides and notifies subscribers. */\n updateOverrides = (newOverrides: Record<string, string>) => {\n this.overrides = { ...this.overrides, ...newOverrides }\n this.emit()\n }\n\n /** Returns the current client snapshot for `useSyncExternalStore`. */\n getSnapshot = () => this.overrides\n\n /** Returns the current server snapshot for `useSyncExternalStore`. */\n getServerSnapshot = () => this.overrides\n\n /** Subscribes to override changes and returns an unsubscribe callback. */\n subscribe = (callback: () => void) => {\n this.listeners.add(callback)\n return () => {\n this.listeners.delete(callback)\n }\n }\n\n private emit = () => {\n for (const listener of Array.from(this.listeners)) {\n try {\n listener()\n } catch (error) {\n console.error('TranslationStore: Listener error', error)\n }\n }\n }\n}\n\n/**\n * Legacy constructor alias retained for existing theme text integrations.\n * @deprecated Use {@link TranslationStore} instead. This alias remains available\n * for backward compatibility.\n */\nexport const ThemeTextStore = TranslationStore\n/**\n * Legacy type alias retained for existing theme text integrations.\n * @deprecated Use {@link TranslationStore} instead. This alias remains available\n * for backward compatibility.\n */\nexport type ThemeTextStore = TranslationStore\n","import type { UIMatch } from 'react-router'\nimport type { WeaverseLoaderData } from '../types'\n\n/**\n * Weaverse page data accepted by {@link WeaverseHydrogenRoot}, including\n * deferred React Router loader results and an explicit no-render value.\n */\nexport type WeaverseDataValue =\n | WeaverseLoaderData\n | Promise<WeaverseLoaderData>\n | null\n\n/**\n * Resolve the `weaverseData` payload for a `<WeaverseHydrogenRoot>` instance.\n *\n * Resolution order (first match wins):\n *\n * 1. **Explicit prop** — the caller passed `data` directly. Used as-is,\n * including when it is a `Promise` (handled upstream via `<Await>`) or\n * an explicit `null` (suppresses rendering).\n * 2. **Own route's loader data** — the loader data for the route that\n * rendered this component, obtained via `useLoaderData()`. This is\n * React Router's route-scoped primitive and is what makes nested\n * layout + child Weaverse pages work: each `<WeaverseContent />`\n * resolves to *its own* route's `weaverseData` regardless of siblings.\n * 3. **Ancestor match fallback** — walk `useMatches()` from leaf to root\n * and return the first ancestor whose `loaderData` exposes a\n * `weaverseData` key. This preserves the long-standing behaviour where\n * a child route with no loader (e.g. an `index.tsx` that omits\n * `weaverseData`) still renders its layout's Weaverse page.\n *\n * The helper is intentionally pure (no hook calls) so it can be unit-tested\n * without a React Router context. Hook calls happen in the component.\n *\n * ## Back-compat contract\n *\n * Themes that pre-date the `data` prop addition pass `dataProp === undefined`,\n * so resolution starts at Tier 2. For the canonical single-instance pattern\n * (one `<WeaverseContent />` inside a route whose loader returns\n * `{ weaverseData }`), Tier 2 returns the same value the old `useMatches()`\n * walk did. For the index-without-loader pattern (leaf route exposes no\n * `weaverseData`, layout does), Tier 3's leaf→root walk produces an\n * identical result to the pre-fix code. The only intentional behaviour\n * change is the issue #451 case: two `<WeaverseContent />` instances on the\n * same URL (layout + child, both with their own `weaverseData`) now each\n * render their own page instead of both rendering the deepest one.\n */\nexport function pickWeaverseData(\n dataProp: WeaverseDataValue | undefined,\n ownLoaderData: unknown,\n matches: ReadonlyArray<Pick<UIMatch, 'loaderData'>>\n): WeaverseDataValue {\n // Tier 1: explicit prop wins (including explicit `null`).\n if (dataProp !== undefined) {\n return dataProp\n }\n\n // Tier 2: own route's loader data — the route-scoped primitive.\n if (hasWeaverseData(ownLoaderData)) {\n return ownLoaderData.weaverseData as WeaverseDataValue\n }\n\n // Tier 3: ancestor walk (leaf → root) for legacy / index-without-loader cases.\n for (let i = matches.length - 1; i >= 0; i--) {\n const loaderData = matches[i].loaderData\n if (hasWeaverseData(loaderData)) {\n return loaderData.weaverseData as WeaverseDataValue\n }\n }\n\n return null\n}\n\nfunction hasWeaverseData(\n value: unknown\n): value is Record<string, unknown> & { weaverseData: unknown } {\n // The `in` check alone returns true for `{ weaverseData: undefined }`,\n // which would let Tier 2 short-circuit and return `undefined` — bypassing\n // the Tier 3 ancestor walk that would otherwise resolve the missing data.\n // Require the value to be present (not `undefined`).\n if (\n typeof value !== 'object' ||\n value === null ||\n !('weaverseData' in (value as Record<string, unknown>))\n ) {\n return false\n }\n return (value as Record<string, unknown>).weaverseData !== undefined\n}\n","import type { WeaverseHydrogenParams } from '../types'\n\ninterface BrowserLocationLike {\n pathname: string\n search: string\n}\n\nfunction getBrowserLocation(): BrowserLocationLike | undefined {\n if (typeof window === 'undefined') {\n return\n }\n return window.location\n}\n\nfunction getQueriesFromSearch(\n search: string\n): Record<string, string | boolean> {\n let queries: Record<string, string | boolean> = {}\n let params = new URLSearchParams(search)\n for (let [key, value] of params.entries()) {\n if (value === 'true') {\n queries[key] = true\n } else if (value === 'false') {\n queries[key] = false\n } else {\n queries[key] = value\n }\n }\n return queries\n}\n\n/**\n * React Router v7 single-fetch revalidation can render client data returned\n * from a `*.data` request while the browser is still on the canonical URL.\n * Instance identity must follow the browser URL, not the transient data\n * endpoint, otherwise the SDK creates a fresh Weaverse instance mid-session:\n * in design mode that drops the existing Studio bridge/interactions, and in\n * the live theme it resets every section's runtime state after any\n * revalidation (cart mutations, locale switches, `revalidate()`). See #451.\n */\nexport function normalizeRequestInfo(\n params: WeaverseHydrogenParams,\n browserLocation: BrowserLocationLike | undefined = getBrowserLocation()\n): WeaverseHydrogenParams {\n if (!browserLocation) {\n return params\n }\n\n let { pathname, search } = browserLocation\n if (\n params.requestInfo.pathname === pathname &&\n params.requestInfo.search === search\n ) {\n return params\n }\n\n return {\n ...params,\n requestInfo: {\n ...params.requestInfo,\n pathname,\n queries: getQueriesFromSearch(search),\n search,\n },\n }\n}\n","/**\n * Structural comparison used to detect whether a reused Weaverse instance\n * must adopt a fresh loader payload.\n *\n * `JSON.stringify` cannot do this job on the client:\n *\n * - Route loader data reaches `dataContext` unserialized, so deferred values\n * are still `Promise`s. React 19 development builds hang an enumerable,\n * self-referencing `_debugInfo` off those promises, and stringifying one\n * throws `TypeError: Converting circular structure to JSON` during render\n * (issue #511).\n * - In production every promise stringifies to `{}`, so a *fresh* deferred\n * value looks unchanged and the reused instance keeps serving the previous\n * render's promise. Tokenizing promises to a constant (`'[[promise]]'`) has\n * the same defect — it is stable by construction, therefore blind to\n * identity.\n *\n * Semantics, chosen deliberately:\n *\n * - **Promises/thenables are atomic**: compared by identity, never traversed.\n * A fresh promise is a change; the same promise is not. Debug metadata is\n * invisible to the comparison.\n * - **Opaque objects are atomic**: anything that is not a plain object, an\n * array, or `toJSON`-serializable (`Map`, `Set`, `URL`, `RegExp`, streams,\n * async iterators, cross-realm promises, class instances) is compared by\n * identity. `JSON.stringify` flattens all of them to `{}`, which would\n * silently collapse two distinct async values into \"unchanged\".\n * - **Cyclic graphs are compared coinductively**: a pair already being\n * compared is assumed equal, so equal self/mutual cycles are equal while a\n * differing leaf anywhere still reports a change. Nothing throws.\n * - **JSON-visible fields only**: `undefined`/function/symbol properties are\n * omitted from objects and read as `null` in arrays, and NaN/±Infinity read\n * as `null` — matching the previous `JSON.stringify` behavior for plain wire\n * payloads. Key order is irrelevant, which removes the old \"false mismatch\n * costs a re-render\" caveat.\n */\n\n/** `JSON.stringify` drops these from objects and nulls them inside arrays. */\nfunction isJsonOmitted(value: unknown): boolean {\n return (\n value === undefined ||\n typeof value === 'function' ||\n typeof value === 'symbol'\n )\n}\n\nfunction isObjectLike(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object'\n}\n\n/** Duck-typed so cross-realm promises and hand-rolled thenables also match. */\nfunction isThenable(value: Record<string, unknown>): boolean {\n return typeof value.then === 'function'\n}\n\nfunction isPlainObject(value: Record<string, unknown>): boolean {\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/** Returns the `toJSON()` projection, or the value itself when there is none. */\nfunction toJsonValue(value: Record<string, unknown>): unknown {\n return typeof value.toJSON === 'function'\n ? (value.toJSON as () => unknown)()\n : value\n}\n\n/** Maps NaN/±Infinity to `null`, matching how `JSON.stringify` renders them. */\nfunction toFiniteOrNull(value: unknown): unknown {\n return typeof value === 'number' && !Number.isFinite(value) ? null : value\n}\n\n/** Compares two loader payloads for JSON-visible structural equality. */\nexport function isSameLoaderPayload(left: unknown, right: unknown): boolean {\n // Pairs currently being compared, flattened as [a0, b0, a1, b1, ...].\n // Re-entering a pair means a cycle closed on both sides; assuming equality\n // there is what makes equal cyclic graphs compare equal (bisimulation)\n // while a differing leaf anywhere still reports a change.\n //\n // Scoped to the active path rather than every visited pair, so memory stays\n // proportional to graph depth (single digits for loader payloads) instead of\n // node count, and the common all-equal walk allocates one array.\n //\n // Tradeoff: a graph that shares one subtree through many nested parents\n // re-walks it per path. Wire-serialized loader payloads are trees, so this\n // does not arise; memoizing equal pairs instead measured ~2x slower on a\n // realistic 400-item page, which is the case that actually runs per render.\n const activePairs: object[] = []\n\n function isSame(rawA: unknown, rawB: unknown): boolean {\n if (Object.is(rawA, rawB)) {\n return true\n }\n // `JSON.stringify` renders NaN/±Infinity as `null`; normalizing here keeps\n // a non-finite number equal to the `null` a previous wire payload carried.\n const a = toFiniteOrNull(rawA)\n const b = toFiniteOrNull(rawB)\n if (a === b) {\n // Also accepts 0/-0, which `JSON.stringify` renders identically.\n return true\n }\n if (!(isObjectLike(a) && isObjectLike(b))) {\n return false\n }\n if (isThenable(a) || isThenable(b)) {\n // Identity comparison above already failed: distinct async values.\n return false\n }\n for (let index = 0; index < activePairs.length; index += 2) {\n if (activePairs[index] === a && activePairs[index + 1] === b) {\n return true\n }\n }\n\n activePairs.push(a, b)\n try {\n return isSameOpenPair(a, b)\n } finally {\n activePairs.length -= 2\n }\n }\n\n function isSameOpenPair(\n a: Record<string, unknown>,\n b: Record<string, unknown>\n ): boolean {\n const aJson = toJsonValue(a)\n const bJson = toJsonValue(b)\n if (aJson !== a || bJson !== b) {\n return isSame(aJson, bJson)\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return isSameArray(a, b)\n }\n if (!(isPlainObject(a) && isPlainObject(b))) {\n // Opaque object with no JSON projection — identity is the only honest\n // signal, and it already failed.\n return false\n }\n return isSameObject(a, b)\n }\n\n function isSameArray(a: unknown[], b: unknown[]): boolean {\n if (a.length !== b.length) {\n return false\n }\n for (let index = 0; index < a.length; index++) {\n const aItem = isJsonOmitted(a[index]) ? null : a[index]\n const bItem = isJsonOmitted(b[index]) ? null : b[index]\n if (!isSame(aItem, bItem)) {\n return false\n }\n }\n return true\n }\n\n function isSameObject(\n a: Record<string, unknown>,\n b: Record<string, unknown>\n ): boolean {\n let aKeyCount = 0\n for (const key of Object.keys(a)) {\n if (isJsonOmitted(a[key])) {\n continue\n }\n aKeyCount++\n // A JSON-visible value never compares equal to an omitted one, so a\n // missing/undefined counterpart falls out of `isSame` as a change.\n if (!isSame(a[key], b[key])) {\n return false\n }\n }\n let bKeyCount = 0\n for (const key of Object.keys(b)) {\n if (!isJsonOmitted(b[key])) {\n bKeyCount++\n }\n }\n return aKeyCount === bKeyCount\n }\n\n return isSame(left, right)\n}\n","import type { WeaverseHydrogenParams } from '../types'\nimport type { WeaverseHydrogen } from '../WeaverseHydrogenRoot'\nimport { isSameLoaderPayload } from './is-same-loader-payload'\n\n/**\n * Apply a fresh loader payload to a reused Weaverse instance.\n *\n * With requestInfo normalized to the browser URL, same-URL revalidations\n * (cart mutations, `useRevalidator()`, locale-neutral re-fetches) reuse the\n * cached `window.__weaverses[pageId]` instance instead of constructing a new\n * one — which preserves section state, but would silently drop the fresh\n * `data`/`dataContext` the loaders just returned. Sync them here.\n *\n * Design mode is excluded by the caller: Studio owns the instance data there\n * (unsaved drafts must not be clobbered) and applies updates via\n * `refreshStudio` instead.\n *\n * Change detection uses {@link isSameLoaderPayload}: a structural comparison\n * that treats promises/thenables and other opaque objects as atomic values\n * compared by identity, and tolerates cyclic graphs. `dataContext` carries\n * live route loader data — including unresolved deferred promises whose React\n * development metadata is cyclic — so it cannot be JSON-serialized here.\n */\nexport function syncReusedInstance(\n weaverse: WeaverseHydrogen,\n params: WeaverseHydrogenParams\n) {\n weaverse.requestInfo = params.requestInfo\n weaverse.internal = params.internal\n\n let dataChanged = !isSameLoaderPayload(weaverse.data, params.data)\n let contextChanged = !isSameLoaderPayload(\n weaverse.dataContext ?? null,\n params.dataContext ?? null\n )\n\n if (contextChanged) {\n // Assign before notifying any item store: components resolve data\n // connectors against `weaverse.dataContext` at render time, so the\n // fresh context must be in place when re-renders flush.\n weaverse.dataContext = params.dataContext ?? null\n }\n if (dataChanged) {\n // State-preserving: existing item stores receive `setData` (and emit),\n // missing ones are created — no full instance teardown.\n weaverse.setProjectData(params.data)\n } else if (contextChanged) {\n // Context-only change: memoized item components subscribe to their item\n // store snapshot, and snapshot identity follows the `_store` reference —\n // a bare `triggerUpdate()` would notify with an identical snapshot and\n // `useSyncExternalStore` would skip the re-render. `setData({})` swaps\n // the store reference so connectors re-resolve against the new context.\n for (const { id } of params.data?.items || []) {\n weaverse.itemInstances.get(id)?.setData({})\n }\n }\n if (dataChanged || contextChanged) {\n weaverse.triggerUpdate()\n }\n}\n","import { isBrowser } from '@weaverse/react'\nimport { createContext, useContext, useEffect, useRef } from 'react'\nimport { useRouteLoaderData } from 'react-router'\nimport type {\n HydrogenThemeSchema,\n HydrogenThemeSettings,\n PublicEnv,\n} from '../types'\n\n/** Root-loader theme data used to initialize a {@link ThemeSettingsStore}. */\nexport interface WeaverseThemeData {\n /** Storefront-safe environment values, when available. */\n publicEnv?: PublicEnv\n /** Theme schema exposed to Studio, when available. */\n schema?: HydrogenThemeSchema\n /** Published theme setting values. */\n theme: HydrogenThemeSettings\n}\n\n/** Mutable, subscribable store for theme settings received from the root loader. */\nexport class ThemeSettingsStore {\n /** Current merged theme setting values. */\n settings: HydrogenThemeSettings = {}\n /** Theme schema exposed to Studio, when available. */\n schema?: HydrogenThemeSchema\n /** Storefront-safe environment values, when available. */\n publicEnv?: PublicEnv\n private listeners: Set<() => void> = new Set()\n private hasWarnedListenerCount = false\n private isDestroyed = false\n\n /** Creates a theme settings store from root-loader theme data. */\n constructor(data: WeaverseThemeData) {\n const { theme, schema, publicEnv } = data || {}\n this.settings = { ...theme }\n this.schema = schema\n this.publicEnv = publicEnv\n if (isBrowser) {\n window.__weaverseThemeSettingsStore = this\n }\n }\n\n /** Merges setting changes into the current snapshot and notifies subscribers. */\n updateThemeSettings = (newSettings: HydrogenThemeSettings) => {\n if (this.isDestroyed) {\n console.warn('ThemeSettingsStore: Cannot update destroyed store')\n return\n }\n\n this.settings = {\n ...this.settings,\n ...newSettings,\n }\n this.emit()\n }\n\n /** Returns the current client snapshot for `useSyncExternalStore`. */\n getSnapshot = () => this.settings\n\n /** Returns the current server snapshot for `useSyncExternalStore`. */\n getServerSnapshot = () => this.settings\n\n /** Subscribes to setting changes and returns an unsubscribe callback. */\n subscribe = (callback: () => void) => {\n if (this.isDestroyed) {\n console.warn('ThemeSettingsStore: Cannot subscribe to destroyed store')\n return () => {}\n }\n\n this.listeners.add(callback)\n\n if (!this.hasWarnedListenerCount && this.listeners.size > 500) {\n this.hasWarnedListenerCount = true\n console.warn(\n `ThemeSettingsStore: ${this.listeners.size} listeners detected. ` +\n 'This may indicate a performance issue. Consider using fewer useThemeSettings() calls.'\n )\n }\n\n return () => {\n this.listeners.delete(callback)\n }\n }\n\n private emit = () => {\n if (this.isDestroyed) {\n return\n }\n\n const currentListeners = Array.from(this.listeners)\n\n for (const listener of currentListeners) {\n try {\n listener()\n } catch (error) {\n console.error('ThemeSettingsStore: Listener error', error)\n }\n }\n }\n\n /** Clears subscribers and detaches the browser-global store reference. */\n destroy = () => {\n if (this.isDestroyed) {\n return\n }\n\n this.listeners.clear()\n this.isDestroyed = true\n\n if (isBrowser && window.__weaverseThemeSettingsStore === this) {\n window.__weaverseThemeSettingsStore = undefined\n }\n }\n}\n\nexport const ThemeSettingsStoreContext =\n createContext<ThemeSettingsStore | null>(null)\nThemeSettingsStoreContext.displayName = 'ThemeSettingsStoreContext'\n\nexport function useCreateThemeSettingsStore(): ThemeSettingsStore {\n const data = useRouteLoaderData('root') as {\n weaverseTheme: WeaverseThemeData\n }\n const storeRef = useRef<ThemeSettingsStore | null>(null)\n\n if (!storeRef.current) {\n storeRef.current = new ThemeSettingsStore(data?.weaverseTheme)\n }\n\n const theme = data?.weaverseTheme?.theme\n useEffect(() => {\n if (storeRef.current && theme) {\n storeRef.current.updateThemeSettings(theme)\n }\n }, [theme])\n\n return storeRef.current\n}\n\nexport function useThemeSettingsStore(): ThemeSettingsStore {\n const fromContext = useContext(ThemeSettingsStoreContext)\n const data = useRouteLoaderData('root') as {\n weaverseTheme: WeaverseThemeData\n }\n const fallbackRef = useRef<ThemeSettingsStore | null>(null)\n\n if (!(fallbackRef.current || fromContext)) {\n fallbackRef.current = new ThemeSettingsStore(data?.weaverseTheme)\n }\n\n const store = fromContext ?? fallbackRef.current!\n const theme = data?.weaverseTheme?.theme\n useEffect(() => {\n if (!fromContext && theme) {\n store.updateThemeSettings(theme)\n }\n }, [fromContext, store, theme])\n\n return store\n}\n","import { loadScript } from '@weaverse/react'\nimport { useEffect } from 'react'\nimport {\n useLocation,\n useNavigate,\n useNavigation,\n useRevalidator,\n} from 'react-router'\nimport { useTranslation } from '../hooks/translation-context'\nimport type { WeaverseHydrogen } from '../index'\nimport { hasWeaverseStudio } from '../types'\nimport { getStudioScriptSrc, resolveStudioScriptSrc } from './studio-script-src'\nimport { useThemeSettingsStore } from './use-theme-settings-store'\n\nconst STUDIO_READY_POLL_MS = 50\nconst STUDIO_READY_TIMEOUT_MS = 5000\n\n/**\n * Resolve once `window.weaverseStudio` is available, or `null` on timeout.\n * The studio script sets the global when it *executes*; `loadScript` can\n * resolve earlier for tags it did not create (e.g. SSR-injected markup),\n * so never assume readiness right after the script promise settles.\n */\nfunction waitForStudio(): Promise<Window['weaverseStudio'] | null> {\n return new Promise((resolve) => {\n let startedAt = Date.now()\n function check() {\n if (hasWeaverseStudio(window)) {\n return resolve(window.weaverseStudio)\n }\n if (Date.now() - startedAt >= STUDIO_READY_TIMEOUT_MS) {\n console.warn('[Weaverse] Studio script did not initialize in time')\n return resolve(null)\n }\n setTimeout(check, STUDIO_READY_POLL_MS)\n }\n check()\n })\n}\n\n/**\n * Load the Studio bridge script on every design/preview render so Studio's\n * `checkWeaversePage()` handshake is answered instead of timing out — crucially\n * on routes where the page-scoped {@link useStudio} never mounts: 404s, error\n * boundaries, and non-Weaverse routes. The bridge registers its RPC endpoint\n * and `window.weaverseStudio` the moment the script executes, independent of any\n * page binding. Without this, a content-less route never loads the script and\n * Studio reports a false \"Connection lost\" instead of \"this page has no Weaverse\n * content set up\".\n *\n * `loadScript` is idempotent, so on content routes this coexists with the\n * page-scoped {@link useStudio} (same src) — that hook still binds the page via\n * `init`. Gating this on whether a route \"has Weaverse data\" is deliberately\n * avoided: route matches can't tell whether the page-scoped bridge actually\n * mounts (an `ErrorBoundary` replacing a data route, or data passed via the\n * `data` prop), and suppressing the script there would reintroduce the timeout\n * this fixes. Loading the script is harmless; it only registers the responder.\n *\n * Known limitation: on a route whose `weaverseData` is a deferred Promise, the\n * script can load before the page streams in, so `checkWeaversePage()` may\n * briefly observe `NOT_WEAVERSE_PAGE`. The complete fix is a \"loading\" state in\n * `checkWeaversePage` so the handshake retries rather than latching — that lives\n * in the Studio script, not here. Tracked in Weaverse/builder#2515.\n *\n * Mounted via {@link withWeaverse}, which must be the root route's `Layout`\n * export so the bridge renders even when a route's `ErrorBoundary` replaces the\n * page. Outside Studio (no design/preview params) it is a no-op.\n */\nexport function useStudioConnect() {\n let { search } = useLocation()\n useEffect(() => {\n // Loopback Studio hosts are only honored when the storefront itself is\n // loopback (see resolveStudioScriptSrc), so pass the document's hostname.\n let hostname = typeof window === 'undefined' ? '' : window.location.hostname\n let src = resolveStudioScriptSrc(search, hostname)\n if (src) {\n loadScript(src).catch(console.error)\n }\n }, [search])\n}\n\nexport function useStudio(weaverse: WeaverseHydrogen) {\n let { revalidate } = useRevalidator()\n let navigation = useNavigation()\n let { pathname, search } = useLocation()\n let navigate = useNavigate()\n let themeSettingsStore = useThemeSettingsStore()\n let { translationStore, themeTextStore, merchantOverrides } = useTranslation()\n let {\n isDesignMode,\n weaverseHost,\n weaverseVersion,\n isPreviewMode,\n isRevisionPreview,\n } = weaverse\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only revalidate on pathname/search changes\n useEffect(() => {\n if (navigation.state !== 'idle') {\n return\n }\n let src = getStudioScriptSrc({\n isDesignMode,\n isPreviewMode,\n isRevisionPreview,\n weaverseHost,\n weaverseVersion,\n })\n if (!src) {\n return\n }\n if (isRevisionPreview || isPreviewMode) {\n loadScript(src).catch(console.error)\n } else {\n weaverse.internal = {\n ...weaverse.internal,\n navigate,\n revalidate,\n merchantOverrides,\n themeSettingsStore,\n translationStore,\n // Deprecated alias for existing Studio bridge integrations.\n themeTextStore,\n }\n loadScript(src)\n .then(waitForStudio)\n .then((studio) => studio?.init(weaverse))\n .catch(console.error)\n }\n }, [pathname, search, navigation.state])\n}\n","import type { ElementData } from '@weaverse/react'\nimport {\n isBrowser,\n useSafeExternalStore,\n Weaverse,\n WeaverseItemStore,\n WeaverseRoot,\n} from '@weaverse/react'\nimport {\n type ComponentType,\n type JSX,\n memo,\n Suspense,\n useMemo,\n useRef,\n} from 'react'\nimport { ErrorBoundary } from 'react-error-boundary'\nimport {\n Await,\n useLoaderData,\n useMatches,\n useRouteLoaderData,\n} from 'react-router'\nimport { defaultComponents } from './components'\nimport {\n type TranslateFunction,\n TranslationProvider,\n} from './hooks/translation-context'\nimport { createWeaverseDataContext } from './hooks/use-weaverse-data-context'\nimport type {\n HydrogenComponentData,\n HydrogenElement,\n HydrogenPageData,\n HydrogenThemeSettings,\n TranslationChanges,\n TranslationEntry,\n TranslationItemEntry,\n TranslationMap,\n WeaverseInternal,\n WeaverseLoaderRequestInfo,\n} from './index'\nimport type {\n HydrogenComponent,\n WeaverseHydrogenParams,\n WeaverseLoaderData,\n} from './types'\nimport { hasWeaverseStudio } from './types'\nimport { generateDataFromSchema } from './utils'\nimport {\n pickWeaverseData,\n type WeaverseDataValue,\n} from './utils/pick-weaverse-data'\nimport { normalizeRequestInfo } from './utils/studio-request-info'\nimport { syncReusedInstance } from './utils/sync-reused-instance'\nimport { TranslationStore } from './utils/translation-store'\nimport { useStudio, useStudioConnect } from './utils/use-studio'\nimport {\n ThemeSettingsStoreContext,\n useCreateThemeSettingsStore,\n useThemeSettingsStore,\n} from './utils/use-theme-settings-store'\n\n/*\n=== IMPORTANT DESIGN PRINCIPLE ===\nCONSTRUCTOR TIMING AND DEFERRED PROCESSING\n\nWhen working with React component systems and registries:\n- Keep constructors SIMPLE - don't do heavy work in them\n- Defer processing until RENDER TIME, not initialization\n- Avoid registry lookups during object construction (components may not be registered yet)\n- Simple code is more reliable than complex upfront optimization\n- Respect the initialization sequence: registration → instance creation → rendering\n\nHistory: Attempting to do schema processing in the constructor (commit 495e1220) broke\nthe pilot template because it tried to access the component registry before components were registered.\nThe fix was to defer that work until the component is actually rendered.\n====================================\n*/\n\n/** Runtime store for one rendered Hydrogen component instance. */\nexport class WeaverseHydrogenItem extends WeaverseItemStore {\n /** Owning Hydrogen runtime instance. */\n declare weaverse: WeaverseHydrogen\n\n /**\n * Cached merged snapshot (base + translations).\n * Reset to `null` whenever `_store` or the item's translation entry changes.\n */\n private _cachedSnapshot: ElementData | null = null\n private _snapshotStoreRef: ElementData | null = null\n private _snapshotTranslationRef: TranslationItemEntry | null = null\n\n /** Creates an item store from serialized component data and its owner. */\n constructor(initialData: HydrogenComponentData, weaverse: WeaverseHydrogen) {\n super(initialData, weaverse)\n const { data, ...rest } = initialData\n if (!this.Element?.schema) {\n console.error('Element is missing schema or not found!')\n return\n }\n const schemaData = generateDataFromSchema(this.Element.schema)\n Object.assign(this._store, schemaData, data, rest)\n }\n\n /** Registered component definition for this item's type. */\n get Element(): HydrogenElement {\n return super.Element\n }\n\n /**\n * Override setData to flatten serialized `data` the same way the constructor\n * does. Core's `initProject()` reuses item stores keyed by item id (identical\n * ids across locales), and the inherited setData only shallow-merges the raw\n * item — fresh settings would land under `_store.data` while the stale\n * flattened values keep rendering.\n *\n * Schema defaults are re-applied ahead of incoming settings because a\n * serialized payload can omit fields — or the optional `data` object itself —\n * when values equal schema defaults. The stored nested `data` is also replaced\n * so the public serialized state does not retain the previous locale payload.\n *\n * An empty update is the context-only refresh from `syncReusedInstance`: swap\n * the store reference so memoized subscribers re-render, and leave the\n * settings untouched.\n */\n setData = (update: Omit<ElementData, 'id' | 'type'>) => {\n let source = update ?? {}\n let { data, ...rest } = source\n let isEmptyUpdate = Object.keys(source).length === 0\n\n if (isEmptyUpdate) {\n this._store = { ...this._store }\n } else {\n let type = source.type ?? this._store.type\n let schema = this.weaverse.elementRegistry.get(type)?.schema\n let isSerializedItem = 'id' in source && 'type' in source\n let shouldNormalize = data !== undefined || isSerializedItem\n\n if (schema && shouldNormalize) {\n let { data: _previousData, ...store } = this._store\n let schemaData = generateDataFromSchema(schema)\n this._store = {\n ...store,\n ...(data === undefined ? {} : { data }),\n ...schemaData,\n ...data,\n ...rest,\n }\n } else {\n this._store = { ...this._store, ...source }\n }\n }\n\n this.triggerUpdate()\n return this.data\n }\n\n /**\n * Override getSnapShot to merge translation data when in translation mode.\n * Memoizes the result: returns the same object reference as long as\n * both `_store` and the translation entry haven't changed.\n * This is critical for `useSyncExternalStore` stability.\n */\n getSnapShot = (): ElementData => {\n const base = this._store\n const translations = this.weaverse.translationMap?.[this._id]\n\n // No translations → return base directly (fast path)\n if (!translations) {\n return base\n }\n\n // Check if cache is still valid (same _store ref + same translation entry ref)\n if (\n this._cachedSnapshot &&\n this._snapshotStoreRef === base &&\n this._snapshotTranslationRef === translations\n ) {\n return this._cachedSnapshot\n }\n\n // Build merged snapshot\n const merged = { ...base }\n for (const [key, entry] of Object.entries(translations)) {\n if (entry.translatedValue !== undefined) {\n merged[key] = entry.translatedValue\n }\n }\n\n this._cachedSnapshot = merged\n this._snapshotStoreRef = base\n this._snapshotTranslationRef = translations\n return merged\n }\n}\n\nWeaverse.ItemConstructor = WeaverseHydrogenItem\n\n/**\n * Hydrogen-specific Weaverse runtime that owns page data, component stores,\n * Studio state, and translation sidecars for one rendered page.\n */\nexport class WeaverseHydrogen extends Weaverse {\n /** Identifier of the rendered page. */\n pageId: string\n /** Runtime services and project metadata exposed to integrations. */\n internal: Partial<WeaverseInternal>\n /** Normalized URL and locale information for the current request. */\n requestInfo: WeaverseLoaderRequestInfo\n /** Identifier of the project supplying the page. */\n projectId: string\n /** Origin used for Studio assets and editor communication. */\n weaverseHost: string\n /** Base URL used for public content API requests. */\n weaverseApiBase: string\n /**\n * API key read from environment/configuration for storefront requests or\n * supplied by Studio requests while editing and previewing.\n */\n weaverseApiKey: string\n /** Studio asset version supplied by the preview request. */\n weaverseVersion: string\n /** Whether the page is running inside the visual editor. */\n isDesignMode: boolean\n /** Whether a single component preview is being rendered. */\n isPreviewMode: boolean\n /** Whether a saved page revision is being previewed. */\n isRevisionPreview: boolean\n /** Component type requested by section preview mode. */\n sectionType: string\n /** Component item store constructor used by the core runtime. */\n declare ItemConstructor: typeof WeaverseHydrogenItem\n /** Current page content owned by the runtime. */\n declare data: HydrogenPageData\n /** Component item stores indexed by instance ID. */\n declare static itemInstances: Map<string, WeaverseHydrogenItem>\n /** Registered component definitions indexed by component type. */\n declare static elementRegistry: Map<string, HydrogenElement>\n\n // ─── Translation sidecar (design mode only) ────────────────────────\n /**\n * Translation map received from the builder in design mode.\n * Keyed by item ID, each entry maps field names to translated values.\n * `WeaverseHydrogenItem.getSnapShot()` merges these into the data\n * returned to components, so translations render without monkey-patching.\n */\n translationMap: TranslationMap = {}\n /** Locale code for the active translation sidecar. */\n translationLocale = ''\n /** Builder language identifier for the active translation sidecar. */\n translationLanguageId = ''\n\n /** Creates a page runtime from resolved loader data and request settings. */\n constructor(params: WeaverseHydrogenParams) {\n const { internal, pageId, requestInfo, ...coreParams } = params\n super({ ...coreParams })\n this.internal = internal\n this.pageId = pageId\n this.requestInfo = requestInfo\n // Assign configuration properties\n this.projectId = params.projectId\n this.weaverseHost = params.weaverseHost\n this.weaverseApiBase = params.weaverseApiBase\n this.weaverseApiKey = params.weaverseApiKey\n this.weaverseVersion = params.weaverseVersion || ''\n this.isDesignMode = params.isDesignMode ?? false\n this.isPreviewMode = params.isPreviewMode ?? false\n this.isRevisionPreview = params.isRevisionPreview ?? false\n this.sectionType = params.sectionType || ''\n\n // Extract translation sidecar from page data if present (design mode)\n this.extractTranslationSidecar()\n }\n\n /**\n * Extract translation sidecar data from `this.data` (the page data).\n * The builder attaches `translationMap`, `translationLocale`, and\n * `translationLanguageId` to the page data in design mode.\n */\n extractTranslationSidecar = () => {\n const pageData = this.data as Record<string, any>\n if (pageData?.translationMap) {\n this.translationMap = pageData.translationMap\n this.translationLocale = pageData.translationLocale || ''\n this.translationLanguageId = pageData.translationLanguageId || ''\n }\n }\n\n /**\n * Set the translation sidecar data.\n * Called by the studio bridge when translation data arrives or changes.\n * Triggers a re-render of all items so translated snapshots are recalculated.\n */\n setTranslationSidecar = (\n translationMap: TranslationMap,\n locale: string,\n languageId: string\n ) => {\n this.translationMap = translationMap\n this.translationLocale = locale\n this.translationLanguageId = languageId\n // Invalidate all item snapshot caches and trigger re-render\n this.refreshAllItems()\n }\n\n /**\n * Update a single translation entry for a specific item field.\n * Used by the studio bridge when the user edits a translatable field.\n */\n updateTranslation = (\n itemId: string,\n key: string,\n originalValue: string,\n translatedValue: string\n ) => {\n if (!this.translationMap[itemId]) {\n this.translationMap[itemId] = {}\n }\n // Create a new entry reference so getSnapShot detects the change\n this.translationMap[itemId] = {\n ...this.translationMap[itemId],\n [key]: { originalValue, translatedValue },\n }\n // Trigger re-render for this specific item\n const instance = this.itemInstances.get(itemId)\n if (instance) {\n instance.triggerUpdate()\n }\n }\n\n /**\n * Collect all translation changes across all weaverse instances.\n * Used by the save flow to persist translation edits.\n */\n getTranslationChanges = (): TranslationChanges | undefined => {\n const entries: TranslationEntry[] = []\n const languageId = this.translationLanguageId\n if (!(this.translationLocale && languageId)) {\n return\n }\n\n for (const [itemId, fields] of Object.entries(this.translationMap)) {\n for (const [key, entry] of Object.entries(fields)) {\n entries.push({\n itemId,\n key: `data.${key}`,\n originalValue: entry.originalValue,\n translatedValue: entry.translatedValue,\n })\n }\n }\n\n if (entries.length === 0) {\n return\n }\n return { languageId, entries }\n }\n\n /**\n * Override setProjectData to re-extract translation sidecar from new page data.\n */\n setProjectData = (data: HydrogenPageData) => {\n this.data = data\n this.extractTranslationSidecar()\n this.initProject()\n }\n}\n\nfunction createWeaverseInstance(\n params: WeaverseHydrogenParams\n): WeaverseHydrogen {\n const normalizedParams = normalizeRequestInfo(params)\n if (isBrowser) {\n window.__weaverses = window.__weaverses || {}\n const existing = window.__weaverses[normalizedParams.pageId]\n // Reuse the instance only while the browser stays on the same URL —\n // navigation to a different pathname/search builds a fresh instance.\n const isReused =\n existing?.requestInfo?.pathname ===\n normalizedParams.requestInfo.pathname &&\n existing?.requestInfo?.search === normalizedParams.requestInfo.search\n const weaverse = isReused\n ? existing\n : new WeaverseHydrogen(normalizedParams)\n window.__weaverses[normalizedParams.pageId] = weaverse\n if (weaverse.isDesignMode) {\n weaverse.requestInfo = normalizedParams.requestInfo\n if (hasWeaverseStudio(window)) {\n window.weaverseStudio.refreshStudio(normalizedParams)\n }\n } else if (isReused) {\n // Same-URL revalidation in live/preview mode: the reused instance\n // must adopt the fresh loader payload (see syncReusedInstance).\n syncReusedInstance(weaverse, normalizedParams)\n }\n return weaverse\n }\n return new WeaverseHydrogen(normalizedParams)\n}\n\nconst StudioBridge = memo(({ context }: { context: WeaverseHydrogen }) => {\n useStudio(context)\n return null\n})\n\nconst StudioConnect = memo(() => {\n useStudioConnect()\n return null\n})\n\n/**\n * Component lists already pushed into the element registry. Registration is\n * idempotent (the registry checks `has(type)`), but walking the full list\n * allocates and loops on every render — theme component arrays are\n * module-level constants, so register each list identity once.\n */\nconst registeredComponentLists = new WeakSet<HydrogenComponent[]>()\n\nfunction RenderRoot(props: {\n data: WeaverseLoaderData\n components: HydrogenComponent[]\n dataContext?: Record<string, any>\n}) {\n const { data, components, dataContext } = props\n if (!registeredComponentLists.has(components)) {\n for (const comp of [...components, ...defaultComponents]) {\n if (comp?.schema?.type) {\n registerComponent({\n type: comp.schema.type,\n Component: comp.default,\n schema: comp.schema,\n loader: comp.loader,\n })\n }\n }\n registeredComponentLists.add(components)\n }\n const { page, configs, project, pageAssignment } = data || {}\n\n // Keep original page data - processing will happen at component level in renderer\n\n const weaverse = createWeaverseInstance({\n ...configs,\n dataContext,\n data: page,\n pageId: page?.id,\n internal: { project, pageAssignment },\n })\n return (\n <>\n <WeaverseRoot context={weaverse} />\n <StudioBridge context={weaverse} />\n </>\n )\n}\n\n/**\n * Register a Weaverse component with the global element registry.\n * Must be called before rendering components in WeaverseHydrogenRoot.\n *\n * @param element - Component configuration with schema, Component, and optional loader\n *\n * @example\n * ```typescript\n * import Hero from './sections/Hero'\n * import { schema } from './sections/Hero'\n *\n * registerComponent({\n * type: 'hero',\n * Component: Hero,\n * schema,\n * loader: async ({ data, weaverse }) => {\n * return { someData: 'value' }\n * }\n * })\n * ```\n */\nexport function registerComponent(element: HydrogenElement) {\n WeaverseHydrogen.registerElement(element)\n}\n\n/** Props passed to a custom Weaverse page error component. */\nexport interface WeaverseHydrogenRootErrorProps {\n /** Error raised while resolving or rendering the Weaverse page. */\n error: Error | unknown\n}\n\n/** Props accepted by {@link WeaverseHydrogenRoot}. */\nexport interface WeaverseHydrogenRootProps {\n /** Theme components available to the page renderer. */\n components: HydrogenComponent[]\n /**\n * Optional explicit `weaverseData` payload. When provided, bypasses the\n * automatic route-scoped resolution. Accepts a resolved value, a\n * `Promise` (handled via `<Await>`), or `null` to suppress rendering.\n *\n * Recommended for nested layout + child route compositions where two\n * `<WeaverseHydrogenRoot>` instances need to render different Weaverse\n * pages on the same URL. See issue #451.\n */\n data?: WeaverseDataValue\n /** Component rendered when page data cannot be resolved or awaited. */\n errorComponent?: React.FC<WeaverseHydrogenRootErrorProps>\n}\n\n/**\n * Renders the Weaverse page for the current React Router route.\n *\n * Pass `data` to override automatic route-loader resolution. A promise is\n * handled with React Router's `Await`, while explicit `null` suppresses output.\n */\nexport const WeaverseHydrogenRoot = memo(\n ({\n components,\n data: dataProp,\n errorComponent: ErrorComponent = ({ error }) => (\n <div>\n {error instanceof Error\n ? error.message\n : 'An unexpected error occurred'}\n </div>\n ),\n }: WeaverseHydrogenRootProps) => {\n const matches = useMatches()\n\n // Flat route-keyed data context for data-connector template resolution\n // (e.g. {{root.layout.shop.name}}). Legitimately needs all matches;\n // memoized so same-matches re-renders don't allocate a fresh context.\n const enhancedDataContext = useMemo(\n () => createWeaverseDataContext(matches),\n [matches]\n )\n\n // Route-scoped weaverseData lookup. `useLoaderData()` returns the\n // closest route's loader data, which is what makes nested layout +\n // child routes work — each <WeaverseHydrogenRoot> instance resolves\n // to its own route's weaverseData. See pickWeaverseData() for the\n // three-tier fallback policy.\n const ownLoaderData = useLoaderData() as unknown\n const weaverseData = useMemo(\n () => pickWeaverseData(dataProp, ownLoaderData, matches),\n [dataProp, ownLoaderData, matches]\n )\n\n // Explicit `data={null}` is the documented signal for \"suppress rendering\"\n // (e.g. a route conditionally disables Weaverse without unmounting the\n // component). This is distinct from auto-resolution returning `null`,\n // which means \"data was expected but not found\" — the error path below.\n if (dataProp === null) {\n return null\n }\n\n if (weaverseData) {\n if (weaverseData instanceof Promise) {\n return (\n <ErrorBoundary fallbackRender={ErrorComponent as any}>\n <Suspense>\n <Await resolve={weaverseData}>\n {(resolvedData) => (\n <RenderRoot\n components={components}\n data={resolvedData}\n dataContext={enhancedDataContext}\n />\n )}\n </Await>\n </Suspense>\n </ErrorBoundary>\n )\n }\n return (\n <RenderRoot\n components={components}\n data={weaverseData}\n dataContext={enhancedDataContext}\n />\n )\n }\n return (\n <ErrorComponent\n error={{ message: 'No Weaverse data found in route matches!' }}\n />\n )\n }\n)\n\n/**\n * Options for the `withWeaverse` HOC.\n */\nexport type WithWeaverseOptions = {\n /**\n * Optional external translation function (e.g. from Shopify i18n).\n * When provided it becomes the **highest-priority** source\n * in the `t()` resolution chain exposed by `useTranslation()`.\n */\n t?: TranslateFunction\n}\n\n/**\n * Higher-order component that wraps your app with Weaverse theme settings and\n * translation context, and mounts the Studio connect bridge.\n *\n * Export the result as your root route's **`Layout`** (not the default route\n * `Component`). In React Router the root `Layout` wraps both the matched route\n * and its `ErrorBoundary`, so the Studio bridge keeps rendering on 404s and\n * loader/render errors — exactly the pages where Studio must still answer its\n * handshake instead of reporting a false \"Connection lost\". A default-component\n * wrapper (`export default withWeaverse(App)`) is replaced by the error\n * boundary on those routes and would drop the bridge.\n *\n * @param Component - The root layout component to wrap\n * @param options - Optional configuration (e.g. an external `t` function)\n * @returns Wrapped component with theme settings + translation providers\n *\n * @example\n * ```typescript\n * import { withWeaverse } from '@weaverse/hydrogen'\n *\n * // Basic usage — export as the root route Layout\n * export const Layout = withWeaverse(RootLayout)\n *\n * // With an external translation function\n * export const Layout = withWeaverse(RootLayout, { t: myI18nFunction })\n * ```\n */\nexport function withWeaverse(\n Component: ComponentType<any>,\n options?: WithWeaverseOptions\n) {\n return (props: JSX.IntrinsicAttributes) => {\n const themeSettingsStore = useCreateThemeSettingsStore()\n const translationData = useTranslationData()\n const translationStoreRef = useRef<TranslationStore | null>(null)\n if (!translationStoreRef.current) {\n translationStoreRef.current = new TranslationStore()\n }\n return (\n <ThemeSettingsStoreContext.Provider value={themeSettingsStore}>\n <TranslationProvider\n merchantOverrides={translationData.merchantOverrides}\n staticContent={translationData.staticContent}\n t={options?.t}\n translationStore={translationStoreRef.current}\n >\n <StudioConnect />\n <Component {...props} />\n </TranslationProvider>\n </ThemeSettingsStoreContext.Provider>\n )\n }\n}\n\n/**\n * Internal hook to read staticContent and merchantOverrides from root loader data.\n * Similar pattern to useThemeSettingsStore – reads from the 'root' route loader.\n */\nfunction useTranslationData(): {\n staticContent: Record<string, unknown>\n merchantOverrides?: Record<string, unknown>\n} {\n const data = useRouteLoaderData('root') as {\n weaverseTheme?: {\n staticContent?: Record<string, unknown>\n merchantOverrides?: Record<string, unknown>\n }\n }\n return {\n staticContent: data?.weaverseTheme?.staticContent ?? {},\n merchantOverrides: data?.weaverseTheme?.merchantOverrides,\n }\n}\n\n/**\n * React hook to access Weaverse theme settings from anywhere in your component tree.\n * Must be used within a component wrapped by `withWeaverse` or inside `WeaverseHydrogenRoot`.\n *\n * @returns Current theme settings object\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const theme = useThemeSettings()\n * const primaryColor = theme.colors?.primary\n *\n * return <div style={{ color: primaryColor }}>Styled content</div>\n * }\n * ```\n */\nexport function useThemeSettings<T = HydrogenThemeSettings>() {\n const themeSettingsStore = useThemeSettingsStore()\n const settings = useSafeExternalStore(\n themeSettingsStore.subscribe,\n themeSettingsStore.getSnapshot,\n themeSettingsStore.getServerSnapshot\n )\n return settings as T\n}\n","// Query params that influence Weaverse page resolution on the Builder:\n// revision previews, design-mode flags, and `weaverse*` control params\n// (host, version, project id). Everything else — utm_*, fbclid, gclid,\n// storefront filters — is irrelevant to which page the Builder returns.\nconst KEPT_PARAM_RE = /^(?:__revisionId|isDesignMode|weaverse)/\n\n/**\n * Normalize the storefront URL sent in the Builder page API request body.\n *\n * The POST body participates in the `withCache` cache key, so a raw\n * `request.url` fragments the cache by every marketing/tracking param:\n * each distinct `?utm_…`/`fbclid` URL is a guaranteed Builder round-trip\n * even when the resolved page is identical — precisely the paid/social\n * traffic that needs the cache most (builder#2450).\n *\n * The Builder reads only the pathname (locale/type/handle fallback) and\n * the params matched above from this URL, so keep exactly those. Params\n * are sorted for a stable cache key regardless of their order in the\n * incoming URL.\n */\nexport function normalizePageUrl(url: string): string {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n // Not an absolute URL (shouldn't happen for request.url) — send as-is.\n return url\n }\n const kept = [...parsed.searchParams].filter(([key]) =>\n KEPT_PARAM_RE.test(key)\n )\n kept.sort(([a], [b]) => a.localeCompare(b))\n const search = new URLSearchParams(kept).toString()\n // React Router single-fetch requests loader data from `/<path>.data`, which\n // resolves to the same Builder page as `/<path>`. Strip the suffix so a\n // client navigation and a document load hash to one edge-cache key (the\n // api.weaverse.io worker keys on this url) instead of two — keeping a page's\n // first client navigation off the cold-MISS path.\n let { pathname } = parsed\n if (pathname.endsWith('.data')) {\n pathname = pathname.slice(0, -'.data'.length)\n }\n return `${parsed.origin}${pathname}${search ? `?${search}` : ''}`\n}\n","import {\n CacheCustom,\n createWithCache,\n type HydrogenEnv,\n type I18nBase,\n} from '@shopify/hydrogen'\nimport type {\n CachingStrategy,\n CustomPageEntry,\n FetchProjectPayload,\n FetchProjectRequestBody,\n HydrogenComponent,\n HydrogenComponentData,\n HydrogenPageData,\n LoadPageParams,\n PageType,\n ProjectIdValidationResult,\n ThemeSettingsResponse,\n WeaverseClientArgs,\n WeaverseLoaderData,\n WeaverseProjectConfigs,\n WeaverseStudioQueries,\n WithCacheFetchResponse,\n} from './types'\nimport {\n hasError,\n isFetchProjectPayload,\n isProjectIdFunction,\n WeaverseError,\n} from './types'\nimport {\n generateDataFromSchema,\n getPreviewData,\n getRequestQueries,\n getWeaverseConfigs,\n} from './utils'\nimport { normalizePageUrl } from './utils/normalize-page-url'\n\n/**\n * Cache duration constants (in seconds).\n * These values optimize CDN hit rates while maintaining fresh content.\n */\nconst CACHE_DURATIONS = {\n /** Short browser freshness for content that can change in Builder */\n SHORT: 60,\n /** Shared cache freshness for anonymous storefront traffic */\n SHARED_SHORT: 300,\n /** Long stale window so slow Builder responses do not block storefront rendering */\n LONG: 86_400,\n /** Extra freshness for sitemap-like index data */\n STATIC: 3600,\n} as const\n\n/**\n * Network timeout for fetch requests (in milliseconds).\n * Default is 10 seconds to balance reliability and user experience.\n */\nconst DEFAULT_FETCH_TIMEOUT_MS = 10_000\n\n/**\n * Bounded retry for the public API fetch. A single slow/cold origin response,\n * a transient 5xx, or a network blip would otherwise make loadPage return null\n * — rendering the \"Please add new section\" placeholder or throwing a 404 in\n * the route. Two attempts (one retry) is enough: by the time the first attempt\n * times out, the edge proxy's single-flight leader has usually populated its\n * versioned cache, so the retry lands on a warm HIT.\n */\nconst MAX_FETCH_ATTEMPTS = 2\nconst FETCH_RETRY_BACKOFF_MS = 300\n\n/**\n * Retry only transient failures: request timeouts, network errors, and origin\n * 5xx. A 4xx is deterministic (e.g. a genuine 404) — retrying just wastes time.\n */\nfunction isRetryableFetchError(error: unknown): boolean {\n if (!(error instanceof WeaverseError)) {\n return false\n }\n if (error.code === 'TIMEOUT_ERROR' || error.code === 'NETWORK_ERROR') {\n return true\n }\n return error.code === 'FETCH_ERROR' && (error.statusCode ?? 0) >= 500\n}\n\n/**\n * Weaverse API version path\n */\nconst API_PATH = 'v1' as const\n\n/**\n * Default cache strategy for Weaverse API requests.\n * Optimized for CDN performance with 23-hour stale content tolerance.\n */\nconst DEFAULT_CACHE_STRATEGY: CachingStrategy = {\n maxAge: CACHE_DURATIONS.SHORT,\n sMaxAge: CACHE_DURATIONS.SHARED_SHORT,\n staleWhileRevalidate: CACHE_DURATIONS.LONG,\n staleIfError: CACHE_DURATIONS.LONG,\n} as const\n\n/** Builder API resource whose freshness policy should be used for a request. */\nexport type BuilderApiCacheTarget =\n | 'custom-pages'\n | 'merchant-overrides'\n | 'project'\n | 'theme-settings'\n\n/** Fetch options accepted by {@link WeaverseClient.fetchWithCache}. */\nexport interface WeaverseFetchWithCacheOptions extends RequestInit {\n /** Builder API resource whose default freshness policy should be used. */\n cacheTarget?: BuilderApiCacheTarget\n /** Explicit Hydrogen caching strategy overriding the resource default. */\n strategy?: CachingStrategy\n}\n\n/** Pagination and locale options for {@link WeaverseClient.fetchCustomPages}. */\nexport interface FetchCustomPagesOptions {\n /** Maximum number of custom pages requested per API page. */\n limit?: number\n /** Locale whose published custom pages should be returned. */\n locale?: string\n}\n\nconst SMART_CACHE_STRATEGIES: Record<BuilderApiCacheTarget, CachingStrategy> = {\n project: DEFAULT_CACHE_STRATEGY,\n 'theme-settings': DEFAULT_CACHE_STRATEGY,\n 'merchant-overrides': DEFAULT_CACHE_STRATEGY,\n 'custom-pages': {\n maxAge: CACHE_DURATIONS.SHORT,\n sMaxAge: CACHE_DURATIONS.STATIC,\n staleWhileRevalidate: CACHE_DURATIONS.LONG,\n staleIfError: CACHE_DURATIONS.LONG,\n },\n} as const\n\n/**\n * Options objects created by the internal `project_configs` request whose\n * subrequest cache identity deliberately excludes the body. Theme settings\n * carry the storefront origin so Builder can attribute hostnames; hashing the\n * body would give every domain of one project its own entry.\n *\n * The SUCCESSFUL theme payload is the same for every storefront of a project,\n * which is what makes one shared entry correct. This is not a claim that\n * Builder can never answer differently per host: a hostname-blocked request\n * returns a 403 `{ error }` body, and `shouldCacheResponse` rejects anything\n * `hasError()` matches, so a refusal is never stored under (or served from)\n * the shared entry. If a future response shape ever varies by host WITHOUT an\n * `error` field, this exclusion has to be revisited.\n *\n * Keyed on the exact options object, NOT on `cacheTarget`: `fetchWithCache`\n * is public API, so gating on the target would silently collapse the cache of\n * any consumer who selects `theme-settings` with varying bodies. An outside\n * caller's options object is never in this set and keeps a body-derived key.\n *\n * The WeakSet-membership slot in the cache key (`has(options)`) is the actual\n * discriminator — no caller-supplied value can reach it. The sentinel is not\n * load-bearing for that; it only keeps the omitted body legible in cache\n * debugging instead of a bare `undefined`.\n */\nconst bodyFreeCacheRequests = new WeakSet<object>()\nconst BODY_FREE_CACHE_SENTINEL = '\\u0000weaverse:body-free'\n\n/**\n * Request-scoped client for loading Weaverse pages and theme settings in Hydrogen.\n *\n * Create one client from the Hydrogen app context, then call\n * {@link WeaverseClient.loadPage} from route loaders and\n * {@link WeaverseClient.loadThemeSettings} from the root loader.\n */\nexport class WeaverseClient {\n /** Builder API version used by this client. */\n API = API_PATH\n /** Stable project configuration shared by page requests. */\n basePageConfigs: Omit<WeaverseProjectConfigs, 'requestInfo'>\n /** Stable request body fields shared by page requests. */\n basePageRequestBody: Omit<FetchProjectRequestBody, 'url'>\n /** Resolved project and rendering-mode configuration. */\n configs: WeaverseProjectConfigs\n /** Hydrogen cache wrapper used for Builder API requests. */\n withCache: ReturnType<typeof createWithCache>\n\n /** Incoming request associated with this client instance. */\n request: WeaverseClientArgs['request']\n /** Hydrogen customer-account client, when configured. */\n customerAccount: WeaverseClientArgs['customerAccount']\n /** Hydrogen Storefront API client and locale context. */\n storefront: WeaverseClientArgs['storefront']\n /** Components registered for page rendering and component loaders. */\n components: WeaverseClientArgs['components']\n /** Theme schema used for defaults and Studio editing. */\n themeSchema: WeaverseClientArgs['themeSchema']\n /** Hydrogen runtime environment variables. */\n env: WeaverseClientArgs['env']\n /** Cache storage supplied by the Hydrogen runtime. */\n cache: WeaverseClientArgs['cache']\n /** Background execution hook supplied by the Oxygen runtime. */\n waitUntil: WeaverseClientArgs['waitUntil']\n\n // Performance optimizations\n private readonly parsedUrl: URL\n private readonly componentsByType: Map<string, HydrogenComponent>\n\n // Configuration\n private readonly fetchTimeoutMs: number\n\n /** Creates a request-scoped client from the Hydrogen app context. */\n constructor(args: WeaverseClientArgs) {\n // Assign required dependencies\n this.request = args.request\n this.storefront = args.storefront\n this.customerAccount = args.customerAccount\n this.components = args.components\n this.themeSchema = args.themeSchema\n this.env = args.env\n this.cache = args.cache\n this.waitUntil = args.waitUntil\n\n // Performance optimizations\n this.parsedUrl = new URL(args.request.url)\n this.componentsByType = this.buildComponentLookupMap(args.components)\n\n // Configuration\n this.fetchTimeoutMs = args.fetchTimeoutMs || DEFAULT_FETCH_TIMEOUT_MS\n\n // Initialize cache and configs\n this.initializeCache(args)\n this.initializeConfigs(args)\n }\n\n /**\n * Initialize Hydrogen cache with proper configuration.\n * Logs warning if waitUntil is missing.\n */\n private initializeCache(args: WeaverseClientArgs): void {\n if (!args.waitUntil) {\n console.warn(\n '⚠️ WeaverseClient: waitUntil not provided, background operations may not complete'\n )\n }\n\n this.withCache = createWithCache({\n cache: args.cache,\n waitUntil: args.waitUntil || (() => Promise.resolve()),\n request: args.request,\n })\n }\n\n /**\n * Initialize configs with projectId resolution and fail-fast validation.\n * Throws WeaverseError if projectId cannot be resolved.\n */\n private initializeConfigs(args: WeaverseClientArgs): void {\n // Get base configs once to avoid duplicate calls\n const baseConfigs = getWeaverseConfigs(\n args.request,\n args.env as HydrogenEnv\n )\n\n // Resolve projectId with multi-project support\n const resolvedProjectId = this.resolveProjectIdSync(\n args.projectId,\n args.request,\n args.env as HydrogenEnv,\n baseConfigs\n )\n\n // Fail-fast validation: throw if projectId is empty\n if (!resolvedProjectId || resolvedProjectId.trim() === '') {\n throw new WeaverseError(\n 'Failed to initialize WeaverseClient: No valid projectId found. ' +\n 'Set WEAVERSE_PROJECT_ID environment variable or provide projectId parameter.',\n 'MISSING_PROJECT_ID'\n )\n }\n\n // Initialize configs with resolved projectId\n this.configs = {\n ...baseConfigs,\n projectId: resolvedProjectId,\n }\n\n // Initialize base configurations\n this.basePageConfigs = {\n projectId: this.configs.projectId,\n weaverseHost: this.configs.weaverseHost,\n weaverseApiBase: this.configs.weaverseApiBase,\n weaverseApiKey: this.configs.weaverseApiKey,\n weaverseVersion: this.configs.weaverseVersion,\n isDesignMode: this.configs.isDesignMode,\n isPreviewMode: this.configs.isPreviewMode,\n isRevisionPreview: this.configs.isRevisionPreview,\n }\n\n this.basePageRequestBody = {\n isDesignMode: this.configs.isDesignMode,\n i18n: args.storefront.i18n,\n projectId: this.configs.projectId,\n }\n\n // Freeze configs to prevent accidental mutations\n Object.freeze(this.configs)\n Object.freeze(this.basePageConfigs)\n Object.freeze(this.basePageRequestBody)\n }\n\n /**\n * Build component lookup map for O(1) access by type.\n * Significantly improves performance for large component lists.\n */\n private buildComponentLookupMap(\n components: HydrogenComponent[]\n ): Map<string, HydrogenComponent> {\n return new Map(components.map((comp) => [comp.schema?.type, comp]))\n }\n\n /**\n * Extract comprehensive error information from unknown error type.\n * Preserves error context, codes, and stack traces for debugging.\n *\n * @param error - Unknown error to extract information from\n * @returns Structured error information with message, code, stack, and context\n *\n * @example\n * ```typescript\n * try {\n * // ... operation\n * } catch (error) {\n * const errorInfo = this.extractErrorInfo(error)\n * console.error('Operation failed:', errorInfo.message, errorInfo.context)\n * }\n * ```\n */\n private extractErrorInfo(error: unknown): {\n message: string\n code?: string\n stack?: string\n context?: Record<string, unknown>\n } {\n if (error instanceof WeaverseError) {\n return {\n message: error.message,\n code: error.code,\n context: error.context,\n stack: error.stack,\n }\n }\n\n if (error instanceof Error) {\n return {\n message: error.message,\n stack: error.stack,\n }\n }\n\n return {\n message: String(error),\n }\n }\n\n /**\n * Extract error message only (for backward compatibility).\n * Use extractErrorInfo() for more detailed error information.\n *\n * @deprecated Use extractErrorInfo() instead to preserve error context\n */\n private extractErrorMessage(error: unknown): string {\n return this.extractErrorInfo(error).message\n }\n\n /**\n * Validates projectId format (alphanumeric, hyphens, underscores only).\n * Returns detailed validation result with error message.\n *\n * @param projectId - Project identifier to validate\n * @returns Validation result with error message if invalid\n */\n private validateProjectId(projectId: string): ProjectIdValidationResult {\n if (!projectId || projectId.trim() === '') {\n return {\n valid: false,\n error: 'Project ID cannot be empty',\n }\n }\n\n // Only allow alphanumeric characters, hyphens, and underscores\n const validPattern = /^[a-zA-Z0-9_-]+$/\n if (!validPattern.test(projectId)) {\n return {\n valid: false,\n error: `Invalid format: \"${projectId}\". Only alphanumeric characters, hyphens, and underscores are allowed.`,\n }\n }\n\n return { valid: true }\n }\n\n /**\n * Resolves projectId with multi-project architecture support.\n * Uses priority chain to determine the correct project ID.\n *\n * @param projectId - Project identifier (string, function, or undefined)\n * @param request - HTTP request for context access\n * @param env - Hydrogen environment with variables\n * @param baseConfigs - Pre-fetched base configs to avoid duplicate calls\n * @returns Resolved project ID string (empty string if none found)\n */\n private resolveProjectIdSync(\n projectId: string | (() => string) | (() => Promise<string>) | undefined,\n request: Request,\n env: HydrogenEnv,\n baseConfigs?: WeaverseProjectConfigs\n ): string {\n return (\n this.resolveFromQueryParams(request) ||\n this.resolveFromFunction(projectId) ||\n this.resolveFromString(projectId) ||\n this.resolveFromEnvironment(baseConfigs, request, env) ||\n ''\n )\n }\n\n /**\n * Priority 1: Resolve projectId from URL query parameters.\n * Used for design mode and preview mode overrides.\n */\n private resolveFromQueryParams(request: Request): string | null {\n const queries = getRequestQueries<WeaverseStudioQueries>(request)\n return queries.weaverseProjectId || null\n }\n\n /**\n * Priority 2: Resolve projectId from function parameter.\n * Detects and rejects async functions with helpful error.\n */\n private resolveFromFunction(\n projectId: string | (() => string) | (() => Promise<string>) | undefined\n ): string | null {\n if (!isProjectIdFunction(projectId)) {\n return null\n }\n\n // Check if it's an async function BEFORE calling\n if (projectId.constructor.name === 'AsyncFunction') {\n throw new WeaverseError(\n 'Async projectId functions must be awaited before passing to WeaverseClient. ' +\n 'Use: projectId: await getProjectAsync() instead of: projectId: getProjectAsync',\n 'ASYNC_PROJECT_ID'\n )\n }\n\n try {\n const result = projectId()\n\n // Safety net: check if result is a Promise\n if (result instanceof Promise) {\n throw new WeaverseError(\n 'Async projectId functions must be awaited before passing to WeaverseClient. ' +\n 'Use: projectId: await getProjectAsync() instead of: projectId: getProjectAsync',\n 'ASYNC_PROJECT_ID'\n )\n }\n\n if (result && result.trim() !== '') {\n const trimmed = result.trim()\n const validation = this.validateProjectId(trimmed)\n\n if (validation.valid) {\n return trimmed\n }\n\n // Throw on validation failure - fail-fast for explicit projectId\n throw new WeaverseError(\n validation.error || 'Invalid projectId format',\n 'INVALID_PROJECT_ID'\n )\n }\n } catch (err) {\n // Re-throw WeaverseError (async function errors, validation errors)\n if (err instanceof WeaverseError) {\n throw err\n }\n\n // Wrap unexpected errors\n throw new WeaverseError(\n `Failed to evaluate projectId function: ${err instanceof Error ? err.message : String(err)}`,\n 'PROJECT_ID_FUNCTION_ERROR',\n undefined,\n { cause: err instanceof Error ? err.stack : String(err) }\n )\n }\n\n return null\n }\n\n /**\n * Priority 3: Resolve projectId from explicit string parameter.\n */\n private resolveFromString(\n projectId: string | (() => string) | (() => Promise<string>) | undefined\n ): string | null {\n if (typeof projectId !== 'string') {\n return null\n }\n\n const trimmed = projectId.trim()\n if (trimmed === '') {\n return null\n }\n\n const validation = this.validateProjectId(trimmed)\n if (validation.valid) {\n return trimmed\n }\n\n // Throw on validation failure - fail-fast for explicit projectId\n throw new WeaverseError(\n validation.error || 'Invalid projectId format',\n 'INVALID_PROJECT_ID'\n )\n }\n\n /**\n * Priority 4: Resolve projectId from environment variables.\n */\n private resolveFromEnvironment(\n baseConfigs: WeaverseProjectConfigs | undefined,\n request: Request,\n env: HydrogenEnv\n ): string | null {\n const configs = baseConfigs || getWeaverseConfigs(request, env)\n\n if (configs.projectId && configs.projectId.trim() !== '') {\n return configs.projectId.trim()\n }\n\n return null\n }\n\n /**\n * Helper method for direct fetching in design mode.\n * Returns same format as withCache.fetch for consistency.\n * Includes 10-second timeout to prevent hanging requests.\n */\n private readonly fetchOnce = async <T>(\n url: string,\n options: RequestInit,\n timeoutMs: number\n ): Promise<WithCacheFetchResponse<T>> => {\n const controller = new AbortController()\n const timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(\n () => controller.abort(),\n timeoutMs\n )\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new WeaverseError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'FETCH_ERROR',\n response.status,\n { url, errorText }\n )\n }\n\n const data = (await response.json()) as T\n return { data, response }\n } catch (err) {\n if (err instanceof WeaverseError) {\n throw err\n }\n\n if (err.name === 'AbortError') {\n throw new WeaverseError(\n `Request timeout after ${timeoutMs}ms`,\n 'TIMEOUT_ERROR',\n undefined,\n { url, timeoutMs }\n )\n }\n\n throw new WeaverseError(\n 'Network error during fetch',\n 'NETWORK_ERROR',\n undefined,\n { url, cause: err instanceof Error ? err.message : String(err) }\n )\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId)\n }\n }\n }\n\n private readonly directFetch = async <T>(\n url: string,\n options: RequestInit = {},\n timeoutMs = this.fetchTimeoutMs\n ): Promise<WithCacheFetchResponse<T>> => {\n let lastError: unknown\n for (let attempt = 1; attempt <= MAX_FETCH_ATTEMPTS; attempt++) {\n try {\n return await this.fetchOnce<T>(url, options, timeoutMs)\n } catch (err) {\n lastError = err\n if (attempt >= MAX_FETCH_ATTEMPTS || !isRetryableFetchError(err)) {\n throw err\n }\n await new Promise((resolve) =>\n setTimeout(resolve, FETCH_RETRY_BACKOFF_MS * attempt)\n )\n }\n }\n throw lastError\n }\n\n // Helper method for building API URLs consistently\n private getApiUrl(endpoint: string): string {\n const { weaverseApiBase } = this.configs\n return `${weaverseApiBase}/api/public/${endpoint}`\n }\n\n private isExternalPublicApiUrl(url: string): boolean {\n const { weaverseApiBase, weaverseHost } = this.configs\n return (\n weaverseApiBase !== weaverseHost &&\n url.startsWith(`${weaverseApiBase}/api/public/`)\n )\n }\n\n /**\n * Fetch data with caching support for both design mode and production.\n * Uses direct fetch in design mode, Hydrogen's withCache in production.\n * Automatically includes projectId in cache key for multi-project isolation.\n *\n * @param url - The URL to fetch from\n * @param options - Fetch options including optional cache strategy\n * @returns Promise resolving to the fetched data\n *\n * @example\n * ```typescript\n * const data = await weaverse.fetchWithCache<MyData>(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify({ key: 'value' }) }\n * )\n * ```\n */\n public fetchWithCache = async <T = unknown>(\n url: string,\n options: WeaverseFetchWithCacheOptions = {}\n ): Promise<T> => {\n const { cacheTarget, strategy: strategyOverride, ...fetchOptions } = options\n const strategy =\n strategyOverride ||\n CacheCustom(\n cacheTarget\n ? SMART_CACHE_STRATEGIES[cacheTarget]\n : DEFAULT_CACHE_STRATEGY\n )\n\n // Update cache key to include method, body content, and projectId for multi-project isolation\n // Prefix for easier debugging in cache systems\n //\n // The body is omitted only for options objects marked internally (see\n // `bodyFreeCacheRequests`): the storefront origin must reach Builder for\n // hostname attribution, but two domains of one project have to share one\n // entry. Every other caller keeps a body-derived key.\n const cacheKey = [\n 'weaverse-fetch',\n url,\n options.method || 'GET',\n bodyFreeCacheRequests.has(options)\n ? BODY_FREE_CACHE_SENTINEL\n : fetchOptions.body,\n // WeakSet-derived discriminator: this slot cannot be produced by any\n // caller-supplied shape, so no external call can reach the marked\n // identity — even one that happens to send the sentinel string as its\n // body.\n bodyFreeCacheRequests.has(options),\n this.configs.projectId,\n cacheTarget || 'default',\n ]\n let result: WithCacheFetchResponse<T>\n\n // Bypass the shared Hydrogen subrequest cache for design/revision modes\n // and for the Cloudflare public API proxy. The proxy owns freshness with\n // versioned cache keys; keeping Hydrogen's URL/body cache in front would\n // keep serving a stale response even after Builder bumps the proxy's\n // project version.\n if (\n this.configs.isDesignMode ||\n this.configs.isRevisionPreview ||\n this.isExternalPublicApiUrl(url)\n ) {\n result = await this.directFetch<T>(url, fetchOptions)\n } else {\n // Use withCache.fetch for better integration with Hydrogen's caching system\n result = (await this.withCache.fetch(url, fetchOptions, {\n cacheKey,\n cacheStrategy: strategy,\n shouldCacheResponse: (response: any): boolean => {\n // An aborted request never caches: Hydrogen turns a body read cut\n // short by the abort into an empty payload, not an error.\n if (fetchOptions.signal?.aborted) {\n return false\n }\n // Cache any non-error response (for both Weaverse API and third-party APIs)\n return (\n !hasError(response) && response !== null && response !== undefined\n )\n },\n displayName: 'Weaverse API',\n })) as WithCacheFetchResponse<T>\n }\n\n return result.data\n }\n\n /**\n * Safe origin of the incoming storefront request: scheme, host and explicit\n * port. Userinfo, path, query and fragment are dropped, so no customer\n * route or credential-bearing value leaves the storefront. Returns undefined\n * for a non-http(s) request so the field is simply omitted.\n */\n private safeStorefrontOrigin(): string | undefined {\n const { protocol, host } = this.parsedUrl\n if (protocol !== 'http:' && protocol !== 'https:') {\n return\n }\n return host ? `${protocol}//${host}` : undefined\n }\n\n /**\n * Load theme settings from Weaverse API with fallback to schema defaults.\n * Merges remote settings with local theme schema and handles design mode serialization.\n *\n * @param strategy - Optional cache strategy override\n * @returns Promise resolving to theme settings response\n *\n * @example\n * ```typescript\n * const settings = await weaverse.loadThemeSettings()\n * const primaryColor = settings.theme.colors?.primary\n * ```\n */\n loadThemeSettings = async (\n strategy?: CachingStrategy\n ): Promise<ThemeSettingsResponse> => {\n const defaultThemeSettings = generateDataFromSchema(this.themeSchema)\n try {\n const { configs } = this\n const { projectId, isDesignMode } = configs\n if (!projectId) {\n throw new Error('Missing Weaverse projectId!')\n }\n\n const url = this.getApiUrl('project_configs')\n\n // Theme/config reads carry no route, so Builder could not tell which\n // storefront asked. `storefrontUrl` is the request's safe origin only —\n // scheme, host and explicit port, never a path, query, fragment or\n // userinfo — so hosted-content attribution works without sending\n // customer-visible URL data. Older Builder deployments ignore the extra\n // field. The response does not vary by storefront, so the origin stays\n // out of BOTH cache identities: the edge excludes it from its selectors,\n // and this request is marked in `bodyFreeCacheRequests` so Hydrogen's\n // own subrequest cache key omits the body — hashing it would otherwise\n // give every domain of one project its own entry.\n const body = JSON.stringify({\n isDesignMode,\n projectId,\n storefrontUrl: this.safeStorefrontOrigin(),\n })\n\n // Fetch theme settings and merchant overrides in parallel. The options\n // object is registered in `bodyFreeCacheRequests` so `fetchWithCache`\n // keeps the storefront origin out of the subrequest cache identity for\n // exactly this internal request — see the marker's doc comment.\n const themeSettingsOptions: WeaverseFetchWithCacheOptions = {\n method: 'POST',\n cacheTarget: 'theme-settings',\n strategy,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'Accept-Encoding': 'gzip, deflate, br',\n },\n }\n bodyFreeCacheRequests.add(themeSettingsOptions)\n\n const [data, merchantOverrides] = await Promise.all([\n this.fetchWithCache<ThemeSettingsResponse>(url, themeSettingsOptions),\n this.fetchMerchantOverrides(strategy),\n ])\n\n let result = data\n\n // Validate that data is a proper object, not corrupted/compressed content\n if (typeof result !== 'object' || result === null) {\n console.warn(\n 'Invalid theme settings response format, using defaults:',\n {\n type: typeof result,\n isString: typeof result === 'string',\n length:\n typeof result === 'string' ? (result as string).length : 'N/A',\n preview:\n typeof result === 'string'\n ? `${(result as string).slice(0, 50)}...`\n : String(result),\n }\n )\n result = { theme: defaultThemeSettings }\n }\n\n if (this.themeSchema?.settings || this.themeSchema?.inspector) {\n // Ensure result.theme exists and is an object before merging\n if (!result.theme || typeof result.theme !== 'object') {\n result.theme = defaultThemeSettings\n } else {\n result.theme = {\n ...defaultThemeSettings,\n ...result.theme,\n }\n }\n }\n\n // Always include staticContent from themeSchema.i18n\n const staticContent = this.themeSchema?.i18n?.staticContent\n if (staticContent) {\n result.staticContent = staticContent\n }\n\n // Include merchant overrides (locale-specific translations from DB)\n if (merchantOverrides) {\n result.merchantOverrides = merchantOverrides\n }\n\n if (this.configs.isDesignMode) {\n result = {\n ...result,\n schema:\n this.themeSchema && typeof this.themeSchema === 'object'\n ? {\n ...this.themeSchema,\n settings: this.themeSchema?.settings?.map((group) => ({\n ...group,\n inputs: group?.inputs?.map((input) => {\n if (typeof input?.condition === 'function') {\n return {\n ...input,\n condition: input.condition.toString(),\n }\n }\n return input\n }),\n })),\n }\n : undefined,\n publicEnv: this.configs.publicEnv,\n }\n }\n return result\n } catch (error) {\n const errorMessage = 'Unable to load theme settings'\n const errorDetails = this.extractErrorMessage(error)\n\n console.error(errorMessage, errorDetails)\n\n return {\n theme: defaultThemeSettings,\n staticContent: this.themeSchema?.i18n?.staticContent,\n _error: errorDetails,\n _loadFailed: true,\n }\n }\n }\n\n /**\n * Fetch locale-specific merchant overrides from the translation API.\n * Returns a nested JSON object with translated values.\n * Falls back to empty object on error to avoid blocking theme rendering.\n */\n private fetchMerchantOverrides = async (\n strategy?: CachingStrategy\n ): Promise<Record<string, unknown> | undefined> => {\n try {\n const { projectId, weaverseHost } = this.configs\n const i18n = this.storefront.i18n\n\n // Skip entirely when the theme hasn't opted into i18n. Merchant overrides\n // are locale-specific translations; a theme with no `i18n` schema has no\n // translatable surface, so the fetch would always come back empty. Gating\n // here keeps non-i18n storefronts from making a translation API call on\n // every SSR — same `themeSchema.i18n` condition that guards `staticContent`.\n if (!this.themeSchema?.i18n) {\n return\n }\n\n if (!(projectId && weaverseHost)) {\n return\n }\n\n // Build locale code from storefront i18n (e.g. \"en-us\")\n const language = (i18n?.language || 'en').toLowerCase()\n const country = (i18n?.country || 'us').toLowerCase()\n const locale = `${language}-${country}`\n\n const url = `${weaverseHost}/api/translation/static?projectId=${projectId}&locale=${locale}`\n\n // Overrides are optional, and `loadThemeSettings` awaits them next to\n // the main settings. Hydrogen's cached fetch adds no deadline of its\n // own, so bound the request and its body with the client fetch timeout;\n // on abort the catch below falls back to theme defaults. Design and\n // revision modes ignore this signal and keep `directFetch`'s own\n // timeout and retry.\n const overrides = await this.fetchWithCache<Record<string, unknown>>(\n url,\n {\n method: 'GET',\n cacheTarget: 'merchant-overrides',\n strategy,\n headers: {\n Accept: 'application/json',\n },\n signal: AbortSignal.timeout(this.fetchTimeoutMs),\n }\n )\n\n // Validate it's a proper object\n if (typeof overrides === 'object' && overrides !== null) {\n return overrides\n }\n\n return\n } catch (error) {\n // Don't let merchant overrides failure block theme rendering\n console.warn(\n 'Unable to load merchant overrides, using theme defaults:',\n this.extractErrorMessage(error)\n )\n return\n }\n }\n\n /**\n * Generate fallback page with default structure when page data is unavailable.\n * Used internally when API returns no page or when page needs default content.\n *\n * @param message - Custom message to display in the fallback page\n * @returns HydrogenPageData with single main component containing the message\n */\n generateFallbackPage = (message: string): HydrogenPageData => {\n const rootId = crypto.randomUUID()\n return {\n id: `fallback_page_${Date.now()}`,\n rootId,\n name: 'Default Page',\n items: [\n {\n type: 'main',\n id: rootId,\n data: { dangerouslySetInnerHTML: { __html: message } },\n },\n ],\n }\n }\n\n /**\n * Fetch all published custom pages for sitemap generation.\n * Paginates automatically, never throws, returns accumulated results on partial failure.\n */\n async fetchCustomPages(\n opts?: FetchCustomPagesOptions\n ): Promise<CustomPageEntry[]> {\n const { weaverseApiBase, projectId } = this.configs\n const entries: CustomPageEntry[] = []\n const MAX_PAGES = 100\n\n let cursor: string | null = null\n\n for (let i = 0; i < MAX_PAGES; i++) {\n const params = new URLSearchParams()\n if (opts?.locale) {\n params.set('locale', opts.locale)\n }\n if (opts?.limit) {\n params.set('limit', String(opts.limit))\n }\n if (cursor) {\n params.set('cursor', cursor)\n }\n\n const qs = params.toString()\n const url = `${weaverseApiBase}/api/public/v1/projects/${projectId}/custom-pages${qs ? `?${qs}` : ''}`\n\n try {\n const result = await this.fetchWithCache<{\n data: CustomPageEntry[]\n nextCursor: string | null\n }>(url, { cacheTarget: 'custom-pages' })\n entries.push(...(result.data || []))\n\n if (!result.nextCursor) {\n return entries\n }\n cursor = result.nextCursor\n } catch (err: any) {\n const status = err?.status\n const msg = err?.message || String(err)\n console.warn(\n entries.length === 0\n ? `[Weaverse] Failed to fetch custom pages: ${msg}${status ? ` (HTTP ${status})` : ''}`\n : `[Weaverse] Custom pages pagination interrupted: ${msg}`\n )\n return entries\n }\n }\n\n console.warn(\n '[Weaverse] Custom pages pagination cap reached (100 iterations)'\n )\n return entries\n }\n\n /**\n * Load page data from Weaverse API with optional route-level project override.\n * Fetches page content, executes component loaders, and handles empty items fallback.\n *\n * @param params - Optional page loading parameters\n * @param params.type - Page type (INDEX, PAGE, PRODUCT, COLLECTION, etc.)\n * @param params.handle - Page handle for dynamic routes\n * @param params.locale - Locale override\n * @param params.projectId - Route-level project ID override (for multi-project)\n * @param params.strategy - Custom cache strategy override\n * @returns Promise resolving to page data or null on error\n *\n * @example\n * ```typescript\n * // Basic usage\n * const data = await weaverse.loadPage()\n *\n * // With page type\n * const data = await weaverse.loadPage({ type: 'INDEX' })\n *\n * // Route-level project override\n * const data = await weaverse.loadPage({\n * type: 'PAGE',\n * handle: 'about',\n * projectId: 'campaign-project-123'\n * })\n * ```\n */\n loadPage = async (\n params: LoadPageParams = {}\n ): Promise<WeaverseLoaderData | null> => {\n try {\n const { request, storefront, basePageRequestBody, basePageConfigs } = this\n const {\n projectId: clientProjectId,\n weaverseHost,\n isPreviewMode,\n sectionType,\n } = this.configs\n\n // Validate route-level projectId if provided\n if (params.projectId !== undefined) {\n if (typeof params.projectId !== 'string') {\n console.error(\n 'Route-level projectId validation failed: must be a string. ' +\n `Received: ${typeof params.projectId}`\n )\n return null\n }\n\n const validation = this.validateProjectId(params.projectId)\n if (!validation.valid) {\n console.error(\n `Route-level projectId validation failed: ${validation.error}`\n )\n return null\n }\n }\n\n // Override client-level projectId with route-level projectId if provided\n const effectiveProjectId = params.projectId || clientProjectId\n\n if (isPreviewMode) {\n return getPreviewData(sectionType || '', this.components, weaverseHost)\n }\n\n if (!effectiveProjectId) {\n throw new Error('Missing Weaverse projectId!')\n }\n\n const { strategy, ...pageLoadParams } = params\n const body: {\n projectId: string\n url: string\n i18n?: I18nBase\n params?: {\n type?: PageType\n locale?: string\n handle?: string\n }\n isDesignMode?: boolean\n } = {\n ...basePageRequestBody,\n projectId: effectiveProjectId, // Use effective (potentially overridden) projectId\n params: pageLoadParams,\n // Stripped to pathname + Weaverse params — tracking params would\n // fragment the subrequest cache key (see normalizePageUrl).\n url: normalizePageUrl(request.url),\n }\n\n const reqInit: RequestInit = {\n method: 'POST',\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'X-Visitor-UA': request.headers.get('user-agent') || '',\n },\n }\n const url = this.getApiUrl('project')\n\n const projectData: FetchProjectPayload =\n await this.fetchWithCache<FetchProjectPayload>(url, {\n ...reqInit,\n cacheTarget: 'project',\n strategy,\n })\n\n if (hasError(projectData)) {\n throw new Error(projectData.error)\n }\n\n // Extract what we can from the response using type guard\n // If validation fails, use fallback data instead of throwing\n let page: HydrogenPageData | undefined\n let project: WeaverseLoaderData['project'] | undefined\n let pageAssignment: WeaverseLoaderData['pageAssignment'] | undefined\n\n if (isFetchProjectPayload(projectData)) {\n // Valid response - extract normally\n page = projectData.page\n project = projectData.project\n pageAssignment = projectData.pageAssignment\n } else {\n console.warn(\n 'Invalid project data structure received from API, using fallback data',\n { projectId: effectiveProjectId }\n )\n // Try to extract what we can from the malformed response\n const responseData = projectData as any\n page = responseData?.page\n project = responseData?.project\n pageAssignment = responseData?.pageAssignment\n }\n\n if (!project) {\n console.warn('Weaverse project not found. Id:', effectiveProjectId)\n project = {\n id: effectiveProjectId,\n name: 'Weaverse project not found.',\n weaverseShopId: '',\n }\n }\n\n if (!page) {\n page = this.generateFallbackPage(\n '<div style=\"text-align: center;\">Please add new section to start.</div>'\n )\n }\n\n if (page?.items?.length === 0) {\n page.items.push({\n type: 'main',\n id: page.rootId || crypto.randomUUID(),\n data: {},\n })\n }\n\n if (page?.items) {\n const items = page.items\n page.items = await Promise.all(items.map(this.execComponentLoader))\n }\n return {\n page,\n project,\n pageAssignment,\n configs: {\n ...basePageConfigs,\n requestInfo: {\n i18n: storefront.i18n,\n queries: getRequestQueries<WeaverseStudioQueries>(request),\n pathname: this.parsedUrl.pathname,\n search: this.parsedUrl.search,\n },\n },\n }\n } catch (error) {\n const errorMessage = '❌ Page load failed'\n const errorContext: Record<string, unknown> = {\n projectId: params.projectId || this.configs.projectId,\n }\n\n if (error instanceof WeaverseError) {\n console.error(errorMessage, {\n code: error.code,\n message: error.message,\n ...errorContext,\n ...error.context,\n })\n } else if (error instanceof Error) {\n console.error(errorMessage, {\n message: error.message,\n stack: error.stack,\n ...errorContext,\n })\n } else {\n console.error(errorMessage, {\n error: String(error),\n ...errorContext,\n })\n }\n\n return null\n }\n }\n\n /** Executes the registered loader for one component and attaches its result. */\n execComponentLoader = async (item: HydrogenComponentData) => {\n const { data = {}, type, id } = item\n const component = this.componentsByType.get(type)\n const loader = component?.loader\n if (typeof loader === 'function' && component) {\n try {\n return {\n ...item,\n loaderData: await Promise.resolve(\n loader({\n data: { ...generateDataFromSchema(component.schema), ...data },\n weaverse: this,\n })\n ),\n }\n } catch (error) {\n console.warn('❌ Item loader run failed.', type, id, error)\n return item\n }\n }\n return item\n }\n}\n","/**\n * React and React Router integrations for rendering Weaverse content in\n * Shopify Hydrogen storefronts.\n *\n * @packageDocumentation\n */\n\nimport { getSelectedProductOptions as hydrogen_getSelectedProductOptions } from '@shopify/hydrogen'\nimport type { SelectedOptionInput } from '@shopify/hydrogen/storefront-api-types'\nimport {\n isBrowser,\n isIframe,\n useChildInstances,\n useItemInstance,\n useParentInstance,\n useWeaverse,\n} from '@weaverse/react'\n\n/**\n * Filter out Weaverse-specific query parameters from product options.\n * Removes `isDesignMode` and any parameters starting with `weaverse` prefix.\n *\n * @param request - The incoming HTTP request\n * @returns Filtered product options for Shopify Hydrogen\n *\n * @example\n * ```typescript\n * export async function loader({ request }: LoaderFunctionArgs) {\n * const selectedOptions = getSelectedProductOptions(request)\n * // Use selectedOptions for product queries without Weaverse params\n * }\n * ```\n */\nexport function getSelectedProductOptions(\n request: Request\n): SelectedOptionInput[] {\n let options = hydrogen_getSelectedProductOptions(request)\n return options.filter(\n ({ name }) => name !== 'isDesignMode' && !name.startsWith('weaverse')\n )\n}\n\n// Re-export all types and utilities from schema package\nexport * from '@weaverse/schema'\nexport * from './components'\nexport {\n getNestedKey,\n interpolate,\n // Deprecated aliases — kept for backward compatibility.\n ThemeTextProvider,\n type ThemeTextProviderProps,\n type ThemeTextValue,\n type TranslateFunction,\n // Canonical translation API.\n TranslationProvider,\n type TranslationProviderProps,\n type TranslationValue,\n useThemeText,\n useTranslation,\n} from './hooks/translation-context'\n// Export Hydrogen-specific hooks\nexport {\n createWeaverseDataContext,\n type RouteKeyedDataContext,\n useWeaverseDataContext,\n type WeaverseDataContext,\n} from './hooks/use-weaverse-data-context'\n// Export hydrogen-specific modules\nexport * from './seo'\nexport * from './types'\nexport * from './utils'\nexport type { WeaverseDataValue } from './utils/pick-weaverse-data'\nexport { ThemeTextStore, TranslationStore } from './utils/translation-store'\nexport type {\n ThemeSettingsStore,\n WeaverseThemeData,\n} from './utils/use-theme-settings-store'\nexport * from './WeaverseHydrogenRoot'\nexport * from './weaverse-client'\n// Re-export utilities from @weaverse/react\nexport {\n isBrowser,\n isIframe,\n useChildInstances,\n useItemInstance,\n useParentInstance,\n useWeaverse,\n}\n"]}
1
+ {"version":3,"file":"index.js","names":["MainComponent","mainSchema","isPlainObject","isBrowser","WeaverseItemStore","Weaverse","isBrowser","WeaverseRoot","ErrorBoundary","Suspense","Await"],"sources":["../src/components/main.tsx","../src/components/index.ts","../src/hooks/translation-context.tsx","../src/hooks/use-weaverse-data-context.ts","../src/seo.ts","../src/types.ts","../src/utils/studio-script-src.ts","../src/utils/index.ts","../src/utils/translation-store.ts","../src/utils/pick-weaverse-data.ts","../src/utils/studio-request-info.ts","../src/utils/is-same-loader-payload.ts","../src/utils/sync-reused-instance.ts","../src/utils/use-theme-settings-store.ts","../src/utils/use-studio.ts","../src/WeaverseHydrogenRoot.tsx","../src/utils/normalize-page-url.ts","../src/weaverse-client.ts","../src/index.ts"],"sourcesContent":["import { createSchema, type SchemaType } from '@weaverse/schema'\nimport type { HTMLAttributes } from 'react'\nimport type { HydrogenComponentProps } from '../types'\n\n/*\n Main is the default Weaverse component that is used to render the main content.\n This component wraps all the sections/components inside a Weaverse page.\n*/\nfunction Main(props: HydrogenComponentProps & HTMLAttributes<HTMLDivElement>) {\n let { children, dangerouslySetInnerHTML, ...rest } = props\n\n return (\n <div\n {...rest}\n // biome-ignore lint/correctness/noChildrenProp: <explanation>\n children={children}\n // biome-ignore lint/security/noDangerouslySetInnerHtmlWithChildren: <explanation>\n dangerouslySetInnerHTML={children ? undefined : dangerouslySetInnerHTML}\n />\n )\n}\n\nexport default Main\n\nexport let schema: SchemaType = createSchema({\n type: 'main',\n title: 'Main',\n})\n","import type { HydrogenComponent } from '../types'\nimport MainComponent, { schema as mainSchema } from './main'\n\n/** Built-in components required to render the root of every Weaverse page. */\nexport let defaultComponents: HydrogenComponent[] = [\n {\n default: MainComponent,\n schema: mainSchema,\n },\n]\n","import { useSafeExternalStore } from '@weaverse/react'\nimport { createContext, type ReactNode, useContext, useMemo } from 'react'\nimport type { TranslationStore } from '../utils/translation-store'\n\n/**\n * Traverse a nested object by dot-path.\n *\n * @example\n * getNestedKey({ cart: { title: 'Cart' } }, 'cart.title') // => 'Cart'\n * getNestedKey({}, 'cart.title', 'fallback') // => 'fallback'\n */\nexport function getNestedKey(\n obj: Record<string, unknown>,\n path: string,\n fallback?: string\n): string | undefined {\n const keys = path.split('.')\n let current: unknown = obj\n\n for (const key of keys) {\n if (current == null || typeof current !== 'object') {\n return fallback\n }\n current = (current as Record<string, unknown>)[key]\n }\n\n if (typeof current === 'string') {\n return current\n }\n\n return fallback\n}\n\n/**\n * Replace `{{variable}}` patterns in a string with provided values.\n *\n * @example\n * interpolate('Hello {{name}}!', { name: 'World' }) // => 'Hello World!'\n * interpolate('-{{percentage}}% Off', { percentage: 15 }) // => '-15% Off'\n */\nexport function interpolate(\n template: string,\n variables?: Record<string, string | number>\n): string {\n if (!variables) {\n return template\n }\n\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key: string) => {\n const value = variables[key]\n return value === undefined ? match : String(value)\n })\n}\n\n// ---------------------------------------------------------------------------\n// Context & Provider\n// ---------------------------------------------------------------------------\n\n/**\n * Signature for a translation function.\n */\nexport type TranslateFunction = (\n key: string,\n variables?: Record<string, string | number>\n) => string\n\n/** Translation function, stores, and locale overrides exposed by the provider. */\nexport type TranslationValue = {\n /**\n * Translate a key with optional variable interpolation.\n *\n * Priority chain (highest wins):\n * 1. External `t` (passed into `withWeaverse` / `TranslationProvider`)\n * 2. `merchantOverrides` (DB overrides for the current locale + design overrides)\n * 3. `staticContent` (theme default JSON)\n * 4. The key itself (fallback)\n *\n * @example\n * t('cart.title') // => \"Cart\"\n * t('badge.sale', { percentage: 15 }) // => \"-15% Off\"\n */\n t: TranslateFunction\n /** Exposed for useStudio to attach to weaverse.internal. Null in production. */\n translationStore: TranslationStore | null\n /**\n * @deprecated Use {@link TranslationValue.translationStore} instead. Kept as a\n * backward-compatible alias pointing at the same store instance.\n */\n themeTextStore: TranslationStore | null\n /** Active-locale translated keys loaded from the storefront API. */\n merchantOverrides: Record<string, unknown> | null\n}\n\nconst TranslationContext = createContext<TranslationValue | null>(null)\nTranslationContext.displayName = 'WeaverseTranslationContext'\n\n/** Inputs accepted by {@link TranslationProvider}. */\nexport type TranslationProviderProps = {\n /** Theme-provided default-locale translation content. */\n staticContent: Record<string, unknown>\n /** Active-locale translations published by the merchant. */\n merchantOverrides?: Record<string, unknown>\n /**\n * Optional external translation function.\n * When provided it becomes the **highest-priority** source:\n * if it returns a non-empty string that differs from the raw key,\n * that value is used; otherwise the internal resolution chain continues.\n */\n t?: TranslateFunction\n /** Optional store for live design-mode text overrides from the builder. */\n translationStore?: TranslationStore | null\n /**\n * @deprecated Use {@link TranslationProviderProps.translationStore} instead.\n * Still accepted for backward compatibility; ignored when `translationStore`\n * is also provided.\n */\n themeTextStore?: TranslationStore | null\n /** React content that can consume the translation context. */\n children: ReactNode\n}\n\n/**\n * Build the `t()` translation function over a fixed set of sources.\n *\n * Resolution order, highest priority first:\n * 1. `externalT` – host i18n (e.g. Shopify), unless it echoes the key\n * 2. `designOverrides` – live design-mode edits, flat dot-path keys\n * 3. `merchantOverrides` – locale overrides from the API, nested\n * 4. `staticContent` – the theme's default locale JSON\n * 5. the key itself\n *\n * Design overrides are looked up per-key (own properties only) rather than\n * merged into `merchantOverrides`: a flat key like `cart.title` must override\n * exactly that leaf without wiping sibling keys (`cart.subtitle`), and a\n * per-key own-property lookup never builds nested objects from\n * merchant-controlled keys, so it cannot pollute `Object.prototype`.\n */\nexport function createTranslate(sources: {\n staticContent: Record<string, unknown>\n merchantOverrides?: Record<string, unknown>\n designOverrides?: Record<string, string>\n externalT?: TranslateFunction\n}): TranslateFunction {\n const { staticContent, merchantOverrides, designOverrides, externalT } =\n sources\n return (key, variables) => {\n // Priority 1: external t (e.g. Shopify i18n, third-party library).\n if (externalT) {\n const external = externalT(key, variables)\n // Accept the external value unless it echoed the key unchanged.\n if (external && external !== key) {\n return external\n }\n }\n\n // Priority 2: live design-mode override (flat, keyed by exact dot-path,\n // own properties only so inherited keys never resolve to functions).\n const design =\n designOverrides && Object.hasOwn(designOverrides, key)\n ? designOverrides[key]\n : undefined\n // Priority 3: merchant overrides (nested). Priority 4: static content.\n const override = merchantOverrides\n ? getNestedKey(merchantOverrides, key)\n : undefined\n const staticValue = getNestedKey(staticContent, key)\n\n // Priority 5: the key itself as the final fallback.\n const raw = design ?? override ?? staticValue ?? key\n return interpolate(raw, variables)\n }\n}\n\n// No-op fallback for useSafeExternalStore when store is null (production).\n// Module-level constants — stable references, zero allocation per render.\nconst EMPTY: Record<string, string> = {}\nconst NOOP_SUBSCRIBE = () => () => {}\nconst NOOP_SNAPSHOT = () => EMPTY\n\n/**\n * Provider that wraps the app to expose the `t()` function.\n *\n * - `staticContent` – the theme's default locale JSON (from themeSchema.i18n)\n * - `merchantOverrides` – locale-specific overrides fetched from the API\n * - `translationStore` – optional store for live design-mode text overrides\n * (the deprecated `themeTextStore` prop is accepted as a fallback)\n */\nexport function TranslationProvider({\n staticContent,\n merchantOverrides,\n t: externalT,\n translationStore,\n themeTextStore,\n children,\n}: TranslationProviderProps) {\n // Canonical store, falling back to the deprecated `themeTextStore` prop.\n const store = translationStore ?? themeTextStore ?? null\n\n // Subscribe to design-mode overrides. No-op when store is null (production).\n const designOverrides = useSafeExternalStore(\n store?.subscribe ?? NOOP_SUBSCRIBE,\n store?.getSnapshot ?? NOOP_SNAPSHOT,\n store?.getServerSnapshot ?? NOOP_SNAPSHOT\n )\n\n const value = useMemo<TranslationValue>(\n () => ({\n t: createTranslate({\n staticContent,\n merchantOverrides,\n designOverrides,\n externalT,\n }),\n translationStore: store,\n // Deprecated alias — same instance, kept for backward compatibility.\n themeTextStore: store,\n merchantOverrides: merchantOverrides ?? null,\n }),\n [staticContent, merchantOverrides, designOverrides, externalT, store]\n )\n\n return (\n <TranslationContext.Provider value={value}>\n {children}\n </TranslationContext.Provider>\n )\n}\n\n/**\n * Hook to access the translation `t()` function.\n *\n * Must be used inside a component wrapped by `withWeaverse` or `TranslationProvider`.\n *\n * @example\n * ```tsx\n * function CartTitle() {\n * const { t } = useTranslation()\n * return <h2>{t('cart.title')}</h2>\n * }\n * ```\n */\nexport function useTranslation(): TranslationValue {\n const ctx = useContext(TranslationContext)\n if (!ctx) {\n throw new Error(\n 'useTranslation must be used within <TranslationProvider>. Wrap your app with withWeaverse().'\n )\n }\n return ctx\n}\n\n// ---------------------------------------------------------------------------\n// Deprecated aliases (backward compatibility — kept exported indefinitely)\n// ---------------------------------------------------------------------------\n\n/**\n * Legacy name for {@link TranslationProvider}.\n * @deprecated Use {@link TranslationProvider} instead.\n */\nexport const ThemeTextProvider = TranslationProvider\n/**\n * Legacy name for {@link useTranslation}.\n * @deprecated Use {@link useTranslation} instead.\n */\nexport const useThemeText = useTranslation\n/**\n * Legacy name for {@link TranslationValue}.\n * @deprecated Use {@link TranslationValue} instead.\n */\nexport type ThemeTextValue = TranslationValue\n/**\n * Legacy name for {@link TranslationProviderProps}.\n * @deprecated Use {@link TranslationProviderProps} instead.\n */\nexport type ThemeTextProviderProps = TranslationProviderProps\n","import { type UIMatch, useMatches } from 'react-router'\n\n/** Loader data indexed by React Router's conventional route identifiers. */\nexport interface RouteKeyedDataContext {\n /** Root route loader data, when the root loader returned an object. */\n root?: Record<string, unknown>\n /** Loader data for a non-root route keyed by its route identifier. */\n [routeKey: `routes/${string}`]: Record<string, unknown>\n}\n\n/**\n * Flat loader-data map keyed by React Router route ID.\n * Use route IDs such as `root` or `routes/products.$handle` in data bindings.\n */\nexport type WeaverseDataContext = RouteKeyedDataContext &\n Record<string, unknown>\n\n/**\n * Creates flat route-keyed structure from matches\n * Target: {root: {...rootData}, \"routes/product\": {...productData}}\n * Eliminates all duplication by using route IDs as keys\n */\nfunction createFlatDataContext(\n matches: UIMatch<unknown, unknown>[]\n): WeaverseDataContext {\n const context: WeaverseDataContext = {}\n\n // Process matches from root to leaf, creating route-keyed structure\n for (const match of matches) {\n if (match.data && typeof match.data === 'object') {\n // Use route ID as key (e.g., \"root\", \"routes/product\")\n context[match.id] = match.data\n }\n }\n\n return context\n}\n\n/**\n * Hook to get flat route-keyed data context from matches\n * Returns: {root: {...}, \"routes/xxx\": {...}}\n * No more useLoaderData dependency - everything comes from matches\n */\nexport function useWeaverseDataContext(): WeaverseDataContext {\n const matches = useMatches()\n\n // Create flat route-keyed structure - eliminates duplication\n return createFlatDataContext(matches)\n}\n\n/**\n * Helper function to create flat route-keyed data context from useMatches() result\n * Returns: {root: {...}, \"routes/xxx\": {...}}\n */\nexport function createWeaverseDataContext(\n matches: UIMatch<unknown, unknown>[]\n): WeaverseDataContext {\n // Create flat route-keyed structure - clean and efficient\n return createFlatDataContext(matches)\n}\n\n/**\n * Type guard to check if data is WeaverseDataContext (simplified)\n */\nexport function isWeaverseDataContext(\n data: unknown\n): data is WeaverseDataContext {\n return data !== null && typeof data === 'object'\n}\n","import type { PageSEOData } from '@weaverse/schema'\nimport type { MetaDescriptor } from 'react-router'\nimport type { HydrogenPageData, WeaverseLoaderData } from './types'\n\n/** Object containing an optional Weaverse page for SEO extraction. */\nexport interface WeaverseSeoPageContainer {\n /** Page whose published SEO fields should be formatted. */\n page?: HydrogenPageData | null\n}\n\n/** Input accepted by {@link getWeaverseSeoMeta}. */\nexport type WeaverseSeoInput =\n | WeaverseLoaderData\n | HydrogenPageData\n | WeaverseSeoPageContainer\n | null\n | undefined\n\n/**\n * Convert a Weaverse page-level SEO payload into React Router\n * `MetaDescriptor[]`. Pure, synchronous, tree-shakeable — does not fetch.\n *\n * Behavior:\n * - `title` → top-level `{ title }` descriptor.\n * - `description` / `keywords` → `<meta name=\"...\">`.\n * - `canonicalUrl` → `<link rel=\"canonical\">`.\n * - `openGraph.*` → `<meta property=\"og:*\">`. `og:type` defaults to\n * `'website'` when any other OG field is present.\n * - `twitter.*` → `<meta name=\"twitter:*\">`. `twitter:card` defaults to\n * `'summary'` when any other Twitter field is present.\n * - `robots` is always emitted (defaults to `'index,follow'`) so themes\n * stacking multiple SEO sources have a deterministic last word on\n * indexing for Weaverse-managed pages.\n * - Empty strings / missing fields are filtered before return so empty\n * descriptors don't override earlier sources (e.g. Hydrogen\n * `getSeoMeta`).\n */\nexport function formatMetaDescriptors(\n seo: PageSEOData | null | undefined\n): MetaDescriptor[] {\n if (!seo) {\n return [{ name: 'robots', content: 'index,follow' }]\n }\n\n let descriptors: MetaDescriptor[] = []\n\n if (seo.title) {\n descriptors.push({ title: seo.title })\n }\n if (seo.description) {\n descriptors.push({ name: 'description', content: seo.description })\n }\n if (seo.keywords) {\n descriptors.push({ name: 'keywords', content: seo.keywords })\n }\n if (seo.canonicalUrl) {\n descriptors.push({\n tagName: 'link',\n rel: 'canonical',\n href: seo.canonicalUrl,\n })\n }\n\n let og = seo.openGraph\n if (og && (og.title || og.description || og.image || og.type)) {\n if (og.title) {\n descriptors.push({ property: 'og:title', content: og.title })\n }\n if (og.description) {\n descriptors.push({ property: 'og:description', content: og.description })\n }\n if (og.image) {\n descriptors.push({ property: 'og:image', content: og.image })\n }\n descriptors.push({ property: 'og:type', content: og.type || 'website' })\n }\n\n let tw = seo.twitter\n if (tw && (tw.title || tw.description || tw.image || tw.cardType)) {\n descriptors.push({\n name: 'twitter:card',\n content: tw.cardType || 'summary',\n })\n if (tw.title) {\n descriptors.push({ name: 'twitter:title', content: tw.title })\n }\n if (tw.description) {\n descriptors.push({ name: 'twitter:description', content: tw.description })\n }\n if (tw.image) {\n descriptors.push({ name: 'twitter:image', content: tw.image })\n }\n }\n\n let index = seo.robots?.index !== false\n let follow = seo.robots?.follow !== false\n descriptors.push({\n name: 'robots',\n content: `${index ? 'index' : 'noindex'},${follow ? 'follow' : 'nofollow'}`,\n })\n\n return descriptors\n}\n\n/**\n * Convenience accessor: pull `page.seo` out of a `WeaverseLoaderData`\n * (or `HydrogenPageData`) and emit `MetaDescriptor[]`. Null-safe.\n *\n * @example\n * ```ts\n * export const meta: MetaFunction<typeof loader> = ({ data }) => {\n * return getWeaverseSeoMeta(data?.weaverseData)\n * }\n * ```\n */\nexport function getWeaverseSeoMeta(data: WeaverseSeoInput): MetaDescriptor[] {\n if (!data) {\n return formatMetaDescriptors(null)\n }\n let page =\n 'items' in data && 'id' in data\n ? (data as HydrogenPageData)\n : ((data as WeaverseSeoPageContainer).page ?? null)\n return formatMetaDescriptors(page?.seo ?? null)\n}\n","import type {\n CachingStrategy,\n HydrogenContext,\n I18nBase,\n} from '@shopify/hydrogen'\nimport type {\n AppLoadContext,\n LoaderFunctionArgs as RemixOxygenLoaderArgs,\n} from '@shopify/remix-oxygen'\nimport type {\n ElementData,\n PositionInputValue,\n WeaverseCoreParams,\n WeaverseElement,\n WeaverseImage,\n WeaverseProjectDataType,\n WeaverseResourcePickerData,\n WeaverseVideo,\n} from '@weaverse/react'\nimport type {\n // Enhanced type exports from schema package\n BasicInput,\n ComponentAvailabilityContext,\n ComponentGroup,\n HeadingInput,\n InputType,\n InspectorGroup,\n PageSEOData,\n PageType,\n Resolvable,\n ComponentPresets as SchemaComponentPresets,\n SchemaType,\n SchemaValidationIssue,\n SchemaValidationResult,\n ThemeRoutes,\n} from '@weaverse/schema'\nimport { isValidSchema } from '@weaverse/schema'\nimport type * as React from 'react'\nimport type { ForwardRefExoticComponent } from 'react'\nimport type { NavigateFunction } from 'react-router'\nimport type { TranslationStore } from './utils/translation-store'\nimport type { ThemeSettingsStore } from './utils/use-theme-settings-store'\nimport type { WeaverseHydrogen } from './WeaverseHydrogenRoot'\nimport type { WeaverseClient } from './weaverse-client'\n\n// Re-export CachingStrategy from Hydrogen for convenience\nexport type { CachingStrategy } from '@shopify/hydrogen'\n// Re-export types from schema for backward compatibility and convenience\nexport type {\n // Enhanced type exports\n BasicInput,\n ComponentAvailabilityContext,\n ComponentGroup,\n HeadingInput,\n InputType,\n InspectorGroup,\n PageType,\n PositionInputValue,\n Resolvable,\n SchemaValidationIssue,\n SchemaValidationResult,\n WeaverseImage,\n WeaverseVideo,\n}\n\n/** Arguments passed to a component's server-side loader. */\nexport type ComponentLoaderArgs<T = any, _E = any> = {\n /** Persisted component data merged with schema defaults. */\n data: T\n /** Request-scoped client available to the component loader. */\n weaverse: WeaverseClient\n}\n\n/** Application load context initialized with a request-scoped Weaverse client. */\nexport interface WeaverseRouteAppLoadContext extends AppLoadContext {\n /** Client used to load Weaverse content for the current request. */\n weaverse: WeaverseClient\n}\n\n/** React Router loader arguments whose app context includes the Weaverse client. */\nexport interface RouteLoaderArgs extends RemixOxygenLoaderArgs {\n /** Request-scoped application context with the initialized Weaverse client. */\n context: WeaverseRouteAppLoadContext\n}\n\n/** Primitive value accepted in a component's persisted data. */\nexport type ComponentDataValue = string | number | boolean | undefined | null\n\n/** Reference to a direct child component instance. */\nexport interface HydrogenChildComponentReference {\n /** Unique identifier of the child component instance. */\n id: string\n}\n\n/** Serialized component instance returned in a Weaverse page. */\nexport interface HydrogenComponentData extends ElementData {\n /** References to direct child component instances. */\n children?: HydrogenChildComponentReference[]\n /** ISO timestamp recording when the component instance was created. */\n createdAt?: string\n /** Persisted component setting values and structured payloads. */\n data?: Record<string, ComponentDataValue | Record<string, unknown>>\n /** ISO timestamp recording soft deletion, when applicable. */\n deletedAt?: string\n /** Unique component instance identifier. */\n id: string\n /** Registered component type used to select its renderer. */\n type: string\n /** ISO timestamp recording the latest component update. */\n updatedAt?: string\n}\n\n/**\n * Optimized: Use Zod-inferred SchemaType directly instead of extending\n * This ensures perfect type consistency with the schema validation\n */\nexport type HydrogenComponentSchema = SchemaType\n\n/** Props supplied by Weaverse when rendering a registered Hydrogen component. */\nexport interface HydrogenComponentProps<L = any> extends WeaverseElement {\n /** Rendered child component instances. */\n children?: React.JSX.Element[]\n /** Optional CSS class passed through by the renderer. */\n className?: string\n /** Result returned by the component's server-side loader. */\n loaderData?: L\n}\n\n/** Normalized request details attached to loader data for Studio navigation. */\nexport type WeaverseLoaderRequestInfo = {\n /** URL search string, including the leading question mark when present. */\n search: string\n /** Storefront request pathname. */\n pathname: string\n /** Parsed request query parameters. */\n queries: {\n /** Query parameter value keyed by parameter name. */\n [key: string]: string | boolean\n }\n /** Locale used to load the page. */\n i18n: WeaverseI18n\n}\n\n/** Published theme setting values keyed by schema setting name. */\nexport type HydrogenThemeSettings = {\n /** Published theme setting value keyed by schema setting name. */\n [key: string]: any\n}\n\n/** Project metadata returned with a Weaverse page payload. */\nexport type HydrogenProjectType = {\n /** Unique Weaverse project identifier. */\n id: string\n /** Identifier of the Shopify shop connected to the project. */\n weaverseShopId: string\n /** Human-readable project name. */\n name: string\n /** Additional project metadata returned by the content API. */\n [key: string]: any\n}\n\n/** Runtime services and project metadata exposed to Weaverse integrations. */\nexport type WeaverseInternal = {\n /** Route assignment for the rendered Weaverse page. */\n pageAssignment: HydrogenPageAssignment\n /** Metadata for the active Weaverse project. */\n project: HydrogenProjectType\n /** React Router navigation function, attached in design mode. */\n navigate: NavigateFunction\n /** Revalidates the active React Router data routes. */\n revalidate: () => void\n /** Mutable theme settings store used by Studio. */\n themeSettingsStore: ThemeSettingsStore\n /** Mutable translation store used by Studio, when translations are enabled. */\n translationStore?: TranslationStore | null\n /** @deprecated Use translationStore instead. */\n themeTextStore?: TranslationStore | null\n /** Active-locale merchant translation overrides. */\n merchantOverrides?: Record<string, unknown> | null\n}\n\n/**\n * Optimized: Use direct type alias to maintain consistency\n */\nexport type HydrogenComponentPresets = SchemaComponentPresets\n\n/** Registered runtime definition for a Hydrogen component type. */\nexport type HydrogenElement = {\n /** React renderer for this registered component type. */\n Component:\n | ForwardRefExoticComponent<HydrogenComponentProps>\n | ((props: HydrogenComponentProps) => React.JSX.Element)\n /** Unique component type matching the component schema. */\n type: string\n /** Component schema used for settings, defaults, and availability. */\n schema?: HydrogenComponentSchema\n /** Optional data loader function for server-side data fetching. */\n loader?: (args: ComponentLoaderArgs) => Promise<unknown>\n}\n\n/** Initialization parameters for a request-scoped {@link WeaverseHydrogen} runtime. */\nexport interface WeaverseHydrogenParams\n extends Omit<WeaverseCoreParams, 'ItemConstructor'> {\n /** Page content used to initialize component instances. */\n data: HydrogenPageData\n /** Route loader data made available to component data bindings. */\n dataContext?: Record<string, unknown> | null\n /** Runtime services and metadata available to integrations. */\n internal: Partial<WeaverseInternal>\n /** Whether the page is running inside the visual editor. */\n isDesignMode?: boolean\n /** Whether a component preview is being rendered. */\n isPreviewMode?: boolean\n /** Whether a saved page revision is being previewed. */\n isRevisionPreview?: boolean\n /** Identifier of the page being rendered. */\n pageId: string\n /** Identifier of the Weaverse project supplying content. */\n projectId: string\n /** Normalized URL and locale information for this request. */\n requestInfo: WeaverseLoaderRequestInfo\n /** Component type requested by section preview mode. */\n sectionType?: string\n /** Base URL used for public Weaverse API requests. */\n weaverseApiBase: string\n /**\n * API key read from environment/configuration for storefront requests or\n * supplied by Studio requests while editing and previewing.\n */\n weaverseApiKey: string\n /** Origin used for Weaverse Studio assets and editor communication. */\n weaverseHost: string\n /**\n * Public data API origin. Keep `weaverseHost` for Studio scripts/editor\n * assets; point this at the Cloudflare proxy (`https://api.weaverse.io`)\n * when edge caching is enabled.\n */\n weaversePublicApiBase?: string\n /** Optional Studio asset version used by preview integrations. */\n weaverseVersion?: string\n}\n\n/** Export shape for a renderable component, its schema, and optional loader. */\nexport type HydrogenComponent<T extends HydrogenComponentProps = any> = {\n /** React renderer exported by the component module. */\n default: ForwardRefExoticComponent<T> | ((props: T) => React.JSX.Element)\n /** Schema exported by the component module. */\n schema: HydrogenComponentSchema\n /** Optional data loader function for server-side data fetching. */\n loader?: (args: ComponentLoaderArgs) => Promise<unknown>\n}\n\n/** Weaverse Studio query parameters recognized by the Hydrogen runtime. */\nexport type WeaverseStudioQueries = {\n /** Project identifier selected by Studio for this request. */\n weaverseProjectId: string\n /** API key passed by Studio for design and preview requests. */\n weaverseApiKey: string\n /** Studio origin serving editor assets and APIs. */\n weaverseHost: string\n /** Studio asset version requested by the editor. */\n weaverseVersion: string\n /** Whether the request is for the visual editor. */\n isDesignMode: boolean\n /** Whether the request renders a component preview. */\n isPreviewMode?: boolean\n /** Component type requested for section preview. */\n sectionType?: string\n}\n\n/** Storefront-safe environment values exposed with theme settings. */\nexport type PublicEnv = {\n /** Public Shopify storefront domain. */\n PUBLIC_STORE_DOMAIN: string\n /** Public Storefront API access token. */\n PUBLIC_STOREFRONT_API_TOKEN: string\n}\n\n/** Resolved project, API endpoint, and rendering-mode configuration. */\nexport type WeaverseProjectConfigs = {\n /** Identifier of the Weaverse project supplying content. */\n projectId: string\n /** Origin used for Studio assets and editor communication. */\n weaverseHost: string\n /** Base URL used for public Weaverse content API requests. */\n weaverseApiBase: string\n /** Explicit public data API origin, when separately configured. */\n weaversePublicApiBase?: string\n /**\n * API key read from environment/configuration for storefront requests or\n * supplied by Studio requests while editing and previewing.\n */\n weaverseApiKey: string\n /** Optional Studio asset version. */\n weaverseVersion?: string\n /** Whether the request is running inside the visual editor. */\n isDesignMode?: boolean\n /** Whether the request renders a component preview. */\n isPreviewMode?: boolean\n /** Whether the request previews a saved page revision. */\n isRevisionPreview?: boolean\n /** Component type requested for section preview. */\n sectionType?: string\n /** Storefront-safe environment values exposed with theme settings. */\n publicEnv?: PublicEnv\n}\n\n/** Assignment describing which project page handles a storefront route. */\nexport type HydrogenPageAssignment = {\n /** Project identifier owning the assigned page. */\n projectId: string\n /** Storefront page type matched by the assignment. */\n type: PageType\n /** Route or resource handle matched by the assignment. */\n handle: string\n /** Locale matched by the assignment. */\n locale: string\n /** Inheritance details when the assignment comes from another project. */\n meta?: {\n /** Whether the assignment was inherited. */\n inherited: boolean\n /** Project identifier where the assignment originated. */\n sourceProjectId: string\n /** Number of inheritance levels traversed. */\n depth: number\n }\n}\n\n/** Complete payload returned by {@link WeaverseClient.loadPage}. */\nexport type WeaverseLoaderData = {\n /** Resolved runtime configuration and normalized request details. */\n configs: Omit<WeaverseProjectConfigs, 'publicEnv'> & {\n /** Normalized URL and locale information for the request. */\n requestInfo: WeaverseLoaderRequestInfo\n }\n /** Published page content to render. */\n page: HydrogenPageData\n /** Metadata for the project supplying the page. */\n project: HydrogenProjectType\n /** Route assignment that selected the page, when available. */\n pageAssignment?: HydrogenPageAssignment\n}\n\n/** Published Weaverse page content consumed by the Hydrogen renderer. */\nexport interface HydrogenPageData extends WeaverseProjectDataType {\n /** Internal cache identifier attached by the content API when available. */\n __cacheId?: string\n /** Unique page identifier. */\n id: string\n /** Serialized component instances belonging to the page. */\n items: HydrogenComponentData[]\n /** Human-readable page name. */\n name: string\n /**\n * Page-level SEO metadata published by Weaverse Builder. `null` when\n * the page has no `PageSeo` row; absent on revision snapshots that\n * predate the SEO feature. Themes should treat both as \"no Weaverse\n * override\".\n */\n seo?: PageSEOData | null\n /** Additional page fields supplied by the content API. */\n [key: string]: any\n}\n\n/** Locale metadata used when requesting localized Weaverse content. */\nexport type WeaverseI18n = I18nBase & {\n /** Human-readable locale label displayed in Studio. */\n label?: string\n /** Locale path prefix used by the storefront router. */\n pathPrefix?: string\n /** Additional locale metadata supplied by the storefront. */\n [key: string]: any\n}\n\n/** Theme metadata, global settings, and localization configuration. */\nexport type HydrogenThemeSchema = {\n /** Theme identity, author, and support metadata. */\n info: {\n /** Human-readable theme name. */\n name: string\n /** Theme version displayed in Studio. */\n version: string\n /** Theme author name. */\n author: string\n /** URL of the theme author's profile image. */\n authorProfilePhoto: string\n /** URL of the theme documentation. */\n documentationUrl: string\n /** URL where merchants can request theme support. */\n supportUrl: string\n }\n /** @deprecated Use settings instead. */\n inspector?: InspectorGroup[]\n /**\n * Store-wide defaults for the Media Manager gallery. Mirrors\n * `MediaInputConfigs` in `@weaverse/schema`, which documents the fields.\n *\n * Deliberately a sibling of `settings` rather than an entry inside it:\n * `settings` renders as merchant-editable controls in Studio, and these\n * rules are meant to be fixed by the theme author. An individual `image` or\n * `video` input can still override them through its own `configs`.\n *\n * Note: duplicated instead of imported because this package pins the\n * published `@weaverse/schema`, which does not export the type yet. Replace\n * with the shared type once schema ships it.\n */\n media?: {\n /** Filename prefixes hidden from the Media Manager gallery. */\n excludeFilenamePrefixes?: string[]\n /** Hide files used in products. Matches usage, not origin. */\n excludeProductFiles?: boolean\n }\n /** Groups of global theme settings exposed in Studio. */\n settings?: InspectorGroup[]\n /**\n * URL patterns for the page types whose routes differ from the Shopify\n * convention, so Studio can navigate to them, e.g.\n * `{ COLLECTION: '/shop/:handle' }`. See `ThemeRoutes`.\n */\n routes?: ThemeRoutes\n /** Theme localization configuration. */\n i18n?: {\n /** Strategy used to encode the locale in storefront URLs. */\n urlStructure: 'url-path' | 'subdomain' | 'top-level-domain'\n /** Locale used when no localized route is selected. */\n defaultLocale: WeaverseI18n\n /** Locales enabled for the connected Shopify shop. */\n shopLocales: WeaverseI18n[]\n /** Default-locale static translation content. */\n staticContent?: Record<string, unknown>\n /** Enable the translation UI in the builder. */\n translation?: boolean\n }\n}\n\n/** Request body sent to the Weaverse project content endpoint. */\nexport type FetchProjectRequestBody = {\n /** Identifier of the project to load. */\n projectId: string\n /** Normalized storefront URL being resolved. */\n url: string\n /** Storefront locale for localized content. */\n i18n?: WeaverseI18n\n /** Optional route-specific page lookup parameters. */\n params?: {\n /** Storefront page type to load. */\n type?: PageType\n /** Locale override for this page lookup. */\n locale?: string\n /** Resource or custom-page handle to load. */\n handle?: string\n }\n /** Whether draft editor content should be returned. */\n isDesignMode?: boolean\n}\n\n/** Project content response before it is normalized into loader data. */\nexport type FetchProjectPayload = {\n /** Published or draft page content; absent when no page matches. */\n page?: HydrogenPageData\n /** Project metadata; absent in some error responses. */\n project?: HydrogenProjectType\n /** Assignment that selected the page, when one matched. */\n pageAssignment?: HydrogenPageAssignment\n /** API error message, when the request could not be fulfilled. */\n error?: string\n /** Additional fields returned by compatible API versions. */\n [key: string]: any\n}\n\n/**\n * Project identifier value - can be static string or dynamic function.\n *\n * **Static String**: Direct project ID reference\n * ```ts\n * 'project-abc-123'\n * ```\n *\n * **Synchronous Function**: Returns project ID based on request context\n * ```ts\n * () => {\n * const host = new URL(request.url).hostname\n * return PROJECT_MAP[host] || 'default-project'\n * }\n * ```\n *\n * **Asynchronous Function**: Async project resolution (must be awaited before passing)\n * ```ts\n * async () => {\n * return await database.getProjectId(userId)\n * }\n * ```\n */\nexport type ProjectIdValue = string | (() => string) | (() => Promise<string>)\n\n/**\n * Type guard for detecting function-based projectId.\n *\n * Used internally by WeaverseClient constructor to determine\n * if projectId needs evaluation or can be used directly.\n */\nexport function isProjectIdFunction(\n projectId: ProjectIdValue | undefined\n): projectId is (() => string) | (() => Promise<string>) {\n return typeof projectId === 'function'\n}\n\n/**\n * Extended WeaverseClient constructor arguments supporting multi-project architecture.\n *\n * @example Static project (existing pattern - backward compatible)\n * ```ts\n * const weaverse = new WeaverseClient({\n * ...hydrogenContext,\n * projectId: 'project-default-123'\n * })\n * ```\n *\n * @example Dynamic project selection (new capability)\n * ```ts\n * const weaverse = new WeaverseClient({\n * ...hydrogenContext,\n * projectId: () => {\n * const origin = new URL(request.url).origin\n * if (origin === 'https://mystore.se') return process.env.WEAVERSE_PROJECT_SWEDEN!\n * if (origin === 'https://mystore.fr') return process.env.WEAVERSE_PROJECT_FRANCE!\n * return process.env.WEAVERSE_PROJECT_ID!\n * }\n * })\n * ```\n *\n * **Priority Chain** (highest to lowest):\n * 1. URL query parameter: `?weaverseProjectId=...` (design mode, preview mode)\n * 2. Function result (if function provided)\n * 3. Explicit string value (if string provided)\n * 4. Environment variable: `WEAVERSE_PROJECT_ID` (Hydrogen env or process.env)\n * 5. Empty string (triggers validation error in methods)\n *\n * **Function Requirements**:\n * - Must return non-empty string\n * - Can access request via closure for routing decisions\n * - Evaluated once per WeaverseClient instance (request-scoped)\n * - Async functions must be awaited before passing to constructor\n * - Should handle edge cases (missing headers, invalid domains, etc.)\n *\n * **Request Context Access**:\n * Functions access request via closure from constructor arguments.\n */\nexport type WeaverseClientArgs = HydrogenContext & {\n /**\n * React components registered with Weaverse CMS.\n * Each component must have a schema defining its properties and settings.\n */\n components: HydrogenComponent[]\n\n /**\n * Theme schema defining global theme settings (colors, fonts, layouts).\n * Used to generate default theme configuration and validate theme data.\n */\n themeSchema: HydrogenThemeSchema\n\n /**\n * Incoming HTTP request object from React Router loader.\n * Provides access to URL, headers, cookies for dynamic routing decisions.\n */\n request: Request\n\n /**\n * Hydrogen cache instance for content caching.\n *Supports multi-tenant caching with project-specific cache keys.\n */\n cache: Cache\n\n /**\n * Project identifier for loading content from Weaverse CMS.\n *\n * **Value Types**:\n * - Static string: 'project-123' (existing usage)\n * - Synchronous function: () => determineProject(request)\n * - Asynchronous function: async () => await getProject(request) (must be awaited)\n *\n * **Backward Compatibility**:\n * - Optional parameter (defaults to environment variable)\n * - Existing code without projectId continues to work unchanged\n *\n * **Cache Isolation**:\n * ProjectId is included in cache keys to prevent cross-project content pollution.\n * Each project's content is cached separately, ensuring multi-tenant isolation.\n */\n projectId?: ProjectIdValue\n\n /**\n * Fetch timeout in milliseconds for API requests.\n * Defaults to 10000ms (10 seconds) if not specified.\n * Useful for adjusting based on network conditions or deployment environment.\n *\n * @default 10000\n * @example\n * ```typescript\n * new WeaverseClient({\n * // ... other args\n * fetchTimeoutMs: 5000 // 5 second timeout\n * })\n * ```\n */\n fetchTimeoutMs?: number\n\n /**\n * Reject `loadPage()` with a {@link WeaverseLoadError} when the page cannot\n * be loaded, instead of resolving to `null`.\n *\n * With the default (`false`), an unavailable API, an invalid response and a\n * configuration failure all resolve to `null`, the same value a missing\n * project produces, so a route cannot tell an outage from a 404. Enable this\n * to answer failures with a retryable or configuration error response while\n * genuine absence keeps resolving to `null` or a fallback page.\n *\n * @default false\n */\n throwPageLoadFailures?: boolean\n}\n\n/** Product selected through a Weaverse resource-picker setting. */\nexport type WeaverseProduct = WeaverseResourcePickerData\n/** Collection selected through a Weaverse resource-picker setting. */\nexport type WeaverseCollection = WeaverseResourcePickerData\n/** Blog selected through a Weaverse resource-picker setting. */\nexport type WeaverseBlog = WeaverseResourcePickerData\n/** Article selected through a Weaverse resource-picker setting. */\nexport type WeaverseArticle = WeaverseResourcePickerData\n/** Metaobject selected through a Weaverse resource-picker setting. */\nexport type WeaverseMetaObject = WeaverseResourcePickerData\n\n/** Response returned by Hydrogen's cached fetch helper. */\nexport type WithCacheFetchResponse<T> = {\n /** Parsed response payload. */\n data: T\n /** Underlying Fetch API response. */\n response: Response\n}\n\n/** Theme configuration returned by the Weaverse project API. */\nexport type ThemeSettingsResponse = {\n /** Published theme setting values. */\n theme?: HydrogenThemeSettings\n /** Theme schema included for Studio editing. */\n schema?: HydrogenThemeSchema\n /** Storefront-safe environment values included in design mode. */\n publicEnv?: PublicEnv\n /** Theme's default locale JSON from `themeSchema.i18n.staticContent`. */\n staticContent?: Record<string, unknown>\n /** Locale-specific merchant overrides from the API. */\n merchantOverrides?: Record<string, unknown>\n /** Diagnostic message when loading fell back to schema defaults. */\n _error?: string\n /** Whether remote theme settings failed to load. */\n _loadFailed?: boolean\n}\n\n/**\n * Legacy data-or-error response shape retained for compatibility.\n *\n * The client's current direct-fetch implementation uses\n * {@link WithCacheFetchResponse} internally instead of returning this shape.\n */\nexport type DirectFetchResponse<T = unknown> = {\n /** Parsed payload when the legacy request succeeded. */\n data?: T\n /** Error message when the legacy request failed. */\n error?: string\n}\n\n/** Predicate used to decide whether a fetched response may be cached. */\nexport type CacheResponseValidator<T = unknown> = (\n response: WithCacheFetchResponse<T> | T\n) => boolean\n\n/** Error raised by Weaverse requests with a stable code and optional context. */\nexport class WeaverseError extends Error {\n /** Machine-readable error code. */\n public readonly code: string\n /** HTTP status associated with the failure, when available. */\n public readonly statusCode?: number\n /** Structured diagnostic details for logging and error handling. */\n public readonly context?: Record<string, unknown>\n\n /** Creates a Weaverse request error with a stable code and diagnostics. */\n constructor(\n message: string,\n code = 'WEAVERSE_ERROR',\n statusCode?: number,\n context?: Record<string, unknown>\n ) {\n super(message)\n this.name = 'WeaverseError'\n this.code = code\n this.statusCode = statusCode\n this.context = context\n\n // Maintains proper stack trace for where our error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, WeaverseError)\n }\n }\n}\n\n/**\n * Why a Weaverse page could not be loaded, as distinct from the page being\n * genuinely absent.\n *\n * - `unavailable`: the Weaverse API timed out, could not be reached, or\n * answered with a transient status (408, 425, 429 or 5xx) after the built-in\n * retry. Retrying later can succeed.\n * - `invalid-response`: the API answered successfully with a body that is not\n * a page/project envelope.\n * - `configuration`: the request was refused or could not be built (missing or\n * invalid project ID, 400/401/403 from the API). Retrying will not help.\n */\nexport type WeaverseLoadFailureKind =\n | 'unavailable'\n | 'invalid-response'\n | 'configuration'\n\n/**\n * Error thrown by {@link WeaverseClient.loadPage} when the client is created\n * with `throwPageLoadFailures: true` and the page cannot be loaded.\n *\n * Genuine absence is not an error: a missing project still resolves to `null`\n * and an unassigned page still resolves to a fallback page.\n */\nexport class WeaverseLoadError extends WeaverseError {\n /** Failure class used to choose a response status or recovery action. */\n public readonly kind: WeaverseLoadFailureKind\n\n /** Creates a classified page-load failure. */\n constructor(\n message: string,\n kind: WeaverseLoadFailureKind,\n statusCode?: number,\n context?: Record<string, unknown>\n ) {\n super(message, 'LOAD_FAILURE', statusCode, context)\n this.name = 'WeaverseLoadError'\n this.kind = kind\n }\n}\n\n/**\n * Validation result type for project ID validation.\n * Returns validation status with optional error message.\n */\nexport type ProjectIdValidationResult = {\n /** Whether the project identifier passed validation. */\n valid: boolean\n /** Validation error message when `valid` is false. */\n error?: string\n}\n\n/** Published custom page entry suitable for sitemap generation. */\nexport interface CustomPageEntry {\n /** Suggested sitemap update frequency. */\n changeFrequency?: 'daily' | 'weekly' | 'monthly'\n /** Weaverse custom page handle. */\n handle: string\n /** ISO timestamp of the latest published update. */\n lastModified: string\n /** Locale code, or `null` for the project's default locale. */\n locale: string | null\n /** Storefront path for the custom page. */\n path: string\n /** Optional sitemap priority from zero to one. */\n priority?: number\n}\n\n/**\n * Type guards for response validation\n */\n\nexport function isWithCacheFetchResponse<T>(\n response: unknown\n): response is WithCacheFetchResponse<T> {\n return (\n typeof response === 'object' &&\n response !== null &&\n 'data' in response &&\n 'response' in response\n )\n}\n\n/** Checks whether a value contains the required project response fields. */\nexport function isFetchProjectPayload(\n payload: unknown\n): payload is FetchProjectPayload {\n return (\n typeof payload === 'object' &&\n payload !== null &&\n 'page' in payload &&\n 'project' in payload &&\n 'pageAssignment' in payload\n )\n}\n\n/** Response containing an error message returned by a Weaverse request. */\nexport interface WeaverseErrorResponse {\n /** Human-readable request failure message. */\n error: string\n}\n\n/** Checks whether a response contains a string error message. */\nexport function hasError(response: unknown): response is WeaverseErrorResponse {\n return (\n typeof response === 'object' &&\n response !== null &&\n 'error' in response &&\n typeof (response as Record<string, unknown>).error === 'string'\n )\n}\n\n/** Checks whether a value contains a theme settings object. */\nexport function isThemeSettingsResponse(\n data: unknown\n): data is ThemeSettingsResponse {\n if (typeof data !== 'object' || data === null) {\n return false\n }\n\n const record = data as Record<string, unknown>\n return (\n 'theme' in record &&\n typeof record.theme === 'object' &&\n record.theme !== null\n )\n}\n\n/**\n * Enhanced type utilities for better development experience\n */\nexport type HydrogenSchemaValidationResult =\n SchemaValidationResult<HydrogenComponentSchema>\n\n/**\n * Type guard to check if a schema is valid.\n * Leverages validation from @weaverse/schema package which provides\n * comprehensive Zod-based validation with the ElementSchema.\n *\n * @param schema - Unknown value to validate\n * @returns True if schema is a valid HydrogenComponentSchema\n *\n * @example\n * ```typescript\n * if (isValidHydrogenSchema(userInput)) {\n * // userInput is now typed as HydrogenComponentSchema\n * console.log(userInput.type)\n * }\n * ```\n */\nexport function isValidHydrogenSchema(\n schema: unknown\n): schema is HydrogenComponentSchema {\n // Use the comprehensive validation from @weaverse/schema package\n return isValidSchema(schema)\n}\n\n/** Type-safe component schema authoring options. */\nexport type CreateHydrogenSchemaOptions = {\n /** Human-readable component title displayed in Studio. */\n title: string\n /** Unique component type used for registration and persisted items. */\n type: string\n /** Maximum number of instances allowed in the containing scope. */\n limit?: number\n /** Inspector groups defining editable component settings. */\n settings?: InspectorGroup[]\n /** Component types allowed as direct children. */\n childTypes?: string[]\n /**\n * Legacy page and placement availability restrictions.\n *\n * @deprecated Use `enabled` instead. Convert the arrays to checks in an\n * `enabled` resolver, for example:\n * `enabled: ({page, group}) => pages.includes(page.type) &&\n * (groups.includes('*') || groups.includes(group))`.\n */\n enabledOn?: {\n /** Page types where the component can be inserted. */\n pages?: PageType[]\n /** Placement groups where the component can be inserted; `*` allows all. */\n groups?: ('*' | 'header' | 'footer' | 'body')[]\n }\n /** Static or context-aware component availability rule. */\n enabled?: Resolvable<boolean, ComponentAvailabilityContext>\n /** Default component data and optional nested component presets. */\n presets?: {\n /** Components inserted as children by the preset. */\n children?: SchemaComponentPresets[]\n /** Additional default setting value keyed by setting name. */\n [key: string]: any\n }\n}\n\n// Extended window interface for hydrogen-specific globals\ndeclare global {\n interface Window {\n __weaverse?: WeaverseHydrogen\n __weaverses?: Record<string, WeaverseHydrogen>\n __weaverseThemeSettingsStore?: ThemeSettingsStore\n }\n}\n\n/** Browser bridge exposed by Weaverse Studio in design and preview modes. */\nexport interface WeaverseStudio {\n /** Connects Studio to a newly created Hydrogen runtime. */\n init: (weaverse: WeaverseHydrogen) => void\n /** Refreshes Studio after the active runtime configuration changes. */\n refreshStudio: (params: WeaverseHydrogenParams) => void\n}\n\n/** Browser window after the Weaverse Studio bridge has initialized. */\nexport interface WeaverseStudioWindow extends Window {\n /** Studio bridge used to initialize and refresh the Hydrogen runtime. */\n weaverseStudio: WeaverseStudio\n}\n\n/** Checks whether the browser window exposes the Weaverse Studio bridge. */\nexport function hasWeaverseStudio(\n window: Window\n): window is WeaverseStudioWindow {\n return 'weaverseStudio' in window && typeof window.weaverseStudio === 'object'\n}\n\ndeclare module '@shopify/remix-oxygen' {\n interface AppLoadContext {\n weaverse: WeaverseClient\n }\n}\n\ndeclare module '@shopify/hydrogen' {\n interface HydrogenEnv {\n CUSTOM_COLLECTION_BANNER_METAFIELD: string\n JUDGEME_PRIVATE_API_TOKEN: string\n KLAVIYO_PRIVATE_API_TOKEN: string\n METAOBJECT_COLOR_NAME_KEY: string\n METAOBJECT_COLOR_VALUE_KEY: string\n METAOBJECT_COLORS_TYPE: string\n PUBLIC_GOOGLE_GTM_ID: string\n PUBLIC_SHOPIFY_INBOX_SHOP_ID: string\n PUBLIC_STORE_DOMAIN: string\n PUBLIC_STOREFRONT_API_TOKEN: string\n WEAVERSE_API_KEY: string\n WEAVERSE_HOST?: string\n WEAVERSE_PROJECT_ID: string\n WEAVERSE_PUBLIC_API_BASE?: string\n }\n}\n\n/**\n * Parameters for loadPage method supporting route-level project override.\n *\n * @example Basic usage (uses client-level project)\n * ```ts\n * const weaverseData = await weaverse.loadPage({\n * type: 'PRODUCT',\n * handle: params.productHandle\n * })\n * ```\n *\n * @example Route-level project override\n * ```ts\n * export async function loader({ params, context }: LoaderFunctionArgs) {\n * const { weaverse } = context\n *\n * // Use special campaign project for this route only\n * const weaverseData = await weaverse.loadPage({\n * type: 'PRODUCT',\n * handle: params.productHandle,\n * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN // Override\n * })\n *\n * return { weaverseData }\n * }\n * ```\n */\nexport type LoadPageParams = {\n /**\n * Page type to load from Weaverse CMS.\n *\n * Determines which template to use for rendering the page.\n * Falls back to 'INDEX' if not specified or if page type doesn't exist.\n *\n * @default 'INDEX'\n */\n type?: PageType\n\n /**\n * Locale for internationalization.\n *\n * Format: IETF BCP 47 language tag (e.g., 'en-US', 'fr-FR', 'de-DE')\n * Used to load locale-specific content and translations.\n */\n locale?: string\n\n /**\n * Page handle for dynamic pages.\n *\n * Identifies specific resource within page type:\n * - Product handle: 'red-sneakers'\n * - Collection handle: 'summer-sale'\n * - Page handle: 'about-us'\n * - Article handle: 'how-to-style-sneakers'\n */\n handle?: string\n\n /**\n * Cache strategy override for this specific page load.\n *\n * Overrides default cache strategy for special use cases:\n * - Fresh content for checkout pages (no cache)\n * - Long-lived cache for static pages (1 hour+)\n * - Short-lived cache for frequently updated content (5 minutes)\n */\n strategy?: CachingStrategy\n\n /**\n * Optional project override for this specific page load.\n *\n * **Precedence**: Route-level projectId takes precedence over client-level projectId.\n *\n * **Use Cases**:\n * - Campaign landing pages with custom content\n * - VIP customer experiences with dedicated projects\n * - A/B testing specific pages without changing global config\n * - Seasonal promotions with limited-time content\n *\n * **Validation**:\n * - Must be non-empty string\n * - Validated before API call\n * - Falls back to client-level projectId if undefined\n * - Does NOT support function (string only)\n *\n * **Cache Isolation**:\n * Override projectId is included in cache key, ensuring separate caches\n * for different projects even on the same route.\n *\n * @example Campaign page override\n * ```ts\n * const campaignData = await weaverse.loadPage({\n * type: 'PAGE',\n * handle: 'summer-sale',\n * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN\n * })\n * ```\n */\n projectId?: string\n}\n\n// ─── Translation sidecar types (design mode) ─────────────────────────\n\n/** A single translated field for one item. */\nexport interface TranslationMapEntry {\n /** Source-locale value used to detect subsequent content changes. */\n originalValue: string\n /** Localized value rendered for the target locale. */\n translatedValue: string\n}\n\n/** Per-item translation fields, keyed by field name */\nexport type TranslationItemEntry = {\n /** Translation entry keyed by component field name. */\n [key: string]: TranslationMapEntry\n}\n\n/**\n * Translation map sent from the builder alongside page data in design mode.\n * Keyed by item ID, each value maps field names to translation entries.\n */\nexport type TranslationMap = {\n /** Translated fields keyed by component instance identifier. */\n [itemId: string]: TranslationItemEntry\n}\n\n/** A single translation entry for save payloads. */\nexport interface TranslationEntry {\n /** Marks an existing translation for deletion. */\n deleted?: boolean\n /** Identifier of the component instance owning the field. */\n itemId: string\n /** Dot-path to the translated component field. */\n key: string\n /** Source-locale value used to detect content changes. */\n originalValue: string\n /** Localized value to persist. */\n translatedValue: string\n}\n\n/** Result of collecting translation changes for the save flow */\nexport type TranslationChanges = {\n /** Builder language identifier receiving the changes. */\n languageId: string\n /** Translation entries to create, update, or delete. */\n entries: TranslationEntry[]\n}\n","/** Rendering mode and host details used to select a Studio bridge script. */\nexport interface StudioMode {\n /** Whether the storefront is running inside the visual editor. */\n isDesignMode?: boolean\n /** Whether a component preview is being rendered. */\n isPreviewMode?: boolean\n /** Whether a saved page revision is being previewed. */\n isRevisionPreview?: boolean\n /** Trusted origin serving Studio bridge assets. */\n weaverseHost: string\n /** Studio asset version appended to the script URL. */\n weaverseVersion: string\n}\n\nconst DEFAULT_WEAVERSE_HOST = 'https://studio.weaverse.io'\n\n/**\n * Weaverse-controlled apex domains the Studio bridge may be served from\n * (matched on the host itself and any subdomain).\n */\nconst TRUSTED_STUDIO_DOMAINS = ['weaverse.io', 'weaverse.dev']\n\nfunction isLoopbackHostname(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname.endsWith('.localhost')\n )\n}\n\nexport interface TrustedStudioHostOptions {\n /**\n * Also trust loopback hosts (`localhost` / `127.0.0.1` / `*.localhost`) over\n * http or https.\n *\n * Only safe when the **storefront itself** is loopback (genuine local-builder\n * dev). A production https page can still load a loopback script — loopback is\n * a \"potentially trustworthy\" origin and is not blocked as mixed content — so\n * honoring a query-supplied loopback host on a public storefront would let a\n * crafted link run whatever a visitor's local service serves inside the\n * storefront origin. MUST stay off on the server, where it is an SSRF vector\n * for page/theme fetches.\n */\n allowLoopback?: boolean\n}\n\n/**\n * Whether `host` is an origin we trust to serve the Studio bridge script (or,\n * server-side, to resolve page/theme data).\n *\n * The bridge executes inside the storefront document and the host can drive\n * server-side fetches, so a host taken from an attacker-controllable source —\n * e.g. a crafted `?weaverseHost=` query — is both an XSS and an SSRF vector.\n * Callers MUST reject untrusted hosts before acting on them. Trusts\n * `weaverse.io`/`weaverse.dev` and their subdomains over https; loopback is\n * opt-in (see {@link TrustedStudioHostOptions.allowLoopback}).\n */\nexport function isTrustedStudioHost(\n host: string,\n options?: TrustedStudioHostOptions\n): boolean {\n let parsed: URL\n try {\n parsed = new URL(host)\n } catch {\n return false\n }\n let { hostname, protocol } = parsed\n // Loopback (opt-in) is the only place http is allowed — a local builder\n // serves the bridge over http and there is no cleartext-downgrade risk to a\n // private address. Every other trusted host must be https so server-side\n // page/theme fetches are never downgraded to cleartext.\n if (options?.allowLoopback && isLoopbackHostname(hostname)) {\n return protocol === 'http:' || protocol === 'https:'\n }\n if (protocol !== 'https:') {\n return false\n }\n return TRUSTED_STUDIO_DOMAINS.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`)\n )\n}\n\n/**\n * Build the Studio bridge script URL for the current mode, or `null` when the\n * storefront is not being previewed inside Weaverse Studio.\n *\n * This is the single gate that keeps the bridge off production storefronts:\n * a normal visitor's URL carries none of the design/preview markers, so the\n * result is `null` and no script is ever requested.\n *\n * Shared by the page-scoped `useStudio` (which also binds the page for\n * editing) and the root-level `useStudioConnect` (which only needs the script\n * to load so Studio's `checkWeaversePage()` handshake can answer on routes\n * with no Weaverse content).\n */\nexport function getStudioScriptSrc(mode: StudioMode): string | null {\n let {\n isDesignMode,\n isPreviewMode,\n isRevisionPreview,\n weaverseHost,\n weaverseVersion,\n } = mode\n let base = `${weaverseHost}/static/studio/hydrogen`\n let version = `?v=${weaverseVersion}`\n if (isRevisionPreview || isPreviewMode) {\n return `${base}/preview.js${version}`\n }\n if (isDesignMode) {\n return `${base}/index.js${version}`\n }\n return null\n}\n\n/**\n * Resolve the Studio bridge script URL from a URL query string — the markers\n * Studio attaches when it drives the preview iframe (`isDesignMode`,\n * `isPreviewMode`, `__revisionId`, `weaverseHost`, `weaverseVersion`) — or\n * `null` outside Studio.\n *\n * `storefrontHostname` is the document's own hostname: a loopback Studio host\n * is only honored when the storefront itself is loopback (genuine local-builder\n * dev), so a crafted public link can't load a script from a visitor's loopback\n * service into the storefront origin.\n *\n * The `weaverseHost` query is attacker-controllable, so a host that is not a\n * {@link isTrustedStudioHost trusted origin} resolves to `null` (no bridge) —\n * it is never silently replaced with production Studio, which would otherwise\n * inject the wrong bridge for self-hosted/staging deployments. Such deployments\n * (a non-`weaverse.io` `WEAVERSE_HOST`) therefore don't load the root bridge on\n * content-less routes; the page-scoped {@link getStudioScriptSrc} via\n * `useStudio` still uses the configured host on content routes.\n *\n * Pure (no DOM) so the root-level connect's production gate stays unit-testable\n * and needs no loader data.\n */\nexport function resolveStudioScriptSrc(\n search: string,\n storefrontHostname = ''\n): string | null {\n let params = new URLSearchParams(search)\n // Match the server's getRequestQueries(), which keeps the LAST value of a\n // duplicated key. Studio appends its own control params, so a pre-existing\n // (stale/untrusted) `weaverseHost` earlier in the URL must not win here, or\n // the root bridge would be skipped while the loader uses the later host.\n let last = (key: string) => params.getAll(key).at(-1)\n let host = last('weaverseHost')\n if (host) {\n let allowLoopback = isLoopbackHostname(storefrontHostname)\n if (!isTrustedStudioHost(host, { allowLoopback })) {\n return null\n }\n }\n return getStudioScriptSrc({\n isDesignMode: last('isDesignMode') === 'true',\n isPreviewMode: last('isPreviewMode') === 'true',\n isRevisionPreview: params.has('__revisionId'),\n weaverseHost: host || DEFAULT_WEAVERSE_HOST,\n weaverseVersion: last('weaverseVersion') || '',\n })\n}\n","import type { HydrogenEnv } from '@shopify/hydrogen'\nimport type {\n HydrogenComponent,\n HydrogenComponentSchema,\n HydrogenThemeSchema,\n WeaverseLoaderData,\n WeaverseProjectConfigs,\n WeaverseStudioQueries,\n} from '../types'\nimport { isTrustedStudioHost } from './studio-script-src'\n\n// Track warned types to avoid spam\nlet warnedTypes = new Set<string>()\n\nfunction logOnce(type: string, message: string) {\n if (!warnedTypes.has(type)) {\n console.warn(message)\n warnedTypes.add(type)\n }\n}\n\nfunction deepMergeArrays<T>(target: T[], source: T[]): T[] {\n return [...target, ...source]\n}\n\nfunction mergeInspectorSettings(\n settings: any[],\n inspector: any[],\n type: string\n): any[] {\n if (!inspector?.length) {\n return settings\n }\n if (!settings?.length) {\n return inspector\n }\n\n // Log collision notice\n console.info(\n `Schema \"${type}\": Both 'settings' and 'inspector' found. Using 'settings' with 'inspector' as fallback.`\n )\n\n return deepMergeArrays(settings, inspector)\n}\n\n/** Options for extracting query parameters from a request URL. */\nexport interface RequestQueryOptions {\n /** Query parameter names to include; all parameters are included when omitted. */\n allowedKeys?: string[]\n}\n\n/**\n * Extract and parse query parameters from a request URL.\n * Supports optional allowlist for security-sensitive applications.\n *\n * @param request - The incoming request\n * @param options - Optional configuration\n * @param options.allowedKeys - If provided, only these keys will be extracted\n * @returns Parsed query parameters with type coercion for booleans\n *\n * @example\n * ```typescript\n * // Extract all params\n * const queries = getRequestQueries(request)\n *\n * // Extract only allowed params (security-sensitive)\n * const queries = getRequestQueries(request, {\n * allowedKeys: ['weaverseProjectId', 'weaverseHost']\n * })\n * ```\n */\nexport function getRequestQueries<T = Record<string, string | boolean>>(\n request: Request,\n options?: RequestQueryOptions\n): T {\n let url = new URL(request.url)\n let queries: Record<string, unknown> = {}\n\n for (let [key, value] of url.searchParams.entries()) {\n // If allowlist provided, skip non-allowed keys\n if (options?.allowedKeys && !options.allowedKeys.includes(key)) {\n continue\n }\n\n // Type-safe conversion for known boolean patterns\n if (value === 'true') {\n queries[key] = true\n } else if (value === 'false') {\n queries[key] = false\n } else {\n queries[key] = value\n }\n }\n\n return queries as T\n}\n\n/**\n * Resolves project, endpoint, and Studio mode configuration for a request.\n * URL-provided Studio values take precedence over environment defaults.\n */\nexport function getWeaverseConfigs(\n request: Request,\n env: HydrogenEnv\n): WeaverseProjectConfigs {\n let queries = getRequestQueries<WeaverseStudioQueries>(request)\n let {\n WEAVERSE_PROJECT_ID,\n WEAVERSE_API_KEY,\n WEAVERSE_HOST,\n WEAVERSE_PUBLIC_API_BASE,\n PUBLIC_STORE_DOMAIN,\n PUBLIC_STOREFRONT_API_TOKEN,\n } = env || {}\n let envFromProcess = (typeof process !== 'undefined' && process.env) || {}\n let {\n weaverseProjectId,\n weaverseHost,\n isDesignMode,\n isPreviewMode,\n sectionType,\n weaverseVersion,\n weaverseApiKey,\n } = queries\n\n let url = new URL(request.url)\n let isRevisionPreview = url.searchParams.has('__revisionId')\n let configuredWeaverseHost = WEAVERSE_HOST || envFromProcess.WEAVERSE_HOST\n // `weaverseHost` arrives from the request URL (Studio drives the preview\n // iframe with it), so it is attacker-controllable; only honor it when it is a\n // trusted Weaverse origin, otherwise fall back to the env/default host. This\n // stops a crafted `?weaverseHost=` from pointing Studio scripts or data reads\n // at an arbitrary origin.\n let trustedUrlHost =\n typeof weaverseHost === 'string' && isTrustedStudioHost(weaverseHost)\n ? weaverseHost\n : ''\n let resolvedWeaverseHost =\n trustedUrlHost || configuredWeaverseHost || 'https://studio.weaverse.io'\n // Public data reads default to the edge proxy, but an explicit custom\n // WEAVERSE_HOST (staging/self-hosted Weaverse) must stay the API base so\n // those deployments don't fetch page/config data from the production proxy.\n let resolvedWeaverseApiBase = trustedUrlHost\n ? trustedUrlHost\n : WEAVERSE_PUBLIC_API_BASE ||\n envFromProcess.WEAVERSE_PUBLIC_API_BASE ||\n (configuredWeaverseHost &&\n configuredWeaverseHost !== 'https://studio.weaverse.io'\n ? configuredWeaverseHost\n : 'https://api.weaverse.io')\n\n return {\n projectId:\n weaverseProjectId ||\n WEAVERSE_PROJECT_ID ||\n envFromProcess.WEAVERSE_PROJECT_ID ||\n '',\n weaverseHost: resolvedWeaverseHost,\n weaverseApiBase: resolvedWeaverseApiBase,\n weaversePublicApiBase: resolvedWeaverseApiBase,\n weaverseApiKey:\n weaverseApiKey ||\n WEAVERSE_API_KEY ||\n envFromProcess.WEAVERSE_API_KEY ||\n '',\n weaverseVersion: weaverseVersion || '',\n isDesignMode,\n isPreviewMode,\n isRevisionPreview,\n sectionType: sectionType || '',\n publicEnv: {\n PUBLIC_STORE_DOMAIN: PUBLIC_STORE_DOMAIN || '',\n PUBLIC_STOREFRONT_API_TOKEN: PUBLIC_STOREFRONT_API_TOKEN || '',\n },\n }\n}\n\n/**\n * Cache for generateDataFromSchema results using WeakMap.\n * WeakMap allows garbage collection when schema objects are no longer referenced.\n */\nconst schemaDefaultsCache = new WeakMap<\n HydrogenComponentSchema | HydrogenThemeSchema,\n Record<string, any>\n>()\n\n/**\n * Generate default data from component or theme schema.\n * Results are memoized using WeakMap for performance.\n *\n * @param schema - Component or theme schema\n * @returns Default data object extracted from schema inputs\n */\nexport function generateDataFromSchema(\n schema: HydrogenComponentSchema | HydrogenThemeSchema\n) {\n // Check cache first for performance\n const cached = schemaDefaultsCache.get(schema)\n if (cached) {\n return cached\n }\n\n let data: Record<string, any> = {}\n\n // Handle migration from inspector to settings\n let inspectorGroups: any[] = []\n\n // Type guard to check if it's a component schema\n const isComponentSchema = (\n s: HydrogenComponentSchema | HydrogenThemeSchema\n ): s is HydrogenComponentSchema => 'type' in s && typeof s.type === 'string'\n\n if (isComponentSchema(schema)) {\n // Handle HydrogenComponentSchema\n if (schema.settings) {\n inspectorGroups = schema.settings\n }\n\n if (schema.inspector) {\n if (schema.settings?.length) {\n // Both exist - merge with settings taking priority\n inspectorGroups = mergeInspectorSettings(\n schema.settings,\n schema.inspector,\n schema.type || 'unknown'\n )\n } else {\n // Only inspector exists - use it but warn about deprecation\n inspectorGroups = schema.inspector\n if (schema.type) {\n logOnce(\n schema.type,\n `⚠️ Schema \"${schema.type}\": The 'inspector' property is deprecated. Please use 'settings' instead.`\n )\n }\n }\n }\n } else {\n // Handle HydrogenThemeSchema\n if (schema.settings) {\n inspectorGroups = schema.settings\n }\n\n if (schema.inspector) {\n if (schema.settings?.length) {\n // Both exist - merge with settings taking priority\n inspectorGroups = mergeInspectorSettings(\n schema.settings,\n schema.inspector,\n 'Theme Schema'\n )\n } else {\n // Only inspector exists - use it but warn about deprecation\n inspectorGroups = schema.inspector\n logOnce(\n 'ThemeSchema',\n `⚠️ Theme Schema: The 'inspector' property is deprecated. Please use 'settings' instead.`\n )\n }\n }\n }\n\n if (inspectorGroups?.length) {\n for (let group of inspectorGroups) {\n for (let input of group.inputs) {\n let { name, defaultValue } = input\n if (name && defaultValue !== null && defaultValue !== undefined) {\n data[name] = defaultValue\n }\n }\n }\n }\n\n // Cache the result before returning\n schemaDefaultsCache.set(schema, data)\n\n return data\n}\n\nfunction recursivelyAddDataItem(\n type: string,\n components: HydrogenComponent<any>[],\n items: any[],\n initData?: object\n) {\n let component = components.find((c) => c.schema.type === type)\n if (!component) {\n return\n }\n let childIds = []\n let id = crypto.randomUUID()\n let { children, ...data } = component.schema?.presets || {}\n if (children) {\n for (let c of children) {\n let { type, children, ...data } = c\n let childId = recursivelyAddDataItem(type, components, items, data)\n childIds.push({ id: childId } as never)\n }\n }\n items.push({\n data: { ...data, ...initData },\n id,\n type,\n children: childIds,\n })\n return id\n}\n\n/** Creates synthetic loader data for previewing one registered component type. */\nexport function getPreviewData(\n type: string,\n components: HydrogenComponent[],\n weaverseHost: string\n) {\n let items = []\n return {\n project: { id: 'x', weaverseShopId: 'shop-id', name: 'Section Preview' },\n configs: {\n projectId: 'x',\n weaverseHost,\n isDesignMode: false,\n isPreviewMode: true,\n requestInfo: {\n i18n: {\n label: 'United States (USD $)',\n language: 'EN',\n country: 'US',\n currency: 'USD',\n pathPrefix: '',\n },\n queries: {},\n pathname: '/',\n search: '',\n },\n },\n page: {\n id: 'weaverse-preview-page',\n name: 'Preview section',\n rootId: '1',\n items: [\n {\n data: {},\n id: '1',\n type: 'main',\n children: [{ id: recursivelyAddDataItem(type, components, items) }],\n },\n ...items,\n ],\n },\n } as unknown as WeaverseLoaderData\n}\n","/**\n * Minimal mutable store for design-mode static text overrides.\n *\n * useSyncExternalStore-compatible. Passed into TranslationProvider which\n * subscribes internally and merges overrides into merchantOverrides.\n * The studio bridge calls updateOverrides() via weaverse.internal.translationStore\n * (also exposed as the deprecated weaverse.internal.themeTextStore alias).\n *\n * Shape: flat Record<string, string> — dot-notation keys map to values\n * (e.g. \"cart.title\" → \"Shopping Cart\").\n */\nexport class TranslationStore {\n /** Current flat translation overrides keyed by dot-path. */\n overrides: Record<string, string> = {}\n private listeners: Set<() => void> = new Set()\n\n /** Replaces all overrides and notifies subscribers. */\n setOverrides = (overrides: Record<string, string>) => {\n this.overrides = { ...overrides }\n this.emit()\n }\n\n /** Merges changed overrides and notifies subscribers. */\n updateOverrides = (newOverrides: Record<string, string>) => {\n this.overrides = { ...this.overrides, ...newOverrides }\n this.emit()\n }\n\n /** Returns the current client snapshot for `useSyncExternalStore`. */\n getSnapshot = () => this.overrides\n\n /** Returns the current server snapshot for `useSyncExternalStore`. */\n getServerSnapshot = () => this.overrides\n\n /** Subscribes to override changes and returns an unsubscribe callback. */\n subscribe = (callback: () => void) => {\n this.listeners.add(callback)\n return () => {\n this.listeners.delete(callback)\n }\n }\n\n private emit = () => {\n for (const listener of Array.from(this.listeners)) {\n try {\n listener()\n } catch (error) {\n console.error('TranslationStore: Listener error', error)\n }\n }\n }\n}\n\n/**\n * Legacy constructor alias retained for existing theme text integrations.\n * @deprecated Use {@link TranslationStore} instead. This alias remains available\n * for backward compatibility.\n */\nexport const ThemeTextStore = TranslationStore\n/**\n * Legacy type alias retained for existing theme text integrations.\n * @deprecated Use {@link TranslationStore} instead. This alias remains available\n * for backward compatibility.\n */\nexport type ThemeTextStore = TranslationStore\n","import type { UIMatch } from 'react-router'\nimport type { WeaverseLoaderData } from '../types'\n\n/**\n * Weaverse page data accepted by {@link WeaverseHydrogenRoot}, including\n * deferred React Router loader results and an explicit no-render value.\n */\nexport type WeaverseDataValue =\n | WeaverseLoaderData\n | Promise<WeaverseLoaderData>\n | null\n\n/**\n * Resolve the `weaverseData` payload for a `<WeaverseHydrogenRoot>` instance.\n *\n * Resolution order (first match wins):\n *\n * 1. **Explicit prop** — the caller passed `data` directly. Used as-is,\n * including when it is a `Promise` (handled upstream via `<Await>`) or\n * an explicit `null` (suppresses rendering).\n * 2. **Own route's loader data** — the loader data for the route that\n * rendered this component, obtained via `useLoaderData()`. This is\n * React Router's route-scoped primitive and is what makes nested\n * layout + child Weaverse pages work: each `<WeaverseContent />`\n * resolves to *its own* route's `weaverseData` regardless of siblings.\n * 3. **Ancestor match fallback** — walk `useMatches()` from leaf to root\n * and return the first ancestor whose `loaderData` exposes a\n * `weaverseData` key. This preserves the long-standing behaviour where\n * a child route with no loader (e.g. an `index.tsx` that omits\n * `weaverseData`) still renders its layout's Weaverse page.\n *\n * The helper is intentionally pure (no hook calls) so it can be unit-tested\n * without a React Router context. Hook calls happen in the component.\n *\n * ## Back-compat contract\n *\n * Themes that pre-date the `data` prop addition pass `dataProp === undefined`,\n * so resolution starts at Tier 2. For the canonical single-instance pattern\n * (one `<WeaverseContent />` inside a route whose loader returns\n * `{ weaverseData }`), Tier 2 returns the same value the old `useMatches()`\n * walk did. For the index-without-loader pattern (leaf route exposes no\n * `weaverseData`, layout does), Tier 3's leaf→root walk produces an\n * identical result to the pre-fix code. The only intentional behaviour\n * change is the issue #451 case: two `<WeaverseContent />` instances on the\n * same URL (layout + child, both with their own `weaverseData`) now each\n * render their own page instead of both rendering the deepest one.\n */\nexport function pickWeaverseData(\n dataProp: WeaverseDataValue | undefined,\n ownLoaderData: unknown,\n matches: ReadonlyArray<Pick<UIMatch, 'loaderData'>>\n): WeaverseDataValue {\n // Tier 1: explicit prop wins (including explicit `null`).\n if (dataProp !== undefined) {\n return dataProp\n }\n\n // Tier 2: own route's loader data — the route-scoped primitive.\n if (hasWeaverseData(ownLoaderData)) {\n return ownLoaderData.weaverseData as WeaverseDataValue\n }\n\n // Tier 3: ancestor walk (leaf → root) for legacy / index-without-loader cases.\n for (let i = matches.length - 1; i >= 0; i--) {\n const loaderData = matches[i].loaderData\n if (hasWeaverseData(loaderData)) {\n return loaderData.weaverseData as WeaverseDataValue\n }\n }\n\n return null\n}\n\nfunction hasWeaverseData(\n value: unknown\n): value is Record<string, unknown> & { weaverseData: unknown } {\n // The `in` check alone returns true for `{ weaverseData: undefined }`,\n // which would let Tier 2 short-circuit and return `undefined` — bypassing\n // the Tier 3 ancestor walk that would otherwise resolve the missing data.\n // Require the value to be present (not `undefined`).\n if (\n typeof value !== 'object' ||\n value === null ||\n !('weaverseData' in (value as Record<string, unknown>))\n ) {\n return false\n }\n return (value as Record<string, unknown>).weaverseData !== undefined\n}\n","import type { WeaverseHydrogenParams } from '../types'\n\ninterface BrowserLocationLike {\n pathname: string\n search: string\n}\n\nfunction getBrowserLocation(): BrowserLocationLike | undefined {\n if (typeof window === 'undefined') {\n return\n }\n return window.location\n}\n\nfunction getQueriesFromSearch(\n search: string\n): Record<string, string | boolean> {\n let queries: Record<string, string | boolean> = {}\n let params = new URLSearchParams(search)\n for (let [key, value] of params.entries()) {\n if (value === 'true') {\n queries[key] = true\n } else if (value === 'false') {\n queries[key] = false\n } else {\n queries[key] = value\n }\n }\n return queries\n}\n\n/**\n * React Router v7 single-fetch revalidation can render client data returned\n * from a `*.data` request while the browser is still on the canonical URL.\n * Instance identity must follow the browser URL, not the transient data\n * endpoint, otherwise the SDK creates a fresh Weaverse instance mid-session:\n * in design mode that drops the existing Studio bridge/interactions, and in\n * the live theme it resets every section's runtime state after any\n * revalidation (cart mutations, locale switches, `revalidate()`). See #451.\n */\nexport function normalizeRequestInfo(\n params: WeaverseHydrogenParams,\n browserLocation: BrowserLocationLike | undefined = getBrowserLocation()\n): WeaverseHydrogenParams {\n if (!browserLocation) {\n return params\n }\n\n let { pathname, search } = browserLocation\n if (\n params.requestInfo.pathname === pathname &&\n params.requestInfo.search === search\n ) {\n return params\n }\n\n return {\n ...params,\n requestInfo: {\n ...params.requestInfo,\n pathname,\n queries: getQueriesFromSearch(search),\n search,\n },\n }\n}\n","/**\n * Structural comparison used to detect whether a reused Weaverse instance\n * must adopt a fresh loader payload.\n *\n * `JSON.stringify` cannot do this job on the client:\n *\n * - Route loader data reaches `dataContext` unserialized, so deferred values\n * are still `Promise`s. React 19 development builds hang an enumerable,\n * self-referencing `_debugInfo` off those promises, and stringifying one\n * throws `TypeError: Converting circular structure to JSON` during render\n * (issue #511).\n * - In production every promise stringifies to `{}`, so a *fresh* deferred\n * value looks unchanged and the reused instance keeps serving the previous\n * render's promise. Tokenizing promises to a constant (`'[[promise]]'`) has\n * the same defect — it is stable by construction, therefore blind to\n * identity.\n *\n * Semantics, chosen deliberately:\n *\n * - **Promises/thenables are atomic**: compared by identity, never traversed.\n * A fresh promise is a change; the same promise is not. Debug metadata is\n * invisible to the comparison.\n * - **Opaque objects are atomic**: anything that is not a plain object, an\n * array, or `toJSON`-serializable (`Map`, `Set`, `URL`, `RegExp`, streams,\n * async iterators, cross-realm promises, class instances) is compared by\n * identity. `JSON.stringify` flattens all of them to `{}`, which would\n * silently collapse two distinct async values into \"unchanged\".\n * - **Cyclic graphs are compared coinductively**: a pair already being\n * compared is assumed equal, so equal self/mutual cycles are equal while a\n * differing leaf anywhere still reports a change. Nothing throws.\n * - **JSON-visible fields only**: `undefined`/function/symbol properties are\n * omitted from objects and read as `null` in arrays, and NaN/±Infinity read\n * as `null` — matching the previous `JSON.stringify` behavior for plain wire\n * payloads. Key order is irrelevant, which removes the old \"false mismatch\n * costs a re-render\" caveat.\n */\n\n/** `JSON.stringify` drops these from objects and nulls them inside arrays. */\nfunction isJsonOmitted(value: unknown): boolean {\n return (\n value === undefined ||\n typeof value === 'function' ||\n typeof value === 'symbol'\n )\n}\n\nfunction isObjectLike(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object'\n}\n\n/** Duck-typed so cross-realm promises and hand-rolled thenables also match. */\nfunction isThenable(value: Record<string, unknown>): boolean {\n return typeof value.then === 'function'\n}\n\nfunction isPlainObject(value: Record<string, unknown>): boolean {\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/** Returns the `toJSON()` projection, or the value itself when there is none. */\nfunction toJsonValue(value: Record<string, unknown>): unknown {\n return typeof value.toJSON === 'function'\n ? (value.toJSON as () => unknown)()\n : value\n}\n\n/** Maps NaN/±Infinity to `null`, matching how `JSON.stringify` renders them. */\nfunction toFiniteOrNull(value: unknown): unknown {\n return typeof value === 'number' && !Number.isFinite(value) ? null : value\n}\n\n/** Compares two loader payloads for JSON-visible structural equality. */\nexport function isSameLoaderPayload(left: unknown, right: unknown): boolean {\n // Pairs currently being compared, flattened as [a0, b0, a1, b1, ...].\n // Re-entering a pair means a cycle closed on both sides; assuming equality\n // there is what makes equal cyclic graphs compare equal (bisimulation)\n // while a differing leaf anywhere still reports a change.\n //\n // Scoped to the active path rather than every visited pair, so memory stays\n // proportional to graph depth (single digits for loader payloads) instead of\n // node count, and the common all-equal walk allocates one array.\n //\n // Tradeoff: a graph that shares one subtree through many nested parents\n // re-walks it per path. Wire-serialized loader payloads are trees, so this\n // does not arise; memoizing equal pairs instead measured ~2x slower on a\n // realistic 400-item page, which is the case that actually runs per render.\n const activePairs: object[] = []\n\n function isSame(rawA: unknown, rawB: unknown): boolean {\n if (Object.is(rawA, rawB)) {\n return true\n }\n // `JSON.stringify` renders NaN/±Infinity as `null`; normalizing here keeps\n // a non-finite number equal to the `null` a previous wire payload carried.\n const a = toFiniteOrNull(rawA)\n const b = toFiniteOrNull(rawB)\n if (a === b) {\n // Also accepts 0/-0, which `JSON.stringify` renders identically.\n return true\n }\n if (!(isObjectLike(a) && isObjectLike(b))) {\n return false\n }\n if (isThenable(a) || isThenable(b)) {\n // Identity comparison above already failed: distinct async values.\n return false\n }\n for (let index = 0; index < activePairs.length; index += 2) {\n if (activePairs[index] === a && activePairs[index + 1] === b) {\n return true\n }\n }\n\n activePairs.push(a, b)\n try {\n return isSameOpenPair(a, b)\n } finally {\n activePairs.length -= 2\n }\n }\n\n function isSameOpenPair(\n a: Record<string, unknown>,\n b: Record<string, unknown>\n ): boolean {\n const aJson = toJsonValue(a)\n const bJson = toJsonValue(b)\n if (aJson !== a || bJson !== b) {\n return isSame(aJson, bJson)\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return isSameArray(a, b)\n }\n if (!(isPlainObject(a) && isPlainObject(b))) {\n // Opaque object with no JSON projection — identity is the only honest\n // signal, and it already failed.\n return false\n }\n return isSameObject(a, b)\n }\n\n function isSameArray(a: unknown[], b: unknown[]): boolean {\n if (a.length !== b.length) {\n return false\n }\n for (let index = 0; index < a.length; index++) {\n const aItem = isJsonOmitted(a[index]) ? null : a[index]\n const bItem = isJsonOmitted(b[index]) ? null : b[index]\n if (!isSame(aItem, bItem)) {\n return false\n }\n }\n return true\n }\n\n function isSameObject(\n a: Record<string, unknown>,\n b: Record<string, unknown>\n ): boolean {\n let aKeyCount = 0\n for (const key of Object.keys(a)) {\n if (isJsonOmitted(a[key])) {\n continue\n }\n aKeyCount++\n // A JSON-visible value never compares equal to an omitted one, so a\n // missing/undefined counterpart falls out of `isSame` as a change.\n if (!isSame(a[key], b[key])) {\n return false\n }\n }\n let bKeyCount = 0\n for (const key of Object.keys(b)) {\n if (!isJsonOmitted(b[key])) {\n bKeyCount++\n }\n }\n return aKeyCount === bKeyCount\n }\n\n return isSame(left, right)\n}\n","import type { WeaverseHydrogenParams } from '../types'\nimport type { WeaverseHydrogen } from '../WeaverseHydrogenRoot'\nimport { isSameLoaderPayload } from './is-same-loader-payload'\n\n/**\n * Apply a fresh loader payload to a reused Weaverse instance.\n *\n * With requestInfo normalized to the browser URL, same-URL revalidations\n * (cart mutations, `useRevalidator()`, locale-neutral re-fetches) reuse the\n * cached `window.__weaverses[pageId]` instance instead of constructing a new\n * one — which preserves section state, but would silently drop the fresh\n * `data`/`dataContext` the loaders just returned. Sync them here.\n *\n * Design mode is excluded by the caller: Studio owns the instance data there\n * (unsaved drafts must not be clobbered) and applies updates via\n * `refreshStudio` instead.\n *\n * Change detection uses {@link isSameLoaderPayload}: a structural comparison\n * that treats promises/thenables and other opaque objects as atomic values\n * compared by identity, and tolerates cyclic graphs. `dataContext` carries\n * live route loader data — including unresolved deferred promises whose React\n * development metadata is cyclic — so it cannot be JSON-serialized here.\n */\nexport function syncReusedInstance(\n weaverse: WeaverseHydrogen,\n params: WeaverseHydrogenParams\n) {\n weaverse.requestInfo = params.requestInfo\n weaverse.internal = params.internal\n\n let dataChanged = !isSameLoaderPayload(weaverse.data, params.data)\n let contextChanged = !isSameLoaderPayload(\n weaverse.dataContext ?? null,\n params.dataContext ?? null\n )\n\n if (contextChanged) {\n // Assign before notifying any item store: components resolve data\n // connectors against `weaverse.dataContext` at render time, so the\n // fresh context must be in place when re-renders flush.\n weaverse.dataContext = params.dataContext ?? null\n }\n if (dataChanged) {\n // State-preserving: existing item stores receive `setData` (and emit),\n // missing ones are created — no full instance teardown.\n weaverse.setProjectData(params.data)\n } else if (contextChanged) {\n // Context-only change: memoized item components subscribe to their item\n // store snapshot, and snapshot identity follows the `_store` reference —\n // a bare `triggerUpdate()` would notify with an identical snapshot and\n // `useSyncExternalStore` would skip the re-render. `setData({})` swaps\n // the store reference so connectors re-resolve against the new context.\n for (const { id } of params.data?.items || []) {\n weaverse.itemInstances.get(id)?.setData({})\n }\n }\n if (dataChanged || contextChanged) {\n weaverse.triggerUpdate()\n }\n}\n","import { isBrowser } from '@weaverse/react'\nimport { createContext, useContext, useEffect, useRef } from 'react'\nimport { useRouteLoaderData } from 'react-router'\nimport type {\n HydrogenThemeSchema,\n HydrogenThemeSettings,\n PublicEnv,\n} from '../types'\n\n/** Root-loader theme data used to initialize a {@link ThemeSettingsStore}. */\nexport interface WeaverseThemeData {\n /** Storefront-safe environment values, when available. */\n publicEnv?: PublicEnv\n /** Theme schema exposed to Studio, when available. */\n schema?: HydrogenThemeSchema\n /** Published theme setting values. */\n theme: HydrogenThemeSettings\n}\n\n/** Mutable, subscribable store for theme settings received from the root loader. */\nexport class ThemeSettingsStore {\n /** Current merged theme setting values. */\n settings: HydrogenThemeSettings = {}\n /** Theme schema exposed to Studio, when available. */\n schema?: HydrogenThemeSchema\n /** Storefront-safe environment values, when available. */\n publicEnv?: PublicEnv\n private listeners: Set<() => void> = new Set()\n private hasWarnedListenerCount = false\n private isDestroyed = false\n\n /** Creates a theme settings store from root-loader theme data. */\n constructor(data: WeaverseThemeData) {\n const { theme, schema, publicEnv } = data || {}\n this.settings = { ...theme }\n this.schema = schema\n this.publicEnv = publicEnv\n if (isBrowser) {\n window.__weaverseThemeSettingsStore = this\n }\n }\n\n /** Merges setting changes into the current snapshot and notifies subscribers. */\n updateThemeSettings = (newSettings: HydrogenThemeSettings) => {\n if (this.isDestroyed) {\n console.warn('ThemeSettingsStore: Cannot update destroyed store')\n return\n }\n\n this.settings = {\n ...this.settings,\n ...newSettings,\n }\n this.emit()\n }\n\n /** Returns the current client snapshot for `useSyncExternalStore`. */\n getSnapshot = () => this.settings\n\n /** Returns the current server snapshot for `useSyncExternalStore`. */\n getServerSnapshot = () => this.settings\n\n /** Subscribes to setting changes and returns an unsubscribe callback. */\n subscribe = (callback: () => void) => {\n if (this.isDestroyed) {\n console.warn('ThemeSettingsStore: Cannot subscribe to destroyed store')\n return () => {}\n }\n\n this.listeners.add(callback)\n\n if (!this.hasWarnedListenerCount && this.listeners.size > 500) {\n this.hasWarnedListenerCount = true\n console.warn(\n `ThemeSettingsStore: ${this.listeners.size} listeners detected. ` +\n 'This may indicate a performance issue. Consider using fewer useThemeSettings() calls.'\n )\n }\n\n return () => {\n this.listeners.delete(callback)\n }\n }\n\n private emit = () => {\n if (this.isDestroyed) {\n return\n }\n\n const currentListeners = Array.from(this.listeners)\n\n for (const listener of currentListeners) {\n try {\n listener()\n } catch (error) {\n console.error('ThemeSettingsStore: Listener error', error)\n }\n }\n }\n\n /** Clears subscribers and detaches the browser-global store reference. */\n destroy = () => {\n if (this.isDestroyed) {\n return\n }\n\n this.listeners.clear()\n this.isDestroyed = true\n\n if (isBrowser && window.__weaverseThemeSettingsStore === this) {\n window.__weaverseThemeSettingsStore = undefined\n }\n }\n}\n\nexport const ThemeSettingsStoreContext =\n createContext<ThemeSettingsStore | null>(null)\nThemeSettingsStoreContext.displayName = 'ThemeSettingsStoreContext'\n\nexport function useCreateThemeSettingsStore(): ThemeSettingsStore {\n const data = useRouteLoaderData('root') as {\n weaverseTheme: WeaverseThemeData\n }\n const storeRef = useRef<ThemeSettingsStore | null>(null)\n\n if (!storeRef.current) {\n storeRef.current = new ThemeSettingsStore(data?.weaverseTheme)\n }\n\n const theme = data?.weaverseTheme?.theme\n useEffect(() => {\n if (storeRef.current && theme) {\n storeRef.current.updateThemeSettings(theme)\n }\n }, [theme])\n\n return storeRef.current\n}\n\nexport function useThemeSettingsStore(): ThemeSettingsStore {\n const fromContext = useContext(ThemeSettingsStoreContext)\n const data = useRouteLoaderData('root') as {\n weaverseTheme: WeaverseThemeData\n }\n const fallbackRef = useRef<ThemeSettingsStore | null>(null)\n\n if (!(fallbackRef.current || fromContext)) {\n fallbackRef.current = new ThemeSettingsStore(data?.weaverseTheme)\n }\n\n const store = fromContext ?? fallbackRef.current!\n const theme = data?.weaverseTheme?.theme\n useEffect(() => {\n if (!fromContext && theme) {\n store.updateThemeSettings(theme)\n }\n }, [fromContext, store, theme])\n\n return store\n}\n","import { loadScript } from '@weaverse/react'\nimport { useEffect } from 'react'\nimport {\n useLocation,\n useNavigate,\n useNavigation,\n useRevalidator,\n} from 'react-router'\nimport { useTranslation } from '../hooks/translation-context'\nimport type { WeaverseHydrogen } from '../index'\nimport { hasWeaverseStudio } from '../types'\nimport { getStudioScriptSrc, resolveStudioScriptSrc } from './studio-script-src'\nimport { useThemeSettingsStore } from './use-theme-settings-store'\n\nconst STUDIO_READY_POLL_MS = 50\nconst STUDIO_READY_TIMEOUT_MS = 5000\n\n/**\n * Resolve once `window.weaverseStudio` is available, or `null` on timeout.\n * The studio script sets the global when it *executes*; `loadScript` can\n * resolve earlier for tags it did not create (e.g. SSR-injected markup),\n * so never assume readiness right after the script promise settles.\n */\nfunction waitForStudio(): Promise<Window['weaverseStudio'] | null> {\n return new Promise((resolve) => {\n let startedAt = Date.now()\n function check() {\n if (hasWeaverseStudio(window)) {\n return resolve(window.weaverseStudio)\n }\n if (Date.now() - startedAt >= STUDIO_READY_TIMEOUT_MS) {\n console.warn('[Weaverse] Studio script did not initialize in time')\n return resolve(null)\n }\n setTimeout(check, STUDIO_READY_POLL_MS)\n }\n check()\n })\n}\n\n/**\n * Load the Studio bridge script on every design/preview render so Studio's\n * `checkWeaversePage()` handshake is answered instead of timing out — crucially\n * on routes where the page-scoped {@link useStudio} never mounts: 404s, error\n * boundaries, and non-Weaverse routes. The bridge registers its RPC endpoint\n * and `window.weaverseStudio` the moment the script executes, independent of any\n * page binding. Without this, a content-less route never loads the script and\n * Studio reports a false \"Connection lost\" instead of \"this page has no Weaverse\n * content set up\".\n *\n * `loadScript` is idempotent, so on content routes this coexists with the\n * page-scoped {@link useStudio} (same src) — that hook still binds the page via\n * `init`. Gating this on whether a route \"has Weaverse data\" is deliberately\n * avoided: route matches can't tell whether the page-scoped bridge actually\n * mounts (an `ErrorBoundary` replacing a data route, or data passed via the\n * `data` prop), and suppressing the script there would reintroduce the timeout\n * this fixes. Loading the script is harmless; it only registers the responder.\n *\n * Known limitation: on a route whose `weaverseData` is a deferred Promise, the\n * script can load before the page streams in, so `checkWeaversePage()` may\n * briefly observe `NOT_WEAVERSE_PAGE`. The complete fix is a \"loading\" state in\n * `checkWeaversePage` so the handshake retries rather than latching — that lives\n * in the Studio script, not here. Tracked in Weaverse/builder#2515.\n *\n * Mounted via {@link withWeaverse}, which must be the root route's `Layout`\n * export so the bridge renders even when a route's `ErrorBoundary` replaces the\n * page. Outside Studio (no design/preview params) it is a no-op.\n */\nexport function useStudioConnect() {\n let { search } = useLocation()\n useEffect(() => {\n // Loopback Studio hosts are only honored when the storefront itself is\n // loopback (see resolveStudioScriptSrc), so pass the document's hostname.\n let hostname = typeof window === 'undefined' ? '' : window.location.hostname\n let src = resolveStudioScriptSrc(search, hostname)\n if (src) {\n loadScript(src).catch(console.error)\n }\n }, [search])\n}\n\nexport function useStudio(weaverse: WeaverseHydrogen) {\n let { revalidate } = useRevalidator()\n let navigation = useNavigation()\n let { pathname, search } = useLocation()\n let navigate = useNavigate()\n let themeSettingsStore = useThemeSettingsStore()\n let { translationStore, themeTextStore, merchantOverrides } = useTranslation()\n let {\n isDesignMode,\n weaverseHost,\n weaverseVersion,\n isPreviewMode,\n isRevisionPreview,\n } = weaverse\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: only revalidate on pathname/search changes\n useEffect(() => {\n if (navigation.state !== 'idle') {\n return\n }\n let src = getStudioScriptSrc({\n isDesignMode,\n isPreviewMode,\n isRevisionPreview,\n weaverseHost,\n weaverseVersion,\n })\n if (!src) {\n return\n }\n if (isRevisionPreview || isPreviewMode) {\n loadScript(src).catch(console.error)\n } else {\n weaverse.internal = {\n ...weaverse.internal,\n navigate,\n revalidate,\n merchantOverrides,\n themeSettingsStore,\n translationStore,\n // Deprecated alias for existing Studio bridge integrations.\n themeTextStore,\n }\n loadScript(src)\n .then(waitForStudio)\n .then((studio) => studio?.init(weaverse))\n .catch(console.error)\n }\n }, [pathname, search, navigation.state])\n}\n","import type { ElementData } from '@weaverse/react'\nimport {\n isBrowser,\n useSafeExternalStore,\n Weaverse,\n WeaverseItemStore,\n WeaverseRoot,\n} from '@weaverse/react'\nimport {\n type ComponentType,\n type JSX,\n memo,\n Suspense,\n useMemo,\n useRef,\n} from 'react'\nimport { ErrorBoundary } from 'react-error-boundary'\nimport {\n Await,\n useLoaderData,\n useMatches,\n useRouteLoaderData,\n} from 'react-router'\nimport { defaultComponents } from './components'\nimport {\n type TranslateFunction,\n TranslationProvider,\n} from './hooks/translation-context'\nimport { createWeaverseDataContext } from './hooks/use-weaverse-data-context'\nimport type {\n HydrogenComponentData,\n HydrogenElement,\n HydrogenPageData,\n HydrogenThemeSettings,\n TranslationChanges,\n TranslationEntry,\n TranslationItemEntry,\n TranslationMap,\n WeaverseInternal,\n WeaverseLoaderRequestInfo,\n} from './index'\nimport type {\n HydrogenComponent,\n WeaverseHydrogenParams,\n WeaverseLoaderData,\n} from './types'\nimport { hasWeaverseStudio } from './types'\nimport { generateDataFromSchema } from './utils'\nimport {\n pickWeaverseData,\n type WeaverseDataValue,\n} from './utils/pick-weaverse-data'\nimport { normalizeRequestInfo } from './utils/studio-request-info'\nimport { syncReusedInstance } from './utils/sync-reused-instance'\nimport { TranslationStore } from './utils/translation-store'\nimport { useStudio, useStudioConnect } from './utils/use-studio'\nimport {\n ThemeSettingsStoreContext,\n useCreateThemeSettingsStore,\n useThemeSettingsStore,\n} from './utils/use-theme-settings-store'\n\n/*\n=== IMPORTANT DESIGN PRINCIPLE ===\nCONSTRUCTOR TIMING AND DEFERRED PROCESSING\n\nWhen working with React component systems and registries:\n- Keep constructors SIMPLE - don't do heavy work in them\n- Defer processing until RENDER TIME, not initialization\n- Avoid registry lookups during object construction (components may not be registered yet)\n- Simple code is more reliable than complex upfront optimization\n- Respect the initialization sequence: registration → instance creation → rendering\n\nHistory: Attempting to do schema processing in the constructor (commit 495e1220) broke\nthe pilot template because it tried to access the component registry before components were registered.\nThe fix was to defer that work until the component is actually rendered.\n====================================\n*/\n\n/** Runtime store for one rendered Hydrogen component instance. */\nexport class WeaverseHydrogenItem extends WeaverseItemStore {\n /** Owning Hydrogen runtime instance. */\n declare weaverse: WeaverseHydrogen\n\n /**\n * Cached merged snapshot (base + translations).\n * Reset to `null` whenever `_store` or the item's translation entry changes.\n */\n private _cachedSnapshot: ElementData | null = null\n private _snapshotStoreRef: ElementData | null = null\n private _snapshotTranslationRef: TranslationItemEntry | null = null\n\n /** Creates an item store from serialized component data and its owner. */\n constructor(initialData: HydrogenComponentData, weaverse: WeaverseHydrogen) {\n super(initialData, weaverse)\n const { data, ...rest } = initialData\n if (!this.Element?.schema) {\n console.error('Element is missing schema or not found!')\n return\n }\n const schemaData = generateDataFromSchema(this.Element.schema)\n Object.assign(this._store, schemaData, data, rest)\n }\n\n /** Registered component definition for this item's type. */\n get Element(): HydrogenElement {\n return super.Element\n }\n\n /**\n * Override setData to flatten serialized `data` the same way the constructor\n * does. Core's `initProject()` reuses item stores keyed by item id (identical\n * ids across locales), and the inherited setData only shallow-merges the raw\n * item — fresh settings would land under `_store.data` while the stale\n * flattened values keep rendering.\n *\n * Schema defaults are re-applied ahead of incoming settings because a\n * serialized payload can omit fields — or the optional `data` object itself —\n * when values equal schema defaults. The stored nested `data` is also replaced\n * so the public serialized state does not retain the previous locale payload.\n *\n * An empty update is the context-only refresh from `syncReusedInstance`: swap\n * the store reference so memoized subscribers re-render, and leave the\n * settings untouched.\n */\n setData = (update: Omit<ElementData, 'id' | 'type'>) => {\n let source = update ?? {}\n let { data, ...rest } = source\n let isEmptyUpdate = Object.keys(source).length === 0\n\n if (isEmptyUpdate) {\n this._store = { ...this._store }\n } else {\n let type = source.type ?? this._store.type\n let schema = this.weaverse.elementRegistry.get(type)?.schema\n let isSerializedItem = 'id' in source && 'type' in source\n let shouldNormalize = data !== undefined || isSerializedItem\n\n if (schema && shouldNormalize) {\n let { data: _previousData, ...store } = this._store\n let schemaData = generateDataFromSchema(schema)\n this._store = {\n ...store,\n ...(data === undefined ? {} : { data }),\n ...schemaData,\n ...data,\n ...rest,\n }\n } else {\n this._store = { ...this._store, ...source }\n }\n }\n\n this.triggerUpdate()\n return this.data\n }\n\n /**\n * Override getSnapShot to merge translation data when in translation mode.\n * Memoizes the result: returns the same object reference as long as\n * both `_store` and the translation entry haven't changed.\n * This is critical for `useSyncExternalStore` stability.\n */\n getSnapShot = (): ElementData => {\n const base = this._store\n const translations = this.weaverse.translationMap?.[this._id]\n\n // No translations → return base directly (fast path)\n if (!translations) {\n return base\n }\n\n // Check if cache is still valid (same _store ref + same translation entry ref)\n if (\n this._cachedSnapshot &&\n this._snapshotStoreRef === base &&\n this._snapshotTranslationRef === translations\n ) {\n return this._cachedSnapshot\n }\n\n // Build merged snapshot\n const merged = { ...base }\n for (const [key, entry] of Object.entries(translations)) {\n if (entry.translatedValue !== undefined) {\n merged[key] = entry.translatedValue\n }\n }\n\n this._cachedSnapshot = merged\n this._snapshotStoreRef = base\n this._snapshotTranslationRef = translations\n return merged\n }\n}\n\nWeaverse.ItemConstructor = WeaverseHydrogenItem\n\n/**\n * Hydrogen-specific Weaverse runtime that owns page data, component stores,\n * Studio state, and translation sidecars for one rendered page.\n */\nexport class WeaverseHydrogen extends Weaverse {\n /** Identifier of the rendered page. */\n pageId: string\n /** Runtime services and project metadata exposed to integrations. */\n internal: Partial<WeaverseInternal>\n /** Normalized URL and locale information for the current request. */\n requestInfo: WeaverseLoaderRequestInfo\n /** Identifier of the project supplying the page. */\n projectId: string\n /** Origin used for Studio assets and editor communication. */\n weaverseHost: string\n /** Base URL used for public content API requests. */\n weaverseApiBase: string\n /**\n * API key read from environment/configuration for storefront requests or\n * supplied by Studio requests while editing and previewing.\n */\n weaverseApiKey: string\n /** Studio asset version supplied by the preview request. */\n weaverseVersion: string\n /** Whether the page is running inside the visual editor. */\n isDesignMode: boolean\n /** Whether a single component preview is being rendered. */\n isPreviewMode: boolean\n /** Whether a saved page revision is being previewed. */\n isRevisionPreview: boolean\n /** Component type requested by section preview mode. */\n sectionType: string\n /** Component item store constructor used by the core runtime. */\n declare ItemConstructor: typeof WeaverseHydrogenItem\n /** Current page content owned by the runtime. */\n declare data: HydrogenPageData\n /** Component item stores indexed by instance ID. */\n declare static itemInstances: Map<string, WeaverseHydrogenItem>\n /** Registered component definitions indexed by component type. */\n declare static elementRegistry: Map<string, HydrogenElement>\n\n // ─── Translation sidecar (design mode only) ────────────────────────\n /**\n * Translation map received from the builder in design mode.\n * Keyed by item ID, each entry maps field names to translated values.\n * `WeaverseHydrogenItem.getSnapShot()` merges these into the data\n * returned to components, so translations render without monkey-patching.\n */\n translationMap: TranslationMap = {}\n /** Locale code for the active translation sidecar. */\n translationLocale = ''\n /** Builder language identifier for the active translation sidecar. */\n translationLanguageId = ''\n\n /** Creates a page runtime from resolved loader data and request settings. */\n constructor(params: WeaverseHydrogenParams) {\n const { internal, pageId, requestInfo, ...coreParams } = params\n super({ ...coreParams })\n this.internal = internal\n this.pageId = pageId\n this.requestInfo = requestInfo\n // Assign configuration properties\n this.projectId = params.projectId\n this.weaverseHost = params.weaverseHost\n this.weaverseApiBase = params.weaverseApiBase\n this.weaverseApiKey = params.weaverseApiKey\n this.weaverseVersion = params.weaverseVersion || ''\n this.isDesignMode = params.isDesignMode ?? false\n this.isPreviewMode = params.isPreviewMode ?? false\n this.isRevisionPreview = params.isRevisionPreview ?? false\n this.sectionType = params.sectionType || ''\n\n // Extract translation sidecar from page data if present (design mode)\n this.extractTranslationSidecar()\n }\n\n /**\n * Extract translation sidecar data from `this.data` (the page data).\n * The builder attaches `translationMap`, `translationLocale`, and\n * `translationLanguageId` to the page data in design mode.\n */\n extractTranslationSidecar = () => {\n const pageData = this.data as Record<string, any>\n if (pageData?.translationMap) {\n this.translationMap = pageData.translationMap\n this.translationLocale = pageData.translationLocale || ''\n this.translationLanguageId = pageData.translationLanguageId || ''\n }\n }\n\n /**\n * Set the translation sidecar data.\n * Called by the studio bridge when translation data arrives or changes.\n * Triggers a re-render of all items so translated snapshots are recalculated.\n */\n setTranslationSidecar = (\n translationMap: TranslationMap,\n locale: string,\n languageId: string\n ) => {\n this.translationMap = translationMap\n this.translationLocale = locale\n this.translationLanguageId = languageId\n // Invalidate all item snapshot caches and trigger re-render\n this.refreshAllItems()\n }\n\n /**\n * Update a single translation entry for a specific item field.\n * Used by the studio bridge when the user edits a translatable field.\n */\n updateTranslation = (\n itemId: string,\n key: string,\n originalValue: string,\n translatedValue: string\n ) => {\n if (!this.translationMap[itemId]) {\n this.translationMap[itemId] = {}\n }\n // Create a new entry reference so getSnapShot detects the change\n this.translationMap[itemId] = {\n ...this.translationMap[itemId],\n [key]: { originalValue, translatedValue },\n }\n // Trigger re-render for this specific item\n const instance = this.itemInstances.get(itemId)\n if (instance) {\n instance.triggerUpdate()\n }\n }\n\n /**\n * Collect all translation changes across all weaverse instances.\n * Used by the save flow to persist translation edits.\n */\n getTranslationChanges = (): TranslationChanges | undefined => {\n const entries: TranslationEntry[] = []\n const languageId = this.translationLanguageId\n if (!(this.translationLocale && languageId)) {\n return\n }\n\n for (const [itemId, fields] of Object.entries(this.translationMap)) {\n for (const [key, entry] of Object.entries(fields)) {\n entries.push({\n itemId,\n key: `data.${key}`,\n originalValue: entry.originalValue,\n translatedValue: entry.translatedValue,\n })\n }\n }\n\n if (entries.length === 0) {\n return\n }\n return { languageId, entries }\n }\n\n /**\n * Override setProjectData to re-extract translation sidecar from new page data.\n */\n setProjectData = (data: HydrogenPageData) => {\n this.data = data\n this.extractTranslationSidecar()\n this.initProject()\n }\n}\n\nfunction createWeaverseInstance(\n params: WeaverseHydrogenParams\n): WeaverseHydrogen {\n const normalizedParams = normalizeRequestInfo(params)\n if (isBrowser) {\n window.__weaverses = window.__weaverses || {}\n const existing = window.__weaverses[normalizedParams.pageId]\n // Reuse the instance only while the browser stays on the same URL —\n // navigation to a different pathname/search builds a fresh instance.\n const isReused =\n existing?.requestInfo?.pathname ===\n normalizedParams.requestInfo.pathname &&\n existing?.requestInfo?.search === normalizedParams.requestInfo.search\n const weaverse = isReused\n ? existing\n : new WeaverseHydrogen(normalizedParams)\n window.__weaverses[normalizedParams.pageId] = weaverse\n if (weaverse.isDesignMode) {\n weaverse.requestInfo = normalizedParams.requestInfo\n if (hasWeaverseStudio(window)) {\n window.weaverseStudio.refreshStudio(normalizedParams)\n }\n } else if (isReused) {\n // Same-URL revalidation in live/preview mode: the reused instance\n // must adopt the fresh loader payload (see syncReusedInstance).\n syncReusedInstance(weaverse, normalizedParams)\n }\n return weaverse\n }\n return new WeaverseHydrogen(normalizedParams)\n}\n\nconst StudioBridge = memo(({ context }: { context: WeaverseHydrogen }) => {\n useStudio(context)\n return null\n})\n\nconst StudioConnect = memo(() => {\n useStudioConnect()\n return null\n})\n\n/**\n * Component lists already pushed into the element registry. Registration is\n * idempotent (the registry checks `has(type)`), but walking the full list\n * allocates and loops on every render — theme component arrays are\n * module-level constants, so register each list identity once.\n */\nconst registeredComponentLists = new WeakSet<HydrogenComponent[]>()\n\nfunction RenderRoot(props: {\n data: WeaverseLoaderData\n components: HydrogenComponent[]\n dataContext?: Record<string, any>\n}) {\n const { data, components, dataContext } = props\n if (!registeredComponentLists.has(components)) {\n for (const comp of [...components, ...defaultComponents]) {\n if (comp?.schema?.type) {\n registerComponent({\n type: comp.schema.type,\n Component: comp.default,\n schema: comp.schema,\n loader: comp.loader,\n })\n }\n }\n registeredComponentLists.add(components)\n }\n const { page, configs, project, pageAssignment } = data || {}\n\n // Keep original page data - processing will happen at component level in renderer\n\n const weaverse = createWeaverseInstance({\n ...configs,\n dataContext,\n data: page,\n pageId: page?.id,\n internal: { project, pageAssignment },\n })\n return (\n <>\n <WeaverseRoot context={weaverse} />\n <StudioBridge context={weaverse} />\n </>\n )\n}\n\n/**\n * Register a Weaverse component with the global element registry.\n * Must be called before rendering components in WeaverseHydrogenRoot.\n *\n * @param element - Component configuration with schema, Component, and optional loader\n *\n * @example\n * ```typescript\n * import Hero from './sections/Hero'\n * import { schema } from './sections/Hero'\n *\n * registerComponent({\n * type: 'hero',\n * Component: Hero,\n * schema,\n * loader: async ({ data, weaverse }) => {\n * return { someData: 'value' }\n * }\n * })\n * ```\n */\nexport function registerComponent(element: HydrogenElement) {\n WeaverseHydrogen.registerElement(element)\n}\n\n/** Props passed to a custom Weaverse page error component. */\nexport interface WeaverseHydrogenRootErrorProps {\n /** Error raised while resolving or rendering the Weaverse page. */\n error: Error | unknown\n}\n\n/** Props accepted by {@link WeaverseHydrogenRoot}. */\nexport interface WeaverseHydrogenRootProps {\n /** Theme components available to the page renderer. */\n components: HydrogenComponent[]\n /**\n * Optional explicit `weaverseData` payload. When provided, bypasses the\n * automatic route-scoped resolution. Accepts a resolved value, a\n * `Promise` (handled via `<Await>`), or `null` to suppress rendering.\n *\n * Recommended for nested layout + child route compositions where two\n * `<WeaverseHydrogenRoot>` instances need to render different Weaverse\n * pages on the same URL. See issue #451.\n */\n data?: WeaverseDataValue\n /** Component rendered when page data cannot be resolved or awaited. */\n errorComponent?: React.FC<WeaverseHydrogenRootErrorProps>\n}\n\n/**\n * Renders the Weaverse page for the current React Router route.\n *\n * Pass `data` to override automatic route-loader resolution. A promise is\n * handled with React Router's `Await`, while explicit `null` suppresses output.\n */\nexport const WeaverseHydrogenRoot = memo(\n ({\n components,\n data: dataProp,\n errorComponent: ErrorComponent = ({ error }) => (\n <div>\n {error instanceof Error\n ? error.message\n : 'An unexpected error occurred'}\n </div>\n ),\n }: WeaverseHydrogenRootProps) => {\n const matches = useMatches()\n\n // Flat route-keyed data context for data-connector template resolution\n // (e.g. {{root.layout.shop.name}}). Legitimately needs all matches;\n // memoized so same-matches re-renders don't allocate a fresh context.\n const enhancedDataContext = useMemo(\n () => createWeaverseDataContext(matches),\n [matches]\n )\n\n // Route-scoped weaverseData lookup. `useLoaderData()` returns the\n // closest route's loader data, which is what makes nested layout +\n // child routes work — each <WeaverseHydrogenRoot> instance resolves\n // to its own route's weaverseData. See pickWeaverseData() for the\n // three-tier fallback policy.\n const ownLoaderData = useLoaderData() as unknown\n const weaverseData = useMemo(\n () => pickWeaverseData(dataProp, ownLoaderData, matches),\n [dataProp, ownLoaderData, matches]\n )\n\n // Explicit `data={null}` is the documented signal for \"suppress rendering\"\n // (e.g. a route conditionally disables Weaverse without unmounting the\n // component). This is distinct from auto-resolution returning `null`,\n // which means \"data was expected but not found\" — the error path below.\n if (dataProp === null) {\n return null\n }\n\n if (weaverseData) {\n if (weaverseData instanceof Promise) {\n return (\n <ErrorBoundary fallbackRender={ErrorComponent as any}>\n <Suspense>\n <Await resolve={weaverseData}>\n {(resolvedData) => (\n <RenderRoot\n components={components}\n data={resolvedData}\n dataContext={enhancedDataContext}\n />\n )}\n </Await>\n </Suspense>\n </ErrorBoundary>\n )\n }\n return (\n <RenderRoot\n components={components}\n data={weaverseData}\n dataContext={enhancedDataContext}\n />\n )\n }\n return (\n <ErrorComponent\n error={{ message: 'No Weaverse data found in route matches!' }}\n />\n )\n }\n)\n\n/**\n * Options for the `withWeaverse` HOC.\n */\nexport type WithWeaverseOptions = {\n /**\n * Optional external translation function (e.g. from Shopify i18n).\n * When provided it becomes the **highest-priority** source\n * in the `t()` resolution chain exposed by `useTranslation()`.\n */\n t?: TranslateFunction\n}\n\n/**\n * Higher-order component that wraps your app with Weaverse theme settings and\n * translation context, and mounts the Studio connect bridge.\n *\n * Export the result as your root route's **`Layout`** (not the default route\n * `Component`). In React Router the root `Layout` wraps both the matched route\n * and its `ErrorBoundary`, so the Studio bridge keeps rendering on 404s and\n * loader/render errors — exactly the pages where Studio must still answer its\n * handshake instead of reporting a false \"Connection lost\". A default-component\n * wrapper (`export default withWeaverse(App)`) is replaced by the error\n * boundary on those routes and would drop the bridge.\n *\n * @param Component - The root layout component to wrap\n * @param options - Optional configuration (e.g. an external `t` function)\n * @returns Wrapped component with theme settings + translation providers\n *\n * @example\n * ```typescript\n * import { withWeaverse } from '@weaverse/hydrogen'\n *\n * // Basic usage — export as the root route Layout\n * export const Layout = withWeaverse(RootLayout)\n *\n * // With an external translation function\n * export const Layout = withWeaverse(RootLayout, { t: myI18nFunction })\n * ```\n */\nexport function withWeaverse(\n Component: ComponentType<any>,\n options?: WithWeaverseOptions\n) {\n return (props: JSX.IntrinsicAttributes) => {\n const themeSettingsStore = useCreateThemeSettingsStore()\n const translationData = useTranslationData()\n const translationStoreRef = useRef<TranslationStore | null>(null)\n if (!translationStoreRef.current) {\n translationStoreRef.current = new TranslationStore()\n }\n return (\n <ThemeSettingsStoreContext.Provider value={themeSettingsStore}>\n <TranslationProvider\n merchantOverrides={translationData.merchantOverrides}\n staticContent={translationData.staticContent}\n t={options?.t}\n translationStore={translationStoreRef.current}\n >\n <StudioConnect />\n <Component {...props} />\n </TranslationProvider>\n </ThemeSettingsStoreContext.Provider>\n )\n }\n}\n\n/**\n * Internal hook to read staticContent and merchantOverrides from root loader data.\n * Similar pattern to useThemeSettingsStore – reads from the 'root' route loader.\n */\nfunction useTranslationData(): {\n staticContent: Record<string, unknown>\n merchantOverrides?: Record<string, unknown>\n} {\n const data = useRouteLoaderData('root') as {\n weaverseTheme?: {\n staticContent?: Record<string, unknown>\n merchantOverrides?: Record<string, unknown>\n }\n }\n return {\n staticContent: data?.weaverseTheme?.staticContent ?? {},\n merchantOverrides: data?.weaverseTheme?.merchantOverrides,\n }\n}\n\n/**\n * React hook to access Weaverse theme settings from anywhere in your component tree.\n * Must be used within a component wrapped by `withWeaverse` or inside `WeaverseHydrogenRoot`.\n *\n * @returns Current theme settings object\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const theme = useThemeSettings()\n * const primaryColor = theme.colors?.primary\n *\n * return <div style={{ color: primaryColor }}>Styled content</div>\n * }\n * ```\n */\nexport function useThemeSettings<T = HydrogenThemeSettings>() {\n const themeSettingsStore = useThemeSettingsStore()\n const settings = useSafeExternalStore(\n themeSettingsStore.subscribe,\n themeSettingsStore.getSnapshot,\n themeSettingsStore.getServerSnapshot\n )\n return settings as T\n}\n","// Query params that influence Weaverse page resolution on the Builder:\n// revision previews, design-mode flags, and `weaverse*` control params\n// (host, version, project id). Everything else — utm_*, fbclid, gclid,\n// storefront filters — is irrelevant to which page the Builder returns.\nconst KEPT_PARAM_RE = /^(?:__revisionId|isDesignMode|weaverse)/\n\n/**\n * Normalize the storefront URL sent in the Builder page API request body.\n *\n * The POST body participates in the `withCache` cache key, so a raw\n * `request.url` fragments the cache by every marketing/tracking param:\n * each distinct `?utm_…`/`fbclid` URL is a guaranteed Builder round-trip\n * even when the resolved page is identical — precisely the paid/social\n * traffic that needs the cache most (builder#2450).\n *\n * The Builder reads only the pathname (locale/type/handle fallback) and\n * the params matched above from this URL, so keep exactly those. Params\n * are sorted for a stable cache key regardless of their order in the\n * incoming URL.\n */\nexport function normalizePageUrl(url: string): string {\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n // Not an absolute URL (shouldn't happen for request.url) — send as-is.\n return url\n }\n const kept = [...parsed.searchParams].filter(([key]) =>\n KEPT_PARAM_RE.test(key)\n )\n kept.sort(([a], [b]) => a.localeCompare(b))\n const search = new URLSearchParams(kept).toString()\n // React Router single-fetch requests loader data from `/<path>.data`, which\n // resolves to the same Builder page as `/<path>`. Strip the suffix so a\n // client navigation and a document load hash to one edge-cache key (the\n // api.weaverse.io worker keys on this url) instead of two — keeping a page's\n // first client navigation off the cold-MISS path.\n let { pathname } = parsed\n if (pathname.endsWith('.data')) {\n pathname = pathname.slice(0, -'.data'.length)\n }\n return `${parsed.origin}${pathname}${search ? `?${search}` : ''}`\n}\n","import {\n CacheCustom,\n createWithCache,\n type HydrogenEnv,\n type I18nBase,\n} from '@shopify/hydrogen'\nimport type {\n CachingStrategy,\n CustomPageEntry,\n FetchProjectPayload,\n FetchProjectRequestBody,\n HydrogenComponent,\n HydrogenComponentData,\n HydrogenPageData,\n LoadPageParams,\n PageType,\n ProjectIdValidationResult,\n ThemeSettingsResponse,\n WeaverseClientArgs,\n WeaverseLoaderData,\n WeaverseProjectConfigs,\n WeaverseStudioQueries,\n WithCacheFetchResponse,\n} from './types'\nimport {\n hasError,\n isProjectIdFunction,\n WeaverseError,\n WeaverseLoadError,\n type WeaverseLoadFailureKind,\n} from './types'\nimport {\n generateDataFromSchema,\n getPreviewData,\n getRequestQueries,\n getWeaverseConfigs,\n} from './utils'\nimport { normalizePageUrl } from './utils/normalize-page-url'\n\n/**\n * Cache duration constants (in seconds).\n * These values optimize CDN hit rates while maintaining fresh content.\n */\nconst CACHE_DURATIONS = {\n /** Short browser freshness for content that can change in Builder */\n SHORT: 60,\n /** Shared cache freshness for anonymous storefront traffic */\n SHARED_SHORT: 300,\n /** Long stale window so slow Builder responses do not block storefront rendering */\n LONG: 86_400,\n /** Extra freshness for sitemap-like index data */\n STATIC: 3600,\n} as const\n\n/**\n * Network timeout for fetch requests (in milliseconds).\n * Default is 10 seconds to balance reliability and user experience.\n */\nconst DEFAULT_FETCH_TIMEOUT_MS = 10_000\n\n/**\n * Bounded retry for the public API fetch. A single slow/cold origin response,\n * a transient 5xx, or a network blip would otherwise make loadPage return null\n * — rendering the \"Please add new section\" placeholder or throwing a 404 in\n * the route. Two attempts (one retry) is enough: by the time the first attempt\n * times out, the edge proxy's single-flight leader has usually populated its\n * versioned cache, so the retry lands on a warm HIT.\n */\nconst MAX_FETCH_ATTEMPTS = 2\nconst FETCH_RETRY_BACKOFF_MS = 300\n\n/**\n * Retry only transient failures: request timeouts, network errors, and origin\n * 5xx. A 4xx is deterministic (e.g. a genuine 404) — retrying just wastes time.\n */\nfunction isRetryableFetchError(error: unknown): boolean {\n if (!(error instanceof WeaverseError)) {\n return false\n }\n // A successful status with an unparsable body was classified as a network\n // error before it got its own code; it keeps the same single retry.\n if (\n error.code === 'TIMEOUT_ERROR' ||\n error.code === 'NETWORK_ERROR' ||\n error.code === 'INVALID_RESPONSE'\n ) {\n return true\n }\n return error.code === 'FETCH_ERROR' && (error.statusCode ?? 0) >= 500\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Whether a successful `/project` body is a page envelope.\n *\n * `page: null` is Builder's authoritative \"nothing assigned at this URL\" and\n * stays valid; anything without a `page` field, with an `error` field, or with\n * a page that has no item list is not an answer about this URL at all.\n */\nfunction isProjectEnvelope(payload: unknown): boolean {\n if (!isPlainObject(payload) || hasError(payload) || !('page' in payload)) {\n return false\n }\n const { page, project } = payload\n const validPage =\n page === null || (isPlainObject(page) && Array.isArray(page.items))\n return validPage && (project == null || isPlainObject(project))\n}\n\n/**\n * Whether a successful `/project_configs` body carries theme settings.\n *\n * Builder always sends the `theme` field; `null` means the merchant never\n * saved settings, so schema defaults are the real configuration.\n */\nfunction isThemeConfigsEnvelope(payload: unknown): boolean {\n return (\n isPlainObject(payload) &&\n !hasError(payload) &&\n 'theme' in payload &&\n (payload.theme === null || isPlainObject(payload.theme))\n )\n}\n\n/**\n * Classifies a page-load failure. `'absent'` is Builder's 404 for a project\n * that does not exist, which keeps resolving to `null` like before.\n */\nfunction classifyPageLoadFailure(\n error: unknown\n): WeaverseLoadFailureKind | 'absent' {\n if (error instanceof WeaverseLoadError) {\n return error.kind\n }\n if (!(error instanceof WeaverseError)) {\n // Thrown while turning a response into page data: the body was not\n // the shape it claimed to be.\n return 'invalid-response'\n }\n if (error.code === 'TIMEOUT_ERROR' || error.code === 'NETWORK_ERROR') {\n return 'unavailable'\n }\n if (error.code === 'INVALID_RESPONSE') {\n return 'invalid-response'\n }\n if (error.code === 'FETCH_ERROR') {\n const status = error.statusCode ?? 0\n if (status === 404) {\n return 'absent'\n }\n if (status === 408 || status === 425 || status === 429 || status >= 500) {\n return 'unavailable'\n }\n }\n // Refusals (400/401/403) and project-ID errors: retrying cannot succeed.\n return 'configuration'\n}\n\n/**\n * Validators for Builder requests made by this client itself, keyed on the\n * exact options object (same reasoning as `bodyFreeCacheRequests`). On the\n * cached path such a request rejects a non-2xx status instead of resolving\n * to `null`, and only stores a body its validator accepts. Every other\n * `fetchWithCache` caller keeps the existing behavior.\n */\nconst builderPayloadValidators = new WeakMap<\n object,\n (payload: unknown) => boolean\n>()\n\n/**\n * Gives a rejection from Hydrogen's cached fetch the code `fetchOnce` gives\n * the same failure on the direct path.\n *\n * Hydrogen calls the platform `fetch` itself, so a request that never got a\n * response rejects with the platform's error instead of a `WeaverseError`.\n * The Fetch standard rejects a network failure with a `TypeError` and an\n * aborted request with the signal's `AbortError`/`TimeoutError`; those are\n * outages. Anything else is returned unchanged, so it is not reported as one.\n */\nfunction cachedTransportError(error: unknown, url: string): unknown {\n if (error instanceof WeaverseError || !(error instanceof Error)) {\n return error\n }\n if (error.name === 'AbortError' || error.name === 'TimeoutError') {\n return new WeaverseError('Request timed out', 'TIMEOUT_ERROR', undefined, {\n url,\n })\n }\n if (error instanceof TypeError) {\n return new WeaverseError(\n 'Network error during fetch',\n 'NETWORK_ERROR',\n undefined,\n { url, cause: error.message }\n )\n }\n return error\n}\n\n/**\n * Weaverse API version path\n */\nconst API_PATH = 'v1' as const\n\n/**\n * Default cache strategy for Weaverse API requests.\n * Optimized for CDN performance with 23-hour stale content tolerance.\n */\nconst DEFAULT_CACHE_STRATEGY: CachingStrategy = {\n maxAge: CACHE_DURATIONS.SHORT,\n sMaxAge: CACHE_DURATIONS.SHARED_SHORT,\n staleWhileRevalidate: CACHE_DURATIONS.LONG,\n staleIfError: CACHE_DURATIONS.LONG,\n} as const\n\n/** Builder API resource whose freshness policy should be used for a request. */\nexport type BuilderApiCacheTarget =\n | 'custom-pages'\n | 'merchant-overrides'\n | 'project'\n | 'theme-settings'\n\n/** Fetch options accepted by {@link WeaverseClient.fetchWithCache}. */\nexport interface WeaverseFetchWithCacheOptions extends RequestInit {\n /** Builder API resource whose default freshness policy should be used. */\n cacheTarget?: BuilderApiCacheTarget\n /** Explicit Hydrogen caching strategy overriding the resource default. */\n strategy?: CachingStrategy\n}\n\n/** Pagination and locale options for {@link WeaverseClient.fetchCustomPages}. */\nexport interface FetchCustomPagesOptions {\n /** Maximum number of custom pages requested per API page. */\n limit?: number\n /** Locale whose published custom pages should be returned. */\n locale?: string\n}\n\nconst SMART_CACHE_STRATEGIES: Record<BuilderApiCacheTarget, CachingStrategy> = {\n project: DEFAULT_CACHE_STRATEGY,\n 'theme-settings': DEFAULT_CACHE_STRATEGY,\n 'merchant-overrides': DEFAULT_CACHE_STRATEGY,\n 'custom-pages': {\n maxAge: CACHE_DURATIONS.SHORT,\n sMaxAge: CACHE_DURATIONS.STATIC,\n staleWhileRevalidate: CACHE_DURATIONS.LONG,\n staleIfError: CACHE_DURATIONS.LONG,\n },\n} as const\n\n/**\n * Options objects created by the internal `project_configs` request whose\n * subrequest cache identity deliberately excludes the body. Theme settings\n * carry the storefront origin so Builder can attribute hostnames; hashing the\n * body would give every domain of one project its own entry.\n *\n * The SUCCESSFUL theme payload is the same for every storefront of a project,\n * which is what makes one shared entry correct. This is not a claim that\n * Builder can never answer differently per host: a hostname-blocked request\n * returns a 403 `{ error }` body, and `shouldCacheResponse` rejects anything\n * `hasError()` matches, so a refusal is never stored under (or served from)\n * the shared entry. If a future response shape ever varies by host WITHOUT an\n * `error` field, this exclusion has to be revisited.\n *\n * Keyed on the exact options object, NOT on `cacheTarget`: `fetchWithCache`\n * is public API, so gating on the target would silently collapse the cache of\n * any consumer who selects `theme-settings` with varying bodies. An outside\n * caller's options object is never in this set and keeps a body-derived key.\n *\n * The WeakSet-membership slot in the cache key (`has(options)`) is the actual\n * discriminator — no caller-supplied value can reach it. The sentinel is not\n * load-bearing for that; it only keeps the omitted body legible in cache\n * debugging instead of a bare `undefined`.\n */\nconst bodyFreeCacheRequests = new WeakSet<object>()\nconst BODY_FREE_CACHE_SENTINEL = '\\u0000weaverse:body-free'\n\n/**\n * Request-scoped client for loading Weaverse pages and theme settings in Hydrogen.\n *\n * Create one client from the Hydrogen app context, then call\n * {@link WeaverseClient.loadPage} from route loaders and\n * {@link WeaverseClient.loadThemeSettings} from the root loader.\n */\nexport class WeaverseClient {\n /** Builder API version used by this client. */\n API = API_PATH\n /** Stable project configuration shared by page requests. */\n basePageConfigs: Omit<WeaverseProjectConfigs, 'requestInfo'>\n /** Stable request body fields shared by page requests. */\n basePageRequestBody: Omit<FetchProjectRequestBody, 'url'>\n /** Resolved project and rendering-mode configuration. */\n configs: WeaverseProjectConfigs\n /** Hydrogen cache wrapper used for Builder API requests. */\n withCache: ReturnType<typeof createWithCache>\n\n /** Incoming request associated with this client instance. */\n request: WeaverseClientArgs['request']\n /** Hydrogen customer-account client, when configured. */\n customerAccount: WeaverseClientArgs['customerAccount']\n /** Hydrogen Storefront API client and locale context. */\n storefront: WeaverseClientArgs['storefront']\n /** Components registered for page rendering and component loaders. */\n components: WeaverseClientArgs['components']\n /** Theme schema used for defaults and Studio editing. */\n themeSchema: WeaverseClientArgs['themeSchema']\n /** Hydrogen runtime environment variables. */\n env: WeaverseClientArgs['env']\n /** Cache storage supplied by the Hydrogen runtime. */\n cache: WeaverseClientArgs['cache']\n /** Background execution hook supplied by the Oxygen runtime. */\n waitUntil: WeaverseClientArgs['waitUntil']\n\n // Performance optimizations\n private readonly parsedUrl: URL\n private readonly componentsByType: Map<string, HydrogenComponent>\n\n // Configuration\n private readonly fetchTimeoutMs: number\n private readonly throwPageLoadFailures: boolean\n\n /** Creates a request-scoped client from the Hydrogen app context. */\n constructor(args: WeaverseClientArgs) {\n // Assign required dependencies\n this.request = args.request\n this.storefront = args.storefront\n this.customerAccount = args.customerAccount\n this.components = args.components\n this.themeSchema = args.themeSchema\n this.env = args.env\n this.cache = args.cache\n this.waitUntil = args.waitUntil\n\n // Performance optimizations\n this.parsedUrl = new URL(args.request.url)\n this.componentsByType = this.buildComponentLookupMap(args.components)\n\n // Configuration\n this.fetchTimeoutMs = args.fetchTimeoutMs || DEFAULT_FETCH_TIMEOUT_MS\n this.throwPageLoadFailures = args.throwPageLoadFailures === true\n\n // Initialize cache and configs\n this.initializeCache(args)\n this.initializeConfigs(args)\n }\n\n /**\n * Initialize Hydrogen cache with proper configuration.\n * Logs warning if waitUntil is missing.\n */\n private initializeCache(args: WeaverseClientArgs): void {\n if (!args.waitUntil) {\n console.warn(\n '⚠️ WeaverseClient: waitUntil not provided, background operations may not complete'\n )\n }\n\n this.withCache = createWithCache({\n cache: args.cache,\n waitUntil: args.waitUntil || (() => Promise.resolve()),\n request: args.request,\n })\n }\n\n /**\n * Initialize configs with projectId resolution and fail-fast validation.\n * Throws WeaverseError if projectId cannot be resolved.\n */\n private initializeConfigs(args: WeaverseClientArgs): void {\n // Get base configs once to avoid duplicate calls\n const baseConfigs = getWeaverseConfigs(\n args.request,\n args.env as HydrogenEnv\n )\n\n // Resolve projectId with multi-project support\n const resolvedProjectId = this.resolveProjectIdSync(\n args.projectId,\n args.request,\n args.env as HydrogenEnv,\n baseConfigs\n )\n\n // Fail-fast validation: throw if projectId is empty\n if (!resolvedProjectId || resolvedProjectId.trim() === '') {\n throw new WeaverseError(\n 'Failed to initialize WeaverseClient: No valid projectId found. ' +\n 'Set WEAVERSE_PROJECT_ID environment variable or provide projectId parameter.',\n 'MISSING_PROJECT_ID'\n )\n }\n\n // Initialize configs with resolved projectId\n this.configs = {\n ...baseConfigs,\n projectId: resolvedProjectId,\n }\n\n // Initialize base configurations\n this.basePageConfigs = {\n projectId: this.configs.projectId,\n weaverseHost: this.configs.weaverseHost,\n weaverseApiBase: this.configs.weaverseApiBase,\n weaverseApiKey: this.configs.weaverseApiKey,\n weaverseVersion: this.configs.weaverseVersion,\n isDesignMode: this.configs.isDesignMode,\n isPreviewMode: this.configs.isPreviewMode,\n isRevisionPreview: this.configs.isRevisionPreview,\n }\n\n this.basePageRequestBody = {\n isDesignMode: this.configs.isDesignMode,\n i18n: args.storefront.i18n,\n projectId: this.configs.projectId,\n }\n\n // Freeze configs to prevent accidental mutations\n Object.freeze(this.configs)\n Object.freeze(this.basePageConfigs)\n Object.freeze(this.basePageRequestBody)\n }\n\n /**\n * Build component lookup map for O(1) access by type.\n * Significantly improves performance for large component lists.\n */\n private buildComponentLookupMap(\n components: HydrogenComponent[]\n ): Map<string, HydrogenComponent> {\n return new Map(components.map((comp) => [comp.schema?.type, comp]))\n }\n\n /**\n * Extract comprehensive error information from unknown error type.\n * Preserves error context, codes, and stack traces for debugging.\n *\n * @param error - Unknown error to extract information from\n * @returns Structured error information with message, code, stack, and context\n *\n * @example\n * ```typescript\n * try {\n * // ... operation\n * } catch (error) {\n * const errorInfo = this.extractErrorInfo(error)\n * console.error('Operation failed:', errorInfo.message, errorInfo.context)\n * }\n * ```\n */\n private extractErrorInfo(error: unknown): {\n message: string\n code?: string\n stack?: string\n context?: Record<string, unknown>\n } {\n if (error instanceof WeaverseError) {\n return {\n message: error.message,\n code: error.code,\n context: error.context,\n stack: error.stack,\n }\n }\n\n if (error instanceof Error) {\n return {\n message: error.message,\n stack: error.stack,\n }\n }\n\n return {\n message: String(error),\n }\n }\n\n /**\n * Extract error message only (for backward compatibility).\n * Use extractErrorInfo() for more detailed error information.\n *\n * @deprecated Use extractErrorInfo() instead to preserve error context\n */\n private extractErrorMessage(error: unknown): string {\n return this.extractErrorInfo(error).message\n }\n\n /**\n * Validates projectId format (alphanumeric, hyphens, underscores only).\n * Returns detailed validation result with error message.\n *\n * @param projectId - Project identifier to validate\n * @returns Validation result with error message if invalid\n */\n private validateProjectId(projectId: string): ProjectIdValidationResult {\n if (!projectId || projectId.trim() === '') {\n return {\n valid: false,\n error: 'Project ID cannot be empty',\n }\n }\n\n // Only allow alphanumeric characters, hyphens, and underscores\n const validPattern = /^[a-zA-Z0-9_-]+$/\n if (!validPattern.test(projectId)) {\n return {\n valid: false,\n error: `Invalid format: \"${projectId}\". Only alphanumeric characters, hyphens, and underscores are allowed.`,\n }\n }\n\n return { valid: true }\n }\n\n /**\n * Resolves projectId with multi-project architecture support.\n * Uses priority chain to determine the correct project ID.\n *\n * @param projectId - Project identifier (string, function, or undefined)\n * @param request - HTTP request for context access\n * @param env - Hydrogen environment with variables\n * @param baseConfigs - Pre-fetched base configs to avoid duplicate calls\n * @returns Resolved project ID string (empty string if none found)\n */\n private resolveProjectIdSync(\n projectId: string | (() => string) | (() => Promise<string>) | undefined,\n request: Request,\n env: HydrogenEnv,\n baseConfigs?: WeaverseProjectConfigs\n ): string {\n return (\n this.resolveFromQueryParams(request) ||\n this.resolveFromFunction(projectId) ||\n this.resolveFromString(projectId) ||\n this.resolveFromEnvironment(baseConfigs, request, env) ||\n ''\n )\n }\n\n /**\n * Priority 1: Resolve projectId from URL query parameters.\n * Used for design mode and preview mode overrides.\n */\n private resolveFromQueryParams(request: Request): string | null {\n const queries = getRequestQueries<WeaverseStudioQueries>(request)\n return queries.weaverseProjectId || null\n }\n\n /**\n * Priority 2: Resolve projectId from function parameter.\n * Detects and rejects async functions with helpful error.\n */\n private resolveFromFunction(\n projectId: string | (() => string) | (() => Promise<string>) | undefined\n ): string | null {\n if (!isProjectIdFunction(projectId)) {\n return null\n }\n\n // Check if it's an async function BEFORE calling\n if (projectId.constructor.name === 'AsyncFunction') {\n throw new WeaverseError(\n 'Async projectId functions must be awaited before passing to WeaverseClient. ' +\n 'Use: projectId: await getProjectAsync() instead of: projectId: getProjectAsync',\n 'ASYNC_PROJECT_ID'\n )\n }\n\n try {\n const result = projectId()\n\n // Safety net: check if result is a Promise\n if (result instanceof Promise) {\n throw new WeaverseError(\n 'Async projectId functions must be awaited before passing to WeaverseClient. ' +\n 'Use: projectId: await getProjectAsync() instead of: projectId: getProjectAsync',\n 'ASYNC_PROJECT_ID'\n )\n }\n\n if (result && result.trim() !== '') {\n const trimmed = result.trim()\n const validation = this.validateProjectId(trimmed)\n\n if (validation.valid) {\n return trimmed\n }\n\n // Throw on validation failure - fail-fast for explicit projectId\n throw new WeaverseError(\n validation.error || 'Invalid projectId format',\n 'INVALID_PROJECT_ID'\n )\n }\n } catch (err) {\n // Re-throw WeaverseError (async function errors, validation errors)\n if (err instanceof WeaverseError) {\n throw err\n }\n\n // Wrap unexpected errors\n throw new WeaverseError(\n `Failed to evaluate projectId function: ${err instanceof Error ? err.message : String(err)}`,\n 'PROJECT_ID_FUNCTION_ERROR',\n undefined,\n { cause: err instanceof Error ? err.stack : String(err) }\n )\n }\n\n return null\n }\n\n /**\n * Priority 3: Resolve projectId from explicit string parameter.\n */\n private resolveFromString(\n projectId: string | (() => string) | (() => Promise<string>) | undefined\n ): string | null {\n if (typeof projectId !== 'string') {\n return null\n }\n\n const trimmed = projectId.trim()\n if (trimmed === '') {\n return null\n }\n\n const validation = this.validateProjectId(trimmed)\n if (validation.valid) {\n return trimmed\n }\n\n // Throw on validation failure - fail-fast for explicit projectId\n throw new WeaverseError(\n validation.error || 'Invalid projectId format',\n 'INVALID_PROJECT_ID'\n )\n }\n\n /**\n * Priority 4: Resolve projectId from environment variables.\n */\n private resolveFromEnvironment(\n baseConfigs: WeaverseProjectConfigs | undefined,\n request: Request,\n env: HydrogenEnv\n ): string | null {\n const configs = baseConfigs || getWeaverseConfigs(request, env)\n\n if (configs.projectId && configs.projectId.trim() !== '') {\n return configs.projectId.trim()\n }\n\n return null\n }\n\n /**\n * Helper method for direct fetching in design mode.\n * Returns same format as withCache.fetch for consistency.\n * Includes 10-second timeout to prevent hanging requests.\n */\n private readonly fetchOnce = async <T>(\n url: string,\n options: RequestInit,\n timeoutMs: number\n ): Promise<WithCacheFetchResponse<T>> => {\n const controller = new AbortController()\n const timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(\n () => controller.abort(),\n timeoutMs\n )\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new WeaverseError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'FETCH_ERROR',\n response.status,\n { url, errorText }\n )\n }\n\n let data: T\n try {\n data = (await response.json()) as T\n } catch (parseError) {\n // A cut-short body still times out; anything else is a successful\n // status whose body is not JSON, which is not a network failure.\n if (parseError?.name === 'AbortError') {\n throw parseError\n }\n throw new WeaverseError(\n 'Response body is not valid JSON',\n 'INVALID_RESPONSE',\n response.status,\n { url }\n )\n }\n return { data, response }\n } catch (err) {\n if (err instanceof WeaverseError) {\n throw err\n }\n\n if (err.name === 'AbortError') {\n throw new WeaverseError(\n `Request timeout after ${timeoutMs}ms`,\n 'TIMEOUT_ERROR',\n undefined,\n { url, timeoutMs }\n )\n }\n\n throw new WeaverseError(\n 'Network error during fetch',\n 'NETWORK_ERROR',\n undefined,\n { url, cause: err instanceof Error ? err.message : String(err) }\n )\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId)\n }\n }\n }\n\n private readonly directFetch = async <T>(\n url: string,\n options: RequestInit = {},\n timeoutMs = this.fetchTimeoutMs\n ): Promise<WithCacheFetchResponse<T>> => {\n let lastError: unknown\n for (let attempt = 1; attempt <= MAX_FETCH_ATTEMPTS; attempt++) {\n try {\n return await this.fetchOnce<T>(url, options, timeoutMs)\n } catch (err) {\n lastError = err\n if (attempt >= MAX_FETCH_ATTEMPTS || !isRetryableFetchError(err)) {\n throw err\n }\n await new Promise((resolve) =>\n setTimeout(resolve, FETCH_RETRY_BACKOFF_MS * attempt)\n )\n }\n }\n throw lastError\n }\n\n // Helper method for building API URLs consistently\n private getApiUrl(endpoint: string): string {\n const { weaverseApiBase } = this.configs\n return `${weaverseApiBase}/api/public/${endpoint}`\n }\n\n private isExternalPublicApiUrl(url: string): boolean {\n const { weaverseApiBase, weaverseHost } = this.configs\n return (\n weaverseApiBase !== weaverseHost &&\n url.startsWith(`${weaverseApiBase}/api/public/`)\n )\n }\n\n /**\n * Fetch data with caching support for both design mode and production.\n * Uses direct fetch in design mode, Hydrogen's withCache in production.\n * Automatically includes projectId in cache key for multi-project isolation.\n *\n * @param url - The URL to fetch from\n * @param options - Fetch options including optional cache strategy\n * @returns Promise resolving to the fetched data\n *\n * @example\n * ```typescript\n * const data = await weaverse.fetchWithCache<MyData>(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify({ key: 'value' }) }\n * )\n * ```\n */\n public fetchWithCache = async <T = unknown>(\n url: string,\n options: WeaverseFetchWithCacheOptions = {}\n ): Promise<T> => {\n const { cacheTarget, strategy: strategyOverride, ...fetchOptions } = options\n const strategy =\n strategyOverride ||\n CacheCustom(\n cacheTarget\n ? SMART_CACHE_STRATEGIES[cacheTarget]\n : DEFAULT_CACHE_STRATEGY\n )\n\n // Update cache key to include method, body content, and projectId for multi-project isolation\n // Prefix for easier debugging in cache systems\n //\n // The body is omitted only for options objects marked internally (see\n // `bodyFreeCacheRequests`): the storefront origin must reach Builder for\n // hostname attribution, but two domains of one project have to share one\n // entry. Every other caller keeps a body-derived key.\n const cacheKey = [\n 'weaverse-fetch',\n url,\n options.method || 'GET',\n bodyFreeCacheRequests.has(options)\n ? BODY_FREE_CACHE_SENTINEL\n : fetchOptions.body,\n // WeakSet-derived discriminator: this slot cannot be produced by any\n // caller-supplied shape, so no external call can reach the marked\n // identity — even one that happens to send the sentinel string as its\n // body.\n bodyFreeCacheRequests.has(options),\n this.configs.projectId,\n cacheTarget || 'default',\n ]\n let result: WithCacheFetchResponse<T>\n\n // Bypass the shared Hydrogen subrequest cache for design/revision modes\n // and for the Cloudflare public API proxy. The proxy owns freshness with\n // versioned cache keys; keeping Hydrogen's URL/body cache in front would\n // keep serving a stale response even after Builder bumps the proxy's\n // project version.\n const validateBuilderPayload = builderPayloadValidators.get(options)\n\n if (\n this.configs.isDesignMode ||\n this.configs.isRevisionPreview ||\n this.isExternalPublicApiUrl(url)\n ) {\n result = await this.directFetch<T>(url, fetchOptions)\n } else {\n // Use withCache.fetch for better integration with Hydrogen's caching system\n const cachedFetch = this.withCache.fetch(url, fetchOptions, {\n cacheKey,\n cacheStrategy: strategy,\n shouldCacheResponse: (response: any): boolean => {\n // An aborted request never caches: Hydrogen turns a body read cut\n // short by the abort into an empty payload, not an error.\n if (fetchOptions.signal?.aborted) {\n return false\n }\n if (validateBuilderPayload && !validateBuilderPayload(response)) {\n return false\n }\n // Cache any non-error response (for both Weaverse API and third-party APIs)\n return (\n !hasError(response) && response !== null && response !== undefined\n )\n },\n displayName: 'Weaverse API',\n })\n // Only this client's own Builder requests are normalized; a\n // third-party `fetchWithCache` caller keeps the platform error.\n result = (await (validateBuilderPayload\n ? cachedFetch.catch((error: unknown) => {\n throw cachedTransportError(error, url)\n })\n : cachedFetch)) as WithCacheFetchResponse<T>\n\n // Hydrogen resolves a non-2xx status with a `null` body. For this\n // client's own Builder requests that would read as \"nothing published\";\n // surface the status the direct path already throws instead.\n const { response } = result\n if (validateBuilderPayload && response && !response.ok) {\n throw new WeaverseError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'FETCH_ERROR',\n response.status,\n { url }\n )\n }\n }\n\n return result.data\n }\n\n /**\n * Safe origin of the incoming storefront request: scheme, host and explicit\n * port. Userinfo, path, query and fragment are dropped, so no customer\n * route or credential-bearing value leaves the storefront. Returns undefined\n * for a non-http(s) request so the field is simply omitted.\n */\n private safeStorefrontOrigin(): string | undefined {\n const { protocol, host } = this.parsedUrl\n if (protocol !== 'http:' && protocol !== 'https:') {\n return\n }\n return host ? `${protocol}//${host}` : undefined\n }\n\n /**\n * Load theme settings from Weaverse API with fallback to schema defaults.\n * Merges remote settings with local theme schema and handles design mode serialization.\n *\n * @param strategy - Optional cache strategy override\n * @returns Promise resolving to theme settings response\n *\n * @example\n * ```typescript\n * const settings = await weaverse.loadThemeSettings()\n * const primaryColor = settings.theme.colors?.primary\n * ```\n */\n loadThemeSettings = async (\n strategy?: CachingStrategy\n ): Promise<ThemeSettingsResponse> => {\n const defaultThemeSettings = generateDataFromSchema(this.themeSchema)\n try {\n const { configs } = this\n const { projectId, isDesignMode } = configs\n if (!projectId) {\n throw new Error('Missing Weaverse projectId!')\n }\n\n const url = this.getApiUrl('project_configs')\n\n // Theme/config reads carry no route, so Builder could not tell which\n // storefront asked. `storefrontUrl` is the request's safe origin only —\n // scheme, host and explicit port, never a path, query, fragment or\n // userinfo — so hosted-content attribution works without sending\n // customer-visible URL data. Older Builder deployments ignore the extra\n // field. The response does not vary by storefront, so the origin stays\n // out of BOTH cache identities: the edge excludes it from its selectors,\n // and this request is marked in `bodyFreeCacheRequests` so Hydrogen's\n // own subrequest cache key omits the body — hashing it would otherwise\n // give every domain of one project its own entry.\n const body = JSON.stringify({\n isDesignMode,\n projectId,\n storefrontUrl: this.safeStorefrontOrigin(),\n })\n\n // Fetch theme settings and merchant overrides in parallel. The options\n // object is registered in `bodyFreeCacheRequests` so `fetchWithCache`\n // keeps the storefront origin out of the subrequest cache identity for\n // exactly this internal request — see the marker's doc comment.\n const themeSettingsOptions: WeaverseFetchWithCacheOptions = {\n method: 'POST',\n cacheTarget: 'theme-settings',\n strategy,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'Accept-Encoding': 'gzip, deflate, br',\n },\n }\n bodyFreeCacheRequests.add(themeSettingsOptions)\n builderPayloadValidators.set(themeSettingsOptions, isThemeConfigsEnvelope)\n\n const [data, merchantOverrides] = await Promise.all([\n this.fetchWithCache<ThemeSettingsResponse>(url, themeSettingsOptions),\n this.fetchMerchantOverrides(strategy),\n ])\n\n // A body without a `theme` field (corrupted content, an error body, an\n // empty object) is not the merchant's configuration. Report it like any\n // other failure so schema defaults are never presented as loaded.\n if (!isThemeConfigsEnvelope(data)) {\n throw new WeaverseError(\n 'Invalid theme settings response format',\n 'INVALID_RESPONSE'\n )\n }\n\n let result = data\n\n if (this.themeSchema?.settings || this.themeSchema?.inspector) {\n // Ensure result.theme exists and is an object before merging\n if (!result.theme || typeof result.theme !== 'object') {\n result.theme = defaultThemeSettings\n } else {\n result.theme = {\n ...defaultThemeSettings,\n ...result.theme,\n }\n }\n }\n\n // Always include staticContent from themeSchema.i18n\n const staticContent = this.themeSchema?.i18n?.staticContent\n if (staticContent) {\n result.staticContent = staticContent\n }\n\n // Include merchant overrides (locale-specific translations from DB)\n if (merchantOverrides) {\n result.merchantOverrides = merchantOverrides\n }\n\n if (this.configs.isDesignMode) {\n result = {\n ...result,\n schema:\n this.themeSchema && typeof this.themeSchema === 'object'\n ? {\n ...this.themeSchema,\n settings: this.themeSchema?.settings?.map((group) => ({\n ...group,\n inputs: group?.inputs?.map((input) => {\n if (typeof input?.condition === 'function') {\n return {\n ...input,\n condition: input.condition.toString(),\n }\n }\n return input\n }),\n })),\n }\n : undefined,\n publicEnv: this.configs.publicEnv,\n }\n }\n return result\n } catch (error) {\n const errorMessage = 'Unable to load theme settings'\n const errorDetails = this.extractErrorMessage(error)\n\n console.error(errorMessage, errorDetails)\n\n return {\n theme: defaultThemeSettings,\n staticContent: this.themeSchema?.i18n?.staticContent,\n _error: errorDetails,\n _loadFailed: true,\n }\n }\n }\n\n /**\n * Fetch locale-specific merchant overrides from the translation API.\n * Returns a nested JSON object with translated values.\n * Falls back to empty object on error to avoid blocking theme rendering.\n */\n private fetchMerchantOverrides = async (\n strategy?: CachingStrategy\n ): Promise<Record<string, unknown> | undefined> => {\n try {\n const { projectId, weaverseHost } = this.configs\n const i18n = this.storefront.i18n\n\n // Skip entirely when the theme hasn't opted into i18n. Merchant overrides\n // are locale-specific translations; a theme with no `i18n` schema has no\n // translatable surface, so the fetch would always come back empty. Gating\n // here keeps non-i18n storefronts from making a translation API call on\n // every SSR — same `themeSchema.i18n` condition that guards `staticContent`.\n if (!this.themeSchema?.i18n) {\n return\n }\n\n if (!(projectId && weaverseHost)) {\n return\n }\n\n // Build locale code from storefront i18n (e.g. \"en-us\")\n const language = (i18n?.language || 'en').toLowerCase()\n const country = (i18n?.country || 'us').toLowerCase()\n const locale = `${language}-${country}`\n\n const url = `${weaverseHost}/api/translation/static?projectId=${projectId}&locale=${locale}`\n\n // Overrides are optional, and `loadThemeSettings` awaits them next to\n // the main settings. Hydrogen's cached fetch adds no deadline of its\n // own, so bound the request and its body with the client fetch timeout;\n // on abort the catch below falls back to theme defaults. Design and\n // revision modes ignore this signal and keep `directFetch`'s own\n // timeout and retry.\n const overrides = await this.fetchWithCache<Record<string, unknown>>(\n url,\n {\n method: 'GET',\n cacheTarget: 'merchant-overrides',\n strategy,\n headers: {\n Accept: 'application/json',\n },\n signal: AbortSignal.timeout(this.fetchTimeoutMs),\n }\n )\n\n // Validate it's a proper object\n if (typeof overrides === 'object' && overrides !== null) {\n return overrides\n }\n\n return\n } catch (error) {\n // Don't let merchant overrides failure block theme rendering\n console.warn(\n 'Unable to load merchant overrides, using theme defaults:',\n this.extractErrorMessage(error)\n )\n return\n }\n }\n\n /**\n * Generate fallback page with default structure when page data is unavailable.\n * Used internally when API returns no page or when page needs default content.\n *\n * @param message - Custom message to display in the fallback page\n * @returns HydrogenPageData with single main component containing the message\n */\n generateFallbackPage = (message: string): HydrogenPageData => {\n const rootId = crypto.randomUUID()\n return {\n id: `fallback_page_${Date.now()}`,\n rootId,\n name: 'Default Page',\n items: [\n {\n type: 'main',\n id: rootId,\n data: { dangerouslySetInnerHTML: { __html: message } },\n },\n ],\n }\n }\n\n /**\n * Fetch all published custom pages for sitemap generation.\n * Paginates automatically, never throws, returns accumulated results on partial failure.\n */\n async fetchCustomPages(\n opts?: FetchCustomPagesOptions\n ): Promise<CustomPageEntry[]> {\n const { weaverseApiBase, projectId } = this.configs\n const entries: CustomPageEntry[] = []\n const MAX_PAGES = 100\n\n let cursor: string | null = null\n\n for (let i = 0; i < MAX_PAGES; i++) {\n const params = new URLSearchParams()\n if (opts?.locale) {\n params.set('locale', opts.locale)\n }\n if (opts?.limit) {\n params.set('limit', String(opts.limit))\n }\n if (cursor) {\n params.set('cursor', cursor)\n }\n\n const qs = params.toString()\n const url = `${weaverseApiBase}/api/public/v1/projects/${projectId}/custom-pages${qs ? `?${qs}` : ''}`\n\n try {\n const result = await this.fetchWithCache<{\n data: CustomPageEntry[]\n nextCursor: string | null\n }>(url, { cacheTarget: 'custom-pages' })\n entries.push(...(result.data || []))\n\n if (!result.nextCursor) {\n return entries\n }\n cursor = result.nextCursor\n } catch (err: any) {\n const status = err?.status\n const msg = err?.message || String(err)\n console.warn(\n entries.length === 0\n ? `[Weaverse] Failed to fetch custom pages: ${msg}${status ? ` (HTTP ${status})` : ''}`\n : `[Weaverse] Custom pages pagination interrupted: ${msg}`\n )\n return entries\n }\n }\n\n console.warn(\n '[Weaverse] Custom pages pagination cap reached (100 iterations)'\n )\n return entries\n }\n\n /**\n * Load page data from Weaverse API with optional route-level project override.\n * Fetches page content, executes component loaders, and handles empty items fallback.\n *\n * @param params - Optional page loading parameters\n * @param params.type - Page type (INDEX, PAGE, PRODUCT, COLLECTION, etc.)\n * @param params.handle - Page handle for dynamic routes\n * @param params.locale - Locale override\n * @param params.projectId - Route-level project ID override (for multi-project)\n * @param params.strategy - Custom cache strategy override\n * @returns Promise resolving to page data or null on error\n *\n * @example\n * ```typescript\n * // Basic usage\n * const data = await weaverse.loadPage()\n *\n * // With page type\n * const data = await weaverse.loadPage({ type: 'INDEX' })\n *\n * // Route-level project override\n * const data = await weaverse.loadPage({\n * type: 'PAGE',\n * handle: 'about',\n * projectId: 'campaign-project-123'\n * })\n * ```\n */\n loadPage = async (\n params: LoadPageParams = {}\n ): Promise<WeaverseLoaderData | null> => {\n // Validate route-level projectId if provided\n if (params.projectId !== undefined) {\n const message =\n typeof params.projectId === 'string'\n ? this.validateProjectId(params.projectId).error\n : `must be a string. Received: ${typeof params.projectId}`\n if (message) {\n console.error(`Route-level projectId validation failed: ${message}`)\n if (this.throwPageLoadFailures) {\n throw new WeaverseLoadError(\n 'Route-level projectId validation failed',\n 'configuration'\n )\n }\n return null\n }\n }\n\n try {\n const { request, storefront, basePageRequestBody, basePageConfigs } = this\n const {\n projectId: clientProjectId,\n weaverseHost,\n isPreviewMode,\n sectionType,\n } = this.configs\n\n // Override client-level projectId with route-level projectId if provided\n const effectiveProjectId = params.projectId || clientProjectId\n\n if (isPreviewMode) {\n return getPreviewData(sectionType || '', this.components, weaverseHost)\n }\n\n if (!effectiveProjectId) {\n throw new WeaverseLoadError(\n 'Missing Weaverse projectId!',\n 'configuration'\n )\n }\n\n const { strategy, ...pageLoadParams } = params\n const body: {\n projectId: string\n url: string\n i18n?: I18nBase\n params?: {\n type?: PageType\n locale?: string\n handle?: string\n }\n isDesignMode?: boolean\n } = {\n ...basePageRequestBody,\n projectId: effectiveProjectId, // Use effective (potentially overridden) projectId\n params: pageLoadParams,\n // Stripped to pathname + Weaverse params — tracking params would\n // fragment the subrequest cache key (see normalizePageUrl).\n url: normalizePageUrl(request.url),\n }\n\n const reqInit: RequestInit = {\n method: 'POST',\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'X-Visitor-UA': request.headers.get('user-agent') || '',\n },\n }\n const url = this.getApiUrl('project')\n\n const projectOptions: WeaverseFetchWithCacheOptions = {\n ...reqInit,\n cacheTarget: 'project',\n strategy,\n }\n builderPayloadValidators.set(projectOptions, isProjectEnvelope)\n const projectData: FetchProjectPayload =\n await this.fetchWithCache<FetchProjectPayload>(url, projectOptions)\n\n if (hasError(projectData)) {\n throw new WeaverseLoadError(\n 'Weaverse API returned an error body',\n 'invalid-response'\n )\n }\n\n if (!isProjectEnvelope(projectData)) {\n // A body that does not answer for this URL is not \"nothing assigned\n // here\". Without the opt-in, keep the historical fallback page.\n if (this.throwPageLoadFailures) {\n throw new WeaverseLoadError(\n 'Invalid project data structure received from API',\n 'invalid-response'\n )\n }\n console.warn(\n 'Invalid project data structure received from API, using fallback data',\n { projectId: effectiveProjectId }\n )\n }\n\n // Extract what we can; a legacy-mode malformed body may lack any field.\n const responseData = projectData as Partial<FetchProjectPayload> | null\n let page: HydrogenPageData | undefined = responseData?.page ?? undefined\n let project: WeaverseLoaderData['project'] | undefined =\n responseData?.project\n const pageAssignment: WeaverseLoaderData['pageAssignment'] | undefined =\n responseData?.pageAssignment\n\n if (!project) {\n console.warn('Weaverse project not found. Id:', effectiveProjectId)\n project = {\n id: effectiveProjectId,\n name: 'Weaverse project not found.',\n weaverseShopId: '',\n }\n }\n\n if (!page) {\n page = this.generateFallbackPage(\n '<div style=\"text-align: center;\">Please add new section to start.</div>'\n )\n }\n\n if (page?.items?.length === 0) {\n page.items.push({\n type: 'main',\n id: page.rootId || crypto.randomUUID(),\n data: {},\n })\n }\n\n if (page?.items) {\n const items = page.items\n page.items = await Promise.all(items.map(this.execComponentLoader))\n }\n return {\n page,\n project,\n pageAssignment,\n configs: {\n ...basePageConfigs,\n requestInfo: {\n i18n: storefront.i18n,\n queries: getRequestQueries<WeaverseStudioQueries>(request),\n pathname: this.parsedUrl.pathname,\n search: this.parsedUrl.search,\n },\n },\n }\n } catch (error) {\n const failure = classifyPageLoadFailure(error)\n const errorMessage = '❌ Page load failed'\n const errorContext: Record<string, unknown> = {\n projectId: params.projectId || this.configs.projectId,\n }\n\n if (error instanceof WeaverseError) {\n console.error(errorMessage, {\n code: error.code,\n message: error.message,\n ...errorContext,\n ...error.context,\n })\n } else if (error instanceof Error) {\n console.error(errorMessage, {\n message: error.message,\n stack: error.stack,\n ...errorContext,\n })\n } else {\n console.error(errorMessage, {\n error: String(error),\n ...errorContext,\n })\n }\n\n if (failure === 'absent' || !this.throwPageLoadFailures) {\n return null\n }\n if (error instanceof WeaverseLoadError) {\n throw error\n }\n // Fixed message: the cause can carry request-derived detail.\n throw new WeaverseLoadError(\n 'Unable to load Weaverse page',\n failure,\n error instanceof WeaverseError ? error.statusCode : undefined\n )\n }\n }\n\n /** Executes the registered loader for one component and attaches its result. */\n execComponentLoader = async (item: HydrogenComponentData) => {\n const { data = {}, type, id } = item\n const component = this.componentsByType.get(type)\n const loader = component?.loader\n if (typeof loader === 'function' && component) {\n try {\n return {\n ...item,\n loaderData: await Promise.resolve(\n loader({\n data: { ...generateDataFromSchema(component.schema), ...data },\n weaverse: this,\n })\n ),\n }\n } catch (error) {\n console.warn('❌ Item loader run failed.', type, id, error)\n return item\n }\n }\n return item\n }\n}\n","/**\n * React and React Router integrations for rendering Weaverse content in\n * Shopify Hydrogen storefronts.\n *\n * @packageDocumentation\n */\n\nimport { getSelectedProductOptions as hydrogen_getSelectedProductOptions } from '@shopify/hydrogen'\nimport type { SelectedOptionInput } from '@shopify/hydrogen/storefront-api-types'\nimport {\n isBrowser,\n isIframe,\n useChildInstances,\n useItemInstance,\n useParentInstance,\n useWeaverse,\n} from '@weaverse/react'\n\n/**\n * Filter out Weaverse-specific query parameters from product options.\n * Removes `isDesignMode` and any parameters starting with `weaverse` prefix.\n *\n * @param request - The incoming HTTP request\n * @returns Filtered product options for Shopify Hydrogen\n *\n * @example\n * ```typescript\n * export async function loader({ request }: LoaderFunctionArgs) {\n * const selectedOptions = getSelectedProductOptions(request)\n * // Use selectedOptions for product queries without Weaverse params\n * }\n * ```\n */\nexport function getSelectedProductOptions(\n request: Request\n): SelectedOptionInput[] {\n let options = hydrogen_getSelectedProductOptions(request)\n return options.filter(\n ({ name }) => name !== 'isDesignMode' && !name.startsWith('weaverse')\n )\n}\n\n// Re-export all types and utilities from schema package\nexport * from '@weaverse/schema'\nexport * from './components'\nexport {\n getNestedKey,\n interpolate,\n // Deprecated aliases — kept for backward compatibility.\n ThemeTextProvider,\n type ThemeTextProviderProps,\n type ThemeTextValue,\n type TranslateFunction,\n // Canonical translation API.\n TranslationProvider,\n type TranslationProviderProps,\n type TranslationValue,\n useThemeText,\n useTranslation,\n} from './hooks/translation-context'\n// Export Hydrogen-specific hooks\nexport {\n createWeaverseDataContext,\n type RouteKeyedDataContext,\n useWeaverseDataContext,\n type WeaverseDataContext,\n} from './hooks/use-weaverse-data-context'\n// Export hydrogen-specific modules\nexport * from './seo'\nexport * from './types'\nexport * from './utils'\nexport type { WeaverseDataValue } from './utils/pick-weaverse-data'\nexport { ThemeTextStore, TranslationStore } from './utils/translation-store'\nexport type {\n ThemeSettingsStore,\n WeaverseThemeData,\n} from './utils/use-theme-settings-store'\nexport * from './WeaverseHydrogenRoot'\nexport * from './weaverse-client'\n// Re-export utilities from @weaverse/react\nexport {\n isBrowser,\n isIframe,\n useChildInstances,\n useItemInstance,\n useParentInstance,\n useWeaverse,\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,KAAK,OAAgE;CAC5E,IAAI,EAAE,UAAU,yBAAyB,GAAG,SAAS;CAErD,OACE,iBAAA,GAAA,kBAAA,KAAC,OAAD;EACE,GAAI;EAEM;EAEV,yBAAyB,WAAW,KAAA,IAAY;CACjD,CAAA;AAEL;;;;AChBA,IAAW,oBAAyC,CAClD;CACE,SAASA;CACDC,SDiBD,GAAA,iBAAA,cAAkC;EAC3C,MAAM;EACN,OAAO;CACT,CCpBYA;AACV,CACF;;;;;;;;;;ACEA,SAAgB,aACd,KACA,MACA,UACoB;CACpB,MAAM,OAAO,KAAK,MAAM,GAAG;CAC3B,IAAI,UAAmB;CAEvB,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,WAAW,QAAQ,OAAO,YAAY,UACxC,OAAO;EAET,UAAW,QAAoC;CACjD;CAEA,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO;AACT;;;;;;;;AASA,SAAgB,YACd,UACA,WACQ;CACR,IAAI,CAAC,WACH,OAAO;CAGT,OAAO,SAAS,QAAQ,mBAAmB,OAAO,QAAgB;EAChE,MAAM,QAAQ,UAAU;EACxB,OAAO,UAAU,KAAA,IAAY,QAAQ,OAAO,KAAK;CACnD,CAAC;AACH;AAyCA,MAAM,sBA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