@growth-labs/store 0.1.0 → 0.2.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.
Files changed (48) hide show
  1. package/dist/api.d.ts.map +1 -1
  2. package/dist/api.js +5 -0
  3. package/dist/api.js.map +1 -1
  4. package/dist/health.d.ts +20 -1
  5. package/dist/health.d.ts.map +1 -1
  6. package/dist/health.js +68 -10
  7. package/dist/health.js.map +1 -1
  8. package/dist/index.d.ts +3 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +13 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/options.d.ts +107 -1
  13. package/dist/options.d.ts.map +1 -1
  14. package/dist/options.js +24 -1
  15. package/dist/options.js.map +1 -1
  16. package/dist/orders.d.ts +34 -0
  17. package/dist/orders.d.ts.map +1 -0
  18. package/dist/orders.js +169 -0
  19. package/dist/orders.js.map +1 -0
  20. package/dist/routes/cart-bootstrap.d.ts.map +1 -1
  21. package/dist/routes/cart-bootstrap.js +2 -1
  22. package/dist/routes/cart-bootstrap.js.map +1 -1
  23. package/dist/routes/checkout.d.ts.map +1 -1
  24. package/dist/routes/checkout.js +2 -1
  25. package/dist/routes/checkout.js.map +1 -1
  26. package/dist/routes/webhook.d.ts.map +1 -1
  27. package/dist/routes/webhook.js +29 -1
  28. package/dist/routes/webhook.js.map +1 -1
  29. package/dist/state.d.ts +2 -2
  30. package/dist/state.d.ts.map +1 -1
  31. package/dist/state.js +32 -2
  32. package/dist/state.js.map +1 -1
  33. package/migrations/0001_gl_store_orders.sql +23 -0
  34. package/package.json +2 -1
  35. package/src/api.ts +5 -0
  36. package/src/components/StoreCartPage.astro +1 -1
  37. package/src/components/StoreCollectionPage.astro +1 -1
  38. package/src/components/StoreIndexPage.astro +1 -1
  39. package/src/components/StoreProductPage.astro +1 -1
  40. package/src/health.ts +93 -12
  41. package/src/index.ts +18 -0
  42. package/src/options.ts +26 -1
  43. package/src/orders.ts +223 -0
  44. package/src/routes/cart-bootstrap.ts +2 -1
  45. package/src/routes/checkout.ts +2 -1
  46. package/src/routes/webhook.ts +31 -1
  47. package/src/state.ts +34 -2
  48. package/src/virtual.d.ts +2 -2
package/src/options.ts CHANGED
@@ -15,7 +15,7 @@ const merchantReturnPolicySchema = z.object({
15
15
  returnPolicyCategory: z.string().min(1),
16
16
  })
17
17
 
18
- export const storeOptionsSchema = z.object({
18
+ const baseStoreOptionsSchema = z.object({
19
19
  /** Shown in the store JSON-LD `brand.name` and page copy. */
20
20
  brandName: z.string().min(1),
21
21
 
@@ -67,8 +67,33 @@ export const storeOptionsSchema = z.object({
67
67
  cartBootstrapPath: z.string().default('/api/store/cart-bootstrap'),
68
68
  })
69
69
  .default({}),
70
+
71
+ /**
72
+ * B2 order telemetry: every verified `ORDER_PLACED` webhook is persisted to
73
+ * the package-owned `gl_store_orders` D1 table and mirrored to WAE as
74
+ * `store_order_placed`. `siteId` defaults to `cartOrigin` — the site
75
+ * already has exactly one identity for attribution, so this avoids asking
76
+ * for the same value twice.
77
+ */
78
+ telemetry: z
79
+ .object({
80
+ d1Binding: z.string().default('DB'),
81
+ waeBinding: z.string().default('ANALYTICS'),
82
+ siteId: z.string().min(1).optional(),
83
+ /** Health check goes red when a site with prior orders has ingested none for this many days. */
84
+ staleOrderAlertDays: z.number().int().positive().default(7),
85
+ })
86
+ .default({}),
70
87
  })
71
88
 
89
+ export const storeOptionsSchema = baseStoreOptionsSchema.transform((options) => ({
90
+ ...options,
91
+ telemetry: {
92
+ ...options.telemetry,
93
+ siteId: options.telemetry.siteId ?? options.cartOrigin,
94
+ },
95
+ }))
96
+
72
97
  export type StoreOptions = z.input<typeof storeOptionsSchema>
73
98
  export type ResolvedStoreOptions = z.output<typeof storeOptionsSchema>
74
99
  export type StoreCollectionInput = z.input<typeof storeCollectionSchema>
package/src/orders.ts ADDED
@@ -0,0 +1,223 @@
1
+ import type { OrderPlacedHandler } from './api.js'
2
+ import type { FwOrderPlacedEvent } from './types.js'
3
+
4
+ export interface OrderTelemetryOptions {
5
+ d1Binding: string
6
+ waeBinding: string
7
+ siteId: string
8
+ }
9
+
10
+ interface D1PreparedStatement {
11
+ bind(...values: unknown[]): D1PreparedStatement
12
+ run(): Promise<unknown>
13
+ }
14
+
15
+ interface D1LikeDatabase {
16
+ prepare(query: string): D1PreparedStatement
17
+ }
18
+
19
+ interface WaeLikeBinding {
20
+ writeDataPoint(dataPoint: {
21
+ blobs: string[]
22
+ doubles: number[]
23
+ indexes: string[]
24
+ }): unknown | Promise<unknown>
25
+ }
26
+
27
+ /**
28
+ * Resolves `cloudflare:workers` via a dynamic import wrapped in try/catch —
29
+ * `createD1OrderHandler` is wired from `index.ts`'s `astro:config:setup`
30
+ * hook, which runs under plain Node during `astro build`/`astro check`.
31
+ * See health.ts and scripts/verify-pure-node-import.mjs for the same pattern.
32
+ */
33
+ async function resolveTelemetryEnv(): Promise<Record<string, unknown> | null> {
34
+ try {
35
+ const mod = (await import('cloudflare:workers')) as { env?: Record<string, unknown> }
36
+ return mod?.env ?? null
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+
42
+ async function sha256Hex(input: string): Promise<string> {
43
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input))
44
+ return Array.from(new Uint8Array(digest))
45
+ .map((byte) => byte.toString(16).padStart(2, '0'))
46
+ .join('')
47
+ }
48
+
49
+ function orderItemCount(event: FwOrderPlacedEvent): number {
50
+ return event.data.offers.reduce((total, offer) => total + (offer.variant.quantity ?? 0), 0)
51
+ }
52
+
53
+ function buildItemsJson(event: FwOrderPlacedEvent): string {
54
+ return JSON.stringify(
55
+ event.data.offers.map((offer) => ({
56
+ offerId: offer.id,
57
+ name: offer.name ?? null,
58
+ variantId: offer.variant.id,
59
+ sku: offer.variant.sku ?? null,
60
+ quantity: offer.variant.quantity ?? 0,
61
+ unitPrice: (offer.variant.unitPrice ?? offer.variant.price)?.value ?? null,
62
+ })),
63
+ )
64
+ }
65
+
66
+ function cartOriginFor(event: FwOrderPlacedEvent, fallback: string): string {
67
+ const metadata = event.data.metadata
68
+ const fromMetadata =
69
+ metadata && typeof metadata.cart_origin === 'string'
70
+ ? (metadata.cart_origin as string)
71
+ : undefined
72
+ return fromMetadata ?? fallback
73
+ }
74
+
75
+ /**
76
+ * Mirrors `@growth-labs/analytics`'s `store_order_placed` blob/double layout
77
+ * (packages don't import each other — PLATFORM_PATTERNS.md — so this
78
+ * replicates the slot mapping from `buildWAEDataPoint`/`buildStorefrontWAEParams`
79
+ * rather than calling into that package).
80
+ */
81
+ export function buildStoreOrderWAEDataPoint(
82
+ options: OrderTelemetryOptions,
83
+ event: FwOrderPlacedEvent,
84
+ rawPayloadHash: string,
85
+ ): { blobs: string[]; doubles: number[]; indexes: string[] } {
86
+ const utm = event.data.trackingParams ?? {}
87
+ const labelExtras: Record<string, string | number> = {
88
+ cartOrigin: cartOriginFor(event, options.siteId),
89
+ rawPayloadHash,
90
+ itemCount: orderItemCount(event),
91
+ }
92
+ if (event.data.email) labelExtras.customerEmail = event.data.email
93
+
94
+ return {
95
+ blobs: [
96
+ 'store_order_placed', // blob1 eventName
97
+ options.siteId, // blob2 siteId
98
+ '', // blob3 visitorId
99
+ '', // blob4 sessionId
100
+ '', // blob5 pageUrl
101
+ '', // blob6 pagePath
102
+ '', // blob7 referrer
103
+ utm.utm_source ?? '', // blob8 utmSource
104
+ utm.utm_medium ?? '', // blob9 utmMedium
105
+ utm.utm_campaign ?? '', // blob10 utmCampaign
106
+ '', // blob11 derivedSource
107
+ '', // blob12 country
108
+ '', // blob13 deviceType
109
+ '', // blob14 browserName
110
+ '', // blob15 osName
111
+ event.data.id, // blob16 contentSlug = orderId
112
+ 'order', // blob17 contentType
113
+ 'storefront', // blob18 eventCategory
114
+ JSON.stringify(labelExtras), // blob19 eventLabel
115
+ 'false', // blob20 isNewVisitor
116
+ ],
117
+ doubles: [
118
+ Date.now(), // double1 timestamp
119
+ orderItemCount(event), // double2 eventValue
120
+ 0,
121
+ 0,
122
+ 0,
123
+ 0,
124
+ 0,
125
+ 0,
126
+ 0, // double3-9
127
+ 0, // double10 productPrice (not applicable to a whole order)
128
+ event.data.amounts.total.value, // double11 cartValue
129
+ 0,
130
+ 0,
131
+ 0,
132
+ 0,
133
+ 0,
134
+ 0,
135
+ 0,
136
+ 0,
137
+ 0, // double12-20
138
+ ],
139
+ indexes: ['store_order_placed'],
140
+ }
141
+ }
142
+
143
+ /**
144
+ * B2's order-telemetry handler, wired via `setOrderPlacedHandler` from
145
+ * `index.ts` for every consuming site automatically: persists every verified
146
+ * `ORDER_PLACED` webhook to the package-owned `gl_store_orders` D1 table
147
+ * (migrations/0001_gl_store_orders.sql) and emits the mirrored WAE point.
148
+ *
149
+ * The D1 write and the WAE write are independent best-effort operations —
150
+ * a WAE outage must not drop the durable order row, and vice versa. Both
151
+ * failure paths log a structured, greppable event rather than throwing:
152
+ * `createWebhookResponse` has already validated the HMAC signature and is
153
+ * about to return 200 to Fourthwall by the time this handler runs, so
154
+ * throwing here would not trigger a useful retry, only an unhandled
155
+ * rejection after the response was already sent.
156
+ */
157
+ export function createD1OrderHandler(options: OrderTelemetryOptions): OrderPlacedHandler {
158
+ return async (event: FwOrderPlacedEvent) => {
159
+ const env = await resolveTelemetryEnv()
160
+ if (!env) {
161
+ console.error('store.order_telemetry.env_unavailable', { orderId: event.data.id })
162
+ return
163
+ }
164
+
165
+ const rawPayloadHash = await sha256Hex(JSON.stringify(event))
166
+
167
+ const db = env[options.d1Binding] as D1LikeDatabase | undefined
168
+ if (!db) {
169
+ console.error('store.order_telemetry.d1_binding_missing', {
170
+ binding: options.d1Binding,
171
+ orderId: event.data.id,
172
+ })
173
+ } else {
174
+ try {
175
+ await db
176
+ .prepare(
177
+ `INSERT OR IGNORE INTO gl_store_orders
178
+ (id, shop_id, site_id, amount, currency, items_json, cart_origin, utm_source, utm_medium, utm_campaign, utm_term, utm_content, raw_payload_hash, received_at)
179
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
180
+ )
181
+ .bind(
182
+ event.data.id,
183
+ event.data.shopId ?? event.shopId ?? null,
184
+ options.siteId,
185
+ event.data.amounts.total.value,
186
+ event.data.amounts.total.currency,
187
+ buildItemsJson(event),
188
+ cartOriginFor(event, options.siteId),
189
+ event.data.trackingParams?.utm_source ?? null,
190
+ event.data.trackingParams?.utm_medium ?? null,
191
+ event.data.trackingParams?.utm_campaign ?? null,
192
+ event.data.trackingParams?.utm_term ?? null,
193
+ event.data.trackingParams?.utm_content ?? null,
194
+ rawPayloadHash,
195
+ Date.now(),
196
+ )
197
+ .run()
198
+ } catch (error) {
199
+ console.error('store.order_telemetry.d1_write_failed', {
200
+ orderId: event.data.id,
201
+ error: error instanceof Error ? error.message : String(error),
202
+ })
203
+ }
204
+ }
205
+
206
+ const wae = env[options.waeBinding] as WaeLikeBinding | undefined
207
+ if (!wae?.writeDataPoint) {
208
+ console.error('store.order_telemetry.wae_binding_missing', {
209
+ binding: options.waeBinding,
210
+ orderId: event.data.id,
211
+ })
212
+ return
213
+ }
214
+ try {
215
+ await wae.writeDataPoint(buildStoreOrderWAEDataPoint(options, event, rawPayloadHash))
216
+ } catch (error) {
217
+ console.error('store.order_telemetry.wae_write_failed', {
218
+ orderId: event.data.id,
219
+ error: error instanceof Error ? error.message : String(error),
220
+ })
221
+ }
222
+ }
223
+ }
@@ -2,5 +2,6 @@ import type { APIContext } from 'astro'
2
2
  import { getConfig } from '../state.js'
3
3
 
4
4
  export async function GET(_context: APIContext): Promise<Response> {
5
- return Response.json({ currency: getConfig().defaultCurrency })
5
+ const config = await getConfig()
6
+ return Response.json({ currency: config.defaultCurrency })
6
7
  }
@@ -4,10 +4,11 @@ import { type CheckoutEnv, createCheckoutResponse } from '../api.js'
4
4
  import { getConfig } from '../state.js'
5
5
 
6
6
  export async function POST(context: APIContext): Promise<Response> {
7
+ const config = await getConfig()
7
8
  return createCheckoutResponse({
8
9
  request: context.request,
9
10
  env: cloudflareEnv as CheckoutEnv,
10
- cartOrigin: getConfig().cartOrigin,
11
+ cartOrigin: config.cartOrigin,
11
12
  })
12
13
  }
13
14
 
@@ -1,8 +1,38 @@
1
1
  import { env as cloudflareEnv } from 'cloudflare:workers'
2
2
  import type { APIContext } from 'astro'
3
- import { createWebhookResponse, type WebhookEnv } from '../api.js'
3
+ import { createWebhookResponse, setOrderPlacedHandler, type WebhookEnv } from '../api.js'
4
+ import { createD1OrderHandler } from '../orders.js'
5
+ import { getConfigOrNull } from '../state.js'
6
+
7
+ let orderHandlerRegistered = false
8
+
9
+ /**
10
+ * `store()`'s `astro:config:setup` hook also calls `setOrderPlacedHandler`,
11
+ * but that call runs in the astro CLI's Node process while loading
12
+ * astro.config.mjs — a different module instantiation than the one a built
13
+ * Worker ships (see state.ts). This route module IS part of the Worker's own
14
+ * runtime bundle (it's `injectRoute`-registered), so it registers the D1
15
+ * order handler itself, once, against the exact `api.js` instance this
16
+ * route's `createWebhookResponse` call also uses. Idempotent with the
17
+ * config-setup-time call — whichever runs last in a given process wins, and
18
+ * both install the same handler shape.
19
+ */
20
+ async function ensureOrderHandlerRegistered(): Promise<void> {
21
+ if (orderHandlerRegistered) return
22
+ const config = await getConfigOrNull()
23
+ if (!config) return
24
+ setOrderPlacedHandler(
25
+ createD1OrderHandler({
26
+ d1Binding: config.telemetry.d1Binding,
27
+ waeBinding: config.telemetry.waeBinding,
28
+ siteId: config.telemetry.siteId,
29
+ }),
30
+ )
31
+ orderHandlerRegistered = true
32
+ }
4
33
 
5
34
  export async function POST(context: APIContext): Promise<Response> {
35
+ await ensureOrderHandlerRegistered()
6
36
  return createWebhookResponse({
7
37
  request: context.request,
8
38
  env: cloudflareEnv as WebhookEnv,
package/src/state.ts CHANGED
@@ -6,7 +6,36 @@ export function _setConfig(next: ResolvedStoreOptions): void {
6
6
  config = next
7
7
  }
8
8
 
9
- export function getConfig(): ResolvedStoreOptions {
9
+ /**
10
+ * `_setConfig` is called both by `store()`'s `astro:config:setup` hook — which
11
+ * runs in the astro CLI's Node process while *loading* astro.config.mjs, a
12
+ * different module instantiation than the one the built Worker ships — and by
13
+ * the vite-plugin-generated `virtual:growth-labs/store/config` module, which
14
+ * bakes the resolved options in as literal data and calls `_setConfig` as
15
+ * part of its own module body. The virtual module is the only one of the two
16
+ * that is guaranteed to execute inside the actual bundled Worker's runtime
17
+ * module graph, so it is the fallback here.
18
+ *
19
+ * A dynamic import keeps the `virtual:` specifier off every caller's static
20
+ * import graph (the pure-Node import gate, and any non-Vite tooling, would
21
+ * otherwise choke on the scheme) — see scripts/verify-pure-node-import.mjs
22
+ * and health.ts's identical `cloudflare:workers` pattern.
23
+ */
24
+ async function resolveViaVirtualModule(): Promise<ResolvedStoreOptions | null> {
25
+ try {
26
+ const mod = (await import('virtual:growth-labs/store/config')) as {
27
+ config?: ResolvedStoreOptions
28
+ }
29
+ return mod?.config ?? null
30
+ } catch {
31
+ return null
32
+ }
33
+ }
34
+
35
+ export async function getConfig(): Promise<ResolvedStoreOptions> {
36
+ if (!config) {
37
+ config = await resolveViaVirtualModule()
38
+ }
10
39
  if (!config) {
11
40
  throw new Error(
12
41
  '@growth-labs/store: config accessed before the integration ran. Add store() to astro.config.mjs.',
@@ -15,6 +44,9 @@ export function getConfig(): ResolvedStoreOptions {
15
44
  return config
16
45
  }
17
46
 
18
- export function getConfigOrNull(): ResolvedStoreOptions | null {
47
+ export async function getConfigOrNull(): Promise<ResolvedStoreOptions | null> {
48
+ if (!config) {
49
+ config = await resolveViaVirtualModule()
50
+ }
19
51
  return config
20
52
  }
package/src/virtual.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  declare module 'virtual:growth-labs/store/config' {
2
2
  import type { ResolvedStoreOptions } from '@growth-labs/store'
3
3
  export const config: ResolvedStoreOptions
4
- export function getConfig(): ResolvedStoreOptions
5
- export function getConfigOrNull(): ResolvedStoreOptions | null
4
+ export function getConfig(): Promise<ResolvedStoreOptions>
5
+ export function getConfigOrNull(): Promise<ResolvedStoreOptions | null>
6
6
  }