@fayz-ai/storefront 0.12.1 → 0.13.1
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/{chunk-OYKFJ6FG.js → chunk-6DWZAAIW.js} +74 -24
- package/dist/chunk-6DWZAAIW.js.map +1 -0
- package/dist/components/SmoothImage.d.ts +17 -1
- package/dist/components/SmoothImage.d.ts.map +1 -1
- package/dist/components/collection/CategoryShowcase.d.ts.map +1 -1
- package/dist/components/product/ProductCard.d.ts.map +1 -1
- package/dist/components/product/ProductGallery.d.ts.map +1 -1
- package/dist/data/facets.d.ts +9 -0
- package/dist/data/facets.d.ts.map +1 -1
- package/dist/document/config.d.ts +12 -0
- package/dist/document/config.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/seo.d.ts.map +1 -1
- package/dist/render.js +1 -1
- package/dist/views/CatalogPage.d.ts.map +1 -1
- package/dist/views/MyPurchasesPage.d.ts.map +1 -1
- package/dist/views/ProductDetailPage.d.ts.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-OYKFJ6FG.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app/define.ts","../src/app/scaffold.tsx","../src/document/upgrade.ts","../src/document/change.ts","../src/document/describe.ts","../src/hooks/use-catalog.ts","../src/hooks/use-storefront.ts","../src/hooks/use-region.ts","../src/hooks/use-policies.ts","../src/hooks/use-cart.ts","../src/hooks/use-checkout.ts","../src/hooks/use-payment-methods.ts","../src/hooks/use-shipping.ts","../src/hooks/use-address.ts","../src/hooks/use-order.ts","../src/extend/editor-bridge.ts","../src/blocks/block-at-path.ts","../src/document/overlay.ts","../src/document/presets.ts","../src/views/HomePage.tsx","../src/index.ts"],"names":["React","here","position","clone","sectionOf","before","to","listDeprecations","isRecord","describeBlocks","result","jsx","core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,IAAM,mBAAA,GAAsB;AAAA,EACjC,IAAA,EAAM,YAAA;AAAA,EACN,MAAA,EAAQ,cAAA;AAAA,EACR,IAAA,EAAM,YAAA;AAAA,EACN,OAAA,EAAS,eAAA;AAAA,EACT,IAAA,EAAM;AACR;ACxTO,SAAS,kBAAA,CAAmB,EAAE,QAAA,EAAS,EAAiD;AAC7F,EAAA,uBAAOC,IAAC,cAAA,EAAA,EAAe,IAAA,EAAK,QAAO,IAAA,EAAM,EAAE,MAAA,EAAQ,QAAA,EAAS,EAAG,CAAA;AACjE;AAEO,SAAS,QAAA,CAAS,EAAE,QAAA,EAAS,EAAiD;AACnF,EAAA,uBAAOA,GAAAA,CAAC,kBAAA,EAAA,EAAmB,QAAA,EAAoB,CAAA;AACjD;AC0dO,IAAM,SAAA,GAAkC,IAAI,IAAA,KAAS;AAC1D,EAAA,0BAAA,EAA2B;AAC3B,EAAA,OAAOC,WAAA,CAAc,GAAG,IAAI,CAAA;AAC9B","file":"index.js","sourcesContent":["import type {\n StorefrontConfig,\n StorefrontRouteDefinition,\n} from '../document/config'\nimport type { StorefrontComponents } from '../extend/component-contracts'\nimport type { StorefrontSection } from '../blocks/sections'\nimport type { CreateStorefrontOptions } from './createStorefrontApp'\n\n/**\n * Identity helpers for generated/custom storefronts.\n *\n * They do not add runtime behavior; they make the intended client-app shape\n * explicit and keep TypeScript inference tight across config, components, routes,\n * sections and app creation options.\n */\nexport function defineStorefrontConfig<const T extends StorefrontConfig>(config: T): T {\n return config\n}\n\nexport function defineStorefrontComponents<const T extends StorefrontComponents>(components: T): T {\n return components\n}\n\nexport function defineStorefrontRoutes<const T extends readonly StorefrontRouteDefinition[]>(routes: T): T {\n return routes\n}\n\nexport function defineStorefrontSections<const T extends readonly StorefrontSection[]>(sections: T): T {\n return sections\n}\n\nexport function defineStorefrontApp<const T extends CreateStorefrontOptions>(options: T): T {\n return options\n}\n","import React from 'react'\nimport { registerScaffold, defineApp } from '@fayz-ai/core'\nimport type { AppManifest, BackendProvider } from '@fayz-ai/core'\nimport { StorefrontConfigProvider, resolveConfig } from '../document/config'\nimport { StorefrontConfigHost } from '../document/store-policy'\nimport type { StorefrontConfig } from '../document/config'\nimport type { StorefrontTheme } from '../lib/theme'\nimport type { HomeConfig, NavLink, FooterConfig } from '../blocks/sections'\nimport { initStorefrontRuntime, StorefrontShell } from './createStorefrontApp'\nimport { exportStore, hydrateStoreDocument, slugifyStoreName } from '../document/round-trip'\nimport '../blocks/registry' // ensure section blocks are registered\n\ntype StorefrontBackendProvider = NonNullable<StorefrontConfig['backend']>['provider']\n\n// ---------------------------------------------------------------------------\n// Storefront scaffold — renders a store from a pure-data AppManifest.\n//\n// The storefront surface carries its full declarative form as a Store Document\n// (surface.options.document, see store-document.ts): every serializable config\n// field lives in a document section, and code-valued fields (components,\n// routes, provider, adapters, JSX) are referenced by registered handle NAME.\n// The in-memory config Map this file used to keep is gone — a document plus\n// the handle registry reconstitutes the store in any session, which is what\n// makes export/diff/edit by an agent possible at all (spine §3 L0).\n// ---------------------------------------------------------------------------\n\n/** StorefrontConfig → AppManifest (the sugar-to-data direction). */\nexport function defineStorefront(config: StorefrontConfig): AppManifest {\n const id = slugifyStoreName(config.name)\n // Serialize the whole config into the document, auto-registering handles\n // (`<id>.<path>`) for code values the app did not name itself. Explicitly\n // registered handles win the reverse lookup, so a store that calls\n // registerHandle keeps its own names in the document.\n const document = exportStore(config, { appId: id, registerMissingHandles: true })\n const backendProvider = (config.backend?.provider ?? (config.provider ? 'custom' : 'mock')) as BackendProvider\n\n return defineApp({\n id,\n name: config.name,\n backend: {\n provider: backendProvider,\n url: config.backend?.url,\n },\n locale: {\n default: config.locale ?? 'pt-BR',\n supported: [config.locale ?? 'pt-BR'],\n currency: config.currency ?? 'BRL',\n },\n theme: config.theme as Record<string, unknown> | undefined,\n surfaces: {\n storefront: {\n scaffold: 'storefront',\n options: { document: document as unknown as Record<string, unknown> },\n },\n },\n })\n}\n\n/**\n * AppManifest → StorefrontConfig (the data-to-render direction).\n *\n * New manifests carry a Store Document; hydration resolves code by handle\n * name. `onError: 'report'` deliberately: this is the shopper path, and a\n * stale document must degrade loudly in the console rather than white-screen\n * the store (I7). The authoring loop gets the hard errors from\n * validateStore / `fayz validate` instead.\n *\n * Legacy manifests (committed before the document existed) carry flat surface\n * options; they map best-effort, without the code-valued fields — which is\n * exactly what they carried across sessions before, since the old in-memory\n * Map only worked inside the session that authored it.\n */\nfunction manifestToStorefrontConfig(manifest: AppManifest, surfaceName: string): StorefrontConfig {\n const surface = manifest.surfaces[surfaceName]\n const o = (surface?.options ?? {}) as Record<string, unknown>\n\n if (o.document && typeof o.document === 'object') {\n return hydrateStoreDocument(o.document as Record<string, unknown>, { onError: 'report' })\n }\n\n return {\n name: manifest.name,\n currency: (manifest.locale as { currency?: string } | undefined)?.currency,\n locale: (manifest.locale as { default?: string } | undefined)?.default,\n theme: manifest.theme as StorefrontTheme | undefined,\n announcement: o.announcement as string | undefined,\n home: o.home as HomeConfig | undefined,\n pages: o.pages as StorefrontConfig['pages'],\n nav: o.nav as NavLink[] | undefined,\n footer: o.footer as FooterConfig | undefined,\n shipping: o.shipping as StorefrontConfig['shipping'],\n features: o.features as StorefrontConfig['features'],\n catalog: o.catalog as StorefrontConfig['catalog'],\n backend: {\n provider: manifest.backend?.provider as StorefrontBackendProvider,\n url: manifest.backend?.url,\n },\n }\n}\n\nexport function StorefrontScaffold({ manifest, surface }: { manifest: AppManifest; surface: string }) {\n const config = React.useMemo(() => manifestToStorefrontConfig(manifest, surface), [manifest, surface])\n const resolved = React.useMemo(() => resolveConfig(config), [config])\n const inited = React.useRef(false)\n if (!inited.current) {\n initStorefrontRuntime(config)\n inited.current = true\n }\n return (\n <StorefrontConfigHost config={resolved}>\n <StorefrontShell />\n </StorefrontConfigHost>\n )\n}\nStorefrontScaffold.displayName = 'StorefrontScaffold'\n\n// Registration is lazy (called from the storefront renderApp wrapper and\n// createStorefront*) so that importing the @fayz-ai/storefront barrel stays\n// side-effect-free and tree-shakable.\nlet storefrontScaffoldRegistered = false\nexport function registerStorefrontScaffold(): void {\n if (storefrontScaffoldRegistered) return\n storefrontScaffoldRegistered = true\n registerScaffold('storefront', StorefrontScaffold, { source: 'sdk', label: 'Storefront' })\n}\n","import { getDeprecation, listDeprecations } from '@fayz-ai/sdk/deprecations'\nimport type { FayzDeprecation } from '@fayz-ai/sdk/deprecations'\nimport { storefrontDiscountToPromotion } from '@fayz-ai/shop/rules'\nimport type { Promotion } from '@fayz-ai/shop/rules'\nimport { STORE_SECTIONS, isRecord } from './sections'\nimport type { StoreDocument, StoreSectionName } from './sections'\nimport { validateStore } from './validate'\nimport type { StoreValidationReport } from './validate'\n\n// ---------------------------------------------------------------------------\n// `fayz upgrade` — codemods keyed to document version (spine M10).\n//\n// The store document already carries a per-SECTION version, following\n// WooCommerce Blueprint's `get_schema(int $version)`. M10 makes that number\n// mean something operational: a codemod declares the section and the exact\n// version it moves FROM and TO, so \"has this store been migrated\" is a lookup\n// rather than a judgement, and one SDK serves a migrated and an unmigrated\n// fleet at the same time. A deprecated field is accepted below the version\n// that retires it and is a hard validation error at or above it — the shim and\n// the removal are the same declaration, read from two sides.\n//\n// THE REFUSAL RULE, which is the whole reason this is trustworthy: a codemod\n// that cannot be safe does not do its best. It refuses, names the decision a\n// human must make, and leaves the document byte-identical. Guessing here would\n// be worse than not having the command, because the failure lands in a store's\n// checkout and nobody would know which run caused it.\n//\n// Every function in this module is PURE. Reading and writing files is the\n// CLI's job; this half has to stay testable and has to be callable from the\n// author loop next to describeStore / validateStore / applyChange.\n// ---------------------------------------------------------------------------\n\n/** One deprecated thing found in one store. */\nexport interface StoreDeprecationFinding {\n /** Registry row id. */\n id: string\n /** Dotted document path, when the deprecation is on the document surface. */\n path?: string\n /** What exactly was found, in the author's words. */\n detail: string\n deprecatedIn: string\n removeIn: string\n /** I2 — always present, always the thing to write instead. */\n replacement: string\n /** The codemod that answers it. */\n codemod: string\n /** False when only a human can retire it (pool state, code outside the document). */\n automatable: boolean\n}\n\n/** Why a codemod would not run, and what a human has to decide instead. */\nexport interface StoreCodemodRefusal {\n reason: string\n /** The decisions, one per line. Never a suggestion the codemod could have\n * taken itself — if it could, it would have. */\n decide: string[]\n}\n\nexport type StoreCodemodStatus =\n /** The document changed (possibly only its section version). */\n | 'applied'\n /** Nothing here to migrate: the section is absent, or already past this version. */\n | 'not-applicable'\n /** Something is here, and moving it safely needs a human. */\n | 'refused'\n\n/** A section version move — the key the codemod is filed under. */\nexport interface StoreCodemodVersionKey {\n section: StoreSectionName\n from: number\n to: number\n}\n\nexport interface StoreCodemodResult {\n codemod: string\n status: StoreCodemodStatus\n /** Registry ids this codemod retires. */\n deprecations: string[]\n /** The version move, or null for a deprecation that is not on the document\n * surface at all — which is itself why such a codemod always refuses. */\n version: StoreCodemodVersionKey | null\n /** One line per document change, in the applyChange path vocabulary. */\n changes: string[]\n note: string\n refusal?: StoreCodemodRefusal\n}\n\nexport interface StoreUpgradeOptions {\n /** Restrict the run to these codemod ids. Unknown ids are a hard error\n * naming the valid set (I2). */\n only?: readonly string[]\n}\n\nexport interface StoreUpgradeResult {\n /** False when a codemod refused or the result would not validate. */\n ok: boolean\n /** The upgraded document. Deep-equal to the input when `changed` is false. */\n doc: StoreDocument\n changed: boolean\n deprecations: StoreDeprecationFinding[]\n codemods: StoreCodemodResult[]\n /** The result validated. A codemod that would break the document is a bug\n * in the codemod, and this is where it surfaces. */\n validation: StoreValidationReport\n}\n\n// --- Detection ----------------------------------------------------------------\n\nfunction sectionOf(doc: Record<string, unknown>, name: string): Record<string, unknown> | null {\n const value = doc[name]\n return isRecord(value) ? value : null\n}\n\nfunction sectionVersion(doc: Record<string, unknown>, name: StoreSectionName): number | null {\n const section = sectionOf(doc, name)\n if (!section) return null\n return typeof section.version === 'number' ? section.version : null\n}\n\nfunction finding(row: FayzDeprecation, detail: string, path: string | undefined, automatable: boolean): StoreDeprecationFinding {\n return {\n id: row.id,\n path,\n detail,\n deprecatedIn: row.deprecatedIn,\n removeIn: row.removeIn,\n replacement: row.replacement,\n codemod: row.codemod,\n automatable,\n }\n}\n\n/**\n * What in THIS document is deprecated — the machine-readable answer to the\n * question I10 exists to make askable.\n *\n * Only the document surface is visible from here. A deprecation living in the\n * store's own code (the productMetadata overlay) or in a pool (the two SQL\n * ones) is reported by its row as un-automatable rather than omitted: an\n * enumerable deprecation that quietly drops the ones you cannot see from a\n * JSON file would be the silent-failure mode the whole spine is against.\n */\nexport function scanStoreDeprecations(input: StoreDocument | Record<string, unknown>): StoreDeprecationFinding[] {\n const doc = input as Record<string, unknown>\n const found: StoreDeprecationFinding[] = []\n\n for (const row of listDeprecations()) {\n if (row.surface !== 'document-field') continue\n\n if (row.id === 'storefront.commerce.discounts') {\n const commerce = sectionOf(doc, 'commerce')\n const discounts = commerce?.discounts\n if (Array.isArray(discounts) && discounts.length > 0) {\n const codes = discounts\n .map((entry) => (isRecord(entry) && typeof entry.code === 'string' ? entry.code : '?'))\n .join(', ')\n found.push(\n finding(row, `${discounts.length} legacy coupon code(s): ${codes}`, 'commerce.discounts', true),\n )\n }\n continue\n }\n\n if (row.id === 'storefront.backend.supabaseUrl' || row.id === 'storefront.backend.supabaseAnonKey') {\n const field = row.id === 'storefront.backend.supabaseUrl' ? 'supabaseUrl' : 'supabaseAnonKey'\n const backend = sectionOf(doc, 'backend')\n if (backend && typeof backend[field] === 'string') {\n found.push(finding(row, `legacy backend.${field} is set`, `backend.${field}`, true))\n }\n continue\n }\n }\n\n return found\n}\n\n/**\n * The deprecations no document can answer for, with the reason.\n *\n * The CLI merges these into its report so `fayz upgrade` never implies a store\n * is clean when the only reason it looks clean is that the evidence is not in\n * the repo.\n */\nexport function unobservableDeprecations(): StoreDeprecationFinding[] {\n return listDeprecations()\n .filter((row) => row.surface !== 'document-field')\n .map((row) => finding(row, row.detect, undefined, false))\n}\n\n// --- The codemods -------------------------------------------------------------\n\ninterface Codemod {\n id: string\n title: string\n version: StoreCodemodVersionKey | null\n run(doc: Record<string, unknown>): StoreCodemodResult\n}\n\nfunction result(\n mod: Pick<Codemod, 'id' | 'version'>,\n status: StoreCodemodStatus,\n note: string,\n extra: Partial<StoreCodemodResult> = {},\n): StoreCodemodResult {\n return {\n codemod: mod.id,\n status,\n deprecations: listDeprecations().filter((row) => row.codemod === mod.id).map((row) => row.id),\n version: mod.version,\n changes: [],\n note,\n ...extra,\n }\n}\n\n/** Deep clone through JSON — the document is JSON by construction (exportStore\n * refuses anything else), so this cannot lose a value. */\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nconst PERCENT_CODE_KEYS = new Set(['code', 'percent', 'title'])\n\n/**\n * commerce.discounts → promotions.promotions (commerce v1 → v2).\n *\n * Safe because the translation is not invented here: it is\n * `storefrontDiscountToPromotion`, the SAME function the runtime shim already\n * routes every legacy code through. The money after the codemod is the money\n * before it, by construction rather than by review.\n */\nconst discountsToPromotions: Codemod = {\n id: 'commerce.discounts-to-promotions',\n title: 'Legacy percent coupon codes become rule-engine promotions',\n version: { section: 'commerce', from: 1, to: 2 },\n run(doc) {\n const mod = discountsToPromotions\n const version = sectionVersion(doc, 'commerce')\n if (version === null) return result(mod, 'not-applicable', 'no commerce section')\n if (version !== 1) return result(mod, 'not-applicable', `commerce is already at version ${version}`)\n\n const commerce = sectionOf(doc, 'commerce')!\n const raw = commerce.discounts\n const entries = Array.isArray(raw) ? raw : []\n\n // --- refuse before touching anything -------------------------------------\n const decide: string[] = []\n\n for (const [index, entry] of entries.entries()) {\n const at = `commerce.discounts[${index}]`\n if (!isRecord(entry)) {\n decide.push(`${at} is not an object — rewrite it as {code, percent, title?} or delete it.`)\n continue\n }\n const unknown = Object.keys(entry).filter((key) => !PERCENT_CODE_KEYS.has(key))\n if (unknown.length > 0) {\n decide.push(\n `${at} carries ${unknown.join(', ')}, which {code, percent, title?} has no meaning for — ` +\n 'say what those should become as promotion rules, or delete them.',\n )\n }\n if (typeof entry.code !== 'string' || entry.code.trim() === '') {\n decide.push(`${at}.code is missing — a coupon with no code cannot become a code-gated promotion.`)\n }\n if (typeof entry.percent !== 'number' || !Number.isFinite(entry.percent) || entry.percent <= 0 || entry.percent > 100) {\n decide.push(\n `${at}.percent is ${JSON.stringify(entry.percent)} — outside (0, 100], so the intended discount is not derivable.`,\n )\n }\n }\n\n const codeOf = (entry: unknown): string | null =>\n isRecord(entry) && typeof entry.code === 'string' ? entry.code.trim().toUpperCase() : null\n\n // Already a promotion under the same code: two live definitions of one\n // coupon, and only a human knows which is the real one.\n const promotionsSection = sectionOf(doc, 'promotions')\n const existing = Array.isArray(promotionsSection?.promotions) ? (promotionsSection!.promotions as unknown[]) : []\n for (const entry of entries) {\n const code = codeOf(entry)\n if (!code) continue\n const clash = existing.find((promo) => isRecord(promo) && typeof promo.code === 'string' && promo.code.trim().toUpperCase() === code)\n if (clash) {\n decide.push(\n `${code} is already declared in promotions.promotions (${isRecord(clash) ? String(clash.id ?? 'no id') : '?'}) ` +\n 'as well as in commerce.discounts — delete whichever of the two is not the live offer.',\n )\n }\n }\n\n // The catalog seed carries the same code. Today buildMockSeed SUPPRESSES\n // the seed row because the config code wins; migrating the config code out\n // of `discounts` removes that suppression and the seed row comes back as a\n // second promotion with the same code. Found by reading buildMockSeed, not\n // by reasoning about it.\n const catalog = sectionOf(doc, 'catalog')\n const seeded = Array.isArray(catalog?.discounts) ? (catalog!.discounts as unknown[]) : []\n for (const entry of entries) {\n const code = codeOf(entry)\n if (!code) continue\n if (seeded.some((seed) => codeOf(seed) === code)) {\n decide.push(\n `${code} is declared in BOTH commerce.discounts and catalog.discounts. The config copy currently ` +\n 'suppresses the catalog seed; once it becomes a promotion that suppression stops and the code ' +\n 'would apply twice. Delete whichever of the two is not the real offer, then re-run.',\n )\n }\n }\n\n if (decide.length > 0) {\n return result(mod, 'refused', `${entries.length} legacy code(s) present`, {\n refusal: {\n reason: 'the legacy codes cannot be translated without a decision this command must not make',\n decide,\n },\n })\n }\n\n // --- apply ---------------------------------------------------------------\n const changes: string[] = []\n if (entries.length > 0) {\n const migrated: Promotion[] = entries.map((entry) => {\n const record = entry as { code: string; percent: number; title?: string }\n return storefrontDiscountToPromotion(record)\n })\n const target = sectionOf(doc, 'promotions') ?? { version: STORE_SECTIONS.promotions.versions[0]! }\n const list = Array.isArray(target.promotions) ? [...(target.promotions as unknown[])] : []\n for (const promotion of migrated) {\n list.push(promotion as unknown as Record<string, unknown>)\n changes.push(`insert promotions.promotions[] ${promotion.code} (${promotion.applicationMethod.value}% off order)`)\n }\n target.promotions = list\n doc.promotions = target\n delete commerce.discounts\n changes.push(`remove commerce.discounts (${entries.length} entr${entries.length === 1 ? 'y' : 'ies'})`)\n }\n commerce.version = 2\n changes.push('set commerce.version 1 → 2')\n\n return result(\n mod,\n 'applied',\n entries.length === 0\n ? 'no legacy codes; version bump only, which records that this document is past the migration'\n : `${entries.length} legacy code(s) migrated onto the rule engine`,\n { changes },\n )\n },\n}\n\n/**\n * backend.supabaseUrl / backend.supabaseAnonKey → auth.supabase (backend v1 → v2).\n *\n * Not a pure relocation, and this is the interesting part. `resolveAuthAdapter`\n * reads `config.provider ?? config.adapter ?? (fallback?.supabaseUrl ? 'supabase' : 'mock')`\n * — so today the legacy field is ALSO what selects the supabase auth provider.\n * Move the credentials without saying anything about the provider and a store\n * with `auth` silent flips to mock auth: it would still build, still render,\n * and simply stop signing anybody in. So when the provider is not declared,\n * this refuses.\n */\nconst supabaseToAuth: Codemod = {\n id: 'backend.supabase-to-auth',\n title: 'Legacy supabase connection fields move under auth.supabase',\n version: { section: 'backend', from: 1, to: 2 },\n run(doc) {\n const mod = supabaseToAuth\n const version = sectionVersion(doc, 'backend')\n if (version === null) return result(mod, 'not-applicable', 'no backend section')\n if (version !== 1) return result(mod, 'not-applicable', `backend is already at version ${version}`)\n\n const backend = sectionOf(doc, 'backend')!\n const url = typeof backend.supabaseUrl === 'string' ? backend.supabaseUrl : undefined\n const anonKey = typeof backend.supabaseAnonKey === 'string' ? backend.supabaseAnonKey : undefined\n\n const auth = sectionOf(doc, 'auth')\n const authSupabase = auth && isRecord(auth.supabase) ? auth.supabase : null\n\n if (url !== undefined || anonKey !== undefined) {\n const decide: string[] = []\n const declaresProvider = Boolean(auth && (typeof auth.provider === 'string' || typeof auth.adapter === 'string'))\n if (!declaresProvider) {\n decide.push(\n \"declare auth.provider explicitly — 'supabase' to keep today's behaviour (the legacy field is what \" +\n \"currently selects it, via resolveAuthAdapter's `fallback?.supabaseUrl ? 'supabase' : 'mock'`), \" +\n \"or 'mock' if these credentials were vestigial. Moving them silently would flip the store to mock auth.\",\n )\n }\n if (authSupabase && typeof authSupabase.url === 'string' && url !== undefined && authSupabase.url !== url) {\n decide.push(`auth.supabase.url and backend.supabaseUrl disagree — say which project the store talks to.`)\n }\n if (\n authSupabase &&\n typeof authSupabase.anonKey === 'string' &&\n anonKey !== undefined &&\n authSupabase.anonKey !== anonKey\n ) {\n decide.push('auth.supabase.anonKey and backend.supabaseAnonKey disagree — say which key is current.')\n }\n if (decide.length > 0) {\n return result(mod, 'refused', 'legacy supabase fields are set', {\n refusal: { reason: 'moving the credentials would change who the store authenticates as', decide },\n })\n }\n }\n\n const changes: string[] = []\n if (url !== undefined || anonKey !== undefined) {\n const target = sectionOf(doc, 'auth') ?? { version: STORE_SECTIONS.auth.versions[0]! }\n const supabase = isRecord(target.supabase) ? { ...target.supabase } : {}\n if (url !== undefined) {\n supabase.url = url\n delete backend.supabaseUrl\n changes.push('move backend.supabaseUrl → auth.supabase.url')\n }\n if (anonKey !== undefined) {\n supabase.anonKey = anonKey\n delete backend.supabaseAnonKey\n changes.push('move backend.supabaseAnonKey → auth.supabase.anonKey')\n }\n target.supabase = supabase\n doc.auth = target\n }\n backend.version = 2\n changes.push('set backend.version 1 → 2')\n\n return result(\n mod,\n 'applied',\n changes.length === 1 ? 'no legacy supabase fields; version bump only' : 'legacy supabase connection moved under auth',\n { changes },\n )\n },\n}\n\n/**\n * A codemod for a deprecation that is NOT on the document surface.\n *\n * It exists, it runs, and it always refuses — which is the honest shape. The\n * registry gives every deprecation a codemod id precisely so that `fayz\n * upgrade` can never answer \"nothing to do\" about a thing it simply cannot\n * see. What it produces instead is the worklist.\n */\nfunction offDocumentCodemod(id: string, deprecationId: string, decide: string[]): Codemod {\n return {\n id,\n title: getDeprecation(deprecationId).title,\n version: null,\n run() {\n const row = getDeprecation(deprecationId)\n return result({ id, version: null }, 'refused', row.detect, {\n refusal: {\n reason:\n `${row.id} does not live in the store document, so no document transform can retire it. ` +\n `It lives in: ${row.where.join(', ')}.`,\n decide,\n },\n })\n },\n }\n}\n\nconst productMetadataOverlay = offDocumentCodemod(\n 'shop.product-metadata-overlay',\n 'shop.provider.productMetadata',\n [\n 'Confirm, per product, that every option axis the overlay declares (sizes / colors / options) exists as a real variant in admin > product > variants. Only the database knows this; the repo does not.',\n 'For an axis that has NO variants: decide whether the product is genuinely single-variant (delete the axis from the overlay) or whether variants must be created first (do that, then delete it).',\n 'For metadata that is display-only and has no variant equivalent (badges, care text): decide where it goes — the product\\'s own metadata column, or a block prop.',\n 'Then delete the `productMetadata` option from createFayzShopProvider (usually src/config/shop.ts) and the local catalog rows that feed it.',\n ],\n)\n\nconst inventoryCountWrite = offDocumentCodemod(\n 'shop.inventory-count-write',\n 'shop.inventory.directCountWrite',\n [\n 'Apply 0036 (and 0037) to every pool, so a direct write is translated instead of lost.',\n \"Then find the callers: SELECT count(*) FROM plg_shop_stock_movements WHERE reason_code = 'legacy_write' is the backlog, and it names the variants.\",\n 'For each caller, decide what the write MEANT — a receipt, a loss, a stock count, a correction. The shim records all of them as `adjustment` because it is told a number changed and never why; only the person who wrote the caller can say which it was.',\n 'Rewrite each caller to insert the right movement kind. The column keeps working until then.',\n ],\n)\n\nconst placeOrderVariantless = offDocumentCodemod(\n 'shop.place-order-variantless',\n 'shop.placeOrder.variantless',\n [\n 'Apply 0037_default_variant.sql to every pool. Its exit condition is stated in 0039\\'s header: the count of products with no variant must read 0 on every pool.',\n 'Verify it per pool — a repo has no way to observe pool state, and removing the leg while one pool still has variantless products would stop those sales dead.',\n 'Only once every pool reads 0 may the deprecated leg be deleted from shop_place_order.',\n ],\n)\n\nconst saasPackageRename = offDocumentCodemod(\n 'admin.saas-package-rename',\n 'admin.package.saas',\n [\n \"Rewrite the imports: every `from '@fayz-ai/saas'` (and its /ui, /db, /org, /billing, /permissions subpaths) becomes the same path under '@fayz-ai/admin'. The exported API is identical, so this is a find-and-replace, not a decision.\",\n 'Swap the dependency in package.json: remove @fayz-ai/saas, add @fayz-ai/admin at the same range.',\n 'If the app has a LOCAL plugin or a tsconfig path that names @fayz-ai/saas, update those too — a stale alias resolves to the shim and keeps the warning alive after the imports are clean.',\n ],\n)\n\nconst CODEMODS: readonly Codemod[] = [\n discountsToPromotions,\n supabaseToAuth,\n productMetadataOverlay,\n inventoryCountWrite,\n placeOrderVariantless,\n saasPackageRename,\n]\n\n/** Every codemod id, in run order. */\nexport const STORE_CODEMOD_IDS: readonly string[] = CODEMODS.map((mod) => mod.id)\n\n/** What each codemod is, as data — describeStore publishes this. */\nexport interface StoreCodemodDescriptor {\n id: string\n title: string\n /** Registry ids it retires. */\n deprecations: string[]\n /** The section version it is keyed to, or null when the deprecation is not\n * on the document surface (such a codemod always refuses). */\n version: StoreCodemodVersionKey | null\n /** Can it ever apply without a human? */\n automatable: boolean\n}\n\nexport function describeCodemods(): StoreCodemodDescriptor[] {\n return CODEMODS.map((mod) => ({\n id: mod.id,\n title: mod.title,\n deprecations: listDeprecations().filter((row) => row.codemod === mod.id).map((row) => row.id),\n version: mod.version,\n automatable: mod.version !== null,\n }))\n}\n\n/**\n * Run the codemods against a document and report exactly what would change.\n *\n * PURE: the input document is never mutated, and a refused codemod contributes\n * nothing to the output — a refusal must leave the document byte-identical or\n * the refusal was not a refusal.\n */\nexport function upgradeStore(\n input: StoreDocument | Record<string, unknown>,\n options: StoreUpgradeOptions = {},\n): StoreUpgradeResult {\n let selected = CODEMODS\n if (options.only) {\n for (const id of options.only) {\n if (!STORE_CODEMOD_IDS.includes(id)) {\n throw new Error(`Unknown codemod \"${id}\". Valid: ${STORE_CODEMOD_IDS.join(', ')}`)\n }\n }\n selected = CODEMODS.filter((mod) => options.only!.includes(mod.id))\n }\n\n const doc = clone(input) as Record<string, unknown>\n const codemods: StoreCodemodResult[] = []\n let changed = false\n\n for (const mod of selected) {\n // Each codemod runs against a scratch copy so a refusal — or a throw —\n // cannot leave a half-applied document behind. Only an `applied` result\n // is promoted.\n const scratch = clone(doc)\n const outcome = mod.run(scratch)\n codemods.push(outcome)\n if (outcome.status === 'applied') {\n for (const key of Object.keys(doc)) delete doc[key]\n Object.assign(doc, scratch)\n if (outcome.changes.length > 0) changed = true\n }\n }\n\n return {\n ok: codemods.every((outcome) => outcome.status !== 'refused'),\n doc: doc as unknown as StoreDocument,\n changed,\n deprecations: scanStoreDeprecations(input),\n codemods,\n validation: validateStore(doc),\n }\n}\n","import { blockInstanceId } from '../blocks/page-blocks'\nimport { STORE_SECTION_NAMES, isRecord, isJsonValue } from './sections'\nimport type { StoreDocument, StoreSectionName } from './sections'\nimport { validateStore } from './validate'\nimport type { StoreValidationError, StoreValidationReport } from './validate'\n\n// ---------------------------------------------------------------------------\n// applyChange — the fourth ability (spine §3 L5).\n//\n// describeStore says what a store CAN be, validateStore says whether it IS\n// valid, renderStore says what it LOOKS like. applyChange is the only one that\n// writes, and it exists so that an agent's edit is a small typed operation\n// against a path rather than \"emit the whole document again\": a regenerated\n// document loses everything the agent did not think to repeat, and a diff of\n// one is unreadable.\n//\n// Three properties, each of which is the reason a benchmark's edit surface is\n// not usable by a generator:\n//\n// 1. It addresses the SAME paths validateStore reports\n// ('presentation.pages.home.blocks[2].props.title'), plus a block-id form\n// ('blocks[#hero]') because two product rails on one page are otherwise\n// indistinguishable — the problem `StorefrontBlockRef.id` exists for.\n// An agent therefore corrects at exactly the address it was given.\n//\n// 2. It is TRANSACTIONAL and gated by validateStore. A batch that would\n// leave the document invalid is refused whole, with the reasons, and the\n// input document is returned untouched. There is no half-applied state to\n// reason about and no way to author a store the renderer will choke on.\n//\n// 3. Every failure names the valid set (I2): an unknown block id lists the\n// ids present, a locked section lists the writable ones. Silent\n// no-op-on-unknown is what makes generated configuration uncorrectable.\n//\n// It is deliberately five operations. WooCommerce's answer to \"let extensions\n// change things\" was 3,657 hooks; the lesson §4 draws is that a surface an\n// agent cannot enumerate is a surface it cannot use.\n// ---------------------------------------------------------------------------\n\n/** JSON values a change may write. */\nexport type StoreChangeValue = unknown\n\nexport const STORE_CHANGE_OPS = ['set', 'remove', 'insert', 'move'] as const\nexport type StoreChangeOp = (typeof STORE_CHANGE_OPS)[number]\n\nexport interface StoreChange {\n /**\n * `set` — write `value` at `path` (creating missing intermediate objects).\n * `remove` — delete the key, or splice the array element, at `path`.\n * `insert` — splice `value` into the array at `path`, at `index` (default: append).\n * `move` — relocate the array element at `path` to `index`.\n */\n op: StoreChangeOp\n /**\n * Dotted document path, the same shape `validateStore` reports:\n * `presentation.pages.home.blocks[2].props.title`. An array step may address\n * a block by id instead of by position — `blocks[#hero]` — which is the only\n * form that stays correct across a reorder.\n */\n path: string\n /** `set` / `insert`: the JSON value to write. */\n value?: StoreChangeValue\n /** `insert` / `move`: destination index. `insert` defaults to append. */\n index?: number\n}\n\nexport interface AppliedStoreChange {\n op: StoreChangeOp\n path: string\n /** The path with every `[#id]` step resolved to the position it hit — what\n * actually moved, which is what a diff or an undo needs. */\n resolvedPath: string\n /** The value that was there before, when there was one. */\n before?: StoreChangeValue\n /** The value that is there now, when the op leaves one. */\n after?: StoreChangeValue\n}\n\nexport interface ApplyChangeOptions {\n /**\n * Sections this caller may write. Defaults to every section EXCEPT `code`:\n * a code entry is a handle name resolved out of the handle registry, so an\n * agent inventing one produces a document that hydrates to a missing\n * component. Pass it explicitly to move a route or drop an override.\n */\n sections?: readonly StoreSectionName[]\n /**\n * 'reject' (default) — a batch whose RESULT fails validation is discarded\n * whole and `doc` is the untouched input. 'allow' returns the changed\n * document with the report anyway, for a caller that is mid-way through a\n * multi-step edit and will validate at the end.\n */\n onInvalid?: 'reject' | 'allow'\n}\n\nexport interface StoreChangeResult {\n /** True only when every change applied AND the result validates. */\n ok: boolean\n /** The resulting document — the input, unchanged, when a rejected batch failed. */\n doc: StoreDocument\n /** One entry per change, in order, for the changes that were applied. */\n applied: AppliedStoreChange[]\n /** Path/permission failures AND the resulting document's validation errors,\n * in one list, in the shape `validateStore` returns — so a caller has one\n * error vocabulary to correct on rather than two. */\n errors: StoreValidationError[]\n /** Validation of the resulting document. */\n validation: StoreValidationReport\n}\n\n/** Sections a change may write unless the caller says otherwise. */\nexport const DEFAULT_WRITABLE_SECTIONS: readonly StoreSectionName[] = STORE_SECTION_NAMES.filter(\n (name) => name !== 'code',\n)\n\n// --- Paths --------------------------------------------------------------------\n\ntype PathStep =\n | { kind: 'key'; key: string }\n | { kind: 'index'; index: number }\n | { kind: 'id'; id: string }\n\n/** Render a step the way it is written, for error paths and `resolvedPath`. */\nfunction stepText(step: PathStep): string {\n if (step.kind === 'key') return step.key\n if (step.kind === 'index') return `[${step.index}]`\n return `[#${step.id}]`\n}\n\nfunction pathText(steps: readonly PathStep[]): string {\n return steps.reduce((acc, step) => {\n if (step.kind === 'key') return acc ? `${acc}.${step.key}` : step.key\n return acc + stepText(step)\n }, '')\n}\n\n/**\n * Parse `presentation.pages.home.blocks[#hero].props.title` into steps.\n * Returns null for anything malformed — an unparseable path is a hard error,\n * never a silently ignored change.\n */\nexport function parseStorePath(path: string): PathStep[] | null {\n if (typeof path !== 'string' || path.trim() === '') return null\n const steps: PathStep[] = []\n let i = 0\n const source = path.trim()\n let expectKey = true\n\n while (i < source.length) {\n if (source[i] === '.') {\n if (expectKey) return null // '..' or a leading dot\n i++\n expectKey = true\n continue\n }\n if (source[i] === '[') {\n const close = source.indexOf(']', i)\n if (close === -1) return null\n const inner = source.slice(i + 1, close)\n if (inner.startsWith('#')) {\n const id = inner.slice(1)\n if (!id) return null\n steps.push({ kind: 'id', id })\n } else {\n if (!/^\\d+$/.test(inner)) return null\n steps.push({ kind: 'index', index: Number(inner) })\n }\n i = close + 1\n expectKey = false\n continue\n }\n if (!expectKey) return null // 'a[0]b' — a key glued to a bracket\n const next = source.slice(i).search(/[.[]/)\n const key = next === -1 ? source.slice(i) : source.slice(i, i + next)\n if (!key) return null\n steps.push({ kind: 'key', key })\n i += key.length\n expectKey = false\n }\n\n return expectKey || steps.length === 0 ? null : steps\n}\n\n/**\n * Position of the entry addressed by `[#id]`, or -1.\n *\n * Matches the authored `id` first, then the id the RENDERER gives an\n * unidentified block (`blockInstanceId` — `<type>-<index>`). Most documents in\n * the fleet author no ids at all, so without the second form every id\n * `renderStore` hands back would be unaddressable by the ability whose job is\n * to act on it.\n */\nfunction findById(list: readonly unknown[], id: string): number {\n const authored = list.findIndex((entry) => isRecord(entry) && entry.id === id)\n if (authored !== -1) return authored\n return list.findIndex((entry, index) => isRecord(entry) && blockInstanceId(entry, index) === id)\n}\n\n/** The ids present in a list, as an agent would see them (I2's valid set). */\nfunction blockIdsIn(list: readonly unknown[]): string[] {\n return list.flatMap((entry, index) =>\n isRecord(entry) && (typeof entry.id === 'string' || typeof entry.type === 'string')\n ? [blockInstanceId(entry, index)]\n : [],\n )\n}\n\n// --- Navigation ---------------------------------------------------------------\n\ninterface Cursor {\n container: Record<string, unknown> | unknown[]\n /** Where inside the container the final step points. */\n step: PathStep\n /** Array position, when the container is an array. */\n position: number\n /** Steps walked, for `resolvedPath`. */\n walked: PathStep[]\n}\n\ntype NavResult = { ok: true; cursor: Cursor } | { ok: false; error: StoreValidationError }\n\nfunction navError(path: string, code: string, message: string, valid?: string[]): NavResult {\n return { ok: false, error: valid ? { path, code, message, valid } : { path, code, message } }\n}\n\n/**\n * Walk to the CONTAINER of the last step.\n *\n * `create` makes missing intermediate objects along a pure-key path — an agent\n * adding the store's first editorial page should not have to `set\n * presentation.pages` and `set presentation.pages.content` first. It never\n * creates array slots: a position that does not exist is a mistake, not an\n * intent, and it is reported with the length that does exist.\n */\nfunction navigate(root: Record<string, unknown>, steps: PathStep[], create: boolean): NavResult {\n let node: unknown = root\n const walked: PathStep[] = []\n\n for (let i = 0; i < steps.length - 1; i++) {\n const step = steps[i]!\n const here = pathText(walked)\n if (step.kind === 'key') {\n if (!isRecord(node)) {\n return navError(here || '(document)', 'not-an-object', `${here || 'the document'} is not an object, so \".${step.key}\" cannot be followed`)\n }\n if (!(step.key in node) || node[step.key] === undefined) {\n if (!create) {\n return navError(\n pathText([...walked, step]),\n 'unknown-path',\n `${pathText([...walked, step])} does not exist`,\n Object.keys(node).sort(),\n )\n }\n node[step.key] = {}\n }\n node = node[step.key]\n walked.push(step)\n continue\n }\n\n if (!Array.isArray(node)) {\n return navError(here || '(document)', 'not-an-array', `${here || 'the document'} is not an array, so \"${stepText(step)}\" cannot be followed`)\n }\n const position = step.kind === 'index' ? step.index : findById(node, step.id)\n if (position < 0 || position >= node.length) {\n return step.kind === 'id'\n ? navError(pathText([...walked, step]), 'unknown-block-id', `no entry in ${here} has the id \"${step.id}\"`, blockIdsIn(node))\n : navError(pathText([...walked, step]), 'index-out-of-range', `${here} has ${node.length} entr${node.length === 1 ? 'y' : 'ies'}, so index ${step.index} is out of range`)\n }\n node = node[position]\n walked.push({ kind: 'index', index: position })\n }\n\n const last = steps[steps.length - 1]!\n const here = pathText(walked)\n if (last.kind === 'key') {\n if (!isRecord(node)) {\n return navError(here || '(document)', 'not-an-object', `${here || 'the document'} is not an object, so \".${last.key}\" cannot be written`)\n }\n return { ok: true, cursor: { container: node, step: last, position: -1, walked } }\n }\n if (!Array.isArray(node)) {\n return navError(here || '(document)', 'not-an-array', `${here || 'the document'} is not an array, so \"${stepText(last)}\" cannot be written`)\n }\n const position = last.kind === 'index' ? last.index : findById(node, last.id)\n if (last.kind === 'id' && position < 0) {\n return navError(pathText([...walked, last]), 'unknown-block-id', `no entry in ${here} has the id \"${last.id}\"`, blockIdsIn(node))\n }\n return { ok: true, cursor: { container: node, step: last, position, walked } }\n}\n\n// --- Apply --------------------------------------------------------------------\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nfunction sectionOf(steps: PathStep[]): string | null {\n const first = steps[0]\n return first && first.kind === 'key' ? first.key : null\n}\n\n/**\n * Apply an ordered batch of changes to a Store Document.\n *\n * Transactional: the batch either applies whole and validates, or the input\n * document comes back untouched with every reason listed.\n *\n * applyChange(doc, { op: 'set', path: 'theme.colors.primary', value: '41 54% 55%' })\n * applyChange(doc, [\n * { op: 'insert', path: 'presentation.home.sections', index: 0, value: { type: 'seals' } },\n * { op: 'move', path: 'presentation.home.sections[#hero]', index: 1 },\n * ])\n */\nexport function applyChange(\n input: StoreDocument | Record<string, unknown>,\n changes: StoreChange | readonly StoreChange[],\n options: ApplyChangeOptions = {},\n): StoreChangeResult {\n const batch = Array.isArray(changes) ? changes : [changes as StoreChange]\n const writable = options.sections ?? DEFAULT_WRITABLE_SECTIONS\n const onInvalid = options.onInvalid ?? 'reject'\n\n const original = input as Record<string, unknown>\n const errors: StoreValidationError[] = []\n const applied: AppliedStoreChange[] = []\n\n if (!isRecord(original)) {\n const error: StoreValidationError = {\n path: '',\n code: 'invalid-document',\n message: 'a Store Document is an object',\n }\n return {\n ok: false,\n doc: input as StoreDocument,\n applied,\n errors: [error],\n validation: { ok: false, errors: [error] },\n }\n }\n\n const draft = clone(original)\n\n for (let index = 0; index < batch.length; index++) {\n const change = batch[index]!\n const at = `changes[${index}]`\n\n if (!STORE_CHANGE_OPS.includes(change?.op)) {\n errors.push({\n path: `${at}.op`,\n code: 'unknown-change-op',\n message: `\"${String(change?.op)}\" is not a change operation`,\n valid: [...STORE_CHANGE_OPS],\n })\n continue\n }\n\n const steps = parseStorePath(change.path)\n if (!steps) {\n errors.push({\n path: `${at}.path`,\n code: 'invalid-path',\n message: `\"${String(change.path)}\" is not a document path — dotted keys with [0] or [#block-id] steps`,\n })\n continue\n }\n\n const section = sectionOf(steps)\n if (section === null || !STORE_SECTION_NAMES.includes(section as StoreSectionName)) {\n errors.push({\n path: `${at}.path`,\n code: 'unknown-section',\n message: `\"${String(section ?? change.path)}\" is not a document section`,\n valid: [...STORE_SECTION_NAMES],\n })\n continue\n }\n if (!writable.includes(section as StoreSectionName)) {\n errors.push({\n path: `${at}.path`,\n code: 'section-not-writable',\n message:\n section === 'code'\n ? 'the code section holds handle NAMES resolved from the handle registry — an invented one hydrates to a missing component. Pass { sections: [..., \\'code\\'] } to write it deliberately.'\n : `the \"${section}\" section is not writable by this caller`,\n valid: [...writable],\n })\n continue\n }\n if ((change.op === 'set' || change.op === 'insert') && !isJsonValue(change.value)) {\n errors.push({\n path: `${at}.value`,\n code: 'invalid-value',\n message: 'a change writes JSON — code belongs in a registered handle referenced from the code section',\n })\n continue\n }\n\n // A section the document has not opened yet gets opened at v1, so adding\n // the first promotion or the first editorial page is one change, not three.\n if (draft[section] === undefined && (change.op === 'set' || change.op === 'insert')) {\n draft[section] = { version: 1 }\n }\n\n const nav = navigate(draft, steps, change.op === 'set')\n if (!nav.ok) {\n errors.push({ ...nav.error, path: nav.error.path })\n continue\n }\n const { container, step, position, walked } = nav.cursor\n const resolvedSteps = [...walked, step.kind === 'id' ? { kind: 'index' as const, index: position } : step]\n const resolvedPath = pathText(resolvedSteps)\n\n if (Array.isArray(container)) {\n const before = position >= 0 && position < container.length ? clone(container[position]) : undefined\n if (change.op === 'set') {\n if (position < 0 || position >= container.length) {\n errors.push({\n path: change.path,\n code: 'index-out-of-range',\n message: `${pathText(walked)} has ${container.length} entries — use insert to add one`,\n })\n continue\n }\n container[position] = clone(change.value)\n applied.push({ op: 'set', path: change.path, resolvedPath, before, after: clone(change.value) })\n continue\n }\n if (change.op === 'remove') {\n if (position < 0 || position >= container.length) {\n errors.push({\n path: change.path,\n code: 'index-out-of-range',\n message: `${pathText(walked)} has ${container.length} entries, so ${stepText(step)} cannot be removed`,\n })\n continue\n }\n container.splice(position, 1)\n applied.push({ op: 'remove', path: change.path, resolvedPath, before })\n continue\n }\n if (change.op === 'move') {\n if (position < 0 || position >= container.length) {\n errors.push({\n path: change.path,\n code: 'index-out-of-range',\n message: `${pathText(walked)} has ${container.length} entries, so ${stepText(step)} cannot be moved`,\n })\n continue\n }\n const to = change.index ?? 0\n if (!Number.isInteger(to) || to < 0 || to >= container.length) {\n errors.push({\n path: `${at}.index`,\n code: 'index-out-of-range',\n message: `move destination must be 0..${container.length - 1}, got ${String(change.index)}`,\n })\n continue\n }\n const [entry] = container.splice(position, 1)\n container.splice(to, 0, entry)\n applied.push({ op: 'move', path: change.path, resolvedPath, before, after: clone(entry) })\n continue\n }\n // insert INTO an array addressed by an element step is ambiguous; the\n // array itself is the target ('...sections', not '...sections[2]').\n errors.push({\n path: `${at}.path`,\n code: 'invalid-path',\n message: `insert targets the array itself — use \"${pathText(walked)}\" with { index: ${Math.max(position, 0)} }`,\n })\n continue\n }\n\n // Object container.\n const key = (step as { key: string }).key\n const before = key in container ? clone(container[key]) : undefined\n\n if (change.op === 'set') {\n container[key] = clone(change.value)\n applied.push({ op: 'set', path: change.path, resolvedPath, before, after: clone(change.value) })\n continue\n }\n if (change.op === 'remove') {\n if (!(key in container)) {\n errors.push({\n path: change.path,\n code: 'unknown-path',\n message: `${resolvedPath} does not exist`,\n valid: Object.keys(container).sort(),\n })\n continue\n }\n delete container[key]\n applied.push({ op: 'remove', path: change.path, resolvedPath, before })\n continue\n }\n // insert / move target arrays.\n const target = container[key]\n if (!Array.isArray(target)) {\n errors.push({\n path: change.path,\n code: 'not-an-array',\n message: `${resolvedPath} is ${target === undefined ? 'not present' : `a ${typeof target}`}, and ${change.op} targets an array`,\n })\n continue\n }\n if (change.op === 'move') {\n errors.push({\n path: `${at}.path`,\n code: 'invalid-path',\n message: `move targets an element — address it as \"${resolvedPath}[0]\" or \"${resolvedPath}[#id]\"`,\n })\n continue\n }\n const to = change.index ?? target.length\n if (!Number.isInteger(to) || to < 0 || to > target.length) {\n errors.push({\n path: `${at}.index`,\n code: 'index-out-of-range',\n message: `insert index must be 0..${target.length}, got ${String(change.index)}`,\n })\n continue\n }\n target.splice(to, 0, clone(change.value))\n applied.push({\n op: 'insert',\n path: change.path,\n resolvedPath: `${resolvedPath}[${to}]`,\n after: clone(change.value),\n })\n }\n\n const validation = validateStore(draft)\n const failed = errors.length > 0 || !validation.ok\n const rejected = failed && onInvalid === 'reject'\n\n return {\n ok: !failed,\n doc: (rejected ? original : draft) as unknown as StoreDocument,\n applied: rejected ? [] : applied,\n errors: [...errors, ...validation.errors],\n validation,\n }\n}\n","import {\n BLOCK_SETTING_TYPES,\n ENTITY_FIELD_TYPES,\n describeBlocks,\n describeEntities,\n describeExtensionPoints,\n describeLoaders,\n handleRegistry,\n} from '@fayz-ai/core'\nimport type {\n BlockDescriptor,\n EntityDescriptor,\n ExtensionPointDescriptor,\n JsonSchema,\n LoaderDescriptor,\n RegistryEntryDescriptor,\n} from '@fayz-ai/core'\nimport { RULE_OPERATORS, listRuleAttributes } from '@fayz-ai/shop/rules'\nimport type { RuleAttribute } from '@fayz-ai/shop/rules'\nimport { fayzDeprecationPolicy, listDeprecations } from '@fayz-ai/sdk/deprecations'\nimport type { FayzDeprecation, FayzDeprecationPolicy } from '@fayz-ai/sdk/deprecations'\nimport { describeCodemods, scanStoreDeprecations } from './upgrade'\nimport type { StoreCodemodDescriptor, StoreDeprecationFinding } from './upgrade'\nimport { registerStorefrontBlocks } from '../blocks/registry'\nimport { registerStorefrontExtensionPoints } from '../extend/extension-points'\nimport { STOREFRONT_COMPONENT_KEYS } from '../extend/component-contracts'\nimport { STOREFRONT_SLOTS } from '../extend/slots'\nimport type { SlotDescriptor } from '../extend/slots'\nimport { DEFAULT_WRITABLE_SECTIONS, STORE_CHANGE_OPS } from './change'\nimport { STORE_SECTIONS, STORE_SECTION_NAMES, sectionToJsonSchema, isRecord } from './sections'\nimport type { StoreDocument, StoreSectionName } from './sections'\nimport { validateStore, STOREFRONT_PAGE_KINDS } from './validate'\nimport type { StoreValidationReport } from './validate'\n\n// ---------------------------------------------------------------------------\n// describeStore — what a store IS and what it CAN be, as one machine-readable\n// value. This is the catalog an agent reads before generating or editing a\n// document: the registries with their schemas, the section schemas, the page\n// kinds, the slot inventory, the registered handles, the setting vocabulary.\n// Serializable on purpose — it has to survive a prompt and a wire.\n// ---------------------------------------------------------------------------\n\n/**\n * What this store's backend can do.\n *\n * Designed to become backend-aware: today every store is Fayz-backed, so the\n * values are constants. When a second backend lands (spine I11 — e.g. a\n * Shopify-backed store whose catalog is mirrored into canonical tables), this\n * shape is derived from the backend provider instead: a Shopify-backed store\n * keeps `catalogMirror` but cannot run our rule engine, so `ruleEngine`\n * flips false while the document stays identical. Consumers must branch on\n * these flags, never on the provider name.\n */\nexport interface StoreCapabilities {\n /** Backend family serving the store. */\n backend: string\n /** Commerce modes the storefront shell can run. */\n commerceModes: readonly string[]\n /** Reads come from the canonical Fayz catalog (mirrored for ERP-backed stores). */\n catalogMirror: boolean\n /** Cart + checkout run against the Fayz order path. */\n checkout: boolean\n /** Declared data loaders resolved once per page (spine M3). */\n loaders: boolean\n /** Rule engine (spine M6): promotions as data, evaluated by the reference\n * evaluator (mock) or shop_compute_promotion_actions (Supabase). True for\n * Fayz-backed stores; a backend that cannot run our rules (e.g. a\n * Shopify-mirrored store) flips this false and consumers must branch on\n * the flag, never the provider name. */\n ruleEngine: boolean\n /** Custom entity declarations (spine M4): defineEntity + entity.* loaders +\n * generic storage. True for Fayz-backed stores (both providers implement\n * the entity surface); a future backend without it flips this false and\n * consumers must branch on the flag, never the provider name. */\n customEntities: boolean\n /** Extension point registry (spine M7): declared seams with enforced\n * input+output schemas, many dependency-ordered handlers, and exactly one\n * nullable beforePlaceOrder escape valve. */\n extensionPoints: boolean\n}\n\nexport interface StoreSectionDescription {\n description: string\n /** Section versions this SDK understands, ascending. */\n versions: readonly number[]\n /** JSON Schema for the section, compiled from the same spec the validator runs. */\n schema: JsonSchema\n}\n\n/** Summary of one concrete document, when one is passed in. */\n/** The I10 contract, as data the agent reads before authoring (spine M10):\n * the policy, every deprecation, and the codemod that answers each one. */\nexport interface StoreContractDescription {\n policy: FayzDeprecationPolicy\n deprecations: FayzDeprecation[]\n codemods: StoreCodemodDescriptor[]\n}\n\nexport interface StoreDocumentSummary {\n name?: string\n /** Sections present in the document. */\n sections: string[]\n /** Block types the document places (pages, home, slots), sorted, deduped. */\n blocksUsed: string[]\n /** Loader ids the document's data declarations reference, sorted, deduped.\n * Meta-level needs of placed blocks are not repeated here — they are the\n * block's own contract, readable from the blocks registry. */\n loadersUsed: string[]\n /** Handle names the document references, sorted, deduped. */\n handlesUsed: string[]\n /** What in THIS store is deprecated, and what replaces it (I10 + I2). */\n deprecations: StoreDeprecationFinding[]\n validation: StoreValidationReport\n}\n\n/**\n * One of the author-facing abilities (spine §3 L5).\n *\n * Enumerating them is the point. WooCommerce's own conclusion about agent\n * surfaces — quoted in the spine — is that the surface must be \"purpose-built\n * domain abilities … instead of automatically projecting every REST-shaped\n * operation\", and an ability an agent cannot discover is an ability it will not\n * use. There are four, they are listed here with their input schemas, and the\n * list is derived from nothing: if a fifth is added it must be added here.\n */\nexport interface StoreAbilityDescriptor {\n name: 'describeStore' | 'validateStore' | 'renderStore' | 'applyChange'\n /** Where it is imported from. */\n module: string\n /** Does it change the document? */\n writes: boolean\n description: string\n /** JSON Schema of the options/arguments beyond the document itself. */\n input: JsonSchema\n /** What the caller gets back, in prose — the shapes are exported types. */\n output: string\n}\n\nexport interface StoreDescription {\n version: 1\n capabilities: StoreCapabilities\n /** The four abilities, with their input schemas (spine L5). */\n abilities: readonly StoreAbilityDescriptor[]\n sections: Record<StoreSectionName, StoreSectionDescription>\n /** The deprecation contract (spine M10, I10). Enumerable on purpose: an\n * agent that cannot read what is going away will keep generating it. */\n contract: StoreContractDescription\n registries: {\n blocks: BlockDescriptor[]\n loaders: LoaderDescriptor[]\n entities: EntityDescriptor[]\n handles: RegistryEntryDescriptor[]\n /** The rule attribute vocabulary AS ROWS (I9) — the same rows the admin\n * promotion form renders from and validateStore checks against. */\n ruleAttributes: RuleAttribute[]\n /** Every extension point with its input/output schemas AND registered\n * handlers (spine M7) — the enumerable behaviour surface. */\n extensionPoints: ExtensionPointDescriptor[]\n }\n /** The closed operator set rules may use. */\n ruleOperators: readonly string[]\n pageKinds: readonly string[]\n slots: readonly SlotDescriptor[]\n componentSlots: readonly string[]\n settingTypes: readonly string[]\n /** The field-type vocabulary defineEntity accepts (spine M4). */\n entityFieldTypes: readonly string[]\n document?: StoreDocumentSummary\n}\n\n/** The four abilities (spine L5), as data the agent can read before calling. */\nconst STORE_ABILITIES: readonly StoreAbilityDescriptor[] = [\n {\n name: 'describeStore',\n module: '@fayz-ai/storefront',\n writes: false,\n description:\n 'What a store IS and what it CAN be: section schemas, every registry with its JSON Schema, page kinds, slots, handles, the rule vocabulary, the extension points — plus a summary of a document when one is passed. Read this before authoring.',\n input: {\n type: 'object',\n properties: { document: { type: 'object', description: 'Optional Store Document to summarize against the surface.' } },\n additionalProperties: false,\n },\n output: 'StoreDescription',\n },\n {\n name: 'validateStore',\n module: '@fayz-ai/storefront',\n writes: false,\n description:\n 'The gate. Every unknown id — section, field, page kind, block type, block setting, slot, handle, loader, rule attribute — is a hard error that names the valid set (I2). Correct on `errors[].valid`, not on the prose.',\n input: { type: 'object', properties: {}, additionalProperties: false },\n output: 'StoreValidationReport { ok, errors: [{ path, code, message, valid? }] }',\n },\n {\n name: 'renderStore',\n module: '@fayz-ai/storefront/render',\n writes: false,\n description:\n 'Render one route of the document to HTML, headless, and report what came out: title, visible text, heading outline, every block that rendered, every loader that ran and what it returned, and every diagnostic the page logged. This is how an author sees what it authored.',\n input: {\n type: 'object',\n properties: {\n path: { type: 'string', description: \"Route to render ('/', '/catalog', '/product/:slug' resolved, '/biography').\" },\n provider: {\n type: 'string',\n enum: ['config', 'document'],\n description:\n \"'config' uses the provider the store implies; 'document' uses a mock seeded from the document's catalog section — deterministic and network-free.\",\n },\n onError: { type: 'string', enum: ['throw', 'report'] },\n html: { type: 'string', enum: ['document', 'fragment'] },\n maxPasses: { type: 'number' },\n stylesheets: { type: 'array', items: { type: 'string' } },\n lang: { type: 'string' },\n },\n additionalProperties: false,\n },\n output: 'StoreRenderResult { ok, title, found, html, text, outline, blocks, links, data, diagnostics, validation }',\n },\n {\n name: 'applyChange',\n module: '@fayz-ai/storefront',\n writes: true,\n description:\n 'The only write. An ordered batch of typed operations against document paths — the same paths validateStore reports, plus a `blocks[#id]` form. Transactional: a batch whose result would not validate is refused whole, with the reasons.',\n input: {\n type: 'object',\n properties: {\n changes: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n op: { type: 'string', enum: [...STORE_CHANGE_OPS] },\n path: {\n type: 'string',\n description: \"Dotted document path, e.g. 'presentation.pages.home.blocks[#hero].props.title'.\",\n },\n value: { description: 'set / insert: the JSON value to write.' },\n index: { type: 'number', description: 'insert / move: destination index.' },\n },\n required: ['op', 'path'],\n additionalProperties: false,\n },\n },\n sections: {\n type: 'array',\n items: { type: 'string', enum: [...STORE_SECTION_NAMES] },\n description: `Sections this caller may write. Default: ${DEFAULT_WRITABLE_SECTIONS.join(', ')}.`,\n },\n onInvalid: { type: 'string', enum: ['reject', 'allow'] },\n },\n required: ['changes'],\n additionalProperties: false,\n },\n output: 'StoreChangeResult { ok, doc, applied, errors, validation }',\n },\n]\n\nfunction collectBlockTypes(out: Set<string>, loaders: Set<string>, blocks: unknown): void {\n if (!Array.isArray(blocks)) return\n for (const entry of blocks) {\n if (!isRecord(entry)) continue\n if (typeof entry.type === 'string') out.add(entry.type)\n if (isRecord(entry.data)) {\n for (const need of Object.values(entry.data)) {\n if (isRecord(need) && typeof need.loader === 'string') loaders.add(need.loader)\n }\n }\n if (Array.isArray(entry.children)) collectBlockTypes(out, loaders, entry.children)\n }\n}\n\nfunction summarizeDocument(doc: StoreDocument | Record<string, unknown>): StoreDocumentSummary {\n const record = doc as Record<string, unknown>\n const store = isRecord(record.store) ? record.store : undefined\n const presentation = isRecord(record.presentation) ? record.presentation : undefined\n const code = isRecord(record.code) ? record.code : undefined\n\n const blocks = new Set<string>()\n const loaders = new Set<string>()\n if (isRecord(presentation?.home)) collectBlockTypes(blocks, loaders, presentation.home.sections)\n if (isRecord(presentation?.pages)) {\n for (const [kind, page] of Object.entries(presentation.pages)) {\n if (!isRecord(page)) continue\n // pages.content is a MAP of editorial pages, one level deeper.\n if (kind === 'content') {\n for (const contentPage of Object.values(page)) {\n if (isRecord(contentPage)) collectBlockTypes(blocks, loaders, contentPage.blocks)\n }\n continue\n }\n collectBlockTypes(blocks, loaders, page.blocks)\n }\n }\n if (isRecord(presentation?.slots)) {\n for (const area of Object.values(presentation.slots)) {\n if (!isRecord(area)) continue\n for (const slotBlocks of Object.values(area)) collectBlockTypes(blocks, loaders, slotBlocks)\n }\n }\n\n const handles = new Set<string>()\n if (code) {\n for (const field of ['logo', 'provider', 'auth', 'footerCredit']) {\n if (typeof code[field] === 'string') handles.add(code[field] as string)\n }\n if (isRecord(code.components)) {\n for (const handle of Object.values(code.components)) {\n if (typeof handle === 'string') handles.add(handle)\n }\n }\n if (Array.isArray(code.routes)) {\n for (const route of code.routes) {\n if (isRecord(route) && typeof route.component === 'string') handles.add(route.component)\n }\n }\n }\n\n return {\n name: typeof store?.name === 'string' ? store.name : undefined,\n sections: Object.keys(record).filter((key) => key !== '$kind'),\n blocksUsed: [...blocks].sort(),\n loadersUsed: [...loaders].sort(),\n handlesUsed: [...handles].sort(),\n deprecations: scanStoreDeprecations(doc),\n validation: validateStore(doc),\n }\n}\n\n/**\n * The machine-readable description of the storefront authoring surface, plus —\n * when a document is passed — a summary of that document against it.\n */\nexport function describeStore(doc?: StoreDocument | Record<string, unknown>): StoreDescription {\n registerStorefrontBlocks()\n registerStorefrontExtensionPoints()\n\n const sections = {} as Record<StoreSectionName, StoreSectionDescription>\n for (const name of STORE_SECTION_NAMES) {\n sections[name] = {\n description: STORE_SECTIONS[name].description,\n versions: [...STORE_SECTIONS[name].versions],\n schema: sectionToJsonSchema(name),\n }\n }\n\n const description: StoreDescription = {\n version: 1,\n capabilities: {\n backend: 'fayz',\n commerceModes: ['checkout', 'catalog', 'enquiry'],\n catalogMirror: true,\n checkout: true,\n loaders: true,\n ruleEngine: true,\n customEntities: true,\n extensionPoints: true,\n },\n abilities: STORE_ABILITIES,\n sections,\n contract: {\n policy: fayzDeprecationPolicy,\n deprecations: listDeprecations(),\n codemods: describeCodemods(),\n },\n registries: {\n blocks: describeBlocks({ includeExperimental: true }),\n loaders: describeLoaders(),\n entities: describeEntities(),\n handles: handleRegistry.describe(),\n ruleAttributes: listRuleAttributes(),\n extensionPoints: describeExtensionPoints(),\n },\n ruleOperators: RULE_OPERATORS,\n pageKinds: [...STOREFRONT_PAGE_KINDS],\n slots: STOREFRONT_SLOTS,\n componentSlots: STOREFRONT_COMPONENT_KEYS,\n settingTypes: BLOCK_SETTING_TYPES,\n entityFieldTypes: ENTITY_FIELD_TYPES,\n }\n\n if (doc !== undefined) description.document = summarizeDocument(doc)\n return description\n}\n","import { useStorefrontConfig } from '../document/config'\nimport { useCatalogStore } from '../stores/catalog.store'\n\n/** The catalog store, plus the config a listing page needs to render a link. */\nexport function useCatalog() {\n const config = useStorefrontConfig()\n const catalog = useCatalogStore()\n return { ...catalog, catalogPath: config.catalogPath, config }\n}\n","import { useStorefrontConfig } from '../document/config'\n\n/** The resolved storefront config — defaults applied, every field present. */\nexport function useStorefront() {\n return useStorefrontConfig()\n}\n","import { useStorefrontConfig } from '../document/config'\nimport { formatMoney } from '../lib/format'\n\nexport interface StorefrontRegion {\n currency: string\n locale: string\n /** Money formatted for this store, so a caller never re-derives the pair. */\n format: (value: number) => string\n}\n\n/**\n * Currency and locale, with the formatter already bound to them.\n *\n * Returning the bound formatter is the point: `formatMoney` defaults to BRL and\n * pt-BR, so every call site that passes only a number silently formats a\n * non-Brazilian store's prices as reais.\n */\nexport function useRegion(): StorefrontRegion {\n const { currency, locale } = useStorefrontConfig()\n return { currency, locale, format: (value: number) => formatMoney(value, currency, locale) }\n}\n","import { useStorefrontConfig } from '../document/config'\n\nexport type PolicyKind = 'privacy' | 'terms' | 'returns'\n\nexport interface StorefrontPolicy {\n kind: PolicyKind\n title: string\n path: string\n /** The store's own text, or null when it has not published this one yet. */\n content: string | null\n published: boolean\n}\n\nconst POLICIES: ReadonlyArray<{ kind: PolicyKind; title: string; path: string }> = [\n { kind: 'privacy', title: 'Política de Privacidade', path: '/privacy' },\n { kind: 'terms', title: 'Termos de Uso', path: '/terms' },\n { kind: 'returns', title: 'Trocas e Devoluções', path: '/refunds' },\n]\n\nexport interface UsePolicies {\n policies: StorefrontPolicy[]\n /** True when every policy has text — what a payment processor asks for at go-live. */\n complete: boolean\n contactEmail?: string\n}\n\n/**\n * The institutional pages, as data.\n *\n * All three are always listed, published or not: the routes and footer links\n * have to exist before the store writes its policies, because a 404 where a\n * processor expects a returns policy blocks go-live. `published` is what a\n * checklist reads; the page itself renders a placeholder.\n */\nexport function usePolicies(): UsePolicies {\n const config = useStorefrontConfig()\n const policies = POLICIES.map((policy) => {\n const content = config.legal?.[policy.kind]?.trim() || null\n return { ...policy, content, published: content !== null }\n })\n return {\n policies,\n complete: policies.every((policy) => policy.published),\n contactEmail: config.footer?.contact?.email,\n }\n}\n","import { useCartStore } from '../stores/cart.store'\n\n/** The cart: lines, totals and the drawer. */\nexport function useCart() {\n return useCartStore()\n}\n","import React from 'react'\nimport type { PaymentMethodKind, ShippingAddressInput } from '@fayz-ai/shop/types'\nimport { useStorefrontConfig } from '../document/config'\nimport {\n useCartStore,\n selectCount,\n selectSubtotal,\n selectDiscountTotal,\n selectShipping,\n selectTotal,\n} from '../stores/cart.store'\nimport { useSessionStore } from '../stores/session.store'\nimport { placeStorefrontOrder } from '../workflows/checkout'\nimport type {\n PlaceStorefrontOrderResult,\n StorefrontCheckoutAddress,\n StorefrontCheckoutCustomer,\n} from '../workflows/checkout'\n\nexport interface CheckoutTotals {\n count: number\n subtotal: number\n discountTotal: number\n shipping: number\n total: number\n}\n\nexport interface CheckoutSubmission {\n customer: StorefrontCheckoutCustomer\n address?: StorefrontCheckoutAddress\n shippingAddress?: ShippingAddressInput\n paymentMethod?: PaymentMethodKind\n markPaid?: boolean\n}\n\nexport interface UseCheckout {\n /** False when the store sells by catalog or enquiry — there is no checkout to render. */\n enabled: boolean\n /** True when the cart has nothing in it: the reason an enabled checkout still cannot proceed. */\n empty: boolean\n totals: CheckoutTotals\n placing: boolean\n error: string | null\n placeOrder: (input: CheckoutSubmission) => Promise<PlaceStorefrontOrderResult | null>\n}\n\n/**\n * The checkout, with the cart, session and config already bound.\n *\n * `placeOrder` takes only what the shopper typed. Everything the server needs\n * to be told about — lines, discount, totals, the customer session — is read\n * here from the stores, because a caller assembling that payload is a caller\n * that can assemble it wrongly, and the prices in it are exactly the numbers a\n * client must not be trusted with. `shop_place_order` recomputes from the\n * catalog regardless; this keeps the two from disagreeing on screen.\n *\n * `placing` is guarded rather than advisory: a double-submitted checkout is two\n * orders and two charges, and the button being disabled is not a guarantee.\n */\nexport function useCheckout(): UseCheckout {\n const config = useStorefrontConfig()\n const cart = useCartStore()\n const session = useSessionStore()\n const [placing, setPlacing] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n const inflight = React.useRef(false)\n\n const lines = cart.lines\n const totals: CheckoutTotals = {\n count: selectCount({ lines }),\n subtotal: selectSubtotal({ lines }),\n discountTotal: selectDiscountTotal({ lines, discountPercent: cart.discountPercent }),\n shipping: selectShipping({ lines }, config),\n total: selectTotal({ lines, discountPercent: cart.discountPercent }, config),\n }\n\n const placeOrder = React.useCallback(\n async (input: CheckoutSubmission) => {\n if (inflight.current) return null\n inflight.current = true\n setPlacing(true)\n setError(null)\n try {\n return await placeStorefrontOrder({\n config,\n cart: {\n lines: useCartStore.getState().lines,\n discountCode: useCartStore.getState().discountCode,\n discountPercent: useCartStore.getState().discountPercent,\n },\n session: { customerId: session.customerId, email: session.email },\n ...input,\n })\n } catch (err: unknown) {\n setError(err instanceof Error ? err.message : String(err))\n return null\n } finally {\n inflight.current = false\n setPlacing(false)\n }\n },\n [config, session.customerId, session.email],\n )\n\n return {\n enabled: config.features.checkout,\n empty: lines.length === 0,\n totals,\n placing,\n error,\n placeOrder,\n }\n}\n","import type { PaymentMethodKind } from '@fayz-ai/shop/types'\nimport { useStorefrontConfig } from '../document/config'\n\nexport interface UsePaymentMethods {\n /** The kinds this store offers, in the order it declared them. */\n methods: readonly PaymentMethodKind[]\n /** The default selection: the first declared method, or null when none are. */\n preferred: PaymentMethodKind | null\n supports: (method: PaymentMethodKind) => boolean\n}\n\n/**\n * Which payment methods the store offers.\n *\n * Deliberately provider-agnostic. A method is a declared KIND (`pix`,\n * `credit_card`, `cash`) — never a Stripe or Mercado Pago object — because the\n * canonical rule is that no storefront code imports a provider client. Which\n * gateway settles a `pix` is the backend's business, and swapping it must not\n * change a line here.\n */\nexport function usePaymentMethods(): UsePaymentMethods {\n const { payments } = useStorefrontConfig()\n const methods = payments.methods\n return {\n methods,\n preferred: methods[0] ?? null,\n supports: (method: PaymentMethodKind) => methods.includes(method),\n }\n}\n","import type { ShippingQuoteOption } from '@fayz-ai/shop/types'\nimport { useStorefrontConfig } from '../document/config'\nimport { useCartStore, selectSubtotal, selectShipping, selectRequiresShipping } from '../stores/cart.store'\nimport { useDeliveryStore } from '../stores/delivery.store'\nimport type { DeliveryStatus } from '../stores/delivery.store'\n\nexport interface UseShipping {\n postalCode: string\n status: DeliveryStatus\n error: string | null\n options: ShippingQuoteOption[]\n selectedZoneId: string | null\n /** What the current cart would be charged, quote or flat rate. */\n rate: number\n /** False when nothing in the cart travels (0046). The delivery block is not\n * shown at all — a download has no address, and \"Grátis\" implies one. */\n requiresShipping: boolean\n /** True when the flat-rate free-above threshold is already met. */\n free: boolean\n /** How much more the shopper must add to ship free, or null when there is no threshold. */\n amountToFreeShipping: number | null\n quote: (postalCode: string) => Promise<void>\n selectZone: (zoneId: string) => void\n clear: () => void\n}\n\n/**\n * What delivery costs for the cart as it stands.\n *\n * The quote is asked for against the CURRENT subtotal and is never persisted —\n * a price restored from localStorage is a price the shopper can edit with\n * devtools. The order is charged from `shop_place_order`, which recomputes from\n * the same zones and ignores anything the client sends; this hook exists to\n * show a number, not to decide one.\n */\nexport function useShipping(): UseShipping {\n const config = useStorefrontConfig()\n const lines = useCartStore((state) => state.lines)\n const delivery = useDeliveryStore()\n\n const subtotal = selectSubtotal({ lines })\n const rate = selectShipping({ lines }, config)\n const threshold = config.shipping.freeAbove ?? null\n\n return {\n postalCode: delivery.postalCode,\n status: delivery.status,\n error: delivery.error,\n options: delivery.options,\n selectedZoneId: delivery.selectedZoneId,\n rate,\n requiresShipping: lines.length === 0 || selectRequiresShipping({ lines }),\n free: rate === 0 && lines.length > 0,\n amountToFreeShipping:\n threshold === null || subtotal >= threshold ? null : Math.max(0, threshold - subtotal),\n quote: (postalCode: string) => delivery.resolve(postalCode, subtotal),\n selectZone: delivery.selectZone,\n clear: delivery.clear,\n }\n}\n","import React from 'react'\nimport { formatPostalCode, lookupPostalCode, normalizePostalCode } from '@fayz-ai/core'\nimport type { PostalAddress } from '@fayz-ai/core'\n\nexport type AddressLookupStatus = 'idle' | 'loading' | 'found' | 'not-found' | 'error'\n\nexport interface UseAddress {\n postalCode: string\n /** The same code formatted for display (`01311-000`). */\n display: string\n address: PostalAddress | null\n status: AddressLookupStatus\n error: string | null\n /** Set the code and look it up once it is complete. Partial input never calls out. */\n setPostalCode: (value: string) => void\n clear: () => void\n}\n\nconst COMPLETE = 8\n\n/**\n * A postal code, and the address it resolves to.\n *\n * The lookup fires on the code being COMPLETE rather than on every keystroke —\n * a debounce would still send `0`, `01`, `013`… and each is a request that can\n * only fail. The last completed lookup wins: a shopper who corrects a typo mid\n * flight must not have the stale response overwrite the new one.\n *\n * This is the address half of checkout, separated from `useShipping` on purpose:\n * a store that does not ship still asks for a billing address.\n */\nexport function useAddress(initial = ''): UseAddress {\n const [postalCode, setValue] = React.useState(normalizePostalCode(initial))\n const [address, setAddress] = React.useState<PostalAddress | null>(null)\n const [status, setStatus] = React.useState<AddressLookupStatus>('idle')\n const [error, setError] = React.useState<string | null>(null)\n const inflight = React.useRef(0)\n\n const setPostalCode = React.useCallback((value: string) => {\n const normalized = normalizePostalCode(value)\n setValue(normalized)\n\n if (normalized.length < COMPLETE) {\n setAddress(null)\n setStatus('idle')\n setError(null)\n return\n }\n\n const ticket = ++inflight.current\n setStatus('loading')\n setError(null)\n void lookupPostalCode(normalized)\n .then((found) => {\n if (ticket !== inflight.current) return\n setAddress(found)\n setStatus(found ? 'found' : 'not-found')\n })\n .catch((err: unknown) => {\n if (ticket !== inflight.current) return\n setAddress(null)\n setStatus('error')\n setError(err instanceof Error ? err.message : String(err))\n })\n }, [])\n\n const clear = React.useCallback(() => {\n inflight.current++\n setValue('')\n setAddress(null)\n setStatus('idle')\n setError(null)\n }, [])\n\n return {\n postalCode,\n display: formatPostalCode(postalCode),\n address,\n status,\n error,\n setPostalCode,\n clear,\n }\n}\n","import React from 'react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport type { Order } from '@fayz-ai/shop/types'\n\nexport interface UseOrder {\n order: Order | null\n loading: boolean\n error: string | null\n reload: () => void\n}\n\n/**\n * One order by id — the confirmation page, and the link a shopper is emailed.\n *\n * A null id is a legitimate state (the route matched before the id resolved),\n * not an error: it settles to `loading: false` with no order rather than\n * reporting a failure the shopper cannot act on. The last request wins, so a\n * fast reload cannot leave the previous order on screen.\n */\nexport function useOrder(orderId: string | null | undefined): UseOrder {\n const [order, setOrder] = React.useState<Order | null>(null)\n const [loading, setLoading] = React.useState(Boolean(orderId))\n const [error, setError] = React.useState<string | null>(null)\n const [nonce, setNonce] = React.useState(0)\n\n React.useEffect(() => {\n if (!orderId) {\n setOrder(null)\n setLoading(false)\n setError(null)\n return\n }\n\n let current = true\n setLoading(true)\n setError(null)\n\n void getShopProvider()\n .getOrder(orderId)\n .then((found) => {\n if (!current) return\n setOrder(found ?? null)\n setLoading(false)\n })\n .catch((err: unknown) => {\n if (!current) return\n setOrder(null)\n setError(err instanceof Error ? err.message : String(err))\n setLoading(false)\n })\n\n return () => {\n current = false\n }\n }, [orderId, nonce])\n\n return { order, loading, error, reload: () => setNonce((n) => n + 1) }\n}\n","import { BLOCK_PATH_ATTRIBUTE, BLOCK_TYPE_ATTRIBUTE, setBlockEditorMode } from '@fayz-ai/core'\n\n// The editor bridge — a storefront running inside an editor's iframe.\n// ACTIVATE/DEACTIVATE in; READY/PICKED/CANCELLED/NAVIGATION_CHANGE out.\n//\n// A pick answers with `{ path, type }` rather than a CSS selector: the page was\n// rendered from a document, so the path is simply true, and the parent hands it\n// straight to describeStore for the settings schema and to applyChange to save.\n//\n// Allowed origins are declared by the CALLER, never announced by the sender —\n// an iframe's parent is chosen by whoever embeds the page, so trusting the\n// announcement hands an element picker to any hostile embedder. Outbound\n// messages go to the activating origin, never '*', and nothing is posted before\n// one has activated.\n\nexport interface EditorBridgeOptions {\n /**\n * Origins allowed to drive the picker. An activation from anywhere else is\n * ignored. Required: there is no safe default, because the parent of an\n * iframe is chosen by whoever embedded it.\n */\n allowedOrigins: readonly string[]\n /** Test seam. Defaults to the ambient window. */\n target?: Window\n}\n\nexport interface PickedBlock {\n /** Dotted document path — what applyChange accepts and validateStore reports. */\n path: string\n /** The block's registered type, so the parent can look up its schema. */\n type: string\n /** Bounding rect of the block's first painted child, for the parent's overlay. */\n rect?: { top: number; left: number; width: number; height: number }\n}\n\nexport const EDITOR_MESSAGES = {\n activate: 'ACTIVATE_ELEMENT_PICKER',\n deactivate: 'DEACTIVATE_ELEMENT_PICKER',\n ready: 'ELEMENT_PICKER_READY',\n picked: 'ELEMENT_PICKED',\n cancelled: 'ELEMENT_PICKER_CANCELLED',\n navigation: 'NAVIGATION_CHANGE',\n} as const\n\n/**\n * The nearest ancestor that is a block, and the element that actually paints.\n *\n * The stamp lives on a `display: contents` wrapper, which has no box of its\n * own — `getBoundingClientRect()` on it returns zeros. So the rect comes from\n * its first element child, which is the block's real root.\n */\nexport function blockAt(element: Element | null): { path: string; type: string; node: Element } | null {\n let current: Element | null = element\n while (current) {\n const path = current.getAttribute?.(BLOCK_PATH_ATTRIBUTE)\n if (path) {\n const painted = current.firstElementChild ?? current\n return { path, type: current.getAttribute(BLOCK_TYPE_ATTRIBUTE) ?? '', node: painted }\n }\n current = current.parentElement\n }\n return null\n}\n\nfunction rectOf(element: Element): PickedBlock['rect'] {\n const r = element.getBoundingClientRect?.()\n if (!r) return undefined\n return { top: r.top, left: r.left, width: r.width, height: r.height }\n}\n\n/**\n * Wire the storefront to an editor parent. Returns a teardown.\n *\n * Inert when the page is not framed: a storefront served to a shopper has\n * `window.parent === window`, nothing is registered, and editor mode stays off.\n */\nexport function connectEditorBridge(options: EditorBridgeOptions): () => void {\n const win = options.target ?? (typeof window === 'undefined' ? undefined : window)\n if (!win || win.parent === win) return () => {}\n\n const allowed = new Set(options.allowedOrigins)\n let parentOrigin: string | null = null\n let active = false\n let hovered: { path: string; type: string; node: Element } | null = null\n\n const post = (message: Record<string, unknown>) => {\n if (!parentOrigin) return\n win.parent.postMessage(message, parentOrigin)\n }\n\n const onMove = (event: MouseEvent) => {\n if (!active) return\n hovered = blockAt(event.target as Element)\n }\n\n const onClick = (event: MouseEvent) => {\n if (!active) return\n // A picker click must never also follow the link it landed on.\n event.preventDefault()\n event.stopPropagation()\n const hit = hovered ?? blockAt(event.target as Element)\n if (!hit) return\n const picked: PickedBlock = { path: hit.path, type: hit.type, rect: rectOf(hit.node) }\n post({ type: EDITOR_MESSAGES.picked, data: picked })\n stop()\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (!active || event.key !== 'Escape') return\n event.preventDefault()\n post({ type: EDITOR_MESSAGES.cancelled })\n stop()\n }\n\n function start() {\n if (active) return\n active = true\n setBlockEditorMode(true)\n win!.document.addEventListener('mousemove', onMove, true)\n win!.document.addEventListener('click', onClick, true)\n win!.document.addEventListener('keydown', onKeyDown, true)\n win!.document.body.style.cursor = 'crosshair'\n post({ type: EDITOR_MESSAGES.ready })\n }\n\n function stop() {\n if (!active) return\n active = false\n hovered = null\n win!.document.removeEventListener('mousemove', onMove, true)\n win!.document.removeEventListener('click', onClick, true)\n win!.document.removeEventListener('keydown', onKeyDown, true)\n win!.document.body.style.cursor = ''\n }\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== win.parent) return\n // The origin must be declared by US, not announced by the sender — an\n // attacker embedding the store controls both `event.data.parentOrigin` and\n // the frame, so trusting the announcement trusts the attacker.\n if (!allowed.has(event.origin)) return\n parentOrigin = event.origin\n\n const kind = (event.data as { type?: string } | null)?.type\n if (kind === EDITOR_MESSAGES.activate) start()\n else if (kind === EDITOR_MESSAGES.deactivate) stop()\n }\n\n win.addEventListener('message', onMessage)\n return () => {\n stop()\n setBlockEditorMode(false)\n win.removeEventListener('message', onMessage)\n }\n}\n\n/**\n * Tell the parent the route changed, so its URL bar follows the iframe.\n *\n * Silent until an allowed parent has activated the bridge — the path is not\n * sensitive, but broadcasting to '*' from every storefront is a habit worth\n * not forming.\n */\nexport function reportNavigation(path: string, parentOrigin: string | null, target?: Window): void {\n const win = target ?? (typeof window === 'undefined' ? undefined : window)\n if (!win || win.parent === win || !parentOrigin) return\n win.parent.postMessage({ type: EDITOR_MESSAGES.navigation, path }, parentOrigin)\n}\n","import { describeBlocks } from '@fayz-ai/core'\nimport type { BlockDescriptor } from '@fayz-ai/core'\nimport { parseStorePath } from '../document/change'\nimport { registerStorefrontBlocks } from './registry'\nimport { BLOCK_STRUCTURAL_KEYS, isNestedBlockRef } from './page-blocks'\nimport type { StoreDocument } from '../document/sections'\n\n// From a picked document path to everything a form generator needs: which block\n// it is, what it currently says, and the SETTINGS SCHEMA it declared. A form\n// built from that schema cannot offer a setting the block does not have and\n// updates itself when the block does.\n//\n// Deliberately NOT a renderer — returning data keeps the SDK out of any one\n// editor's design system.\n\nexport interface BlockAtPath {\n /** The path as given, echoed so a caller can key state by it. */\n path: string\n /** The block's registered type. */\n type: string\n /**\n * Where this block's settings live: `<path>.props` for the nested form,\n * `<path>` itself for the flat one. Both forms MIX inside one array, so a\n * caller appending `.props` by hand is right about some blocks and silently\n * wrong about the rest. Pass this to `settingChange` and it cannot happen.\n */\n settingsPath: string\n /** Current values, whichever form they took — the form's initial state. */\n props: Record<string, unknown>\n /** Empty when the block declares no settings, which is itself the answer. */\n settings: BlockDescriptor['settings']\n /** For a caller that wants labels, help text or presets. */\n descriptor: BlockDescriptor | null\n}\n\nexport type BlockAtPathError =\n | { code: 'unparseable-path'; message: string }\n | { code: 'no-block-at-path'; message: string }\n | { code: 'unknown-block'; message: string; valid: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Walk a parsed path, resolving `[#id]` steps against `id` fields. */\nfunction walk(document: StoreDocument | Record<string, unknown>, path: string): unknown {\n const steps = parseStorePath(path)\n if (!steps) return undefined\n let cursor: unknown = document\n for (const step of steps) {\n if (step.kind === 'key') {\n if (!isRecord(cursor)) return undefined\n cursor = cursor[step.key]\n } else if (step.kind === 'index') {\n if (!Array.isArray(cursor)) return undefined\n cursor = cursor[step.index]\n } else {\n if (!Array.isArray(cursor)) return undefined\n cursor = cursor.find((item) => isRecord(item) && item.id === step.id)\n }\n }\n return cursor\n}\n\n/**\n * Resolve a picked path against a Store Document.\n *\n * Every failure names what went wrong and, for an unknown block, the valid set\n * (I2) — an editor that silently renders an empty panel teaches a merchant that\n * the editor is broken.\n */\nexport function blockAtPath(\n document: StoreDocument | Record<string, unknown>,\n path: string,\n): { ok: true; block: BlockAtPath } | { ok: false; error: BlockAtPathError } {\n if (!parseStorePath(path)) {\n return { ok: false, error: { code: 'unparseable-path', message: `\"${path}\" is not a document path` } }\n }\n\n const node = walk(document, path)\n if (!isRecord(node) || typeof node.type !== 'string') {\n return {\n ok: false,\n error: { code: 'no-block-at-path', message: `nothing at \"${path}\" is a block (a block is an object with a \"type\")` },\n }\n }\n\n // The registry is the source of the schema, so it must be populated — the\n // same requirement `validateStore` has, for the same reason.\n registerStorefrontBlocks()\n const descriptors = describeBlocks()\n const descriptor = descriptors.find((d) => d.id === node.type) ?? null\n\n if (!descriptor) {\n return {\n ok: false,\n error: {\n code: 'unknown-block',\n message: `block \"${node.type}\" is not registered`,\n valid: descriptors.map((d) => d.id).sort(),\n },\n }\n }\n\n // `isNestedBlockRef` is the renderer's own rule, imported rather than\n // restated: the renderer and the editor disagreeing about where a block's\n // settings live is exactly the bug that makes an edit vanish on save.\n const nested = isNestedBlockRef(node)\n const props = nested\n ? isRecord(node.props)\n ? node.props\n : {}\n : Object.fromEntries(Object.entries(node).filter(([key]) => !BLOCK_STRUCTURAL_KEYS.has(key)))\n\n return {\n ok: true,\n block: {\n path,\n type: node.type,\n settingsPath: nested ? `${path}.props` : path,\n props,\n settings: descriptor.settings ?? [],\n descriptor,\n },\n }\n}\n\n/**\n * The change that saves one edited setting.\n *\n * Takes `settingsPath`, not the block's path: only `blockAtPath` has seen the\n * node and knows which form it took. Hardcoding `.props.` here wrote an ignored\n * key on every flat block — a save that reported success and changed nothing.\n */\nexport function settingChange(settingsPath: string, settingId: string, value: unknown): {\n op: 'set' | 'remove'\n path: string\n value?: unknown\n} {\n const path = `${settingsPath}.${settingId}`\n // Clearing a field means the setting is absent, not present-and-empty — an\n // empty string would render as an empty heading where the default belongs.\n if (value === undefined || value === '') return { op: 'remove', path }\n return { op: 'set', path, value }\n}\n","import { applyChange, parseStorePath } from './change'\nimport type { StoreChange } from './change'\nimport type { StoreDocument } from './sections'\nimport { BLOCK_STRUCTURAL_KEYS, isNestedBlockRef } from '../blocks/page-blocks'\nimport { validateStore } from './validate'\nimport type { StoreValidationReport } from './validate'\n\n// The settings overlay, shaped like Shopify's `settings_data.json`: the\n// committed `fayz.store.json` holds the structure, the overlay holds what the\n// merchant chose, and the two merge at render.\n//\n// THE RULE, and why this is not a generic deep merge: an overlay may only\n// change SETTINGS. It may not add, remove, reorder or retype a block, and it\n// may not touch catalog, commerce, backend, auth or code. Without it, the first\n// overlay that inserts a block makes the committed document a lie. A refused\n// path is therefore the mechanism, not a failure mode to route around — an\n// editor that needs to add a block is asking for a commit.\n\n/** Sparse map of document path -> value. Absent means \"use the document's\". */\nexport type StoreOverlay = Record<string, unknown>\n\nexport interface OverlayRejection {\n path: string\n code: 'unparseable-path' | 'not-a-setting' | 'section-not-overlayable' | 'no-block-at-path'\n message: string\n}\n\nexport interface ApplyOverlayResult {\n /** The document a shopper is served: base with the accepted settings applied. */\n document: Record<string, unknown>\n /** Paths that were applied, in the order they were. */\n applied: string[]\n /** Paths the rule refused, each saying why. */\n rejected: OverlayRejection[]\n /** Validation of the MERGED document — the only one that matters. */\n validation: StoreValidationReport\n}\n\n/**\n * Sections an overlay may reach into at all. Everything else is mirrored from\n * the backend (catalog), money (commerce), infrastructure (backend, auth) or\n * code — none of which is a settings-panel change.\n */\nexport const OVERLAYABLE_SECTIONS = ['presentation', 'theme'] as const\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Is this path a setting? Needs the document, and cannot work without it —\n * a path-only rule (\"settings live under `props`\") failed the fleet twice:\n *\n * - the two block forms MIX inside one array (artorious's home page is 3\n * nested and 5 flat), so requiring `props` made the flat ones uneditable;\n * - a setting VALUE can look exactly like a block — a form field is\n * `{id, label, type, required}` — so keying on `type` would refuse a\n * legitimate edit.\n *\n * The walk resolves against the real document and asks the renderer's own\n * `isNestedBlockRef` which form each block took. It stops the moment it enters\n * a setting, which is what makes the form-field case need no exception.\n *\n * `theme` is settings throughout — it is nothing but tokens.\n */\nexport function isSettingPath(\n document: StoreDocument | Record<string, unknown>,\n path: string,\n): OverlayRejection | null {\n const steps = parseStorePath(path)\n if (!steps || steps.length === 0) {\n return { path, code: 'unparseable-path', message: `\"${path}\" is not a document path` }\n }\n\n const head = steps[0]\n if (head?.kind !== 'key' || !OVERLAYABLE_SECTIONS.includes(head.key as (typeof OVERLAYABLE_SECTIONS)[number])) {\n return {\n path,\n code: 'section-not-overlayable',\n message:\n `an overlay may only change ${OVERLAYABLE_SECTIONS.join(' and ')} — ` +\n `\"${path}\" targets something else. Catalog mirrors the backend, commerce is money, ` +\n `code is code: none of those is a settings-panel change.`,\n }\n }\n\n if (head.key === 'theme') return null\n\n const structural = (): OverlayRejection => ({\n path,\n code: 'not-a-setting',\n message:\n `\"${path}\" is not a setting. An overlay changes what a block SAYS, never which ` +\n `blocks exist or in what order — adding, removing, reordering or retyping a block ` +\n `is a change to the committed document, and belongs in a commit.`,\n })\n\n let cursor: unknown = document\n // True when `cursor` is a block: we reached it by indexing an array while\n // still walking structure, and every array reached that way is a block\n // container (the walk returns the moment it enters settings, so a list\n // setting's array is never indexed here).\n let atBlock = false\n\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i]!\n\n if (atBlock) {\n if (!isRecord(cursor)) {\n return {\n path,\n code: 'no-block-at-path',\n message:\n `nothing in the document sits at the block \"${path}\" names — most likely a setting ` +\n `left behind by a block deleted in a later commit. pruneOverlay drops these.`,\n }\n }\n if (step.kind !== 'key') return structural()\n\n if (isNestedBlockRef(cursor)) {\n // `children` is another block array, not a setting: keep walking\n // structure so a nested block's own settings still resolve.\n if (step.key === 'children') {\n cursor = cursor.children\n atBlock = false\n continue\n }\n // Anything but `props` is identity (type, id, data) or a stray key the\n // renderer ignores in this form.\n if (step.key !== 'props') return structural()\n // The props object itself: replacing it wholesale is a rewrite.\n if (i === steps.length - 1) return structural()\n return null\n }\n\n // Flat form: everything that is not identity is a setting, which is the\n // same line `toBlockNode` draws when it reads this block.\n if (BLOCK_STRUCTURAL_KEYS.has(step.key)) return structural()\n return null\n }\n\n if (step.kind === 'key') {\n if (!isRecord(cursor)) return structural()\n cursor = cursor[step.key]\n continue\n }\n if (!Array.isArray(cursor)) return structural()\n cursor = step.kind === 'index' ? cursor[step.index] : cursor.find((item) => isRecord(item) && item.id === step.id)\n atBlock = true\n }\n\n // The steps ran out while still walking structure: the path names a whole\n // block, a block array, or a page — all of which are the repo's to say.\n return structural()\n}\n\n/**\n * Merge an overlay onto a document. Never mutates the input. Rejections are\n * reported rather than thrown: an overlay with one bad entry must still deliver\n * the other forty, or a store stops updating and nobody knows why.\n */\nexport function applyOverlay(\n document: StoreDocument | Record<string, unknown>,\n overlay: StoreOverlay,\n): ApplyOverlayResult {\n const rejected: OverlayRejection[] = []\n const changes: StoreChange[] = []\n\n // Sorted so the result is deterministic regardless of key insertion order —\n // two servers merging the same overlay must serve the same page.\n for (const path of Object.keys(overlay).sort()) {\n const rejection = isSettingPath(document, path)\n if (rejection) {\n rejected.push(rejection)\n continue\n }\n const value = overlay[path]\n changes.push(\n value === undefined\n ? { op: 'remove', path }\n : { op: 'set', path, value: value as StoreChange['value'] },\n )\n }\n\n // `onInvalid: 'reject'` discards an invalid merge whole and serves the BASE:\n // degrading to what the repo says is safe, half-merging is a page nobody has\n // validated. The save path validates before persisting; this is the belt.\n const result = applyChange(document, changes, {\n sections: [...OVERLAYABLE_SECTIONS],\n onInvalid: 'reject',\n })\n\n // `applyChange.errors` mixes its own refusals with the merged document's\n // validation errors. Only errors on a submitted path count as rejections —\n // blaming an overlay entry for a pre-existing error at `commerce.mode` would\n // have pruneOverlay delete healthy settings.\n //\n // Blame matches BOTH directions along a branch. Downward: `set` creates\n // missing intermediates, so an entry can materialise a block with no `type`\n // and the error lands beneath it. Upward: the array refuses the index and the\n // error lands at `blocks[9]`, a PREFIX of what was submitted — which is what\n // an orphan actually produces, so matching only downward let every orphan\n // through silently. A bare section path is excluded, or one document-level\n // error would condemn the whole overlay.\n const applied = new Set(result.applied.map((a) => a.path))\n const beneath = (ancestor: string, descendant: string): boolean =>\n descendant === ancestor || descendant.startsWith(`${ancestor}.`) || descendant.startsWith(`${ancestor}[`)\n\n for (const failure of result.errors) {\n if (!failure.path || !failure.path.includes('.')) continue\n const owner = changes.find(\n (c) => !applied.has(c.path) && (beneath(c.path, failure.path) || beneath(failure.path, c.path)),\n )\n if (!owner || rejected.some((r) => r.path === owner.path)) continue\n rejected.push({ path: owner.path, code: 'not-a-setting', message: failure.message })\n }\n\n return {\n document: result.doc as unknown as Record<string, unknown>,\n applied: result.applied.map((a) => a.resolvedPath),\n rejected,\n validation: result.validation,\n }\n}\n\n/**\n * Drop overlay entries the document can no longer accept. Orphans are harmless\n * on their own — applyOverlay refuses them — but they accumulate, and an\n * overlay nobody prunes hides a real mistake among a hundred dead ones.\n */\nexport function pruneOverlay(\n document: StoreDocument | Record<string, unknown>,\n overlay: StoreOverlay,\n): { overlay: StoreOverlay; dropped: string[] } {\n const result = applyOverlay(document, overlay)\n const dead = new Set(result.rejected.map((r) => r.path))\n const kept: StoreOverlay = {}\n for (const [path, value] of Object.entries(overlay)) {\n if (!dead.has(path)) kept[path] = value\n }\n return { overlay: kept, dropped: [...dead].sort() }\n}\n","import type { StorefrontTheme } from '../lib/theme'\nimport type { HomeConfig } from '../blocks/sections'\n\n// ---------------------------------------------------------------------------\n// Template presets — recreations of the four Nuvemshop patterns selected in\n// docs/archive/storefront-templates-research.md. Each is { theme, home() } so an app\n// (or the Fayz agent) starts from a complete professional store and overrides\n// copy, colors, hero images and sections — the saas-core theming workflow.\n// ---------------------------------------------------------------------------\n\n/** Real imagery for a template home — resolved at build time (e.g. via\n * scripts/fetch-unsplash.mjs); falls back to gradient placeholders when omitted. */\nexport interface TemplateImages {\n hero?: Array<string | undefined>\n banners?: Array<string | undefined>\n}\n\nexport interface StorefrontTemplate {\n id: string\n /** The Nuvemshop pattern this recreates */\n inspiration: string\n theme: StorefrontTheme\n /** Default home blueprint — pass the store name for copy interpolation */\n home: (storeName: string, images?: TemplateImages) => HomeConfig\n announcement?: string\n}\n\n/** maré — elegant fashion (Rio): airy warm paper, olive ink, sand CTA, centered logo. */\nexport const mareTemplate: StorefrontTemplate = {\n id: 'mare',\n inspiration: 'Nuvemshop Rio',\n announcement: 'FRETE GRÁTIS EM COMPRAS ACIMA DE R$ 300',\n theme: {\n name: 'mare',\n colors: {\n background: '40 14% 93%',\n foreground: '90 8% 38%',\n primary: '42 32% 61%',\n primaryForeground: '40 30% 12%',\n card: '40 20% 97%',\n cardForeground: '90 10% 25%',\n muted: '40 12% 88%',\n mutedForeground: '90 6% 50%',\n border: '40 10% 82%',\n announcementBackground: '90 10% 30%',\n announcementForeground: '40 20% 95%',\n },\n font: { heading: 'Plus Jakarta Sans', body: 'Plus Jakarta Sans' },\n radius: 'soft',\n header: { variant: 'centered' },\n productCard: { style: 'editorial', imageAspect: 'portrait' },\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'banner',\n height: 'tall',\n slides: [\n { title: 'Feito para durar', subtitle: `A nova coleção ${storeName} chegou — peças atemporais em materiais honestos.`, cta: 'Ver coleção', hue: 75, image: images?.hero?.[0] },\n ],\n },\n { type: 'categories', style: 'bubbles' },\n { type: 'products', title: 'Destaques', filter: 'all', limit: 4 },\n { type: 'banner', title: 'Até 30% off', eyebrow: 'por tempo limitado', subtitle: 'Peças selecionadas da estação', cta: 'Aproveitar', hue: 40, image: images?.banners?.[0] },\n { type: 'products', title: 'Promoções', filter: 'sale', limit: 4 },\n { type: 'products', title: 'Lançamentos', filter: 'new', limit: 4 },\n { type: 'newsletter', title: 'Assine nossa newsletter', subtitle: 'Novidades e ofertas exclusivas, sem spam.' },\n ],\n }),\n}\n\n/** sertão — editorial organic (Uyuni): cream paper, coffee serif ink, boxed hero, manifesto. */\nexport const sertaoTemplate: StorefrontTemplate = {\n id: 'sertao',\n inspiration: 'Nuvemshop Uyuni',\n theme: {\n name: 'sertao',\n colors: {\n background: '30 100% 98%',\n foreground: '28 42% 32%',\n primary: '28 42% 32%',\n primaryForeground: '30 100% 97%',\n card: '32 60% 96%',\n cardForeground: '28 40% 26%',\n muted: '32 40% 92%',\n mutedForeground: '28 22% 48%',\n border: '28 30% 80%',\n },\n font: { heading: 'Marcellus', body: 'Marcellus', fallback: 'serif' },\n radius: 'none',\n header: { variant: 'minimal', uppercaseNav: true },\n productCard: { style: 'editorial', imageAspect: 'portrait' },\n uppercaseButtons: true,\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'banner',\n height: 'tall',\n slides: [\n { title: 'Essenciais naturais', subtitle: 'Conheça nossa coleção', cta: 'Ver mais', hue: 28, boxed: true, image: images?.hero?.[0] },\n ],\n },\n {\n type: 'manifesto',\n text: `Num mundo de pressa e excesso, ${storeName} escolhe o caminho lento: ingredientes honestos, produção pequena e cuidado em cada detalhe.`,\n },\n { type: 'categories', style: 'tiles' },\n { type: 'products', title: 'ESSENCIAIS', filter: 'all', limit: 4 },\n {\n type: 'testimonials',\n title: 'Nossos clientes',\n items: [\n { quote: 'Qualidade impecável e um cheiro que abraça.', author: 'Helena M.' },\n { quote: 'Compro há dois anos e nunca me decepcionou.', author: 'Rafael T.' },\n { quote: 'Entrega rápida e embalagem linda, dá gosto de presentear.', author: 'Cláudia P.' },\n ],\n },\n { type: 'products', title: 'NOVIDADES', filter: 'new', limit: 4 },\n {\n type: 'benefits',\n items: [\n { icon: 'Truck', title: 'Frete para todo o Brasil', text: 'Envio em até 48h' },\n { icon: 'Leaf', title: '100% vegano', text: 'Sem testes em animais' },\n { icon: 'RotateCcw', title: 'Troca fácil', text: '30 dias para trocar' },\n ],\n },\n { type: 'newsletter', title: 'NEWSLETTER', subtitle: 'Histórias, lançamentos e cuidado — direto no seu e-mail.' },\n ],\n }),\n}\n\n/** volt — bold tech (Brasília): white canvas, near-black ink, vivid CTA, dark search-first header, split hero. */\nexport const voltTemplate: StorefrontTemplate = {\n id: 'volt',\n inspiration: 'Nuvemshop Brasília',\n announcement: 'CUPOM BEMVINDO10 — 10% DE DESCONTO NA PRIMEIRA COMPRA',\n theme: {\n name: 'volt',\n colors: {\n background: '0 0% 100%',\n foreground: '0 0% 7%',\n primary: '341 100% 45%',\n primaryForeground: '0 0% 100%',\n card: '0 0% 98%',\n cardForeground: '0 0% 10%',\n muted: '0 0% 94%',\n mutedForeground: '0 0% 40%',\n border: '0 0% 88%',\n headerBackground: '0 0% 6%',\n headerForeground: '0 0% 98%',\n announcementBackground: '341 100% 45%',\n announcementForeground: '0 0% 100%',\n },\n font: { heading: 'Chakra Petch', body: 'Rubik' },\n radius: 'soft',\n header: { variant: 'search', uppercaseNav: true },\n productCard: { style: 'card', imageAspect: 'square' },\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'split',\n slides: [\n { title: 'Tecnologia', subtitle: 'O melhor do hardware e dos acessórios', hue: 250, image: images?.hero?.[0] },\n { title: 'Ofertas', subtitle: `Descontos semanais ${storeName}`, hue: 341, href: '/catalog', image: images?.hero?.[1] },\n ],\n },\n {\n type: 'benefits',\n items: [\n { icon: 'CreditCard', title: '3x sem juros', text: 'Em todo o site' },\n { icon: 'Truck', title: 'Envio em 24h', text: 'Para todo o Brasil' },\n { icon: 'ShieldCheck', title: 'Compra segura', text: 'Seus dados protegidos' },\n ],\n },\n { type: 'products', title: 'NOVIDADES', filter: 'new', limit: 4 },\n { type: 'banner', title: 'DESCONTOS SEMANAIS', eyebrow: 'toda sexta', subtitle: 'Ofertas novas, estoque limitado', cta: 'Conferir', hue: 341, image: images?.banners?.[0] },\n { type: 'products', title: 'PROMOÇÕES', filter: 'sale', limit: 4 },\n { type: 'newsletter', title: 'Entre para o clube', subtitle: 'Cupons e lançamentos antes de todo mundo.' },\n ],\n }),\n}\n\n/** atelier — classic premium retail (Flex): white, near-black, gold accent, slider hero, trust badges. */\nexport const atelierTemplate: StorefrontTemplate = {\n id: 'atelier',\n inspiration: 'Nuvemshop Flex',\n theme: {\n name: 'atelier',\n colors: {\n background: '0 0% 100%',\n foreground: '0 0% 9%',\n primary: '40 45% 48%',\n primaryForeground: '0 0% 100%',\n card: '0 0% 99%',\n cardForeground: '0 0% 9%',\n muted: '40 10% 95%',\n mutedForeground: '0 0% 42%',\n border: '0 0% 88%',\n announcementBackground: '0 0% 9%',\n announcementForeground: '0 0% 98%',\n },\n font: { heading: 'Outfit', body: 'Outfit' },\n radius: 'none',\n header: { variant: 'centered', uppercaseNav: true },\n productCard: { style: 'card', imageAspect: 'square' },\n uppercaseButtons: true,\n },\n announcement: 'PARCELE EM ATÉ 10X · 5% OFF NO PIX',\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'slider',\n height: 'medium',\n slides: [\n { title: 'Feito para quem valoriza detalhes', subtitle: `Coleção exclusiva ${storeName}`, cta: 'APROVEITE', hue: 40, image: images?.hero?.[0] },\n { title: 'Clássicos que não saem de moda', subtitle: 'Peças autorais, produção limitada', cta: 'VER COLEÇÃO', hue: 210, image: images?.hero?.[1] },\n ],\n },\n {\n type: 'benefits',\n items: [\n { icon: 'CreditCard', title: 'Parcele em até 10x', text: 'Ou 5% off no PIX' },\n { icon: 'Lock', title: 'Site 100% seguro', text: 'Seus dados protegidos' },\n { icon: 'Award', title: 'Peças exclusivas', text: 'Produtos 100% autorais' },\n ],\n },\n { type: 'categories', style: 'tiles' },\n { type: 'products', title: 'Novidades', filter: 'new', limit: 4 },\n { type: 'banner', title: 'Promoções', eyebrow: 'seleção especial', subtitle: 'Selecionados com até 25% off', cta: 'Ver ofertas', hue: 40, image: images?.banners?.[0] },\n { type: 'products', title: 'Promoções', filter: 'sale', limit: 4 },\n {\n type: 'testimonials',\n title: 'O que dizem sobre nós',\n items: [\n { quote: 'Acabamento perfeito, superou a expectativa.', author: 'Mariana C.' },\n { quote: 'Atendimento impecável do pedido à entrega.', author: 'Jorge L.' },\n { quote: 'Virou minha loja favorita para presentes.', author: 'Paula R.' },\n ],\n },\n { type: 'newsletter' },\n ],\n }),\n}\n\n/** food — warm appetizing delivery (steakhouse / burger / comfort food): dark inviting\n * header, ember CTA, cream canvas, rounded cards, menu-first home with \"mais pedidos\"\n * rail and social proof. Built for restaurant/food stores — override to go fully dark. */\nexport const foodTemplate: StorefrontTemplate = {\n id: 'food',\n inspiration: 'Delivery / restaurant storefront',\n announcement: 'ENTREGA GRÁTIS ACIMA DE R$ 150 · PEÇA JÁ',\n theme: {\n name: 'food',\n colors: {\n background: '30 33% 97%',\n foreground: '20 14% 15%',\n primary: '14 84% 50%',\n primaryForeground: '0 0% 100%',\n card: '30 33% 99%',\n cardForeground: '20 14% 15%',\n muted: '28 20% 92%',\n mutedForeground: '22 10% 42%',\n border: '28 18% 85%',\n headerBackground: '20 14% 11%',\n headerForeground: '30 24% 96%',\n announcementBackground: '14 84% 50%',\n announcementForeground: '0 0% 100%',\n },\n font: { heading: 'Poppins', body: 'Inter' },\n radius: 'round',\n header: { variant: 'classic' },\n productCard: { style: 'card', imageAspect: 'square' },\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'banner',\n height: 'tall',\n slides: [\n { title: 'Sabor de verdade, na sua porta', subtitle: `${storeName} — feito na hora, do jeito que você ama.`, cta: 'Ver cardápio', href: '/catalog', hue: 20, image: images?.hero?.[0] },\n ],\n },\n {\n type: 'benefits',\n items: [\n { icon: 'Flame', title: 'Feito na hora', text: 'Preparado com capricho' },\n { icon: 'Truck', title: 'Entrega rápida', text: 'Frete grátis acima de R$ 150' },\n { icon: 'CreditCard', title: 'Pagamento fácil', text: 'Pix, cartão e mais' },\n ],\n },\n { type: 'categories', style: 'tiles', title: 'Nosso cardápio' },\n { type: 'products', title: 'Mais pedidos', eyebrow: 'favoritos da casa', filter: 'all', limit: 8 },\n { type: 'banner', title: 'Combo do dia', eyebrow: 'oferta', subtitle: 'Seleção especial com desconto', cta: 'Aproveitar', hue: 14, image: images?.banners?.[0] },\n { type: 'products', title: 'Novidades no cardápio', filter: 'new', limit: 4 },\n {\n type: 'testimonials',\n title: 'O que dizem por aí',\n items: [\n { quote: 'Chegou quentinho e absurdo de bom. Virei cliente!', author: 'Rafael M.' },\n { quote: 'Sabor de restaurante em casa, sem complicação.', author: 'Beatriz L.' },\n { quote: 'Entrega rápida e porção generosa. Recomendo demais.', author: 'Diego S.' },\n ],\n },\n { type: 'newsletter', title: 'Receba nossas ofertas', subtitle: 'Promoções e novidades do cardápio, direto no seu e-mail.' },\n ],\n }),\n}\n\nexport const storefrontTemplates = {\n mare: mareTemplate,\n sertao: sertaoTemplate,\n volt: voltTemplate,\n atelier: atelierTemplate,\n food: foodTemplate,\n} as const\n\nexport type StorefrontTemplateId = keyof typeof storefrontTemplates\n","import React from 'react'\nimport type { StorefrontBlockLike } from '../blocks/page-blocks'\nimport { StorefrontPage } from './StorefrontPage'\n\n// Kept as the public shorthand for \"render this list of sections as a page\".\n// Several stores import it directly for their own routes, so it stays — but it\n// now delegates to StorefrontPage rather than rendering a tree of its own.\n// Two page renderers would drift, and the one that drifted would be this one:\n// it would silently miss page context, the diagnostics and (from Fase 3) slots.\nexport function StorefrontSections({ sections }: { sections: readonly StorefrontBlockLike[] }) {\n return <StorefrontPage kind=\"home\" page={{ blocks: sections }} />\n}\n\nexport function HomePage({ sections }: { sections: readonly StorefrontBlockLike[] }) {\n return <StorefrontSections sections={sections} />\n}\n","// Factory\nexport {\n createStorefront,\n createStorefrontApp,\n initStorefrontRuntime,\n registerStorefrontEntities,\n resolveStorefrontProvider,\n StorefrontShell,\n} from './app/createStorefrontApp'\nexport type { CreateStorefrontOptions, StorefrontShellProps } from './app/createStorefrontApp'\nexport {\n defineStorefrontConfig,\n defineStorefrontComponents,\n defineStorefrontRoutes,\n defineStorefrontSections,\n defineStorefrontApp,\n} from './app/define'\nexport type {\n StorefrontConfig,\n ResolvedStorefrontConfig,\n StorefrontRouteComponentProps,\n StorefrontRouteChrome,\n StorefrontCommerceMode,\n StorefrontImageLoadingConfig,\n StorefrontImageLoadingMode,\n StorefrontRouteDefinition,\n StorefrontRouteKind,\n StorefrontRouteParams,\n StorefrontEnquiryConfig,\n StorefrontSearchConfig,\n} from './document/config'\nexport type {\n StorefrontActions,\n StorefrontComponents,\n ProductCardProps,\n ProductCardImageOrder,\n ProductDetailProps,\n ProductGalleryProps,\n ProductGalleryOrder,\n ProductPriceProps,\n ProductActionsProps,\n ProductEnquiryFormContractProps,\n CategoryCardProps,\n CollectionSectionProps,\n HeroSectionContractProps,\n MediaCarouselProps as MediaCarouselContractProps,\n ProductSliderProps as ProductSliderContractProps,\n StorefrontChromeProps,\n StorefrontStateProps,\n} from './extend/component-contracts'\nexport { useStorefrontConfig, useStorefrontConfigOptional } from './document/config'\n// The config seam. `createStorefront` wires these internally; exporting them is\n// what lets a page or a block be rendered outside it — by a store with fully\n// custom routing, by the visual editor's preview, and by a test. Its absence is\n// the reason this package had no tests.\nexport { resolveConfig, StorefrontConfigProvider } from './document/config'\n// The merchant's saved policy, overlaid on the declared config. `applyStoreSettings`\n// is exported for its own sake: it decides what a shopper is offered, and a\n// bespoke storefront that builds its own provider tree needs the same merge.\nexport { StorefrontConfigHost, applyStoreSettings } from './document/store-policy'\n\n// Manifest path (renderApp(defineStorefront(config)) / storefront scaffold)\nexport { defineStorefront, StorefrontScaffold } from './app/scaffold'\n\n// Store Document v1 (spine M1): serialize / validate / describe / hydrate.\n// The handle registry itself lives in @fayz-ai/core (registerHandle et al) and\n// is re-exported here so storefront apps depend on one package.\nexport {\n exportStore,\n hydrateStoreDocument,\n slugifyStoreName,\n STORE_DOCUMENT_KIND,\n} from './document/round-trip'\nexport type { ExportStoreOptions, HydrateStoreOptions } from './document/round-trip'\nexport {\n STORE_SECTIONS,\n STORE_SECTION_NAMES,\n sectionToJsonSchema,\n STORE_COMMERCE_MODES,\n STORE_PAYMENT_MODES,\n STORE_PAYMENT_METHOD_KINDS,\n STORE_BACKEND_PROVIDERS,\n STORE_ROUTE_KINDS,\n STORE_ROUTE_CHROMES,\n} from './document/sections'\nexport type {\n StoreDocument,\n StoreSectionName,\n StoreIdentitySection,\n StoreThemeSection,\n StoreCommerceSection,\n StorePresentationSection,\n StoreContentSection,\n StoreCatalogSection,\n StoreBackendSection,\n StoreAuthSection,\n StoreCodeSection,\n StoreCodeRouteRef,\n StoreFieldSpec,\n StoreFieldDeprecation,\n StoreSectionSpec,\n} from './document/sections'\nexport { validateStore, STOREFRONT_PAGE_KINDS } from './document/validate'\nexport type { StoreValidationReport, StoreValidationError } from './document/validate'\nexport { describeStore } from './document/describe'\nexport type {\n StoreDescription,\n StoreAbilityDescriptor,\n StoreCapabilities,\n StoreSectionDescription,\n StoreDocumentSummary,\n StoreContractDescription,\n} from './document/describe'\n// The M10 contract: what is deprecated in this store, and the codemods keyed\n// to document version that retire it. `fayz upgrade` drives these.\nexport {\n upgradeStore,\n scanStoreDeprecations,\n unobservableDeprecations,\n describeCodemods,\n STORE_CODEMOD_IDS,\n} from './document/upgrade'\nexport type {\n StoreUpgradeResult,\n StoreUpgradeOptions,\n StoreCodemodResult,\n StoreCodemodStatus,\n StoreCodemodRefusal,\n StoreCodemodDescriptor,\n StoreCodemodVersionKey,\n StoreDeprecationFinding,\n} from './document/upgrade'\n// applyChange — the fourth ability (spine M8). `renderStore` is the third and\n// lives on the ./render subpath, because it imports react-dom/server.\nexport {\n applyChange,\n parseStorePath,\n STORE_CHANGE_OPS,\n DEFAULT_WRITABLE_SECTIONS,\n} from './document/change'\nexport type {\n StoreChange,\n StoreChangeOp,\n StoreChangeResult,\n AppliedStoreChange,\n ApplyChangeOptions,\n} from './document/change'\nexport { STOREFRONT_COMPONENT_KEYS } from './extend/component-contracts'\nexport {\n registerHandle,\n resolveHandle,\n getHandle,\n hasHandle,\n listHandles,\n handleNameFor,\n} from '@fayz-ai/core'\n\n// Block system (storefront sections as registry blocks)\nexport { registerStorefrontBlocks, sectionsToBlocks } from './blocks/registry'\n\n// Loaders — declared reads through the ShopProvider port (M3, I11)\nexport { registerStorefrontLoaders } from './data/loaders'\nexport type {\n StorefrontLoaderContext,\n ProductsListParams,\n ProductBySlugParams,\n ProductsSort,\n EntityListParams,\n EntityBySlugParams,\n} from './data/loaders'\n\n// Page data — needs collected from the block tree, resolved once per page\nexport {\n PageDataScope,\n useLoader,\n useBlockData,\n BlockDataError,\n collectDataNeeds,\n resolveDataParams,\n resolvePageData,\n resolvePageDataNeed,\n} from './blocks/page-data'\nexport type {\n PageDataEntry,\n PageDataNeed,\n PageDataStatus,\n PageDataScopeProps,\n UseLoaderResult,\n} from './blocks/page-data'\n\n// The static-render seam renderStore drives the live components through (M8).\nexport { currentStaticRenderPass, withStaticRenderPass } from './app/static-render'\nexport type { StaticRenderPass, StaticHeadInput } from './app/static-render'\n\n// Pages as block trees (compose any route, not just the home)\nexport {\n toBlockNodes,\n defaultPageBlocks,\n checkPageBlocks,\n matchContentPage,\n contentPagePath,\n routePathParams,\n mergePageTheme,\n pageThemeSelector,\n CATALOG_BODY_BLOCK,\n PRODUCT_BODY_BLOCK,\n} from './blocks/page-blocks'\nexport type {\n StorefrontBlockRef,\n StorefrontBlockLike,\n StorefrontPageConfig,\n StorefrontContentPageConfig,\n ContentPageMatch,\n StorefrontPagesConfig,\n StorefrontPageKind,\n PageBlockDiagnostic,\n} from './blocks/page-blocks'\nexport {\n StorefrontPage,\n useStorefrontPage,\n useStorefrontPageOptional,\n resetPageDiagnostics,\n} from './views/StorefrontPage'\nexport type { StorefrontPageProps, StorefrontPageContextValue } from './views/StorefrontPage'\n\n// Partial overrides (adjust a component's props without adopting the component)\nexport { resolveOverride, overrideComponent, overrideProps } from './extend/component-override'\nexport type { ComponentOverride, ResolvedOverride } from './extend/component-override'\n\n// Named slots (graft blocks into an SDK page without owning the page)\nexport { Slot, useSlotContext, listSlots, usedSlots, STOREFRONT_SLOTS } from './extend/slots'\nexport type {\n StorefrontSlots,\n StorefrontSlotArea,\n StorefrontSlotContextMap,\n SlotDescriptor,\n SlotProps,\n ListSlotsOptions,\n} from './extend/slots'\n\n// Routing\nexport { Link, navigateTo, useHashPath, matchPath } from './app/router'\nexport type { LinkProps } from './app/router'\n\n// Stores\nexport {\n useCartStore,\n selectCount,\n selectSubtotal,\n selectDiscountTotal,\n selectShipping,\n selectTotal,\n} from './stores/cart.store'\nexport type { CartLine, CartState } from './stores/cart.store'\nexport { useSessionStore } from './stores/session.store'\nexport type { SessionState } from './stores/session.store'\nexport {\n signInByEmail,\n signUpCustomer,\n establishCustomerSession,\n signOutCustomer,\n getCustomerAuthAdapter,\n resolveAuthAdapter,\n EmailConfirmationRequiredError,\n} from './data/auth'\nexport type { StorefrontAuthAdapter, StorefrontAuthConfig, EstablishSessionOptions } from './data/auth'\nexport { useCatalogStore } from './stores/catalog.store'\nexport type { CatalogState, CatalogSort } from './stores/catalog.store'\n// Metadata refinements — one matcher, shared by the catalogue page, the rails\n// and the server-side loader.\nexport { matchesFacets, withFacet, mergeCollectionFacet, toFacetMap } from './data/facets'\nexport type { CatalogFacets, CatalogFacetEntry } from './data/facets'\n\n// Hooks\nexport {\n useProducts,\n useProduct,\n useCategories,\n useCatalog,\n useStorefront,\n useStorefrontActions,\n useStorefrontHead,\n useRegion,\n usePolicies,\n useCart,\n useCheckout,\n useDiscountValidator,\n usePaymentMethods,\n useShipping,\n useAddress,\n useOrder,\n useMyOrders,\n useEnquiry,\n} from './hooks'\nexport type {\n StorefrontRegion,\n PolicyKind,\n StorefrontPolicy,\n UsePolicies,\n CheckoutTotals,\n CheckoutSubmission,\n UseCheckout,\n UsePaymentMethods,\n UseShipping,\n AddressLookupStatus,\n UseAddress,\n UseOrder,\n} from './hooks'\n\n// Components (for custom layouts)\nexport { StorefrontHeader } from './components/layout/StorefrontHeader'\nexport { SearchOverlay } from './components/layout/SearchOverlay'\nexport { SmoothImage } from './components/SmoothImage'\nexport type { SmoothImageProps } from './components/SmoothImage'\nexport { ProductCard, pickProductCardImage } from './components/product/ProductCard'\n// Exported precisely because it was NOT, and the one store that needed a\n// different image order had nothing to wrap — so it cloned all 158 lines.\nexport { ProductGallery, orderGalleryImages } from './components/product/ProductGallery'\nexport { ProductEnquiryForm } from './components/product/ProductEnquiryForm'\nexport type { ProductEnquiryFormProps } from './components/product/ProductEnquiryForm'\nexport { OrderTrackingTimeline } from './components/order/OrderTrackingTimeline'\nexport { ProductGrid } from './components/collection/ProductGrid'\nexport { FiltersPanel } from './components/collection/FiltersPanel'\nexport type { CatalogFacetConfig } from './components/collection/FiltersPanel'\nexport { CartDrawer } from './components/cart/CartDrawer'\nexport { Price } from './components/Price'\nexport { PaymentTerms, resolvePaymentTerms } from './components/PaymentTerms'\nexport type { PaymentTermsProps, ResolvedPaymentTerms } from './components/PaymentTerms'\nexport { ProductSpecs } from './components/product/ProductSpecs'\nexport { ProductReviews } from './components/product/ProductReviews'\nexport type { ProductReview, StorefrontReviewsConfig } from './components/product/ProductReviews'\nexport { QuantityInput } from './components/cart/QuantityInput'\nexport { ProductOptionSelector } from './components/product/ProductOptionSelector'\nexport type { ProductOptionSelectorProps } from './components/product/ProductOptionSelector'\nexport {\n getProductOptionGroups,\n normalizeProductOptionSelection,\n formatProductOptionSelection,\n productOptionSelectionKey,\n resolveVariantForSelection,\n selectionPrice,\n resetProductOptionsDeprecationWarnings,\n} from './data/product-options'\nexport type { ProductOptionGroup, ProductOptionSelection } from './data/product-options'\n\n// Extension points (spine M7) — the storefront's declared behaviour seams.\nexport {\n CART_LINE_ANNOTATION_POINT,\n ORDER_METADATA_POINT,\n PRODUCT_CARD_BADGE_POINT,\n CHECKOUT_FIELD_POINT,\n BEFORE_PLACE_ORDER_VALVE,\n registerStorefrontExtensionPoints,\n resetStorefrontExtensionPoints,\n getCartLineAnnotations,\n getProductCardBadges,\n getCheckoutFieldContributions,\n collectOrderMetadata,\n runBeforePlaceOrderValve,\n} from './extend/extension-points'\nexport type {\n CartLineAnnotationInput,\n CartLineAnnotation,\n OrderMetadataInput,\n ProductCardBadgeInput,\n ProductCardBadge,\n CheckoutFieldInput,\n CheckoutFieldContribution,\n BeforePlaceOrderContext,\n} from './extend/extension-points'\n\n// Pages (for custom routing)\nexport { ContentPage } from './views/ContentPage'\nexport type { ContentPageProps } from './views/ContentPage'\nexport { CatalogPage } from './views/CatalogPage'\nexport { ProductDetailPage } from './views/ProductDetailPage'\nexport { CheckoutPage } from './views/CheckoutPage'\nexport { OrderConfirmationPage } from './views/OrderConfirmationPage'\nexport { MyPurchasesPage } from './views/MyPurchasesPage'\nexport { placeStorefrontOrder } from './workflows/checkout'\nexport type {\n PlaceStorefrontOrderInput,\n PlaceStorefrontOrderResult,\n StorefrontCheckoutAddress,\n StorefrontCheckoutCustomer,\n} from './workflows/checkout'\n\n// Theming + templates\nexport { StorefrontThemeStyle, themeToCss, THEME_SCALE_FIELDS, THEME_SCALE_VAR_PREFIX } from './lib/theme'\nexport type {\n ThemeScaleField,\n StorefrontTheme,\n StorefrontThemeColors,\n StorefrontThemeFont,\n StorefrontRadius,\n HeaderVariant,\n HeroVariant,\n CardStyle,\n ThemeCssOptions,\n} from './lib/theme'\nexport {\n CollectionHero,\n ProductSpotlight,\n MotifStrip,\n CollectionCta,\n} from './components/marketing/CollectionSections'\nexport type {\n CollectionHeroProps,\n ProductSpotlightProps,\n MotifStripProps,\n CollectionCtaProps,\n} from './components/marketing/CollectionSections'\nexport type { StorefrontSection, HomeSection, HomeConfig, HeroSlide, MediaCarouselItem, NavLink, FooterConfig } from './blocks/sections'\nexport { bannerPlaceholder, productPlaceholder, PLACEHOLDER_ASPECTS } from './blocks/sections'\n// The editor seam: a storefront in an editor's iframe reports which DOCUMENT\n// NODE was clicked, not which DOM element.\nexport { connectEditorBridge, reportNavigation, blockAt, EDITOR_MESSAGES } from './extend/editor-bridge'\nexport type { EditorBridgeOptions, PickedBlock } from './extend/editor-bridge'\n// From a picked path to the settings schema that draws its form — the first\n// consumer of the block schemas I1 has been emitting since M1.\nexport { blockAtPath, settingChange } from './blocks/block-at-path'\n// The settings overlay: a merchant edit reaches a live store without a build,\n// and the repo keeps authority over what the store IS (G2 — hybrid).\nexport { applyOverlay, pruneOverlay, isSettingPath, OVERLAYABLE_SECTIONS } from './document/overlay'\nexport type { StoreOverlay, ApplyOverlayResult, OverlayRejection } from './document/overlay'\nexport type { BlockAtPath, BlockAtPathError } from './blocks/block-at-path'\nexport {\n storefrontTemplates,\n mareTemplate,\n sertaoTemplate,\n voltTemplate,\n atelierTemplate,\n foodTemplate,\n} from './document/presets'\nexport type { StorefrontTemplate, StorefrontTemplateId } from './document/presets'\n\n// Home sections (for custom compositions)\nexport { HomePage, StorefrontSections } from './views/HomePage'\nexport { HeroSection } from './components/marketing/HeroSection'\nexport { MediaCarousel } from './components/marketing/MediaCarousel'\nexport type { MediaCarouselProps } from './components/marketing/MediaCarousel'\nexport { CategoryShowcase } from './components/collection/CategoryShowcase'\nexport { ProductRail } from './components/product/ProductRail'\nexport { ProductSlider } from './components/product/ProductSlider'\nexport type { ProductSliderProps } from './components/product/ProductSlider'\nexport {\n BenefitsRow,\n PromoBanner,\n ManifestoBlock,\n Testimonials,\n NewsletterBand,\n} from './components/marketing/MiscSections'\nexport { FormBlock, buildEnquiryFromForm } from './components/marketing/FormBlock'\nexport type { FormBlockProps, FormBlockField, FormBlockFieldType } from './components/marketing/FormBlock'\nexport { EntityListBlock, entityListBlockMeta } from './components/marketing/EntityList'\nexport { SealsBand, StoryQuote, ImageTiles, FaqSection } from './components/marketing/EditorialSections'\nexport type { SealItem, StoryQuoteProps, ImageTile, ImageTilesProps, FaqItem } from './components/marketing/EditorialSections'\nexport { StepsSection, CountdownBand, TierCards, nextMilestone } from './components/marketing/ConversionSections'\nexport type { StepItem, CountdownMilestone, TierItem } from './components/marketing/ConversionSections'\nexport type { BenefitItem } from './components/marketing/MiscSections'\nexport { StorefrontFooter } from './components/layout/StorefrontFooter'\n\n// Motion (core animation primitives)\nexport { Reveal, useInView, useScrolled, usePopOnChange, prefersReducedMotion } from './lib/motion'\nexport type { RevealProps } from './lib/motion'\n\n// Utilities\nexport { formatMoney, roundCents } from './lib/format'\nexport { TID } from './lib/testids'\nexport {\n productCardComponentContract,\n storefrontComponentContracts,\n} from './extend/component-selectors'\nexport type {\n ProductCardComponentContract,\n ProductDetailComponentContract,\n} from './extend/component-selectors'\n\n// ---------------------------------------------------------------------------\n// Front-door re-exports: storefront apps depend on @fayz-ai/storefront alone.\n// Runtime helpers come from @fayz-ai/core; UI / shop catalog / shop provider\n// live on their own subpaths (./ui, ./catalog, ./shop) to keep module graphs\n// separate. Mirrors the @fayz-ai/admin front door.\n// ---------------------------------------------------------------------------\n// renderApp is wrapped (not re-exported) so the 'storefront' scaffold registers\n// on first render instead of at import time — keeps the barrel side-effect-free.\nimport { renderApp as coreRenderApp } from '@fayz-ai/core'\nimport { registerStorefrontScaffold } from './app/scaffold'\n\nexport const renderApp: typeof coreRenderApp = (...args) => {\n registerStorefrontScaffold()\n return coreRenderApp(...args)\n}\n\nexport { getSupabaseClientOptional } from '@fayz-ai/core'\nexport { registerStorefrontScaffold } from './app/scaffold'\n\n// SSR hydration: the wire that carries server-resolved data into the browser.\nexport { serializePageData, readHydratedPageData, hydratedEntriesFor, PAGE_DATA_SCRIPT_ID } from './app/hydration'\nexport type { HydrationPayload } from './app/hydration'\n\n// Serving: which paths exist, and which of them a shared cache may hold.\nexport { isPublicPath, isKnownPath, resolveStorefrontRoute, storefrontPaths } from './app/serving'\nexport type { StorefrontRouteMatch } from './app/serving'\n\n// SEO descriptors — what a route tells a crawler about itself.\nexport { productSeo, pageSeo, productJsonLd, primaryImageUrl } from './lib/seo'\nexport type { StorefrontSeoContext } from './lib/seo'\n\n// Diagnostics: one rule set for a dev toolbar, a CI check and a prerender\n// validator, so a page cannot be graded three different ways.\nexport { auditStorefrontSeo, collectSeoAuditInput } from './diagnostics/seo-audit'\nexport type { SeoAuditInput, SeoAuditResult, SeoFinding, SeoFindingStatus } from './diagnostics/seo-audit'\n\n// Routing — the addressing scheme is injected, not assumed. See ./app/router.\nexport {\n useRoutePath,\n useNavigate,\n useRouterAdapter,\n useScrollToTopOnNavigate,\n shellRouterAdapter,\n StorefrontRouterProvider,\n} from './app/router'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/app/define.ts","../src/app/scaffold.tsx","../src/document/upgrade.ts","../src/document/change.ts","../src/document/describe.ts","../src/hooks/use-catalog.ts","../src/hooks/use-storefront.ts","../src/hooks/use-region.ts","../src/hooks/use-policies.ts","../src/hooks/use-cart.ts","../src/hooks/use-checkout.ts","../src/hooks/use-payment-methods.ts","../src/hooks/use-shipping.ts","../src/hooks/use-address.ts","../src/hooks/use-order.ts","../src/extend/editor-bridge.ts","../src/blocks/block-at-path.ts","../src/document/overlay.ts","../src/document/presets.ts","../src/views/HomePage.tsx","../src/index.ts"],"names":["React","here","position","clone","sectionOf","before","to","listDeprecations","isRecord","describeBlocks","result","jsx","coreRenderApp"],"mappings":";;;;;;;;;;;;AAeO,SAAS,uBAAyD,MAAA,EAAc;AACrF,EAAA,OAAO,MAAA;AACT;AAEO,SAAS,2BAAiE,UAAA,EAAkB;AACjG,EAAA,OAAO,UAAA;AACT;AAEO,SAAS,uBAA6E,MAAA,EAAc;AACzG,EAAA,OAAO,MAAA;AACT;AAEO,SAAS,yBAAuE,QAAA,EAAgB;AACrG,EAAA,OAAO,QAAA;AACT;AAEO,SAAS,oBAA6D,OAAA,EAAe;AAC1F,EAAA,OAAO,OAAA;AACT;ACNO,SAAS,iBAAiB,MAAA,EAAuC;AACtE,EAAA,MAAM,EAAA,GAAK,gBAAA,CAAiB,MAAA,CAAO,IAAI,CAAA;AAKvC,EAAA,MAAM,QAAA,GAAW,YAAY,MAAA,EAAQ,EAAE,OAAO,EAAA,EAAI,sBAAA,EAAwB,MAAM,CAAA;AAChF,EAAA,MAAM,kBAAmB,MAAA,CAAO,OAAA,EAAS,QAAA,KAAa,MAAA,CAAO,WAAW,QAAA,GAAW,MAAA,CAAA;AAEnF,EAAA,OAAO,SAAA,CAAU;AAAA,IACf,EAAA;AAAA,IACA,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,OAAA,EAAS;AAAA,MACP,QAAA,EAAU,eAAA;AAAA,MACV,GAAA,EAAK,OAAO,OAAA,EAAS;AAAA,KACvB;AAAA,IACA,MAAA,EAAQ;AAAA,MACN,OAAA,EAAS,OAAO,MAAA,IAAU,OAAA;AAAA,MAC1B,SAAA,EAAW,CAAC,MAAA,CAAO,MAAA,IAAU,OAAO,CAAA;AAAA,MACpC,QAAA,EAAU,OAAO,QAAA,IAAY;AAAA,KAC/B;AAAA,IACA,OAAO,MAAA,CAAO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AE,KAAA,EAAO,8DAAA,EAAuD,MAAA,EAAQ,UAAA;AAAW;AACrF,OACF;AAAA,MACA,EAAE,IAAA,EAAM,YAAA,EAAc,KAAA,EAAO,uBAAA,EAAyB,UAAU,mEAAA;AAA2D;AAC7H,GACF;AACF;AAEO,IAAM,mBAAA,GAAsB;AAAA,EACjC,IAAA,EAAM,YAAA;AAAA,EACN,MAAA,EAAQ,cAAA;AAAA,EACR,IAAA,EAAM,YAAA;AAAA,EACN,OAAA,EAAS,eAAA;AAAA,EACT,IAAA,EAAM;AACR;ACxTO,SAAS,kBAAA,CAAmB,EAAE,QAAA,EAAS,EAAiD;AAC7F,EAAA,uBAAOC,IAAC,cAAA,EAAA,EAAe,IAAA,EAAK,QAAO,IAAA,EAAM,EAAE,MAAA,EAAQ,QAAA,EAAS,EAAG,CAAA;AACjE;AAEO,SAAS,QAAA,CAAS,EAAE,QAAA,EAAS,EAAiD;AACnF,EAAA,uBAAOA,GAAAA,CAAC,kBAAA,EAAA,EAAmB,QAAA,EAAoB,CAAA;AACjD;AC0dO,IAAM,SAAA,GAAkC,IAAI,IAAA,KAAS;AAC1D,EAAA,0BAAA,EAA2B;AAC3B,EAAA,OAAOC,WAAA,CAAc,GAAG,IAAI,CAAA;AAC9B","file":"index.js","sourcesContent":["import type {\n StorefrontConfig,\n StorefrontRouteDefinition,\n} from '../document/config'\nimport type { StorefrontComponents } from '../extend/component-contracts'\nimport type { StorefrontSection } from '../blocks/sections'\nimport type { CreateStorefrontOptions } from './createStorefrontApp'\n\n/**\n * Identity helpers for generated/custom storefronts.\n *\n * They do not add runtime behavior; they make the intended client-app shape\n * explicit and keep TypeScript inference tight across config, components, routes,\n * sections and app creation options.\n */\nexport function defineStorefrontConfig<const T extends StorefrontConfig>(config: T): T {\n return config\n}\n\nexport function defineStorefrontComponents<const T extends StorefrontComponents>(components: T): T {\n return components\n}\n\nexport function defineStorefrontRoutes<const T extends readonly StorefrontRouteDefinition[]>(routes: T): T {\n return routes\n}\n\nexport function defineStorefrontSections<const T extends readonly StorefrontSection[]>(sections: T): T {\n return sections\n}\n\nexport function defineStorefrontApp<const T extends CreateStorefrontOptions>(options: T): T {\n return options\n}\n","import React from 'react'\nimport { registerScaffold, defineApp } from '@fayz-ai/core'\nimport type { AppManifest, BackendProvider } from '@fayz-ai/core'\nimport { StorefrontConfigProvider, resolveConfig } from '../document/config'\nimport { StorefrontConfigHost } from '../document/store-policy'\nimport type { StorefrontConfig } from '../document/config'\nimport type { StorefrontTheme } from '../lib/theme'\nimport type { HomeConfig, NavLink, FooterConfig } from '../blocks/sections'\nimport { initStorefrontRuntime, StorefrontShell } from './createStorefrontApp'\nimport { exportStore, hydrateStoreDocument, slugifyStoreName } from '../document/round-trip'\nimport '../blocks/registry' // ensure section blocks are registered\n\ntype StorefrontBackendProvider = NonNullable<StorefrontConfig['backend']>['provider']\n\n// ---------------------------------------------------------------------------\n// Storefront scaffold — renders a store from a pure-data AppManifest.\n//\n// The storefront surface carries its full declarative form as a Store Document\n// (surface.options.document, see store-document.ts): every serializable config\n// field lives in a document section, and code-valued fields (components,\n// routes, provider, adapters, JSX) are referenced by registered handle NAME.\n// The in-memory config Map this file used to keep is gone — a document plus\n// the handle registry reconstitutes the store in any session, which is what\n// makes export/diff/edit by an agent possible at all (spine §3 L0).\n// ---------------------------------------------------------------------------\n\n/** StorefrontConfig → AppManifest (the sugar-to-data direction). */\nexport function defineStorefront(config: StorefrontConfig): AppManifest {\n const id = slugifyStoreName(config.name)\n // Serialize the whole config into the document, auto-registering handles\n // (`<id>.<path>`) for code values the app did not name itself. Explicitly\n // registered handles win the reverse lookup, so a store that calls\n // registerHandle keeps its own names in the document.\n const document = exportStore(config, { appId: id, registerMissingHandles: true })\n const backendProvider = (config.backend?.provider ?? (config.provider ? 'custom' : 'mock')) as BackendProvider\n\n return defineApp({\n id,\n name: config.name,\n backend: {\n provider: backendProvider,\n url: config.backend?.url,\n },\n locale: {\n default: config.locale ?? 'pt-BR',\n supported: [config.locale ?? 'pt-BR'],\n currency: config.currency ?? 'BRL',\n },\n theme: config.theme as Record<string, unknown> | undefined,\n surfaces: {\n storefront: {\n scaffold: 'storefront',\n options: { document: document as unknown as Record<string, unknown> },\n },\n },\n })\n}\n\n/**\n * AppManifest → StorefrontConfig (the data-to-render direction).\n *\n * New manifests carry a Store Document; hydration resolves code by handle\n * name. `onError: 'report'` deliberately: this is the shopper path, and a\n * stale document must degrade loudly in the console rather than white-screen\n * the store (I7). The authoring loop gets the hard errors from\n * validateStore / `fayz validate` instead.\n *\n * Legacy manifests (committed before the document existed) carry flat surface\n * options; they map best-effort, without the code-valued fields — which is\n * exactly what they carried across sessions before, since the old in-memory\n * Map only worked inside the session that authored it.\n */\nfunction manifestToStorefrontConfig(manifest: AppManifest, surfaceName: string): StorefrontConfig {\n const surface = manifest.surfaces[surfaceName]\n const o = (surface?.options ?? {}) as Record<string, unknown>\n\n if (o.document && typeof o.document === 'object') {\n return hydrateStoreDocument(o.document as Record<string, unknown>, { onError: 'report' })\n }\n\n return {\n name: manifest.name,\n currency: (manifest.locale as { currency?: string } | undefined)?.currency,\n locale: (manifest.locale as { default?: string } | undefined)?.default,\n theme: manifest.theme as StorefrontTheme | undefined,\n announcement: o.announcement as string | undefined,\n home: o.home as HomeConfig | undefined,\n pages: o.pages as StorefrontConfig['pages'],\n nav: o.nav as NavLink[] | undefined,\n footer: o.footer as FooterConfig | undefined,\n shipping: o.shipping as StorefrontConfig['shipping'],\n features: o.features as StorefrontConfig['features'],\n catalog: o.catalog as StorefrontConfig['catalog'],\n backend: {\n provider: manifest.backend?.provider as StorefrontBackendProvider,\n url: manifest.backend?.url,\n },\n }\n}\n\nexport function StorefrontScaffold({ manifest, surface }: { manifest: AppManifest; surface: string }) {\n const config = React.useMemo(() => manifestToStorefrontConfig(manifest, surface), [manifest, surface])\n const resolved = React.useMemo(() => resolveConfig(config), [config])\n const inited = React.useRef(false)\n if (!inited.current) {\n initStorefrontRuntime(config)\n inited.current = true\n }\n return (\n <StorefrontConfigHost config={resolved}>\n <StorefrontShell />\n </StorefrontConfigHost>\n )\n}\nStorefrontScaffold.displayName = 'StorefrontScaffold'\n\n// Registration is lazy (called from the storefront renderApp wrapper and\n// createStorefront*) so that importing the @fayz-ai/storefront barrel stays\n// side-effect-free and tree-shakable.\nlet storefrontScaffoldRegistered = false\nexport function registerStorefrontScaffold(): void {\n if (storefrontScaffoldRegistered) return\n storefrontScaffoldRegistered = true\n registerScaffold('storefront', StorefrontScaffold, { source: 'sdk', label: 'Storefront' })\n}\n","import { getDeprecation, listDeprecations } from '@fayz-ai/sdk/deprecations'\nimport type { FayzDeprecation } from '@fayz-ai/sdk/deprecations'\nimport { storefrontDiscountToPromotion } from '@fayz-ai/shop/rules'\nimport type { Promotion } from '@fayz-ai/shop/rules'\nimport { STORE_SECTIONS, isRecord } from './sections'\nimport type { StoreDocument, StoreSectionName } from './sections'\nimport { validateStore } from './validate'\nimport type { StoreValidationReport } from './validate'\n\n// ---------------------------------------------------------------------------\n// `fayz upgrade` — codemods keyed to document version (spine M10).\n//\n// The store document already carries a per-SECTION version, following\n// WooCommerce Blueprint's `get_schema(int $version)`. M10 makes that number\n// mean something operational: a codemod declares the section and the exact\n// version it moves FROM and TO, so \"has this store been migrated\" is a lookup\n// rather than a judgement, and one SDK serves a migrated and an unmigrated\n// fleet at the same time. A deprecated field is accepted below the version\n// that retires it and is a hard validation error at or above it — the shim and\n// the removal are the same declaration, read from two sides.\n//\n// THE REFUSAL RULE, which is the whole reason this is trustworthy: a codemod\n// that cannot be safe does not do its best. It refuses, names the decision a\n// human must make, and leaves the document byte-identical. Guessing here would\n// be worse than not having the command, because the failure lands in a store's\n// checkout and nobody would know which run caused it.\n//\n// Every function in this module is PURE. Reading and writing files is the\n// CLI's job; this half has to stay testable and has to be callable from the\n// author loop next to describeStore / validateStore / applyChange.\n// ---------------------------------------------------------------------------\n\n/** One deprecated thing found in one store. */\nexport interface StoreDeprecationFinding {\n /** Registry row id. */\n id: string\n /** Dotted document path, when the deprecation is on the document surface. */\n path?: string\n /** What exactly was found, in the author's words. */\n detail: string\n deprecatedIn: string\n removeIn: string\n /** I2 — always present, always the thing to write instead. */\n replacement: string\n /** The codemod that answers it. */\n codemod: string\n /** False when only a human can retire it (pool state, code outside the document). */\n automatable: boolean\n}\n\n/** Why a codemod would not run, and what a human has to decide instead. */\nexport interface StoreCodemodRefusal {\n reason: string\n /** The decisions, one per line. Never a suggestion the codemod could have\n * taken itself — if it could, it would have. */\n decide: string[]\n}\n\nexport type StoreCodemodStatus =\n /** The document changed (possibly only its section version). */\n | 'applied'\n /** Nothing here to migrate: the section is absent, or already past this version. */\n | 'not-applicable'\n /** Something is here, and moving it safely needs a human. */\n | 'refused'\n\n/** A section version move — the key the codemod is filed under. */\nexport interface StoreCodemodVersionKey {\n section: StoreSectionName\n from: number\n to: number\n}\n\nexport interface StoreCodemodResult {\n codemod: string\n status: StoreCodemodStatus\n /** Registry ids this codemod retires. */\n deprecations: string[]\n /** The version move, or null for a deprecation that is not on the document\n * surface at all — which is itself why such a codemod always refuses. */\n version: StoreCodemodVersionKey | null\n /** One line per document change, in the applyChange path vocabulary. */\n changes: string[]\n note: string\n refusal?: StoreCodemodRefusal\n}\n\nexport interface StoreUpgradeOptions {\n /** Restrict the run to these codemod ids. Unknown ids are a hard error\n * naming the valid set (I2). */\n only?: readonly string[]\n}\n\nexport interface StoreUpgradeResult {\n /** False when a codemod refused or the result would not validate. */\n ok: boolean\n /** The upgraded document. Deep-equal to the input when `changed` is false. */\n doc: StoreDocument\n changed: boolean\n deprecations: StoreDeprecationFinding[]\n codemods: StoreCodemodResult[]\n /** The result validated. A codemod that would break the document is a bug\n * in the codemod, and this is where it surfaces. */\n validation: StoreValidationReport\n}\n\n// --- Detection ----------------------------------------------------------------\n\nfunction sectionOf(doc: Record<string, unknown>, name: string): Record<string, unknown> | null {\n const value = doc[name]\n return isRecord(value) ? value : null\n}\n\nfunction sectionVersion(doc: Record<string, unknown>, name: StoreSectionName): number | null {\n const section = sectionOf(doc, name)\n if (!section) return null\n return typeof section.version === 'number' ? section.version : null\n}\n\nfunction finding(row: FayzDeprecation, detail: string, path: string | undefined, automatable: boolean): StoreDeprecationFinding {\n return {\n id: row.id,\n path,\n detail,\n deprecatedIn: row.deprecatedIn,\n removeIn: row.removeIn,\n replacement: row.replacement,\n codemod: row.codemod,\n automatable,\n }\n}\n\n/**\n * What in THIS document is deprecated — the machine-readable answer to the\n * question I10 exists to make askable.\n *\n * Only the document surface is visible from here. A deprecation living in the\n * store's own code (the productMetadata overlay) or in a pool (the two SQL\n * ones) is reported by its row as un-automatable rather than omitted: an\n * enumerable deprecation that quietly drops the ones you cannot see from a\n * JSON file would be the silent-failure mode the whole spine is against.\n */\nexport function scanStoreDeprecations(input: StoreDocument | Record<string, unknown>): StoreDeprecationFinding[] {\n const doc = input as Record<string, unknown>\n const found: StoreDeprecationFinding[] = []\n\n for (const row of listDeprecations()) {\n if (row.surface !== 'document-field') continue\n\n if (row.id === 'storefront.commerce.discounts') {\n const commerce = sectionOf(doc, 'commerce')\n const discounts = commerce?.discounts\n if (Array.isArray(discounts) && discounts.length > 0) {\n const codes = discounts\n .map((entry) => (isRecord(entry) && typeof entry.code === 'string' ? entry.code : '?'))\n .join(', ')\n found.push(\n finding(row, `${discounts.length} legacy coupon code(s): ${codes}`, 'commerce.discounts', true),\n )\n }\n continue\n }\n\n if (row.id === 'storefront.backend.supabaseUrl' || row.id === 'storefront.backend.supabaseAnonKey') {\n const field = row.id === 'storefront.backend.supabaseUrl' ? 'supabaseUrl' : 'supabaseAnonKey'\n const backend = sectionOf(doc, 'backend')\n if (backend && typeof backend[field] === 'string') {\n found.push(finding(row, `legacy backend.${field} is set`, `backend.${field}`, true))\n }\n continue\n }\n }\n\n return found\n}\n\n/**\n * The deprecations no document can answer for, with the reason.\n *\n * The CLI merges these into its report so `fayz upgrade` never implies a store\n * is clean when the only reason it looks clean is that the evidence is not in\n * the repo.\n */\nexport function unobservableDeprecations(): StoreDeprecationFinding[] {\n return listDeprecations()\n .filter((row) => row.surface !== 'document-field')\n .map((row) => finding(row, row.detect, undefined, false))\n}\n\n// --- The codemods -------------------------------------------------------------\n\ninterface Codemod {\n id: string\n title: string\n version: StoreCodemodVersionKey | null\n run(doc: Record<string, unknown>): StoreCodemodResult\n}\n\nfunction result(\n mod: Pick<Codemod, 'id' | 'version'>,\n status: StoreCodemodStatus,\n note: string,\n extra: Partial<StoreCodemodResult> = {},\n): StoreCodemodResult {\n return {\n codemod: mod.id,\n status,\n deprecations: listDeprecations().filter((row) => row.codemod === mod.id).map((row) => row.id),\n version: mod.version,\n changes: [],\n note,\n ...extra,\n }\n}\n\n/** Deep clone through JSON — the document is JSON by construction (exportStore\n * refuses anything else), so this cannot lose a value. */\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nconst PERCENT_CODE_KEYS = new Set(['code', 'percent', 'title'])\n\n/**\n * commerce.discounts → promotions.promotions (commerce v1 → v2).\n *\n * Safe because the translation is not invented here: it is\n * `storefrontDiscountToPromotion`, the SAME function the runtime shim already\n * routes every legacy code through. The money after the codemod is the money\n * before it, by construction rather than by review.\n */\nconst discountsToPromotions: Codemod = {\n id: 'commerce.discounts-to-promotions',\n title: 'Legacy percent coupon codes become rule-engine promotions',\n version: { section: 'commerce', from: 1, to: 2 },\n run(doc) {\n const mod = discountsToPromotions\n const version = sectionVersion(doc, 'commerce')\n if (version === null) return result(mod, 'not-applicable', 'no commerce section')\n if (version !== 1) return result(mod, 'not-applicable', `commerce is already at version ${version}`)\n\n const commerce = sectionOf(doc, 'commerce')!\n const raw = commerce.discounts\n const entries = Array.isArray(raw) ? raw : []\n\n // --- refuse before touching anything -------------------------------------\n const decide: string[] = []\n\n for (const [index, entry] of entries.entries()) {\n const at = `commerce.discounts[${index}]`\n if (!isRecord(entry)) {\n decide.push(`${at} is not an object — rewrite it as {code, percent, title?} or delete it.`)\n continue\n }\n const unknown = Object.keys(entry).filter((key) => !PERCENT_CODE_KEYS.has(key))\n if (unknown.length > 0) {\n decide.push(\n `${at} carries ${unknown.join(', ')}, which {code, percent, title?} has no meaning for — ` +\n 'say what those should become as promotion rules, or delete them.',\n )\n }\n if (typeof entry.code !== 'string' || entry.code.trim() === '') {\n decide.push(`${at}.code is missing — a coupon with no code cannot become a code-gated promotion.`)\n }\n if (typeof entry.percent !== 'number' || !Number.isFinite(entry.percent) || entry.percent <= 0 || entry.percent > 100) {\n decide.push(\n `${at}.percent is ${JSON.stringify(entry.percent)} — outside (0, 100], so the intended discount is not derivable.`,\n )\n }\n }\n\n const codeOf = (entry: unknown): string | null =>\n isRecord(entry) && typeof entry.code === 'string' ? entry.code.trim().toUpperCase() : null\n\n // Already a promotion under the same code: two live definitions of one\n // coupon, and only a human knows which is the real one.\n const promotionsSection = sectionOf(doc, 'promotions')\n const existing = Array.isArray(promotionsSection?.promotions) ? (promotionsSection!.promotions as unknown[]) : []\n for (const entry of entries) {\n const code = codeOf(entry)\n if (!code) continue\n const clash = existing.find((promo) => isRecord(promo) && typeof promo.code === 'string' && promo.code.trim().toUpperCase() === code)\n if (clash) {\n decide.push(\n `${code} is already declared in promotions.promotions (${isRecord(clash) ? String(clash.id ?? 'no id') : '?'}) ` +\n 'as well as in commerce.discounts — delete whichever of the two is not the live offer.',\n )\n }\n }\n\n // The catalog seed carries the same code. Today buildMockSeed SUPPRESSES\n // the seed row because the config code wins; migrating the config code out\n // of `discounts` removes that suppression and the seed row comes back as a\n // second promotion with the same code. Found by reading buildMockSeed, not\n // by reasoning about it.\n const catalog = sectionOf(doc, 'catalog')\n const seeded = Array.isArray(catalog?.discounts) ? (catalog!.discounts as unknown[]) : []\n for (const entry of entries) {\n const code = codeOf(entry)\n if (!code) continue\n if (seeded.some((seed) => codeOf(seed) === code)) {\n decide.push(\n `${code} is declared in BOTH commerce.discounts and catalog.discounts. The config copy currently ` +\n 'suppresses the catalog seed; once it becomes a promotion that suppression stops and the code ' +\n 'would apply twice. Delete whichever of the two is not the real offer, then re-run.',\n )\n }\n }\n\n if (decide.length > 0) {\n return result(mod, 'refused', `${entries.length} legacy code(s) present`, {\n refusal: {\n reason: 'the legacy codes cannot be translated without a decision this command must not make',\n decide,\n },\n })\n }\n\n // --- apply ---------------------------------------------------------------\n const changes: string[] = []\n if (entries.length > 0) {\n const migrated: Promotion[] = entries.map((entry) => {\n const record = entry as { code: string; percent: number; title?: string }\n return storefrontDiscountToPromotion(record)\n })\n const target = sectionOf(doc, 'promotions') ?? { version: STORE_SECTIONS.promotions.versions[0]! }\n const list = Array.isArray(target.promotions) ? [...(target.promotions as unknown[])] : []\n for (const promotion of migrated) {\n list.push(promotion as unknown as Record<string, unknown>)\n changes.push(`insert promotions.promotions[] ${promotion.code} (${promotion.applicationMethod.value}% off order)`)\n }\n target.promotions = list\n doc.promotions = target\n delete commerce.discounts\n changes.push(`remove commerce.discounts (${entries.length} entr${entries.length === 1 ? 'y' : 'ies'})`)\n }\n commerce.version = 2\n changes.push('set commerce.version 1 → 2')\n\n return result(\n mod,\n 'applied',\n entries.length === 0\n ? 'no legacy codes; version bump only, which records that this document is past the migration'\n : `${entries.length} legacy code(s) migrated onto the rule engine`,\n { changes },\n )\n },\n}\n\n/**\n * backend.supabaseUrl / backend.supabaseAnonKey → auth.supabase (backend v1 → v2).\n *\n * Not a pure relocation, and this is the interesting part. `resolveAuthAdapter`\n * reads `config.provider ?? config.adapter ?? (fallback?.supabaseUrl ? 'supabase' : 'mock')`\n * — so today the legacy field is ALSO what selects the supabase auth provider.\n * Move the credentials without saying anything about the provider and a store\n * with `auth` silent flips to mock auth: it would still build, still render,\n * and simply stop signing anybody in. So when the provider is not declared,\n * this refuses.\n */\nconst supabaseToAuth: Codemod = {\n id: 'backend.supabase-to-auth',\n title: 'Legacy supabase connection fields move under auth.supabase',\n version: { section: 'backend', from: 1, to: 2 },\n run(doc) {\n const mod = supabaseToAuth\n const version = sectionVersion(doc, 'backend')\n if (version === null) return result(mod, 'not-applicable', 'no backend section')\n if (version !== 1) return result(mod, 'not-applicable', `backend is already at version ${version}`)\n\n const backend = sectionOf(doc, 'backend')!\n const url = typeof backend.supabaseUrl === 'string' ? backend.supabaseUrl : undefined\n const anonKey = typeof backend.supabaseAnonKey === 'string' ? backend.supabaseAnonKey : undefined\n\n const auth = sectionOf(doc, 'auth')\n const authSupabase = auth && isRecord(auth.supabase) ? auth.supabase : null\n\n if (url !== undefined || anonKey !== undefined) {\n const decide: string[] = []\n const declaresProvider = Boolean(auth && (typeof auth.provider === 'string' || typeof auth.adapter === 'string'))\n if (!declaresProvider) {\n decide.push(\n \"declare auth.provider explicitly — 'supabase' to keep today's behaviour (the legacy field is what \" +\n \"currently selects it, via resolveAuthAdapter's `fallback?.supabaseUrl ? 'supabase' : 'mock'`), \" +\n \"or 'mock' if these credentials were vestigial. Moving them silently would flip the store to mock auth.\",\n )\n }\n if (authSupabase && typeof authSupabase.url === 'string' && url !== undefined && authSupabase.url !== url) {\n decide.push(`auth.supabase.url and backend.supabaseUrl disagree — say which project the store talks to.`)\n }\n if (\n authSupabase &&\n typeof authSupabase.anonKey === 'string' &&\n anonKey !== undefined &&\n authSupabase.anonKey !== anonKey\n ) {\n decide.push('auth.supabase.anonKey and backend.supabaseAnonKey disagree — say which key is current.')\n }\n if (decide.length > 0) {\n return result(mod, 'refused', 'legacy supabase fields are set', {\n refusal: { reason: 'moving the credentials would change who the store authenticates as', decide },\n })\n }\n }\n\n const changes: string[] = []\n if (url !== undefined || anonKey !== undefined) {\n const target = sectionOf(doc, 'auth') ?? { version: STORE_SECTIONS.auth.versions[0]! }\n const supabase = isRecord(target.supabase) ? { ...target.supabase } : {}\n if (url !== undefined) {\n supabase.url = url\n delete backend.supabaseUrl\n changes.push('move backend.supabaseUrl → auth.supabase.url')\n }\n if (anonKey !== undefined) {\n supabase.anonKey = anonKey\n delete backend.supabaseAnonKey\n changes.push('move backend.supabaseAnonKey → auth.supabase.anonKey')\n }\n target.supabase = supabase\n doc.auth = target\n }\n backend.version = 2\n changes.push('set backend.version 1 → 2')\n\n return result(\n mod,\n 'applied',\n changes.length === 1 ? 'no legacy supabase fields; version bump only' : 'legacy supabase connection moved under auth',\n { changes },\n )\n },\n}\n\n/**\n * A codemod for a deprecation that is NOT on the document surface.\n *\n * It exists, it runs, and it always refuses — which is the honest shape. The\n * registry gives every deprecation a codemod id precisely so that `fayz\n * upgrade` can never answer \"nothing to do\" about a thing it simply cannot\n * see. What it produces instead is the worklist.\n */\nfunction offDocumentCodemod(id: string, deprecationId: string, decide: string[]): Codemod {\n return {\n id,\n title: getDeprecation(deprecationId).title,\n version: null,\n run() {\n const row = getDeprecation(deprecationId)\n return result({ id, version: null }, 'refused', row.detect, {\n refusal: {\n reason:\n `${row.id} does not live in the store document, so no document transform can retire it. ` +\n `It lives in: ${row.where.join(', ')}.`,\n decide,\n },\n })\n },\n }\n}\n\nconst productMetadataOverlay = offDocumentCodemod(\n 'shop.product-metadata-overlay',\n 'shop.provider.productMetadata',\n [\n 'Confirm, per product, that every option axis the overlay declares (sizes / colors / options) exists as a real variant in admin > product > variants. Only the database knows this; the repo does not.',\n 'For an axis that has NO variants: decide whether the product is genuinely single-variant (delete the axis from the overlay) or whether variants must be created first (do that, then delete it).',\n 'For metadata that is display-only and has no variant equivalent (badges, care text): decide where it goes — the product\\'s own metadata column, or a block prop.',\n 'Then delete the `productMetadata` option from createFayzShopProvider (usually src/config/shop.ts) and the local catalog rows that feed it.',\n ],\n)\n\nconst inventoryCountWrite = offDocumentCodemod(\n 'shop.inventory-count-write',\n 'shop.inventory.directCountWrite',\n [\n 'Apply 0036 (and 0037) to every pool, so a direct write is translated instead of lost.',\n \"Then find the callers: SELECT count(*) FROM plg_shop_stock_movements WHERE reason_code = 'legacy_write' is the backlog, and it names the variants.\",\n 'For each caller, decide what the write MEANT — a receipt, a loss, a stock count, a correction. The shim records all of them as `adjustment` because it is told a number changed and never why; only the person who wrote the caller can say which it was.',\n 'Rewrite each caller to insert the right movement kind. The column keeps working until then.',\n ],\n)\n\nconst placeOrderVariantless = offDocumentCodemod(\n 'shop.place-order-variantless',\n 'shop.placeOrder.variantless',\n [\n 'Apply 0037_default_variant.sql to every pool. Its exit condition is stated in 0039\\'s header: the count of products with no variant must read 0 on every pool.',\n 'Verify it per pool — a repo has no way to observe pool state, and removing the leg while one pool still has variantless products would stop those sales dead.',\n 'Only once every pool reads 0 may the deprecated leg be deleted from shop_place_order.',\n ],\n)\n\nconst saasPackageRename = offDocumentCodemod(\n 'admin.saas-package-rename',\n 'admin.package.saas',\n [\n \"Rewrite the imports: every `from '@fayz-ai/saas'` (and its /ui, /db, /org, /billing, /permissions subpaths) becomes the same path under '@fayz-ai/admin'. The exported API is identical, so this is a find-and-replace, not a decision.\",\n 'Swap the dependency in package.json: remove @fayz-ai/saas, add @fayz-ai/admin at the same range.',\n 'If the app has a LOCAL plugin or a tsconfig path that names @fayz-ai/saas, update those too — a stale alias resolves to the shim and keeps the warning alive after the imports are clean.',\n ],\n)\n\nconst CODEMODS: readonly Codemod[] = [\n discountsToPromotions,\n supabaseToAuth,\n productMetadataOverlay,\n inventoryCountWrite,\n placeOrderVariantless,\n saasPackageRename,\n]\n\n/** Every codemod id, in run order. */\nexport const STORE_CODEMOD_IDS: readonly string[] = CODEMODS.map((mod) => mod.id)\n\n/** What each codemod is, as data — describeStore publishes this. */\nexport interface StoreCodemodDescriptor {\n id: string\n title: string\n /** Registry ids it retires. */\n deprecations: string[]\n /** The section version it is keyed to, or null when the deprecation is not\n * on the document surface (such a codemod always refuses). */\n version: StoreCodemodVersionKey | null\n /** Can it ever apply without a human? */\n automatable: boolean\n}\n\nexport function describeCodemods(): StoreCodemodDescriptor[] {\n return CODEMODS.map((mod) => ({\n id: mod.id,\n title: mod.title,\n deprecations: listDeprecations().filter((row) => row.codemod === mod.id).map((row) => row.id),\n version: mod.version,\n automatable: mod.version !== null,\n }))\n}\n\n/**\n * Run the codemods against a document and report exactly what would change.\n *\n * PURE: the input document is never mutated, and a refused codemod contributes\n * nothing to the output — a refusal must leave the document byte-identical or\n * the refusal was not a refusal.\n */\nexport function upgradeStore(\n input: StoreDocument | Record<string, unknown>,\n options: StoreUpgradeOptions = {},\n): StoreUpgradeResult {\n let selected = CODEMODS\n if (options.only) {\n for (const id of options.only) {\n if (!STORE_CODEMOD_IDS.includes(id)) {\n throw new Error(`Unknown codemod \"${id}\". Valid: ${STORE_CODEMOD_IDS.join(', ')}`)\n }\n }\n selected = CODEMODS.filter((mod) => options.only!.includes(mod.id))\n }\n\n const doc = clone(input) as Record<string, unknown>\n const codemods: StoreCodemodResult[] = []\n let changed = false\n\n for (const mod of selected) {\n // Each codemod runs against a scratch copy so a refusal — or a throw —\n // cannot leave a half-applied document behind. Only an `applied` result\n // is promoted.\n const scratch = clone(doc)\n const outcome = mod.run(scratch)\n codemods.push(outcome)\n if (outcome.status === 'applied') {\n for (const key of Object.keys(doc)) delete doc[key]\n Object.assign(doc, scratch)\n if (outcome.changes.length > 0) changed = true\n }\n }\n\n return {\n ok: codemods.every((outcome) => outcome.status !== 'refused'),\n doc: doc as unknown as StoreDocument,\n changed,\n deprecations: scanStoreDeprecations(input),\n codemods,\n validation: validateStore(doc),\n }\n}\n","import { blockInstanceId } from '../blocks/page-blocks'\nimport { STORE_SECTION_NAMES, isRecord, isJsonValue } from './sections'\nimport type { StoreDocument, StoreSectionName } from './sections'\nimport { validateStore } from './validate'\nimport type { StoreValidationError, StoreValidationReport } from './validate'\n\n// ---------------------------------------------------------------------------\n// applyChange — the fourth ability (spine §3 L5).\n//\n// describeStore says what a store CAN be, validateStore says whether it IS\n// valid, renderStore says what it LOOKS like. applyChange is the only one that\n// writes, and it exists so that an agent's edit is a small typed operation\n// against a path rather than \"emit the whole document again\": a regenerated\n// document loses everything the agent did not think to repeat, and a diff of\n// one is unreadable.\n//\n// Three properties, each of which is the reason a benchmark's edit surface is\n// not usable by a generator:\n//\n// 1. It addresses the SAME paths validateStore reports\n// ('presentation.pages.home.blocks[2].props.title'), plus a block-id form\n// ('blocks[#hero]') because two product rails on one page are otherwise\n// indistinguishable — the problem `StorefrontBlockRef.id` exists for.\n// An agent therefore corrects at exactly the address it was given.\n//\n// 2. It is TRANSACTIONAL and gated by validateStore. A batch that would\n// leave the document invalid is refused whole, with the reasons, and the\n// input document is returned untouched. There is no half-applied state to\n// reason about and no way to author a store the renderer will choke on.\n//\n// 3. Every failure names the valid set (I2): an unknown block id lists the\n// ids present, a locked section lists the writable ones. Silent\n// no-op-on-unknown is what makes generated configuration uncorrectable.\n//\n// It is deliberately five operations. WooCommerce's answer to \"let extensions\n// change things\" was 3,657 hooks; the lesson §4 draws is that a surface an\n// agent cannot enumerate is a surface it cannot use.\n// ---------------------------------------------------------------------------\n\n/** JSON values a change may write. */\nexport type StoreChangeValue = unknown\n\nexport const STORE_CHANGE_OPS = ['set', 'remove', 'insert', 'move'] as const\nexport type StoreChangeOp = (typeof STORE_CHANGE_OPS)[number]\n\nexport interface StoreChange {\n /**\n * `set` — write `value` at `path` (creating missing intermediate objects).\n * `remove` — delete the key, or splice the array element, at `path`.\n * `insert` — splice `value` into the array at `path`, at `index` (default: append).\n * `move` — relocate the array element at `path` to `index`.\n */\n op: StoreChangeOp\n /**\n * Dotted document path, the same shape `validateStore` reports:\n * `presentation.pages.home.blocks[2].props.title`. An array step may address\n * a block by id instead of by position — `blocks[#hero]` — which is the only\n * form that stays correct across a reorder.\n */\n path: string\n /** `set` / `insert`: the JSON value to write. */\n value?: StoreChangeValue\n /** `insert` / `move`: destination index. `insert` defaults to append. */\n index?: number\n}\n\nexport interface AppliedStoreChange {\n op: StoreChangeOp\n path: string\n /** The path with every `[#id]` step resolved to the position it hit — what\n * actually moved, which is what a diff or an undo needs. */\n resolvedPath: string\n /** The value that was there before, when there was one. */\n before?: StoreChangeValue\n /** The value that is there now, when the op leaves one. */\n after?: StoreChangeValue\n}\n\nexport interface ApplyChangeOptions {\n /**\n * Sections this caller may write. Defaults to every section EXCEPT `code`:\n * a code entry is a handle name resolved out of the handle registry, so an\n * agent inventing one produces a document that hydrates to a missing\n * component. Pass it explicitly to move a route or drop an override.\n */\n sections?: readonly StoreSectionName[]\n /**\n * 'reject' (default) — a batch whose RESULT fails validation is discarded\n * whole and `doc` is the untouched input. 'allow' returns the changed\n * document with the report anyway, for a caller that is mid-way through a\n * multi-step edit and will validate at the end.\n */\n onInvalid?: 'reject' | 'allow'\n}\n\nexport interface StoreChangeResult {\n /** True only when every change applied AND the result validates. */\n ok: boolean\n /** The resulting document — the input, unchanged, when a rejected batch failed. */\n doc: StoreDocument\n /** One entry per change, in order, for the changes that were applied. */\n applied: AppliedStoreChange[]\n /** Path/permission failures AND the resulting document's validation errors,\n * in one list, in the shape `validateStore` returns — so a caller has one\n * error vocabulary to correct on rather than two. */\n errors: StoreValidationError[]\n /** Validation of the resulting document. */\n validation: StoreValidationReport\n}\n\n/** Sections a change may write unless the caller says otherwise. */\nexport const DEFAULT_WRITABLE_SECTIONS: readonly StoreSectionName[] = STORE_SECTION_NAMES.filter(\n (name) => name !== 'code',\n)\n\n// --- Paths --------------------------------------------------------------------\n\ntype PathStep =\n | { kind: 'key'; key: string }\n | { kind: 'index'; index: number }\n | { kind: 'id'; id: string }\n\n/** Render a step the way it is written, for error paths and `resolvedPath`. */\nfunction stepText(step: PathStep): string {\n if (step.kind === 'key') return step.key\n if (step.kind === 'index') return `[${step.index}]`\n return `[#${step.id}]`\n}\n\nfunction pathText(steps: readonly PathStep[]): string {\n return steps.reduce((acc, step) => {\n if (step.kind === 'key') return acc ? `${acc}.${step.key}` : step.key\n return acc + stepText(step)\n }, '')\n}\n\n/**\n * Parse `presentation.pages.home.blocks[#hero].props.title` into steps.\n * Returns null for anything malformed — an unparseable path is a hard error,\n * never a silently ignored change.\n */\nexport function parseStorePath(path: string): PathStep[] | null {\n if (typeof path !== 'string' || path.trim() === '') return null\n const steps: PathStep[] = []\n let i = 0\n const source = path.trim()\n let expectKey = true\n\n while (i < source.length) {\n if (source[i] === '.') {\n if (expectKey) return null // '..' or a leading dot\n i++\n expectKey = true\n continue\n }\n if (source[i] === '[') {\n const close = source.indexOf(']', i)\n if (close === -1) return null\n const inner = source.slice(i + 1, close)\n if (inner.startsWith('#')) {\n const id = inner.slice(1)\n if (!id) return null\n steps.push({ kind: 'id', id })\n } else {\n if (!/^\\d+$/.test(inner)) return null\n steps.push({ kind: 'index', index: Number(inner) })\n }\n i = close + 1\n expectKey = false\n continue\n }\n if (!expectKey) return null // 'a[0]b' — a key glued to a bracket\n const next = source.slice(i).search(/[.[]/)\n const key = next === -1 ? source.slice(i) : source.slice(i, i + next)\n if (!key) return null\n steps.push({ kind: 'key', key })\n i += key.length\n expectKey = false\n }\n\n return expectKey || steps.length === 0 ? null : steps\n}\n\n/**\n * Position of the entry addressed by `[#id]`, or -1.\n *\n * Matches the authored `id` first, then the id the RENDERER gives an\n * unidentified block (`blockInstanceId` — `<type>-<index>`). Most documents in\n * the fleet author no ids at all, so without the second form every id\n * `renderStore` hands back would be unaddressable by the ability whose job is\n * to act on it.\n */\nfunction findById(list: readonly unknown[], id: string): number {\n const authored = list.findIndex((entry) => isRecord(entry) && entry.id === id)\n if (authored !== -1) return authored\n return list.findIndex((entry, index) => isRecord(entry) && blockInstanceId(entry, index) === id)\n}\n\n/** The ids present in a list, as an agent would see them (I2's valid set). */\nfunction blockIdsIn(list: readonly unknown[]): string[] {\n return list.flatMap((entry, index) =>\n isRecord(entry) && (typeof entry.id === 'string' || typeof entry.type === 'string')\n ? [blockInstanceId(entry, index)]\n : [],\n )\n}\n\n// --- Navigation ---------------------------------------------------------------\n\ninterface Cursor {\n container: Record<string, unknown> | unknown[]\n /** Where inside the container the final step points. */\n step: PathStep\n /** Array position, when the container is an array. */\n position: number\n /** Steps walked, for `resolvedPath`. */\n walked: PathStep[]\n}\n\ntype NavResult = { ok: true; cursor: Cursor } | { ok: false; error: StoreValidationError }\n\nfunction navError(path: string, code: string, message: string, valid?: string[]): NavResult {\n return { ok: false, error: valid ? { path, code, message, valid } : { path, code, message } }\n}\n\n/**\n * Walk to the CONTAINER of the last step.\n *\n * `create` makes missing intermediate objects along a pure-key path — an agent\n * adding the store's first editorial page should not have to `set\n * presentation.pages` and `set presentation.pages.content` first. It never\n * creates array slots: a position that does not exist is a mistake, not an\n * intent, and it is reported with the length that does exist.\n */\nfunction navigate(root: Record<string, unknown>, steps: PathStep[], create: boolean): NavResult {\n let node: unknown = root\n const walked: PathStep[] = []\n\n for (let i = 0; i < steps.length - 1; i++) {\n const step = steps[i]!\n const here = pathText(walked)\n if (step.kind === 'key') {\n if (!isRecord(node)) {\n return navError(here || '(document)', 'not-an-object', `${here || 'the document'} is not an object, so \".${step.key}\" cannot be followed`)\n }\n if (!(step.key in node) || node[step.key] === undefined) {\n if (!create) {\n return navError(\n pathText([...walked, step]),\n 'unknown-path',\n `${pathText([...walked, step])} does not exist`,\n Object.keys(node).sort(),\n )\n }\n node[step.key] = {}\n }\n node = node[step.key]\n walked.push(step)\n continue\n }\n\n if (!Array.isArray(node)) {\n return navError(here || '(document)', 'not-an-array', `${here || 'the document'} is not an array, so \"${stepText(step)}\" cannot be followed`)\n }\n const position = step.kind === 'index' ? step.index : findById(node, step.id)\n if (position < 0 || position >= node.length) {\n return step.kind === 'id'\n ? navError(pathText([...walked, step]), 'unknown-block-id', `no entry in ${here} has the id \"${step.id}\"`, blockIdsIn(node))\n : navError(pathText([...walked, step]), 'index-out-of-range', `${here} has ${node.length} entr${node.length === 1 ? 'y' : 'ies'}, so index ${step.index} is out of range`)\n }\n node = node[position]\n walked.push({ kind: 'index', index: position })\n }\n\n const last = steps[steps.length - 1]!\n const here = pathText(walked)\n if (last.kind === 'key') {\n if (!isRecord(node)) {\n return navError(here || '(document)', 'not-an-object', `${here || 'the document'} is not an object, so \".${last.key}\" cannot be written`)\n }\n return { ok: true, cursor: { container: node, step: last, position: -1, walked } }\n }\n if (!Array.isArray(node)) {\n return navError(here || '(document)', 'not-an-array', `${here || 'the document'} is not an array, so \"${stepText(last)}\" cannot be written`)\n }\n const position = last.kind === 'index' ? last.index : findById(node, last.id)\n if (last.kind === 'id' && position < 0) {\n return navError(pathText([...walked, last]), 'unknown-block-id', `no entry in ${here} has the id \"${last.id}\"`, blockIdsIn(node))\n }\n return { ok: true, cursor: { container: node, step: last, position, walked } }\n}\n\n// --- Apply --------------------------------------------------------------------\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nfunction sectionOf(steps: PathStep[]): string | null {\n const first = steps[0]\n return first && first.kind === 'key' ? first.key : null\n}\n\n/**\n * Apply an ordered batch of changes to a Store Document.\n *\n * Transactional: the batch either applies whole and validates, or the input\n * document comes back untouched with every reason listed.\n *\n * applyChange(doc, { op: 'set', path: 'theme.colors.primary', value: '41 54% 55%' })\n * applyChange(doc, [\n * { op: 'insert', path: 'presentation.home.sections', index: 0, value: { type: 'seals' } },\n * { op: 'move', path: 'presentation.home.sections[#hero]', index: 1 },\n * ])\n */\nexport function applyChange(\n input: StoreDocument | Record<string, unknown>,\n changes: StoreChange | readonly StoreChange[],\n options: ApplyChangeOptions = {},\n): StoreChangeResult {\n const batch = Array.isArray(changes) ? changes : [changes as StoreChange]\n const writable = options.sections ?? DEFAULT_WRITABLE_SECTIONS\n const onInvalid = options.onInvalid ?? 'reject'\n\n const original = input as Record<string, unknown>\n const errors: StoreValidationError[] = []\n const applied: AppliedStoreChange[] = []\n\n if (!isRecord(original)) {\n const error: StoreValidationError = {\n path: '',\n code: 'invalid-document',\n message: 'a Store Document is an object',\n }\n return {\n ok: false,\n doc: input as StoreDocument,\n applied,\n errors: [error],\n validation: { ok: false, errors: [error] },\n }\n }\n\n const draft = clone(original)\n\n for (let index = 0; index < batch.length; index++) {\n const change = batch[index]!\n const at = `changes[${index}]`\n\n if (!STORE_CHANGE_OPS.includes(change?.op)) {\n errors.push({\n path: `${at}.op`,\n code: 'unknown-change-op',\n message: `\"${String(change?.op)}\" is not a change operation`,\n valid: [...STORE_CHANGE_OPS],\n })\n continue\n }\n\n const steps = parseStorePath(change.path)\n if (!steps) {\n errors.push({\n path: `${at}.path`,\n code: 'invalid-path',\n message: `\"${String(change.path)}\" is not a document path — dotted keys with [0] or [#block-id] steps`,\n })\n continue\n }\n\n const section = sectionOf(steps)\n if (section === null || !STORE_SECTION_NAMES.includes(section as StoreSectionName)) {\n errors.push({\n path: `${at}.path`,\n code: 'unknown-section',\n message: `\"${String(section ?? change.path)}\" is not a document section`,\n valid: [...STORE_SECTION_NAMES],\n })\n continue\n }\n if (!writable.includes(section as StoreSectionName)) {\n errors.push({\n path: `${at}.path`,\n code: 'section-not-writable',\n message:\n section === 'code'\n ? 'the code section holds handle NAMES resolved from the handle registry — an invented one hydrates to a missing component. Pass { sections: [..., \\'code\\'] } to write it deliberately.'\n : `the \"${section}\" section is not writable by this caller`,\n valid: [...writable],\n })\n continue\n }\n if ((change.op === 'set' || change.op === 'insert') && !isJsonValue(change.value)) {\n errors.push({\n path: `${at}.value`,\n code: 'invalid-value',\n message: 'a change writes JSON — code belongs in a registered handle referenced from the code section',\n })\n continue\n }\n\n // A section the document has not opened yet gets opened at v1, so adding\n // the first promotion or the first editorial page is one change, not three.\n if (draft[section] === undefined && (change.op === 'set' || change.op === 'insert')) {\n draft[section] = { version: 1 }\n }\n\n const nav = navigate(draft, steps, change.op === 'set')\n if (!nav.ok) {\n errors.push({ ...nav.error, path: nav.error.path })\n continue\n }\n const { container, step, position, walked } = nav.cursor\n const resolvedSteps = [...walked, step.kind === 'id' ? { kind: 'index' as const, index: position } : step]\n const resolvedPath = pathText(resolvedSteps)\n\n if (Array.isArray(container)) {\n const before = position >= 0 && position < container.length ? clone(container[position]) : undefined\n if (change.op === 'set') {\n if (position < 0 || position >= container.length) {\n errors.push({\n path: change.path,\n code: 'index-out-of-range',\n message: `${pathText(walked)} has ${container.length} entries — use insert to add one`,\n })\n continue\n }\n container[position] = clone(change.value)\n applied.push({ op: 'set', path: change.path, resolvedPath, before, after: clone(change.value) })\n continue\n }\n if (change.op === 'remove') {\n if (position < 0 || position >= container.length) {\n errors.push({\n path: change.path,\n code: 'index-out-of-range',\n message: `${pathText(walked)} has ${container.length} entries, so ${stepText(step)} cannot be removed`,\n })\n continue\n }\n container.splice(position, 1)\n applied.push({ op: 'remove', path: change.path, resolvedPath, before })\n continue\n }\n if (change.op === 'move') {\n if (position < 0 || position >= container.length) {\n errors.push({\n path: change.path,\n code: 'index-out-of-range',\n message: `${pathText(walked)} has ${container.length} entries, so ${stepText(step)} cannot be moved`,\n })\n continue\n }\n const to = change.index ?? 0\n if (!Number.isInteger(to) || to < 0 || to >= container.length) {\n errors.push({\n path: `${at}.index`,\n code: 'index-out-of-range',\n message: `move destination must be 0..${container.length - 1}, got ${String(change.index)}`,\n })\n continue\n }\n const [entry] = container.splice(position, 1)\n container.splice(to, 0, entry)\n applied.push({ op: 'move', path: change.path, resolvedPath, before, after: clone(entry) })\n continue\n }\n // insert INTO an array addressed by an element step is ambiguous; the\n // array itself is the target ('...sections', not '...sections[2]').\n errors.push({\n path: `${at}.path`,\n code: 'invalid-path',\n message: `insert targets the array itself — use \"${pathText(walked)}\" with { index: ${Math.max(position, 0)} }`,\n })\n continue\n }\n\n // Object container.\n const key = (step as { key: string }).key\n const before = key in container ? clone(container[key]) : undefined\n\n if (change.op === 'set') {\n container[key] = clone(change.value)\n applied.push({ op: 'set', path: change.path, resolvedPath, before, after: clone(change.value) })\n continue\n }\n if (change.op === 'remove') {\n if (!(key in container)) {\n errors.push({\n path: change.path,\n code: 'unknown-path',\n message: `${resolvedPath} does not exist`,\n valid: Object.keys(container).sort(),\n })\n continue\n }\n delete container[key]\n applied.push({ op: 'remove', path: change.path, resolvedPath, before })\n continue\n }\n // insert / move target arrays.\n const target = container[key]\n if (!Array.isArray(target)) {\n errors.push({\n path: change.path,\n code: 'not-an-array',\n message: `${resolvedPath} is ${target === undefined ? 'not present' : `a ${typeof target}`}, and ${change.op} targets an array`,\n })\n continue\n }\n if (change.op === 'move') {\n errors.push({\n path: `${at}.path`,\n code: 'invalid-path',\n message: `move targets an element — address it as \"${resolvedPath}[0]\" or \"${resolvedPath}[#id]\"`,\n })\n continue\n }\n const to = change.index ?? target.length\n if (!Number.isInteger(to) || to < 0 || to > target.length) {\n errors.push({\n path: `${at}.index`,\n code: 'index-out-of-range',\n message: `insert index must be 0..${target.length}, got ${String(change.index)}`,\n })\n continue\n }\n target.splice(to, 0, clone(change.value))\n applied.push({\n op: 'insert',\n path: change.path,\n resolvedPath: `${resolvedPath}[${to}]`,\n after: clone(change.value),\n })\n }\n\n const validation = validateStore(draft)\n const failed = errors.length > 0 || !validation.ok\n const rejected = failed && onInvalid === 'reject'\n\n return {\n ok: !failed,\n doc: (rejected ? original : draft) as unknown as StoreDocument,\n applied: rejected ? [] : applied,\n errors: [...errors, ...validation.errors],\n validation,\n }\n}\n","import {\n BLOCK_SETTING_TYPES,\n ENTITY_FIELD_TYPES,\n describeBlocks,\n describeEntities,\n describeExtensionPoints,\n describeLoaders,\n handleRegistry,\n} from '@fayz-ai/core'\nimport type {\n BlockDescriptor,\n EntityDescriptor,\n ExtensionPointDescriptor,\n JsonSchema,\n LoaderDescriptor,\n RegistryEntryDescriptor,\n} from '@fayz-ai/core'\nimport { RULE_OPERATORS, listRuleAttributes } from '@fayz-ai/shop/rules'\nimport type { RuleAttribute } from '@fayz-ai/shop/rules'\nimport { fayzDeprecationPolicy, listDeprecations } from '@fayz-ai/sdk/deprecations'\nimport type { FayzDeprecation, FayzDeprecationPolicy } from '@fayz-ai/sdk/deprecations'\nimport { describeCodemods, scanStoreDeprecations } from './upgrade'\nimport type { StoreCodemodDescriptor, StoreDeprecationFinding } from './upgrade'\nimport { registerStorefrontBlocks } from '../blocks/registry'\nimport { registerStorefrontExtensionPoints } from '../extend/extension-points'\nimport { STOREFRONT_COMPONENT_KEYS } from '../extend/component-contracts'\nimport { STOREFRONT_SLOTS } from '../extend/slots'\nimport type { SlotDescriptor } from '../extend/slots'\nimport { DEFAULT_WRITABLE_SECTIONS, STORE_CHANGE_OPS } from './change'\nimport { STORE_SECTIONS, STORE_SECTION_NAMES, sectionToJsonSchema, isRecord } from './sections'\nimport type { StoreDocument, StoreSectionName } from './sections'\nimport { validateStore, STOREFRONT_PAGE_KINDS } from './validate'\nimport type { StoreValidationReport } from './validate'\n\n// ---------------------------------------------------------------------------\n// describeStore — what a store IS and what it CAN be, as one machine-readable\n// value. This is the catalog an agent reads before generating or editing a\n// document: the registries with their schemas, the section schemas, the page\n// kinds, the slot inventory, the registered handles, the setting vocabulary.\n// Serializable on purpose — it has to survive a prompt and a wire.\n// ---------------------------------------------------------------------------\n\n/**\n * What this store's backend can do.\n *\n * Designed to become backend-aware: today every store is Fayz-backed, so the\n * values are constants. When a second backend lands (spine I11 — e.g. a\n * Shopify-backed store whose catalog is mirrored into canonical tables), this\n * shape is derived from the backend provider instead: a Shopify-backed store\n * keeps `catalogMirror` but cannot run our rule engine, so `ruleEngine`\n * flips false while the document stays identical. Consumers must branch on\n * these flags, never on the provider name.\n */\nexport interface StoreCapabilities {\n /** Backend family serving the store. */\n backend: string\n /** Commerce modes the storefront shell can run. */\n commerceModes: readonly string[]\n /** Reads come from the canonical Fayz catalog (mirrored for ERP-backed stores). */\n catalogMirror: boolean\n /** Cart + checkout run against the Fayz order path. */\n checkout: boolean\n /** Declared data loaders resolved once per page (spine M3). */\n loaders: boolean\n /** Rule engine (spine M6): promotions as data, evaluated by the reference\n * evaluator (mock) or shop_compute_promotion_actions (Supabase). True for\n * Fayz-backed stores; a backend that cannot run our rules (e.g. a\n * Shopify-mirrored store) flips this false and consumers must branch on\n * the flag, never the provider name. */\n ruleEngine: boolean\n /** Custom entity declarations (spine M4): defineEntity + entity.* loaders +\n * generic storage. True for Fayz-backed stores (both providers implement\n * the entity surface); a future backend without it flips this false and\n * consumers must branch on the flag, never the provider name. */\n customEntities: boolean\n /** Extension point registry (spine M7): declared seams with enforced\n * input+output schemas, many dependency-ordered handlers, and exactly one\n * nullable beforePlaceOrder escape valve. */\n extensionPoints: boolean\n}\n\nexport interface StoreSectionDescription {\n description: string\n /** Section versions this SDK understands, ascending. */\n versions: readonly number[]\n /** JSON Schema for the section, compiled from the same spec the validator runs. */\n schema: JsonSchema\n}\n\n/** Summary of one concrete document, when one is passed in. */\n/** The I10 contract, as data the agent reads before authoring (spine M10):\n * the policy, every deprecation, and the codemod that answers each one. */\nexport interface StoreContractDescription {\n policy: FayzDeprecationPolicy\n deprecations: FayzDeprecation[]\n codemods: StoreCodemodDescriptor[]\n}\n\nexport interface StoreDocumentSummary {\n name?: string\n /** Sections present in the document. */\n sections: string[]\n /** Block types the document places (pages, home, slots), sorted, deduped. */\n blocksUsed: string[]\n /** Loader ids the document's data declarations reference, sorted, deduped.\n * Meta-level needs of placed blocks are not repeated here — they are the\n * block's own contract, readable from the blocks registry. */\n loadersUsed: string[]\n /** Handle names the document references, sorted, deduped. */\n handlesUsed: string[]\n /** What in THIS store is deprecated, and what replaces it (I10 + I2). */\n deprecations: StoreDeprecationFinding[]\n validation: StoreValidationReport\n}\n\n/**\n * One of the author-facing abilities (spine §3 L5).\n *\n * Enumerating them is the point. WooCommerce's own conclusion about agent\n * surfaces — quoted in the spine — is that the surface must be \"purpose-built\n * domain abilities … instead of automatically projecting every REST-shaped\n * operation\", and an ability an agent cannot discover is an ability it will not\n * use. There are four, they are listed here with their input schemas, and the\n * list is derived from nothing: if a fifth is added it must be added here.\n */\nexport interface StoreAbilityDescriptor {\n name: 'describeStore' | 'validateStore' | 'renderStore' | 'applyChange'\n /** Where it is imported from. */\n module: string\n /** Does it change the document? */\n writes: boolean\n description: string\n /** JSON Schema of the options/arguments beyond the document itself. */\n input: JsonSchema\n /** What the caller gets back, in prose — the shapes are exported types. */\n output: string\n}\n\nexport interface StoreDescription {\n version: 1\n capabilities: StoreCapabilities\n /** The four abilities, with their input schemas (spine L5). */\n abilities: readonly StoreAbilityDescriptor[]\n sections: Record<StoreSectionName, StoreSectionDescription>\n /** The deprecation contract (spine M10, I10). Enumerable on purpose: an\n * agent that cannot read what is going away will keep generating it. */\n contract: StoreContractDescription\n registries: {\n blocks: BlockDescriptor[]\n loaders: LoaderDescriptor[]\n entities: EntityDescriptor[]\n handles: RegistryEntryDescriptor[]\n /** The rule attribute vocabulary AS ROWS (I9) — the same rows the admin\n * promotion form renders from and validateStore checks against. */\n ruleAttributes: RuleAttribute[]\n /** Every extension point with its input/output schemas AND registered\n * handlers (spine M7) — the enumerable behaviour surface. */\n extensionPoints: ExtensionPointDescriptor[]\n }\n /** The closed operator set rules may use. */\n ruleOperators: readonly string[]\n pageKinds: readonly string[]\n slots: readonly SlotDescriptor[]\n componentSlots: readonly string[]\n settingTypes: readonly string[]\n /** The field-type vocabulary defineEntity accepts (spine M4). */\n entityFieldTypes: readonly string[]\n document?: StoreDocumentSummary\n}\n\n/** The four abilities (spine L5), as data the agent can read before calling. */\nconst STORE_ABILITIES: readonly StoreAbilityDescriptor[] = [\n {\n name: 'describeStore',\n module: '@fayz-ai/storefront',\n writes: false,\n description:\n 'What a store IS and what it CAN be: section schemas, every registry with its JSON Schema, page kinds, slots, handles, the rule vocabulary, the extension points — plus a summary of a document when one is passed. Read this before authoring.',\n input: {\n type: 'object',\n properties: { document: { type: 'object', description: 'Optional Store Document to summarize against the surface.' } },\n additionalProperties: false,\n },\n output: 'StoreDescription',\n },\n {\n name: 'validateStore',\n module: '@fayz-ai/storefront',\n writes: false,\n description:\n 'The gate. Every unknown id — section, field, page kind, block type, block setting, slot, handle, loader, rule attribute — is a hard error that names the valid set (I2). Correct on `errors[].valid`, not on the prose.',\n input: { type: 'object', properties: {}, additionalProperties: false },\n output: 'StoreValidationReport { ok, errors: [{ path, code, message, valid? }] }',\n },\n {\n name: 'renderStore',\n module: '@fayz-ai/storefront/render',\n writes: false,\n description:\n 'Render one route of the document to HTML, headless, and report what came out: title, visible text, heading outline, every block that rendered, every loader that ran and what it returned, and every diagnostic the page logged. This is how an author sees what it authored.',\n input: {\n type: 'object',\n properties: {\n path: { type: 'string', description: \"Route to render ('/', '/catalog', '/product/:slug' resolved, '/biography').\" },\n provider: {\n type: 'string',\n enum: ['config', 'document'],\n description:\n \"'config' uses the provider the store implies; 'document' uses a mock seeded from the document's catalog section — deterministic and network-free.\",\n },\n onError: { type: 'string', enum: ['throw', 'report'] },\n html: { type: 'string', enum: ['document', 'fragment'] },\n maxPasses: { type: 'number' },\n stylesheets: { type: 'array', items: { type: 'string' } },\n lang: { type: 'string' },\n },\n additionalProperties: false,\n },\n output: 'StoreRenderResult { ok, title, found, html, text, outline, blocks, links, data, diagnostics, validation }',\n },\n {\n name: 'applyChange',\n module: '@fayz-ai/storefront',\n writes: true,\n description:\n 'The only write. An ordered batch of typed operations against document paths — the same paths validateStore reports, plus a `blocks[#id]` form. Transactional: a batch whose result would not validate is refused whole, with the reasons.',\n input: {\n type: 'object',\n properties: {\n changes: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n op: { type: 'string', enum: [...STORE_CHANGE_OPS] },\n path: {\n type: 'string',\n description: \"Dotted document path, e.g. 'presentation.pages.home.blocks[#hero].props.title'.\",\n },\n value: { description: 'set / insert: the JSON value to write.' },\n index: { type: 'number', description: 'insert / move: destination index.' },\n },\n required: ['op', 'path'],\n additionalProperties: false,\n },\n },\n sections: {\n type: 'array',\n items: { type: 'string', enum: [...STORE_SECTION_NAMES] },\n description: `Sections this caller may write. Default: ${DEFAULT_WRITABLE_SECTIONS.join(', ')}.`,\n },\n onInvalid: { type: 'string', enum: ['reject', 'allow'] },\n },\n required: ['changes'],\n additionalProperties: false,\n },\n output: 'StoreChangeResult { ok, doc, applied, errors, validation }',\n },\n]\n\nfunction collectBlockTypes(out: Set<string>, loaders: Set<string>, blocks: unknown): void {\n if (!Array.isArray(blocks)) return\n for (const entry of blocks) {\n if (!isRecord(entry)) continue\n if (typeof entry.type === 'string') out.add(entry.type)\n if (isRecord(entry.data)) {\n for (const need of Object.values(entry.data)) {\n if (isRecord(need) && typeof need.loader === 'string') loaders.add(need.loader)\n }\n }\n if (Array.isArray(entry.children)) collectBlockTypes(out, loaders, entry.children)\n }\n}\n\nfunction summarizeDocument(doc: StoreDocument | Record<string, unknown>): StoreDocumentSummary {\n const record = doc as Record<string, unknown>\n const store = isRecord(record.store) ? record.store : undefined\n const presentation = isRecord(record.presentation) ? record.presentation : undefined\n const code = isRecord(record.code) ? record.code : undefined\n\n const blocks = new Set<string>()\n const loaders = new Set<string>()\n if (isRecord(presentation?.home)) collectBlockTypes(blocks, loaders, presentation.home.sections)\n if (isRecord(presentation?.pages)) {\n for (const [kind, page] of Object.entries(presentation.pages)) {\n if (!isRecord(page)) continue\n // pages.content is a MAP of editorial pages, one level deeper.\n if (kind === 'content') {\n for (const contentPage of Object.values(page)) {\n if (isRecord(contentPage)) collectBlockTypes(blocks, loaders, contentPage.blocks)\n }\n continue\n }\n collectBlockTypes(blocks, loaders, page.blocks)\n }\n }\n if (isRecord(presentation?.slots)) {\n for (const area of Object.values(presentation.slots)) {\n if (!isRecord(area)) continue\n for (const slotBlocks of Object.values(area)) collectBlockTypes(blocks, loaders, slotBlocks)\n }\n }\n\n const handles = new Set<string>()\n if (code) {\n for (const field of ['logo', 'provider', 'auth', 'footerCredit']) {\n if (typeof code[field] === 'string') handles.add(code[field] as string)\n }\n if (isRecord(code.components)) {\n for (const handle of Object.values(code.components)) {\n if (typeof handle === 'string') handles.add(handle)\n }\n }\n if (Array.isArray(code.routes)) {\n for (const route of code.routes) {\n if (isRecord(route) && typeof route.component === 'string') handles.add(route.component)\n }\n }\n }\n\n return {\n name: typeof store?.name === 'string' ? store.name : undefined,\n sections: Object.keys(record).filter((key) => key !== '$kind'),\n blocksUsed: [...blocks].sort(),\n loadersUsed: [...loaders].sort(),\n handlesUsed: [...handles].sort(),\n deprecations: scanStoreDeprecations(doc),\n validation: validateStore(doc),\n }\n}\n\n/**\n * The machine-readable description of the storefront authoring surface, plus —\n * when a document is passed — a summary of that document against it.\n */\nexport function describeStore(doc?: StoreDocument | Record<string, unknown>): StoreDescription {\n registerStorefrontBlocks()\n registerStorefrontExtensionPoints()\n\n const sections = {} as Record<StoreSectionName, StoreSectionDescription>\n for (const name of STORE_SECTION_NAMES) {\n sections[name] = {\n description: STORE_SECTIONS[name].description,\n versions: [...STORE_SECTIONS[name].versions],\n schema: sectionToJsonSchema(name),\n }\n }\n\n const description: StoreDescription = {\n version: 1,\n capabilities: {\n backend: 'fayz',\n commerceModes: ['checkout', 'catalog', 'enquiry'],\n catalogMirror: true,\n checkout: true,\n loaders: true,\n ruleEngine: true,\n customEntities: true,\n extensionPoints: true,\n },\n abilities: STORE_ABILITIES,\n sections,\n contract: {\n policy: fayzDeprecationPolicy,\n deprecations: listDeprecations(),\n codemods: describeCodemods(),\n },\n registries: {\n blocks: describeBlocks({ includeExperimental: true }),\n loaders: describeLoaders(),\n entities: describeEntities(),\n handles: handleRegistry.describe(),\n ruleAttributes: listRuleAttributes(),\n extensionPoints: describeExtensionPoints(),\n },\n ruleOperators: RULE_OPERATORS,\n pageKinds: [...STOREFRONT_PAGE_KINDS],\n slots: STOREFRONT_SLOTS,\n componentSlots: STOREFRONT_COMPONENT_KEYS,\n settingTypes: BLOCK_SETTING_TYPES,\n entityFieldTypes: ENTITY_FIELD_TYPES,\n }\n\n if (doc !== undefined) description.document = summarizeDocument(doc)\n return description\n}\n","import { useStorefrontConfig } from '../document/config'\nimport { useCatalogStore } from '../stores/catalog.store'\n\n/** The catalog store, plus the config a listing page needs to render a link. */\nexport function useCatalog() {\n const config = useStorefrontConfig()\n const catalog = useCatalogStore()\n return { ...catalog, catalogPath: config.catalogPath, config }\n}\n","import { useStorefrontConfig } from '../document/config'\n\n/** The resolved storefront config — defaults applied, every field present. */\nexport function useStorefront() {\n return useStorefrontConfig()\n}\n","import { useStorefrontConfig } from '../document/config'\nimport { formatMoney } from '../lib/format'\n\nexport interface StorefrontRegion {\n currency: string\n locale: string\n /** Money formatted for this store, so a caller never re-derives the pair. */\n format: (value: number) => string\n}\n\n/**\n * Currency and locale, with the formatter already bound to them.\n *\n * Returning the bound formatter is the point: `formatMoney` defaults to BRL and\n * pt-BR, so every call site that passes only a number silently formats a\n * non-Brazilian store's prices as reais.\n */\nexport function useRegion(): StorefrontRegion {\n const { currency, locale } = useStorefrontConfig()\n return { currency, locale, format: (value: number) => formatMoney(value, currency, locale) }\n}\n","import { useStorefrontConfig } from '../document/config'\n\nexport type PolicyKind = 'privacy' | 'terms' | 'returns'\n\nexport interface StorefrontPolicy {\n kind: PolicyKind\n title: string\n path: string\n /** The store's own text, or null when it has not published this one yet. */\n content: string | null\n published: boolean\n}\n\nconst POLICIES: ReadonlyArray<{ kind: PolicyKind; title: string; path: string }> = [\n { kind: 'privacy', title: 'Política de Privacidade', path: '/privacy' },\n { kind: 'terms', title: 'Termos de Uso', path: '/terms' },\n { kind: 'returns', title: 'Trocas e Devoluções', path: '/refunds' },\n]\n\nexport interface UsePolicies {\n policies: StorefrontPolicy[]\n /** True when every policy has text — what a payment processor asks for at go-live. */\n complete: boolean\n contactEmail?: string\n}\n\n/**\n * The institutional pages, as data.\n *\n * All three are always listed, published or not: the routes and footer links\n * have to exist before the store writes its policies, because a 404 where a\n * processor expects a returns policy blocks go-live. `published` is what a\n * checklist reads; the page itself renders a placeholder.\n */\nexport function usePolicies(): UsePolicies {\n const config = useStorefrontConfig()\n const policies = POLICIES.map((policy) => {\n const content = config.legal?.[policy.kind]?.trim() || null\n return { ...policy, content, published: content !== null }\n })\n return {\n policies,\n complete: policies.every((policy) => policy.published),\n contactEmail: config.footer?.contact?.email,\n }\n}\n","import { useCartStore } from '../stores/cart.store'\n\n/** The cart: lines, totals and the drawer. */\nexport function useCart() {\n return useCartStore()\n}\n","import React from 'react'\nimport type { PaymentMethodKind, ShippingAddressInput } from '@fayz-ai/shop/types'\nimport { useStorefrontConfig } from '../document/config'\nimport {\n useCartStore,\n selectCount,\n selectSubtotal,\n selectDiscountTotal,\n selectShipping,\n selectTotal,\n} from '../stores/cart.store'\nimport { useSessionStore } from '../stores/session.store'\nimport { placeStorefrontOrder } from '../workflows/checkout'\nimport type {\n PlaceStorefrontOrderResult,\n StorefrontCheckoutAddress,\n StorefrontCheckoutCustomer,\n} from '../workflows/checkout'\n\nexport interface CheckoutTotals {\n count: number\n subtotal: number\n discountTotal: number\n shipping: number\n total: number\n}\n\nexport interface CheckoutSubmission {\n customer: StorefrontCheckoutCustomer\n address?: StorefrontCheckoutAddress\n shippingAddress?: ShippingAddressInput\n paymentMethod?: PaymentMethodKind\n markPaid?: boolean\n}\n\nexport interface UseCheckout {\n /** False when the store sells by catalog or enquiry — there is no checkout to render. */\n enabled: boolean\n /** True when the cart has nothing in it: the reason an enabled checkout still cannot proceed. */\n empty: boolean\n totals: CheckoutTotals\n placing: boolean\n error: string | null\n placeOrder: (input: CheckoutSubmission) => Promise<PlaceStorefrontOrderResult | null>\n}\n\n/**\n * The checkout, with the cart, session and config already bound.\n *\n * `placeOrder` takes only what the shopper typed. Everything the server needs\n * to be told about — lines, discount, totals, the customer session — is read\n * here from the stores, because a caller assembling that payload is a caller\n * that can assemble it wrongly, and the prices in it are exactly the numbers a\n * client must not be trusted with. `shop_place_order` recomputes from the\n * catalog regardless; this keeps the two from disagreeing on screen.\n *\n * `placing` is guarded rather than advisory: a double-submitted checkout is two\n * orders and two charges, and the button being disabled is not a guarantee.\n */\nexport function useCheckout(): UseCheckout {\n const config = useStorefrontConfig()\n const cart = useCartStore()\n const session = useSessionStore()\n const [placing, setPlacing] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n const inflight = React.useRef(false)\n\n const lines = cart.lines\n const totals: CheckoutTotals = {\n count: selectCount({ lines }),\n subtotal: selectSubtotal({ lines }),\n discountTotal: selectDiscountTotal({ lines, discountPercent: cart.discountPercent }),\n shipping: selectShipping({ lines }, config),\n total: selectTotal({ lines, discountPercent: cart.discountPercent }, config),\n }\n\n const placeOrder = React.useCallback(\n async (input: CheckoutSubmission) => {\n if (inflight.current) return null\n inflight.current = true\n setPlacing(true)\n setError(null)\n try {\n return await placeStorefrontOrder({\n config,\n cart: {\n lines: useCartStore.getState().lines,\n discountCode: useCartStore.getState().discountCode,\n discountPercent: useCartStore.getState().discountPercent,\n },\n session: { customerId: session.customerId, email: session.email },\n ...input,\n })\n } catch (err: unknown) {\n setError(err instanceof Error ? err.message : String(err))\n return null\n } finally {\n inflight.current = false\n setPlacing(false)\n }\n },\n [config, session.customerId, session.email],\n )\n\n return {\n enabled: config.features.checkout,\n empty: lines.length === 0,\n totals,\n placing,\n error,\n placeOrder,\n }\n}\n","import type { PaymentMethodKind } from '@fayz-ai/shop/types'\nimport { useStorefrontConfig } from '../document/config'\n\nexport interface UsePaymentMethods {\n /** The kinds this store offers, in the order it declared them. */\n methods: readonly PaymentMethodKind[]\n /** The default selection: the first declared method, or null when none are. */\n preferred: PaymentMethodKind | null\n supports: (method: PaymentMethodKind) => boolean\n}\n\n/**\n * Which payment methods the store offers.\n *\n * Deliberately provider-agnostic. A method is a declared KIND (`pix`,\n * `credit_card`, `cash`) — never a Stripe or Mercado Pago object — because the\n * canonical rule is that no storefront code imports a provider client. Which\n * gateway settles a `pix` is the backend's business, and swapping it must not\n * change a line here.\n */\nexport function usePaymentMethods(): UsePaymentMethods {\n const { payments } = useStorefrontConfig()\n const methods = payments.methods\n return {\n methods,\n preferred: methods[0] ?? null,\n supports: (method: PaymentMethodKind) => methods.includes(method),\n }\n}\n","import type { ShippingQuoteOption } from '@fayz-ai/shop/types'\nimport { useStorefrontConfig } from '../document/config'\nimport { useCartStore, selectSubtotal, selectShipping, selectRequiresShipping } from '../stores/cart.store'\nimport { useDeliveryStore } from '../stores/delivery.store'\nimport type { DeliveryStatus } from '../stores/delivery.store'\n\nexport interface UseShipping {\n postalCode: string\n status: DeliveryStatus\n error: string | null\n options: ShippingQuoteOption[]\n selectedZoneId: string | null\n /** What the current cart would be charged, quote or flat rate. */\n rate: number\n /** False when nothing in the cart travels (0046). The delivery block is not\n * shown at all — a download has no address, and \"Grátis\" implies one. */\n requiresShipping: boolean\n /** True when the flat-rate free-above threshold is already met. */\n free: boolean\n /** How much more the shopper must add to ship free, or null when there is no threshold. */\n amountToFreeShipping: number | null\n quote: (postalCode: string) => Promise<void>\n selectZone: (zoneId: string) => void\n clear: () => void\n}\n\n/**\n * What delivery costs for the cart as it stands.\n *\n * The quote is asked for against the CURRENT subtotal and is never persisted —\n * a price restored from localStorage is a price the shopper can edit with\n * devtools. The order is charged from `shop_place_order`, which recomputes from\n * the same zones and ignores anything the client sends; this hook exists to\n * show a number, not to decide one.\n */\nexport function useShipping(): UseShipping {\n const config = useStorefrontConfig()\n const lines = useCartStore((state) => state.lines)\n const delivery = useDeliveryStore()\n\n const subtotal = selectSubtotal({ lines })\n const rate = selectShipping({ lines }, config)\n const threshold = config.shipping.freeAbove ?? null\n\n return {\n postalCode: delivery.postalCode,\n status: delivery.status,\n error: delivery.error,\n options: delivery.options,\n selectedZoneId: delivery.selectedZoneId,\n rate,\n requiresShipping: lines.length === 0 || selectRequiresShipping({ lines }),\n free: rate === 0 && lines.length > 0,\n amountToFreeShipping:\n threshold === null || subtotal >= threshold ? null : Math.max(0, threshold - subtotal),\n quote: (postalCode: string) => delivery.resolve(postalCode, subtotal),\n selectZone: delivery.selectZone,\n clear: delivery.clear,\n }\n}\n","import React from 'react'\nimport { formatPostalCode, lookupPostalCode, normalizePostalCode } from '@fayz-ai/core'\nimport type { PostalAddress } from '@fayz-ai/core'\n\nexport type AddressLookupStatus = 'idle' | 'loading' | 'found' | 'not-found' | 'error'\n\nexport interface UseAddress {\n postalCode: string\n /** The same code formatted for display (`01311-000`). */\n display: string\n address: PostalAddress | null\n status: AddressLookupStatus\n error: string | null\n /** Set the code and look it up once it is complete. Partial input never calls out. */\n setPostalCode: (value: string) => void\n clear: () => void\n}\n\nconst COMPLETE = 8\n\n/**\n * A postal code, and the address it resolves to.\n *\n * The lookup fires on the code being COMPLETE rather than on every keystroke —\n * a debounce would still send `0`, `01`, `013`… and each is a request that can\n * only fail. The last completed lookup wins: a shopper who corrects a typo mid\n * flight must not have the stale response overwrite the new one.\n *\n * This is the address half of checkout, separated from `useShipping` on purpose:\n * a store that does not ship still asks for a billing address.\n */\nexport function useAddress(initial = ''): UseAddress {\n const [postalCode, setValue] = React.useState(normalizePostalCode(initial))\n const [address, setAddress] = React.useState<PostalAddress | null>(null)\n const [status, setStatus] = React.useState<AddressLookupStatus>('idle')\n const [error, setError] = React.useState<string | null>(null)\n const inflight = React.useRef(0)\n\n const setPostalCode = React.useCallback((value: string) => {\n const normalized = normalizePostalCode(value)\n setValue(normalized)\n\n if (normalized.length < COMPLETE) {\n setAddress(null)\n setStatus('idle')\n setError(null)\n return\n }\n\n const ticket = ++inflight.current\n setStatus('loading')\n setError(null)\n void lookupPostalCode(normalized)\n .then((found) => {\n if (ticket !== inflight.current) return\n setAddress(found)\n setStatus(found ? 'found' : 'not-found')\n })\n .catch((err: unknown) => {\n if (ticket !== inflight.current) return\n setAddress(null)\n setStatus('error')\n setError(err instanceof Error ? err.message : String(err))\n })\n }, [])\n\n const clear = React.useCallback(() => {\n inflight.current++\n setValue('')\n setAddress(null)\n setStatus('idle')\n setError(null)\n }, [])\n\n return {\n postalCode,\n display: formatPostalCode(postalCode),\n address,\n status,\n error,\n setPostalCode,\n clear,\n }\n}\n","import React from 'react'\nimport { getShopProvider } from '@fayz-ai/shop/runtime'\nimport type { Order } from '@fayz-ai/shop/types'\n\nexport interface UseOrder {\n order: Order | null\n loading: boolean\n error: string | null\n reload: () => void\n}\n\n/**\n * One order by id — the confirmation page, and the link a shopper is emailed.\n *\n * A null id is a legitimate state (the route matched before the id resolved),\n * not an error: it settles to `loading: false` with no order rather than\n * reporting a failure the shopper cannot act on. The last request wins, so a\n * fast reload cannot leave the previous order on screen.\n */\nexport function useOrder(orderId: string | null | undefined): UseOrder {\n const [order, setOrder] = React.useState<Order | null>(null)\n const [loading, setLoading] = React.useState(Boolean(orderId))\n const [error, setError] = React.useState<string | null>(null)\n const [nonce, setNonce] = React.useState(0)\n\n React.useEffect(() => {\n if (!orderId) {\n setOrder(null)\n setLoading(false)\n setError(null)\n return\n }\n\n let current = true\n setLoading(true)\n setError(null)\n\n void getShopProvider()\n .getOrder(orderId)\n .then((found) => {\n if (!current) return\n setOrder(found ?? null)\n setLoading(false)\n })\n .catch((err: unknown) => {\n if (!current) return\n setOrder(null)\n setError(err instanceof Error ? err.message : String(err))\n setLoading(false)\n })\n\n return () => {\n current = false\n }\n }, [orderId, nonce])\n\n return { order, loading, error, reload: () => setNonce((n) => n + 1) }\n}\n","import { BLOCK_PATH_ATTRIBUTE, BLOCK_TYPE_ATTRIBUTE, setBlockEditorMode } from '@fayz-ai/core'\n\n// The editor bridge — a storefront running inside an editor's iframe.\n// ACTIVATE/DEACTIVATE in; READY/PICKED/CANCELLED/NAVIGATION_CHANGE out.\n//\n// A pick answers with `{ path, type }` rather than a CSS selector: the page was\n// rendered from a document, so the path is simply true, and the parent hands it\n// straight to describeStore for the settings schema and to applyChange to save.\n//\n// Allowed origins are declared by the CALLER, never announced by the sender —\n// an iframe's parent is chosen by whoever embeds the page, so trusting the\n// announcement hands an element picker to any hostile embedder. Outbound\n// messages go to the activating origin, never '*', and nothing is posted before\n// one has activated.\n\nexport interface EditorBridgeOptions {\n /**\n * Origins allowed to drive the picker. An activation from anywhere else is\n * ignored. Required: there is no safe default, because the parent of an\n * iframe is chosen by whoever embedded it.\n */\n allowedOrigins: readonly string[]\n /** Test seam. Defaults to the ambient window. */\n target?: Window\n}\n\nexport interface PickedBlock {\n /** Dotted document path — what applyChange accepts and validateStore reports. */\n path: string\n /** The block's registered type, so the parent can look up its schema. */\n type: string\n /** Bounding rect of the block's first painted child, for the parent's overlay. */\n rect?: { top: number; left: number; width: number; height: number }\n}\n\nexport const EDITOR_MESSAGES = {\n activate: 'ACTIVATE_ELEMENT_PICKER',\n deactivate: 'DEACTIVATE_ELEMENT_PICKER',\n ready: 'ELEMENT_PICKER_READY',\n picked: 'ELEMENT_PICKED',\n cancelled: 'ELEMENT_PICKER_CANCELLED',\n navigation: 'NAVIGATION_CHANGE',\n} as const\n\n/**\n * The nearest ancestor that is a block, and the element that actually paints.\n *\n * The stamp lives on a `display: contents` wrapper, which has no box of its\n * own — `getBoundingClientRect()` on it returns zeros. So the rect comes from\n * its first element child, which is the block's real root.\n */\nexport function blockAt(element: Element | null): { path: string; type: string; node: Element } | null {\n let current: Element | null = element\n while (current) {\n const path = current.getAttribute?.(BLOCK_PATH_ATTRIBUTE)\n if (path) {\n const painted = current.firstElementChild ?? current\n return { path, type: current.getAttribute(BLOCK_TYPE_ATTRIBUTE) ?? '', node: painted }\n }\n current = current.parentElement\n }\n return null\n}\n\nfunction rectOf(element: Element): PickedBlock['rect'] {\n const r = element.getBoundingClientRect?.()\n if (!r) return undefined\n return { top: r.top, left: r.left, width: r.width, height: r.height }\n}\n\n/**\n * Wire the storefront to an editor parent. Returns a teardown.\n *\n * Inert when the page is not framed: a storefront served to a shopper has\n * `window.parent === window`, nothing is registered, and editor mode stays off.\n */\nexport function connectEditorBridge(options: EditorBridgeOptions): () => void {\n const win = options.target ?? (typeof window === 'undefined' ? undefined : window)\n if (!win || win.parent === win) return () => {}\n\n const allowed = new Set(options.allowedOrigins)\n let parentOrigin: string | null = null\n let active = false\n let hovered: { path: string; type: string; node: Element } | null = null\n\n const post = (message: Record<string, unknown>) => {\n if (!parentOrigin) return\n win.parent.postMessage(message, parentOrigin)\n }\n\n const onMove = (event: MouseEvent) => {\n if (!active) return\n hovered = blockAt(event.target as Element)\n }\n\n const onClick = (event: MouseEvent) => {\n if (!active) return\n // A picker click must never also follow the link it landed on.\n event.preventDefault()\n event.stopPropagation()\n const hit = hovered ?? blockAt(event.target as Element)\n if (!hit) return\n const picked: PickedBlock = { path: hit.path, type: hit.type, rect: rectOf(hit.node) }\n post({ type: EDITOR_MESSAGES.picked, data: picked })\n stop()\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (!active || event.key !== 'Escape') return\n event.preventDefault()\n post({ type: EDITOR_MESSAGES.cancelled })\n stop()\n }\n\n function start() {\n if (active) return\n active = true\n setBlockEditorMode(true)\n win!.document.addEventListener('mousemove', onMove, true)\n win!.document.addEventListener('click', onClick, true)\n win!.document.addEventListener('keydown', onKeyDown, true)\n win!.document.body.style.cursor = 'crosshair'\n post({ type: EDITOR_MESSAGES.ready })\n }\n\n function stop() {\n if (!active) return\n active = false\n hovered = null\n win!.document.removeEventListener('mousemove', onMove, true)\n win!.document.removeEventListener('click', onClick, true)\n win!.document.removeEventListener('keydown', onKeyDown, true)\n win!.document.body.style.cursor = ''\n }\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== win.parent) return\n // The origin must be declared by US, not announced by the sender — an\n // attacker embedding the store controls both `event.data.parentOrigin` and\n // the frame, so trusting the announcement trusts the attacker.\n if (!allowed.has(event.origin)) return\n parentOrigin = event.origin\n\n const kind = (event.data as { type?: string } | null)?.type\n if (kind === EDITOR_MESSAGES.activate) start()\n else if (kind === EDITOR_MESSAGES.deactivate) stop()\n }\n\n win.addEventListener('message', onMessage)\n return () => {\n stop()\n setBlockEditorMode(false)\n win.removeEventListener('message', onMessage)\n }\n}\n\n/**\n * Tell the parent the route changed, so its URL bar follows the iframe.\n *\n * Silent until an allowed parent has activated the bridge — the path is not\n * sensitive, but broadcasting to '*' from every storefront is a habit worth\n * not forming.\n */\nexport function reportNavigation(path: string, parentOrigin: string | null, target?: Window): void {\n const win = target ?? (typeof window === 'undefined' ? undefined : window)\n if (!win || win.parent === win || !parentOrigin) return\n win.parent.postMessage({ type: EDITOR_MESSAGES.navigation, path }, parentOrigin)\n}\n","import { describeBlocks } from '@fayz-ai/core'\nimport type { BlockDescriptor } from '@fayz-ai/core'\nimport { parseStorePath } from '../document/change'\nimport { registerStorefrontBlocks } from './registry'\nimport { BLOCK_STRUCTURAL_KEYS, isNestedBlockRef } from './page-blocks'\nimport type { StoreDocument } from '../document/sections'\n\n// From a picked document path to everything a form generator needs: which block\n// it is, what it currently says, and the SETTINGS SCHEMA it declared. A form\n// built from that schema cannot offer a setting the block does not have and\n// updates itself when the block does.\n//\n// Deliberately NOT a renderer — returning data keeps the SDK out of any one\n// editor's design system.\n\nexport interface BlockAtPath {\n /** The path as given, echoed so a caller can key state by it. */\n path: string\n /** The block's registered type. */\n type: string\n /**\n * Where this block's settings live: `<path>.props` for the nested form,\n * `<path>` itself for the flat one. Both forms MIX inside one array, so a\n * caller appending `.props` by hand is right about some blocks and silently\n * wrong about the rest. Pass this to `settingChange` and it cannot happen.\n */\n settingsPath: string\n /** Current values, whichever form they took — the form's initial state. */\n props: Record<string, unknown>\n /** Empty when the block declares no settings, which is itself the answer. */\n settings: BlockDescriptor['settings']\n /** For a caller that wants labels, help text or presets. */\n descriptor: BlockDescriptor | null\n}\n\nexport type BlockAtPathError =\n | { code: 'unparseable-path'; message: string }\n | { code: 'no-block-at-path'; message: string }\n | { code: 'unknown-block'; message: string; valid: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Walk a parsed path, resolving `[#id]` steps against `id` fields. */\nfunction walk(document: StoreDocument | Record<string, unknown>, path: string): unknown {\n const steps = parseStorePath(path)\n if (!steps) return undefined\n let cursor: unknown = document\n for (const step of steps) {\n if (step.kind === 'key') {\n if (!isRecord(cursor)) return undefined\n cursor = cursor[step.key]\n } else if (step.kind === 'index') {\n if (!Array.isArray(cursor)) return undefined\n cursor = cursor[step.index]\n } else {\n if (!Array.isArray(cursor)) return undefined\n cursor = cursor.find((item) => isRecord(item) && item.id === step.id)\n }\n }\n return cursor\n}\n\n/**\n * Resolve a picked path against a Store Document.\n *\n * Every failure names what went wrong and, for an unknown block, the valid set\n * (I2) — an editor that silently renders an empty panel teaches a merchant that\n * the editor is broken.\n */\nexport function blockAtPath(\n document: StoreDocument | Record<string, unknown>,\n path: string,\n): { ok: true; block: BlockAtPath } | { ok: false; error: BlockAtPathError } {\n if (!parseStorePath(path)) {\n return { ok: false, error: { code: 'unparseable-path', message: `\"${path}\" is not a document path` } }\n }\n\n const node = walk(document, path)\n if (!isRecord(node) || typeof node.type !== 'string') {\n return {\n ok: false,\n error: { code: 'no-block-at-path', message: `nothing at \"${path}\" is a block (a block is an object with a \"type\")` },\n }\n }\n\n // The registry is the source of the schema, so it must be populated — the\n // same requirement `validateStore` has, for the same reason.\n registerStorefrontBlocks()\n const descriptors = describeBlocks()\n const descriptor = descriptors.find((d) => d.id === node.type) ?? null\n\n if (!descriptor) {\n return {\n ok: false,\n error: {\n code: 'unknown-block',\n message: `block \"${node.type}\" is not registered`,\n valid: descriptors.map((d) => d.id).sort(),\n },\n }\n }\n\n // `isNestedBlockRef` is the renderer's own rule, imported rather than\n // restated: the renderer and the editor disagreeing about where a block's\n // settings live is exactly the bug that makes an edit vanish on save.\n const nested = isNestedBlockRef(node)\n const props = nested\n ? isRecord(node.props)\n ? node.props\n : {}\n : Object.fromEntries(Object.entries(node).filter(([key]) => !BLOCK_STRUCTURAL_KEYS.has(key)))\n\n return {\n ok: true,\n block: {\n path,\n type: node.type,\n settingsPath: nested ? `${path}.props` : path,\n props,\n settings: descriptor.settings ?? [],\n descriptor,\n },\n }\n}\n\n/**\n * The change that saves one edited setting.\n *\n * Takes `settingsPath`, not the block's path: only `blockAtPath` has seen the\n * node and knows which form it took. Hardcoding `.props.` here wrote an ignored\n * key on every flat block — a save that reported success and changed nothing.\n */\nexport function settingChange(settingsPath: string, settingId: string, value: unknown): {\n op: 'set' | 'remove'\n path: string\n value?: unknown\n} {\n const path = `${settingsPath}.${settingId}`\n // Clearing a field means the setting is absent, not present-and-empty — an\n // empty string would render as an empty heading where the default belongs.\n if (value === undefined || value === '') return { op: 'remove', path }\n return { op: 'set', path, value }\n}\n","import { applyChange, parseStorePath } from './change'\nimport type { StoreChange } from './change'\nimport type { StoreDocument } from './sections'\nimport { BLOCK_STRUCTURAL_KEYS, isNestedBlockRef } from '../blocks/page-blocks'\nimport { validateStore } from './validate'\nimport type { StoreValidationReport } from './validate'\n\n// The settings overlay, shaped like Shopify's `settings_data.json`: the\n// committed `fayz.store.json` holds the structure, the overlay holds what the\n// merchant chose, and the two merge at render.\n//\n// THE RULE, and why this is not a generic deep merge: an overlay may only\n// change SETTINGS. It may not add, remove, reorder or retype a block, and it\n// may not touch catalog, commerce, backend, auth or code. Without it, the first\n// overlay that inserts a block makes the committed document a lie. A refused\n// path is therefore the mechanism, not a failure mode to route around — an\n// editor that needs to add a block is asking for a commit.\n\n/** Sparse map of document path -> value. Absent means \"use the document's\". */\nexport type StoreOverlay = Record<string, unknown>\n\nexport interface OverlayRejection {\n path: string\n code: 'unparseable-path' | 'not-a-setting' | 'section-not-overlayable' | 'no-block-at-path'\n message: string\n}\n\nexport interface ApplyOverlayResult {\n /** The document a shopper is served: base with the accepted settings applied. */\n document: Record<string, unknown>\n /** Paths that were applied, in the order they were. */\n applied: string[]\n /** Paths the rule refused, each saying why. */\n rejected: OverlayRejection[]\n /** Validation of the MERGED document — the only one that matters. */\n validation: StoreValidationReport\n}\n\n/**\n * Sections an overlay may reach into at all. Everything else is mirrored from\n * the backend (catalog), money (commerce), infrastructure (backend, auth) or\n * code — none of which is a settings-panel change.\n */\nexport const OVERLAYABLE_SECTIONS = ['presentation', 'theme'] as const\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Is this path a setting? Needs the document, and cannot work without it —\n * a path-only rule (\"settings live under `props`\") failed the fleet twice:\n *\n * - the two block forms MIX inside one array (artorious's home page is 3\n * nested and 5 flat), so requiring `props` made the flat ones uneditable;\n * - a setting VALUE can look exactly like a block — a form field is\n * `{id, label, type, required}` — so keying on `type` would refuse a\n * legitimate edit.\n *\n * The walk resolves against the real document and asks the renderer's own\n * `isNestedBlockRef` which form each block took. It stops the moment it enters\n * a setting, which is what makes the form-field case need no exception.\n *\n * `theme` is settings throughout — it is nothing but tokens.\n */\nexport function isSettingPath(\n document: StoreDocument | Record<string, unknown>,\n path: string,\n): OverlayRejection | null {\n const steps = parseStorePath(path)\n if (!steps || steps.length === 0) {\n return { path, code: 'unparseable-path', message: `\"${path}\" is not a document path` }\n }\n\n const head = steps[0]\n if (head?.kind !== 'key' || !OVERLAYABLE_SECTIONS.includes(head.key as (typeof OVERLAYABLE_SECTIONS)[number])) {\n return {\n path,\n code: 'section-not-overlayable',\n message:\n `an overlay may only change ${OVERLAYABLE_SECTIONS.join(' and ')} — ` +\n `\"${path}\" targets something else. Catalog mirrors the backend, commerce is money, ` +\n `code is code: none of those is a settings-panel change.`,\n }\n }\n\n if (head.key === 'theme') return null\n\n const structural = (): OverlayRejection => ({\n path,\n code: 'not-a-setting',\n message:\n `\"${path}\" is not a setting. An overlay changes what a block SAYS, never which ` +\n `blocks exist or in what order — adding, removing, reordering or retyping a block ` +\n `is a change to the committed document, and belongs in a commit.`,\n })\n\n let cursor: unknown = document\n // True when `cursor` is a block: we reached it by indexing an array while\n // still walking structure, and every array reached that way is a block\n // container (the walk returns the moment it enters settings, so a list\n // setting's array is never indexed here).\n let atBlock = false\n\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i]!\n\n if (atBlock) {\n if (!isRecord(cursor)) {\n return {\n path,\n code: 'no-block-at-path',\n message:\n `nothing in the document sits at the block \"${path}\" names — most likely a setting ` +\n `left behind by a block deleted in a later commit. pruneOverlay drops these.`,\n }\n }\n if (step.kind !== 'key') return structural()\n\n if (isNestedBlockRef(cursor)) {\n // `children` is another block array, not a setting: keep walking\n // structure so a nested block's own settings still resolve.\n if (step.key === 'children') {\n cursor = cursor.children\n atBlock = false\n continue\n }\n // Anything but `props` is identity (type, id, data) or a stray key the\n // renderer ignores in this form.\n if (step.key !== 'props') return structural()\n // The props object itself: replacing it wholesale is a rewrite.\n if (i === steps.length - 1) return structural()\n return null\n }\n\n // Flat form: everything that is not identity is a setting, which is the\n // same line `toBlockNode` draws when it reads this block.\n if (BLOCK_STRUCTURAL_KEYS.has(step.key)) return structural()\n return null\n }\n\n if (step.kind === 'key') {\n if (!isRecord(cursor)) return structural()\n cursor = cursor[step.key]\n continue\n }\n if (!Array.isArray(cursor)) return structural()\n cursor = step.kind === 'index' ? cursor[step.index] : cursor.find((item) => isRecord(item) && item.id === step.id)\n atBlock = true\n }\n\n // The steps ran out while still walking structure: the path names a whole\n // block, a block array, or a page — all of which are the repo's to say.\n return structural()\n}\n\n/**\n * Merge an overlay onto a document. Never mutates the input. Rejections are\n * reported rather than thrown: an overlay with one bad entry must still deliver\n * the other forty, or a store stops updating and nobody knows why.\n */\nexport function applyOverlay(\n document: StoreDocument | Record<string, unknown>,\n overlay: StoreOverlay,\n): ApplyOverlayResult {\n const rejected: OverlayRejection[] = []\n const changes: StoreChange[] = []\n\n // Sorted so the result is deterministic regardless of key insertion order —\n // two servers merging the same overlay must serve the same page.\n for (const path of Object.keys(overlay).sort()) {\n const rejection = isSettingPath(document, path)\n if (rejection) {\n rejected.push(rejection)\n continue\n }\n const value = overlay[path]\n changes.push(\n value === undefined\n ? { op: 'remove', path }\n : { op: 'set', path, value: value as StoreChange['value'] },\n )\n }\n\n // `onInvalid: 'reject'` discards an invalid merge whole and serves the BASE:\n // degrading to what the repo says is safe, half-merging is a page nobody has\n // validated. The save path validates before persisting; this is the belt.\n const result = applyChange(document, changes, {\n sections: [...OVERLAYABLE_SECTIONS],\n onInvalid: 'reject',\n })\n\n // `applyChange.errors` mixes its own refusals with the merged document's\n // validation errors. Only errors on a submitted path count as rejections —\n // blaming an overlay entry for a pre-existing error at `commerce.mode` would\n // have pruneOverlay delete healthy settings.\n //\n // Blame matches BOTH directions along a branch. Downward: `set` creates\n // missing intermediates, so an entry can materialise a block with no `type`\n // and the error lands beneath it. Upward: the array refuses the index and the\n // error lands at `blocks[9]`, a PREFIX of what was submitted — which is what\n // an orphan actually produces, so matching only downward let every orphan\n // through silently. A bare section path is excluded, or one document-level\n // error would condemn the whole overlay.\n const applied = new Set(result.applied.map((a) => a.path))\n const beneath = (ancestor: string, descendant: string): boolean =>\n descendant === ancestor || descendant.startsWith(`${ancestor}.`) || descendant.startsWith(`${ancestor}[`)\n\n for (const failure of result.errors) {\n if (!failure.path || !failure.path.includes('.')) continue\n const owner = changes.find(\n (c) => !applied.has(c.path) && (beneath(c.path, failure.path) || beneath(failure.path, c.path)),\n )\n if (!owner || rejected.some((r) => r.path === owner.path)) continue\n rejected.push({ path: owner.path, code: 'not-a-setting', message: failure.message })\n }\n\n return {\n document: result.doc as unknown as Record<string, unknown>,\n applied: result.applied.map((a) => a.resolvedPath),\n rejected,\n validation: result.validation,\n }\n}\n\n/**\n * Drop overlay entries the document can no longer accept. Orphans are harmless\n * on their own — applyOverlay refuses them — but they accumulate, and an\n * overlay nobody prunes hides a real mistake among a hundred dead ones.\n */\nexport function pruneOverlay(\n document: StoreDocument | Record<string, unknown>,\n overlay: StoreOverlay,\n): { overlay: StoreOverlay; dropped: string[] } {\n const result = applyOverlay(document, overlay)\n const dead = new Set(result.rejected.map((r) => r.path))\n const kept: StoreOverlay = {}\n for (const [path, value] of Object.entries(overlay)) {\n if (!dead.has(path)) kept[path] = value\n }\n return { overlay: kept, dropped: [...dead].sort() }\n}\n","import type { StorefrontTheme } from '../lib/theme'\nimport type { HomeConfig } from '../blocks/sections'\n\n// ---------------------------------------------------------------------------\n// Template presets — recreations of the four Nuvemshop patterns selected in\n// docs/archive/storefront-templates-research.md. Each is { theme, home() } so an app\n// (or the Fayz agent) starts from a complete professional store and overrides\n// copy, colors, hero images and sections — the saas-core theming workflow.\n// ---------------------------------------------------------------------------\n\n/** Real imagery for a template home — resolved at build time (e.g. via\n * scripts/fetch-unsplash.mjs); falls back to gradient placeholders when omitted. */\nexport interface TemplateImages {\n hero?: Array<string | undefined>\n banners?: Array<string | undefined>\n}\n\nexport interface StorefrontTemplate {\n id: string\n /** The Nuvemshop pattern this recreates */\n inspiration: string\n theme: StorefrontTheme\n /** Default home blueprint — pass the store name for copy interpolation */\n home: (storeName: string, images?: TemplateImages) => HomeConfig\n announcement?: string\n}\n\n/** maré — elegant fashion (Rio): airy warm paper, olive ink, sand CTA, centered logo. */\nexport const mareTemplate: StorefrontTemplate = {\n id: 'mare',\n inspiration: 'Nuvemshop Rio',\n announcement: 'FRETE GRÁTIS EM COMPRAS ACIMA DE R$ 300',\n theme: {\n name: 'mare',\n colors: {\n background: '40 14% 93%',\n foreground: '90 8% 38%',\n primary: '42 32% 61%',\n primaryForeground: '40 30% 12%',\n card: '40 20% 97%',\n cardForeground: '90 10% 25%',\n muted: '40 12% 88%',\n mutedForeground: '90 6% 50%',\n border: '40 10% 82%',\n announcementBackground: '90 10% 30%',\n announcementForeground: '40 20% 95%',\n },\n font: { heading: 'Plus Jakarta Sans', body: 'Plus Jakarta Sans' },\n radius: 'soft',\n header: { variant: 'centered' },\n productCard: { style: 'editorial', imageAspect: 'portrait' },\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'banner',\n height: 'tall',\n slides: [\n { title: 'Feito para durar', subtitle: `A nova coleção ${storeName} chegou — peças atemporais em materiais honestos.`, cta: 'Ver coleção', hue: 75, image: images?.hero?.[0] },\n ],\n },\n { type: 'categories', style: 'bubbles' },\n { type: 'products', title: 'Destaques', filter: 'all', limit: 4 },\n { type: 'banner', title: 'Até 30% off', eyebrow: 'por tempo limitado', subtitle: 'Peças selecionadas da estação', cta: 'Aproveitar', hue: 40, image: images?.banners?.[0] },\n { type: 'products', title: 'Promoções', filter: 'sale', limit: 4 },\n { type: 'products', title: 'Lançamentos', filter: 'new', limit: 4 },\n { type: 'newsletter', title: 'Assine nossa newsletter', subtitle: 'Novidades e ofertas exclusivas, sem spam.' },\n ],\n }),\n}\n\n/** sertão — editorial organic (Uyuni): cream paper, coffee serif ink, boxed hero, manifesto. */\nexport const sertaoTemplate: StorefrontTemplate = {\n id: 'sertao',\n inspiration: 'Nuvemshop Uyuni',\n theme: {\n name: 'sertao',\n colors: {\n background: '30 100% 98%',\n foreground: '28 42% 32%',\n primary: '28 42% 32%',\n primaryForeground: '30 100% 97%',\n card: '32 60% 96%',\n cardForeground: '28 40% 26%',\n muted: '32 40% 92%',\n mutedForeground: '28 22% 48%',\n border: '28 30% 80%',\n },\n font: { heading: 'Marcellus', body: 'Marcellus', fallback: 'serif' },\n radius: 'none',\n header: { variant: 'minimal', uppercaseNav: true },\n productCard: { style: 'editorial', imageAspect: 'portrait' },\n uppercaseButtons: true,\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'banner',\n height: 'tall',\n slides: [\n { title: 'Essenciais naturais', subtitle: 'Conheça nossa coleção', cta: 'Ver mais', hue: 28, boxed: true, image: images?.hero?.[0] },\n ],\n },\n {\n type: 'manifesto',\n text: `Num mundo de pressa e excesso, ${storeName} escolhe o caminho lento: ingredientes honestos, produção pequena e cuidado em cada detalhe.`,\n },\n { type: 'categories', style: 'tiles' },\n { type: 'products', title: 'ESSENCIAIS', filter: 'all', limit: 4 },\n {\n type: 'testimonials',\n title: 'Nossos clientes',\n items: [\n { quote: 'Qualidade impecável e um cheiro que abraça.', author: 'Helena M.' },\n { quote: 'Compro há dois anos e nunca me decepcionou.', author: 'Rafael T.' },\n { quote: 'Entrega rápida e embalagem linda, dá gosto de presentear.', author: 'Cláudia P.' },\n ],\n },\n { type: 'products', title: 'NOVIDADES', filter: 'new', limit: 4 },\n {\n type: 'benefits',\n items: [\n { icon: 'Truck', title: 'Frete para todo o Brasil', text: 'Envio em até 48h' },\n { icon: 'Leaf', title: '100% vegano', text: 'Sem testes em animais' },\n { icon: 'RotateCcw', title: 'Troca fácil', text: '30 dias para trocar' },\n ],\n },\n { type: 'newsletter', title: 'NEWSLETTER', subtitle: 'Histórias, lançamentos e cuidado — direto no seu e-mail.' },\n ],\n }),\n}\n\n/** volt — bold tech (Brasília): white canvas, near-black ink, vivid CTA, dark search-first header, split hero. */\nexport const voltTemplate: StorefrontTemplate = {\n id: 'volt',\n inspiration: 'Nuvemshop Brasília',\n announcement: 'CUPOM BEMVINDO10 — 10% DE DESCONTO NA PRIMEIRA COMPRA',\n theme: {\n name: 'volt',\n colors: {\n background: '0 0% 100%',\n foreground: '0 0% 7%',\n primary: '341 100% 45%',\n primaryForeground: '0 0% 100%',\n card: '0 0% 98%',\n cardForeground: '0 0% 10%',\n muted: '0 0% 94%',\n mutedForeground: '0 0% 40%',\n border: '0 0% 88%',\n headerBackground: '0 0% 6%',\n headerForeground: '0 0% 98%',\n announcementBackground: '341 100% 45%',\n announcementForeground: '0 0% 100%',\n },\n font: { heading: 'Chakra Petch', body: 'Rubik' },\n radius: 'soft',\n header: { variant: 'search', uppercaseNav: true },\n productCard: { style: 'card', imageAspect: 'square' },\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'split',\n slides: [\n { title: 'Tecnologia', subtitle: 'O melhor do hardware e dos acessórios', hue: 250, image: images?.hero?.[0] },\n { title: 'Ofertas', subtitle: `Descontos semanais ${storeName}`, hue: 341, href: '/catalog', image: images?.hero?.[1] },\n ],\n },\n {\n type: 'benefits',\n items: [\n { icon: 'CreditCard', title: '3x sem juros', text: 'Em todo o site' },\n { icon: 'Truck', title: 'Envio em 24h', text: 'Para todo o Brasil' },\n { icon: 'ShieldCheck', title: 'Compra segura', text: 'Seus dados protegidos' },\n ],\n },\n { type: 'products', title: 'NOVIDADES', filter: 'new', limit: 4 },\n { type: 'banner', title: 'DESCONTOS SEMANAIS', eyebrow: 'toda sexta', subtitle: 'Ofertas novas, estoque limitado', cta: 'Conferir', hue: 341, image: images?.banners?.[0] },\n { type: 'products', title: 'PROMOÇÕES', filter: 'sale', limit: 4 },\n { type: 'newsletter', title: 'Entre para o clube', subtitle: 'Cupons e lançamentos antes de todo mundo.' },\n ],\n }),\n}\n\n/** atelier — classic premium retail (Flex): white, near-black, gold accent, slider hero, trust badges. */\nexport const atelierTemplate: StorefrontTemplate = {\n id: 'atelier',\n inspiration: 'Nuvemshop Flex',\n theme: {\n name: 'atelier',\n colors: {\n background: '0 0% 100%',\n foreground: '0 0% 9%',\n primary: '40 45% 48%',\n primaryForeground: '0 0% 100%',\n card: '0 0% 99%',\n cardForeground: '0 0% 9%',\n muted: '40 10% 95%',\n mutedForeground: '0 0% 42%',\n border: '0 0% 88%',\n announcementBackground: '0 0% 9%',\n announcementForeground: '0 0% 98%',\n },\n font: { heading: 'Outfit', body: 'Outfit' },\n radius: 'none',\n header: { variant: 'centered', uppercaseNav: true },\n productCard: { style: 'card', imageAspect: 'square' },\n uppercaseButtons: true,\n },\n announcement: 'PARCELE EM ATÉ 10X · 5% OFF NO PIX',\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'slider',\n height: 'medium',\n slides: [\n { title: 'Feito para quem valoriza detalhes', subtitle: `Coleção exclusiva ${storeName}`, cta: 'APROVEITE', hue: 40, image: images?.hero?.[0] },\n { title: 'Clássicos que não saem de moda', subtitle: 'Peças autorais, produção limitada', cta: 'VER COLEÇÃO', hue: 210, image: images?.hero?.[1] },\n ],\n },\n {\n type: 'benefits',\n items: [\n { icon: 'CreditCard', title: 'Parcele em até 10x', text: 'Ou 5% off no PIX' },\n { icon: 'Lock', title: 'Site 100% seguro', text: 'Seus dados protegidos' },\n { icon: 'Award', title: 'Peças exclusivas', text: 'Produtos 100% autorais' },\n ],\n },\n { type: 'categories', style: 'tiles' },\n { type: 'products', title: 'Novidades', filter: 'new', limit: 4 },\n { type: 'banner', title: 'Promoções', eyebrow: 'seleção especial', subtitle: 'Selecionados com até 25% off', cta: 'Ver ofertas', hue: 40, image: images?.banners?.[0] },\n { type: 'products', title: 'Promoções', filter: 'sale', limit: 4 },\n {\n type: 'testimonials',\n title: 'O que dizem sobre nós',\n items: [\n { quote: 'Acabamento perfeito, superou a expectativa.', author: 'Mariana C.' },\n { quote: 'Atendimento impecável do pedido à entrega.', author: 'Jorge L.' },\n { quote: 'Virou minha loja favorita para presentes.', author: 'Paula R.' },\n ],\n },\n { type: 'newsletter' },\n ],\n }),\n}\n\n/** food — warm appetizing delivery (steakhouse / burger / comfort food): dark inviting\n * header, ember CTA, cream canvas, rounded cards, menu-first home with \"mais pedidos\"\n * rail and social proof. Built for restaurant/food stores — override to go fully dark. */\nexport const foodTemplate: StorefrontTemplate = {\n id: 'food',\n inspiration: 'Delivery / restaurant storefront',\n announcement: 'ENTREGA GRÁTIS ACIMA DE R$ 150 · PEÇA JÁ',\n theme: {\n name: 'food',\n colors: {\n background: '30 33% 97%',\n foreground: '20 14% 15%',\n primary: '14 84% 50%',\n primaryForeground: '0 0% 100%',\n card: '30 33% 99%',\n cardForeground: '20 14% 15%',\n muted: '28 20% 92%',\n mutedForeground: '22 10% 42%',\n border: '28 18% 85%',\n headerBackground: '20 14% 11%',\n headerForeground: '30 24% 96%',\n announcementBackground: '14 84% 50%',\n announcementForeground: '0 0% 100%',\n },\n font: { heading: 'Poppins', body: 'Inter' },\n radius: 'round',\n header: { variant: 'classic' },\n productCard: { style: 'card', imageAspect: 'square' },\n },\n home: (storeName, images) => ({\n sections: [\n {\n type: 'hero',\n variant: 'banner',\n height: 'tall',\n slides: [\n { title: 'Sabor de verdade, na sua porta', subtitle: `${storeName} — feito na hora, do jeito que você ama.`, cta: 'Ver cardápio', href: '/catalog', hue: 20, image: images?.hero?.[0] },\n ],\n },\n {\n type: 'benefits',\n items: [\n { icon: 'Flame', title: 'Feito na hora', text: 'Preparado com capricho' },\n { icon: 'Truck', title: 'Entrega rápida', text: 'Frete grátis acima de R$ 150' },\n { icon: 'CreditCard', title: 'Pagamento fácil', text: 'Pix, cartão e mais' },\n ],\n },\n { type: 'categories', style: 'tiles', title: 'Nosso cardápio' },\n { type: 'products', title: 'Mais pedidos', eyebrow: 'favoritos da casa', filter: 'all', limit: 8 },\n { type: 'banner', title: 'Combo do dia', eyebrow: 'oferta', subtitle: 'Seleção especial com desconto', cta: 'Aproveitar', hue: 14, image: images?.banners?.[0] },\n { type: 'products', title: 'Novidades no cardápio', filter: 'new', limit: 4 },\n {\n type: 'testimonials',\n title: 'O que dizem por aí',\n items: [\n { quote: 'Chegou quentinho e absurdo de bom. Virei cliente!', author: 'Rafael M.' },\n { quote: 'Sabor de restaurante em casa, sem complicação.', author: 'Beatriz L.' },\n { quote: 'Entrega rápida e porção generosa. Recomendo demais.', author: 'Diego S.' },\n ],\n },\n { type: 'newsletter', title: 'Receba nossas ofertas', subtitle: 'Promoções e novidades do cardápio, direto no seu e-mail.' },\n ],\n }),\n}\n\nexport const storefrontTemplates = {\n mare: mareTemplate,\n sertao: sertaoTemplate,\n volt: voltTemplate,\n atelier: atelierTemplate,\n food: foodTemplate,\n} as const\n\nexport type StorefrontTemplateId = keyof typeof storefrontTemplates\n","import React from 'react'\nimport type { StorefrontBlockLike } from '../blocks/page-blocks'\nimport { StorefrontPage } from './StorefrontPage'\n\n// Kept as the public shorthand for \"render this list of sections as a page\".\n// Several stores import it directly for their own routes, so it stays — but it\n// now delegates to StorefrontPage rather than rendering a tree of its own.\n// Two page renderers would drift, and the one that drifted would be this one:\n// it would silently miss page context, the diagnostics and (from Fase 3) slots.\nexport function StorefrontSections({ sections }: { sections: readonly StorefrontBlockLike[] }) {\n return <StorefrontPage kind=\"home\" page={{ blocks: sections }} />\n}\n\nexport function HomePage({ sections }: { sections: readonly StorefrontBlockLike[] }) {\n return <StorefrontSections sections={sections} />\n}\n","// Factory\nexport {\n createStorefront,\n createStorefrontApp,\n initStorefrontRuntime,\n registerStorefrontEntities,\n resolveStorefrontProvider,\n StorefrontShell,\n} from './app/createStorefrontApp'\nexport type { CreateStorefrontOptions, StorefrontShellProps } from './app/createStorefrontApp'\nexport {\n defineStorefrontConfig,\n defineStorefrontComponents,\n defineStorefrontRoutes,\n defineStorefrontSections,\n defineStorefrontApp,\n} from './app/define'\nexport type {\n StorefrontConfig,\n ResolvedStorefrontConfig,\n StorefrontRouteComponentProps,\n StorefrontRouteChrome,\n StorefrontCommerceMode,\n StorefrontImageLoadingConfig,\n StorefrontImageLoadingMode,\n StorefrontRouteDefinition,\n StorefrontRouteKind,\n StorefrontRouteParams,\n StorefrontEnquiryConfig,\n StorefrontSearchConfig,\n} from './document/config'\nexport type {\n StorefrontActions,\n StorefrontComponents,\n ProductCardProps,\n ProductCardImageOrder,\n ProductDetailProps,\n ProductGalleryProps,\n ProductGalleryOrder,\n ProductPriceProps,\n ProductActionsProps,\n ProductEnquiryFormContractProps,\n CategoryCardProps,\n CollectionSectionProps,\n HeroSectionContractProps,\n MediaCarouselProps as MediaCarouselContractProps,\n ProductSliderProps as ProductSliderContractProps,\n StorefrontChromeProps,\n StorefrontStateProps,\n} from './extend/component-contracts'\nexport { useStorefrontConfig, useStorefrontConfigOptional } from './document/config'\n// The config seam. `createStorefront` wires these internally; exporting them is\n// what lets a page or a block be rendered outside it — by a store with fully\n// custom routing, by the visual editor's preview, and by a test. Its absence is\n// the reason this package had no tests.\nexport { resolveConfig, StorefrontConfigProvider } from './document/config'\n// The merchant's saved policy, overlaid on the declared config. `applyStoreSettings`\n// is exported for its own sake: it decides what a shopper is offered, and a\n// bespoke storefront that builds its own provider tree needs the same merge.\nexport { StorefrontConfigHost, applyStoreSettings } from './document/store-policy'\n\n// Manifest path (renderApp(defineStorefront(config)) / storefront scaffold)\nexport { defineStorefront, StorefrontScaffold } from './app/scaffold'\n\n// Store Document v1 (spine M1): serialize / validate / describe / hydrate.\n// The handle registry itself lives in @fayz-ai/core (registerHandle et al) and\n// is re-exported here so storefront apps depend on one package.\nexport {\n exportStore,\n hydrateStoreDocument,\n slugifyStoreName,\n STORE_DOCUMENT_KIND,\n} from './document/round-trip'\nexport type { ExportStoreOptions, HydrateStoreOptions } from './document/round-trip'\nexport {\n STORE_SECTIONS,\n STORE_SECTION_NAMES,\n sectionToJsonSchema,\n STORE_COMMERCE_MODES,\n STORE_PAYMENT_MODES,\n STORE_PAYMENT_METHOD_KINDS,\n STORE_BACKEND_PROVIDERS,\n STORE_ROUTE_KINDS,\n STORE_ROUTE_CHROMES,\n} from './document/sections'\nexport type {\n StoreDocument,\n StoreSectionName,\n StoreIdentitySection,\n StoreThemeSection,\n StoreCommerceSection,\n StorePresentationSection,\n StoreContentSection,\n StoreCatalogSection,\n StoreBackendSection,\n StoreAuthSection,\n StoreCodeSection,\n StoreCodeRouteRef,\n StoreFieldSpec,\n StoreFieldDeprecation,\n StoreSectionSpec,\n} from './document/sections'\nexport { validateStore, STOREFRONT_PAGE_KINDS } from './document/validate'\nexport type { StoreValidationReport, StoreValidationError } from './document/validate'\nexport { describeStore } from './document/describe'\nexport type {\n StoreDescription,\n StoreAbilityDescriptor,\n StoreCapabilities,\n StoreSectionDescription,\n StoreDocumentSummary,\n StoreContractDescription,\n} from './document/describe'\n// The M10 contract: what is deprecated in this store, and the codemods keyed\n// to document version that retire it. `fayz upgrade` drives these.\nexport {\n upgradeStore,\n scanStoreDeprecations,\n unobservableDeprecations,\n describeCodemods,\n STORE_CODEMOD_IDS,\n} from './document/upgrade'\nexport type {\n StoreUpgradeResult,\n StoreUpgradeOptions,\n StoreCodemodResult,\n StoreCodemodStatus,\n StoreCodemodRefusal,\n StoreCodemodDescriptor,\n StoreCodemodVersionKey,\n StoreDeprecationFinding,\n} from './document/upgrade'\n// applyChange — the fourth ability (spine M8). `renderStore` is the third and\n// lives on the ./render subpath, because it imports react-dom/server.\nexport {\n applyChange,\n parseStorePath,\n STORE_CHANGE_OPS,\n DEFAULT_WRITABLE_SECTIONS,\n} from './document/change'\nexport type {\n StoreChange,\n StoreChangeOp,\n StoreChangeResult,\n AppliedStoreChange,\n ApplyChangeOptions,\n} from './document/change'\nexport { STOREFRONT_COMPONENT_KEYS } from './extend/component-contracts'\nexport {\n registerHandle,\n resolveHandle,\n getHandle,\n hasHandle,\n listHandles,\n handleNameFor,\n} from '@fayz-ai/core'\n\n// Block system (storefront sections as registry blocks)\nexport { registerStorefrontBlocks, sectionsToBlocks } from './blocks/registry'\n\n// Loaders — declared reads through the ShopProvider port (M3, I11)\nexport { registerStorefrontLoaders } from './data/loaders'\nexport type {\n StorefrontLoaderContext,\n ProductsListParams,\n ProductBySlugParams,\n ProductsSort,\n EntityListParams,\n EntityBySlugParams,\n} from './data/loaders'\n\n// Page data — needs collected from the block tree, resolved once per page\nexport {\n PageDataScope,\n useLoader,\n useBlockData,\n BlockDataError,\n collectDataNeeds,\n resolveDataParams,\n resolvePageData,\n resolvePageDataNeed,\n} from './blocks/page-data'\nexport type {\n PageDataEntry,\n PageDataNeed,\n PageDataStatus,\n PageDataScopeProps,\n UseLoaderResult,\n} from './blocks/page-data'\n\n// The static-render seam renderStore drives the live components through (M8).\nexport { currentStaticRenderPass, withStaticRenderPass } from './app/static-render'\nexport type { StaticRenderPass, StaticHeadInput } from './app/static-render'\n\n// Pages as block trees (compose any route, not just the home)\nexport {\n toBlockNodes,\n defaultPageBlocks,\n checkPageBlocks,\n matchContentPage,\n contentPagePath,\n routePathParams,\n mergePageTheme,\n pageThemeSelector,\n CATALOG_BODY_BLOCK,\n PRODUCT_BODY_BLOCK,\n} from './blocks/page-blocks'\nexport type {\n StorefrontBlockRef,\n StorefrontBlockLike,\n StorefrontPageConfig,\n StorefrontContentPageConfig,\n ContentPageMatch,\n StorefrontPagesConfig,\n StorefrontPageKind,\n PageBlockDiagnostic,\n} from './blocks/page-blocks'\nexport {\n StorefrontPage,\n useStorefrontPage,\n useStorefrontPageOptional,\n resetPageDiagnostics,\n} from './views/StorefrontPage'\nexport type { StorefrontPageProps, StorefrontPageContextValue } from './views/StorefrontPage'\n\n// Partial overrides (adjust a component's props without adopting the component)\nexport { resolveOverride, overrideComponent, overrideProps } from './extend/component-override'\nexport type { ComponentOverride, ResolvedOverride } from './extend/component-override'\n\n// Named slots (graft blocks into an SDK page without owning the page)\nexport { Slot, useSlotContext, listSlots, usedSlots, STOREFRONT_SLOTS } from './extend/slots'\nexport type {\n StorefrontSlots,\n StorefrontSlotArea,\n StorefrontSlotContextMap,\n SlotDescriptor,\n SlotProps,\n ListSlotsOptions,\n} from './extend/slots'\n\n// Routing\nexport { Link, navigateTo, useHashPath, matchPath } from './app/router'\nexport type { LinkProps } from './app/router'\n\n// Stores\nexport {\n useCartStore,\n selectCount,\n selectSubtotal,\n selectDiscountTotal,\n selectShipping,\n selectTotal,\n} from './stores/cart.store'\nexport type { CartLine, CartState } from './stores/cart.store'\nexport { useSessionStore } from './stores/session.store'\nexport type { SessionState } from './stores/session.store'\nexport {\n signInByEmail,\n signUpCustomer,\n establishCustomerSession,\n signOutCustomer,\n getCustomerAuthAdapter,\n resolveAuthAdapter,\n EmailConfirmationRequiredError,\n} from './data/auth'\nexport type { StorefrontAuthAdapter, StorefrontAuthConfig, EstablishSessionOptions } from './data/auth'\nexport { useCatalogStore } from './stores/catalog.store'\nexport type { CatalogState, CatalogSort } from './stores/catalog.store'\n// Metadata refinements — one matcher, shared by the catalogue page, the rails\n// and the server-side loader.\nexport { matchesFacets, withFacet, mergeCollectionFacet, toFacetMap } from './data/facets'\nexport type { CatalogFacets, CatalogFacetEntry } from './data/facets'\n\n// Hooks\nexport {\n useProducts,\n useProduct,\n useCategories,\n useCatalog,\n useStorefront,\n useStorefrontActions,\n useStorefrontHead,\n useRegion,\n usePolicies,\n useCart,\n useCheckout,\n useDiscountValidator,\n usePaymentMethods,\n useShipping,\n useAddress,\n useOrder,\n useMyOrders,\n useEnquiry,\n} from './hooks'\nexport type {\n StorefrontRegion,\n PolicyKind,\n StorefrontPolicy,\n UsePolicies,\n CheckoutTotals,\n CheckoutSubmission,\n UseCheckout,\n UsePaymentMethods,\n UseShipping,\n AddressLookupStatus,\n UseAddress,\n UseOrder,\n} from './hooks'\n\n// Components (for custom layouts)\nexport { StorefrontHeader } from './components/layout/StorefrontHeader'\nexport { SearchOverlay } from './components/layout/SearchOverlay'\nexport { SmoothImage } from './components/SmoothImage'\nexport type { SmoothImageProps, SmoothImageVariant } from './components/SmoothImage'\nexport { ProductCard, pickProductCardImage } from './components/product/ProductCard'\n// Exported precisely because it was NOT, and the one store that needed a\n// different image order had nothing to wrap — so it cloned all 158 lines.\nexport { ProductGallery, orderGalleryImages } from './components/product/ProductGallery'\nexport { ProductEnquiryForm } from './components/product/ProductEnquiryForm'\nexport type { ProductEnquiryFormProps } from './components/product/ProductEnquiryForm'\nexport { OrderTrackingTimeline } from './components/order/OrderTrackingTimeline'\nexport { ProductGrid } from './components/collection/ProductGrid'\nexport { FiltersPanel } from './components/collection/FiltersPanel'\nexport type { CatalogFacetConfig } from './components/collection/FiltersPanel'\nexport { CartDrawer } from './components/cart/CartDrawer'\nexport { Price } from './components/Price'\nexport { PaymentTerms, resolvePaymentTerms } from './components/PaymentTerms'\nexport type { PaymentTermsProps, ResolvedPaymentTerms } from './components/PaymentTerms'\nexport { ProductSpecs } from './components/product/ProductSpecs'\nexport { ProductReviews } from './components/product/ProductReviews'\nexport type { ProductReview, StorefrontReviewsConfig } from './components/product/ProductReviews'\nexport { QuantityInput } from './components/cart/QuantityInput'\nexport { ProductOptionSelector } from './components/product/ProductOptionSelector'\nexport type { ProductOptionSelectorProps } from './components/product/ProductOptionSelector'\nexport {\n getProductOptionGroups,\n normalizeProductOptionSelection,\n formatProductOptionSelection,\n productOptionSelectionKey,\n resolveVariantForSelection,\n selectionPrice,\n resetProductOptionsDeprecationWarnings,\n} from './data/product-options'\nexport type { ProductOptionGroup, ProductOptionSelection } from './data/product-options'\n\n// Extension points (spine M7) — the storefront's declared behaviour seams.\nexport {\n CART_LINE_ANNOTATION_POINT,\n ORDER_METADATA_POINT,\n PRODUCT_CARD_BADGE_POINT,\n CHECKOUT_FIELD_POINT,\n BEFORE_PLACE_ORDER_VALVE,\n registerStorefrontExtensionPoints,\n resetStorefrontExtensionPoints,\n getCartLineAnnotations,\n getProductCardBadges,\n getCheckoutFieldContributions,\n collectOrderMetadata,\n runBeforePlaceOrderValve,\n} from './extend/extension-points'\nexport type {\n CartLineAnnotationInput,\n CartLineAnnotation,\n OrderMetadataInput,\n ProductCardBadgeInput,\n ProductCardBadge,\n CheckoutFieldInput,\n CheckoutFieldContribution,\n BeforePlaceOrderContext,\n} from './extend/extension-points'\n\n// Pages (for custom routing)\nexport { ContentPage } from './views/ContentPage'\nexport type { ContentPageProps } from './views/ContentPage'\nexport { CatalogPage } from './views/CatalogPage'\nexport { ProductDetailPage } from './views/ProductDetailPage'\nexport { CheckoutPage } from './views/CheckoutPage'\nexport { OrderConfirmationPage } from './views/OrderConfirmationPage'\nexport { MyPurchasesPage } from './views/MyPurchasesPage'\nexport { placeStorefrontOrder } from './workflows/checkout'\nexport type {\n PlaceStorefrontOrderInput,\n PlaceStorefrontOrderResult,\n StorefrontCheckoutAddress,\n StorefrontCheckoutCustomer,\n} from './workflows/checkout'\n\n// Theming + templates\nexport { StorefrontThemeStyle, themeToCss, THEME_SCALE_FIELDS, THEME_SCALE_VAR_PREFIX } from './lib/theme'\nexport type {\n ThemeScaleField,\n StorefrontTheme,\n StorefrontThemeColors,\n StorefrontThemeFont,\n StorefrontRadius,\n HeaderVariant,\n HeroVariant,\n CardStyle,\n ThemeCssOptions,\n} from './lib/theme'\nexport {\n CollectionHero,\n ProductSpotlight,\n MotifStrip,\n CollectionCta,\n} from './components/marketing/CollectionSections'\nexport type {\n CollectionHeroProps,\n ProductSpotlightProps,\n MotifStripProps,\n CollectionCtaProps,\n} from './components/marketing/CollectionSections'\nexport type { StorefrontSection, HomeSection, HomeConfig, HeroSlide, MediaCarouselItem, NavLink, FooterConfig } from './blocks/sections'\nexport { bannerPlaceholder, productPlaceholder, PLACEHOLDER_ASPECTS } from './blocks/sections'\n// The editor seam: a storefront in an editor's iframe reports which DOCUMENT\n// NODE was clicked, not which DOM element.\nexport { connectEditorBridge, reportNavigation, blockAt, EDITOR_MESSAGES } from './extend/editor-bridge'\nexport type { EditorBridgeOptions, PickedBlock } from './extend/editor-bridge'\n// From a picked path to the settings schema that draws its form — the first\n// consumer of the block schemas I1 has been emitting since M1.\nexport { blockAtPath, settingChange } from './blocks/block-at-path'\n// The settings overlay: a merchant edit reaches a live store without a build,\n// and the repo keeps authority over what the store IS (G2 — hybrid).\nexport { applyOverlay, pruneOverlay, isSettingPath, OVERLAYABLE_SECTIONS } from './document/overlay'\nexport type { StoreOverlay, ApplyOverlayResult, OverlayRejection } from './document/overlay'\nexport type { BlockAtPath, BlockAtPathError } from './blocks/block-at-path'\nexport {\n storefrontTemplates,\n mareTemplate,\n sertaoTemplate,\n voltTemplate,\n atelierTemplate,\n foodTemplate,\n} from './document/presets'\nexport type { StorefrontTemplate, StorefrontTemplateId } from './document/presets'\n\n// Home sections (for custom compositions)\nexport { HomePage, StorefrontSections } from './views/HomePage'\nexport { HeroSection } from './components/marketing/HeroSection'\nexport { MediaCarousel } from './components/marketing/MediaCarousel'\nexport type { MediaCarouselProps } from './components/marketing/MediaCarousel'\nexport { CategoryShowcase } from './components/collection/CategoryShowcase'\nexport { ProductRail } from './components/product/ProductRail'\nexport { ProductSlider } from './components/product/ProductSlider'\nexport type { ProductSliderProps } from './components/product/ProductSlider'\nexport {\n BenefitsRow,\n PromoBanner,\n ManifestoBlock,\n Testimonials,\n NewsletterBand,\n} from './components/marketing/MiscSections'\nexport { FormBlock, buildEnquiryFromForm } from './components/marketing/FormBlock'\nexport type { FormBlockProps, FormBlockField, FormBlockFieldType } from './components/marketing/FormBlock'\nexport { EntityListBlock, entityListBlockMeta } from './components/marketing/EntityList'\nexport { SealsBand, StoryQuote, ImageTiles, FaqSection } from './components/marketing/EditorialSections'\nexport type { SealItem, StoryQuoteProps, ImageTile, ImageTilesProps, FaqItem } from './components/marketing/EditorialSections'\nexport { StepsSection, CountdownBand, TierCards, nextMilestone } from './components/marketing/ConversionSections'\nexport type { StepItem, CountdownMilestone, TierItem } from './components/marketing/ConversionSections'\nexport type { BenefitItem } from './components/marketing/MiscSections'\nexport { StorefrontFooter } from './components/layout/StorefrontFooter'\n\n// Motion (core animation primitives)\nexport { Reveal, useInView, useScrolled, usePopOnChange, prefersReducedMotion } from './lib/motion'\nexport type { RevealProps } from './lib/motion'\n\n// Utilities\nexport { formatMoney, roundCents } from './lib/format'\nexport { TID } from './lib/testids'\nexport {\n productCardComponentContract,\n storefrontComponentContracts,\n} from './extend/component-selectors'\nexport type {\n ProductCardComponentContract,\n ProductDetailComponentContract,\n} from './extend/component-selectors'\n\n// ---------------------------------------------------------------------------\n// Front-door re-exports: storefront apps depend on @fayz-ai/storefront alone.\n// Runtime helpers come from @fayz-ai/core; UI / shop catalog / shop provider\n// live on their own subpaths (./ui, ./catalog, ./shop) to keep module graphs\n// separate. Mirrors the @fayz-ai/admin front door.\n// ---------------------------------------------------------------------------\n// renderApp is wrapped (not re-exported) so the 'storefront' scaffold registers\n// on first render instead of at import time — keeps the barrel side-effect-free.\nimport { renderApp as coreRenderApp } from '@fayz-ai/core'\nimport { registerStorefrontScaffold } from './app/scaffold'\n\nexport const renderApp: typeof coreRenderApp = (...args) => {\n registerStorefrontScaffold()\n return coreRenderApp(...args)\n}\n\nexport { getSupabaseClientOptional } from '@fayz-ai/core'\nexport { registerStorefrontScaffold } from './app/scaffold'\n\n// SSR hydration: the wire that carries server-resolved data into the browser.\nexport { serializePageData, readHydratedPageData, hydratedEntriesFor, PAGE_DATA_SCRIPT_ID } from './app/hydration'\nexport type { HydrationPayload } from './app/hydration'\n\n// Serving: which paths exist, and which of them a shared cache may hold.\nexport { isPublicPath, isKnownPath, resolveStorefrontRoute, storefrontPaths } from './app/serving'\nexport type { StorefrontRouteMatch } from './app/serving'\n\n// SEO descriptors — what a route tells a crawler about itself.\nexport { productSeo, pageSeo, productJsonLd, primaryImageUrl } from './lib/seo'\nexport type { StorefrontSeoContext } from './lib/seo'\n\n// Diagnostics: one rule set for a dev toolbar, a CI check and a prerender\n// validator, so a page cannot be graded three different ways.\nexport { auditStorefrontSeo, collectSeoAuditInput } from './diagnostics/seo-audit'\nexport type { SeoAuditInput, SeoAuditResult, SeoFinding, SeoFindingStatus } from './diagnostics/seo-audit'\n\n// Routing — the addressing scheme is injected, not assumed. See ./app/router.\nexport {\n useRoutePath,\n useNavigate,\n useRouterAdapter,\n useScrollToTopOnNavigate,\n shellRouterAdapter,\n StorefrontRouterProvider,\n} from './app/router'\n"]}
|