@tokenoftrust/storefront-runner 6.12.7 → 6.12.9

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.
@@ -12,15 +12,21 @@ import type { WebhookTopic } from "./deliveryStore.js";
12
12
  export type CommerceTopic =
13
13
  | "fulfillment.assignment.created"
14
14
  | "fulfillment.assignment.updated"
15
+ | "order.paid"
15
16
  | "order.fulfilled"
16
17
  | "order.partially_fulfilled"
18
+ | "order.cancelled"
19
+ | "order.updated"
17
20
  | "inventory.changed";
18
21
 
19
22
  export const COMMERCE_TOPICS: readonly CommerceTopic[] = [
20
23
  "fulfillment.assignment.created",
21
24
  "fulfillment.assignment.updated",
25
+ "order.paid",
22
26
  "order.fulfilled",
23
27
  "order.partially_fulfilled",
28
+ "order.cancelled",
29
+ "order.updated",
24
30
  "inventory.changed",
25
31
  ];
26
32
 
@@ -84,16 +90,28 @@ function assignmentAdmissible(topic: CommerceTopic, payload: Record<string, unkn
84
90
  return typeof payload.occurredAt === "string" && Number.isFinite(Date.parse(payload.occurredAt));
85
91
  }
86
92
 
87
- /** `OrderData` with `status` exactly `status`: `fulfilled` for order.fulfilled, `created` while lines remain unshipped. */
88
- function orderDataAdmissible(payload: Record<string, unknown>, status: "fulfilled" | "created"): boolean {
93
+ /** `OrderData` with `status` in `allowedStatuses` and optional/required `lineItems`. */
94
+ function orderDataAdmissible(
95
+ payload: Record<string, unknown>,
96
+ allowedStatuses: readonly ("created" | "fulfilled" | "cancelled")[],
97
+ requireLineItems = false,
98
+ ): boolean {
89
99
  if (Object.keys(payload).some((key) => !ORDER_DATA_KEYS.has(key))) return false;
90
- if (!nonEmptyString(payload.id) || payload.status !== status || !nonEmptyString(payload.currency)) return false;
100
+ if (
101
+ !nonEmptyString(payload.id) ||
102
+ typeof payload.status !== "string" ||
103
+ !(allowedStatuses as readonly string[]).includes(payload.status) ||
104
+ !nonEmptyString(payload.currency)
105
+ ) {
106
+ return false;
107
+ }
91
108
  if (payload.customerHash !== undefined && typeof payload.customerHash !== "string") return false;
92
109
  for (const key of ["subtotal", "total"] as const) {
93
110
  if (payload[key] !== undefined && (typeof payload[key] !== "number" || !Number.isFinite(payload[key]))) return false;
94
111
  }
95
- if (payload.lineItems === undefined) return true;
112
+ if (payload.lineItems === undefined) return !requireLineItems;
96
113
  if (!Array.isArray(payload.lineItems)) return false;
114
+ if (requireLineItems && payload.lineItems.length === 0) return false;
97
115
  return payload.lineItems.every(
98
116
  (item) =>
99
117
  isRecord(item) &&
@@ -120,8 +138,11 @@ export function inventoryChangedAdmissible(payload: unknown): boolean {
120
138
  /** True when `payload` is exactly the closed shape `topic` allows and carries no private identity. */
121
139
  export function commercePayloadAdmissible(topic: CommerceTopic, payload: unknown): boolean {
122
140
  if (!isRecord(payload) || commercePayloadHasPrivateIdentity(payload)) return false;
123
- if (topic === "order.fulfilled") return orderDataAdmissible(payload, "fulfilled");
124
- if (topic === "order.partially_fulfilled") return orderDataAdmissible(payload, "created");
141
+ if (topic === "order.paid") return orderDataAdmissible(payload, ["created", "fulfilled"], true);
142
+ if (topic === "order.fulfilled") return orderDataAdmissible(payload, ["fulfilled"]);
143
+ if (topic === "order.partially_fulfilled") return orderDataAdmissible(payload, ["created"]);
144
+ if (topic === "order.cancelled") return orderDataAdmissible(payload, ["cancelled"], true);
145
+ if (topic === "order.updated") return orderDataAdmissible(payload, ["created", "fulfilled", "cancelled"], true);
125
146
  if (topic === "inventory.changed") return inventoryChangedAdmissible(payload);
126
147
  return assignmentAdmissible(topic, payload);
127
148
  }
@@ -52,8 +52,11 @@ export type WebhookTopic =
52
52
  | "catalog.product.updated"
53
53
  | "inventory.changed"
54
54
  | "order.created"
55
+ | "order.paid"
55
56
  | "order.fulfilled"
56
57
  | "order.partially_fulfilled"
58
+ | "order.cancelled"
59
+ | "order.updated"
57
60
  | "customer.marketing_consent.updated"
58
61
  | "attribution.finalized"
59
62
  | "fulfillment.assignment.created"
@@ -26,8 +26,11 @@ export const TOPIC_REQUIRED_SCOPE: Record<WebhookTopic, string | null> = {
26
26
  "catalog.product.updated": "catalog:read",
27
27
  "inventory.changed": "inventory:read",
28
28
  "order.created": "orders:webhook",
29
+ "order.paid": "orders:webhook",
29
30
  "order.fulfilled": "orders:webhook",
30
31
  "order.partially_fulfilled": "orders:webhook",
32
+ "order.cancelled": "orders:webhook",
33
+ "order.updated": "orders:webhook",
31
34
  "customer.marketing_consent.updated": "customers:read:minimal",
32
35
  "attribution.finalized": "attribution:write",
33
36
  "fulfillment.assignment.created": "fulfillment:process",
@@ -37,10 +37,11 @@ function isIsoInstant(value: unknown): value is string {
37
37
  export function verifiedTruthFromForwardedOrder(input: OrderForwardInput): VerifiedOrderTruth | null {
38
38
  if (!LIVE_ENVS.has(input.env)) return null;
39
39
  if (typeof input.providerEventId !== "string" || !isIsoInstant(input.occurredAt) || typeof input.amountMinor !== "number" || !Number.isSafeInteger(input.amountMinor) || input.amountMinor < 0) return null;
40
+ const normalizedStatus = input.status === "paid" ? "created" : input.status;
40
41
  const parsed = parseVerifiedOrderTruth({
41
42
  schemaVersion: "1", authority: "verified-provider", provider: FOXY_PROVIDER,
42
43
  providerEventId: input.providerEventId, providerOrderId: input.externalOrderId,
43
- tenant: input.tenantId, status: input.status, occurredAt: input.occurredAt,
44
+ tenant: input.tenantId, status: normalizedStatus, occurredAt: input.occurredAt,
44
45
  currency: input.currency, amountMinor: input.amountMinor,
45
46
  });
46
47
  return parsed.ok ? parsed.value : null;
@@ -46,6 +46,27 @@ function contractStatus(entry: CommerceOrderBookEntry): ContractOrderStatus {
46
46
  return "created";
47
47
  }
48
48
 
49
+ export interface LedgerContractOrderRecord {
50
+ order: ContractOrder;
51
+ updatedAt: string;
52
+ }
53
+
54
+ function ledgerEntryUpdatedAt(entry: CommerceOrderBookEntry): string {
55
+ let latestIso = isoInstant(entry.placedAt);
56
+ let latestMs = Date.parse(latestIso);
57
+ for (const event of entry.events) {
58
+ const candidate = (event as { occurredAt?: string }).occurredAt;
59
+ if (typeof candidate === "string") {
60
+ const ms = Date.parse(candidate);
61
+ if (Number.isFinite(ms) && (!Number.isFinite(latestMs) || ms > latestMs)) {
62
+ latestMs = ms;
63
+ latestIso = new Date(ms).toISOString();
64
+ }
65
+ }
66
+ }
67
+ return latestIso;
68
+ }
69
+
49
70
  /** Map one paid ledger order to the contract `Order`. */
50
71
  export async function ledgerEntryToContractOrder(
51
72
  entry: CommerceOrderBookEntry,
@@ -77,17 +98,40 @@ function paidOrders(book: readonly CommerceOrderBookEntry[]): CommerceOrderBookE
77
98
  return book.filter((entry) => entry.source !== "scrappy");
78
99
  }
79
100
 
101
+ /** Every paid order in one tenant's stage partition with its effective `updatedAt`, newest `createdAt` first. */
102
+ export async function readLedgerContractOrderRecords(
103
+ ledger: Pick<ScrappyOrderLedger, "readOrderBook">,
104
+ scope: LedgerContractScope,
105
+ hashCustomer: ContractCustomerHasher,
106
+ ): Promise<LedgerContractOrderRecord[]> {
107
+ const book = paidOrders(await ledger.readOrderBook(scope.tenantId, scope.stage));
108
+ const records = await Promise.all(
109
+ book.map(async (entry) => ({
110
+ order: await ledgerEntryToContractOrder(entry, hashCustomer),
111
+ updatedAt: ledgerEntryUpdatedAt(entry),
112
+ })),
113
+ );
114
+ return records.sort((a, b) =>
115
+ a.order.createdAt === b.order.createdAt
116
+ ? a.order.id < b.order.id
117
+ ? -1
118
+ : a.order.id > b.order.id
119
+ ? 1
120
+ : 0
121
+ : a.order.createdAt < b.order.createdAt
122
+ ? 1
123
+ : -1,
124
+ );
125
+ }
126
+
80
127
  /** Every paid order in one tenant's stage partition, newest first. */
81
128
  export async function readLedgerContractOrders(
82
129
  ledger: Pick<ScrappyOrderLedger, "readOrderBook">,
83
130
  scope: LedgerContractScope,
84
131
  hashCustomer: ContractCustomerHasher,
85
132
  ): Promise<ContractOrder[]> {
86
- const book = paidOrders(await ledger.readOrderBook(scope.tenantId, scope.stage));
87
- const orders = await Promise.all(book.map((entry) => ledgerEntryToContractOrder(entry, hashCustomer)));
88
- return orders.sort((a, b) =>
89
- a.createdAt === b.createdAt ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : a.createdAt < b.createdAt ? 1 : -1,
90
- );
133
+ const records = await readLedgerContractOrderRecords(ledger, scope, hashCustomer);
134
+ return records.map((record) => record.order);
91
135
  }
92
136
 
93
137
  /** One paid order in one tenant's stage partition, or `null` when that partition has no such order. */
@@ -69,12 +69,18 @@ import {
69
69
  type CommerceCommandName,
70
70
  } from "./orderMapper.js";
71
71
 
72
+ export type ForwardPaymentStatus = "pending" | "paid" | "refunded" | "cancelled";
73
+
72
74
  /** One reconciled order, as tot-foxycart forwards it. See the contract doc for the wire (JSON) shape. */
73
75
  export interface OrderForwardInput {
74
76
  tenantId: string;
75
77
  externalOrderId: string;
76
78
  env: string;
77
79
  status: OrderStatus;
80
+ /** Optional explicit payment state when the provider forwards payment settlement separately from fulfillment status. */
81
+ paymentStatus?: ForwardPaymentStatus;
82
+ /** Convenience boolean flag when an order arrives or transitions as paid. */
83
+ paid?: boolean;
78
84
  currency: string;
79
85
  total: number;
80
86
  subtotal?: number;
@@ -100,11 +106,17 @@ export interface OrderForwardResult {
100
106
  emitted: WebhookTopic[];
101
107
  }
102
108
 
109
+ function toContractOrderStatus(status: OrderStatus): "created" | "fulfilled" | "cancelled" {
110
+ if (status === "fulfilled") return "fulfilled";
111
+ if (status === "cancelled" || status === "refunded") return "cancelled";
112
+ return "created";
113
+ }
114
+
103
115
  /** The `OrderData` wire shape (`contract/asyncapi.yaml`) — never the internal snake_case row. */
104
116
  function toOrderData(order: Order): Record<string, unknown> {
105
117
  const data: Record<string, unknown> = {
106
118
  id: order.externalOrderId,
107
- status: order.status,
119
+ status: toContractOrderStatus(order.status),
108
120
  currency: order.currency,
109
121
  lineItems: order.lineItems,
110
122
  total: order.total,
@@ -116,13 +128,83 @@ function toOrderData(order: Order): Record<string, unknown> {
116
128
  return data;
117
129
  }
118
130
 
119
- /** Which topics this upsert's status transition warrants — `[]` for none. */
120
- function topicsFor(previousStatus: OrderStatus | null, status: OrderStatus): WebhookTopic[] {
121
- if (previousStatus === null) {
122
- return status === "fulfilled" ? ["order.created", "order.fulfilled"] : ["order.created"];
131
+ function isPaidSignal(input: OrderForwardInput): boolean {
132
+ return input.status === "paid" || input.paid === true || input.paymentStatus === "paid";
133
+ }
134
+
135
+ function isCancelledState(status: OrderStatus | null, paymentStatus?: ForwardPaymentStatus): boolean {
136
+ return (
137
+ status === "cancelled" ||
138
+ status === "refunded" ||
139
+ paymentStatus === "cancelled" ||
140
+ paymentStatus === "refunded"
141
+ );
142
+ }
143
+
144
+ function orderContentSignature(order: Pick<Order, "currency" | "total" | "subtotal" | "lineItems">): string {
145
+ return canonicalJson({
146
+ currency: order.currency,
147
+ total: order.total,
148
+ subtotal: order.subtotal ?? null,
149
+ lineItems: order.lineItems,
150
+ });
151
+ }
152
+
153
+ const emittedTransitionsByDb = new WeakMap<Queryable, Set<string>>();
154
+
155
+ function transitionSetFor(db: Queryable): Set<string> {
156
+ let set = emittedTransitionsByDb.get(db);
157
+ if (!set) {
158
+ set = new Set<string>();
159
+ emittedTransitionsByDb.set(db, set);
160
+ }
161
+ return set;
162
+ }
163
+
164
+ async function hasRecordedOrderTopic(
165
+ db: Queryable,
166
+ tenantId: string,
167
+ externalOrderId: string,
168
+ topic: WebhookTopic,
169
+ ): Promise<boolean> {
170
+ try {
171
+ const row = await db.first<{ ok: number }>(
172
+ `SELECT 1 AS ok FROM webhook_events WHERE tenant_id = ? AND topic = ? AND json_extract(payload, '$.id') = ? LIMIT 1`,
173
+ tenantId,
174
+ topic,
175
+ externalOrderId,
176
+ );
177
+ return row !== null;
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /** Which topics this upsert's lifecycle/content transition warrants — `[]` for none. */
184
+ function topicsFor(previousOrder: Order | null, input: OrderForwardInput, order: Order): WebhookTopic[] {
185
+ const previousStatus = previousOrder?.status ?? null;
186
+ if (previousOrder === null) {
187
+ const initial: WebhookTopic[] = ["order.created"];
188
+ if (isPaidSignal(input)) initial.push("order.paid");
189
+ if (input.status === "fulfilled") initial.push("order.fulfilled");
190
+ if (isCancelledState(input.status, input.paymentStatus)) initial.push("order.cancelled");
191
+ return initial;
192
+ }
193
+
194
+ const emitted: WebhookTopic[] = [];
195
+ if (previousStatus === "created" && isPaidSignal(input)) {
196
+ emitted.push("order.paid");
123
197
  }
124
- if (previousStatus === "created" && status === "fulfilled") return ["order.fulfilled"];
125
- return [];
198
+ if ((previousStatus === "created" || previousStatus === "paid") && input.status === "fulfilled") {
199
+ emitted.push("order.fulfilled");
200
+ }
201
+ if (!isCancelledState(previousStatus) && isCancelledState(input.status, input.paymentStatus)) {
202
+ emitted.push("order.cancelled");
203
+ }
204
+ if (orderContentSignature(previousOrder) !== orderContentSignature(order)) {
205
+ emitted.push("order.updated");
206
+ }
207
+ return emitted;
126
208
  }
127
209
 
128
210
  /**
@@ -140,11 +222,14 @@ export async function receiveForwardedOrder(
140
222
  // input.rawCustomerId is intentionally not read here — see the module doc's
141
223
  // "Customer identity" note for why no hash is derived from it.
142
224
 
143
- const { previousStatus, order } = await store.upsertOrder({
225
+ const effectiveStatus: OrderStatus =
226
+ input.status === "created" && isPaidSignal(input) ? "paid" : input.status;
227
+
228
+ const { previousStatus, previousOrder, order } = await store.upsertOrder({
144
229
  tenantId: input.tenantId,
145
230
  externalOrderId: input.externalOrderId,
146
231
  env: input.env,
147
- status: input.status,
232
+ status: effectiveStatus,
148
233
  currency: input.currency,
149
234
  total: input.total,
150
235
  subtotal: input.subtotal ?? null,
@@ -152,15 +237,34 @@ export async function receiveForwardedOrder(
152
237
  createdAt: input.createdAt ?? new Date().toISOString(),
153
238
  });
154
239
 
240
+ const seenTransitions = transitionSetFor(db);
155
241
  const emitted: WebhookTopic[] = [];
156
- for (const topic of topicsFor(previousStatus, input.status)) {
242
+ for (const topic of topicsFor(previousOrder, input, order)) {
157
243
  if (topic === "order.fulfilled") {
158
244
  if (await emitClaimedOrderFulfilled(db, input, order, options.notify)) emitted.push(topic);
159
245
  continue;
160
246
  }
161
247
  const stage = forwardStage(input.env);
162
248
  if (!stage) continue;
249
+
250
+ const transitionKey =
251
+ topic === "order.updated"
252
+ ? `${input.tenantId}|${stage}|${input.externalOrderId}|order.updated|${
253
+ input.providerEventId ?? `${orderContentSignature(previousOrder!)}->${orderContentSignature(order)}`
254
+ }`
255
+ : `${input.tenantId}|${stage}|${input.externalOrderId}|${topic}`;
256
+
257
+ if (seenTransitions.has(transitionKey)) continue;
258
+ if (
259
+ topic !== "order.updated" &&
260
+ (await hasRecordedOrderTopic(db, input.tenantId, input.externalOrderId, topic))
261
+ ) {
262
+ seenTransitions.add(transitionKey);
263
+ continue;
264
+ }
265
+
163
266
  await emitWebhookEvent(topic, input.tenantId, toOrderData(order), { stage });
267
+ seenTransitions.add(transitionKey);
164
268
  emitted.push(topic);
165
269
  }
166
270
 
@@ -66,9 +66,13 @@ export interface ToContractOrderContext {
66
66
  * signal, e.g. a shipment event, once one exists).
67
67
  */
68
68
  const CANCELLED_STATUS_TOKENS = new Set(["cancelled", "canceled", "refunded", "voided", "rejected", "declined"]);
69
+ const FULFILLED_STATUS_TOKENS = new Set(["fulfilled", "shipped", "delivered"]);
69
70
 
70
71
  function toContractStatus(foxyStatus: string): ContractOrderStatus {
71
- return CANCELLED_STATUS_TOKENS.has(foxyStatus.toLowerCase()) ? "cancelled" : "created";
72
+ const normalized = foxyStatus.toLowerCase();
73
+ if (CANCELLED_STATUS_TOKENS.has(normalized)) return "cancelled";
74
+ if (FULFILLED_STATUS_TOKENS.has(normalized)) return "fulfilled";
75
+ return "created";
72
76
  }
73
77
 
74
78
  /**
@@ -213,11 +217,13 @@ function commandOf(value: Record<string, unknown>): CommerceCommandName | null {
213
217
 
214
218
  function readTotals(value: unknown): MinorTotals | null {
215
219
  if (!isRecord(value)) return null;
220
+ if (value.exciseMinor !== undefined && typeof value.exciseMinor !== "number") return null;
216
221
  const totals = {
217
222
  subtotalMinor: value.subtotalMinor,
218
223
  shippingMinor: value.shippingMinor,
219
224
  taxMinor: value.taxMinor,
220
225
  totalMinor: value.totalMinor,
226
+ ...(typeof value.exciseMinor === "number" ? { exciseMinor: value.exciseMinor } : {}),
221
227
  };
222
228
  if (
223
229
  typeof totals.subtotalMinor !== "number" ||
@@ -31,7 +31,7 @@ import {
31
31
  type StoredCommercePayload,
32
32
  } from "./orderMapper.js";
33
33
 
34
- export type OrderStatus = "created" | "fulfilled" | "refunded" | "cancelled";
34
+ export type OrderStatus = "created" | "paid" | "fulfilled" | "refunded" | "cancelled";
35
35
 
36
36
  /** One order line item (JSON-as-text in the row; see `Order.lineItems` in the contract). */
37
37
  export interface OrderLineItem {
@@ -80,6 +80,7 @@ export interface UpsertOrderInput {
80
80
  */
81
81
  export interface UpsertOrderResult {
82
82
  previousStatus: OrderStatus | null;
83
+ previousOrder: Order | null;
83
84
  order: Order;
84
85
  }
85
86
 
@@ -169,7 +170,7 @@ export class OrdersStore {
169
170
  }
170
171
 
171
172
  const order = await this.getOrder(input.tenantId, input.externalOrderId);
172
- return { previousStatus: existing?.status ?? null, order: order! };
173
+ return { previousStatus: existing?.status ?? null, previousOrder: existing, order: order! };
173
174
  }
174
175
 
175
176
  /** Read one order, scoped to the caller's own tenant. */
@@ -61,6 +61,8 @@ export interface FoxyOrder {
61
61
  externalNumber?: string;
62
62
  /** ISO 8601-*like* — Foxy's offset omits the colon (`-0500` not `-05:00`). */
63
63
  orderedAt: string;
64
+ /** Optional last-modified timestamp when upstream order state changed after placement. */
65
+ updatedAt?: string;
64
66
  currency: string;
65
67
  status: string;
66
68
  customerEmail?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.12.7",
3
+ "version": "6.12.9",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -798,6 +798,7 @@ export function publicCommerceEvent(
798
798
  shippingMinor: input.totals.shippingMinor,
799
799
  taxMinor: input.totals.taxMinor,
800
800
  totalMinor: input.totals.totalMinor,
801
+ ...(input.totals.exciseMinor === undefined ? {} : { exciseMinor: input.totals.exciseMinor }),
801
802
  },
802
803
  verificationDetail: {
803
804
  verification: input.verificationDetail.verification,