@growth-labs/store 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +41 -0
  2. package/dist/api.d.ts +30 -0
  3. package/dist/api.d.ts.map +1 -0
  4. package/dist/api.js +126 -0
  5. package/dist/api.js.map +1 -0
  6. package/dist/availability.d.ts +30 -0
  7. package/dist/availability.d.ts.map +1 -0
  8. package/dist/availability.js +47 -0
  9. package/dist/availability.js.map +1 -0
  10. package/dist/cache.d.ts +34 -0
  11. package/dist/cache.d.ts.map +1 -0
  12. package/dist/cache.js +80 -0
  13. package/dist/cache.js.map +1 -0
  14. package/dist/cart-client.d.ts +54 -0
  15. package/dist/cart-client.d.ts.map +1 -0
  16. package/dist/cart-client.js +347 -0
  17. package/dist/cart-client.js.map +1 -0
  18. package/dist/checkout-client.d.ts +20 -0
  19. package/dist/checkout-client.d.ts.map +1 -0
  20. package/dist/checkout-client.js +33 -0
  21. package/dist/checkout-client.js.map +1 -0
  22. package/dist/checkout-url.d.ts +25 -0
  23. package/dist/checkout-url.d.ts.map +1 -0
  24. package/dist/checkout-url.js +36 -0
  25. package/dist/checkout-url.js.map +1 -0
  26. package/dist/client.d.ts +459 -0
  27. package/dist/client.d.ts.map +1 -0
  28. package/dist/client.js +139 -0
  29. package/dist/client.js.map +1 -0
  30. package/dist/collections.d.ts +27 -0
  31. package/dist/collections.d.ts.map +1 -0
  32. package/dist/collections.js +24 -0
  33. package/dist/collections.js.map +1 -0
  34. package/dist/health.d.ts +17 -0
  35. package/dist/health.d.ts.map +1 -0
  36. package/dist/health.js +38 -0
  37. package/dist/health.js.map +1 -0
  38. package/dist/image.d.ts +25 -0
  39. package/dist/image.d.ts.map +1 -0
  40. package/dist/image.js +43 -0
  41. package/dist/image.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.d.ts.map +1 -0
  44. package/dist/index.js +48 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/options.d.ts +174 -0
  47. package/dist/options.d.ts.map +1 -0
  48. package/dist/options.js +59 -0
  49. package/dist/options.js.map +1 -0
  50. package/dist/product-card-variant.d.ts +13 -0
  51. package/dist/product-card-variant.d.ts.map +1 -0
  52. package/dist/product-card-variant.js +33 -0
  53. package/dist/product-card-variant.js.map +1 -0
  54. package/dist/routes/cart-bootstrap.d.ts +3 -0
  55. package/dist/routes/cart-bootstrap.d.ts.map +1 -0
  56. package/dist/routes/cart-bootstrap.js +5 -0
  57. package/dist/routes/cart-bootstrap.js.map +1 -0
  58. package/dist/routes/checkout.d.ts +4 -0
  59. package/dist/routes/checkout.d.ts.map +1 -0
  60. package/dist/routes/checkout.js +14 -0
  61. package/dist/routes/checkout.js.map +1 -0
  62. package/dist/routes/webhook.d.ts +4 -0
  63. package/dist/routes/webhook.d.ts.map +1 -0
  64. package/dist/routes/webhook.js +12 -0
  65. package/dist/routes/webhook.js.map +1 -0
  66. package/dist/state.d.ts +5 -0
  67. package/dist/state.d.ts.map +1 -0
  68. package/dist/state.js +14 -0
  69. package/dist/state.js.map +1 -0
  70. package/dist/types.d.ts +5111 -0
  71. package/dist/types.d.ts.map +1 -0
  72. package/dist/types.js +167 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/variant.d.ts +59 -0
  75. package/dist/variant.d.ts.map +1 -0
  76. package/dist/variant.js +81 -0
  77. package/dist/variant.js.map +1 -0
  78. package/dist/vite-plugin.d.ts +4 -0
  79. package/dist/vite-plugin.d.ts.map +1 -0
  80. package/dist/vite-plugin.js +24 -0
  81. package/dist/vite-plugin.js.map +1 -0
  82. package/package.json +59 -0
  83. package/src/analytics-window.d.ts +15 -0
  84. package/src/api.ts +184 -0
  85. package/src/availability.ts +65 -0
  86. package/src/cache.ts +118 -0
  87. package/src/cart-client.ts +423 -0
  88. package/src/checkout-client.ts +49 -0
  89. package/src/checkout-url.ts +52 -0
  90. package/src/client.ts +216 -0
  91. package/src/cloudflare-workers.d.ts +3 -0
  92. package/src/collections.ts +63 -0
  93. package/src/components/AddToCartButton.astro +146 -0
  94. package/src/components/CartDrawer.astro +276 -0
  95. package/src/components/CartIcon.astro +96 -0
  96. package/src/components/CollectionCard.astro +81 -0
  97. package/src/components/CurrencySelector.astro +73 -0
  98. package/src/components/Price.astro +34 -0
  99. package/src/components/ProductCard.astro +225 -0
  100. package/src/components/StoreCartPage.astro +219 -0
  101. package/src/components/StoreCollectionPage.astro +166 -0
  102. package/src/components/StoreIndexPage.astro +193 -0
  103. package/src/components/StoreProductPage.astro +296 -0
  104. package/src/components/VariantPicker.astro +190 -0
  105. package/src/health.ts +54 -0
  106. package/src/image.ts +58 -0
  107. package/src/index.ts +75 -0
  108. package/src/options.ts +74 -0
  109. package/src/product-card-variant.ts +47 -0
  110. package/src/routes/cart-bootstrap.ts +6 -0
  111. package/src/routes/checkout.ts +16 -0
  112. package/src/routes/webhook.ts +14 -0
  113. package/src/state.ts +20 -0
  114. package/src/types.ts +196 -0
  115. package/src/variant.ts +119 -0
  116. package/src/virtual.d.ts +6 -0
  117. package/src/vite-plugin.ts +27 -0
package/src/health.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { isWebhookConfigured } from './api.js'
2
+
3
+ /**
4
+ * Structurally matches `@growth-labs/health`'s `CustomCheck` without
5
+ * importing that package — packages don't import one another directly.
6
+ * Wire it in the consuming site's `astro.config.mjs`:
7
+ *
8
+ * health({ checks: [createStoreHealthCheck()] })
9
+ */
10
+ export interface StoreHealthCheckResult {
11
+ ok: boolean
12
+ ms: number
13
+ error?: string
14
+ }
15
+
16
+ /**
17
+ * Resolves `cloudflare:workers` via a dynamic import wrapped in try/catch,
18
+ * keeping the specifier off this module's static import graph — this file
19
+ * is re-exported from the package's main entry, and Node's default ESM
20
+ * loader rejects the `cloudflare:` scheme outright (it isn't a matter of
21
+ * the module being unresolvable at runtime, the loader refuses the scheme
22
+ * before resolution even starts). See scripts/verify-pure-node-import.mjs.
23
+ */
24
+ async function resolveCloudflareEnv(): Promise<{ FW_WEBHOOK_SECRET?: string } | null> {
25
+ try {
26
+ const mod = (await import('cloudflare:workers')) as { env?: Record<string, unknown> }
27
+ return (mod?.env as { FW_WEBHOOK_SECRET?: string } | undefined) ?? null
28
+ } catch {
29
+ return null
30
+ }
31
+ }
32
+
33
+ export function createStoreHealthCheck(): {
34
+ name: string
35
+ check: () => Promise<StoreHealthCheckResult>
36
+ } {
37
+ return {
38
+ name: 'store',
39
+ async check() {
40
+ const start = Date.now()
41
+ const env = await resolveCloudflareEnv()
42
+ const configured = isWebhookConfigured(env)
43
+ return {
44
+ ok: configured,
45
+ ms: Date.now() - start,
46
+ ...(configured
47
+ ? {}
48
+ : {
49
+ error: 'FW_WEBHOOK_SECRET is not set — order telemetry is silently dropping orders',
50
+ }),
51
+ }
52
+ },
53
+ }
54
+ }
package/src/image.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Route a remote image URL through Cloudflare Image Resizing.
3
+ *
4
+ * Uses the zone-local `/cdn-cgi/image/...` transform endpoint. Works on any
5
+ * custom domain whose zone has "Any origin" image resizing enabled. It does
6
+ * NOT work on the workers.dev subdomain, so non-matching URLs pass through
7
+ * unmodified.
8
+ *
9
+ * Opt-in via `imageTransform` on `StoreOptions`. Until a custom domain with
10
+ * Image Resizing is wired up, this stays off and raw CDN URLs ship as-is.
11
+ *
12
+ * `format=auto` picks AVIF/WebP/JPEG based on the request's `Accept` header.
13
+ */
14
+
15
+ import type { FwProduct } from './types.js'
16
+
17
+ export interface OptimizeFwImageOpts {
18
+ width: number
19
+ height?: number
20
+ quality?: number
21
+ fit?: 'cover' | 'contain' | 'scale-down' | 'crop' | 'pad'
22
+ /** From `StoreOptions.imageTransform`. Defaults to disabled. */
23
+ enabled?: boolean
24
+ }
25
+
26
+ const TRANSFORMABLE_HOSTS = ['cdn.fourthwall.com', 'storage.googleapis.com']
27
+
28
+ export function hasProductImages(product: Pick<FwProduct, 'images' | 'variants'>): boolean {
29
+ return (
30
+ product.images.some((image) => Boolean(image.url.trim())) ||
31
+ product.variants.some((variant) => variant.images?.some((image) => Boolean(image.url.trim())))
32
+ )
33
+ }
34
+
35
+ export function optimizeFwImage(
36
+ url: string | null | undefined,
37
+ opts: OptimizeFwImageOpts,
38
+ ): string | null {
39
+ if (!url) return null
40
+ if (!opts.enabled) return url
41
+ try {
42
+ const parsed = new URL(url)
43
+ if (!TRANSFORMABLE_HOSTS.some((h) => parsed.host.endsWith(h))) {
44
+ return url
45
+ }
46
+ } catch {
47
+ return url
48
+ }
49
+
50
+ const params: string[] = [
51
+ `width=${opts.width}`,
52
+ `quality=${opts.quality ?? 82}`,
53
+ `fit=${opts.fit ?? 'cover'}`,
54
+ 'format=auto',
55
+ ]
56
+ if (opts.height) params.push(`height=${opts.height}`)
57
+ return `/cdn-cgi/image/${params.join(',')}/${url}`
58
+ }
package/src/index.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { fileURLToPath } from 'node:url'
2
+ import type { AstroIntegration } from 'astro'
3
+ import { type StoreOptions, storeOptionsSchema } from './options.js'
4
+ import { _setConfig } from './state.js'
5
+ import { growthLabsStorePlugin } from './vite-plugin.js'
6
+
7
+ function isSourceEntrypoint(): boolean {
8
+ return typeof import.meta.url === 'string' && import.meta.url.endsWith('.ts')
9
+ }
10
+
11
+ const ENTRYPOINT_EXTENSION = isSourceEntrypoint() ? '.ts' : '.js'
12
+
13
+ function resolveEntrypoint(path: string): string {
14
+ return fileURLToPath(new URL(`${path}${ENTRYPOINT_EXTENSION}`, import.meta.url))
15
+ }
16
+
17
+ export default function store(userOptions: StoreOptions): AstroIntegration {
18
+ const options = storeOptionsSchema.parse(userOptions)
19
+
20
+ _setConfig(options)
21
+
22
+ return {
23
+ name: '@growth-labs/store',
24
+ hooks: {
25
+ 'astro:config:setup': ({ injectRoute, updateConfig }) => {
26
+ updateConfig({
27
+ vite: { plugins: [growthLabsStorePlugin(options)] },
28
+ })
29
+
30
+ injectRoute({
31
+ pattern: options.routes.checkoutPath,
32
+ entrypoint: resolveEntrypoint('./routes/checkout'),
33
+ })
34
+ injectRoute({
35
+ pattern: options.routes.webhookPath,
36
+ entrypoint: resolveEntrypoint('./routes/webhook'),
37
+ })
38
+ injectRoute({
39
+ pattern: options.routes.cartBootstrapPath,
40
+ entrypoint: resolveEntrypoint('./routes/cart-bootstrap'),
41
+ })
42
+ },
43
+ },
44
+ }
45
+ }
46
+
47
+ export type { CheckoutEnv, OrderPlacedHandler, WebhookEnv } from './api.js'
48
+ export { FOURTHWALL_SIGNATURE_HEADER, isWebhookConfigured, setOrderPlacedHandler } from './api.js'
49
+ export type { FourthwallAvailability, FourthwallAvailabilityStatus } from './availability.js'
50
+ export { resolveFourthwallAvailability } from './availability.js'
51
+ export { buildCacheKey, cachedJson, purgeCollectionCache, purgeProductCache } from './cache.js'
52
+ export { buildCheckoutUrl } from './checkout-url.js'
53
+ export type { FourthwallClient, FourthwallClientConfig } from './client.js'
54
+ export { createFourthwallClient } from './client.js'
55
+ export type { StoreCollection, StoreCollectionGrouping } from './collections.js'
56
+ export {
57
+ filterPublishedCollections,
58
+ getGroupedCollections,
59
+ getStoreCollection,
60
+ resolveProductKind,
61
+ } from './collections.js'
62
+ export { createStoreHealthCheck } from './health.js'
63
+ export { hasProductImages, optimizeFwImage } from './image.js'
64
+ export type { ResolvedStoreOptions, StoreOptions } from './options.js'
65
+ export { storeOptionsSchema } from './options.js'
66
+ export type * from './types.js'
67
+ export type { MerchantReturnPolicy, StoreVariantClientData } from './variant.js'
68
+ export {
69
+ buildStoreProductJsonLd,
70
+ buildStoreVariantClientData,
71
+ createStoreAddToCartAvailabilityState,
72
+ isStoreVariantAvailable,
73
+ normalizeStoreVariantSku,
74
+ selectStoreVariant,
75
+ } from './variant.js'
package/src/options.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { z } from 'zod'
2
+
3
+ const storeCollectionSchema = z.object({
4
+ handle: z.string().min(1),
5
+ name: z.string().min(1),
6
+ description: z.string().optional(),
7
+ coverImagePath: z.string().optional(),
8
+ grouping: z.enum(['division', 'type']).optional(),
9
+ hidden: z.boolean().default(false),
10
+ productKind: z.string().default('merch'),
11
+ })
12
+
13
+ const merchantReturnPolicySchema = z.object({
14
+ applicableCountry: z.string().min(1),
15
+ returnPolicyCategory: z.string().min(1),
16
+ })
17
+
18
+ export const storeOptionsSchema = z.object({
19
+ /** Shown in the store JSON-LD `brand.name` and page copy. */
20
+ brandName: z.string().min(1),
21
+
22
+ /**
23
+ * The Fourthwall catalogue for this site, reconciled into config instead
24
+ * of a per-site fork. An empty array is valid — a site without a
25
+ * Fourthwall shop yet (bigbrain, pre-launch) still gets the health check
26
+ * and routes; checkout stays disabled until `checkoutEnabled` is true.
27
+ */
28
+ collections: z.array(storeCollectionSchema).default([]),
29
+
30
+ /** Fourthwall collection handle treated as "everything" (default `"all"`). */
31
+ catalogueHandle: z.string().default('all'),
32
+
33
+ /**
34
+ * How many products the landing page shows by default. `"all"` (the
35
+ * default) paginates through the full Fourthwall catalogue — sites used
36
+ * to hardcode a 3-product teaser here, which is the "3/11 products
37
+ * shown" defect the channel-store-recovery review found.
38
+ */
39
+ landingProductCount: z.union([z.literal('all'), z.number().int().positive()]).default('all'),
40
+
41
+ defaultCurrency: z.string().default('USD'),
42
+ supportedCurrencies: z.array(z.string()).default(['USD', 'GBP', 'EUR', 'CAD', 'AUD']),
43
+
44
+ /** UTM/analytics origin marker forwarded to Fourthwall checkout, e.g. `"megaprojects"`. */
45
+ cartOrigin: z.string().min(1),
46
+
47
+ /**
48
+ * Whether this site's Fourthwall shop is live. When false, product and
49
+ * collection pages still render (catalogue browsing works) but add-to-cart
50
+ * and checkout are disabled with an explicit "coming soon" state — never
51
+ * fixture/fake products. Used by bigbrain until its shop exists.
52
+ */
53
+ checkoutEnabled: z.boolean().default(true),
54
+
55
+ merchantReturnPolicy: merchantReturnPolicySchema.optional(),
56
+
57
+ imageTransform: z
58
+ .object({
59
+ enabled: z.boolean().default(false),
60
+ })
61
+ .default({}),
62
+
63
+ routes: z
64
+ .object({
65
+ checkoutPath: z.string().default('/api/store/checkout'),
66
+ webhookPath: z.string().default('/api/store/webhook'),
67
+ cartBootstrapPath: z.string().default('/api/store/cart-bootstrap'),
68
+ })
69
+ .default({}),
70
+ })
71
+
72
+ export type StoreOptions = z.input<typeof storeOptionsSchema>
73
+ export type ResolvedStoreOptions = z.output<typeof storeOptionsSchema>
74
+ export type StoreCollectionInput = z.input<typeof storeCollectionSchema>
@@ -0,0 +1,47 @@
1
+ import type { FwImage, FwPrice, FwProduct, FwVariant } from './types.js'
2
+ import { isStoreVariantAvailable } from './variant.js'
3
+
4
+ export interface ProductCardColorOption {
5
+ variantId: string
6
+ colorName: string
7
+ swatch: string | null
8
+ price: FwPrice
9
+ compareAt: FwPrice | null
10
+ image: FwImage | null
11
+ hoverImage: FwImage | null
12
+ }
13
+
14
+ export function getProductCardColorOptions(product: FwProduct): ProductCardColorOption[] {
15
+ const byColor = new Map<string, FwVariant>()
16
+
17
+ for (const variant of product.variants) {
18
+ const sellable = isStoreVariantAvailable(variant)
19
+ const colorName = variant.attributes?.color?.name
20
+ if (!colorName || !sellable) continue
21
+
22
+ if (!byColor.has(colorName)) {
23
+ byColor.set(colorName, variant)
24
+ }
25
+ }
26
+
27
+ return [...byColor.entries()].map(([colorName, variant]) => {
28
+ const images = variant.images?.length ? variant.images : product.images
29
+ return {
30
+ variantId: variant.id,
31
+ colorName,
32
+ swatch: variant.attributes?.color?.swatch ?? null,
33
+ price: variant.unitPrice,
34
+ compareAt: variant.compareAtPrice ?? null,
35
+ image: images[0] ?? null,
36
+ hoverImage: images[1] ?? null,
37
+ }
38
+ })
39
+ }
40
+
41
+ export function formatStorePrice(price: FwPrice): string {
42
+ return new Intl.NumberFormat('en-US', {
43
+ style: 'currency',
44
+ currency: price.currency,
45
+ maximumFractionDigits: Number.isInteger(price.value) ? 0 : 2,
46
+ }).format(price.value)
47
+ }
@@ -0,0 +1,6 @@
1
+ import type { APIContext } from 'astro'
2
+ import { getConfig } from '../state.js'
3
+
4
+ export async function GET(_context: APIContext): Promise<Response> {
5
+ return Response.json({ currency: getConfig().defaultCurrency })
6
+ }
@@ -0,0 +1,16 @@
1
+ import { env as cloudflareEnv } from 'cloudflare:workers'
2
+ import type { APIContext } from 'astro'
3
+ import { type CheckoutEnv, createCheckoutResponse } from '../api.js'
4
+ import { getConfig } from '../state.js'
5
+
6
+ export async function POST(context: APIContext): Promise<Response> {
7
+ return createCheckoutResponse({
8
+ request: context.request,
9
+ env: cloudflareEnv as CheckoutEnv,
10
+ cartOrigin: getConfig().cartOrigin,
11
+ })
12
+ }
13
+
14
+ export function ALL(): Response {
15
+ return Response.json({ error: 'Method not allowed' }, { status: 405 })
16
+ }
@@ -0,0 +1,14 @@
1
+ import { env as cloudflareEnv } from 'cloudflare:workers'
2
+ import type { APIContext } from 'astro'
3
+ import { createWebhookResponse, type WebhookEnv } from '../api.js'
4
+
5
+ export async function POST(context: APIContext): Promise<Response> {
6
+ return createWebhookResponse({
7
+ request: context.request,
8
+ env: cloudflareEnv as WebhookEnv,
9
+ })
10
+ }
11
+
12
+ export function ALL(): Response {
13
+ return Response.json({ error: 'Method not allowed' }, { status: 405 })
14
+ }
package/src/state.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { ResolvedStoreOptions } from './options.js'
2
+
3
+ let config: ResolvedStoreOptions | null = null
4
+
5
+ export function _setConfig(next: ResolvedStoreOptions): void {
6
+ config = next
7
+ }
8
+
9
+ export function getConfig(): ResolvedStoreOptions {
10
+ if (!config) {
11
+ throw new Error(
12
+ '@growth-labs/store: config accessed before the integration ran. Add store() to astro.config.mjs.',
13
+ )
14
+ }
15
+ return config
16
+ }
17
+
18
+ export function getConfigOrNull(): ResolvedStoreOptions | null {
19
+ return config
20
+ }
package/src/types.ts ADDED
@@ -0,0 +1,196 @@
1
+ import { z } from 'zod'
2
+
3
+ export const FwPriceSchema = z.object({
4
+ value: z.number(),
5
+ currency: z.string(),
6
+ })
7
+ export type FwPrice = z.infer<typeof FwPriceSchema>
8
+
9
+ export const FwImageSchema = z.object({
10
+ id: z.string().optional(),
11
+ url: z.string(),
12
+ alt: z.string().optional(),
13
+ width: z.number().optional(),
14
+ height: z.number().optional(),
15
+ })
16
+ export type FwImage = z.infer<typeof FwImageSchema>
17
+
18
+ export const FwVariantAttributeSchema = z.object({
19
+ name: z.string(),
20
+ value: z.string(),
21
+ })
22
+ export type FwVariantAttribute = z.infer<typeof FwVariantAttributeSchema>
23
+
24
+ export const FwVariantSchema = z.object({
25
+ id: z.string(),
26
+ name: z.string().optional(),
27
+ sku: z.string().optional(),
28
+ unitPrice: FwPriceSchema,
29
+ price: FwPriceSchema.optional(),
30
+ compareAtPrice: FwPriceSchema.nullable().optional(),
31
+ // Keep the provider payload intact. Availability is validated and normalized
32
+ // once by resolveFourthwallAvailability so unknown future arms can fail closed.
33
+ stock: z.unknown().optional(),
34
+ attributes: z
35
+ .object({
36
+ description: z.string().optional(),
37
+ color: z
38
+ .object({ name: z.string().optional(), swatch: z.string().optional() })
39
+ .nullable()
40
+ .optional(),
41
+ size: z.object({ name: z.string().optional() }).nullable().optional(),
42
+ })
43
+ .passthrough()
44
+ .optional(),
45
+ images: z.array(FwImageSchema).optional(),
46
+ })
47
+ export type FwVariant = z.infer<typeof FwVariantSchema>
48
+
49
+ export const FwProductSchema = z.object({
50
+ id: z.string(),
51
+ name: z.string(),
52
+ slug: z.string(),
53
+ description: z.string().optional(),
54
+ descriptionHtml: z.string().optional(),
55
+ state: z.object({ type: z.string() }).optional(),
56
+ access: z.object({ type: z.string() }).optional(),
57
+ images: z.array(FwImageSchema),
58
+ variants: z.array(FwVariantSchema),
59
+ createdAt: z.string().optional(),
60
+ updatedAt: z.string().optional(),
61
+ })
62
+ export type FwProduct = z.infer<typeof FwProductSchema>
63
+
64
+ export const FwCollectionSchema = z.object({
65
+ id: z.string(),
66
+ slug: z.string(),
67
+ name: z.string(),
68
+ description: z.string().optional(),
69
+ })
70
+ export type FwCollection = z.infer<typeof FwCollectionSchema>
71
+
72
+ export const FwPagingSchema = z.object({
73
+ hasNextPage: z.boolean(),
74
+ nextPageToken: z.string().nullable().optional(),
75
+ })
76
+ export type FwPaging = z.infer<typeof FwPagingSchema>
77
+
78
+ export const FwCollectionProductsSchema = z.object({
79
+ results: z.array(FwProductSchema),
80
+ paging: FwPagingSchema,
81
+ })
82
+ export type FwCollectionProducts = z.infer<typeof FwCollectionProductsSchema>
83
+
84
+ export const FwCartItemSchema = z.object({
85
+ variant: FwVariantSchema,
86
+ quantity: z.number(),
87
+ })
88
+ export type FwCartItem = z.infer<typeof FwCartItemSchema>
89
+
90
+ export const FwCartSchema = z.object({
91
+ id: z.string(),
92
+ items: z.array(FwCartItemSchema),
93
+ })
94
+ export type FwCart = z.infer<typeof FwCartSchema>
95
+
96
+ export const FwShopSchema = z.object({
97
+ id: z.string().optional(),
98
+ name: z.string().optional(),
99
+ currencies: z.array(z.string()).optional(),
100
+ checkoutDomain: z.string().optional(),
101
+ publicDomain: z.string().optional(),
102
+ })
103
+ export type FwShop = z.infer<typeof FwShopSchema>
104
+
105
+ export const FwOrderLineSchema = z.object({
106
+ variantId: z.string(),
107
+ productId: z.string().optional(),
108
+ sku: z.string().optional(),
109
+ quantity: z.number(),
110
+ unitPrice: FwPriceSchema,
111
+ name: z.string().optional(),
112
+ })
113
+ export type FwOrderLine = z.infer<typeof FwOrderLineSchema>
114
+
115
+ export const FwOrderOfferSchema = z
116
+ .object({
117
+ id: z.string(),
118
+ name: z.string().optional(),
119
+ slug: z.string().optional(),
120
+ variant: z
121
+ .object({
122
+ id: z.string(),
123
+ name: z.string().optional(),
124
+ sku: z.string().optional(),
125
+ unitPrice: FwPriceSchema.optional(),
126
+ quantity: z.number().optional(),
127
+ price: FwPriceSchema.optional(),
128
+ attributes: z.record(z.string(), z.unknown()).optional(),
129
+ })
130
+ .passthrough(),
131
+ })
132
+ .passthrough()
133
+ export type FwOrderOffer = z.infer<typeof FwOrderOfferSchema>
134
+
135
+ export const FwOrderPlacedEventSchema = z
136
+ .object({
137
+ id: z.string(),
138
+ webhookId: z.string().optional(),
139
+ type: z.literal('ORDER_PLACED'),
140
+ shopId: z.string().optional(),
141
+ apiVersion: z.string().optional(),
142
+ createdAt: z.string().optional(),
143
+ testMode: z.boolean().optional(),
144
+ data: z
145
+ .object({
146
+ id: z.string(),
147
+ shopId: z.string().optional(),
148
+ friendlyId: z.string().optional(),
149
+ checkoutId: z.string().optional(),
150
+ email: z.string().email(),
151
+ emailMarketingOptIn: z.boolean().optional(),
152
+ message: z.string().optional(),
153
+ amounts: z
154
+ .object({
155
+ total: FwPriceSchema,
156
+ })
157
+ .passthrough(),
158
+ status: z.string().optional(),
159
+ couponCode: z.string().nullable().optional(),
160
+ metadata: z.record(z.string(), z.unknown()).optional(),
161
+ offers: z.array(FwOrderOfferSchema).default([]),
162
+ trackingParams: z
163
+ .object({
164
+ utm_source: z.string().optional(),
165
+ utm_medium: z.string().optional(),
166
+ utm_campaign: z.string().optional(),
167
+ utm_content: z.string().optional(),
168
+ utm_term: z.string().optional(),
169
+ fbc: z.string().optional(),
170
+ fbp: z.string().optional(),
171
+ })
172
+ .passthrough()
173
+ .optional(),
174
+ })
175
+ .passthrough(),
176
+ })
177
+ .passthrough()
178
+ export type FwOrderPlacedEvent = z.infer<typeof FwOrderPlacedEventSchema>
179
+
180
+ /**
181
+ * Canonical error from the Fourthwall API, carrying HTTP status.
182
+ * Thrown by the client so call sites can branch on `.status`.
183
+ */
184
+ export class FourthwallError extends Error {
185
+ public readonly status: number
186
+ public readonly url: string
187
+ public readonly body?: unknown
188
+
189
+ constructor(status: number, url: string, message: string, body?: unknown) {
190
+ super(message)
191
+ this.name = 'FourthwallError'
192
+ this.status = status
193
+ this.url = url
194
+ this.body = body
195
+ }
196
+ }
package/src/variant.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { z } from 'zod'
2
+ import { resolveFourthwallAvailability } from './availability.js'
3
+ import type { FwImage, FwProduct, FwVariant } from './types.js'
4
+
5
+ const FourthwallVariantIdSchema = z.string().uuid()
6
+
7
+ export function isStoreVariantAvailable(variant: FwVariant): boolean {
8
+ return resolveFourthwallAvailability(variant).purchasable
9
+ }
10
+
11
+ export function normalizeStoreVariantSku(sku: string | null | undefined): string | undefined {
12
+ const normalized = sku?.trim()
13
+ return normalized ? normalized : undefined
14
+ }
15
+
16
+ export interface StoreVariantClientData {
17
+ sku?: string
18
+ name: string
19
+ priceValue: number
20
+ priceCurrency: string
21
+ available: boolean
22
+ }
23
+
24
+ export function buildStoreVariantClientData(variant: FwVariant): StoreVariantClientData {
25
+ const sku = normalizeStoreVariantSku(variant.sku)
26
+ return {
27
+ ...(sku ? { sku } : {}),
28
+ name: variant.name ?? '',
29
+ priceValue: variant.unitPrice.value,
30
+ priceCurrency: variant.unitPrice.currency,
31
+ available: isStoreVariantAvailable(variant),
32
+ }
33
+ }
34
+
35
+ export interface StoreAddToCartAvailabilityState {
36
+ recordSelection(available: boolean | undefined): boolean
37
+ shouldDisable(): boolean
38
+ }
39
+
40
+ export function createStoreAddToCartAvailabilityState(
41
+ initialAvailable: boolean,
42
+ ): StoreAddToCartAvailabilityState {
43
+ let selectedAvailable = initialAvailable === true
44
+ const shouldDisable = () => !selectedAvailable
45
+ return {
46
+ recordSelection(available) {
47
+ selectedAvailable = available === true
48
+ return shouldDisable()
49
+ },
50
+ shouldDisable,
51
+ }
52
+ }
53
+
54
+ export function selectStoreVariant(
55
+ product: FwProduct,
56
+ requestedVariantId: string | null | undefined,
57
+ ): FwVariant | null {
58
+ if (requestedVariantId == null) return product.variants[0] ?? null
59
+ if (!FourthwallVariantIdSchema.safeParse(requestedVariantId).success) return null
60
+ return product.variants.find((variant) => variant.id === requestedVariantId) ?? null
61
+ }
62
+
63
+ export interface MerchantReturnPolicy {
64
+ applicableCountry: string
65
+ /** Schema.org `MerchantReturnPolicy` category, e.g. `"MerchantReturnFiniteReturnWindow"`. */
66
+ returnPolicyCategory: string
67
+ }
68
+
69
+ export interface BuildStoreProductJsonLdInput {
70
+ brandName: string
71
+ canonicalProductUrl: string
72
+ product: FwProduct
73
+ variant: FwVariant
74
+ requestedVariant: boolean
75
+ images: readonly FwImage[]
76
+ merchantReturnPolicy?: MerchantReturnPolicy
77
+ }
78
+
79
+ export function buildStoreProductJsonLd(input: BuildStoreProductJsonLdInput) {
80
+ const offerUrl = new URL(input.canonicalProductUrl)
81
+ if (input.requestedVariant) offerUrl.searchParams.set('variant', input.variant.id)
82
+ const imageUrls = [...new Set(input.images.map((image) => image.url).filter(Boolean))]
83
+ const color = input.variant.attributes?.color?.name
84
+ const size = input.variant.attributes?.size?.name
85
+ const sku = normalizeStoreVariantSku(input.variant.sku)
86
+ const availability = resolveFourthwallAvailability(input.variant)
87
+ return {
88
+ '@context': 'https://schema.org',
89
+ '@type': 'Product',
90
+ name: input.product.name,
91
+ description: input.product.description ?? undefined,
92
+ image: imageUrls,
93
+ ...(sku ? { sku } : {}),
94
+ brand: { '@type': 'Brand', name: input.brandName },
95
+ ...(color ? { color } : {}),
96
+ ...(size ? { size } : {}),
97
+ ...(availability.offerAvailability === null
98
+ ? {}
99
+ : {
100
+ offers: {
101
+ '@type': 'Offer',
102
+ price: input.variant.unitPrice.value,
103
+ priceCurrency: input.variant.unitPrice.currency,
104
+ availability: availability.offerAvailability,
105
+ url: offerUrl.toString(),
106
+ itemCondition: 'https://schema.org/NewCondition',
107
+ ...(input.merchantReturnPolicy
108
+ ? {
109
+ hasMerchantReturnPolicy: {
110
+ '@type': 'MerchantReturnPolicy',
111
+ applicableCountry: input.merchantReturnPolicy.applicableCountry,
112
+ returnPolicyCategory: `https://schema.org/${input.merchantReturnPolicy.returnPolicyCategory}`,
113
+ },
114
+ }
115
+ : {}),
116
+ },
117
+ }),
118
+ }
119
+ }
@@ -0,0 +1,6 @@
1
+ declare module 'virtual:growth-labs/store/config' {
2
+ import type { ResolvedStoreOptions } from '@growth-labs/store'
3
+ export const config: ResolvedStoreOptions
4
+ export function getConfig(): ResolvedStoreOptions
5
+ export function getConfigOrNull(): ResolvedStoreOptions | null
6
+ }