Inicialización de la aplicación
Application Load · React
Application Load es la primera solicitud que tu tienda hace a su backend personal. Devuelve los ajustes y el contenido inicial necesarios para mostrar la interfaz, el perfil del cliente actual cuando ha iniciado sesión y los métodos de la API disponibles en esta sesión.
/api/apploadQué contiene la respuesta
page_data — los datos de la aplicación dentro de la respuesta de la API. Sus cuatro secciones principales tienen funciones distintas:
Datos iniciales de la tienda, perfil del cliente y endpoints de la API disponibles.
interfaces/basklee/appBase/IAppLoad.tsimport type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon';
import type { IApploadUserProfile } from '@/interfaces/basklee/appBase/IApploadUserProfile';
import type { IAppLoadPathsRecord } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonPath';
export interface IAppLoad {
// Ajustes compartidos de la tienda y datos iniciales.
init: IAppLoadCommon;
// Métodos públicos de la API, agrupados en paths.
unauth: IAppLoadPathsRecord;
// Perfil del cliente actual. Se omite para los invitados.
user?: IApploadUserProfile;
// Métodos de la sesión autenticada. Se omiten para los invitados; el backend
// comprueba los permisos.
auth?: IAppLoadPathsRecord;
// Si las funciones del panel del vendedor están activadas en esta tienda.
seller_panel_enabled?: boolean;
// Clave de vista previa de productos para una cuenta con sesión iniciada y
// datos de vendedor.
// No publiques su valor; las interfaces para compradores no necesitan esta
// clave.
view_key?: string;
// Tiempo que tarda el backend en preparar Application Load, en segundos; solo
// con la depuración del proyecto activada.
// No incluye la serialización de la respuesta ni la transferencia por la red.
spent_total?: number;
// Tiempo de carga de init en el backend, en segundos. Solo con la depuración
// del proyecto activada.
spent_init?: number;
// Tiempo de carga del descubrimiento de la API pública, en segundos. Solo con
// la depuración del proyecto activada.
unauth_spent?: number;
// Tiempo de preparación del perfil y de auth, en segundos. Solo en depuración;
// cero para los invitados.
auth_spent?: number;
}
Qué construir con init
Cada campo enlaza con su referencia de datos, sus consumidores reales y las guías de componentes relacionadas.
page_data.init/api/apploadIdioma, monedas y unidades
Idiomas, monedas y unidades de medida, con nombres, formatos de visualización y valores predeterminados para cada idioma.
localeuseBasklee(selectLocales)MainLanguageSwitcherselecciona el idioma; la tienda aplica su moneda y sus unidades predeterminadas a las selecciones actuales.currenciesuseBasklee(selectCurrencies)Opciones de moneda que lee
MainCurrencySwitcher.weightsuseBasklee(selectInit)?.weightsOpciones de unidad de peso que lee
UnitSwitcher.lengthsuseBasklee(selectInit)?.lengthsOpciones de unidad de longitud que lee
UnitSwitcher.shipping_countriesuseBasklee(selectInit)?.shipping_countriesLos países de envío de la tienda, nombrados en las condiciones de devolución de las páginas de producto.
Catálogo y búsqueda
Categorías, colecciones iniciales de productos, sugerencias de búsqueda y planes de suscripción.
cataloguseBasklee(selectCatalog)Árbol de categorías que usan
CatalogHeaderyCategoryGroup.productsuseBasklee(selectProducts)Productos iniciales que leen
ProductGroup,ProductCardy componentes de producto comoHoverImageViewer.featureduseBasklee(selectInit)?.featuredRecomendaciones personalizadas según búsquedas y categorías anteriores. Los componentes de producto las leen con
collection="featured".sellersuseBasklee(selectInit)?.sellersDatos de los vendedores indexados por ID. Cada producto de Application Load identifica a su vendedor con
seller_id; el store de productos resuelve esa referencia cuando los componentes leen el producto.search_hintsuseBasklee(selectInit)?.search_hintsSugerencias localizadas que muestra
MainSearch.tariffsuseBasklee(selectTariffs)Colección de planes que lee
TariffCardspara mostrar componentesTariffCardindividuales.
Marca y metadatos de la página
Logotipos, el icono del sitio, los ajustes de visualización de la tienda y los metadatos SEO.
logosuseBasklee(selectInit)?.logosBrandLogosmuestra el tamaño de logotipo o el icono seleccionado.visual_settingsuseBasklee(selectInit)?.visual_settingsImágenes de las categorías del menú, número y orden de las categorías de inicio y otros ajustes de visualización de la tienda.
seouseBasklee(selectInit)?.seogetStorefrontSeo()prepara los metadatos deapp/pages/index.vue: el título, la descripción y las palabras clave usanuseSeoMeta(), y las etiquetas adicionales usanuseHead().
Contenido y contactos
Banners, eventos de la tienda, contactos de la empresa y enlaces sociales.
main_banneruseBasklee(selectInit)?.main_bannerImágenes de banners que muestra
MainBanneren el idioma actual de la tienda.eventsuseBasklee(selectInit)?.eventsImágenes de eventos que muestra
EventsBlock, filtradas por idioma y poris_layout.contactuseBasklee(selectInit)?.contactContactos y datos de registro de la empresa que muestra
AboutPage.smuseBasklee(selectInit)?.smEnlaces sociales y textos localizados que muestra
SocialLinks.
Cliente y contadores
Estado de autenticación, saldo del monedero y contadores iniciales del carrito y de favoritos. El carrito completo y los datos de la cuenta se obtienen con endpoints de la API aparte.
is_authenticateduseBasklee(selectIsAuthenticated)store.isAuthenticatedcontrola el descubrimiento autenticado y cambiaStorefrontAccountentre Iniciar sesión y el menú de perfil y monedero.walletuseBasklee(selectInit)?.walletWalletBalancemuestra el saldo en la moneda seleccionada, también en el modo compacto deStorefrontAccount.variablesuseBasklee(selectInit)?.variablesContadores iniciales de los botones del carrito y de favoritos, permiso de reserva y estados de contenido predeterminados.
Mapas e integraciones
Centro del mapa, clave pública del mapa y disponibilidad de la búsqueda de direcciones por coordenadas.
default_mapuseBasklee(selectInit)?.default_mapCoordenadas del centro del mapa predeterminadas.
geo_location_enableduseBasklee(selectInit)?.geo_location_enabledIndica si está disponible la búsqueda de direcciones por coordenadas. Las sugerencias de texto dependen del país seleccionado.
public_keysuseBasklee(selectInit)?.public_keysmap_keycarga Yandex Maps para el mapa de entrega del carrito.
Los campos dependen de los ajustes de la tienda y de la sesión actual. Un campo puede faltar o una colección estar vacía. Los productos iniciales no sustituyen a un catálogo completo y paginado.
Cómo llegan los datos a los componentes
useBasklee(selector)- Suscribe un componente a la parte elegida del estado y lo vuelve a renderizar solo cuando cambia esa parte.
useBaskleeStore()- El propio store: para acciones y lecturas puntuales fuera del renderizado (
getState()). selectResult- El resultado completo de la solicitud: el estado HTTP y la respuesta del servidor.
selectData- El objeto
page_datade la respuesta. selectInit- Los datos iniciales
page_data.init;nullhasta que termina una carga. selectProfile- El perfil del cliente tras iniciar sesión; si no,
null. selectStatus · selectIsReady · selectFailure- El estado de la carga: en curso, lista o un fallo con su tipo y sus campos.
proxy.tsEl proxy de Next.js pasa la dirección de la página abierta al renderizado en el servidor y mantiene las páginas personales fuera de las cachés.
Código fuente
import { NextResponse, type NextRequest } from 'next/server'; import { marketplaceNoindexPath } from '@basklee-runtime/marketplace.mjs'; import { APP_LOAD_HANDOFF_HEADER, startAppLoad, } from '@/lib/basklee/appLoadServer'; /** * A full page load: not an in-app navigation (`RSC`), a prefetch or a public * file such as an image. */ function pageLoad(request: NextRequest) { const accept = request.headers.get('accept') ?? ''; return ( request.method === 'GET' && !request.headers.has('rsc') && !request.headers.has('next-router-prefetch') && !/\.[a-z0-9]+$/i.test(request.nextUrl.pathname) && (!accept || accept.includes('text/html') || accept.includes('*/*')) ); } /** * Personalized pages are never shared between visitors or storefront domains. * Next.js manages its own `Vary` header for pages; the API gateway sets the * storefront-domain `Vary` on its own responses. * * A full page load starts Application Load here and hands it to the render: * when it fails, the error page answers HTTP 503 like the Nuxt and SvelteKit * starters (an unknown address keeps its 404). */ export async function proxy(request: NextRequest) { const forwarded = new Headers(request.headers); // Only this proxy names a started load; a visitor cannot pick one. forwarded.delete(APP_LOAD_HANDOFF_HEADER); forwarded.set( 'x-basklee-page-url', request.nextUrl.pathname + request.nextUrl.search, ); let unavailable = false; if (pageLoad(request)) { const { id, load } = startAppLoad(forwarded); forwarded.set(APP_LOAD_HANDOFF_HEADER, id); unavailable = Boolean((await load).failure); } const response = NextResponse.next({ request: { headers: forwarded }, ...(unavailable ? { status: 503 } : {}), }); response.headers.set('Cache-Control', 'private, no-store'); // Pages under BASKLEE_NOINDEX_PATHS stay out of search engines. if (marketplaceNoindexPath(request.nextUrl.pathname)) { response.headers.set('X-Robots-Tag', 'noindex, follow'); } return response; } // The gateway sets its own headers for /api, /ps3 media, robots.txt and the // sitemap (public blog images keep the backend's browser cache rule); static // assets keep their caching. export const config = { matcher: ['/((?!api/|ps3/|_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)'], };app/api/[...basklee]/route.tsLa pasarela: cada solicitud del navegador a
/api/...va desde aquí a la API de tu marketplace con el dominio del escaparate y las cookies de sesión.Código fuente
// Every browser request to /api/... reaches your personal marketplace API here. import { forwardMarketplace } from '@basklee-runtime/marketplace.mjs'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; function handler(request: Request): Promise<Response> { return forwardMarketplace(request, { mimicFrontDomain: process.env.MIMIC_FRONT_DOMAIN ?? '', }); } export { handler as GET, handler as HEAD, handler as OPTIONS, handler as POST, handler as PUT, handler as PATCH, handler as DELETE, };lib/basklee/appLoadServer.tsgetBaskleeAppLoad()llama a la misma pasarela en el servidor, una vez por renderizado. Un fallo no se lanza; va al store.Código fuente
import { cache } from 'react'; import { headers } from 'next/headers'; import { forwardMarketplace } from '@basklee-runtime/marketplace.mjs'; import { appLoadRejectedLocale, appLoadResult, inspectAppLoad, } from '@/lib/basklee/appLoadResult'; import type { AppLoadFailure, AppLoadRequest, AppLoadResult, } from '@/interfaces/basklee/transport'; /** Server-side bootstrap. Never import this module from a client component. */ export interface ServerAppLoad { result: AppLoadResult | null; failure: AppLoadFailure | null; /** Raw backend `Set-Cookie` headers; only a route handler or server action may relay them. */ cookies: string[]; } /** Headers a server render forwards to the marketplace gateway. */ const FORWARDED = [ 'cookie', 'x-front-domain', 'x-forwarded-host', 'x-forwarded-proto', 'host', 'accept-language', 'user-agent', 'x-init-ip', 'x-real-ip', 'x-forwarded-for', 'cf-connecting-ip', 'x-tz', ]; /** Header the proxy sets on a page request whose Application Load it started. */ export const APP_LOAD_HANDOFF_HEADER = 'x-basklee-appload'; /** How long a started Application Load waits for the layout to take it. */ const HANDOFF_TTL = 60_000; const HANDOFF_KEY = Symbol.for('basklee.appLoadHandoff'); /** * Started loads by id. Kept on `globalThis`: the proxy and the page render run * in the same Node process but in separate bundles. */ function handoffs(): Map<string, Promise<ServerAppLoad>> { const scope = globalThis as typeof globalThis & { [HANDOFF_KEY]?: Map<string, Promise<ServerAppLoad>>; }; scope[HANDOFF_KEY] ??= new Map(); return scope[HANDOFF_KEY]; } function buildRequest( incoming: Headers, signal: AbortSignal, withLocale = true, ): Request { const host = incoming.get('x-forwarded-host') || incoming.get('host') || 'localhost'; const protocol = incoming.get('x-forwarded-proto')?.split(',')[0]?.trim() || 'https'; const url = new URL('/api/appload', `${protocol}://${host}`); const pageUrl = new URL( incoming.get('x-basklee-page-url') || '/', url.origin, ); const locale = withLocale ? pageUrl.searchParams.get('locale') : null; if (locale) { url.searchParams.set('lang', locale); } const forward = new Headers(); for (const name of FORWARDED) { const value = incoming.get(name); if (value) { forward.set(name, value); } } forward.set('accept', 'application/json'); forward.set('content-type', 'application/json'); // Same-origin server request: the gateway rejects cross-site mutations by Origin. forward.set('origin', url.origin); return new Request(url, { method: 'POST', headers: forward, body: JSON.stringify({ detalize_mode: 'light', ignore_cache: false, } satisfies AppLoadRequest), signal, }); } /** * Calls the same gateway the browser uses, in process, with this request's domain * and session. It never throws: the failure is stored for the interface to handle. */ export async function requestAppLoad( signal?: AbortSignal, incoming?: Headers, withLocale = true, ): Promise<ServerAppLoad> { const timeout = AbortSignal.timeout(35_000); const combined = signal ? AbortSignal.any([signal, timeout]) : timeout; let response: Response; let source: Headers; let request: Request; try { source = incoming ?? new Headers(await headers()); request = buildRequest(source, combined, withLocale); response = await forwardMarketplace(request, { mimicFrontDomain: process.env.MIMIC_FRONT_DOMAIN ?? '', }); } catch { return { result: null, failure: { kind: 'network', httpStatus: null, fields: [] }, cookies: [], }; } const cookies = response.headers.getSetCookie(); let body: unknown = null; try { body = await response.json(); } catch { body = null; } const failure = inspectAppLoad(body, response.status); // An address with a language the storefront does not have (`?locale=xx`) // opens in the storefront's default language instead of the 503 page. if ( failure && new URL(request.url).searchParams.has('lang') && appLoadRejectedLocale(failure) ) { return requestAppLoad(signal, source, false); } if (failure) { return { result: null, failure, cookies }; } return { result: appLoadResult(body, response.status), failure: null, cookies, }; } /** * Starts Application Load for a page request in `proxy.ts`, before the page * renders, so a failure can answer HTTP 503 (a page cannot change its status * once it streams). Returns the id to pass in `APP_LOAD_HANDOFF_HEADER`; the * render takes the same result, so the page still costs one request. */ export function startAppLoad(incoming: Headers): { id: string; load: Promise<ServerAppLoad>; } { const id = crypto.randomUUID(); const load = requestAppLoad(undefined, incoming); const store = handoffs(); store.set(id, load); setTimeout(() => store.delete(id), HANDOFF_TTL).unref?.(); return { id, load }; } /** * One request per server render, shared by the layout and any server component * that awaits it. Reading it in a layout initializes the marketplace before the * page renders; it never opens an authentication prompt. A load the proxy * started for this request is taken once; otherwise the render requests it. */ export const getBaskleeAppLoad = cache(async (): Promise<ServerAppLoad> => { const incoming = await headers(); const id = incoming.get(APP_LOAD_HANDOFF_HEADER); const started = id ? handoffs().get(id) : undefined; if (id && started) { handoffs().delete(id); return started; } return requestAppLoad(undefined, new Headers(incoming)); });app/layout.tsxEl diseño raíz espera a Application Load antes de que se renderice la página y pasa el resultado a
BaskleeProvider.Código fuente
import type { Metadata } from 'next'; import type { ReactNode } from 'react'; import { BaskleeProvider } from '@/providers/BaskleeProvider'; import { getBaskleeAppLoad } from '@/lib/basklee/appLoadServer'; import { StorefrontShell } from '@/app/StorefrontShell'; import { getBaskleeServerLocale } from '@/lib/basklee/serverLocale'; import { getStorefrontMetadata, getStorefrontMetadataContext, } from '@/lib/basklee/serverMetadata'; import '@/app/globals.css'; export async function generateMetadata(): Promise<Metadata> { return getStorefrontMetadata(); } // Initialization depends on the request domain and session, so pages are dynamic. export const dynamic = 'force-dynamic'; export default async function RootLayout({ children, }: { children: ReactNode; }) { // Bootstrap precedes page rendering. Failures stay in the store for the interface to handle. const { result, failure } = await getBaskleeAppLoad(); const language = await getBaskleeServerLocale(); const { tags, jsonLd } = await getStorefrontMetadataContext(); return ( <html lang={language}> <head> {tags.map((tag, index) => 'property' in tag ? ( <meta key={index} property={tag.property} content={tag.content} /> ) : ( <meta key={index} name={tag.name} content={tag.content} /> ), )} {jsonLd ? ( <script type="application/ld+json" // Escaped by structuredDataJson, so the text cannot close the tag. dangerouslySetInnerHTML={{ __html: jsonLd }} /> ) : null} </head> <body> <BaskleeProvider result={result} failure={failure} locale={language} > <StorefrontShell>{children}</StorefrontShell> </BaskleeProvider> </body> </html> ); }providers/BaskleeProvider.tsxCrea el store una vez por sesión del navegador y aporta
useBasklee,useBaskleeStorey los hooks de los stores relacionados.Código fuente
'use client'; import { createContext, useContext, useRef, useEffect, type ReactNode, } from 'react'; import { useStore } from 'zustand'; import { type BaskleeState, type BaskleeStore, } from '@/stores/basklee'; import { type BaskleeSelectionsState, type BaskleeSelectionsStore, } from '@/stores/baskleeSelections'; import { type BaskleeProductsState, type BaskleeProductsStore, } from '@/stores/baskleeProducts'; import { type BaskleeCatalogState, type BaskleeCatalogStore, createBaskleeCatalogStore, } from '@/stores/baskleeCatalog'; import { type BaskleeBrowseState, type BaskleeBrowseStore, } from '@/stores/baskleeBrowse'; import { createBaskleeStores, type BaskleeStores, } from '@/stores/baskleeScope'; import type { AppLoadFailure, AppLoadResult } from '@/interfaces/basklee'; import type { IAppLoadCommon } from '@/interfaces/basklee/appBase/IAppLoadCommon'; import { selectInit } from '@/stores/basklee'; const BaskleeContext = createContext<BaskleeStore | null>(null); const SelectionsContext = createContext<BaskleeSelectionsStore | null>(null); const ProductsContext = createContext<BaskleeProductsStore | null>(null); const CatalogContext = createContext<BaskleeCatalogStore | null>(null); const BrowseContext = createContext<BaskleeBrowseStore | null>(null); export interface BaskleeProviderProps { /** The server render's snapshot. Hydration reuses it instead of loading again. */ result?: AppLoadResult | null; failure?: AppLoadFailure | null; locale?: string; children: ReactNode; } /** Creates one store for this browser session and keeps it across re-renders. */ export function BaskleeProvider({ result = null, failure = null, locale, children, }: BaskleeProviderProps) { const stores = useRef<BaskleeStores>(null); if (!stores.current) { stores.current = createBaskleeStores(result, failure, locale); } const current = stores.current; return ( <BaskleeContext.Provider value={current.store}> <SelectionsContext.Provider value={current.selections}> <ProductsContext.Provider value={current.products}> <CatalogContext.Provider value={current.catalog}> <BrowseContext.Provider value={current.browse}> {children} </BrowseContext.Provider> </CatalogContext.Provider> </ProductsContext.Provider> </SelectionsContext.Provider> </BaskleeContext.Provider> ); } export function BaskleeCatalogSnapshotProvider({ snapshot, children, }: { snapshot?: NonNullable<IAppLoadCommon['tariffs']>; children: ReactNode; }) { const init = useBasklee(selectInit); const parent = useBaskleeCatalogStore(); const catalog = useRef<BaskleeCatalogStore | null>(null); if (!catalog.current) { catalog.current = createBaskleeCatalogStore(init); if (snapshot) { catalog.current.getState().setTariffs(snapshot); } } const current = catalog.current; useEffect(() => { current.getState().reconcile(init); if (snapshot) { current.getState().setTariffs(snapshot); } }, [current, init, snapshot]); return ( <CatalogContext.Provider value={snapshot ? current : parent}> {children} </CatalogContext.Provider> ); } function useStoreApi(): BaskleeStore { const store = useContext(BaskleeContext); if (!store) { throw new Error('Render this component inside <BaskleeProvider>.'); } return store; } /** Subscribes to one selected part of the marketplace state. */ export function useBasklee<T>(selector: (state: BaskleeState) => T): T { return useStore(useStoreApi(), selector); } /** The store itself, for actions and one-off reads outside render. */ export const useBaskleeStore = useStoreApi; function useSelectionsStoreApi(): BaskleeSelectionsStore { const store = useContext(SelectionsContext); if (!store) { throw new Error('Render this component inside <BaskleeProvider>.'); } return store; } export function useBaskleeSelections<T>( selector: (state: BaskleeSelectionsState) => T, ): T { return useStore(useSelectionsStoreApi(), selector); } export const useBaskleeSelectionsStore = useSelectionsStoreApi; function useProductsStoreApi(): BaskleeProductsStore { const store = useContext(ProductsContext); if (!store) { throw new Error('Render this component inside <BaskleeProvider>.'); } return store; } export function useBaskleeProducts<T>( selector: (state: BaskleeProductsState) => T, ): T { return useStore(useProductsStoreApi(), selector); } export const useBaskleeProductsStore = useProductsStoreApi; function useCatalogStoreApi(): BaskleeCatalogStore { const store = useContext(CatalogContext); if (!store) { throw new Error('Render this component inside <BaskleeProvider>.'); } return store; } export function useBaskleeCatalog<T>( selector: (state: BaskleeCatalogState) => T, ): T { return useStore(useCatalogStoreApi(), selector); } export const useBaskleeCatalogStore = useCatalogStoreApi; function useBrowseStoreApi(): BaskleeBrowseStore { const store = useContext(BrowseContext); if (!store) { throw new Error('Render this component inside <BaskleeProvider>.'); } return store; } export function useBaskleeBrowse<T>( selector: (state: BaskleeBrowseState) => T, ): T { return useStore(useBrowseStoreApi(), selector); } export const useBaskleeBrowseStore = useBrowseStoreApi;stores/basklee.tsEl store con la respuesta y los selectores de sus partes:
selectInit,selectCurrencies,selectProductsy más.Código fuente
import { createStore } from 'zustand/vanilla'; import type { AppLoadFailure, AppLoadLoader, AppLoadResult, AppLoadStatus, IAppLoad, IAppLoadCommon, IAppLoadCommonCurrency, IAppLoadCommonLocale, IAppLoadCommonTariff, IAppLoadPath, IAppLoadPathObject, IApploadUserProfile, ICategory, IProduct, } from '@/interfaces/basklee'; import { appLoadFailure } from '@/lib/basklee/appLoadResult'; import { resolveAppLoadProducts } from '@/lib/basklee/productSeller'; import { guestAppLoadResult } from '@/lib/basklee/guestSession'; /** Shared empty values keep selector results referentially stable between renders. */ const EMPTY_RECORD = Object.freeze({}) as Record<string, never>; const EMPTY_LIST = Object.freeze([]) as readonly never[]; const EMPTY_PATHS = Object.freeze({}) as IAppLoadPathObject; export interface BaskleeSnapshot { result: AppLoadResult | null; status: AppLoadStatus; failure: AppLoadFailure | null; endpoints: IAppLoadPathObject; } export interface BaskleeState extends BaskleeSnapshot { load: ( loader: AppLoadLoader, force?: boolean, preserve?: boolean, ) => Promise<void>; endSession: (loader: AppLoadLoader) => Promise<void>; patchProfile: (patch: Partial<IApploadUserProfile>) => void; patchWallet: (wallet: NonNullable<IAppLoadCommon['wallet']>) => void; reset: () => void; } export type BaskleeStore = ReturnType<typeof createBaskleeStore>; /** Public and authenticated discovery are merged once per snapshot, without mutating the response. */ function mergeEndpoints(result: AppLoadResult | null): IAppLoadPathObject { const page = result?.response.page_data; if (!page) { return EMPTY_PATHS; } const groups: IAppLoadPathObject[] = [page.unauth.paths]; if (page.init.is_authenticated && page.auth) { groups.push(page.auth.paths); } const merged: IAppLoadPathObject = {}; for (const group of groups) { for (const [section, paths] of Object.entries(group)) { merged[section] = { ...merged[section], ...paths }; } } return merged; } /** Builds the hydration snapshot from a server render, without repeating the request. */ export function initialSnapshot( result: AppLoadResult | null = null, failure: AppLoadFailure | null = null, ): BaskleeSnapshot { return { result: failure ? null : result, status: failure ? 'error' : result ? 'success' : 'idle', failure, endpoints: failure ? EMPTY_PATHS : mergeEndpoints(result), }; } /** * One store instance per server render and one per browser session. * Creating the store never starts a request; the loaders are passed to `load`. */ export function createBaskleeStore( snapshot: BaskleeSnapshot = initialSnapshot(), ) { // These belong to this store instance, never serialized state or a module-level cache. let pending: Promise<void> | null = null; let controller: AbortController | null = null; let generation = 0; return createStore<BaskleeState>()((set, get) => ({ ...snapshot, patchProfile(patch) { set((state) => { const page = state.result?.response.page_data; if (!state.result || !page?.user) { return {}; } return { result: { ...state.result, response: { ...state.result.response, page_data: { ...page, user: { ...page.user, ...patch }, }, }, }, }; }); }, // A purchase changes only the balance: it is replaced in place, without // an Application Load that would unmount the page and its confirmation. patchWallet(wallet) { set((state) => { const page = state.result?.response.page_data; if (!state.result || !page?.init?.is_authenticated) { return {}; } return { result: { ...state.result, response: { ...state.result.response, page_data: { ...page, init: { ...page.init, wallet }, }, }, }, }; }); }, reset() { generation++; controller?.abort(); controller = null; pending = null; set({ result: null, failure: null, status: 'idle', endpoints: EMPTY_PATHS, }); }, endSession(loader) { const result = get().result; if (!result?.response.page_data.init.is_authenticated) { return pending ?? Promise.resolve(); } generation++; controller?.abort(); controller = null; pending = null; const guest = guestAppLoadResult(result); set({ result: guest, endpoints: mergeEndpoints(guest) }); return get().load(loader, true, true); }, load( loader: AppLoadLoader, force = false, preserve = false, ): Promise<void> { if (pending) { return pending; } // Reuse both server success and failure after hydration or navigation; retry is explicit. if (!force && get().status !== 'idle') { return Promise.resolve(); } const current = ++generation; controller = new AbortController(); const signal = controller.signal; if (!preserve) { set({ result: null, failure: null, status: 'pending', endpoints: EMPTY_PATHS, }); } pending = Promise.resolve() .then(() => loader(signal)) .then((result) => { if (current !== generation) { return; } set({ result, failure: null, status: 'success', endpoints: mergeEndpoints(result), }); }) .catch((error: unknown) => { if (current !== generation) { return; } set({ result: null, endpoints: EMPTY_PATHS, failure: appLoadFailure(error), status: 'error', }); }) .finally(() => { if (current !== generation) { return; } pending = null; controller = null; }); return pending; }, })); } export const selectIsReady = (state: BaskleeSnapshot): boolean => state.status === 'success' && state.result !== null; export const selectStatus = (state: BaskleeSnapshot): AppLoadStatus => state.status; export const selectFailure = ( state: BaskleeSnapshot, ): AppLoadFailure | null => state.failure; export const selectResult = (state: BaskleeSnapshot): AppLoadResult | null => state.result; export const selectData = (state: BaskleeSnapshot): IAppLoad | null => state.result?.response.page_data ?? null; export const selectInit = (state: BaskleeSnapshot): IAppLoadCommon | null => selectData(state)?.init ?? null; export const selectProfile = ( state: BaskleeSnapshot, ): IApploadUserProfile | null => selectData(state)?.user ?? null; export const selectIsAuthenticated = (state: BaskleeSnapshot): boolean => selectInit(state)?.is_authenticated ?? false; export const selectLocales = ( state: BaskleeSnapshot, ): Record<string, IAppLoadCommonLocale> => selectInit(state)?.locale ?? EMPTY_RECORD; export const selectCurrencies = ( state: BaskleeSnapshot, ): Record<string, IAppLoadCommonCurrency> => selectInit(state)?.currencies ?? EMPTY_RECORD; export const selectCatalog = ( state: BaskleeSnapshot, ): readonly ICategory[] => selectInit(state)?.catalog ?? EMPTY_LIST; export const selectProducts = ( state: BaskleeSnapshot, ): readonly IProduct[] => { const init = selectInit(state); return init ? resolveAppLoadProducts(init.products, init.sellers) : EMPTY_LIST; }; export const selectTariffs = ( state: BaskleeSnapshot, ): IAppLoadCommonTariff | null => selectInit(state)?.tariffs ?? null; export const selectPublicEndpoints = ( state: BaskleeSnapshot, ): IAppLoadPathObject => selectData(state)?.unauth.paths ?? EMPTY_PATHS; export const selectEndpoints = ( state: BaskleeSnapshot, ): IAppLoadPathObject => state.endpoints; export const selectAuthenticatedEndpoints = ( state: BaskleeSnapshot, ): IAppLoadPathObject => selectIsAuthenticated(state) ? (selectData(state)?.auth?.paths ?? EMPTY_PATHS) : EMPTY_PATHS; /** Live discovery describes availability; the backend still checks permissions on every call. */ export const selectEndpoint = (section: string, name: string) => (state: BaskleeSnapshot): IAppLoadPath | undefined => state.endpoints[section]?.[name];stores/baskleeSelections.tsLas elecciones del visitante: idioma, moneda y unidades de peso y longitud.
Código fuente
import { createStore } from 'zustand/vanilla'; import type { IAppLoadCommon } from '@/interfaces/basklee'; export interface BaskleeSelectionsState { localeCode: string; currencyId: string; weightId: string; lengthId: string; init: IAppLoadCommon | null; setLocale: (code: string) => void; setCurrency: (id: string) => void; setUnit: (kind: 'weights' | 'lengths', id: string) => void; reconcile: (init: IAppLoadCommon | null) => void; reset: () => void; } export type BaskleeSelectionsStore = ReturnType< typeof createBaskleeSelectionsStore >; function findLocale(init: IAppLoadCommon, code: string) { return Object.entries(init.locale).find( ([key, value]) => (value.code?.trim() || key).toLowerCase() === code.trim().toLowerCase(), ); } function unitId(values: Record<string, unknown>, preferred?: number | string) { const id = String(preferred ?? ''); return Object.hasOwn(values, id) ? id : (Object.keys(values)[0] ?? ''); } function availableCurrency(init: IAppLoadCommon, preferred?: number | string) { const id = String(preferred ?? ''); if (init.currencies[id]?.allowed_select) { return id; } return Object.keys(init.currencies).find( (key) => init.currencies[key]?.allowed_select, ) ?? ''; } export function initialSelections(init: IAppLoadCommon | null, locale = '') { const selected = init ? findLocale(init, locale) ?? Object.entries(init.locale)[0] : undefined; return { localeCode: selected?.[1].code?.trim() || selected?.[0] || '', currencyId: init ? availableCurrency(init, selected?.[1].currency) : '', weightId: init ? unitId(init.weights ?? {}, selected?.[1].weight) : '', lengthId: init ? unitId(init.lengths ?? {}, selected?.[1].length) : '', }; } /** One customer's choices; created per server render and browser session. */ export function createBaskleeSelectionsStore( init: IAppLoadCommon | null = null, locale = '', ) { return createStore<BaskleeSelectionsState>()((set, get) => ({ ...initialSelections(init, locale), init, setLocale(code) { const current = get().init; const entry = current && findLocale(current, code); if (!current || !entry) { return; } set({ localeCode: entry[1].code?.trim() || entry[0], currencyId: availableCurrency(current, entry[1].currency), weightId: unitId(current.weights ?? {}, entry[1].weight), lengthId: unitId(current.lengths ?? {}, entry[1].length), }); }, setCurrency(id) { if (get().init?.currencies[id]?.allowed_select) { set({ currencyId: id }); } }, setUnit(kind, id) { const values = get().init?.[kind]; if (!values || !Object.hasOwn(values, id)) { return; } set(kind === 'weights' ? { weightId: id } : { lengthId: id }); }, reconcile(next) { if (!next) { set({ ...initialSelections(null), init: null }); return; } const previous = get(); const selected = findLocale(next, previous.localeCode) ?? Object.entries(next.locale)[0]; const localeCode = selected?.[1].code?.trim() || selected?.[0] || ''; const preferredCurrency = next.currencies[previous.currencyId] ?.allowed_select ? previous.currencyId : selected?.[1].currency; set({ init: next, localeCode, currencyId: availableCurrency(next, preferredCurrency), weightId: unitId( next.weights ?? {}, Object.hasOwn(next.weights ?? {}, previous.weightId) ? previous.weightId : selected?.[1].weight, ), lengthId: unitId( next.lengths ?? {}, Object.hasOwn(next.lengths ?? {}, previous.lengthId) ? previous.lengthId : selected?.[1].length, ), }); }, reset() { set({ ...initialSelections(null), init: null }); }, })); }hooks/useBaskleeAppLoad.tsAcciones del navegador:
initialize,refreshyreset. El hook por sí mismo no envía ninguna solicitud; tras iniciar o cerrar sesión, llama aresety después arefresh.Código fuente
'use client'; import { useCallback } from 'react'; import { useBasklee, useBaskleeStore, useBaskleeSelectionsStore, } from '@/providers/BaskleeProvider'; import { requestBrowserAppLoad } from '@/lib/basklee/appLoadClient'; import { selectFailure, selectIsReady, selectResult, selectStatus, } from '@/stores/basklee'; import type { AppLoadFailure, AppLoadResult, AppLoadStatus, } from '@/interfaces/basklee'; export interface BaskleeAppLoad { result: AppLoadResult | null; status: AppLoadStatus; failure: AppLoadFailure | null; isReady: boolean; initialize: () => Promise<void>; refresh: () => Promise<void>; reset: () => void; } /** * Explicit browser actions. Calling this hook does not start a request: the * server render initializes the marketplace and hydration reuses that snapshot. * After a confirmed login or logout, call reset and then refresh. */ export function useBaskleeAppLoad(): BaskleeAppLoad { const store = useBaskleeStore(); const selections = useBaskleeSelectionsStore(); const result = useBasklee(selectResult); const status = useBasklee(selectStatus); const failure = useBasklee(selectFailure); const isReady = useBasklee(selectIsReady); const initialize = useCallback( () => store .getState() .load((signal) => requestBrowserAppLoad(signal, selections.getState().localeCode), ), [store, selections], ); const refresh = useCallback( () => store .getState() .load( (signal) => requestBrowserAppLoad(signal, selections.getState().localeCode), true, ), [store, selections], ); const reset = useCallback(() => store.getState().reset(), [store]); return { result, status, failure, isReady, initialize, refresh, reset }; }lib/basklee/appLoadClient.tsLa solicitud del navegador a través de la pasarela del mismo sitio; el navegador guarda y envía las cookies de sesión por sí mismo.
Código fuente
import { AppLoadError, appLoadRejectedLocale, appLoadResult, inspectAppLoad, } from '@/lib/basklee/appLoadResult'; import type { AppLoadRequest, AppLoadResult, } from '@/interfaces/basklee/transport'; import { APP_ORIGIN, nativeAppRequest } from '@/lib/basklee/nativeApp'; function withTimeout(signal: AbortSignal, milliseconds: number): AbortSignal { if (typeof AbortSignal.any !== 'function') { return signal; } return AbortSignal.any([signal, AbortSignal.timeout(milliseconds)]); } /** * Browser transport for explicit initialize and refresh actions. The browser * sends and stores session cookies itself through the same-origin gateway; * the Android app sends the request to its storefront (nativeApp.ts). */ export async function requestBrowserAppLoad( signal: AbortSignal, locale = '', ): Promise<AppLoadResult> { const path = locale ? `/api/appload?lang=${encodeURIComponent(locale)}` : '/api/appload'; const headers = { Accept: 'application/json', 'Content-Type': 'application/json', }; const request = { detalize_mode: 'light', ignore_cache: false, } satisfies AppLoadRequest; let status: number; let body: unknown = null; try { if (APP_ORIGIN) { const response = await nativeAppRequest(APP_ORIGIN, path, { method: 'POST', headers, data: request, signal: withTimeout(signal, 35_000), }); status = response.status; body = response.body; } else { const response = await fetch(path, { method: 'POST', headers, body: JSON.stringify(request), credentials: 'same-origin', cache: 'no-store', signal: withTimeout(signal, 35_000), }); status = response.status; body = await response.json().catch(() => null); } } catch { throw new AppLoadError('Could not reach the marketplace API.', { kind: 'network', httpStatus: null, fields: [], }); } const failure = inspectAppLoad(body, status); // A language the storefront does not have opens its default language. if (failure && locale && appLoadRejectedLocale(failure)) { return requestBrowserAppLoad(signal); } if (failure) { throw new AppLoadError('Marketplace initialization failed.', failure); } return appLoadResult(body, status); }lib/basklee/appLoadResult.tsComprueba la respuesta y convierte los errores de la red y del servidor en una forma segura única para el store.
Código fuente
import type { AppLoadFailure, AppLoadResponse, AppLoadResult, } from '@/interfaces/basklee/transport'; const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value); /** Validate the bootstrap boundary. Interfaces describe nested data, not a runtime schema. */ export function inspectAppLoad( body: unknown, httpStatus: number, ): AppLoadFailure | null { if (httpStatus < 200 || httpStatus >= 300) { return { kind: 'http', httpStatus, fields: [] }; } if ( record(body) && record(body.form_errors) && Object.keys(body.form_errors).length ) { return { kind: 'validation', httpStatus, fields: Object.keys(body.form_errors), }; } const page = record(body) && body.page_data; const init = record(page) && page.init; const unauth = record(page) && page.unauth; if ( !record(body) || !('form_errors' in body) || (body.form_errors !== null && !record(body.form_errors)) || !record(init) || typeof init.is_authenticated !== 'boolean' || !record(init.locale) || !record(init.currencies) || !record(unauth) || !record(unauth.paths) || Object.values(unauth.paths).some( (group) => !record(group) || Object.values(group).some( (endpoint) => !record(endpoint) || typeof endpoint.target !== 'string' || !Array.isArray(endpoint.methods), ), ) ) { return { kind: 'invalid-response', httpStatus, fields: [] }; } return null; } export function appLoadResult( body: unknown, httpStatus: number, ): AppLoadResult { const failure = inspectAppLoad(body, httpStatus); if (failure) { throw new Error(`AppLoad: ${failure.kind}`); } return { response: body as AppLoadResponse & { page_data: NonNullable<AppLoadResponse['page_data']>; }, httpStatus, loadedAt: new Date().toISOString(), }; } /** Transport and envelope failures reach the store as this sanitized shape. */ export function appLoadFailure(error: unknown): AppLoadFailure { const detail = error && typeof error === 'object' && 'data' in error ? (error as { data: unknown }).data : null; const known = record(detail) && 'kind' in detail && ['http', 'validation', 'invalid-response', 'network'].includes( String(detail.kind), ); if (!known || !record(detail)) { return { kind: 'network', httpStatus: null, fields: [] }; } return { kind: detail.kind as AppLoadFailure['kind'], httpStatus: typeof detail.httpStatus === 'number' ? detail.httpStatus : null, fields: Array.isArray(detail.fields) ? detail.fields.filter( (field): field is string => typeof field === 'string', ) : [], }; } /** Carries a sanitized failure from the transport to the store without a stack or response body. */ export class AppLoadError extends Error { readonly data: AppLoadFailure; constructor(message: string, data: AppLoadFailure) { super(message); this.name = 'AppLoadError'; this.data = data; } } /** * Whether App Load refused the request's language (`?lang=` of a language the * storefront does not have): the backend answers it with field errors and * HTTP 452. The language is the only client value App Load reads, so the * storefront loads again without it. */ export function appLoadRejectedLocale(failure: AppLoadFailure): boolean { return failure.kind === 'validation' || failure.httpStatus === 452; }