@tokenoftrust/storefront-runner 7.15.0 → 8.0.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.
@@ -1,29 +1,55 @@
1
1
  /**
2
- * Cart compliance EVALUATOR — the single enforcement authority. Given a cart's
3
- * regulated lines, a ship-to destination, and a verification state, it returns a
4
- * structured decision on whether checkout may COMPLETE. This is the "not just a
5
- * notice" core: the notices render the same facts, but this function DECIDES.
2
+ * Cart compliance EVALUATOR — the pure declarative enforcement authority. Given a
3
+ * cart's lines, a ship-to destination, a sales channel, and a verification state,
4
+ * it evaluates the resolved `ComplianceRulePack` (plus stricter-only tenant overrides)
5
+ * and returns a structured decision on whether checkout may COMPLETE.
6
6
  *
7
- * Checkout completion + order creation are EXTERNAL (managed cart). So this
8
- * evaluator is consumed at two real fail-closed seams:
9
- * 1. the checkout PREFLIGHT (`/api/compliance/preflight`) — the storefront must
10
- * clear the cart here before handing off to the managed cart;
11
- * 2. the evidence PROMOTE gate — a regulated tenant is only promotable when its
12
- * enforcement wiring resolves (see `evidence-signals.ts`).
7
+ * Fail-closed everywhere: a regulated cart with no resolvable ruleset, a malformed
8
+ * rule pack or unknown operator, an unrecognized channel, a missing postal code when
9
+ * a destination carries ZIP-scoped rules, an unconfigured verification provider, an
10
+ * unsatisfied excise obligation, or an unknown/conflicting/invalid product fact BLOCKS.
13
11
  *
14
- * Fail-closed everywhere: a regulated cart with no resolvable ruleset, an
15
- * unconfigured verification provider, an unsatisfied excise obligation, or a
16
- * product the merchant has not classified shipping into a flavour-ban
17
- * jurisdiction BLOCKS.
18
- * Pure + edge-safe.
12
+ * Pure + edge-safe (zero Node imports, zero controlplane imports, zero `eval`).
19
13
  */
20
- import type { ComplianceRuleset } from "./ruleset.js";
21
- import { stateRuleFor, effectivePerOrderLimit, regionDisplayName } from "./ruleset.js";
22
- import type { ComplianceClassificationGap, ProductComplianceProfile } from "./profile.js";
23
- import { complianceClassificationGaps, isRegulatedProfile } from "./profile.js";
14
+ import type {
15
+ ComplianceBlockCode,
16
+ ComplianceRule,
17
+ ComplianceRuleset,
18
+ FieldPredicate,
19
+ RulePredicate,
20
+ SalesChannel,
21
+ TenantComplianceOverrides,
22
+ } from "./ruleset.js";
23
+ import {
24
+ combineTenantOverrides,
25
+ effectivePerOrderLimit,
26
+ mergeTenantOverrides,
27
+ normalizeRegionCode,
28
+ normalizeSalesChannel,
29
+ normalizeZip5,
30
+ regionDisplayName,
31
+ ruleMatchesDestinationAndChannel,
32
+ stateHasZipScopedRules,
33
+ validateRulePack,
34
+ } from "./ruleset.js";
35
+ import type {
36
+ CatalogReading,
37
+ ComplianceClassificationGap,
38
+ ProductComplianceProfile,
39
+ RegistryJurisdictionCode,
40
+ RegistryListingMap,
41
+ } from "./profile.js";
42
+ import {
43
+ complianceClassificationGaps,
44
+ isFlavoredNicotine,
45
+ isRegulatedProfile,
46
+ } from "./profile.js";
47
+ import { resolveRegistryListing } from "./state-directory.js";
24
48
  import type { VerificationState } from "./verification.js";
25
49
  import { resolveVerificationDecision } from "./verification.js";
26
50
 
51
+ export type { ComplianceBlockCode } from "./ruleset.js";
52
+
27
53
  export interface CartComplianceLine {
28
54
  sku: string;
29
55
  quantity: number;
@@ -44,9 +70,8 @@ export interface CartComplianceInput {
44
70
  /** Resolved ruleset, or null when it could NOT be resolved for a regulated tenant. */
45
71
  ruleset: ComplianceRuleset | null;
46
72
  /**
47
- * True when the tenant is regulated (age/nicotine). Drives fail-closed when the
48
- * ruleset is null. Independent of the lines so an empty/mis-tagged cart on a
49
- * regulated tenant still fails closed rather than sneaking through.
73
+ * True when the tenant is regulated (age/nicotine/regulated rule pack). Drives
74
+ * fail-closed when the ruleset is null or products are unclassified.
50
75
  */
51
76
  regulated: boolean;
52
77
  lines: CartComplianceLine[];
@@ -54,20 +79,12 @@ export interface CartComplianceInput {
54
79
  verification: VerificationState | null;
55
80
  /** Soft front-door affirmation (UX only; never a substitute for verification). */
56
81
  ageAffirmed?: boolean;
82
+ /** Sales channel (`"b2c"` | `"b2b"`). Unspecified defaults fail-closed to `"b2c"`. */
83
+ channel?: SalesChannel | string;
84
+ /** Optional merchant stricter-only overrides composed onto `ruleset.tenantOverrides`. */
85
+ tenantOverrides?: TenantComplianceOverrides;
57
86
  }
58
87
 
59
- export type ComplianceBlockCode =
60
- | "ruleset_unavailable"
61
- | "verification_unconfigured"
62
- | "verification_required"
63
- | "verification_failed"
64
- | "destination_required"
65
- | "region_prohibited"
66
- | "flavored_prohibited"
67
- | "cooling_agent_prohibited"
68
- | "purchase_limit_exceeded"
69
- | "excise_unavailable";
70
-
71
88
  export interface ComplianceBlock {
72
89
  code: ComplianceBlockCode;
73
90
  message: string;
@@ -76,19 +93,19 @@ export interface ComplianceBlock {
76
93
  /** `flavored_prohibited` only: the characterizing flavor labels that triggered it. */
77
94
  flavors?: string[];
78
95
  /**
79
- * `flavored_prohibited` only: the classification the product is missing. Set
80
- * when the block is the fail-closed default for an unclassified product
81
- * rather than a recorded characterizing flavour.
96
+ * `flavored_prohibited` only: the classification the product is missing when
97
+ * blocked as a fail-closed default for an unclassified item.
82
98
  */
83
99
  unclassified?: ComplianceClassificationGap[];
84
- /** True when this block is a fail-closed safety default, not a real violation. */
100
+ /** True when this block is a fail-closed safety default rather than an explicit ban match. */
85
101
  failedClosed?: boolean;
86
- /**
87
- * `region_prohibited` only (operator diagnostic): which declaration refused the
88
- * destination — the tenant ruleset's state no-ship rule, the product's
89
- * `compliance.restricted_states` no-ship list, or its `compliance.allowed_states` allowlist.
90
- */
91
- rule?: "ruleset" | "compliance.restricted_states" | "compliance.allowed_states";
102
+ /** Operator diagnostic naming which declaration layer refused the line/cart. */
103
+ rule?:
104
+ | "ruleset"
105
+ | "compliance.restricted_states"
106
+ | "compliance.allowed_states"
107
+ | "tenant.licensed_states"
108
+ | "tenant.override";
92
109
  /** `rule: "compliance.allowed_states"` only: the regions the product may ship to. */
93
110
  allowedRegions?: string[];
94
111
  /** `rule: "compliance.allowed_states"` only: declared tokens that are not a region code. */
@@ -97,7 +114,7 @@ export interface ComplianceBlock {
97
114
 
98
115
  export interface CartComplianceRequirements {
99
116
  ageVerification: "satisfied" | "required" | "blocked" | "not_required";
100
- /** Adult signature on delivery required (PACT baseline and/or a state rule). */
117
+ /** Adult signature on delivery required (PACT baseline and/or a jurisdiction rule). */
101
118
  adultSignature: boolean;
102
119
  exciseHandling: "managed-cart" | "provider" | "unavailable" | "not_required";
103
120
  destination: "provided" | "required" | "not_required";
@@ -122,26 +139,200 @@ export interface CartComplianceDecision {
122
139
  failedClosed: boolean;
123
140
  }
124
141
 
125
- /** Codes that are HARD stops (vs. actionable steps the shopper can still complete). */
142
+ /** Codes that are HARD stops (vs. actionable shopper steps). */
126
143
  const HARD_BLOCK_CODES: ReadonlySet<ComplianceBlockCode> = new Set([
127
144
  "ruleset_unavailable",
145
+ "invalid_ruleset",
128
146
  "verification_unconfigured",
129
147
  "verification_failed",
148
+ "postal_code_required",
130
149
  "region_prohibited",
131
150
  "flavored_prohibited",
132
151
  "cooling_agent_prohibited",
152
+ "registry_prohibited",
153
+ "fact_prohibited",
154
+ "pact_requirement_failed",
155
+ "sku_limit_exceeded",
133
156
  "purchase_limit_exceeded",
134
157
  "excise_unavailable",
135
158
  ]);
136
159
 
160
+ type PredicateOutcome = "true" | "false" | "indeterminate";
161
+ type ResolvedReading = CatalogReading<string | number | boolean | readonly string[] | RegistryListingMap>;
162
+
163
+ function resolveFieldReading(field: string, line: CartComplianceLine): ResolvedReading {
164
+ const p = line.profile;
165
+ switch (field) {
166
+ case "subject.regulated":
167
+ return { state: "known", value: isRegulatedProfile(p) };
168
+ case "subject.containsNicotine":
169
+ return { state: "known", value: p.containsNicotine };
170
+ case "subject.category":
171
+ return { state: "known", value: p.category };
172
+ case "subject.categoryClassified":
173
+ return { state: "known", value: p.categoryClassified };
174
+ case "subject.flavorStatus":
175
+ return { state: "known", value: p.flavorStatus };
176
+ case "subject.flavorClassified":
177
+ return { state: "known", value: p.flavorClassified };
178
+ case "subject.coolingAgent":
179
+ return p.coolingAgent === null ? { state: "unknown" } : { state: "known", value: p.coolingAgent };
180
+ case "subject.productClass":
181
+ return p.productClass !== undefined ? { state: "known", value: p.productClass } : { state: "unknown" };
182
+ case "catalog.registryListings":
183
+ return p.catalogFacts.registryListings;
184
+ case "catalog.fdaAuthorization":
185
+ return p.catalogFacts.fdaAuthorization;
186
+ case "catalog.nicotineOrigin":
187
+ return p.catalogFacts.nicotineOrigin;
188
+ case "catalog.containsLithiumBattery":
189
+ return p.catalogFacts.containsLithiumBattery;
190
+ case "catalog.unitWeightGrams":
191
+ return p.catalogFacts.unitWeightGrams;
192
+ case "catalog.childResistantPackaging":
193
+ return p.catalogFacts.childResistantPackaging;
194
+ case "catalog.manufacturerLegalName":
195
+ return p.catalogFacts.manufacturerLegalName;
196
+ case "catalog.liquidVolumeMl":
197
+ return p.catalogFacts.liquidVolumeMl;
198
+ case "catalog.systemType":
199
+ return p.catalogFacts.systemType;
200
+ default: {
201
+ if (field.startsWith("facts.")) {
202
+ const key = field.slice("facts.".length);
203
+ const raw = p.facts?.[key];
204
+ if (raw === undefined || raw === null) return { state: "unknown" };
205
+ if (typeof raw === "object" && !Array.isArray(raw) && "state" in raw) {
206
+ return raw as ResolvedReading;
207
+ }
208
+ return { state: "known", value: raw as string | number | boolean | readonly string[] };
209
+ }
210
+ return { state: "invalid" };
211
+ }
212
+ }
213
+ }
214
+
215
+ function evalLeafPredicate(pred: FieldPredicate, line: CartComplianceLine): PredicateOutcome {
216
+ const reading = resolveFieldReading(pred.field, line);
217
+
218
+ if (pred.op === "registry_listed") {
219
+ if (reading.state === "not_applicable") {
220
+ return pred.allowNotApplicable ? "true" : "indeterminate";
221
+ }
222
+ const status = resolveRegistryListing(
223
+ reading as CatalogReading<RegistryListingMap>,
224
+ pred.value as RegistryJurisdictionCode,
225
+ );
226
+ if (status === "listed") return "true";
227
+ if (status === "unlisted") return "false";
228
+ return "indeterminate";
229
+ }
230
+
231
+ if (reading.state === "not_applicable") {
232
+ return pred.allowNotApplicable ? "true" : "indeterminate";
233
+ }
234
+ if (reading.state !== "known") {
235
+ return "indeterminate";
236
+ }
237
+
238
+ const val = reading.value;
239
+ switch (pred.op) {
240
+ case "is_known": {
241
+ if (typeof val === "string") return val.trim().length > 0 ? "true" : "false";
242
+ if (Array.isArray(val)) return val.length > 0 ? "true" : "false";
243
+ return "true";
244
+ }
245
+ case "is_true":
246
+ return typeof val === "boolean" ? (val ? "true" : "false") : "indeterminate";
247
+ case "is_false":
248
+ return typeof val === "boolean" ? (!val ? "true" : "false") : "indeterminate";
249
+ case "eq":
250
+ return val === pred.value ? "true" : "false";
251
+ case "neq":
252
+ return val !== pred.value ? "true" : "false";
253
+ case "in":
254
+ return Array.isArray(pred.value) && (typeof val === "string" || typeof val === "number")
255
+ ? (pred.value.includes(val) ? "true" : "false")
256
+ : "indeterminate";
257
+ case "not_in":
258
+ return Array.isArray(pred.value) && (typeof val === "string" || typeof val === "number")
259
+ ? (!pred.value.includes(val) ? "true" : "false")
260
+ : "indeterminate";
261
+ case "gt":
262
+ case "gte":
263
+ case "lt":
264
+ case "lte": {
265
+ if (typeof val !== "number" || !Number.isFinite(val) || typeof pred.value !== "number" || !Number.isFinite(pred.value)) {
266
+ return "indeterminate";
267
+ }
268
+ if (pred.op === "gt") return val > pred.value ? "true" : "false";
269
+ if (pred.op === "gte") return val >= pred.value ? "true" : "false";
270
+ if (pred.op === "lt") return val < pred.value ? "true" : "false";
271
+ return val <= pred.value ? "true" : "false";
272
+ }
273
+ case "prefix":
274
+ return typeof val === "string" && typeof pred.value === "string"
275
+ ? (val.startsWith(pred.value) ? "true" : "false")
276
+ : "indeterminate";
277
+ default:
278
+ return "indeterminate";
279
+ }
280
+ }
281
+
282
+ /** Kleene 3-valued evaluator: `"indeterminate"` never coerces to `"true"` even under `not`. */
283
+ function evalPredicate(pred: RulePredicate, line: CartComplianceLine): PredicateOutcome {
284
+ if ("all" in pred) {
285
+ let sawIndeterminate = false;
286
+ for (const child of pred.all) {
287
+ const outcome = evalPredicate(child, line);
288
+ if (outcome === "false") return "false";
289
+ if (outcome === "indeterminate") sawIndeterminate = true;
290
+ }
291
+ return sawIndeterminate ? "indeterminate" : "true";
292
+ }
293
+ if ("any" in pred) {
294
+ let sawIndeterminate = false;
295
+ for (const child of pred.any) {
296
+ const outcome = evalPredicate(child, line);
297
+ if (outcome === "true") return "true";
298
+ if (outcome === "indeterminate") sawIndeterminate = true;
299
+ }
300
+ return sawIndeterminate ? "indeterminate" : "false";
301
+ }
302
+ if ("not" in pred) {
303
+ const inner = evalPredicate(pred.not, line);
304
+ if (inner === "true") return "false";
305
+ if (inner === "false") return "true";
306
+ return "indeterminate";
307
+ }
308
+ return evalLeafPredicate(pred, line);
309
+ }
310
+
311
+ function withNote(message: string, note: string | undefined): string {
312
+ return note ? `${message} (${note})` : message;
313
+ }
314
+
315
+ function defaultCoolingApplies(p: ProductComplianceProfile): boolean {
316
+ return p.containsNicotine || p.category === "e-liquid" || p.category === "ends";
317
+ }
318
+
319
+ function matchesSubject(
320
+ rule: ComplianceRule,
321
+ line: CartComplianceLine,
322
+ opts: { allowDefaultUnclassified?: boolean } = {},
323
+ ): PredicateOutcome {
324
+ if (!rule.when?.subjectMatch) {
325
+ return opts.allowDefaultUnclassified === false && !isRegulatedProfile(line.profile) ? "false" : "true";
326
+ }
327
+ return evalPredicate(rule.when.subjectMatch, line);
328
+ }
329
+
137
330
  export function evaluateCartCompliance(
138
331
  input: CartComplianceInput,
139
332
  ): CartComplianceDecision {
140
333
  const blocks: ComplianceBlock[] = [];
141
334
  const regulatedLines = input.lines.filter((l) => isRegulatedProfile(l.profile));
142
335
  const hasRegulatedGoods = regulatedLines.length > 0;
143
- // On a regulated tenant a product with no recorded category may be a
144
- // regulated one: it needs a destination and fails closed where flavours are banned.
145
336
  const unclassifiedLines = input.regulated
146
337
  ? input.lines.filter((l) => !isRegulatedProfile(l.profile) && !l.profile.categoryClassified)
147
338
  : [];
@@ -167,21 +358,47 @@ export function evaluateCartCompliance(
167
358
 
168
359
  const ruleset = input.ruleset;
169
360
  if (!ruleset || (!input.regulated && !hasRegulatedGoods)) {
170
- // Unregulated tenant, no regulated goods → nothing to enforce.
171
361
  return finalize(blocks, requirements, null);
172
362
  }
173
363
 
174
- // 2. Verification gate (fail-closed when required + no provider).
175
- const vDecision = resolveVerificationDecision(
176
- ruleset.verification,
177
- input.verification,
178
- );
364
+ // 2. Validate channel and declarative rule pack before granting any clearance.
365
+ const channel = normalizeSalesChannel(input.channel);
366
+ if (!channel) {
367
+ blocks.push({
368
+ code: "invalid_ruleset",
369
+ failedClosed: true,
370
+ message: "Unrecognized sales channel. Checkout is blocked (safe default = BLOCK).",
371
+ });
372
+ return finalize(blocks, requirements, null);
373
+ }
374
+
375
+ const packCheck = validateRulePack(ruleset.rulePack);
376
+ if (!packCheck.ok) {
377
+ blocks.push({
378
+ code: "invalid_ruleset",
379
+ failedClosed: true,
380
+ message: `Compliance rule pack failed validation (${packCheck.errors[0]}). Checkout is blocked (safe default = BLOCK).`,
381
+ });
382
+ return finalize(blocks, requirements, null);
383
+ }
384
+
385
+ const combinedOverrides = combineTenantOverrides(ruleset.tenantOverrides, input.tenantOverrides);
386
+ const merged = mergeTenantOverrides(ruleset.rulePack, combinedOverrides);
387
+ if (merged.licensedStatesInvalid || merged.invalidOverlayErrors.length > 0) {
388
+ blocks.push({
389
+ code: "invalid_ruleset",
390
+ failedClosed: true,
391
+ message: `Tenant compliance overrides are invalid (${merged.invalidOverlayErrors[0] ?? "malformed licensedStates"}). Checkout is blocked (safe default = BLOCK).`,
392
+ });
393
+ return finalize(blocks, requirements, null);
394
+ }
395
+
396
+ // 3. Verification gate (fail-closed when required + no provider).
397
+ const vDecision = resolveVerificationDecision(ruleset.verification, input.verification);
179
398
  requirements.ageVerification = vDecision.status;
180
399
  if (vDecision.status === "blocked") {
181
400
  blocks.push({
182
- code: vDecision.failedClosed
183
- ? "verification_unconfigured"
184
- : "verification_failed",
401
+ code: vDecision.failedClosed ? "verification_unconfigured" : "verification_failed",
185
402
  failedClosed: vDecision.failedClosed,
186
403
  message: vDecision.reason ?? "Age/identity verification failed.",
187
404
  });
@@ -192,7 +409,7 @@ export function evaluateCartCompliance(
192
409
  });
193
410
  }
194
411
 
195
- // 3. Excise obligation (fail-closed when required + unavailable).
412
+ // 4. Excise obligation (fail-closed when required + unavailable).
196
413
  if (ruleset.excise.required) {
197
414
  requirements.exciseHandling = ruleset.excise.handling;
198
415
  if (ruleset.excise.handling === "unavailable") {
@@ -206,53 +423,126 @@ export function evaluateCartCompliance(
206
423
  }
207
424
  }
208
425
 
209
- // 4. Adult signature (PACT baseline; a state rule can also require it).
426
+ // 5. Adult signature PACT baseline.
210
427
  requirements.adultSignature =
211
428
  ruleset.pactAct.enabled && ruleset.pactAct.adultSignatureRequired;
212
429
 
213
- // 5. Destination-dependent rules. If regulated goods but no ship-to state, the
214
- // cart cannot clear — the state must be known to apply jurisdiction rules.
430
+ // 6. Destination, ZIP, footprint, and per-line declarative rules.
431
+ const allEvaluatedLines = [...regulatedLines, ...unclassifiedLines];
432
+ let activeRules: ComplianceRule[] = [];
433
+ let regionRaw = "";
434
+ let regionCode = "";
435
+ let country = "";
436
+ let zip5: string | null = null;
437
+
215
438
  if (hasRegulatedGoods || unclassifiedLines.length > 0) {
216
439
  if (!input.destination) {
217
440
  requirements.destination = "required";
218
441
  blocks.push({
219
442
  code: "destination_required",
220
- message:
221
- "A ship-to state is required to confirm this order can be legally shipped.",
443
+ message: "A ship-to state is required to confirm this order can be legally shipped.",
222
444
  });
223
445
  } else {
224
446
  requirements.destination = "provided";
225
- const region = input.destination.region.trim().toUpperCase();
226
- const stateRule = stateRuleFor(ruleset, region);
227
- if (stateRule?.adultSignatureRequired) requirements.adultSignature = true;
447
+ country = input.destination.country.trim().toUpperCase();
448
+ regionRaw = input.destination.region.trim().toUpperCase();
449
+ regionCode = normalizeRegionCode(regionRaw);
450
+ const zipRaw = input.destination.postalCode?.trim() ?? "";
451
+ zip5 = normalizeZip5(zipRaw);
452
+
453
+ if (!country || !regionCode) {
454
+ blocks.push({
455
+ code: "destination_required",
456
+ failedClosed: true,
457
+ message: "A valid ship-to country and state are required (safe default = BLOCK).",
458
+ });
459
+ return finalize(blocks, requirements, null);
460
+ }
461
+
462
+ const zipScoped = stateHasZipScopedRules(
463
+ { rulePack: ruleset.rulePack, tenantOverrides: combinedOverrides },
464
+ { country, region: regionCode },
465
+ channel,
466
+ );
467
+ if ((zipScoped || (country === "US" && zipRaw.length > 0)) && !zip5) {
468
+ blocks.push({
469
+ code: "postal_code_required",
470
+ region: regionRaw,
471
+ failedClosed: true,
472
+ message: `A valid 5-digit postal code is required to evaluate shipping restrictions for ${regionRaw} (safe default = BLOCK).`,
473
+ });
474
+ }
475
+
476
+ activeRules = merged.rules.filter((rule) =>
477
+ ruleMatchesDestinationAndChannel(rule, { country, region: regionCode, zip5 }, channel),
478
+ );
479
+
480
+ for (const rule of activeRules) {
481
+ if (rule.effect.kind === "require_adult_signature") {
482
+ if (!rule.when?.subjectMatch || allEvaluatedLines.some((l) => matchesSubject(rule, l) !== "false")) {
483
+ requirements.adultSignature = true;
484
+ }
485
+ }
486
+ }
228
487
 
229
- // Cooling-agent refusals follow every other per-line block, so a flavour or region
230
- // refusal stays the cart's primary finding.
231
488
  const coolingBlocks: ComplianceBlock[] = [];
232
- for (const line of [...regulatedLines, ...unclassifiedLines]) {
233
- // Per-product ToT-synced restriction (data-driven per SKU).
234
- const perProductBanned = line.profile.restrictedRegions.includes(region);
235
- if (stateRule?.banAll || perProductBanned) {
489
+ const baseBanRules = activeRules.filter(
490
+ (r) => r.effect.kind === "ban_shipment" && !merged.overlayRuleIds.has(r.id),
491
+ );
492
+ const overlayBanRules = activeRules.filter(
493
+ (r) => r.effect.kind === "ban_shipment" && merged.overlayRuleIds.has(r.id),
494
+ );
495
+ const flavorRules = activeRules.filter((r) => r.effect.kind === "ban_flavored");
496
+ const coolingRules = activeRules.filter((r) => r.effect.kind === "ban_cooling_agent");
497
+ const predicateRules = activeRules.filter(
498
+ (r): r is ComplianceRule & { effect: Extract<ComplianceRule["effect"], { kind: "require_predicate" }> } =>
499
+ r.effect.kind === "require_predicate",
500
+ );
501
+
502
+ for (const line of allEvaluatedLines) {
503
+ const lineName = line.title ?? line.sku;
504
+ const isUnclassified = !isRegulatedProfile(line.profile) && !line.profile.categoryClassified;
505
+
506
+ // 6a. Base rule-pack ban_shipment.
507
+ const matchedBaseBan = baseBanRules.find((r) => matchesSubject(r, line) !== "false");
508
+ if (matchedBaseBan && matchedBaseBan.effect.kind === "ban_shipment") {
509
+ const outcome = matchesSubject(matchedBaseBan, line);
510
+ blocks.push({
511
+ code: matchedBaseBan.effect.code ?? "region_prohibited",
512
+ region: regionRaw,
513
+ sku: line.sku,
514
+ rule: "ruleset",
515
+ ...(outcome === "indeterminate" ? { failedClosed: true } : {}),
516
+ message:
517
+ matchedBaseBan.effect.message
518
+ ? withNote(matchedBaseBan.effect.message, matchedBaseBan.note)
519
+ : `${lineName} cannot be shipped to ${regionRaw}${
520
+ matchedBaseBan.note ? ` (${matchedBaseBan.note})` : ""
521
+ }.`,
522
+ });
523
+ continue;
524
+ }
525
+
526
+ // 6b. Per-product restricted_states (explicit SKU no-ship list).
527
+ if (line.profile.restrictedRegions.includes(regionRaw) || line.profile.restrictedRegions.includes(regionCode)) {
236
528
  blocks.push({
237
529
  code: "region_prohibited",
238
- region,
530
+ region: regionRaw,
239
531
  sku: line.sku,
240
- rule: stateRule?.banAll ? "ruleset" : "compliance.restricted_states",
241
- message: `${line.title ?? line.sku} cannot be shipped to ${region}${
242
- stateRule?.note ? ` (${stateRule.note})` : ""
243
- }.`,
532
+ rule: "compliance.restricted_states",
533
+ message: `${lineName} cannot be shipped to ${regionRaw}.`,
244
534
  });
245
535
  continue;
246
536
  }
247
- // Per-product ship-to allowlist: a declared list refuses every region it omits.
537
+
538
+ // 6c. Per-product allowed_states allowlist.
248
539
  const allowed = line.profile.allowedRegions;
249
- const regionCode = region.replace(/^US-/, "");
250
540
  if (allowed != null && !allowed.includes(regionCode)) {
251
541
  const rejected = line.profile.allowedRegionsRejected ?? [];
252
- const name = `${line.title ?? line.sku} can't be shipped to ${regionDisplayName(regionCode)}`;
542
+ const name = `${lineName} can't be shipped to ${regionDisplayName(regionCode)}`;
253
543
  blocks.push({
254
544
  code: "region_prohibited",
255
- region,
545
+ region: regionRaw,
256
546
  sku: line.sku,
257
547
  rule: "compliance.allowed_states",
258
548
  allowedRegions: [...allowed],
@@ -265,85 +555,269 @@ export function evaluateCartCompliance(
265
555
  });
266
556
  continue;
267
557
  }
268
- if (stateRule?.banCoolingAgents && coolingAgentApplies(line.profile) && line.profile.coolingAgent !== false) {
558
+
559
+ // 6d. Merchant licensed-state footprint (stricter-only Layer 3).
560
+ if (merged.licensedStates !== null && !merged.licensedStates.includes(regionCode)) {
561
+ blocks.push({
562
+ code: "region_prohibited",
563
+ region: regionRaw,
564
+ sku: line.sku,
565
+ rule: "tenant.licensed_states",
566
+ ...(merged.licensedStates.length === 0 ? { failedClosed: true } : {}),
567
+ message:
568
+ merged.licensedStates.length === 0
569
+ ? `${lineName} cannot be shipped to ${regionRaw}: merchant licensed-state footprint is empty (safe default = BLOCK).`
570
+ : `${lineName} cannot be shipped to ${regionRaw}: destination is outside the merchant's licensed-state footprint.`,
571
+ });
572
+ continue;
573
+ }
574
+
575
+ // 6e. Tenant stricter-only overlay ban_shipment rules.
576
+ const matchedOverlayBan = overlayBanRules.find((r) => matchesSubject(r, line) !== "false");
577
+ if (matchedOverlayBan && matchedOverlayBan.effect.kind === "ban_shipment") {
578
+ const outcome = matchesSubject(matchedOverlayBan, line);
579
+ blocks.push({
580
+ code: matchedOverlayBan.effect.code ?? "region_prohibited",
581
+ region: regionRaw,
582
+ sku: line.sku,
583
+ rule: "tenant.override",
584
+ ...(outcome === "indeterminate" ? { failedClosed: true } : {}),
585
+ message:
586
+ matchedOverlayBan.effect.message
587
+ ? withNote(matchedOverlayBan.effect.message, matchedOverlayBan.note)
588
+ : `${lineName} cannot be shipped to ${regionRaw}${
589
+ matchedOverlayBan.note ? ` (${matchedOverlayBan.note})` : ""
590
+ }.`,
591
+ });
592
+ continue;
593
+ }
594
+
595
+ // 6f. Cooling-agent prohibition (queued after primary flavor/predicate findings).
596
+ const matchedCooling = coolingRules.find((r) =>
597
+ r.when?.subjectMatch
598
+ ? matchesSubject(r, line) !== "false"
599
+ : defaultCoolingApplies(line.profile),
600
+ );
601
+ if (matchedCooling && line.profile.coolingAgent !== false) {
269
602
  const unrecorded = line.profile.coolingAgent === null;
270
603
  coolingBlocks.push({
271
604
  code: "cooling_agent_prohibited",
272
- region,
605
+ region: regionRaw,
273
606
  sku: line.sku,
274
607
  ...(unrecorded ? { failedClosed: true } : {}),
275
608
  message: unrecorded
276
- ? `${line.title ?? line.sku} cannot be shipped to ${region}: its cooling-agent status is not recorded, so it is treated as containing one (safe default = BLOCK)${
277
- stateRule.note ? ` (${stateRule.note})` : ""
609
+ ? `${lineName} cannot be shipped to ${regionRaw}: its cooling-agent status is not recorded, so it is treated as containing one (safe default = BLOCK)${
610
+ matchedCooling.note ? ` (${matchedCooling.note})` : ""
278
611
  }.`
279
- : `${line.title ?? line.sku} cannot be shipped to ${region}: it contains a cooling agent${
280
- stateRule.note ? ` (${stateRule.note})` : ""
612
+ : `${lineName} cannot be shipped to ${regionRaw}: it contains a cooling agent${
613
+ matchedCooling.note ? ` (${matchedCooling.note})` : ""
281
614
  }.`,
282
615
  });
283
616
  }
284
- const gaps = complianceClassificationGaps(line.profile);
285
- if (stateRule?.banFlavored && gaps.length > 0) {
286
- blocks.push({
287
- code: "flavored_prohibited",
288
- region,
289
- sku: line.sku,
290
- flavors: [],
291
- unclassified: gaps,
292
- failedClosed: true,
293
- message: `${line.title ?? line.sku} cannot be shipped to ${region}: its ${gaps
294
- .map((g) => (g === "flavor" ? "flavour" : g))
295
- .join(" and ")} is not classified, so it is treated as flavored (safe default = BLOCK)${
296
- stateRule.note ? ` (${stateRule.note})` : ""
297
- }.`,
298
- });
299
- continue;
617
+
618
+ // 6g. Flavored prohibition.
619
+ const matchedFlavor = flavorRules.find((r) => matchesSubject(r, line) !== "false");
620
+ let haltedOnUnclassified = false;
621
+ if (matchedFlavor) {
622
+ const gaps = complianceClassificationGaps(line.profile);
623
+ if (gaps.length > 0) {
624
+ blocks.push({
625
+ code: "flavored_prohibited",
626
+ region: regionRaw,
627
+ sku: line.sku,
628
+ flavors: [],
629
+ unclassified: gaps,
630
+ failedClosed: true,
631
+ message: `${lineName} cannot be shipped to ${regionRaw}: its ${gaps
632
+ .map((g) => (g === "flavor" ? "flavour" : g))
633
+ .join(" and ")} is not classified, so it is treated as flavored (safe default = BLOCK)${
634
+ matchedFlavor.note ? ` (${matchedFlavor.note})` : ""
635
+ }.`,
636
+ });
637
+ haltedOnUnclassified = true;
638
+ } else if (isFlavoredNicotine(line.profile)) {
639
+ const flavors = line.profile.characterizingFlavors;
640
+ blocks.push({
641
+ code: "flavored_prohibited",
642
+ region: regionRaw,
643
+ sku: line.sku,
644
+ flavors,
645
+ message: `${lineName} cannot be shipped to ${regionRaw}: flavored (${
646
+ flavors.length > 0 ? flavors.join(", ") : "unnamed flavor"
647
+ })${matchedFlavor.note ? ` (${matchedFlavor.note})` : ""}.`,
648
+ });
649
+ }
300
650
  }
301
- if (stateRule?.banFlavored && line.profile.isFlavored) {
302
- const flavors = line.profile.characterizingFlavors;
651
+ if (haltedOnUnclassified) continue;
652
+
653
+ // 6h. Generic declarative predicate requirements (registries, FDA, PACT physical, custom product classes).
654
+ for (const rule of predicateRules) {
655
+ const subjectOutcome = rule.when?.subjectMatch
656
+ ? evalPredicate(rule.when.subjectMatch, line)
657
+ : "true";
658
+
659
+ if (subjectOutcome === "false") {
660
+ if (isUnclassified && rule.effect.blockOnUnclassified) {
661
+ blocks.push({
662
+ code: rule.effect.code,
663
+ region: regionRaw,
664
+ sku: line.sku,
665
+ rule: merged.overlayRuleIds.has(rule.id) ? "tenant.override" : "ruleset",
666
+ failedClosed: true,
667
+ message: withNote(
668
+ rule.effect.failClosedMessage ??
669
+ `${lineName} cannot be shipped to ${regionRaw}: its product category is unclassified (safe default = BLOCK)`,
670
+ rule.note,
671
+ ),
672
+ });
673
+ }
674
+ continue;
675
+ }
676
+
677
+ if (subjectOutcome === "indeterminate") {
678
+ if (rule.effect.blockOnUnclassified || input.regulated) {
679
+ blocks.push({
680
+ code: rule.effect.code,
681
+ region: regionRaw,
682
+ sku: line.sku,
683
+ rule: merged.overlayRuleIds.has(rule.id) ? "tenant.override" : "ruleset",
684
+ failedClosed: true,
685
+ message: withNote(
686
+ rule.effect.failClosedMessage ??
687
+ `${rule.effect.message} (safe default = BLOCK)`,
688
+ rule.note,
689
+ ),
690
+ });
691
+ }
692
+ continue;
693
+ }
694
+
695
+ const outcome = evalPredicate(rule.effect.predicate, line);
696
+ if (outcome === "true") continue;
697
+ const failClosed = outcome === "indeterminate";
303
698
  blocks.push({
304
- code: "flavored_prohibited",
305
- region,
699
+ code: rule.effect.code,
700
+ region: regionRaw,
306
701
  sku: line.sku,
307
- flavors,
308
- message: `${line.title ?? line.sku} cannot be shipped to ${region}: flavored (${
309
- flavors.length > 0 ? flavors.join(", ") : "unnamed flavor"
310
- })${stateRule?.note ? ` (${stateRule.note})` : ""}.`,
702
+ rule: merged.overlayRuleIds.has(rule.id) ? "tenant.override" : "ruleset",
703
+ ...(failClosed ? { failedClosed: true } : {}),
704
+ message: withNote(
705
+ failClosed
706
+ ? (rule.effect.failClosedMessage ?? `${rule.effect.message} (safe default = BLOCK)`)
707
+ : rule.effect.message,
708
+ rule.note,
709
+ ),
311
710
  });
312
711
  }
313
712
  }
713
+
314
714
  blocks.push(...coolingBlocks);
315
715
  }
316
716
  }
317
717
 
318
- // 6. Purchase limit (per-order regulated-unit cap for the destination region).
718
+ // 7. Unit caps (per-SKU and per-order).
319
719
  let purchaseLimit: CartComplianceDecision["purchaseLimit"] = null;
320
- if (hasRegulatedGoods && input.destination) {
321
- const region = input.destination.region.trim().toUpperCase();
322
- const limit = effectivePerOrderLimit(ruleset, region);
720
+ if (hasRegulatedGoods && input.destination && regionCode) {
721
+ // 7a. Per-SKU limits (aggregating split lines carrying the same SKU).
722
+ const skuLimitRules = activeRules.filter(
723
+ (r): r is ComplianceRule & { effect: Extract<ComplianceRule["effect"], { kind: "per_sku_limit" }> } =>
724
+ r.effect.kind === "per_sku_limit",
725
+ );
726
+ const strictestSkuCap = new Map<string, { limit: number; units: number; code: ComplianceBlockCode; message?: string; note?: string }>();
727
+ for (const rule of skuLimitRules) {
728
+ const unitsBySku = new Map<string, number>();
729
+ for (const l of regulatedLines) {
730
+ if (matchesSubject(rule, l) !== "false") {
731
+ unitsBySku.set(l.sku, (unitsBySku.get(l.sku) ?? 0) + Math.max(0, l.quantity));
732
+ }
733
+ }
734
+ for (const [sku, units] of unitsBySku) {
735
+ const prev = strictestSkuCap.get(sku);
736
+ if (!prev || rule.effect.limit < prev.limit) {
737
+ strictestSkuCap.set(sku, {
738
+ limit: rule.effect.limit,
739
+ units,
740
+ code: rule.effect.code ?? "sku_limit_exceeded",
741
+ message: rule.effect.message,
742
+ note: rule.note,
743
+ });
744
+ }
745
+ }
746
+ }
747
+ for (const [sku, cap] of strictestSkuCap) {
748
+ if (cap.units > cap.limit) {
749
+ blocks.push({
750
+ code: cap.code,
751
+ region: regionRaw,
752
+ sku,
753
+ message: withNote(
754
+ cap.message ?? `SKU ${sku} (${cap.units} units) exceeds the ${cap.limit}-unit per-SKU limit for ${regionRaw}.`,
755
+ cap.note,
756
+ ),
757
+ });
758
+ }
759
+ }
760
+
761
+ // 7b. General unscoped per-order regulated-unit limit.
762
+ const unscopedRules = activeRules.filter(
763
+ (r): r is ComplianceRule & { effect: Extract<ComplianceRule["effect"], { kind: "per_order_limit" }> } =>
764
+ r.effect.kind === "per_order_limit" && !r.when?.subjectMatch,
765
+ );
766
+ const limit = effectivePerOrderLimit(
767
+ { rulePack: ruleset.rulePack, tenantOverrides: combinedOverrides },
768
+ { country, region: regionRaw, postalCode: zip5 ?? undefined },
769
+ { channel },
770
+ );
323
771
  if (limit != null && Number.isFinite(limit)) {
324
772
  const units = regulatedLines.reduce((n, l) => n + Math.max(0, l.quantity), 0);
325
773
  const exceeded = units > limit;
326
- purchaseLimit = { region, limit, units, exceeded };
774
+ purchaseLimit = { region: regionRaw, limit, units, exceeded };
327
775
  if (exceeded) {
776
+ const strictestRule = unscopedRules.reduce<typeof unscopedRules[number] | undefined>(
777
+ (best, curr) => (!best || curr.effect.limit < best.effect.limit ? curr : best),
778
+ undefined,
779
+ );
328
780
  blocks.push({
329
- code: "purchase_limit_exceeded",
330
- region,
331
- message: `This order (${units} units) exceeds the ${limit}-unit per-order limit for ${region}${
332
- stateRuleFor(ruleset, region)?.note ? ` (${stateRuleFor(ruleset, region)?.note})` : ""
333
- }.`,
781
+ code: strictestRule?.effect.code ?? "purchase_limit_exceeded",
782
+ region: regionRaw,
783
+ message: withNote(
784
+ strictestRule?.effect.message ?? `This order (${units} units) exceeds the ${limit}-unit per-order limit for ${regionRaw}.`,
785
+ strictestRule?.note,
786
+ ),
334
787
  });
335
788
  }
336
789
  }
790
+
791
+ // 7c. Scoped per-order limits (e.g., hazmat lithium-battery unit caps or synthetic class caps).
792
+ const scopedOrderRules = activeRules.filter(
793
+ (r): r is ComplianceRule & { effect: Extract<ComplianceRule["effect"], { kind: "per_order_limit" }> } =>
794
+ r.effect.kind === "per_order_limit" && r.when?.subjectMatch !== undefined,
795
+ );
796
+ for (const rule of scopedOrderRules) {
797
+ const matchingLines = regulatedLines.filter((l) => matchesSubject(rule, l) !== "false");
798
+ if (matchingLines.length === 0) continue;
799
+ const scopedUnits = matchingLines.reduce((n, l) => n + Math.max(0, l.quantity), 0);
800
+ if (scopedUnits > rule.effect.limit) {
801
+ blocks.push({
802
+ code: rule.effect.code ?? "purchase_limit_exceeded",
803
+ region: regionRaw,
804
+ message: withNote(
805
+ rule.effect.message ?? `This order (${scopedUnits} units) exceeds the ${rule.effect.limit}-unit per-order limit for ${regionRaw}.`,
806
+ rule.note,
807
+ ),
808
+ });
809
+ if (!purchaseLimit) {
810
+ purchaseLimit = { region: regionRaw, limit: rule.effect.limit, units: scopedUnits, exceeded: true };
811
+ }
812
+ } else if (!purchaseLimit) {
813
+ purchaseLimit = { region: regionRaw, limit: rule.effect.limit, units: scopedUnits, exceeded: false };
814
+ }
815
+ }
337
816
  }
338
817
 
339
818
  return finalize(blocks, requirements, purchaseLimit);
340
819
  }
341
820
 
342
- /** A cooling-agent ban reaches nicotine products and liquids/devices a nicotine product is made from. */
343
- function coolingAgentApplies(p: ProductComplianceProfile): boolean {
344
- return p.containsNicotine || p.category === "e-liquid" || p.category === "ends";
345
- }
346
-
347
821
  function finalize(
348
822
  blocks: ComplianceBlock[],
349
823
  requirements: CartComplianceRequirements,