@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/dist/orders.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Resolves `cloudflare:workers` via a dynamic import wrapped in try/catch —
3
+ * `createD1OrderHandler` is wired from `index.ts`'s `astro:config:setup`
4
+ * hook, which runs under plain Node during `astro build`/`astro check`.
5
+ * See health.ts and scripts/verify-pure-node-import.mjs for the same pattern.
6
+ */
7
+ async function resolveTelemetryEnv() {
8
+ try {
9
+ const mod = (await import('cloudflare:workers'));
10
+ return mod?.env ?? null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ async function sha256Hex(input) {
17
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));
18
+ return Array.from(new Uint8Array(digest))
19
+ .map((byte) => byte.toString(16).padStart(2, '0'))
20
+ .join('');
21
+ }
22
+ function orderItemCount(event) {
23
+ return event.data.offers.reduce((total, offer) => total + (offer.variant.quantity ?? 0), 0);
24
+ }
25
+ function buildItemsJson(event) {
26
+ return JSON.stringify(event.data.offers.map((offer) => ({
27
+ offerId: offer.id,
28
+ name: offer.name ?? null,
29
+ variantId: offer.variant.id,
30
+ sku: offer.variant.sku ?? null,
31
+ quantity: offer.variant.quantity ?? 0,
32
+ unitPrice: (offer.variant.unitPrice ?? offer.variant.price)?.value ?? null,
33
+ })));
34
+ }
35
+ function cartOriginFor(event, fallback) {
36
+ const metadata = event.data.metadata;
37
+ const fromMetadata = metadata && typeof metadata.cart_origin === 'string'
38
+ ? metadata.cart_origin
39
+ : undefined;
40
+ return fromMetadata ?? fallback;
41
+ }
42
+ /**
43
+ * Mirrors `@growth-labs/analytics`'s `store_order_placed` blob/double layout
44
+ * (packages don't import each other — PLATFORM_PATTERNS.md — so this
45
+ * replicates the slot mapping from `buildWAEDataPoint`/`buildStorefrontWAEParams`
46
+ * rather than calling into that package).
47
+ */
48
+ export function buildStoreOrderWAEDataPoint(options, event, rawPayloadHash) {
49
+ const utm = event.data.trackingParams ?? {};
50
+ const labelExtras = {
51
+ cartOrigin: cartOriginFor(event, options.siteId),
52
+ rawPayloadHash,
53
+ itemCount: orderItemCount(event),
54
+ };
55
+ if (event.data.email)
56
+ labelExtras.customerEmail = event.data.email;
57
+ return {
58
+ blobs: [
59
+ 'store_order_placed', // blob1 eventName
60
+ options.siteId, // blob2 siteId
61
+ '', // blob3 visitorId
62
+ '', // blob4 sessionId
63
+ '', // blob5 pageUrl
64
+ '', // blob6 pagePath
65
+ '', // blob7 referrer
66
+ utm.utm_source ?? '', // blob8 utmSource
67
+ utm.utm_medium ?? '', // blob9 utmMedium
68
+ utm.utm_campaign ?? '', // blob10 utmCampaign
69
+ '', // blob11 derivedSource
70
+ '', // blob12 country
71
+ '', // blob13 deviceType
72
+ '', // blob14 browserName
73
+ '', // blob15 osName
74
+ event.data.id, // blob16 contentSlug = orderId
75
+ 'order', // blob17 contentType
76
+ 'storefront', // blob18 eventCategory
77
+ JSON.stringify(labelExtras), // blob19 eventLabel
78
+ 'false', // blob20 isNewVisitor
79
+ ],
80
+ doubles: [
81
+ Date.now(), // double1 timestamp
82
+ orderItemCount(event), // double2 eventValue
83
+ 0,
84
+ 0,
85
+ 0,
86
+ 0,
87
+ 0,
88
+ 0,
89
+ 0, // double3-9
90
+ 0, // double10 productPrice (not applicable to a whole order)
91
+ event.data.amounts.total.value, // double11 cartValue
92
+ 0,
93
+ 0,
94
+ 0,
95
+ 0,
96
+ 0,
97
+ 0,
98
+ 0,
99
+ 0,
100
+ 0, // double12-20
101
+ ],
102
+ indexes: ['store_order_placed'],
103
+ };
104
+ }
105
+ /**
106
+ * B2's order-telemetry handler, wired via `setOrderPlacedHandler` from
107
+ * `index.ts` for every consuming site automatically: persists every verified
108
+ * `ORDER_PLACED` webhook to the package-owned `gl_store_orders` D1 table
109
+ * (migrations/0001_gl_store_orders.sql) and emits the mirrored WAE point.
110
+ *
111
+ * The D1 write and the WAE write are independent best-effort operations —
112
+ * a WAE outage must not drop the durable order row, and vice versa. Both
113
+ * failure paths log a structured, greppable event rather than throwing:
114
+ * `createWebhookResponse` has already validated the HMAC signature and is
115
+ * about to return 200 to Fourthwall by the time this handler runs, so
116
+ * throwing here would not trigger a useful retry, only an unhandled
117
+ * rejection after the response was already sent.
118
+ */
119
+ export function createD1OrderHandler(options) {
120
+ return async (event) => {
121
+ const env = await resolveTelemetryEnv();
122
+ if (!env) {
123
+ console.error('store.order_telemetry.env_unavailable', { orderId: event.data.id });
124
+ return;
125
+ }
126
+ const rawPayloadHash = await sha256Hex(JSON.stringify(event));
127
+ const db = env[options.d1Binding];
128
+ if (!db) {
129
+ console.error('store.order_telemetry.d1_binding_missing', {
130
+ binding: options.d1Binding,
131
+ orderId: event.data.id,
132
+ });
133
+ }
134
+ else {
135
+ try {
136
+ await db
137
+ .prepare(`INSERT OR IGNORE INTO gl_store_orders
138
+ (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)
139
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
140
+ .bind(event.data.id, event.data.shopId ?? event.shopId ?? null, options.siteId, event.data.amounts.total.value, event.data.amounts.total.currency, buildItemsJson(event), cartOriginFor(event, options.siteId), event.data.trackingParams?.utm_source ?? null, event.data.trackingParams?.utm_medium ?? null, event.data.trackingParams?.utm_campaign ?? null, event.data.trackingParams?.utm_term ?? null, event.data.trackingParams?.utm_content ?? null, rawPayloadHash, Date.now())
141
+ .run();
142
+ }
143
+ catch (error) {
144
+ console.error('store.order_telemetry.d1_write_failed', {
145
+ orderId: event.data.id,
146
+ error: error instanceof Error ? error.message : String(error),
147
+ });
148
+ }
149
+ }
150
+ const wae = env[options.waeBinding];
151
+ if (!wae?.writeDataPoint) {
152
+ console.error('store.order_telemetry.wae_binding_missing', {
153
+ binding: options.waeBinding,
154
+ orderId: event.data.id,
155
+ });
156
+ return;
157
+ }
158
+ try {
159
+ await wae.writeDataPoint(buildStoreOrderWAEDataPoint(options, event, rawPayloadHash));
160
+ }
161
+ catch (error) {
162
+ console.error('store.order_telemetry.wae_write_failed', {
163
+ orderId: event.data.id,
164
+ error: error instanceof Error ? error.message : String(error),
165
+ });
166
+ }
167
+ };
168
+ }
169
+ //# sourceMappingURL=orders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orders.js","sourceRoot":"","sources":["../src/orders.ts"],"names":[],"mappings":"AA0BA;;;;;GAKG;AACH,KAAK,UAAU,mBAAmB;IACjC,IAAI,CAAC;QACJ,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAsC,CAAA;QACrF,OAAO,GAAG,EAAE,GAAG,IAAI,IAAI,CAAA;IACxB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAA;IACZ,CAAC;AACF,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,KAAa;IACrC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;IACrF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;SACvC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SACjD,IAAI,CAAC,EAAE,CAAC,CAAA;AACX,CAAC;AAED,SAAS,cAAc,CAAC,KAAyB;IAChD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,IAAI,C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CAAC,MAAM,CAAC,KAAK,CAAC;aAC7D,CAAC,CAAA;QACH,CAAC;IACF,CAAC,CAAA;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"cart-bootstrap.d.ts","sourceRoot":"","sources":["../../src/routes/cart-bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAGvC,wBAAsB,GAAG,CAAC,QAAQ,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAEjE"}
1
+ {"version":3,"file":"cart-bootstrap.d.ts","sourceRoot":"","sources":["../../src/routes/cart-bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAGvC,wBAAsB,GAAG,CAAC,QAAQ,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAGjE"}
@@ -1,5 +1,6 @@
1
1
  import { getConfig } from '../state.js';
2
2
  export async function GET(_context) {
3
- return Response.json({ currency: getConfig().defaultCurrency });
3
+ const config = await getConfig();
4
+ return Response.json({ currency: config.defaultCurrency });
4
5
  }
5
6
  //# sourceMappingURL=cart-bootstrap.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cart-bootstrap.js","sourceRoot":"","sources":["../../src/routes/cart-bootstrap.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,MAAM,CAAC,KAAK,UAAU,GAAG,CAAC,QAAoB;IAC7C,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,eAAe,EAAE,CAAC,CAAA;AAChE,CAAC"}
1
+ {"version":3,"file":"cart-bootstrap.js","sourceRoot":"","sources":["../../src/routes/cart-bootstrap.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,MAAM,CAAC,KAAK,UAAU,GAAG,CAAC,QAAoB;IAC7C,MAAM,MAAM,GAAG,MAAM,SAAS,EAAE,CAAA;IAChC,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC,CAAA;AAC3D,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../../src/routes/checkout.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAIvC,wBAAsB,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAMjE;AAED,wBAAgB,GAAG,IAAI,QAAQ,CAE9B"}
1
+ {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../../src/routes/checkout.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAIvC,wBAAsB,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAOjE;AAED,wBAAgB,GAAG,IAAI,QAAQ,CAE9B"}
@@ -2,10 +2,11 @@ import { env as cloudflareEnv } from 'cloudflare:workers';
2
2
  import { createCheckoutResponse } from '../api.js';
3
3
  import { getConfig } from '../state.js';
4
4
  export async function POST(context) {
5
+ const config = await getConfig();
5
6
  return createCheckoutResponse({
6
7
  request: context.request,
7
8
  env: cloudflareEnv,
8
- cartOrigin: getConfig().cartOrigin,
9
+ cartOrigin: config.cartOrigin,
9
10
  });
10
11
  }
11
12
  export function ALL() {
@@ -1 +1 @@
1
- {"version":3,"file":"checkout.js","sourceRoot":"","sources":["../../src/routes/checkout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEzD,OAAO,EAAoB,sBAAsB,EAAE,MAAM,WAAW,CAAA;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,OAAmB;IAC7C,OAAO,sBAAsB,CAAC;QAC7B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,aAA4B;QACjC,UAAU,EAAE,SAAS,EAAE,CAAC,UAAU;KAClC,CAAC,CAAA;AACH,CAAC;AAED,MAAM,UAAU,GAAG;IAClB,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,oBAAoB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;AACvE,CAAC"}
1
+ {"version":3,"file":"checkout.js","sourceRoot":"","sources":["../../src/routes/checkout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEzD,OAAO,EAAoB,sBAAsB,EAAE,MAAM,WAAW,CAAA;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,OAAmB;IAC7C,MAAM,MAAM,GAAG,MAAM,SAAS,EAAE,CAAA;IAChC,OAAO,sBAAsB,CAAC;QAC7B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,aAA4B;QACjC,UAAU,EAAE,MAAM,CAAC,UAAU;KAC7B,CAAC,CAAA;AACH,CAAC;AAED,MAAM,UAAU,GAAG;IAClB,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,oBAAoB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;AACvE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../src/routes/webhook.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAGvC,wBAAsB,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAKjE;AAED,wBAAgB,GAAG,IAAI,QAAQ,CAE9B"}
1
+ {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../src/routes/webhook.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAgCvC,wBAAsB,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAMjE;AAED,wBAAgB,GAAG,IAAI,QAAQ,CAE9B"}
@@ -1,6 +1,34 @@
1
1
  import { env as cloudflareEnv } from 'cloudflare:workers';
2
- import { createWebhookResponse } from '../api.js';
2
+ import { createWebhookResponse, setOrderPlacedHandler } from '../api.js';
3
+ import { createD1OrderHandler } from '../orders.js';
4
+ import { getConfigOrNull } from '../state.js';
5
+ let orderHandlerRegistered = false;
6
+ /**
7
+ * `store()`'s `astro:config:setup` hook also calls `setOrderPlacedHandler`,
8
+ * but that call runs in the astro CLI's Node process while loading
9
+ * astro.config.mjs — a different module instantiation than the one a built
10
+ * Worker ships (see state.ts). This route module IS part of the Worker's own
11
+ * runtime bundle (it's `injectRoute`-registered), so it registers the D1
12
+ * order handler itself, once, against the exact `api.js` instance this
13
+ * route's `createWebhookResponse` call also uses. Idempotent with the
14
+ * config-setup-time call — whichever runs last in a given process wins, and
15
+ * both install the same handler shape.
16
+ */
17
+ async function ensureOrderHandlerRegistered() {
18
+ if (orderHandlerRegistered)
19
+ return;
20
+ const config = await getConfigOrNull();
21
+ if (!config)
22
+ return;
23
+ setOrderPlacedHandler(createD1OrderHandler({
24
+ d1Binding: config.telemetry.d1Binding,
25
+ waeBinding: config.telemetry.waeBinding,
26
+ siteId: config.telemetry.siteId,
27
+ }));
28
+ orderHandlerRegistered = true;
29
+ }
3
30
  export async function POST(context) {
31
+ await ensureOrderHandlerRegistered();
4
32
  return createWebhookResponse({
5
33
  request: context.request,
6
34
  env: cloudflareEnv,
@@ -1 +1 @@
1
- {"version":3,"file":"webhook.js","sourceRoot":"","sources":["../../src/routes/webhook.ts"],"names":[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AI,CAAC,OAAmB;IAC7C,MAAM,4BAA4B,EAAE,CAAA;IACpC,OAAO,qBAAqB,CAAC;QAC5B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,aAA2B;KAChC,CAAC,CAAA;AACH,CAAC;AAED,MAAM,UAAU,GAAG;IAClB,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,oBAAoB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;AACvE,CAAC"}
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ResolvedStoreOptions } from './options.js';
2
2
  export declare function _setConfig(next: ResolvedStoreOptions): void;
3
- export declare function getConfig(): ResolvedStoreOptions;
4
- export declare function getConfigOrNull(): ResolvedStoreOptions | null;
3
+ export declare function getConfig(): Promise<ResolvedStoreOptions>;
4
+ export declare function getConfigOrNull(): Promise<ResolvedStoreOptions | null>;
5
5
  //# sourceMappingURL=state.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAIxD,wBAAgB,UAAU,CAAC,IAAI,EAAE,oBAAoB,GAAG,IAAI,CAE3D;AAED,wBAAgB,SAAS,IAAI,oBAAoB,CAOhD;AAED,wBAAgB,eAAe,IAAI,oBAAoB,GAAG,IAAI,CAE7D"}
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAIxD,wBAAgB,UAAU,CAAC,IAAI,EAAE,oBAAoB,GAAG,IAAI,CAE3D;AA4BD,wBAAsB,SAAS,IAAI,OAAO,CAAC,oBAAoB,CAAC,CAU/D;AAED,wBAAsB,eAAe,IAAI,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAK5E"}
package/dist/state.js CHANGED
@@ -2,13 +2,43 @@ let config = null;
2
2
  export function _setConfig(next) {
3
3
  config = next;
4
4
  }
5
- export function getConfig() {
5
+ /**
6
+ * `_setConfig` is called both by `store()`'s `astro:config:setup` hook — which
7
+ * runs in the astro CLI's Node process while *loading* astro.config.mjs, a
8
+ * different module instantiation than the one the built Worker ships — and by
9
+ * the vite-plugin-generated `virtual:growth-labs/store/config` module, which
10
+ * bakes the resolved options in as literal data and calls `_setConfig` as
11
+ * part of its own module body. The virtual module is the only one of the two
12
+ * that is guaranteed to execute inside the actual bundled Worker's runtime
13
+ * module graph, so it is the fallback here.
14
+ *
15
+ * A dynamic import keeps the `virtual:` specifier off every caller's static
16
+ * import graph (the pure-Node import gate, and any non-Vite tooling, would
17
+ * otherwise choke on the scheme) — see scripts/verify-pure-node-import.mjs
18
+ * and health.ts's identical `cloudflare:workers` pattern.
19
+ */
20
+ async function resolveViaVirtualModule() {
21
+ try {
22
+ const mod = (await import('virtual:growth-labs/store/config'));
23
+ return mod?.config ?? null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export async function getConfig() {
30
+ if (!config) {
31
+ config = await resolveViaVirtualModule();
32
+ }
6
33
  if (!config) {
7
34
  throw new Error('@growth-labs/store: config accessed before the integration ran. Add store() to astro.config.mjs.');
8
35
  }
9
36
  return config;
10
37
  }
11
- export function getConfigOrNull() {
38
+ export async function getConfigOrNull() {
39
+ if (!config) {
40
+ config = await resolveViaVirtualModule();
41
+ }
12
42
  return config;
13
43
  }
14
44
  //# sourceMappingURL=state.js.map
package/dist/state.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAEA,IAAI,MAAM,GAAgC,IAAI,CAAA;AAE9C,MAAM,UAAU,UAAU,CAAC,IAA0B;IACpD,MAAM,GAAG,IAAI,CAAA;AACd,CAAC;AAED,MAAM,UAAU,SAAS;IACxB,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACd,kGAAkG,CAClG,CAAA;IACF,CAAC;IACD,OAAO,MAAM,CAAA;AACd,CAAC;AAED,MAAM,UAAU,eAAe;IAC9B,OAAO,MAAM,CAAA;AACd,CAAC"}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAEA,IAAI,MAAM,GAAgC,IAAI,CAAA;AAE9C,MAAM,UAAU,UAAU,CAAC,IAA0B;IACpD,MAAM,GAAG,IAAI,CAAA;AACd,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,KAAK,UAAU,uBAAuB;IACrC,IAAI,CAAC;QACJ,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM,CAAC,kCAAkC,CAAC,CAE5D,CAAA;QACD,OAAO,GAAG,EAAE,MAAM,IAAI,IAAI,CAAA;IAC3B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAA;IACZ,CAAC;AACF,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,SAAS;IAC9B,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,GAAG,MAAM,uBAAuB,EAAE,CAAA;IACzC,CAAC;IACD,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACd,kGAAkG,CAClG,CAAA;IACF,CAAC;IACD,OAAO,MAAM,CAAA;AACd,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe;IACpC,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,GAAG,MAAM,uBAAuB,EAAE,CAAA;IACzC,CAAC;IACD,OAAO,MAAM,CAAA;AACd,CAAC"}
@@ -0,0 +1,23 @@
1
+ -- 0001_gl_store_orders.sql
2
+ -- @growth-labs/store v0.2.0+ schema.
3
+ -- Compatible with `wrangler d1 migrations apply`.
4
+ -- All statements are idempotent (IF NOT EXISTS).
5
+
6
+ CREATE TABLE IF NOT EXISTS gl_store_orders (
7
+ id TEXT PRIMARY KEY, -- Fourthwall order id (ORDER_PLACED event's data.id)
8
+ shop_id TEXT,
9
+ site_id TEXT NOT NULL, -- this site's `cartOrigin`/`telemetry.siteId` config value
10
+ amount REAL NOT NULL,
11
+ currency TEXT NOT NULL,
12
+ items_json TEXT NOT NULL,
13
+ cart_origin TEXT,
14
+ utm_source TEXT,
15
+ utm_medium TEXT,
16
+ utm_campaign TEXT,
17
+ utm_term TEXT,
18
+ utm_content TEXT,
19
+ raw_payload_hash TEXT NOT NULL,
20
+ received_at INTEGER NOT NULL
21
+ );
22
+
23
+ CREATE INDEX IF NOT EXISTS gl_store_orders_site_received_idx ON gl_store_orders (site_id, received_at);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@growth-labs/store",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "exports": {
@@ -31,6 +31,7 @@
31
31
  "dist",
32
32
  "src/**/*.ts",
33
33
  "src/**/*.astro",
34
+ "migrations",
34
35
  "README.md",
35
36
  "CHANGELOG.md"
36
37
  ],
package/src/api.ts CHANGED
@@ -115,6 +115,7 @@ export async function createWebhookResponse(input: {
115
115
 
116
116
  const signature = input.request.headers.get(FOURTHWALL_SIGNATURE_HEADER)
117
117
  if (!signature) {
118
+ console.error('store.webhook.invalid_signature', { reason: 'missing' })
118
119
  return Response.json({ error: 'Missing signature' }, { status: 401 })
119
120
  }
120
121
 
@@ -132,6 +133,10 @@ export async function createWebhookResponse(input: {
132
133
  input.cryptoImpl ?? globalThis.crypto,
133
134
  ).catch(() => false)
134
135
  if (!isValid) {
136
+ // Tripwire (channel-store-recovery B2): a signature failure is either an
137
+ // attacker probing the endpoint or the wrong secret configured after a
138
+ // rotation — both are worth alerting on, unlike the routine 500 above.
139
+ console.error('store.webhook.invalid_signature', { reason: 'mismatch' })
135
140
  return Response.json({ error: 'Invalid signature' }, { status: 401 })
136
141
  }
137
142
 
@@ -14,7 +14,7 @@ interface Props {
14
14
  }
15
15
 
16
16
  const { storePath = '/store/', fourthwallShopUrl } = Astro.props
17
- const config = getConfig()
17
+ const config = await getConfig()
18
18
  const env = cloudflareEnv as FwEnv
19
19
  const token = env?.PUBLIC_FW_STOREFRONT_TOKEN ?? ''
20
20
  const currency = env?.PUBLIC_FW_DEFAULT_CURRENCY ?? config.defaultCurrency
@@ -18,7 +18,7 @@ interface Props {
18
18
  }
19
19
 
20
20
  const { handle, basePath = '/store', notFoundPath = '/404/' } = Astro.props
21
- const config = getConfig()
21
+ const config = await getConfig()
22
22
 
23
23
  const collection = getStoreCollection(config.collections, handle)
24
24
  if (!collection) {
@@ -19,7 +19,7 @@ interface Props {
19
19
  }
20
20
 
21
21
  const { heading, basePath = '/store' } = Astro.props
22
- const config = getConfig()
22
+ const config = await getConfig()
23
23
  const env = cloudflareEnv as FwEnv
24
24
  const token = env?.PUBLIC_FW_STOREFRONT_TOKEN ?? ''
25
25
  const cookieCurrency = Astro.cookies.get('fw_currency')?.value
@@ -36,7 +36,7 @@ interface Props {
36
36
  }
37
37
 
38
38
  const { slug, basePath = '/store', notFoundResponseStatus = 404, fourthwallShopBaseUrl, kind = 'merch', kindModule: KindModule } = Astro.props
39
- const config = getConfig()
39
+ const config = await getConfig()
40
40
  const env = cloudflareEnv as FwEnv
41
41
  const token = env?.PUBLIC_FW_STOREFRONT_TOKEN ?? ''
42
42
  const cookieCurrency = Astro.cookies.get('fw_currency')?.value
package/src/health.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { isWebhookConfigured } from './api.js'
2
+ import { getConfigOrNull } from './state.js'
2
3
 
3
4
  /**
4
5
  * Structurally matches `@growth-labs/health`'s `CustomCheck` without
@@ -13,6 +14,21 @@ export interface StoreHealthCheckResult {
13
14
  error?: string
14
15
  }
15
16
 
17
+ export interface StoreHealthCheckOptions {
18
+ /** D1 binding to query for the order-staleness tripwire. Defaults to `telemetry.d1Binding`'s default, `"DB"`. */
19
+ d1Binding?: string
20
+ /** Site identity to scope the staleness query to. Defaults to `telemetry.siteId`. Pass it from the resolved store options. */
21
+ siteId?: string
22
+ /** Alert once a site with prior orders has gone this many days without a new one. Default 7. */
23
+ staleOrderAlertDays?: number
24
+ }
25
+
26
+ interface D1LikeDatabase {
27
+ prepare(query: string): {
28
+ bind(...values: unknown[]): { first<T>(column: string): Promise<T | null> }
29
+ }
30
+ }
31
+
16
32
  /**
17
33
  * Resolves `cloudflare:workers` via a dynamic import wrapped in try/catch,
18
34
  * keeping the specifier off this module's static import graph — this file
@@ -21,16 +37,64 @@ export interface StoreHealthCheckResult {
21
37
  * the module being unresolvable at runtime, the loader refuses the scheme
22
38
  * before resolution even starts). See scripts/verify-pure-node-import.mjs.
23
39
  */
24
- async function resolveCloudflareEnv(): Promise<{ FW_WEBHOOK_SECRET?: string } | null> {
40
+ async function resolveCloudflareEnv(): Promise<Record<string, unknown> | null> {
25
41
  try {
26
42
  const mod = (await import('cloudflare:workers')) as { env?: Record<string, unknown> }
27
- return (mod?.env as { FW_WEBHOOK_SECRET?: string } | undefined) ?? null
43
+ return mod?.env ?? null
28
44
  } catch {
29
45
  return null
30
46
  }
31
47
  }
32
48
 
33
- export function createStoreHealthCheck(): {
49
+ /**
50
+ * Tripwire (channel-store-recovery B2): a site that has ever recorded an
51
+ * order but has gone quiet for `staleOrderAlertDays` is almost certainly
52
+ * broken (a silently-failing webhook, a revoked secret, a Fourthwall-side
53
+ * change) rather than genuinely out of sales — the same silent-500 failure
54
+ * mode that started this program. A site with zero orders ever (bigbrain
55
+ * pre-launch, or any site before its first sale) is not alerted on: there is
56
+ * no prior signal to regress from.
57
+ */
58
+ async function checkOrderStaleness(
59
+ env: Record<string, unknown>,
60
+ options: Required<Pick<StoreHealthCheckOptions, 'd1Binding' | 'siteId' | 'staleOrderAlertDays'>>,
61
+ ): Promise<string | undefined> {
62
+ const db = env[options.d1Binding] as D1LikeDatabase | undefined
63
+ if (!db) return undefined // covered by the webhook-secret check above; avoid a duplicate red reason
64
+
65
+ let lastReceivedAt: number | null
66
+ try {
67
+ lastReceivedAt = await db
68
+ .prepare('SELECT MAX(received_at) as last_received_at FROM gl_store_orders WHERE site_id = ?')
69
+ .bind(options.siteId)
70
+ .first<number | null>('last_received_at')
71
+ } catch (error) {
72
+ return `gl_store_orders query failed: ${error instanceof Error ? error.message : String(error)}`
73
+ }
74
+
75
+ if (lastReceivedAt === null || lastReceivedAt === undefined) return undefined
76
+
77
+ const staleMs = options.staleOrderAlertDays * 24 * 60 * 60 * 1000
78
+ const ageMs = Date.now() - lastReceivedAt
79
+ if (ageMs > staleMs) {
80
+ const days = Math.floor(ageMs / (24 * 60 * 60 * 1000))
81
+ return `no order ingested for ${days}d (alert threshold ${options.staleOrderAlertDays}d) — last order at ${new Date(lastReceivedAt).toISOString()}`
82
+ }
83
+ return undefined
84
+ }
85
+
86
+ /**
87
+ * `health({ checks: [createStoreHealthCheck()] })` needs no arguments in the
88
+ * common case: `.check()` resolves `telemetry.{d1Binding,siteId,
89
+ * staleOrderAlertDays}` from the integration's config at request time (via
90
+ * `getConfigOrNull()` — see state.ts for why this must happen per-request
91
+ * rather than once when `createStoreHealthCheck()` itself is called, which
92
+ * for most sites happens while building `astro.config.mjs`'s options object,
93
+ * before the config singleton a built Worker actually serves from exists).
94
+ * Explicit options here only override that default — useful for tests, never
95
+ * required in a real site.
96
+ */
97
+ export function createStoreHealthCheck(options: StoreHealthCheckOptions = {}): {
34
98
  name: string
35
99
  check: () => Promise<StoreHealthCheckResult>
36
100
  } {
@@ -39,16 +103,33 @@ export function createStoreHealthCheck(): {
39
103
  async check() {
40
104
  const start = Date.now()
41
105
  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
- }),
106
+ const configured = isWebhookConfigured(env as { FW_WEBHOOK_SECRET?: string } | null)
107
+ if (!configured) {
108
+ return {
109
+ ok: false,
110
+ ms: Date.now() - start,
111
+ error: 'FW_WEBHOOK_SECRET is not set — order telemetry is silently dropping orders',
112
+ }
51
113
  }
114
+
115
+ const resolvedConfig = options.d1Binding && options.siteId ? null : await getConfigOrNull()
116
+ const d1Binding = options.d1Binding ?? resolvedConfig?.telemetry.d1Binding ?? 'DB'
117
+ const siteId = options.siteId ?? resolvedConfig?.telemetry.siteId
118
+ const staleOrderAlertDays =
119
+ options.staleOrderAlertDays ?? resolvedConfig?.telemetry.staleOrderAlertDays ?? 7
120
+
121
+ if (env && siteId) {
122
+ const staleReason = await checkOrderStaleness(env, {
123
+ d1Binding,
124
+ siteId,
125
+ staleOrderAlertDays,
126
+ })
127
+ if (staleReason) {
128
+ return { ok: false, ms: Date.now() - start, error: staleReason }
129
+ }
130
+ }
131
+
132
+ return { ok: true, ms: Date.now() - start }
52
133
  },
53
134
  }
54
135
  }
package/src/index.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { fileURLToPath } from 'node:url'
2
2
  import type { AstroIntegration } from 'astro'
3
+ import { setOrderPlacedHandler } from './api.js'
3
4
  import { type StoreOptions, storeOptionsSchema } from './options.js'
5
+ import { createD1OrderHandler } from './orders.js'
4
6
  import { _setConfig } from './state.js'
5
7
  import { growthLabsStorePlugin } from './vite-plugin.js'
6
8
 
@@ -19,6 +21,19 @@ export default function store(userOptions: StoreOptions): AstroIntegration {
19
21
 
20
22
  _setConfig(options)
21
23
 
24
+ // B2 (channel-store-recovery): every consuming site gets D1 order
25
+ // persistence + the store_order_placed WAE event automatically — the
26
+ // package owns this now, sites never wire it by hand. A site with its own
27
+ // order pipeline can still override via `setOrderPlacedHandler()` after
28
+ // `store()` runs.
29
+ setOrderPlacedHandler(
30
+ createD1OrderHandler({
31
+ d1Binding: options.telemetry.d1Binding,
32
+ waeBinding: options.telemetry.waeBinding,
33
+ siteId: options.telemetry.siteId,
34
+ }),
35
+ )
36
+
22
37
  return {
23
38
  name: '@growth-labs/store',
24
39
  hooks: {
@@ -59,10 +74,13 @@ export {
59
74
  getStoreCollection,
60
75
  resolveProductKind,
61
76
  } from './collections.js'
77
+ export type { StoreHealthCheckOptions } from './health.js'
62
78
  export { createStoreHealthCheck } from './health.js'
63
79
  export { hasProductImages, optimizeFwImage } from './image.js'
64
80
  export type { ResolvedStoreOptions, StoreOptions } from './options.js'
65
81
  export { storeOptionsSchema } from './options.js'
82
+ export type { OrderTelemetryOptions } from './orders.js'
83
+ export { buildStoreOrderWAEDataPoint, createD1OrderHandler } from './orders.js'
66
84
  export type * from './types.js'
67
85
  export type { MerchantReturnPolicy, StoreVariantClientData } from './variant.js'
68
86
  export {