@tokenoftrust/storefront-runner 7.11.9 → 7.11.11

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.
@@ -2,7 +2,195 @@ import {
2
2
  isPublicCatalogProduct, normalizePurchaseOptions, priceForPurchaseOption, resolveMembershipRule,
3
3
  type CatalogProduct, type CatalogVariant, type TenantConfig,
4
4
  } from "@tot/public-runtime";
5
+ import type { Queryable, QueryStatement } from "@/lib/catalog/d1/catalog";
5
6
  import { resolveMemberContext } from "@/lib/membership/eligibility";
7
+ import type { ShopperScope } from "./scope";
8
+
9
+ export interface TierSkuPrice {
10
+ unitMinor: number;
11
+ currency: string;
12
+ }
13
+
14
+ export interface TierSkuPriceRow extends TierSkuPrice {
15
+ sku: string;
16
+ updatedAt: string;
17
+ }
18
+
19
+ export interface TierSkuPriceInput {
20
+ sku: string;
21
+ unitMinor: number;
22
+ currency?: string;
23
+ }
24
+
25
+ const MAX_SKU_LENGTH = 128;
26
+ const MAX_TIER_ID_LENGTH = 128;
27
+ const SKU_QUERY_CHUNK_SIZE = 90;
28
+ const UPSERT_BATCH_CHUNK_SIZE = 50;
29
+ const CURRENCY_RE = /^[A-Z]{3}$/;
30
+ const CONTROL_CHAR_RE = /\p{C}/u;
31
+
32
+ export function normalizePricingSku(raw: unknown): string | null {
33
+ if (typeof raw !== "string") return null;
34
+ const trimmed = raw.trim();
35
+ if (!trimmed || trimmed.length > MAX_SKU_LENGTH || CONTROL_CHAR_RE.test(trimmed)) return null;
36
+ return trimmed;
37
+ }
38
+
39
+ export function normalizePricingTierId(raw: unknown): string | null {
40
+ if (typeof raw !== "string") return null;
41
+ const trimmed = raw.trim();
42
+ if (!trimmed || trimmed.length > MAX_TIER_ID_LENGTH || CONTROL_CHAR_RE.test(trimmed)) return null;
43
+ return trimmed;
44
+ }
45
+
46
+ export function normalizePricingCurrency(raw: unknown): string | null {
47
+ if (raw === undefined) return "USD";
48
+ if (typeof raw !== "string" || !CURRENCY_RE.test(raw)) return null;
49
+ return raw;
50
+ }
51
+
52
+ export function normalizeTierSkuPriceInput(entry: unknown): { sku: string; unitMinor: number; currency: string } | null {
53
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null;
54
+ const record = entry as Record<string, unknown>;
55
+ for (const key of Object.keys(record)) {
56
+ if (key !== "sku" && key !== "unitMinor" && key !== "currency") return null;
57
+ }
58
+ const sku = normalizePricingSku(record.sku);
59
+ if (!sku) return null;
60
+ if (typeof record.unitMinor !== "number" || !Number.isSafeInteger(record.unitMinor) || record.unitMinor < 0) {
61
+ return null;
62
+ }
63
+ const currency = normalizePricingCurrency(record.currency);
64
+ if (!currency) return null;
65
+ return { sku, unitMinor: record.unitMinor, currency };
66
+ }
67
+
68
+ export async function readTierSkuPrices(
69
+ db: Queryable,
70
+ scope: ShopperScope,
71
+ tierId: string,
72
+ skus?: readonly string[],
73
+ ): Promise<Map<string, TierSkuPrice>> {
74
+ const normalizedTier = normalizePricingTierId(tierId);
75
+ const out = new Map<string, TierSkuPrice>();
76
+ if (!normalizedTier) return out;
77
+
78
+ if (skus === undefined) {
79
+ const rows = await db.all<{ sku: string; unit_minor: number; currency: string }>(
80
+ `SELECT sku, unit_minor, currency
81
+ FROM shopper_tier_sku_prices
82
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ?
83
+ ORDER BY sku ASC`,
84
+ scope.tenantId, scope.stage, normalizedTier,
85
+ );
86
+ for (const row of rows) {
87
+ out.set(row.sku, { unitMinor: row.unit_minor, currency: row.currency });
88
+ }
89
+ return out;
90
+ }
91
+
92
+ const uniqueSkus: string[] = [];
93
+ const seen = new Set<string>();
94
+ for (const rawSku of skus) {
95
+ const sku = normalizePricingSku(rawSku);
96
+ if (sku && !seen.has(sku)) {
97
+ seen.add(sku);
98
+ uniqueSkus.push(sku);
99
+ }
100
+ }
101
+ if (uniqueSkus.length === 0) return out;
102
+
103
+ for (let offset = 0; offset < uniqueSkus.length; offset += SKU_QUERY_CHUNK_SIZE) {
104
+ const chunk = uniqueSkus.slice(offset, offset + SKU_QUERY_CHUNK_SIZE);
105
+ const placeholders = chunk.map(() => "?").join(", ");
106
+ const rows = await db.all<{ sku: string; unit_minor: number; currency: string }>(
107
+ `SELECT sku, unit_minor, currency
108
+ FROM shopper_tier_sku_prices
109
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ? AND sku IN (${placeholders})`,
110
+ scope.tenantId, scope.stage, normalizedTier, ...chunk,
111
+ );
112
+ for (const row of rows) {
113
+ out.set(row.sku, { unitMinor: row.unit_minor, currency: row.currency });
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+
119
+ export async function listTierSkuPrices(
120
+ db: Queryable,
121
+ scope: ShopperScope,
122
+ tierId: string,
123
+ ): Promise<TierSkuPriceRow[]> {
124
+ const normalizedTier = normalizePricingTierId(tierId);
125
+ if (!normalizedTier) return [];
126
+ return db.all<TierSkuPriceRow>(
127
+ `SELECT sku, unit_minor AS unitMinor, currency, updated_at AS updatedAt
128
+ FROM shopper_tier_sku_prices
129
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ?
130
+ ORDER BY sku ASC`,
131
+ scope.tenantId, scope.stage, normalizedTier,
132
+ );
133
+ }
134
+
135
+ export async function upsertTierSkuPrices(
136
+ db: Queryable,
137
+ scope: ShopperScope,
138
+ tierId: string,
139
+ entries: readonly TierSkuPriceInput[],
140
+ nowIso = new Date().toISOString(),
141
+ ): Promise<number> {
142
+ const normalizedTier = normalizePricingTierId(tierId);
143
+ if (!normalizedTier) throw new Error("invalid_tier_id");
144
+
145
+ const normalized: { sku: string; unitMinor: number; currency: string }[] = [];
146
+ for (const entry of entries) {
147
+ const parsed = normalizeTierSkuPriceInput(entry);
148
+ if (!parsed) throw new Error("invalid_sku_price");
149
+ normalized.push(parsed);
150
+ }
151
+ if (normalized.length === 0) return 0;
152
+
153
+ const sql = `INSERT INTO shopper_tier_sku_prices (tenant_id, stage, tier_id, sku, unit_minor, currency, updated_at)
154
+ VALUES (?, ?, ?, ?, ?, ?, ?)
155
+ ON CONFLICT (tenant_id, stage, tier_id, sku) DO UPDATE SET
156
+ unit_minor = excluded.unit_minor,
157
+ currency = excluded.currency,
158
+ updated_at = excluded.updated_at`;
159
+
160
+ const statements: QueryStatement[] = normalized.map(entry => ({
161
+ sql,
162
+ params: [scope.tenantId, scope.stage, normalizedTier, entry.sku, entry.unitMinor, entry.currency, nowIso],
163
+ }));
164
+
165
+ if (db.batch) {
166
+ for (let offset = 0; offset < statements.length; offset += UPSERT_BATCH_CHUNK_SIZE) {
167
+ await db.batch(statements.slice(offset, offset + UPSERT_BATCH_CHUNK_SIZE));
168
+ }
169
+ } else {
170
+ for (const statement of statements) {
171
+ await db.run(statement.sql, ...(statement.params ?? []));
172
+ }
173
+ }
174
+ return normalized.length;
175
+ }
176
+
177
+ export async function deleteTierSkuPrice(
178
+ db: Queryable,
179
+ scope: ShopperScope,
180
+ tierId: string,
181
+ sku: string,
182
+ ): Promise<boolean> {
183
+ const normalizedTier = normalizePricingTierId(tierId);
184
+ const normalizedSku = normalizePricingSku(sku);
185
+ if (!normalizedTier || !normalizedSku) return false;
186
+ const deleted = await db.first<{ sku: string }>(
187
+ `DELETE FROM shopper_tier_sku_prices
188
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ? AND sku = ?
189
+ RETURNING sku`,
190
+ scope.tenantId, scope.stage, normalizedTier, normalizedSku,
191
+ );
192
+ return deleted !== null;
193
+ }
6
194
 
7
195
  export function shopperTierAvailable(tenant: TenantConfig, tierId: string): boolean {
8
196
  return resolveMembershipRule(resolveMemberContext({ memberTierId: tierId }), tenant.commerce?.membership) !== undefined;
@@ -12,10 +200,38 @@ export function shopperCatalogProduct(tenant: TenantConfig, product: CatalogProd
12
200
  return !!product && !!tenant.tot_data_scope && product.tenant_id === tenant.tot_data_scope && isPublicCatalogProduct(product);
13
201
  }
14
202
 
15
- export function shopperVariantPrice(tenant: TenantConfig, product: CatalogProduct, variant: CatalogVariant, tierId: string | null) {
203
+ export function shopperVariantPrice(
204
+ tenant: TenantConfig,
205
+ product: CatalogProduct,
206
+ variant: CatalogVariant,
207
+ tierId: string | null,
208
+ skuOverrides?: ReadonlyMap<string, TierSkuPrice>,
209
+ ) {
16
210
  if (tierId && !shopperTierAvailable(tenant, tierId)) return null;
17
211
  const option = normalizePurchaseOptions(product).find(candidate => candidate.kind === "one_time");
18
212
  if (!option || variant.product_id !== product.id || variant.tenant_id !== product.tenant_id) return null;
213
+
214
+ if (tierId && variant.sku && skuOverrides) {
215
+ const override = skuOverrides.get(variant.sku);
216
+ if (
217
+ override &&
218
+ override.currency.toUpperCase() === variant.currency.toUpperCase() &&
219
+ Number.isSafeInteger(override.unitMinor) &&
220
+ override.unitMinor >= 0
221
+ ) {
222
+ const price = override.unitMinor / 100;
223
+ const compareAtPrice = variant.price > price ? variant.price : (variant.compare_at_price ?? null);
224
+ return {
225
+ id: variant.id,
226
+ title: variant.title,
227
+ available: variant.inventory.available,
228
+ price,
229
+ compareAtPrice,
230
+ currency: variant.currency,
231
+ };
232
+ }
233
+ }
234
+
19
235
  const priced = priceForPurchaseOption(variant.price, option, {
20
236
  member: resolveMemberContext({ memberTierId: tierId }),
21
237
  program: tenant.commerce?.membership,
@@ -15,7 +15,7 @@ type PortalMutation = Extract<ShopperPortalAdmission, `${string}-mutation`>;
15
15
  export type ShopperRouteAdmission = {
16
16
  GET?: Exclude<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation" | PortalMutation>;
17
17
  POST?: Extract<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation" | PortalMutation>;
18
- DELETE?: PortalMutation;
18
+ DELETE?: Extract<ShopperAdmissionClass, "shopper-owner-mutation" | PortalMutation>;
19
19
  };
20
20
 
21
21
  export interface ShopperScope {
@@ -26,6 +26,8 @@ export interface ProcessorConfig {
26
26
  locationId: string;
27
27
  /** The install is active on this tenant, has an endpoint and holds `fulfillment:process`. */
28
28
  notifiable: boolean;
29
+ /** When true, ready orders routed to this processor auto-release without manual operator release. */
30
+ autoRelease: boolean;
29
31
  }
30
32
 
31
33
  export interface OpenAssignment {
@@ -52,14 +54,19 @@ export async function readProcessor(
52
54
  stage: CommerceStage,
53
55
  locationId: string = DEFAULT_LOCATION,
54
56
  ): Promise<ProcessorConfig | null> {
55
- const config = await db.get<{ install_id: string }>(
56
- `SELECT install_id FROM fulfillment_processor_config
57
+ const config = await db.get<{ install_id: string; auto_release: number }>(
58
+ `SELECT install_id, auto_release FROM fulfillment_processor_config
57
59
  WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active'`,
58
60
  [tenantId, stage, locationId],
59
61
  );
60
62
  if (!config) return null;
61
63
  const notifiable = await db.get<{ ok: number }>(`SELECT 1 AS ok WHERE ${NOTIFIABLE_INSTALL}`, [config.install_id, tenantId]);
62
- return { installId: config.install_id, locationId, notifiable: notifiable?.ok === 1 };
64
+ return {
65
+ installId: config.install_id,
66
+ locationId,
67
+ notifiable: notifiable?.ok === 1,
68
+ autoRelease: Number(config.auto_release) !== 0,
69
+ };
63
70
  }
64
71
 
65
72
  /** The processor an order at `locationId` routes to: that location's config, else the catch-all. */
@@ -167,19 +174,31 @@ export type SetProcessorRefusal =
167
174
  */
168
175
  export async function setProcessor(
169
176
  db: FulfillmentDatabase,
170
- input: { tenantId: string; stage: CommerceStage; locationId?: string; installId: string | null; actorId: string; now: string },
177
+ input: {
178
+ tenantId: string;
179
+ stage: CommerceStage;
180
+ locationId?: string;
181
+ installId: string | null;
182
+ autoRelease?: boolean;
183
+ actorId: string;
184
+ now: string;
185
+ },
171
186
  ): Promise<{ ok: true; installId: string | null } | SetProcessorRefusal> {
172
187
  const locationId = input.locationId ?? DEFAULT_LOCATION;
173
188
  if (!LOCATION_ID.test(locationId)) return { ok: false, code: "location-invalid" };
174
189
  for (let attempt = 0; attempt < 3; attempt++) {
175
190
  const current = await readProcessor(db, input.tenantId, input.stage, locationId);
176
- if ((current?.installId ?? null) === input.installId) return { ok: true, installId: input.installId };
177
- if (input.installId !== null && !(await installMayProcess(db, input.tenantId, input.installId))) {
191
+ const sameInstall = (current?.installId ?? null) === input.installId;
192
+ if (sameInstall && (input.installId === null || input.autoRelease === undefined || input.autoRelease === current?.autoRelease)) {
193
+ return { ok: true, installId: input.installId };
194
+ }
195
+ if (!sameInstall && input.installId !== null && !(await installMayProcess(db, input.tenantId, input.installId))) {
178
196
  const why = await processorIneligibility(db, input.tenantId, input.installId);
179
197
  if (why === "not-found") return { ok: false, code: "install-not-found" };
180
198
  if (why.length) return { ok: false, code: "install-not-processor", reasons: why };
181
199
  continue;
182
200
  }
201
+ const autoReleaseFlag = (input.autoRelease ?? true) ? 1 : 0;
183
202
  let first: SqlStatement;
184
203
  if (input.installId === null) {
185
204
  first = {
@@ -187,27 +206,34 @@ export async function setProcessor(
187
206
  WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active' AND install_id = ?`,
188
207
  params: [input.actorId, input.now, input.tenantId, input.stage, locationId, current!.installId],
189
208
  };
209
+ } else if (sameInstall && current) {
210
+ first = {
211
+ sql: `UPDATE fulfillment_processor_config SET auto_release = ?, updated_by = ?, updated_at = ?
212
+ WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active' AND install_id = ?`,
213
+ params: [autoReleaseFlag, input.actorId, input.now, input.tenantId, input.stage, locationId, current.installId],
214
+ };
190
215
  } else if (current) {
191
216
  first = {
192
- sql: `UPDATE fulfillment_processor_config SET install_id = ?, updated_by = ?, updated_at = ?
217
+ sql: `UPDATE fulfillment_processor_config SET install_id = ?, auto_release = ?, updated_by = ?, updated_at = ?
193
218
  WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active' AND install_id = ? AND ${NOTIFIABLE_INSTALL}`,
194
- params: [input.installId, input.actorId, input.now, input.tenantId, input.stage, locationId, current.installId, input.installId, input.tenantId],
219
+ params: [input.installId, autoReleaseFlag, input.actorId, input.now, input.tenantId, input.stage, locationId, current.installId, input.installId, input.tenantId],
195
220
  };
196
221
  } else {
197
222
  first = {
198
- sql: `INSERT INTO fulfillment_processor_config (tenant_id, stage, location_id, install_id, state, updated_by, updated_at)
199
- SELECT ?, ?, ?, ?, 'active', ?, ? WHERE ${NOTIFIABLE_INSTALL}
223
+ sql: `INSERT INTO fulfillment_processor_config (tenant_id, stage, location_id, install_id, state, auto_release, updated_by, updated_at)
224
+ SELECT ?, ?, ?, ?, 'active', ?, ?, ? WHERE ${NOTIFIABLE_INSTALL}
200
225
  ON CONFLICT (tenant_id, stage, location_id) DO UPDATE SET
201
- install_id = excluded.install_id, state = 'active', updated_by = excluded.updated_by, updated_at = excluded.updated_at
226
+ install_id = excluded.install_id, state = 'active', auto_release = excluded.auto_release,
227
+ updated_by = excluded.updated_by, updated_at = excluded.updated_at
202
228
  WHERE fulfillment_processor_config.state = 'cleared'`,
203
- params: [input.tenantId, input.stage, locationId, input.installId, input.actorId, input.now, input.installId, input.tenantId],
229
+ params: [input.tenantId, input.stage, locationId, input.installId, autoReleaseFlag, input.actorId, input.now, input.installId, input.tenantId],
204
230
  };
205
231
  }
206
232
  const statements: SqlStatement[] = [
207
233
  first,
208
234
  { sql: `SELECT json(CASE WHEN changes() >= 1 THEN 'true' ELSE 'cas-not-applied' END)`, params: [] },
209
235
  ];
210
- if (current) {
236
+ if (current && !sameInstall) {
211
237
  statements.push(
212
238
  releaseInstallAssignmentsStatement({
213
239
  tenantId: input.tenantId,
@@ -272,11 +298,12 @@ export function processorGuard(
272
298
  stage: CommerceStage,
273
299
  installId: string,
274
300
  locationId: string = DEFAULT_LOCATION,
301
+ requireAutoRelease = false,
275
302
  ): SqlStatement {
276
303
  return {
277
304
  sql: `EXISTS (
278
305
  SELECT 1 FROM fulfillment_processor_config AS pc
279
- WHERE pc.tenant_id = ? AND pc.stage = ? AND pc.location_id = ? AND pc.install_id = ? AND pc.state = 'active'
306
+ WHERE pc.tenant_id = ? AND pc.stage = ? AND pc.location_id = ? AND pc.install_id = ? AND pc.state = 'active'${requireAutoRelease ? " AND pc.auto_release = 1" : ""}
280
307
  ) AND ${NOTIFIABLE_INSTALL}`,
281
308
  params: [tenantId, stage, locationId, installId, installId, tenantId],
282
309
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.11.9",
3
+ "version": "7.11.11",
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",