### Install Dependencies and Start Server Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-express-minimal/README.md Installs project dependencies and starts the Express server. Use this for local development setup. ```bash npm ci npm start ``` -------------------------------- ### Project Setup Commands Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-typescript-minimal/README.md Run these commands to install dependencies, start the development server, and push your bundle. ```bash npm ci npm start npm run push ``` -------------------------------- ### Install and Start MCP Server Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md Navigate to the MCP directory and run the start command to launch the server. This is necessary for manually testing with AI agent enabled IDEs that communicate via stdio. ```bash cd {{dir-to-mcp}} npm run start ``` -------------------------------- ### Install and Start Test Project Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/test-commerce-sdk-react/README.md Run these commands at the root of the monorepo to install dependencies and start the test project. ```bash # run this at the root of the monorepo npm ci cd ./packages/test-commerce-sdk-react npm start ``` -------------------------------- ### Install All Dependencies Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/CONTRIBUTING.md Use this command to install all project dependencies and link packages in the monorepo. Run this frequently during development. ```bash npm ci ``` -------------------------------- ### Start PWA Kit Project Locally Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/assets/bootstrap/js/README.MD Use this command to start your PWA Kit project locally. It will automatically open your storefront in a browser. ```bash npm start ``` -------------------------------- ### Install Commerce SDK React Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Install the Commerce SDK React library and its peer dependency, @tanstack/react-query, using npm. ```bash npm install @salesforce/commerce-sdk-react @tanstack/react-query ``` -------------------------------- ### Install Dependencies Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-react-sdk/README.md Installs all necessary dependencies for the PWA Kit React SDK. Ensure you have Node.js 16.11 or later and npm 8 or later. ```bash npm i ``` -------------------------------- ### Get Help with PWA Kit Create App Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/README.md Use this command to view all available options and usage instructions for the create app tool. ```bash npx @salesforce/pwa-kit-create-app --help ``` -------------------------------- ### Create a New PWA Kit Project Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/README.md Run this command in your terminal to start the project generation process. ```bash npx @salesforce/pwa-kit-create-app ``` -------------------------------- ### Core OpenTelemetry Module Setup Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/docs/distributed-tracing.md This snippet outlines the core OpenTelemetry setup including the provider, propagator, and context manager. It emphasizes non-global instances and lazy initialization. ```javascript import { NodeTracerProvider } from '@opentelemetry/node'; import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { W3CTraceContextPropagator } from '@opentelemetry/core'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; import { MrtConsoleSpanExporter } from './mrt-console-span-exporter'; // Provider: NodeTracerProvider + SimpleSpanProcessor(MrtConsoleSpanExporter) const provider = new NodeTracerProvider(); provider.addSpanProcessor(new SimpleSpanProcessor(new MrtConsoleSpanExporter())); // Propagator: a module-level W3CTraceContextPropagator instance const propagator = new W3CTraceContextPropagator(); // Context manager: a global AsyncHooksContextManager installed once, lazily let contextManager = null; export const isDistributedTracingEnabled = () => { // Assume getOTELConfig() is defined elsewhere and returns config object const config = getOTELConfig(); return config && config.enabled; }; export const extractContext = (headers) => { if (!isDistributedTracingEnabled()) { return context.active(); // Fallback to active context } try { return propagator.extract(context.active(), headers); } catch (e) { console.error('Failed to extract context:', e); return context.active(); // Fallback on failure } }; export const withServerSpan = async (req, res, parentCtx, fn) => { if (!isDistributedTracingEnabled()) { return fn(); } // Lazy initialization of context manager if (!contextManager) { contextManager = new AsyncHooksContextManager(); contextManager.enable(); // Assuming register() is available and used for context manager setup // propagation.setGlobalPropagator(propagator); // This is NOT done globally // contextManager.register(); // This is NOT done globally } const tracer = provider.getTracer('ssr.render'); const activeSpan = tracer.startSpan('ssr.render', { parent: parentCtx }); return contextManager.with(activeSpan, async () => { try { res.locals.__withChildSpan = withChildSpan; // For universal components const result = await fn(); // Set attributes on the active span setActiveSpanAttribute('http.route', res.locals.route.path); return result; } catch (error) { activeSpan.recordException(error); throw error; } finally { activeSpan.end(); } }); }; export const withChildSpan = (name, fn) => { if (!isDistributedTracingEnabled()) { return fn(); } // Ensure context manager is initialized if not already if (!contextManager) { contextManager = new AsyncHooksContextManager(); contextManager.enable(); } const tracer = provider.getTracer('ssr.render'); // Or a more specific tracer name const activeSpan = tracer.startSpan(name); return contextManager.with(activeSpan, async () => { try { return await fn(); } catch (error) { activeSpan.recordException(error); throw error; } finally { activeSpan.end(); } }); }; export const setActiveSpanAttribute = (key, value) => { if (!isDistributedTracingEnabled()) { return; } const span = context.active(); if (span) { span.setAttribute(key, value); } }; export const getCurrentTraceparent = () => { if (!isDistributedTracingEnabled()) { return null; } const span = context.active(); if (span && span.spanContext && span.spanContext().traceId) { // Constructing a traceparent string is more involved and depends on propagator details // This is a simplified representation. return `00-${span.spanContext().traceId}-00-01`; } return null; }; // Placeholder for getOTELConfig and context/propagation modules const getOTELConfig = () => ({ enabled: true }); // Mock implementation const context = { active: () => ({ setAttribute: () => {} }) }; // Mock implementation const propagation = { setGlobalPropagator: () => {} }; // Mock implementation ``` -------------------------------- ### CommerceApiProvider Setup in React App Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Wrap your React application with CommerceApiProvider and QueryClientProvider for basic setup. Ensure you provide your client ID, organization ID, and other necessary configuration details. ```jsx import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' import {QueryClient, QueryClientProvider} from '@tanstack/react-query' const App = ({children}) => { const queryClient = new QueryClient() return ( {children} ) } export default App ``` -------------------------------- ### View PWA Kit Dev Help Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-dev/README.md Run this command to see all available commands for the PWA Kit developer tool. Ensure Node.js and npm are installed and meet the minimum version requirements. ```bash npx @salesforce/pwa-kit-dev --help ``` -------------------------------- ### Implementing a Layout Component Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER_ARCHITECTURE.md Provides an example of how to implement a layout component that renders child components within specified regions using the `Region` component. ```jsx function TwoColumnLayout({component}) { return (
) } ``` -------------------------------- ### Test Translations with Pseudo Locale Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-retail-react-app/translations/README.md Run this script to start the local development server with the locale forced to a pseudo locale. This helps verify that all hardcoded strings are wrapped with formatting functions. ```bash npm run start:pseudolocale ``` -------------------------------- ### PageDesignerProvider Setup Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER_ARCHITECTURE.md Wraps the application to enable Page Designer's visual editing features. Requires client ID and target origin. ```jsx {children} ``` -------------------------------- ### Error Message for Missing SDK Client Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md This is an example of the error message displayed when a required SDK client is not initialized or provided to the CommerceApiProvider. It helps in debugging configuration issues. ```text Missing required client: shopperProducts. Please initialize shopperProducts class and provide it in CommerceApiProvider's apiClients prop. ``` -------------------------------- ### Site Localization Configuration Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-retail-react-app/translations/README.md Example of defining supported currencies, locales, and default settings for a site in `config/sites.js`. Ensure these settings align with your B2C Commerce instance. ```javascript // config/sites.js modules.exports = [ { id: 'site-id', l10n: { supportedCurrencies: ['GBP', 'EUR', 'CNY', 'JPY'], defaultCurrency: 'GBP', supportedLocales: [ { id: 'de-DE', preferredCurrency: 'EUR' }, { id: 'en-GB', preferredCurrency: 'GBP' }, { id: 'es-MX', preferredCurrency: 'MXN' }, // other locales ], defaultLocale: 'en-GB' } } ] ``` -------------------------------- ### Add PageDesignerInit to App Provider Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER.md This example demonstrates how to render the PageDesignerInit component within the PageDesignerProvider in the main application file (e.g., app/components/_app/index.jsx) to initialize Page Designer. ```jsx {children} ``` -------------------------------- ### Example Custom API JSON Configuration Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md Define custom API metadata in an api.json file for the scapi_custom_api_discovery tool. This includes API name, version, and endpoint details. ```json { "apiName": "reviews", "apiVersion": "v1", "cartridgeName": "plugin_custom_api_intro", "endpointPath": "reviews", "httpMethod": "GET", "securityScheme": "bearer", "baseUrl": "https://your-shortcode.api.commercecloud.salesforce.com/custom/reviews/v1" } ``` -------------------------------- ### Extend Recommended ESLint Config Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-dev/src/configs/eslint/README.md To extend the recommended PWA Kit ESLint configuration, use `require.resolve()` with the full path to the config file. This is necessary because the config is not part of a package starting with 'eslint-config-'. ```javascript module.exports = { extends: [require.resolve('@salesforce/pwa-kit-dev/configs/eslint/recommended')] } ``` -------------------------------- ### Integrate CommerceApiProvider with PWA Kit Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Integrate the CommerceApiProvider into your PWA Kit application's AppConfig component. This setup is necessary for server-side data fetching and state management using React Query. ```jsx // app/components/_app-config/index.jsx import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' import {withReactQuery} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query' const AppConfig = ({children}) => { const headers = { 'correlation-id': correlationId } return ( {children} ) } // Set configuration options for react query. // NOTE: This configuration will be used both on the server-side and client-side. // retry is always disabled on server side regardless of the value from the options const options = { queryClientConfig: { defaultOptions: { queries: { retry: false }, mutations: { retry: false } } } } export default withReactQuery(AppConfig, options) ``` -------------------------------- ### List Available Commands Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/internal-lib-build/README.md Navigate to the internal-lib-build directory and execute the --help flag to view all available commands. ```bash cd packages/internal-lib-build ./bin/internal-lib-build --help ``` -------------------------------- ### Using useCommerceApi and useAccessToken Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Demonstrates how to fetch products using SCAPI clients initialized by `useCommerceApi` and an access token obtained via `useAccessToken`. Ensure you have the necessary imports and that the provider is configured. ```jsx import {useCommerceApi, useAccessToken} from '@salesforce/commerce-sdk-react' const Example = () => { const api = useCommerceApi() const {getTokenWhenReady} = useAccessToken() const fetchProducts = async () => { const token = await getTokenWhenReady() const products = await api.shopperProducts.getProducts({ parameters: {ids: ids.join(',')}, headers: { Authorization: `Bearer ${token}` } }) return products } } ``` -------------------------------- ### Get Browser Geolocation Coordinates Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/src/data/hook-catalog.md Use this hook to get the user's current geolocation coordinates. It provides loading and error states, and a refresh function. ```javascript import React from 'react' import {useGeolocation} from '@salesforce/retail-react-app/app/hooks/use-geo-location' export default function GeolocationExample() { const {coordinates, loading, error, refresh} = useGeolocation() // Example: // if (loading) return
Detecting location…
// if (error) return
Error: {String(error)}
// return ( //
//
{JSON.stringify(coordinates, null, 2)}
// //
// ) } ``` -------------------------------- ### New API Application Initialization Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER.md Demonstrates how to initialize the component registry at the application level in the new API. ```jsx // _app/index.jsx import {initializeRegistry} from './page-designer/registry' initializeRegistry() // At module level, not in useEffect ``` -------------------------------- ### Use Product Query Hook Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Demonstrates how to use the `useProduct` hook to fetch product data. Pass product ID and locale as parameters. Displays loading state and product name. ```jsx import {useProduct} from '@salesforce/commerce-sdk-react' const Example = () => { const query = useProduct({ parameters: { id: '25592770M', locale: 'en-US' } }) return ( <>

isLoading: {query.isLoading}

name: {query.data?.name}

) } ``` -------------------------------- ### Run MCP Demo Commands Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md Execute these commands to run the MCP server demo and observe its capabilities in code analysis and generation. ```bash npm run demo # or: node demo.js ``` -------------------------------- ### Deploy Project to Managed Runtime Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-express-minimal/README.md Builds and pushes the project bundle to the Managed Runtime environment. Use this for deployment. ```bash npm run push ``` -------------------------------- ### Registering Component Importers with Fallbacks Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/PAGE_DESIGNER_ARCHITECTURE.md Demonstrates how to register component importers using `registry.registerImporter`, including an optional fallback for skeleton loading states to improve user experience during initial load. ```javascript registry.registerImporter( 'commerce_assets.banner', () => import('./banner'), () => import('./banner-skeleton') // Optional fallback ) ``` -------------------------------- ### Send JSON-RPC Requests to MCP Server Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md Send JSON-RPC requests to the MCP server to interact with its tools. Examples include listing available tools and calling a specific tool with arguments. ```json {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}} ``` ```json {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "pwakit_get_dev_guidelines", "arguments": {}}} ``` -------------------------------- ### Natural Language Commands for Code Generation Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md Use natural language to instruct Cursor to insert or modify components. Examples include inserting a ProductCard or adding a modal with specific styling. ```plaintext "Insert a ProductCard component after the imports in App.js" "Add a modal component with Tailwind styling to this file" "Create a new button component with these specifications: primary variant, medium size" ``` -------------------------------- ### PWA Kit Loading Screen Logic Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-dev/src/ssr/server/loading-screen/index.html This script handles the loading screen behavior. It checks for a 'loading' query parameter and waits for the application to be ready before redirecting to the specified path. It also includes functionality to animate fun facts displayed on the loading screen. ```javascript (function() { const url = new URL(window.location) const loading = url.searchParams.get('loading') if (loading === '1') { const interval = 1000 const waitForReady = () => { return new Promise((resolve) => { const checkReady = () => { fetch('/__mrt/status') .then((res) => res.json()) .then((data) => { if (data.ready) { resolve() } else { setTimeout(checkReady, interval) } }) } checkReady() }) } waitForReady().then(() => { // Redirect to homepage if path is not defined const path = url.searchParams.get('path') ?? '' window.location = new URL(path, url.origin) }) } const animateFacts = () => { const holdMs = 7000; const transitionMs = 433; const facts = document.querySelectorAll('.fun-fact'); facts.forEach((fact) => { fact.style.transitionDuration = transitionMs + 'ms'; fact.classList.add('fun-fact--hidden'); }); let counter = 0; const modulo = (x, y) => ((x % y) + y) % y const update = () => { const previous = modulo(counter - 1, facts.length) const current = modulo(counter, facts.length) facts[previous].classList.remove('fun-fact--show') setTimeout(() => facts[previous].classList.add('fun-fact--hidden'), transitionMs) facts[current].classList.remove('fun-fact--hidden') setTimeout(() => facts[current].classList.add('fun-fact--show'), 50) } update(); setInterval(() => { counter += 1; update() }, holdMs) } animateFacts() })() ``` -------------------------------- ### Run Linting Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/CONTRIBUTING.md Execute the linting process to check code quality and style consistency across the project. ```bash npm run lint ``` -------------------------------- ### Dynamic Body and Parameters with useCustomMutation Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Shows how to use `useCustomMutation` to dynamically set the request body and parameters, suitable for scenarios with changing inputs. ```jsx import {useCustomMutation} from '@salesforce/commerce-sdk-react' const clientConfig = { parameters: { clientId: 'CLIENT_ID', siteId: 'SITE_ID', organizationId: 'ORG_ID', shortCode: 'SHORT_CODE' }, proxy: 'http://localhost:8888/mobify/proxy/api' }; const mutation = useCustomMutation({ options: { method: 'POST', customApiPathParameters: { endpointPath: 'path/to/resource', apiName: 'hello-world' } }, clientConfig, rawResponse: false }); // use it in a react component const ExampleDynamicMutation = () => { const [colors, setColors] = useState(['blue', 'green', 'white']) const [selectedColor, setSelectedColor] = useState(colors[0]) return ( <> // {isSuccess &&
Guest Login Success! Access Token: {data?.access_token}
} // {error &&
Error: {String(error)}
} // // ) } export default GuestLogin ``` -------------------------------- ### Create New Component File with MCP Server Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md Instruct Cursor/Claude to create a new component file. The MCP server generates a complete file with imports, component definition, export statement, and styling. ```javascript // Ask Cursor/Claude: "Create a new Button component file" // The MCP server will generate a complete component file with: // - Proper imports // - Component definition // - Export statement // - Styling (Tailwind or CSS) ``` -------------------------------- ### Fetch Product List with useProducts Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/src/data/hook-catalog.md Use the `useProducts` hook to fetch multiple products by their IDs. It allows for optional inventory scoping based on the selected store and supports expanding related data like availability and variations. ```javascript import React from 'react' import {useProducts} from '@salesforce/commerce-sdk-react' import {useSelectedStore} from '@salesforce/retail-react-app/app/hooks/use-selected-store' export default function ProductsExample() { // Expect an array of product IDs in `inputIds` const productIds = ['test-product-id-1', 'test-product-id-2'] // Optional inventory scoping by selected store const {selectedStore} = useSelectedStore() const selectedInventoryId = selectedStore?.inventoryId || null const { data, isLoading, isError, error } = useProducts( { parameters: { ids: productIds.join(','), allImages: false, ...(selectedInventoryId ? {inventoryIds: selectedInventoryId} : {}), expand: ['availability', 'variations'], select: '(data.(id,inventory,inventories,master))' } }, {enabled: productIds.length > 0, keepPreviousData: true} ) // Example: // if (isLoading) return
Loading products…
// if (isError) return
Error: {String(error)}
// return
{JSON.stringify(data, null, 2)}
} ``` -------------------------------- ### MCP Server Configuration in mcp.json Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md Configure the MCP server command and environment variables in your mcp.json file. Ensure PWA_STOREFRONT_APP_PATH is set to your app directory. ```json { "mcpServers": { "pwa-kit": { "command": "npx", "args": ["-y", "@salesforce/pwa-kit-mcp"], "env": { "PWA_STOREFRONT_APP_PATH": "{{path-to-app-directory}}" } } } } ``` -------------------------------- ### Build Translations (Extract and Compile) Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-retail-react-app/translations/README.md Run this script to perform both the extraction of default messages and the compilation of translations. ```bash npm run build-translations ``` -------------------------------- ### Specify dw.json Path Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/README.md Use the `--dw-json` flag to provide the path to your `dw.json` configuration file if it's not located in the project root. This is an alternative to using environment variables. ```bash --dw-json "/path/to/dw.json" ``` -------------------------------- ### Basic useCustomMutation Usage Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Demonstrates how to declare and use the `useCustomMutation` hook to send a POST request with a dynamic body and headers. ```jsx const clientConfig = { parameters: { clientId: 'CLIENT_ID', siteId: 'SITE_ID', organizationId: 'ORG_ID', shortCode: 'SHORT_CODE' }, proxy: 'http://localhost:8888/mobify/proxy/api' }; const mutation = useCustomMutation({ options: { method: 'POST', customApiPathParameters: { endpointPath: 'test-hello-world', apiName: 'hello-world' } }, clientConfig, rawResponse: false }); // In your React component ``` -------------------------------- ### Deploy PWA Kit App to Managed Runtime Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-create-app/assets/bootstrap/js/README.MD This command pushes your PWA Kit application bundle to the Managed Runtime. Include a message to identify the bundle. You can specify a different project using the -s argument. ```bash npm run push -- -m "Message to help you recognize this bundle" ``` -------------------------------- ### Using Named Mutation Constants Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/commerce-sdk-react/README.md Illustrates how to import and use named mutation constants for specific SDK operations like `addItemToBasket`. ```jsx import {useShopperBasketsMutation, ShopperBasketsMutations} from '@salesforce/commerce-sdk-react' const Example = ({basketId}) => { // this works const addItemToBasket = useShopperBasketsMutation('addItemToBasket') // this also works const addItemToBasket = useShopperBasketsMutation(ShopperBasketsMutations.AddItemToBasket) return ... } ``` -------------------------------- ### Fetch Single Product Data with useProduct Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/src/data/hook-catalog.md Fetch details for a single product using the `useProduct` hook. It supports fetching by product ID or a `pid` query parameter and can expand various related data like availability, promotions, and variations. Inventory can be scoped by the selected store. ```javascript import React from 'react' import {useParams, useLocation} from 'react-router-dom' import {useProduct} from '@salesforce/commerce-sdk-react' import {useSelectedStore} from '@salesforce/retail-react-app/app/hooks/use-selected-store' export default function ProductExample() { // Inside your component const {productId} = useParams() const location = useLocation() const urlParams = new URLSearchParams(location.search) // If your site uses store selection/inventory const {selectedStore} = useSelectedStore() const selectedInventoryId = selectedStore?.inventoryId || null const { data: productResponse, isLoading, isError, error } = useProduct( { parameters: { id: urlParams.get('pid') || productId, perPricebook: true, expand: [ 'availability', 'promotions', 'options', 'images', 'prices', 'variations', 'set_products', 'bundled_products', 'page_meta_tags' ], allImages: true, ...(selectedInventoryId ? {inventoryIds: selectedInventoryId} : {}) } }, { keepPreviousData: true } ) // Example: // if (isLoading) return
Loading product…
// if (isError) return
Error: {String(error)}
// return
{JSON.stringify(productResponse, null, 2)}
} ``` -------------------------------- ### Compile Translations Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/template-retail-react-app/translations/README.md Run this script to compile translations from all locales into an AST format for improved performance. ```bash npm run compile-translations ``` -------------------------------- ### Batch Component Generation Script Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md Use this script to automate the creation of multiple components. It ensures the target directory exists and writes the generated component code to individual files. ```javascript import { AddComponentTool } from './AddComponentTool.js'; import fs from 'fs/promises'; import path from 'path'; const componentTool = new AddComponentTool(); const componentsToCreate = [ { name: 'ProductCard', type: 'product', options: { styling: 'tailwind' } }, { name: 'AddToCartButton', type: 'button', options: { variant: 'primary' } }, { name: 'ProductModal', type: 'modal', options: { closeOnOverlay: true } }, { name: 'ReviewCard', type: 'card', options: { showHeader: true } } ]; async function generateComponents() { const componentsDir = './src/components'; // Ensure directory exists await fs.mkdir(componentsDir, { recursive: true }); for (const comp of componentsToCreate) { const componentCode = componentTool.createComponentFile( comp.name, comp.type, comp.options ); const fileName = `${comp.name}.jsx`; const filePath = path.join(componentsDir, fileName); await fs.writeFile(filePath, componentCode, 'utf-8'); console.log(`✅ Created ${fileName}`); } } generateComponents().catch(console.error); ``` -------------------------------- ### Use Product Search Hook Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/src/data/hook-catalog.md Performs a product search based on a query and various parameters. Use this hook to implement search functionality and display product results. ```javascript import React, {useState} from 'react' import {useProductSearch} from '@salesforce/commerce-sdk-react' export default function ProductSearchExample() { const [searchQuery, setSearchQuery] = useState('socks') const {data, isLoading, isError, error} = useProductSearch({ parameters: { q: searchQuery, allImages: true, allVariationProperties: true, expand: ['promotions', 'variations', 'prices', 'images', 'custom_properties'], limit: 24, offset: 0, sort: '' } }) // Example: // return ( //
// setSearchQuery(e.target.value)} /> // {isLoading ? 'Loading…' : isError ? String(error) :
{JSON.stringify(data, null, 2)}
} //
// ) } ``` -------------------------------- ### Use Promotions Hook Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/src/data/hook-catalog.md Fetches promotion data based on provided IDs. Use when you need to display or apply specific promotions to the user. ```javascript import React from 'react' import {usePromotions} from '@salesforce/commerce-sdk-react' export default function PromotionsExample() { const promotionIds = ['promo-1', 'promo-2'] const {data, isLoading, isError, error} = usePromotions( {parameters: {ids: promotionIds.join(',')}}, {enabled: promotionIds.length > 0} ) // Example: // if (isLoading) return
Loading promotions…
// if (isError) return
Error: {String(error)}
// return
{JSON.stringify(data, null, 2)}
} ``` -------------------------------- ### Structured Prompts for Component Creation Source: https://github.com/salesforcecommercecloud/pwa-kit/blob/develop/packages/pwa-kit-mcp/docs/cursor-integration-guide.md Provide detailed specifications in a structured format for generating React components. This allows for precise control over component type, name, styling, features, and insertion point. ```plaintext Insert a React component with these specifications. - Type: ProductCard - Name: FeaturedProduct - Styling: Tailwind CSS - Features: Show price, rating, and add-to-cart button - Insert after imports in the current file ```