@tokenoftrust/storefront-runner 7.11.10 → 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 {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.11.10",
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",