@tokenoftrust/storefront-runner 7.11.11 → 7.12.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.11.11",
3
+ "version": "7.12.0",
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",
@@ -40,6 +40,7 @@
40
40
  "./pool-asset-headers": "./src/pool-asset-headers.ts",
41
41
  "./catalog-files": "./src/catalog-files.ts",
42
42
  "./sku": "./src/sku.ts",
43
+ "./paste-order-list": "./src/catalog/paste-order-list.ts",
43
44
  "./embed-catalog": "./src/embed-catalog.mjs",
44
45
  "./retention-holds": "./src/retention-holds.ts",
45
46
  "./publication-content-redirects": "./src/publication-content-redirects.ts",
@@ -0,0 +1,551 @@
1
+ /**
2
+ * Deterministic-first Paste-a-List wholesale ordering parser & catalog matcher.
3
+ *
4
+ * Pure, edge-safe module (no Node APIs) that parses free-text wholesale order
5
+ * lists into structured quantity + query lines, matches them deterministically
6
+ * against active catalog products & variants, surfaces matched / ambiguous /
7
+ * unmatched outcomes, and aggregates matched lines into a cart batch.
8
+ */
9
+ import type { CatalogProduct, CatalogVariant } from "../product.js";
10
+ import { isPublicCatalogProduct } from "../product.js";
11
+ import { cartLineKey, MAX_CART_QUANTITY } from "../checkout.js";
12
+
13
+ /** Maximum accepted raw text payload (16 KiB). */
14
+ export const PASTE_ORDER_MAX_INPUT_BYTES = 16_384;
15
+
16
+ /** Maximum number of candidates surfaced for an ambiguous line. */
17
+ export const PASTE_ORDER_MAX_CANDIDATES = 5;
18
+
19
+ const MIN_FUZZY_SCORE = 0.55;
20
+ const MIN_QUERY_COVERAGE = 0.5;
21
+ const AMBIGUITY_MARGIN = 0.08;
22
+
23
+ const UNIT_ONLY_RE = /^(?:mg|ml|oz|g|kg|lb|lbs|ct|pk|pack|packs|box|boxes|case|cases)$/i;
24
+ const MEASURE_JOIN_RE = /(\d+)\s+(mg|ml|oz|g|kg|ct|pk)\b/gi;
25
+ const DEFAULT_VARIANT_TITLE = "default title";
26
+
27
+ export interface ParsedOrderLine {
28
+ /** 1-based index among non-empty parsed lines. */
29
+ lineNumber: number;
30
+ /** Trimmed raw segment before quantity extraction. */
31
+ rawLine: string;
32
+ /** Positive integer quantity clamped to 1..MAX_CART_QUANTITY. */
33
+ quantity: number;
34
+ /** True when the input explicitly stated a quantity; false when defaulted to 1. */
35
+ quantityExplicit: boolean;
36
+ /** Cleaned product/variant/SKU search query. */
37
+ query: string;
38
+ }
39
+
40
+ export type PasteOrderMatchKind = "sku" | "fuzzy";
41
+
42
+ export interface PasteOrderCandidate {
43
+ productId: string;
44
+ productHandle: string;
45
+ productTitle: string;
46
+ vendor?: string;
47
+ variantId: string;
48
+ variantTitle: string;
49
+ sku?: string;
50
+ lineKey: string;
51
+ optionValues: Record<string, string>;
52
+ /** Omitted when hidePrices is enabled. */
53
+ price?: number;
54
+ currency: string;
55
+ available: boolean;
56
+ /** Deterministic confidence score in [0, 1]. */
57
+ confidence: number;
58
+ matchKind: PasteOrderMatchKind;
59
+ }
60
+
61
+ export type PasteOrderLineStatus = "matched" | "ambiguous" | "unmatched";
62
+
63
+ export interface PasteOrderMatchedLine {
64
+ lineNumber: number;
65
+ rawLine: string;
66
+ query: string;
67
+ quantity: number;
68
+ quantityExplicit: boolean;
69
+ status: PasteOrderLineStatus;
70
+ /** Set when status === "matched". */
71
+ match?: PasteOrderCandidate;
72
+ /** Top candidate when matched, up to maxCandidates when ambiguous, empty when unmatched. */
73
+ candidates: PasteOrderCandidate[];
74
+ }
75
+
76
+ export interface PasteOrderCartItem {
77
+ productId: string;
78
+ productHandle: string;
79
+ productTitle: string;
80
+ variantId: string;
81
+ variantTitle: string;
82
+ sku?: string;
83
+ lineKey: string;
84
+ quantity: number;
85
+ /** Omitted when hidePrices is enabled. */
86
+ price?: number;
87
+ currency: string;
88
+ available: boolean;
89
+ }
90
+
91
+ export interface PasteOrderMatchResult {
92
+ lines: PasteOrderMatchedLine[];
93
+ matchedCount: number;
94
+ ambiguousCount: number;
95
+ unmatchedCount: number;
96
+ cartItems: PasteOrderCartItem[];
97
+ }
98
+
99
+ export interface MatchPasteOrderOptions {
100
+ /** Omit prices from candidates and cart items (e.g. hidePricesForGuests). */
101
+ hidePrices?: boolean;
102
+ /** Maximum candidates returned for ambiguous lines (default 5). */
103
+ maxCandidates?: number;
104
+ }
105
+
106
+ function clampQuantity(raw: number): number {
107
+ if (!Number.isFinite(raw) || raw < 1) return 1;
108
+ return Math.min(Math.floor(raw), MAX_CART_QUANTITY);
109
+ }
110
+
111
+ /**
112
+ * Split raw free-text input into individual candidate segments.
113
+ * Preserves inline ratios like "50/50" or "VG/PG" by only splitting on `/`
114
+ * when surrounded by whitespace (` / `).
115
+ */
116
+ function splitRawSegments(rawText: string): string[] {
117
+ const normalized = rawText.replace(/\r\n?/g, "\n");
118
+ const segments: string[] = [];
119
+ for (const line of normalized.split("\n")) {
120
+ for (const semiPart of line.split(";")) {
121
+ for (const slashPart of semiPart.split(/\s+\/\s+/)) {
122
+ const cleaned = slashPart
123
+ .trim()
124
+ .replace(/^(?:[-*•▪–—]\s+)+/, "")
125
+ .replace(/^\d+[.)]\s+/, "")
126
+ .trim();
127
+ if (cleaned.length > 0) {
128
+ segments.push(cleaned);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return segments;
134
+ }
135
+
136
+ function extractQuantityAndQuery(segment: string): {
137
+ quantity: number;
138
+ quantityExplicit: boolean;
139
+ query: string;
140
+ } {
141
+ // 1. Leading "10 x Product", "10x Product", "10 * Product"
142
+ const leadingCross = /^(\d+)\s*[x×*]\s+(.+)$/i.exec(segment);
143
+ if (leadingCross?.[1] && leadingCross[2]) {
144
+ const query = leadingCross[2].trim();
145
+ if (query.length > 0) {
146
+ return { quantity: clampQuantity(Number(leadingCross[1])), quantityExplicit: true, query };
147
+ }
148
+ }
149
+
150
+ // 2. Leading "x 10 Product" / "x10 Product"
151
+ const leadingXFirst = /^[x×]\s*(\d+)\s+(.+)$/i.exec(segment);
152
+ if (leadingXFirst?.[1] && leadingXFirst[2]) {
153
+ const query = leadingXFirst[2].trim();
154
+ if (query.length > 0) {
155
+ return { quantity: clampQuantity(Number(leadingXFirst[1])), quantityExplicit: true, query };
156
+ }
157
+ }
158
+
159
+ // 3. Trailing "SKU-123 x 5" / "SKU-123 x5" / "SKU-123 * 5"
160
+ const trailingCross = /^(.+?)\s+[x×*]\s*(\d+)$/i.exec(segment);
161
+ if (trailingCross?.[1] && trailingCross[2]) {
162
+ const query = trailingCross[1].trim();
163
+ if (query.length > 0) {
164
+ return { quantity: clampQuantity(Number(trailingCross[2])), quantityExplicit: true, query };
165
+ }
166
+ }
167
+
168
+ // 4. Trailing "SKU-123 qty 5" / "SKU-123 qty: 5"
169
+ const trailingQtyWord = /^(.+?)\s+(?:qty|quantity)[:=\s]+(\d+)$/i.exec(segment);
170
+ if (trailingQtyWord?.[1] && trailingQtyWord[2]) {
171
+ const query = trailingQtyWord[1].trim();
172
+ if (query.length > 0) {
173
+ return { quantity: clampQuantity(Number(trailingQtyWord[2])), quantityExplicit: true, query };
174
+ }
175
+ }
176
+
177
+ // 5. Trailing "SKU-123, 5"
178
+ const trailingComma = /^(.+?)\s*,\s*(\d+)$/.exec(segment);
179
+ if (trailingComma?.[1] && trailingComma[2]) {
180
+ const query = trailingComma[1].trim();
181
+ if (query.length > 0) {
182
+ return { quantity: clampQuantity(Number(trailingComma[2])), quantityExplicit: true, query };
183
+ }
184
+ }
185
+
186
+ // 6. Trailing "SKU-123 - 5" (requires spaces around dash so hyphenated SKUs stay intact)
187
+ const trailingDash = /^(.+?)\s+[-–—]\s+(\d+)$/.exec(segment);
188
+ if (trailingDash?.[1] && trailingDash[2]) {
189
+ const query = trailingDash[1].trim();
190
+ if (query.length > 0) {
191
+ return { quantity: clampQuantity(Number(trailingDash[2])), quantityExplicit: true, query };
192
+ }
193
+ }
194
+
195
+ // 7. Trailing parenthetical "HorizonTech Pink Lemonade (10)"
196
+ const trailingParens = /^(.+?)\s*\(\s*(\d+)\s*\)$/.exec(segment);
197
+ if (trailingParens?.[1] && trailingParens[2]) {
198
+ const query = trailingParens[1].trim();
199
+ if (query.length > 0) {
200
+ return { quantity: clampQuantity(Number(trailingParens[2])), quantityExplicit: true, query };
201
+ }
202
+ }
203
+
204
+ // 8. Leading bare integer "12 Blue Razz 35mg"
205
+ const leadingNumber = /^(\d+)\s+(.+)$/.exec(segment);
206
+ if (leadingNumber?.[1] && leadingNumber[2]) {
207
+ const query = leadingNumber[2].trim();
208
+ if (query.length > 0 && !UNIT_ONLY_RE.test(query)) {
209
+ return { quantity: clampQuantity(Number(leadingNumber[1])), quantityExplicit: true, query };
210
+ }
211
+ }
212
+
213
+ return { quantity: 1, quantityExplicit: false, query: segment };
214
+ }
215
+
216
+ /**
217
+ * Deterministically parse a free-text wholesale order list into structured lines.
218
+ */
219
+ export function parsePasteOrderList(rawText: string): ParsedOrderLine[] {
220
+ if (!rawText || typeof rawText !== "string") return [];
221
+ const segments = splitRawSegments(rawText);
222
+ return segments.map((rawLine, index) => {
223
+ const { quantity, quantityExplicit, query } = extractQuantityAndQuery(rawLine);
224
+ return {
225
+ lineNumber: index + 1,
226
+ rawLine,
227
+ quantity,
228
+ quantityExplicit,
229
+ query,
230
+ };
231
+ });
232
+ }
233
+
234
+ function tokenize(text: string): string[] {
235
+ const normalized = text
236
+ .toLowerCase()
237
+ .replace(MEASURE_JOIN_RE, "$1$2");
238
+ const raw = normalized.split(/[^a-z0-9]+/);
239
+ const seen = new Set<string>();
240
+ const out: string[] = [];
241
+ for (const token of raw) {
242
+ if (token.length > 0 && !seen.has(token)) {
243
+ seen.add(token);
244
+ out.push(token);
245
+ }
246
+ }
247
+ return out;
248
+ }
249
+
250
+ interface IndexedVariant {
251
+ product: CatalogProduct;
252
+ variant: CatalogVariant;
253
+ skuLower: string | null;
254
+ coreTokens: Set<string>;
255
+ coreTokenList: string[];
256
+ variantTokens: Set<string>;
257
+ variantTokenList: string[];
258
+ }
259
+
260
+ function indexCatalog(products: readonly CatalogProduct[]): IndexedVariant[] {
261
+ const indexed: IndexedVariant[] = [];
262
+ for (const product of products) {
263
+ if (!isPublicCatalogProduct(product)) continue;
264
+ const productTokens = tokenize([product.title, product.vendor ?? ""].join(" "));
265
+ for (const variant of product.variants) {
266
+ const optionTexts = Object.values(variant.option_values ?? {});
267
+ const variantTitleClean =
268
+ variant.title && variant.title.trim().toLowerCase() !== DEFAULT_VARIANT_TITLE
269
+ ? variant.title
270
+ : "";
271
+ const variantTokenList = tokenize([variantTitleClean, ...optionTexts].join(" "));
272
+ const variantTokens = new Set(variantTokenList);
273
+ const skuTokens = variant.sku ? tokenize(variant.sku) : [];
274
+
275
+ const coreTokens = new Set<string>([...productTokens, ...variantTokenList, ...skuTokens]);
276
+ const skuLower = variant.sku?.trim() ? variant.sku.trim().toLowerCase() : null;
277
+
278
+ indexed.push({
279
+ product,
280
+ variant,
281
+ skuLower,
282
+ coreTokens,
283
+ coreTokenList: [...coreTokens],
284
+ variantTokens,
285
+ variantTokenList,
286
+ });
287
+ }
288
+ }
289
+ return indexed;
290
+ }
291
+
292
+ function tokenMatchWeight(queryToken: string, targetSet: Set<string>, targetList: string[]): number {
293
+ if (targetSet.has(queryToken)) return 1.0;
294
+ if (queryToken.length >= 3) {
295
+ for (const target of targetList) {
296
+ if (target.startsWith(queryToken) || (target.length >= 4 && queryToken.startsWith(target))) {
297
+ return 0.7;
298
+ }
299
+ }
300
+ }
301
+ return 0;
302
+ }
303
+
304
+ function toCandidate(
305
+ entry: IndexedVariant,
306
+ confidence: number,
307
+ matchKind: PasteOrderMatchKind,
308
+ hidePrices: boolean,
309
+ ): PasteOrderCandidate {
310
+ const { product, variant } = entry;
311
+ const candidate: PasteOrderCandidate = {
312
+ productId: product.id,
313
+ productHandle: product.handle,
314
+ productTitle: product.title,
315
+ variantId: variant.id,
316
+ variantTitle: variant.title,
317
+ lineKey: cartLineKey(variant),
318
+ optionValues: { ...(variant.option_values ?? {}) },
319
+ currency: variant.currency,
320
+ available: Boolean(variant.inventory?.available),
321
+ confidence: Math.round(confidence * 1000) / 1000,
322
+ matchKind,
323
+ };
324
+ if (product.vendor) candidate.vendor = product.vendor;
325
+ if (variant.sku) candidate.sku = variant.sku;
326
+ if (!hidePrices) candidate.price = variant.price;
327
+ return candidate;
328
+ }
329
+
330
+ function scoreLine(
331
+ parsed: ParsedOrderLine,
332
+ catalog: readonly IndexedVariant[],
333
+ hidePrices: boolean,
334
+ maxCandidates: number,
335
+ ): PasteOrderMatchedLine {
336
+ const qSku = parsed.query.trim().toLowerCase();
337
+
338
+ // 1. Exact SKU match (case-insensitive)
339
+ if (qSku.length > 0) {
340
+ const exactSkuMatches = catalog.filter((entry) => entry.skuLower !== null && entry.skuLower === qSku);
341
+ const firstExact = exactSkuMatches[0];
342
+ if (exactSkuMatches.length === 1 && firstExact) {
343
+ const match = toCandidate(firstExact, 1.0, "sku", hidePrices);
344
+ return {
345
+ lineNumber: parsed.lineNumber,
346
+ rawLine: parsed.rawLine,
347
+ query: parsed.query,
348
+ quantity: parsed.quantity,
349
+ quantityExplicit: parsed.quantityExplicit,
350
+ status: "matched",
351
+ match,
352
+ candidates: [match],
353
+ };
354
+ }
355
+ if (exactSkuMatches.length > 1) {
356
+ const candidates = exactSkuMatches
357
+ .slice(0, maxCandidates)
358
+ .map((entry) => toCandidate(entry, 1.0, "sku", hidePrices));
359
+ return {
360
+ lineNumber: parsed.lineNumber,
361
+ rawLine: parsed.rawLine,
362
+ query: parsed.query,
363
+ quantity: parsed.quantity,
364
+ quantityExplicit: parsed.quantityExplicit,
365
+ status: "ambiguous",
366
+ candidates,
367
+ };
368
+ }
369
+ }
370
+
371
+ // 2. Deterministic fuzzy token-overlap scoring
372
+ const queryTokens = tokenize(parsed.query);
373
+ if (queryTokens.length === 0) {
374
+ return {
375
+ lineNumber: parsed.lineNumber,
376
+ rawLine: parsed.rawLine,
377
+ query: parsed.query,
378
+ quantity: parsed.quantity,
379
+ quantityExplicit: parsed.quantityExplicit,
380
+ status: "unmatched",
381
+ candidates: [],
382
+ };
383
+ }
384
+
385
+ const queryTokenSet = new Set(queryTokens);
386
+ const scored: { entry: IndexedVariant; score: number }[] = [];
387
+
388
+ for (const entry of catalog) {
389
+ if (entry.coreTokens.size === 0) continue;
390
+
391
+ let queryHitWeight = 0;
392
+ for (const qt of queryTokens) {
393
+ queryHitWeight += tokenMatchWeight(qt, entry.coreTokens, entry.coreTokenList);
394
+ }
395
+ const queryCoverage = queryHitWeight / queryTokens.length;
396
+ if (queryCoverage < MIN_QUERY_COVERAGE) continue;
397
+
398
+ let variantCoverage = 1.0;
399
+ if (entry.variantTokenList.length > 0) {
400
+ let variantHitWeight = 0;
401
+ for (const vt of entry.variantTokenList) {
402
+ variantHitWeight += tokenMatchWeight(vt, queryTokenSet, queryTokens);
403
+ }
404
+ variantCoverage = variantHitWeight / entry.variantTokenList.length;
405
+ }
406
+
407
+ let coreHitCount = 0;
408
+ for (const ct of entry.coreTokenList) {
409
+ if (tokenMatchWeight(ct, queryTokenSet, queryTokens) > 0) {
410
+ coreHitCount += 1;
411
+ }
412
+ }
413
+ const corePrecision = coreHitCount / entry.coreTokenList.length;
414
+
415
+ const rawScore = 0.72 * queryCoverage + 0.18 * variantCoverage + 0.10 * corePrecision;
416
+ const score = Math.min(0.99, rawScore);
417
+
418
+ if (score >= MIN_FUZZY_SCORE) {
419
+ scored.push({ entry, score });
420
+ }
421
+ }
422
+
423
+ if (scored.length === 0) {
424
+ return {
425
+ lineNumber: parsed.lineNumber,
426
+ rawLine: parsed.rawLine,
427
+ query: parsed.query,
428
+ quantity: parsed.quantity,
429
+ quantityExplicit: parsed.quantityExplicit,
430
+ status: "unmatched",
431
+ candidates: [],
432
+ };
433
+ }
434
+
435
+ scored.sort((a, b) => {
436
+ if (b.score !== a.score) return b.score - a.score;
437
+ const availDiff = Number(Boolean(b.entry.variant.inventory?.available)) - Number(Boolean(a.entry.variant.inventory?.available));
438
+ if (availDiff !== 0) return availDiff;
439
+ if (a.entry.product.handle !== b.entry.product.handle) {
440
+ return a.entry.product.handle < b.entry.product.handle ? -1 : 1;
441
+ }
442
+ return a.entry.variant.id < b.entry.variant.id ? -1 : a.entry.variant.id > b.entry.variant.id ? 1 : 0;
443
+ });
444
+
445
+ const top = scored[0];
446
+ if (!top) {
447
+ return {
448
+ lineNumber: parsed.lineNumber,
449
+ rawLine: parsed.rawLine,
450
+ query: parsed.query,
451
+ quantity: parsed.quantity,
452
+ quantityExplicit: parsed.quantityExplicit,
453
+ status: "unmatched",
454
+ candidates: [],
455
+ };
456
+ }
457
+ const second = scored[1];
458
+ const unambiguous = !second || top.score - second.score >= AMBIGUITY_MARGIN;
459
+
460
+ if (unambiguous) {
461
+ const match = toCandidate(top.entry, top.score, "fuzzy", hidePrices);
462
+ return {
463
+ lineNumber: parsed.lineNumber,
464
+ rawLine: parsed.rawLine,
465
+ query: parsed.query,
466
+ quantity: parsed.quantity,
467
+ quantityExplicit: parsed.quantityExplicit,
468
+ status: "matched",
469
+ match,
470
+ candidates: [match],
471
+ };
472
+ }
473
+
474
+ const candidates = scored
475
+ .slice(0, maxCandidates)
476
+ .map((item) => toCandidate(item.entry, item.score, "fuzzy", hidePrices));
477
+
478
+ return {
479
+ lineNumber: parsed.lineNumber,
480
+ rawLine: parsed.rawLine,
481
+ query: parsed.query,
482
+ quantity: parsed.quantity,
483
+ quantityExplicit: parsed.quantityExplicit,
484
+ status: "ambiguous",
485
+ candidates,
486
+ };
487
+ }
488
+
489
+ /**
490
+ * Parse a free-text wholesale order list and deterministically match each line
491
+ * against active catalog products & variants, returning matched/ambiguous/unmatched
492
+ * lines plus an aggregated cart batch for matched variants.
493
+ */
494
+ export function matchPasteOrderList(
495
+ rawText: string,
496
+ products: readonly CatalogProduct[],
497
+ options: MatchPasteOrderOptions = {},
498
+ ): PasteOrderMatchResult {
499
+ const hidePrices = options.hidePrices === true;
500
+ const maxCandidates = Math.max(1, Math.min(options.maxCandidates ?? PASTE_ORDER_MAX_CANDIDATES, 10));
501
+
502
+ const parsedLines = parsePasteOrderList(rawText);
503
+ const catalog = indexCatalog(products);
504
+
505
+ const lines: PasteOrderMatchedLine[] = [];
506
+ let matchedCount = 0;
507
+ let ambiguousCount = 0;
508
+ let unmatchedCount = 0;
509
+
510
+ const cartByVariantId = new Map<string, PasteOrderCartItem>();
511
+
512
+ for (const parsed of parsedLines) {
513
+ const result = scoreLine(parsed, catalog, hidePrices, maxCandidates);
514
+ lines.push(result);
515
+
516
+ if (result.status === "matched" && result.match) {
517
+ matchedCount += 1;
518
+ const existing = cartByVariantId.get(result.match.variantId);
519
+ if (existing) {
520
+ existing.quantity = clampQuantity(existing.quantity + result.quantity);
521
+ } else {
522
+ const item: PasteOrderCartItem = {
523
+ productId: result.match.productId,
524
+ productHandle: result.match.productHandle,
525
+ productTitle: result.match.productTitle,
526
+ variantId: result.match.variantId,
527
+ variantTitle: result.match.variantTitle,
528
+ lineKey: result.match.lineKey,
529
+ quantity: result.quantity,
530
+ currency: result.match.currency,
531
+ available: result.match.available,
532
+ };
533
+ if (result.match.sku) item.sku = result.match.sku;
534
+ if (!hidePrices && result.match.price !== undefined) item.price = result.match.price;
535
+ cartByVariantId.set(result.match.variantId, item);
536
+ }
537
+ } else if (result.status === "ambiguous") {
538
+ ambiguousCount += 1;
539
+ } else {
540
+ unmatchedCount += 1;
541
+ }
542
+ }
543
+
544
+ return {
545
+ lines,
546
+ matchedCount,
547
+ ambiguousCount,
548
+ unmatchedCount,
549
+ cartItems: [...cartByVariantId.values()],
550
+ };
551
+ }