@brainerce/mcp-server 3.8.0 → 3.11.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/bin/stdio.js CHANGED
@@ -709,7 +709,7 @@ const growProvider = providers.find(p => p.provider === 'grow');
709
709
  const paypalProvider = providers.find(p => p.provider === 'paypal');
710
710
  \`\`\`
711
711
 
712
- Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
712
+ Each provider has: \`id\`, \`provider\` (flexible string \u2014 \`'stripe'\`, \`'grow'\`, \`'paypal'\`, \`'cardcom'\`, \`'morning'\`, \`'takbull'\`, \`'sandbox'\`, and future providers), \`name\`, \`publicKey\`, \`stripeAccountId\` (Stripe only), \`supportedMethods\`, \`testMode\`, \`isDefault\`.
713
713
 
714
714
  The payment intent returned from \`createPaymentIntent()\` includes a \`clientSdk\` object whose \`renderType\` tells you exactly how to render \u2014 **branch on THAT, not on the provider name**:
715
715
 
@@ -1153,6 +1153,8 @@ const material = getProductMetafieldValue(product, 'material');
1153
1153
 
1154
1154
  **Metafield fields:** \`definitionName\` (display label), \`definitionKey\` (lookup key), \`value\`, \`type\` (IMAGE, GALLERY, URL, COLOR, BOOLEAN, DATE, DATETIME, TEXT, TEXTAREA, NUMBER, DIMENSION, WEIGHT, JSON)
1155
1155
 
1156
+ **Translations:** When the store has i18n enabled and \`client.setLocale()\` is active, both the \`definitionName\` (the merchant-authored label like "Warranty Info" / "\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D7\u05E8\u05D9\u05D5\u05EA") **and** free-text \`value\` come back already translated. No per-call locale param needed.
1157
+
1156
1158
  ### Product Customization Fields (Customer Input)
1157
1159
 
1158
1160
  Some products allow customers to provide input at purchase time (e.g., text on a cake, upload a logo). Check \`product.customizationFields\` and render input fields accordingly.
@@ -1286,6 +1288,8 @@ await client.removeCoupon(cartId);
1286
1288
  const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
1287
1289
  \`\`\`
1288
1290
 
1291
+ > **Region-restricted coupons:** a coupon may carry \`regionIds\`. If the buyer's checkout region isn't in that list, \`applyCoupon\` / \`applyCheckoutCoupon\` reject the code even when everything else matches. Empty/omitted \`regionIds\` = valid in all regions.
1292
+
1289
1293
  **On the checkout page** (after checkout session exists \u2014 ALWAYS use this when checkoutId is available):
1290
1294
  \`\`\`typescript
1291
1295
  // Applies to cart AND updates checkout totals in one call
@@ -1613,6 +1617,8 @@ const groups: ModifierGroup[] = product.modifierGroups ?? [];
1613
1617
 
1614
1618
  **Money fields are strings.** \`priceDelta\` is \`"5.00"\` (or \`"-2.00"\` for downsell modifiers \u2014 see below). Use \`parseFloat()\` for display arithmetic; never compute the line total client-side \u2014 the server runs the free-allocation policy and returns the final \`unitPrice\` snapshot on the cart line.
1615
1619
 
1620
+ **Translations are automatic.** Both \`group.name\`/\`group.description\` and each \`modifier.name\`/\`modifier.description\` are overlay-resolved by the server on every read. Call \`client.setLocale('he')\` once and the modifier picker renders in Hebrew with no extra code (\`"\u05EA\u05D5\u05E1\u05E4\u05D5\u05EA"\` / \`"\u05D6\u05D9\u05EA\u05D9\u05DD"\`). See the \`i18n\` topic for the full multi-language flow.
1621
+
1616
1622
  ### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
1617
1623
 
1618
1624
  Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
@@ -2014,19 +2020,24 @@ window.location.href = authorizationUrl;
2014
2020
  \`\`\`typescript
2015
2021
  const params = new URLSearchParams(window.location.search);
2016
2022
  if (params.get('oauth_success') === 'true') {
2017
- const token = params.get('token');
2018
- if (token) {
2019
- client.setCustomerToken(token);
2020
- localStorage.setItem('customerToken', token);
2021
- // Optional: read customer_id, customer_email, is_new from params
2023
+ // Single-use auth_code is exchanged for the JWT via POST \u2014 keeps the JWT
2024
+ // out of the URL (browser history, CDN logs, Referer header).
2025
+ const code = params.get('auth_code');
2026
+ if (code) {
2027
+ const result = await client.exchangeOAuthCode(code);
2028
+ client.setCustomerToken(result.token);
2029
+ localStorage.setItem('customerToken', result.token);
2030
+ // Optional: result.customer, result.isNewCustomer, result.redirectUrl
2022
2031
  // Link guest cart: await client.linkCart(cartId);
2023
- window.location.href = '/account';
2032
+ window.location.href = result.redirectUrl || '/account';
2024
2033
  }
2025
2034
  } else if (params.get('oauth_error')) {
2026
2035
  // Show error: params.get('oauth_error')
2027
2036
  }
2028
2037
  \`\`\`
2029
2038
 
2039
+ > The legacy redirect format placed the JWT directly in the URL as \`?token=\`. That format is still emitted for backward compatibility, but it will be removed in the next major release \u2014 migrate to \`auth_code\` + \`exchangeOAuthCode()\` now.
2040
+
2030
2041
  ### Account Page (/account) \u2014 uses getMyProfile() and getMyOrders()
2031
2042
 
2032
2043
  \`\`\`typescript
@@ -2255,7 +2266,17 @@ overlay needed:
2255
2266
  - \`variants[].name\`
2256
2267
  - \`variant.attributes\` keys and values \u2014 \`getVariantOptions(variant)\` returns translated attribute names and option values automatically
2257
2268
  - \`productAttributeOptions[].attribute.name\`, \`attributeOption.name\`
2258
- - \`metafields[].value\`
2269
+ - \`metafields[].value\` (the free-text values customers submit)
2270
+ - \`metafields[].definition.name\`, \`metafields[].definition.description\` (the merchant-authored custom-field labels \u2014 "Warranty Info" / "\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D7\u05E8\u05D9\u05D5\u05EA")
2271
+ - \`modifierGroups[].name\`, \`modifierGroups[].description\` (the group label shown on the PDP \u2014 e.g. "Toppings" / "\u05EA\u05D5\u05E1\u05E4\u05D5\u05EA")
2272
+ - \`modifierGroups[].modifiers[].name\`, \`modifierGroups[].modifiers[].description\` (each individual modifier \u2014 e.g. "Olives" / "\u05D6\u05D9\u05EA\u05D9\u05DD")
2273
+
2274
+ **Promotional surfaces:**
2275
+ - \`cart.bundles[].name\`, \`cart.bundles[].description\` (the bundle's own merchant-typed label, e.g. "Lunch Combo" / "\u05D0\u05E8\u05D5\u05D7\u05EA \u05E6\u05D4\u05E8\u05D9\u05D9\u05DD")
2276
+ - \`cart.bundles[].offeredProducts[].name\`, \`.slug\` (each product inside the bundle \u2014 fetched fresh from \`Product.translations\`)
2277
+ - \`checkout.bumps[].title\`, \`checkout.bumps[].description\` (the bump headline shown at checkout \u2014 falls back to the translated product name when merchant didn't override)
2278
+ - \`checkout.bumps[].bumpProduct.name\`, \`.slug\` (the underlying product)
2279
+ - Discount-rule names/descriptions (when surfaced as banner text via \`displayConfig\`)
2259
2280
 
2260
2281
  **Taxonomy (\`getCategories\`, \`getBrands\`, \`getTags\`):**
2261
2282
  - \`name\` on each item
@@ -2347,6 +2368,67 @@ Read \`storeInfo.i18n.supportedLocales\` and render a switcher in the header
2347
2368
  that navigates to \`/{otherLocale}/{currentPathWithoutLocale}\`. The middleware
2348
2369
  handles the canonical redirect when the user picks the default locale.`;
2349
2370
  }
2371
+ function getMultilingualSeoSection() {
2372
+ return `## Multilingual SEO
2373
+
2374
+ ### Slugs per locale (IMPORTANT)
2375
+
2376
+ Brainerce stores per-locale slugs in \`Product.translations[locale].slug\`.
2377
+ The API exposes them as \`product.localeSlugs\` \u2014 a flat \`Record<string, string>\`.
2378
+
2379
+ \`\`\`typescript
2380
+ // product.localeSlugs = { he: '\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4', en: 'yoga-mattress', ar: '\u062D\u0635\u064A\u0631\u0629-\u064A\u0648\u063A\u0627' }
2381
+ const locSlug = product.localeSlugs?.[locale] ?? product.slug;
2382
+ \`\`\`
2383
+
2384
+ Use AI translation (\`translateEntities\` / the AI Translate button in the admin) to populate
2385
+ locale-specific slugs automatically. Until translated, all locales fall back to the base slug
2386
+ (which Google still accepts \u2014 it resolves to the correct locale content via Accept-Language).
2387
+
2388
+ ### hreflang tags
2389
+
2390
+ Every product page in a multi-locale store MUST emit bidirectional hreflang tags or Google
2391
+ ignores them entirely. The scaffolded template generates them automatically when
2392
+ \`NEXT_PUBLIC_BRAINERCE_LOCALES=he,en\` is set.
2393
+
2394
+ \`\`\`html
2395
+ <!-- Example output for /en/products/yoga-mattress -->
2396
+ <link rel="alternate" hreflang="he" href="https://store.com/products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4" />
2397
+ <link rel="alternate" hreflang="en" href="https://store.com/en/products/yoga-mattress" />
2398
+ <link rel="alternate" hreflang="x-default" href="https://store.com/products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4" />
2399
+ \`\`\`
2400
+
2401
+ If building a custom storefront, add to \`generateMetadata()\`:
2402
+ \`\`\`typescript
2403
+ alternates: {
2404
+ canonical: locale === defaultLoc ? \`/products/\${slug}\` : \`/\${locale}/products/\${slug}\`,
2405
+ languages: {
2406
+ he: \`\${baseUrl}/products/\${localeSlugs.he ?? baseSlug}\`,
2407
+ en: \`\${baseUrl}/en/products/\${localeSlugs.en ?? baseSlug}\`,
2408
+ 'x-default': \`\${baseUrl}/products/\${localeSlugs[defaultLoc] ?? baseSlug}\`,
2409
+ },
2410
+ },
2411
+ \`\`\`
2412
+
2413
+ ### URL structure
2414
+
2415
+ Google-recommended for headless storefronts:
2416
+ - Default locale: \`/products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4\` (no prefix)
2417
+ - Other locales: \`/en/products/yoga-mattress\` (prefixed)
2418
+ - \u274C Never: \`?locale=he\` query params (Google rates these as "Not recommended")
2419
+
2420
+ ### Sitemap
2421
+
2422
+ The scaffolded \`sitemap.ts\` generates per-locale entries automatically:
2423
+ \`\`\`
2424
+ /products/\u05DE\u05D6\u05E8\u05DF-\u05D9\u05D5\u05D2\u05D4 (he \u2014 default, no prefix)
2425
+ /en/products/yoga-mattress (en)
2426
+ /ar/products/\u062D\u0635\u064A\u0631\u0629-\u064A\u0648\u063A\u0627 (ar)
2427
+ \`\`\`
2428
+
2429
+ Hebrew, Arabic, and other non-Latin slugs are fully supported \u2014 Google recommends
2430
+ using the audience's language in URLs and indexes non-ASCII characters correctly.`;
2431
+ }
2350
2432
  function getAdminApiSection() {
2351
2433
  return `## Admin API (v0.19.0+)
2352
2434
 
@@ -2357,7 +2439,9 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
2357
2439
 
2358
2440
  // Taxonomy: listCategories(), listBrands(), listTags(), listAttributes()
2359
2441
  // Shipping: listShippingZones(), createZoneShippingRate()
2360
- // Tax: getTaxRates(), createTaxRate()
2442
+ // Tax: getTaxRates(), createTaxRate() \u2014 a rate may target a tax class via taxClassId
2443
+ // Tax classes: getTaxClasses(), createTaxClass(), assignTaxClass(), mergeTaxClasses() (scope tax-classes:*)
2444
+ // Regions: getRegions(), createRegion(), setDefaultRegion(), updateRegionPaymentProviders() (scope regions:*)
2361
2445
  // Metafields: getMetafieldDefinitions(), setProductMetafield()
2362
2446
  // Team: getTeamMembers(), inviteTeamMember()
2363
2447
  // Email: getEmailTemplates(), createEmailTemplate()
@@ -2365,6 +2449,13 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
2365
2449
  // OAuth: getOAuthProviders(), configureOAuthProvider()
2366
2450
  \`\`\`
2367
2451
 
2452
+ Store-level team management (\`inviteStoreMember\`, \`updateStoreMember\`) is the
2453
+ canonical replacement for the deprecated account-level helpers above. The
2454
+ invite accepts an optional \`salesChannelIds\` (vibe-coded \`connectionId\`s,
2455
+ \`vc_*\`) to restrict a member to specific channels \u2014 omit or pass \`[]\` for all
2456
+ channels. Use \`updateStoreMemberSalesChannels(storeId, memberId, { salesChannelIds })\`
2457
+ to change that scope later.
2458
+
2368
2459
  ### Per-Channel Publishing
2369
2460
 
2370
2461
  Categories, tags, brands, and metafield definitions are gated to specific
@@ -2396,7 +2487,97 @@ calls fail with \`404 Not Found\`.
2396
2487
 
2397
2488
  The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
2398
2489
  mode) automatically filter by these junction tables, so storefronts never see
2399
- entities that weren't published to their site.`;
2490
+ entities that weren't published to their site.
2491
+
2492
+ ### Tax classes (differential tax rates)
2493
+
2494
+ Charge different rates for different product types. A \`TaxRate\` may target a
2495
+ class via \`taxClassId\`; a rate with \`taxClassId: null\` is the **Standard
2496
+ fallback**. Checkout resolves each line's class **variant \u2192 product \u2192 category
2497
+ \u2192 store default \u2192 null**, then picks the matching rate (Standard if none).
2498
+ \`rate\` is a whole percentage (\`7.25\` = 7.25%). Requires the
2499
+ \`tax-classes:read\` / \`tax-classes:write\` scopes.
2500
+
2501
+ \`\`\`typescript
2502
+ const food = await admin.createTaxClass({ name: 'Food', slug: 'food' });
2503
+ await admin.assignTaxClass(food.id, { productIds: ['prod_1'], categoryIds: ['cat_food'] });
2504
+
2505
+ // class-specific rate \u2014 only food lines use it; everything else uses Standard
2506
+ await admin.createTaxRate({ name: 'VAT (Food)', rate: 0, country: 'GB', taxClassId: food.id });
2507
+
2508
+ // delete is blocked (409) while dependents exist \u2014 merge moves FKs then deletes:
2509
+ await admin.mergeTaxClasses(food.id, standardClassId);
2510
+ \`\`\`
2511
+
2512
+ Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreTaxClasses()\` lists
2513
+ the store's classes (storefront-safe fields only) for a transparency badge.
2514
+
2515
+ For a buyer-facing tax preview on PDP / PLP / cart, \`estimateTax({ country,
2516
+ subtotal })\` returns the tax portion at the Standard rate for the buyer's
2517
+ country. **Non-binding** \u2014 the authoritative tax still runs at checkout with
2518
+ the full shipping address (state / postal / per-class). Always render with an
2519
+ "Estimate" affordance.
2520
+
2521
+ \`\`\`typescript
2522
+ const { estimatedTax, rate, currency, note } = await store.estimateTax({
2523
+ country: 'IT', subtotal: 100,
2524
+ });
2525
+ // \u2192 { appliesTax: true, rate: 22, estimatedTax: 22, currency: 'EUR',
2526
+ // note: 'Estimate \u2014 final tax calculated at checkout\u2026' }
2527
+ \`\`\`
2528
+
2529
+ ### Regions (multi-currency / per-region providers)
2530
+
2531
+ A region binds countries \u2192 currency + tax-display mode + enabled payment
2532
+ providers. Manage them via the SDK (scopes \`regions:read\` / \`regions:write\`).
2533
+ \`detectRegion\` is a pure client-side helper to map a buyer's country to a
2534
+ region; pass the resolved \`regionId\` to \`createCheckout\` to associate the
2535
+ checkout with a region (recorded for reporting + provider scoping; currency
2536
+ follows the cart until FX price conversion lands).
2537
+
2538
+ \`\`\`typescript
2539
+ const eu = await admin.createRegion({
2540
+ name: 'EU', currency: 'EUR', countries: ['DE', 'FR'],
2541
+ taxInclusive: true, paymentProviderIds: ['app_inst_stripe'],
2542
+ });
2543
+ await admin.setDefaultRegion(eu.id);
2544
+
2545
+ const { data: regions } = await admin.getRegions();
2546
+ const region = admin.detectRegion('DE', regions); // \u2192 eu, else default, else null
2547
+ \`\`\`
2548
+
2549
+ Storefront (public, no apiKey \u2014 \`storeId\` mode): \`getStoreRegions()\` lists
2550
+ active regions, \`getStoreRegion(id)\` returns one region + its payment providers.
2551
+ Pair with \`detectRegion\` to pick the buyer's region for currency display.
2552
+
2553
+ \`\`\`typescript
2554
+ const store = new BrainerceClient({ storeId: 'store_123' });
2555
+ const { data: regions } = await store.getStoreRegions();
2556
+ const region = await store.getStoreRegion(regions[0].id);
2557
+ \`\`\`
2558
+
2559
+ For a single round trip, \`getAutoRegion(country)\` resolves a buyer's country
2560
+ to a region server-side. Brainerce does NOT derive the country from the request
2561
+ IP (the storefront server is what reaches the backend, not the end-customer) \u2014
2562
+ your storefront extracts the country from its edge runtime (Cloudflare
2563
+ \`CF-IPCountry\`, Vercel \`request.geo?.country\`, Fastly \`client-geo-country\`,
2564
+ etc.) and forwards it. Returns \`matched=true\` on explicit country hit, \`false\`
2565
+ when falling back to the default region.
2566
+
2567
+ \`\`\`typescript
2568
+ const country = headers.get('cf-ipcountry') ?? 'US';
2569
+ const { region, matched } = await store.getAutoRegion(country);
2570
+ \`\`\`
2571
+
2572
+ A shipping zone can be limited to regions via \`regionIds\` \u2014 the zone is then
2573
+ only offered to checkouts that resolved to one of those regions. Empty/omitted =
2574
+ available for any region (default); each id must belong to the same store.
2575
+
2576
+ \`\`\`typescript
2577
+ await admin.createShippingZone({
2578
+ name: 'EU Express', countries: ['DE', 'FR', 'IT'], regionIds: [eu.id],
2579
+ });
2580
+ \`\`\``;
2400
2581
  }
2401
2582
  function getContactInquiriesSection() {
2402
2583
  return `## Contact Inquiries & Forms (optional)
@@ -2851,6 +3032,146 @@ entries \u2014 pick a descriptive slug (\`'shipping'\`, \`'returns'\`, \`'about'
2851
3032
  - \`get-type-definitions\` with \`domain: 'content'\` for the TypeScript
2852
3033
  interfaces.`;
2853
3034
  }
3035
+ function getBlogSection() {
3036
+ return `## Blog
3037
+
3038
+ Merchants write and schedule blog posts in **Content \u2192 Blog** in the dashboard.
3039
+ Storefronts choose their own URL scheme \u2014 render posts at \`/blog/[slug]\`,
3040
+ \`/articles/[slug]\`, or whatever fits the brand.
3041
+
3042
+ Public reads carry \`Cache-Control: public, max-age=300, stale-while-revalidate=60\`.
3043
+
3044
+ **Scheduling:** A post is visible once \`status === 'PUBLISHED'\` and
3045
+ \`publishedAt <= now()\`. Set a future \`publishedAt\` while publishing to
3046
+ schedule \u2014 no cron needed; visibility is computed at query time.
3047
+
3048
+ ### Reading posts (any SDK mode)
3049
+
3050
+ \`\`\`typescript
3051
+ // List published posts
3052
+ const { data: posts, meta } = await client.blog.getPosts({ page: 1, limit: 10 });
3053
+
3054
+ // Filter by category or tag
3055
+ const { data: news } = await client.blog.getPosts({ category: 'news' });
3056
+ const { data: tips } = await client.blog.getPosts({ tag: 'tutorial' });
3057
+
3058
+ // Fetch one by slug (returns null on 404)
3059
+ const post = await client.blog.getPost('my-first-post');
3060
+ if (post) {
3061
+ console.log(post.title); // string
3062
+ console.log(post.content); // HTML string from rich-text editor
3063
+ console.log(post.excerpt); // optional short summary
3064
+ console.log(post.tags); // string[]
3065
+ console.log(post.coverImageUrl, post.coverImageAlt);
3066
+ console.log(post.publishedAt); // ISO 8601 or undefined
3067
+ }
3068
+ \`\`\`
3069
+
3070
+ ### BlogPost fields
3071
+
3072
+ | Field | Type | Notes |
3073
+ | ----------------- | ----------- | ------------------------------------- |
3074
+ | \`id\` | string | |
3075
+ | \`title\` | string | |
3076
+ | \`slug\` | string | Unique per store, URL-safe |
3077
+ | \`category\` | string? | Free-form (e.g. \`'news'\`) |
3078
+ | \`content\` | string | HTML from rich-text editor |
3079
+ | \`excerpt\` | string? | Short summary for listing cards |
3080
+ | \`coverImageUrl\` | string? | |
3081
+ | \`coverImageAlt\` | string? | |
3082
+ | \`author\` | string? | |
3083
+ | \`tags\` | string[] | |
3084
+ | \`publishedAt\` | string? | ISO 8601; null = publish immediately |
3085
+ | \`seoTitle\` | string? | |
3086
+ | \`seoDescription\`| string? | |
3087
+ | \`ogImageUrl\` | string? | |
3088
+
3089
+ ### Rendering blog content
3090
+
3091
+ \`\`\`tsx
3092
+ // app/blog/[slug]/page.tsx
3093
+ import DOMPurify from 'isomorphic-dompurify';
3094
+
3095
+ const post = await brainerce.blog.getPost(params.slug);
3096
+ if (!post) notFound();
3097
+
3098
+ // Always sanitize before rendering HTML \u2014 treat external-origin content as untrusted
3099
+ const safeHtml = DOMPurify.sanitize(post.content);
3100
+ return <div dangerouslySetInnerHTML={{ __html: safeHtml }} className="prose" />;
3101
+ \`\`\`
3102
+
3103
+ The \`content\` field is HTML produced by the Lexical rich-text editor.
3104
+ **Always sanitize with DOMPurify (or equivalent) before rendering via
3105
+ \`dangerouslySetInnerHTML\`** \u2014 even though the content originates from your
3106
+ own editor, defense-in-depth prevents any stored-XSS path if content is ever
3107
+ migrated or imported from an external source.
3108
+ Apply a \`prose\` class (Tailwind Typography) for automatic styling.
3109
+
3110
+ ### REST endpoints
3111
+
3112
+ | Method | Path | Returns |
3113
+ |--------|------|---------|
3114
+ | GET | \`/api/stores/:storeId/blog/posts\` | \`BlogPostListResponse\` |
3115
+ | GET | \`/api/stores/:storeId/blog/posts/:slug\` | \`BlogPost\` or 404 |
3116
+ | GET | \`/api/vc/:connectionId/blog/posts\` | Same, channel-scoped |
3117
+ | GET | \`/api/vc/:connectionId/blog/posts/:slug\` | \`BlogPost\` or 404 |
3118
+ `;
3119
+ }
3120
+ function getStorefrontBotSection(connectionId) {
3121
+ return `## Storefront Bot (AI chat widget)
3122
+
3123
+ The store's AI shopping assistant. ALL configuration (name, avatar, colors,
3124
+ greeting, starter questions, capabilities, guardrails) lives in the merchant
3125
+ dashboard \u2014 the embed never decides behavior, and the widget renders nothing
3126
+ until the merchant switches the bot Live.
3127
+
3128
+ ### Zero-code embed (any site)
3129
+
3130
+ \`\`\`html
3131
+ <script src="https://cdn.brainerce.com/bot.js" data-connection-id="${connectionId}" defer></script>
3132
+ \`\`\`
3133
+
3134
+ Keep the tag exactly this bare \u2014 do NOT add \`integrity\` or \`crossorigin\`
3135
+ (the bootstrap is intentionally mutable; it is origin-pinned by CSP instead).
3136
+
3137
+ ### SDK mount (React / Next.js / any bundler)
3138
+
3139
+ \`\`\`ts
3140
+ import { BrainerceBot } from 'brainerce/bot';
3141
+
3142
+ // client-side only (e.g. in a useEffect) \u2014 mounts a floating chat bubble
3143
+ const bot = await BrainerceBot.mount({ connectionId: '${connectionId}' });
3144
+ bot?.destroy(); // optional teardown
3145
+ \`\`\`
3146
+
3147
+ \`mount\` resolves to \`null\` when the bot is disabled (FREE plan, switched
3148
+ off, or unconfigured) \u2014 safe to call unconditionally. Options: \`connectionId\`
3149
+ (required), \`baseUrl\` (API origin override), \`target\` (mount element),
3150
+ \`onAddToCart\` (\`({ productId, variantId, quantity }) => boolean | Promise<boolean>\`
3151
+ \u2014 route the widget's cart adds through the site's own cart; \`variantId\` is
3152
+ null for simple products; return false to fall back to the product page).
3153
+
3154
+ Behavior: persists an anonymous session in localStorage, restores the
3155
+ conversation on revisit, streams answers, and shows product recommendation
3156
+ cards (image, price, add-to-cart / view). Multi-variant products get an
3157
+ in-card variant picker; shoppers can also ask the assistant to add an item
3158
+ and it goes through the same cart chain. Zero-result searches feed the
3159
+ merchant's "unmet demand" analytics. Aside from shopper-initiated cart adds,
3160
+ the bot is read-only.
3161
+
3162
+ Add-to-cart resolution chain: \`onAddToCart\` option \u2192 cancelable
3163
+ \`brainerce:bot:add-to-cart\` CustomEvent on window
3164
+ (\`detail: { productId, variantId, quantity, connectionId }\`; call
3165
+ preventDefault() after handling) \u2192 navigate to the product page.
3166
+
3167
+ Rules:
3168
+ - Mount once per page; do not pass any visual config \u2014 the dashboard owns it.
3169
+ - Do not wrap or restyle the widget; it renders in its own Shadow DOM.
3170
+ - Product card links expect the conventional \`/products/<slug>\` route.
3171
+ - Wire \`onAddToCart\` to the site's cart (see the cart section) so the header
3172
+ count updates when the bot adds items.
3173
+ `;
3174
+ }
2854
3175
  function getSectionByTopic(topic, connectionId, currency) {
2855
3176
  const cid = connectionId || "vc_YOUR_CONNECTION_ID";
2856
3177
  const cur = currency || "USD";
@@ -2889,6 +3210,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2889
3210
  return getTaxDisplaySection(cur);
2890
3211
  case "i18n":
2891
3212
  return getI18nSection();
3213
+ case "multilingual-seo":
3214
+ case "hreflang":
3215
+ case "seo-i18n":
3216
+ return getMultilingualSeoSection();
2892
3217
  case "critical-rules":
2893
3218
  return getCriticalRulesSection() + "\n\n" + getTypeQuickReference();
2894
3219
  case "type-reference":
@@ -2899,6 +3224,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2899
3224
  return getContactInquiriesSection();
2900
3225
  case "content":
2901
3226
  return getContentSection();
3227
+ case "blog":
3228
+ return getBlogSection();
3229
+ case "storefront-bot":
3230
+ return getStorefrontBotSection(cid);
2902
3231
  case "all":
2903
3232
  return [
2904
3233
  "# Brainerce SDK \u2014 full topic dump",
@@ -2983,6 +3312,10 @@ function getSectionByTopic(topic, connectionId, currency) {
2983
3312
  "",
2984
3313
  "---",
2985
3314
  "",
3315
+ getMultilingualSeoSection(),
3316
+ "",
3317
+ "---",
3318
+ "",
2986
3319
  getAdminApiSection(),
2987
3320
  "",
2988
3321
  "---",
@@ -2991,10 +3324,18 @@ function getSectionByTopic(topic, connectionId, currency) {
2991
3324
  "",
2992
3325
  "---",
2993
3326
  "",
2994
- getContentSection()
3327
+ getContentSection(),
3328
+ "",
3329
+ "---",
3330
+ "",
3331
+ getBlogSection(),
3332
+ "",
3333
+ "---",
3334
+ "",
3335
+ getStorefrontBotSection(cid)
2995
3336
  ].join("\n");
2996
3337
  default:
2997
- return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, all`;
3338
+ return `Unknown topic: "${topic}". Available topics: setup, products, cart, checkout, checkout-custom-fields, payment, auth, order-confirmation, inventory, discounts, recommendations, product-customization-fields, tax, i18n, critical-rules, type-reference, admin, inquiries, content, blog, all`;
2998
3339
  }
2999
3340
  }
3000
3341
 
@@ -3023,6 +3364,7 @@ var GET_SDK_DOCS_SCHEMA = {
3023
3364
  "admin",
3024
3365
  "inquiries",
3025
3366
  "content",
3367
+ "storefront-bot",
3026
3368
  "all"
3027
3369
  ]).describe("The SDK documentation topic to retrieve"),
3028
3370
  salesChannelId: import_zod.z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
@@ -3054,12 +3396,18 @@ interface Product {
3054
3396
  description?: string | null;
3055
3397
  descriptionFormat?: 'text' | 'html' | 'markdown' | null;
3056
3398
  sku: string;
3057
- basePrice: string; // Use parseFloat() for calculations
3058
- salePrice?: string | null;
3399
+ basePrice: string; // For VARIABLE products: MIN(variants.price). For SIMPLE: the parent price. parseFloat() for math.
3400
+ salePrice?: string | null; // For VARIABLE: MIN(variants.salePrice WHERE NOT NULL) \u2014 null iff no variant is on sale (WC is_on_sale() semantic). For SIMPLE: the parent sale price. Reliable "on sale?" check: product.salePrice !== null.
3059
3401
  costPrice?: string | null;
3060
- priceMin?: string | null; // Lowest variant price (VARIABLE products). Use for catalog/JSON-LD range display.
3061
- priceMax?: string | null; // Highest variant price (VARIABLE products).
3402
+ priceMin?: string | null; // Lowest variant price (VARIABLE products) \u2014 same as basePrice for VARIABLE, kept for back-compat and JSON-LD range display.
3403
+ priceMax?: string | null; // Highest variant price (VARIABLE products). Use with priceMin for "\u20AA49 \u2013 \u20AA199" range.
3062
3404
  priceVaries?: boolean; // true when variant prices differ \u2014 show "\u20AA49 \u2013 \u20AA199" range.
3405
+ // FX DISPLAY overlay (PRD \xA723). Set only when getProducts({ regionId }) was called AND region.currency !== store.currency. basePrice/salePrice above stay in store currency \u2014 these are additive, display-only. The buyer is still charged in store currency at checkout; payment provider handles customer-side FX.
3406
+ displayPrice?: string; // basePrice \xD7 daily FX rate, in displayCurrency.
3407
+ displaySalePrice?: string; // salePrice \xD7 rate (if salePrice present).
3408
+ displayPriceMin?: string; // priceMin \xD7 rate (VARIABLE products).
3409
+ displayPriceMax?: string; // priceMax \xD7 rate (VARIABLE products).
3410
+ displayCurrency?: string; // ISO 4217 of the region \u2014 e.g. "EUR".
3063
3411
  status: string;
3064
3412
  type: 'SIMPLE' | 'VARIABLE';
3065
3413
  isDownloadable?: boolean;
@@ -3103,6 +3451,10 @@ interface ProductVariant {
3103
3451
  name?: string | null;
3104
3452
  price?: string | null;
3105
3453
  salePrice?: string | null;
3454
+ // FX DISPLAY overlay (PRD \xA723) \u2014 same semantics as on the parent Product.
3455
+ displayPrice?: string;
3456
+ displaySalePrice?: string;
3457
+ displayCurrency?: string;
3106
3458
  attributes?: Record<string, string> | null;
3107
3459
  options?: Array<{ name: string; value: string }>;
3108
3460
  inventory?: InventoryInfo | null;
@@ -3174,6 +3526,11 @@ interface ProductQueryParams {
3174
3526
  metafields?: Record<string, string | string[]>;
3175
3527
  sortBy?: 'name' | 'price' | 'createdAt';
3176
3528
  sortOrder?: 'asc' | 'desc';
3529
+ // PRD \xA722: resolve DISPLAY prices for this region. When set + valid, each
3530
+ // product/variant gains resolvedPrice/resolvedCurrency/priceSource (additive;
3531
+ // basePrice/salePrice untouched). Absent/invalid region \u2192 nothing attached.
3532
+ // Display-only. Ignored in vibe-coded (vc_*) mode (storefront/admin paths only).
3533
+ regionId?: string;
3177
3534
  }
3178
3535
 
3179
3536
  interface SearchSuggestions {
@@ -3299,6 +3656,7 @@ interface Checkout {
3299
3656
  status: CheckoutStatus;
3300
3657
  email?: string | null;
3301
3658
  customerId?: string | null;
3659
+ regionId?: string | null; // multi-region: recorded for reporting + provider scoping (currency follows the cart until FX lands)
3302
3660
  shippingAddress?: CheckoutAddress | null;
3303
3661
  billingAddress?: CheckoutAddress | null;
3304
3662
  shippingRateId?: string | null;
@@ -3375,6 +3733,7 @@ interface CreateCheckoutDto {
3375
3733
  cartId: string;
3376
3734
  customerId?: string;
3377
3735
  selectedItemIds?: string[]; // Partial checkout
3736
+ regionId?: string; // multi-region: associate the checkout with a region (must belong to the store; 400 if unknown)
3378
3737
  }
3379
3738
 
3380
3739
  // startGuestCheckout() return type \u2014 DISCRIMINATED UNION
@@ -3393,6 +3752,8 @@ interface TaxBreakdownItem {
3393
3752
  name: string;
3394
3753
  rate: number; // decimal: 0.17 = 17%
3395
3754
  amount: number;
3755
+ taxClassId?: string | null; // rate's tax class (null = Standard)
3756
+ taxClassSlug?: string | null; // class slug for attribution (null = Standard)
3396
3757
  }`;
3397
3758
  var ORDERS_TYPES = `// ---- Orders ----
3398
3759
 
@@ -3450,6 +3811,7 @@ interface OrderItem {
3450
3811
  // Snapshot of buyer-submitted customization values captured at checkout.
3451
3812
  // Keyed by metafield slug. \`value\` is string[] for MULTI_SELECT / GALLERY, string otherwise.
3452
3813
  customizations?: Record<string, { label: string; value: string | string[]; type: string }>;
3814
+ taxClassSlug?: string; // frozen slug of the line's resolved tax class (omitted = Standard fallback)
3453
3815
  }
3454
3816
 
3455
3817
  interface OrderCustomer {
@@ -3632,7 +3994,7 @@ function formatPrice(priceString: string | number | undefined | null, options?:
3632
3994
  function getProductPrice(product: Pick<Product, 'basePrice' | 'salePrice'>): number;
3633
3995
  function getProductPriceInfo(product: Pick<Product, 'basePrice' | 'salePrice' | 'discount' | 'priceMin' | 'priceVaries'>): {
3634
3996
  price: number; originalPrice: number; isOnSale: boolean; discountAmount: number; discountPercent: number;
3635
- }; // Falls back to priceMin when basePrice=0 (VARIABLE products)
3997
+ }; // For VARIABLE products, basePrice/salePrice are pre-aggregated (MIN of variants) \u2014 the helper just reads them. Use this whenever you need an "on sale?" badge or a "X% off" label.
3636
3998
  function getVariantPrice(variant: Pick<ProductVariant, 'price' | 'salePrice'>, productBasePrice: string): number;
3637
3999
 
3638
4000
  // Cart helpers
@@ -4165,6 +4527,122 @@ export interface Content<T extends ContentType = ContentType> extends ContentSum
4165
4527
  // stale-while-revalidate=60. Storefront changes propagate within ~5 min
4166
4528
  // of the merchant publishing. Do not add extra client-side caching
4167
4529
  // beyond Next.js's default fetch cache.`;
4530
+ var REGIONS_TYPES = `// ---- Regions & Tax Classes (Admin mode, apiKey) ----
4531
+ // storeId is derived from the API key \u2014 never pass it on admin calls.
4532
+
4533
+ // ---- Regions ---- (scopes: regions:read / regions:write)
4534
+ // A region binds countries \u2192 currency + tax-display mode + payment providers.
4535
+ interface Region {
4536
+ id: string;
4537
+ accountId: string;
4538
+ storeId: string;
4539
+ name: string;
4540
+ slug: string;
4541
+ currency: string; // ISO 4217, e.g. "EUR"
4542
+ countries: string[]; // ISO 3166-1 alpha-2, e.g. ["DE","FR"]
4543
+ taxInclusive: boolean; // show prices tax-inclusive in this region?
4544
+ automaticTaxes: boolean;
4545
+ isDefault: boolean; // fallback when buyer's country maps to no region
4546
+ isActive: boolean;
4547
+ paymentProviders?: RegionPaymentProvider[];
4548
+ createdAt: string;
4549
+ updatedAt: string;
4550
+ }
4551
+
4552
+ interface RegionPaymentProvider {
4553
+ id: string;
4554
+ regionId: string;
4555
+ appInstallationId: string;
4556
+ isEnabled: boolean;
4557
+ createdAt: string;
4558
+ }
4559
+
4560
+ interface CreateRegionDto {
4561
+ name: string;
4562
+ currency: string; // ISO 4217
4563
+ countries: string[]; // ISO 3166-1 alpha-2
4564
+ taxInclusive?: boolean;
4565
+ automaticTaxes?: boolean;
4566
+ isDefault?: boolean;
4567
+ paymentProviderIds?: string[]; // AppInstallation IDs to enable here
4568
+ }
4569
+ interface UpdateRegionDto extends Partial<CreateRegionDto> { isActive?: boolean }
4570
+
4571
+ // client.detectRegion(country, regions): Region | null \u2014 pure, no network.
4572
+ // \u2192 region whose countries includes the code, else the default region, else null.
4573
+ // Pass the resolved regionId to createCheckout to associate the checkout with a
4574
+ // region (recorded for reporting + provider scoping; currency follows the cart
4575
+ // until FX price conversion lands).
4576
+ //
4577
+ // Storefront (public, no apiKey \u2014 storeId mode):
4578
+ interface PublicRegion {
4579
+ id: string; name: string; slug: string; currency: string;
4580
+ countries: string[]; taxInclusive: boolean; isDefault: boolean;
4581
+ }
4582
+ interface PublicRegionDetail extends PublicRegion {
4583
+ paymentProviders: Array<{ id: string; appId: string; name: string | null }>;
4584
+ }
4585
+ // getStoreRegions(): { data: PublicRegion[] } \u2014 active regions, default first.
4586
+ // getStoreRegion(regionId): PublicRegionDetail \u2014 one region + its providers.
4587
+ interface AutoRegionResponse {
4588
+ region: PublicRegion | null;
4589
+ matched: boolean; // true=country was in a region's list; false=fell back to default
4590
+ country: string; // upper-cased ISO-3166-1 alpha-2; '' when caller omitted it
4591
+ }
4592
+ // getAutoRegion(country): AutoRegionResponse \u2014 server-side resolution in one
4593
+ // round trip. Pair with the country your edge runtime extracts
4594
+ // (CF-IPCountry / request.geo.country / etc.) \u2014 Brainerce does NOT derive the
4595
+ // country from the request IP server-side (storefront != end-customer).
4596
+
4597
+ // ---- Tax Classes ---- (scopes: tax-classes:read / tax-classes:write)
4598
+ // Charge differential rates by product type. A TaxRate may target a class via
4599
+ // taxClassId; a rate with taxClassId=null is the Standard fallback. Per-line
4600
+ // resolution: variant \u2192 product \u2192 category \u2192 store default \u2192 null.
4601
+ interface TaxClass {
4602
+ id: string;
4603
+ accountId: string;
4604
+ storeId: string;
4605
+ name: string;
4606
+ slug: string; // kebab-case, unique per store
4607
+ description?: string | null;
4608
+ isDefault: boolean; // auto-applied to products without an explicit class
4609
+ createdAt: string;
4610
+ updatedAt: string;
4611
+ }
4612
+ interface CreateTaxClassDto { name: string; slug: string; description?: string; isDefault?: boolean }
4613
+ type UpdateTaxClassDto = Partial<CreateTaxClassDto>;
4614
+ // Bulk-assign a class to entities:
4615
+ interface AssignTaxClassDto { productIds?: string[]; variantIds?: string[]; categoryIds?: string[] }
4616
+
4617
+ // TaxRate / CreateTaxRateDto carry an optional taxClassId (null = Standard).
4618
+ // rate is a WHOLE PERCENTAGE (7.25 = 7.25%).
4619
+ //
4620
+ // SDK methods (admin):
4621
+ // Regions: getRegions(), getRegion(id), createRegion(dto), updateRegion(id, dto),
4622
+ // deleteRegion(id), setDefaultRegion(id), updateRegionPaymentProviders(id, ids),
4623
+ // addRegionCountries(id, codes), removeRegionCountry(id, code),
4624
+ // getRegionCompatibleProviders(id), detectRegion(country, regions)
4625
+ // Tax classes: getTaxClasses(), getTaxClass(id), createTaxClass(dto), updateTaxClass(id, dto),
4626
+ // deleteTaxClass(id), setDefaultTaxClass(id), assignTaxClass(id, dto),
4627
+ // mergeTaxClasses(id, targetId)
4628
+ //
4629
+ // SDK methods (storefront, public \u2014 storeId mode, no apiKey):
4630
+ // getStoreRegions(), getStoreRegion(id), getAutoRegion(country)
4631
+ // getStoreTaxClasses(), estimateTax({ country?, subtotal })
4632
+ //
4633
+ // estimateTax returns:
4634
+ interface TaxEstimateResponse {
4635
+ appliesTax: boolean;
4636
+ rate: number | null; // percent (18 = 18%) \u2014 null when no matching rule
4637
+ rateName: string | null;
4638
+ estimatedTax: number; // tax portion of subtotal in store currency
4639
+ pricesIncludeTax: boolean;
4640
+ currency: string; // store currency (cart/order currency)
4641
+ note: string; // disclaimer \u2014 preview is non-binding
4642
+ }
4643
+ // Non-binding by design: the authoritative tax runs at checkout against the
4644
+ // full shipping address. The country comes from your edge runtime
4645
+ // (CF-IPCountry / request.geo.country / etc.), NOT the request IP.`;
4168
4646
  var TYPES_BY_DOMAIN = {
4169
4647
  products: PRODUCTS_TYPES,
4170
4648
  cart: CART_TYPES,
@@ -4176,7 +4654,8 @@ var TYPES_BY_DOMAIN = {
4176
4654
  inquiries: INQUIRIES_TYPES,
4177
4655
  reviews: REVIEWS_TYPES,
4178
4656
  "modifier-groups": MODIFIER_GROUPS_TYPES,
4179
- content: CONTENT_TYPES
4657
+ content: CONTENT_TYPES,
4658
+ regions: REGIONS_TYPES
4180
4659
  };
4181
4660
  function getTypesByDomain(domain) {
4182
4661
  if (domain === "all") {
@@ -4207,10 +4686,12 @@ var GET_TYPE_DEFINITIONS_SCHEMA = {
4207
4686
  "helpers",
4208
4687
  "inquiries",
4209
4688
  "reviews",
4689
+ "modifier-groups",
4210
4690
  "content",
4691
+ "regions",
4211
4692
  "all"
4212
4693
  ]).describe(
4213
- 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page.'
4694
+ 'The domain of types to retrieve. Use "helpers" for helper function signatures and common types like StoreInfo, PaginatedResponse. Use "content" for FAQ / Footer / Header / Announcement / RichText / Page. Use "regions" for Region / TaxClass admin types.'
4214
4695
  )
4215
4696
  };
4216
4697
  async function handleGetTypeDefinitions(args) {
@@ -6000,11 +6481,16 @@ Build both steps EVEN IF the store has no email provider configured today \u2014
6000
6481
  });
6001
6482
  window.location.href = authorizationUrl; // full-page redirect, NOT a popup
6002
6483
  \`\`\`
6003
- 3. **On the callback page** the URL contains \`token\` + \`oauth_success\` (or \`oauth_error\`) query params. Extract and apply the token:
6484
+ 3. **On the callback page** the URL contains \`auth_code\` + \`oauth_success\` (or \`oauth_error\`) query params. Exchange the single-use code for the JWT \u2014 never read the token from the URL:
6004
6485
  \`\`\`ts
6005
- const token = new URLSearchParams(location.search).get('token');
6006
- if (token) client.setCustomerToken(token); // then redirect to account
6486
+ const params = new URLSearchParams(location.search);
6487
+ const code = params.get('auth_code');
6488
+ if (code) {
6489
+ const result = await client.exchangeOAuthCode(code);
6490
+ client.setCustomerToken(result.token); // then redirect to account
6491
+ }
6007
6492
  \`\`\`
6493
+ The legacy \`?token=\` URL param is still emitted for backward compatibility but will be removed in the next major release \u2014 migrate to \`auth_code\` now.
6008
6494
  4. **On \`oauth_error\`:** redirect to login with an error message.
6009
6495
 
6010
6496
  Build the OAuth button region AND the callback handler even when no providers are configured. They auto-hide.`
@@ -6486,7 +6972,9 @@ function renderCapabilitiesSummary(caps) {
6486
6972
  );
6487
6973
  lines.push(`- Downloadable products: ${caps.features.hasDownloadableProducts ? "yes" : "no"}`);
6488
6974
  lines.push(`- Checkout custom fields: ${caps.features.hasCheckoutCustomFields ? "yes" : "no"}`);
6489
- lines.push(`- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`);
6975
+ lines.push(
6976
+ `- Content (FAQ/footer/header/announcements/pages): ${caps.features.hasContent ? "seeded" : "none \u2014 build chrome UI with fallbacks"}`
6977
+ );
6490
6978
  lines.push(
6491
6979
  `- Email verification: ${caps.connection.requireEmailVerification ? "required" : "not required (still build the verify-email flow)"}`
6492
6980
  );