@questwork/q-store-model 0.2.1 → 0.2.2

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.
@@ -0,0 +1,31 @@
1
+ export const ACQUISITION_SOURCES: Readonly<{
2
+ PURCHASE: "PURCHASE";
3
+ ADMIN_ASSIGNMENT: "ADMIN_ASSIGNMENT";
4
+ ROLE_BENEFIT: "ROLE_BENEFIT";
5
+ PROMOTION_REDEMPTION: "PROMOTION_REDEMPTION";
6
+ }>;
7
+ export const ORDER_STATES: Readonly<{
8
+ CREATED: "CREATED";
9
+ PAYMENT_REQUIRED: "PAYMENT_REQUIRED";
10
+ PAYMENT_IN_PROGRESS: "PAYMENT_IN_PROGRESS";
11
+ PAID: "PAID";
12
+ COMPLETED: "COMPLETED";
13
+ CANCELLED: "CANCELLED";
14
+ EXPIRED: "EXPIRED";
15
+ }>;
16
+ export const PAYMENT_ATTEMPT_STATES: Readonly<{
17
+ CREATED: "CREATED";
18
+ PAYMENT_IN_PROGRESS: "PAYMENT_IN_PROGRESS";
19
+ SUCCEEDED: "SUCCEEDED";
20
+ FAILED: "FAILED";
21
+ CANCELLED: "CANCELLED";
22
+ EXPIRED: "EXPIRED";
23
+ }>;
24
+ export const RESERVATION_STATES: Readonly<{
25
+ HELD_FOR_CHECKOUT: "HELD_FOR_CHECKOUT";
26
+ HELD_FOR_PROVIDER: "HELD_FOR_PROVIDER";
27
+ HELD_FOR_REVIEW: "HELD_FOR_REVIEW";
28
+ CONSUMED: "CONSUMED";
29
+ RELEASED: "RELEASED";
30
+ EXPIRED: "EXPIRED";
31
+ }>;
@@ -5,7 +5,7 @@ export function createAcquisitionSnapshot({ id, evaluated, preview, context }: {
5
5
  preview: any;
6
6
  context: any;
7
7
  }): AcquisitionSnapshot;
8
- export function evaluateAcquisitionPreview({ acquisitionSource, categories, countryCode, countryRank, currency, eligibilityFacts, eventRegistrationCode, existingItems, instant, inventoryFacts, merchandise, priceSchedule, products, publishedRules, quantity, requirementInputs, requirementValues, variants, variantSelections, recipientFacts, }: {
8
+ export function evaluateAcquisitionPreview({ acquisitionSource, categories, countryCode, countryRank, currency, eligibilityFacts, eventRegistrationCode, existingItems, instant, inventoryFacts, merchandise, priceSchedule, products, publishedRules, quantity, requirementInputs, requirementValues, salesPeriods, variants, variantSelections, recipientFacts, }: {
9
9
  acquisitionSource: any;
10
10
  categories: any;
11
11
  countryCode: any;
@@ -23,6 +23,7 @@ export function evaluateAcquisitionPreview({ acquisitionSource, categories, coun
23
23
  quantity?: number;
24
24
  requirementInputs?: any[];
25
25
  requirementValues?: {};
26
+ salesPeriods?: any[];
26
27
  variants?: any[];
27
28
  variantSelections?: any[];
28
29
  recipientFacts: any;
@@ -16,7 +16,7 @@ export function evaluatePrerequisiteRules({ rules, existingItems, candidateItems
16
16
  candidateItems?: any[];
17
17
  }): any;
18
18
  export function evaluatePriceMatchCriteria({ match, countryCode, countryRank }: {
19
- match: any;
19
+ match?: {};
20
20
  countryCode: any;
21
21
  countryRank: any;
22
22
  }): any;
@@ -38,8 +38,9 @@ export function planItemRequirements({ rules, candidateItems, requirementInputs,
38
38
  requirementValues?: {};
39
39
  variantSelections?: any[];
40
40
  }): any;
41
- export function resolvePrice({ priceSchedule, currency, countryCode, countryRank, acquisitionSource, instant }: {
41
+ export function resolvePrice({ priceSchedule, salesPeriods, currency, countryCode, countryRank, acquisitionSource, instant }: {
42
42
  priceSchedule: any;
43
+ salesPeriods?: any[];
43
44
  currency: any;
44
45
  countryCode: any;
45
46
  countryRank: any;
@@ -25,4 +25,4 @@ export const DEFAULT_ACTIVE_ITEM_STATES: readonly ("VALID" | "PENDING_REQUIREMEN
25
25
  export function isUsableItem(item: any): boolean;
26
26
  export function sumMatchingItems(items: any, target: any, states: any): any;
27
27
  export function targetMatchesItem(target: any, item: any): any;
28
- export const TERMINAL_ITEM_STATES: readonly ("REVOKED" | "CANCELLED" | "EXPIRED" | "REFUNDED")[];
28
+ export const TERMINAL_ITEM_STATES: readonly ("CANCELLED" | "EXPIRED" | "REVOKED" | "REFUNDED")[];
@@ -6,6 +6,9 @@
6
6
  export const STORE_MODEL_V2_CONTRACT_VERSION: 2;
7
7
  export { StoreContractValidationError } from './internal/StoreContractValidationError.js';
8
8
  export { StoreEntity } from './internal/StoreEntity.js';
9
+ export { ACQUISITION_SOURCES, ORDER_STATES, PAYMENT_ATTEMPT_STATES, RESERVATION_STATES } from './commercialVocabulary.js';
9
10
  export { collectEffectiveRules, createAcquisitionSnapshot, DECISION_CODES, DEFAULT_ACTIVE_ITEM_STATES, evaluateAcquisitionPreview, evaluateEligibilityRules, evaluateInventoryRules, evaluatePrerequisiteRules, evaluatePriceMatchCriteria, evaluateQuantityRules, evaluateRequirementConfigurationState, expandCandidateItems, planItemRequirements, projectWalletItems, resolvePrice, TERMINAL_ITEM_STATES, validateAcquisitionDefinitions } from './evaluation/index.js';
10
- export { AcquisitionSnapshot, Category, Currency, EligibilityFact, Merchandise, MerchandiseComponent, PriceEvaluationContext, PriceMatchCriteria, PriceRow, PriceSchedule, PriceScheduleRef, Product, PublishedRule, PublishedRuleRef, RefundPolicy, RefundPolicyRef, RequirementDefinition, RequirementFieldDefinition, RequirementPlan, SalesPeriod, SalesPeriodRef, Variant, VariantRef, WalletItem } from './models/index.js';
11
+ export { Acquisition, AcquisitionSnapshot, Category, CommercialLifecycle, Currency, EligibilityFact, INVENTORY_LEDGER_ACTIONS, InventoryBalance, InventoryLedgerEntry, Invoice, InvoiceRevision, Merchandise, MerchandiseComponent, Order, OrderLine, PaymentAttempt, PaymentMethodConfigurationSnapshot, PriceEvaluationContext, PriceMatchCriteria, PriceRow, PriceSchedule, PriceScheduleRef, Product, PublishedRule, PublishedRuleRef, Receipt, RefundPolicy, RefundPolicyRef, RequirementDefinition, RequirementFieldDefinition, RequirementPlan, Reservation, SalesPeriod, SalesPeriodRef, Settlement, Variant, VariantRef, WalletItem } from './models/index.js';
12
+ export { calculatePaymentDeadline, canStartPaymentAttempt } from './paymentTime.js';
11
13
  export { ELIGIBILITY_STATES, INVENTORY_MODES, MATCH_MODES, PREREQUISITE_EVIDENCE_SOURCES, QUANTITY_LIMIT_TYPES, REQUIREMENT_COMPLETION_STATES, REQUIREMENT_COMPLETION_TIMINGS, REQUIREMENT_INPUT_TYPES, REQUIREMENT_MODIFICATION_MODES, REQUIREMENT_MODIFICATION_STATES, RULE_SOURCES, RULE_TYPES, TARGET_TYPES, WALLET_ITEM_STATES } from './ruleVocabulary.js';
14
+ export { applyWalletItemRequirementValues, applyWalletItemVariantSelection } from './walletItemUpdates.js';
@@ -5,8 +5,13 @@ export function assertKnownFields({ contractName, object, fields }: {
5
5
  }): void;
6
6
  export function cloneJsonValue(value: any, path?: string): any;
7
7
  export function deepFreeze(value: any): any;
8
+ export function jsonArray(value: any, path: any, issues: any): any;
9
+ export function nonNegativeInteger(value: any, path: any, issues: any, fallback?: number): any;
8
10
  export function nonNegativeNumber(value: any, path: any, issues: any, fallback?: number): number;
9
11
  export function optionalString(value: any, path: any, issues: any): string;
12
+ export function optionalTimestampString(value: any, path: any, issues: any): string;
13
+ export function plainObject(value: any, path: any, issues: any): any;
10
14
  export function positiveInteger(value: any, path: any, issues: any, fallback?: number): any;
11
15
  export function requiredString(value: any, path: any, issues: any): string;
12
16
  export function stringArray(value: any, path: any, issues: any): string[];
17
+ export function timestampString(value: any, path: any, issues: any): string;
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class Acquisition extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -0,0 +1,5 @@
1
+ import { StoreContract } from '../internal/StoreContract.js';
2
+ export class CommercialLifecycle extends StoreContract {
3
+ constructor(object?: {});
4
+ }
5
+ export function normalizeLifecycle(value: any, path: any, supportedStates: any, issues: any): any;
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class InventoryBalance extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -0,0 +1,10 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export const INVENTORY_LEDGER_ACTIONS: Readonly<{
3
+ HELD: "HELD";
4
+ CONSUMED: "CONSUMED";
5
+ RELEASED: "RELEASED";
6
+ }>;
7
+ export class InventoryLedgerEntry extends StoreEntity {
8
+ constructor(object?: {});
9
+ getCode(): any;
10
+ }
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class Invoice extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class InvoiceRevision extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class Order extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -0,0 +1,4 @@
1
+ import { StoreContract } from '../internal/StoreContract.js';
2
+ export class OrderLine extends StoreContract {
3
+ constructor(object?: {});
4
+ }
@@ -0,0 +1,7 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class PaymentAttempt extends StoreEntity {
3
+ static canStart(options: any): boolean;
4
+ static calculateDeadline(options: any): string;
5
+ constructor(object?: {});
6
+ getCode(): any;
7
+ }
@@ -0,0 +1,4 @@
1
+ import { StoreContract } from '../internal/StoreContract.js';
2
+ export class PaymentMethodConfigurationSnapshot extends StoreContract {
3
+ constructor(object?: {});
4
+ }
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class Receipt extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -0,0 +1,4 @@
1
+ import { StoreContract } from '../internal/StoreContract.js';
2
+ export class Reservation extends StoreContract {
3
+ constructor(object?: {});
4
+ }
@@ -0,0 +1,5 @@
1
+ import { StoreEntity } from '../internal/StoreEntity.js';
2
+ export class Settlement extends StoreEntity {
3
+ constructor(object?: {});
4
+ getCode(): any;
5
+ }
@@ -1,9 +1,18 @@
1
+ export { Acquisition } from './Acquisition.js';
1
2
  export { AcquisitionSnapshot } from './AcquisitionSnapshot.js';
2
3
  export { Category } from './Category.js';
4
+ export { CommercialLifecycle } from './CommercialLifecycle.js';
3
5
  export { Currency } from './Currency.js';
4
6
  export { EligibilityFact } from './EligibilityFact.js';
7
+ export { InventoryBalance } from './InventoryBalance.js';
8
+ export { Invoice } from './Invoice.js';
9
+ export { InvoiceRevision } from './InvoiceRevision.js';
5
10
  export { Merchandise } from './Merchandise.js';
6
11
  export { MerchandiseComponent } from './MerchandiseComponent.js';
12
+ export { Order } from './Order.js';
13
+ export { OrderLine } from './OrderLine.js';
14
+ export { PaymentAttempt } from './PaymentAttempt.js';
15
+ export { PaymentMethodConfigurationSnapshot } from './PaymentMethodConfigurationSnapshot.js';
7
16
  export { PriceEvaluationContext } from './PriceEvaluationContext.js';
8
17
  export { PriceMatchCriteria } from './PriceMatchCriteria.js';
9
18
  export { PriceRow } from './PriceRow.js';
@@ -12,13 +21,17 @@ export { PriceScheduleRef } from './PriceScheduleRef.js';
12
21
  export { Product } from './Product.js';
13
22
  export { PublishedRule } from './PublishedRule.js';
14
23
  export { PublishedRuleRef } from './PublishedRuleRef.js';
24
+ export { Receipt } from './Receipt.js';
15
25
  export { RefundPolicy } from './RefundPolicy.js';
16
26
  export { RefundPolicyRef } from './RefundPolicyRef.js';
17
27
  export { RequirementPlan } from './RequirementPlan.js';
28
+ export { Reservation } from './Reservation.js';
18
29
  export { RequirementDefinition } from './ruleDetails/RequirementDefinition.js';
19
30
  export { RequirementFieldDefinition } from './ruleDetails/RequirementFieldDefinition.js';
20
31
  export { SalesPeriod } from './SalesPeriod.js';
21
32
  export { SalesPeriodRef } from './SalesPeriodRef.js';
33
+ export { Settlement } from './Settlement.js';
22
34
  export { Variant } from './Variant.js';
23
35
  export { VariantRef } from './VariantRef.js';
24
36
  export { WalletItem } from './WalletItem.js';
37
+ export { INVENTORY_LEDGER_ACTIONS, InventoryLedgerEntry } from './InventoryLedgerEntry.js';
@@ -0,0 +1,8 @@
1
+ export function calculatePaymentDeadline({ paymentAttemptMeta, defaultPaymentDuration }: {
2
+ paymentAttemptMeta: any;
3
+ defaultPaymentDuration: any;
4
+ }): string;
5
+ export function canStartPaymentAttempt({ paymentAttemptMeta, salesPeriodEnd }: {
6
+ paymentAttemptMeta: any;
7
+ salesPeriodEnd: any;
8
+ }): boolean;
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const st=require("@questwork/q-utilities");class F extends Error{constructor({contractName:o,issues:e}){super(`${o} is invalid: ${e.join("; ")}`),this.name="StoreContractValidationError",this.code="STORE_CONTRACT_INVALID",this.contractName=o,this.issues=[...e]}}const ct=["boolean","number","string"];function N(n,o="value"){if(n===null)return null;if(Array.isArray(n))return n.map((e,t)=>N(e,`${o}[${t}]`));if(ct.includes(typeof n)){if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`${o} must be a finite number`);return n}if(typeof n=="object"&&Object.getPrototypeOf(n)===Object.prototype)return Object.fromEntries(Object.entries(n).map(([e,t])=>{if(typeof t>"u")throw new TypeError(`${o}.${e} must not be undefined`);return[e,N(t,`${o}.${e}`)]}));throw new TypeError(`${o} must contain JSON-safe values only`)}function q(n){return n&&typeof n=="object"&&!Object.isFrozen(n)&&(Object.values(n).forEach(q),Object.freeze(n)),n}function xe({contractName:n,object:o,fields:e}){const t=Object.keys(o).filter(i=>!e.includes(i));if(t.length>0)throw new F({contractName:n,issues:t.map(i=>`unknown field "${i}"`)})}function u(n,o,e){return typeof n!="string"||n.trim().length===0?(e.push(`${o} must be a non-empty string`),""):n}function V(n,o,e){if(!(typeof n>"u"||n===null))return u(n,o,e)}function I(n,o,e,t=1){return!Number.isInteger(n)||n<1?(e.push(`${o} must be a positive integer`),t):n}function at(n,o,e,t=0){return typeof n!="number"||!Number.isFinite(n)||n<0?(e.push(`${o} must be a non-negative finite number`),t):n}function z(n,o,e){return Array.isArray(n)?n.map((t,i)=>u(t,`${o}[${i}]`,e)):(e.push(`${o} must be an array`),[])}class h{constructor({contractName:o,object:e,fields:t,normalize:i}){if(!e||typeof e!="object"||Array.isArray(e))throw new F({contractName:o,issues:["input must be an object"]});xe({contractName:o,object:e,fields:t});const r=[],s=i(N(e),r);if(r.length>0)throw new F({contractName:o,issues:r});Object.assign(this,q(s)),Object.freeze(this)}toObject(){return N(Object.fromEntries(Object.entries(this)))}toJSON(){return this.toObject()}}class de extends h{constructor(o={}){super({contractName:"PriceEvaluationContext",object:o,fields:["acquisitionSource","countryCode","countryRank","currency","instant"],normalize(e,t){const i=u(e.instant,"instant",t);return i&&!Number.isFinite(Date.parse(i))&&t.push("instant must be an ISO-compatible timestamp"),{acquisitionSource:u(e.acquisitionSource,"acquisitionSource",t),countryCode:u(e.countryCode,"countryCode",t),countryRank:I(e.countryRank,"countryRank",t),currency:u(e.currency,"currency",t),instant:i}}})}}class ue extends h{constructor(o={}){super({contractName:"PriceScheduleRef",object:o,fields:["priceScheduleCode","priceScheduleVersion"],normalize(e,t){return{priceScheduleCode:u(e.priceScheduleCode,"priceScheduleCode",t),priceScheduleVersion:I(e.priceScheduleVersion,"priceScheduleVersion",t)}}})}}const A=Object.freeze({ELIGIBILITY:"ELIGIBILITY",INVENTORY:"INVENTORY",PREREQUISITE:"PREREQUISITE",QUANTITY:"QUANTITY",REFUND:"REFUND",REQUIREMENT:"REQUIREMENT"}),M=Object.freeze({ACQUISITION_SOURCE:"ACQUISITION_SOURCE",CATEGORY:"CATEGORY",MERCHANDISE:"MERCHANDISE",PRODUCT:"PRODUCT"}),_=Object.freeze({CATEGORY:"CATEGORY",MERCHANDISE:"MERCHANDISE",PRODUCT:"PRODUCT"}),k=Object.freeze({ACTIVE:"ACTIVE",HOLDING:"HOLDING",ORDER:"ORDER"}),w=Object.freeze({NOT_SUBMITTED:"NOT_SUBMITTED",REJECTED:"REJECTED",REVOKED:"REVOKED",UNDER_REVIEW:"UNDER_REVIEW",VALID:"VALID"}),ne=Object.freeze({CAPACITY_ADMISSION:"CAPACITY_ADMISSION",PRODUCTION_DEMAND:"PRODUCTION_DEMAND",STOCKED_VARIANT:"STOCKED_VARIANT"}),oe=Object.freeze({ALL:"ALL",ANY:"ANY"}),B=Object.freeze({EXISTING:"EXISTING",SAME_ORDER:"SAME_ORDER"}),re=Object.freeze({BEFORE_ITEM_VALID:"BEFORE_ITEM_VALID"}),Y=Object.freeze({ALWAYS:"ALWAYS",LOCK_AFTER_COMPLETE:"LOCK_AFTER_COMPLETE",UNTIL_DEADLINE:"UNTIL_DEADLINE"}),Z=Object.freeze({COMPLETE:"COMPLETE",INCOMPLETE:"INCOMPLETE",OVERDUE:"OVERDUE"}),W=Object.freeze({EDITABLE:"EDITABLE",LOCKED:"LOCKED"}),ee=Object.freeze({EMAIL:"email",TEXT:"text",VARIANT:"VARIANT"}),P=Object.freeze({CANCELLED:"CANCELLED",EXPIRED:"EXPIRED",PENDING_REQUIREMENT:"PENDING_REQUIREMENT",REFUNDED:"REFUNDED",RESERVED:"RESERVED",REVOKED:"REVOKED",VALID:"VALID"});class le extends h{constructor(o={}){super({contractName:"RequirementFieldDefinition",object:o,fields:["autocomplete","deferredLabel","fieldCode","inputType","label","optionValueKey"],normalize(e,t){const i=u(e.inputType,"inputType",t);Object.values(ee).includes(i)||t.push(`inputType "${i}" is not supported`);const r=V(e.autocomplete,"autocomplete",t),s=V(e.deferredLabel,"deferredLabel",t),c=V(e.optionValueKey,"optionValueKey",t);return i===ee.VARIANT&&!c&&t.push("optionValueKey is required when inputType is VARIANT"),i!==ee.VARIANT&&c&&t.push("optionValueKey is only supported when inputType is VARIANT"),{fieldCode:u(e.fieldCode,"fieldCode",t),label:u(e.label,"label",t),inputType:i,...r?{autocomplete:r}:{},...s?{deferredLabel:s}:{},...c?{optionValueKey:c}:{}}}})}}class H extends h{constructor(o={}){super({contractName:"RequirementDefinition",object:o,fields:["requirementCode","label","fields"],normalize(e,t){const i=(Array.isArray(e.fields)?e.fields:[]).flatMap((s,c)=>{try{return[(s instanceof le?s:new le(s)).toObject()]}catch(a){return t.push(`fields[${c}]: ${a.message}`),[]}});Array.isArray(e.fields)||t.push("fields must be an array"),i.length===0&&t.push("fields must contain at least one field");const r=new Set;return i.forEach((s,c)=>{r.has(s.fieldCode)&&t.push(`fields[${c}].fieldCode duplicates "${s.fieldCode}"`),r.add(s.fieldCode)}),{requirementCode:u(e.requirementCode,"requirementCode",t),label:u(e.label,"label",t),fields:i}}})}}function Ye({values:n,allowedValues:o,path:e,issues:t}){n.forEach(i=>{o.includes(i)||t.push(`${e} contains unsupported value "${i}"`)})}function dt(n,o,e,t){return!n||typeof n!="object"||Array.isArray(n)?(e.push(`${o} must be an object`),{}):new h({contractName:o,object:n,fields:["code","type"],normalize(r,s){const c=typeof r.type=="string"?r.type:"",a=typeof r.code=="string"?r.code:"";return c.trim()||s.push("type must be a non-empty string"),a.trim()||s.push("code must be a non-empty string"),c&&!t.includes(c)&&s.push(`type "${c}" is not supported`),{type:c,code:a}}}).toObject()}function ie(n,o,e){if(!(typeof n>"u"||n===null||n==="")){if(typeof n!="string"||!Number.isFinite(Date.parse(n))){e.push(`${o} must be an ISO-8601 timestamp`);return}return n}}class J extends h{constructor(o={}){super({contractName:"RequirementPlan",object:o,fields:["complete","completionDeadline","completionTiming","componentIndex","missingFields","modificationDeadline","modificationMode","productCode","requirement","ruleCode","unitIndex","values"],normalize(e,t){let i={};try{i=(e.requirement instanceof H?e.requirement:new H(e.requirement)).toObject()}catch(a){t.push(`requirement: ${a.message}`)}Object.values(re).includes(e.completionTiming)||t.push(`completionTiming "${e.completionTiming}" is not supported`),Object.values(Y).includes(e.modificationMode)||t.push(`modificationMode "${e.modificationMode}" is not supported`);const r=ie(e.completionDeadline,"completionDeadline",t),s=ie(e.modificationDeadline,"modificationDeadline",t);(!Number.isInteger(e.componentIndex)||e.componentIndex<0)&&t.push("componentIndex must be a non-negative integer"),(!Number.isInteger(e.unitIndex)||e.unitIndex<0)&&t.push("unitIndex must be a non-negative integer"),typeof e.complete!="boolean"&&t.push("complete must be a boolean");let c={};try{!e.values||typeof e.values!="object"||Array.isArray(e.values)?t.push("values must be an object"):c=N(e.values)}catch(a){t.push(`values: ${a.message}`)}return{ruleCode:u(e.ruleCode,"ruleCode",t),requirement:i,productCode:u(e.productCode,"productCode",t),componentIndex:Number.isInteger(e.componentIndex)&&e.componentIndex>=0?e.componentIndex:0,unitIndex:Number.isInteger(e.unitIndex)&&e.unitIndex>=0?e.unitIndex:0,completionTiming:e.completionTiming,modificationMode:e.modificationMode,...r?{completionDeadline:r}:{},...s?{modificationDeadline:s}:{},values:c,missingFields:z(e.missingFields||[],"missingFields",t),complete:e.complete===!0}}})}}class ze extends h{constructor(o={}){super({contractName:"AcquisitionSnapshot",object:o,fields:["id","contractVersion","eventRegistrationCode","purchaserEventRegistrationCode","payerEventRegistrationCode","acquisitionSource","merchandise","quantity","products","priceScheduleRef","matchedPriceRow","priceEvaluationContext","effectiveRules","eligibilityDecisions","requirementPlans","inventoryDecisions","variantSelections","evaluated"],normalize(e,t){let i={};try{i=(e.priceEvaluationContext instanceof de?e.priceEvaluationContext:new de(e.priceEvaluationContext)).toObject()}catch(c){t.push(`priceEvaluationContext: ${c.message}`)}let r={};try{r=(e.priceScheduleRef instanceof ue?e.priceScheduleRef:new ue(e.priceScheduleRef)).toObject()}catch(c){t.push(`priceScheduleRef: ${c.message}`)}const s=(Array.isArray(e.requirementPlans)?e.requirementPlans:[]).flatMap((c,a)=>{try{return[(c instanceof J?c:new J(c)).toObject()]}catch(d){return t.push(`requirementPlans[${a}]: ${d.message}`),[]}});return Array.isArray(e.requirementPlans)||t.push("requirementPlans must be an array"),{id:u(e.id,"id",t),contractVersion:I(e.contractVersion,"contractVersion",t,2),eventRegistrationCode:u(e.eventRegistrationCode,"eventRegistrationCode",t),purchaserEventRegistrationCode:u(e.purchaserEventRegistrationCode,"purchaserEventRegistrationCode",t),payerEventRegistrationCode:u(e.payerEventRegistrationCode,"payerEventRegistrationCode",t),acquisitionSource:u(e.acquisitionSource,"acquisitionSource",t),merchandise:e.merchandise||{},quantity:I(e.quantity,"quantity",t),products:e.products||[],priceScheduleRef:r,matchedPriceRow:e.matchedPriceRow||{},priceEvaluationContext:i,effectiveRules:e.effectiveRules||{},eligibilityDecisions:e.eligibilityDecisions||[],requirementPlans:s,inventoryDecisions:e.inventoryDecisions||[],variantSelections:e.variantSelections||[],evaluated:u(e.evaluated,"evaluated",t)}}})}getId(){return this.id}}const ut=["_id","_tenant","_type","id","meta","metadata","remarks","tenantCode"],Qe=["active","created","creator","deleted","modified","owner","revision"];class U extends st.TenantAwareEntity{constructor({contractName:o,object:e,fields:t,normalize:i}){var l;if(!e||typeof e!="object"||Array.isArray(e))throw new F({contractName:o,issues:["input must be an object"]});xe({contractName:o,object:e,fields:[...ut,...t]});const r=[],s=u(e.tenantCode,"tenantCode",r);lt(e.meta,r),qe(e.metadata,"metadata",r),qe(e.remarks,"remarks",r);const c=N(Object.fromEntries(t.flatMap(f=>Object.hasOwn(e,f)?[[f,e[f]]]:[]))),a=i(c,r);if(r.length>0)throw new F({contractName:o,issues:r});super({...e,tenantCode:s});const d=(l=e.meta)==null?void 0:l.revision;Number.isInteger(d)&&d>=0&&(this.meta.revision=d),this._type=e._type||o,Object.assign(this,a),Object.defineProperty(this,"_storeContractFields",{configurable:!1,enumerable:!1,value:Object.freeze([...t]),writable:!1})}getId(){return this.id===null||typeof this.id>"u"?"":this.id.toString()}toJSON(){return this.toObject()}toObject(){const o={_type:this._type,meta:Ve(this.meta,Qe),metadata:Me(this.metadata),remarks:Me(this.remarks),tenantCode:this.tenantCode,...Ve(this,this._storeContractFields)},e=this.getId();return e&&(o.id=e),N(o)}}function lt(n,o){if(!(typeof n>"u")){if(!n||typeof n!="object"||Array.isArray(n)){o.push("meta must be an object");return}Object.keys(n).forEach(e=>{Qe.includes(e)||o.push(`meta contains unknown field "${e}"`)}),["active","deleted"].forEach(e=>{typeof n[e]<"u"&&typeof n[e]!="boolean"&&o.push(`meta.${e} must be a boolean`)}),["created","modified"].forEach(e=>{typeof n[e]<"u"&&(!Number.isFinite(n[e])||n[e]<0)&&o.push(`meta.${e} must be a non-negative finite number`)}),["creator","owner"].forEach(e=>{typeof n[e]<"u"&&typeof n[e]!="string"&&o.push(`meta.${e} must be a string`)}),typeof n.revision<"u"&&(!Number.isInteger(n.revision)||n.revision<0)&&o.push("meta.revision must be a non-negative integer")}}function Me(n){return Array.isArray(n)?n.map(o=>({key:o.key,value:N(o.value)})):[]}function Ve(n,o){return Object.fromEntries(o.flatMap(e=>typeof n[e]>"u"?[]:[[e,N(n[e])]]))}function qe(n,o,e){if(!(typeof n>"u")){if(!Array.isArray(n)){e.push(`${o} must be an array`);return}n.forEach((t,i)=>{if(!t||typeof t!="object"||Array.isArray(t)){e.push(`${o}[${i}] must be an object`);return}Object.keys(t).forEach(r=>{["key","value"].includes(r)||e.push(`${o}[${i}] contains unknown field "${r}"`)}),u(t.key,`${o}[${i}].key`,e),Object.hasOwn(t,"value")?N(t.value,`${o}[${i}].value`):e.push(`${o}[${i}].value is required`)})}}class pt extends U{constructor(o={}){super({contractName:"Category",object:o,fields:["categoryCode","version","name","description"],normalize(e,t){return{categoryCode:u(e.categoryCode,"categoryCode",t),version:I(e.version,"version",t),name:u(e.name,"name",t),...V(e.description,"description",t)?{description:e.description}:{}}}})}getCode(){return this.categoryCode}}class mt extends U{constructor(o={}){super({contractName:"Currency",object:o,fields:["currencyCode","name","symbol","factor","unit"],normalize(e,t){const i=V(e.symbol,"symbol",t);return{currencyCode:u(e.currencyCode,"currencyCode",t),name:u(e.name,"name",t),...i?{symbol:i}:{},factor:I(e.factor,"factor",t),unit:u(e.unit,"unit",t)}}})}getCode(){return this.currencyCode}}class ft extends h{constructor(o={}){super({contractName:"EligibilityFact",object:o,fields:["eligibilityType","state","revision","decisionReference","reasonCode"],normalize(e,t){const i=u(e.state,"state",t);return Object.values(w).includes(i)||t.push(`state "${i}" is not supported`),(!Number.isInteger(e.revision)||e.revision<0)&&t.push("revision must be a non-negative integer"),{eligibilityType:u(e.eligibilityType,"eligibilityType",t),state:i,revision:Number.isInteger(e.revision)&&e.revision>=0?e.revision:0,...V(e.decisionReference,"decisionReference",t)?{decisionReference:e.decisionReference}:{},...V(e.reasonCode,"reasonCode",t)?{reasonCode:e.reasonCode}:{}}}})}}class pe extends h{constructor(o={}){super({contractName:"MerchandiseComponent",object:o,fields:["productCode","productVersion","quantityPerUnit"],normalize(e,t){return{productCode:u(e.productCode,"productCode",t),productVersion:I(e.productVersion,"productVersion",t),quantityPerUnit:I(e.quantityPerUnit,"quantityPerUnit",t)}}})}}class Et extends U{constructor(o={}){super({contractName:"Merchandise",object:o,fields:["merchandiseCode","version","name","description","components","priceScheduleCode"],normalize(e,t){let i=[];try{i=(e.components||[]).map(r=>(r instanceof pe?r:new pe(r)).toObject())}catch(r){t.push(`components: ${r.message}`)}return i.length===0&&t.push("components must contain at least one component"),{merchandiseCode:u(e.merchandiseCode,"merchandiseCode",t),version:I(e.version,"version",t),name:u(e.name,"name",t),...V(e.description,"description",t)?{description:e.description}:{},components:i,priceScheduleCode:u(e.priceScheduleCode,"priceScheduleCode",t)}}})}getCode(){return this.merchandiseCode}}function Le(n,o,e){if(!(typeof n>"u"||n===null))return I(n,o,e)}class me extends h{constructor(o={}){super({contractName:"PriceMatchCriteria",object:o,fields:["countryCodes","excludedCountryCodes","countryRank"],normalize(e,t){const i=z(e.countryCodes||[],"countryCodes",t),r=z(e.excludedCountryCodes||[],"excludedCountryCodes",t),s=i.filter(a=>r.includes(a));s.length>0&&t.push(`countryCodes and excludedCountryCodes overlap: ${[...new Set(s)].join(", ")}`);let c;if(typeof e.countryRank<"u"&&e.countryRank!==null)if(typeof e.countryRank!="object"||Array.isArray(e.countryRank))t.push("countryRank must be an object");else{Object.keys(e.countryRank).filter(f=>!["min","max"].includes(f)).forEach(f=>t.push(`countryRank contains unknown field "${f}"`));const d=Le(e.countryRank.min,"countryRank.min",t),l=Le(e.countryRank.max,"countryRank.max",t);typeof d>"u"&&typeof l>"u"&&t.push("countryRank must contain min or max"),d&&l&&d>l&&t.push("countryRank.max must be greater than or equal to countryRank.min"),c={...d?{min:d}:{},...l?{max:l}:{}}}return{countryCodes:i,excludedCountryCodes:r,...c?{countryRank:c}:{}}}})}}class fe extends h{constructor(o={}){super({contractName:"SalesPeriodRef",object:o,fields:["salesPeriodCode","salesPeriodVersion"],normalize(e,t){return{salesPeriodCode:u(e.salesPeriodCode,"salesPeriodCode",t),salesPeriodVersion:I(e.salesPeriodVersion,"salesPeriodVersion",t)}}})}}function Ue(n,o,e){if(typeof n>"u"||n===null)return;const t=V(n,o,e);return t&&!Number.isFinite(Date.parse(t))&&e.push(`${o} must be an ISO-compatible timestamp`),t}class Ee extends h{constructor(o={}){super({contractName:"PriceRow",object:o,fields:["priceRowCode","currency","amount","match","salesPeriodRef","validFrom","validUntil","acquisitionSources"],normalize(e,t){const i=Ue(e.validFrom,"validFrom",t),r=Ue(e.validUntil,"validUntil",t);i&&r&&Date.parse(i)>=Date.parse(r)&&t.push("validUntil must be later than validFrom");let s;if(e.salesPeriodRef!==null&&typeof e.salesPeriodRef<"u"){try{s=(e.salesPeriodRef instanceof fe?e.salesPeriodRef:new fe(e.salesPeriodRef)).toObject()}catch(a){t.push(`salesPeriodRef: ${a.message}`)}(!i||!r)&&t.push("salesPeriodRef requires validFrom and validUntil snapshots")}let c={};try{c=(e.match instanceof me?e.match:new me(e.match||{})).toObject()}catch(a){t.push(`match: ${a.message}`)}return{priceRowCode:u(e.priceRowCode,"priceRowCode",t),currency:u(e.currency,"currency",t),amount:at(e.amount,"amount",t),match:c,...s?{salesPeriodRef:s}:{},...i?{validFrom:i}:{},...r?{validUntil:r}:{},acquisitionSources:z(e.acquisitionSources||[],"acquisitionSources",t)}}})}}class Ct extends U{constructor(o={}){super({contractName:"PriceSchedule",object:o,fields:["priceScheduleCode","version","rows"],normalize(e,t){let i=[];try{i=(e.rows||[]).map(r=>(r instanceof Ee?r:new Ee(r)).toObject())}catch(r){t.push(`rows: ${r.message}`)}return i.length===0&&t.push("rows must contain at least one row"),{priceScheduleCode:u(e.priceScheduleCode,"priceScheduleCode",t),version:I(e.version,"version",t),rows:i}}})}getCode(){return this.priceScheduleCode}}class yt extends U{constructor(o={}){super({contractName:"Product",object:o,fields:["productCode","version","name","description","categoryCodes"],normalize(e,t){return{productCode:u(e.productCode,"productCode",t),version:I(e.version,"version",t),name:u(e.name,"name",t),...V(e.description,"description",t)?{description:e.description}:{},categoryCodes:z(e.categoryCodes||[],"categoryCodes",t)}}})}getCode(){return this.productCode}}class It extends h{constructor(o={}){super({contractName:"EligibilityRuleDetails",object:o,fields:["acceptedStates","eligibilityType"],normalize(e,t){const i=z(e.acceptedStates||[],"acceptedStates",t);return i.length===0&&t.push("acceptedStates must contain at least one state"),Ye({values:i,allowedValues:Object.values(w),path:"acceptedStates",issues:t}),{eligibilityType:u(e.eligibilityType,"eligibilityType",t),acceptedStates:i}}})}}class Rt extends h{constructor(o={}){super({contractName:"InventoryRuleDetails",object:o,fields:["inventoryMode","inventoryPoolCode"],normalize(e,t){return Object.values(ne).includes(e.inventoryMode)||t.push(`inventoryMode "${e.inventoryMode}" is not supported`),{inventoryMode:e.inventoryMode,inventoryPoolCode:u(e.inventoryPoolCode,"inventoryPoolCode",t)}}})}}class Tt extends h{constructor(o={}){super({contractName:"PrerequisiteRuleDetails",object:o,fields:["continuous","evidenceSources","matchMode","requires"],normalize(e,t){(!Array.isArray(e.requires)||e.requires.length===0)&&t.push("requires must contain at least one target");const i=(e.requires||[]).map((s,c)=>{try{return dt(s,`requires[${c}]`,t,Object.values(_))}catch(a){return t.push(`requires[${c}]: ${a.message}`),{}}});Object.values(oe).includes(e.matchMode)||t.push(`matchMode "${e.matchMode}" is not supported`);const r=z(e.evidenceSources||[],"evidenceSources",t);return Ye({values:r,allowedValues:Object.values(B),path:"evidenceSources",issues:t}),{requires:i,matchMode:e.matchMode,evidenceSources:r,continuous:e.continuous===!0}}})}}class ht extends h{constructor(o={}){super({contractName:"QuantityRuleDetails",object:o,fields:["limit","limitType"],normalize(e,t){return Object.values(k).includes(e.limitType)||t.push(`limitType "${e.limitType}" is not supported`),{limitType:e.limitType,limit:I(e.limit,"limit",t)}}})}}class Ce extends h{constructor(o={}){super({contractName:"RefundPolicyRef",object:o,fields:["refundPolicyCode","refundPolicyVersion"],normalize(e,t){return{refundPolicyCode:u(e.refundPolicyCode,"refundPolicyCode",t),refundPolicyVersion:I(e.refundPolicyVersion,"refundPolicyVersion",t)}}})}}class gt extends h{constructor(o={}){super({contractName:"RefundRuleDetails",object:o,fields:["refundPolicyRef"],normalize(e,t){try{return{refundPolicyRef:(e.refundPolicyRef instanceof Ce?e.refundPolicyRef:new Ce(e.refundPolicyRef)).toObject()}}catch(i){return t.push(`refundPolicyRef: ${i.message}`),{refundPolicyRef:{}}}}})}}class bt extends h{constructor(o={}){super({contractName:"RequirementRuleDetails",object:o,fields:["completionDeadline","completionTiming","modificationDeadline","modificationMode","requirement"],normalize(e,t){let i={};try{i=(e.requirement instanceof H?e.requirement:new H(e.requirement)).toObject()}catch(c){t.push(`requirement: ${c.message}`)}Object.values(re).includes(e.completionTiming)||t.push(`completionTiming "${e.completionTiming}" is not supported`),Object.values(Y).includes(e.modificationMode)||t.push(`modificationMode "${e.modificationMode}" is not supported`);const r=ie(e.completionDeadline,"completionDeadline",t),s=ie(e.modificationDeadline,"modificationDeadline",t);return e.modificationMode===Y.UNTIL_DEADLINE&&!s&&t.push("modificationDeadline is required when modificationMode is UNTIL_DEADLINE"),e.modificationMode!==Y.UNTIL_DEADLINE&&s&&t.push("modificationDeadline is only supported when modificationMode is UNTIL_DEADLINE"),{requirement:i,completionTiming:e.completionTiming,modificationMode:e.modificationMode,...r?{completionDeadline:r}:{},...s?{modificationDeadline:s}:{}}}})}}const Ot=Object.freeze({[A.ELIGIBILITY]:It,[A.INVENTORY]:Rt,[A.PREREQUISITE]:Tt,[A.QUANTITY]:ht,[A.REFUND]:gt,[A.REQUIREMENT]:bt});function Nt(n,o){const e=Ot[n];if(!e)throw new TypeError(`Rule type "${n}" does not have a details contract`);return new e(o)}function Dt(n,o,e){if(!n||typeof n!="object"||Array.isArray(n))return e.push(`${o} must be an object`),{};const t=u(n.type,`${o}.type`,e),i=u(n.code,`${o}.code`,e);return Object.keys(n).forEach(r=>{["code","type"].includes(r)||e.push(`${o} contains unknown field "${r}"`)}),Object.values(_).includes(t)||e.push(`${o}.type "${t}" is not supported`),{type:t,code:i}}class St extends U{constructor(o={}){super({contractName:"PublishedRule",object:o,fields:["publishedRuleCode","version","ruleType","sourceType","sourceCode","appliesTo","details","reason"],normalize(e,t){const i=u(e.ruleType,"ruleType",t);Object.values(A).includes(i)||t.push(`ruleType "${i}" is not supported`);const r=u(e.sourceType,"sourceType",t);Object.values(M).includes(r)||t.push(`sourceType "${r}" is not supported`);const s=Dt(e.appliesTo,"appliesTo",t);let c={};try{c=Nt(i,e.details).toObject()}catch(a){t.push(`details: ${a.message}`)}return{publishedRuleCode:u(e.publishedRuleCode,"publishedRuleCode",t),version:I(e.version,"version",t),ruleType:i,sourceType:r,sourceCode:u(e.sourceCode,"sourceCode",t),appliesTo:s,details:c,...e.reason?{reason:e.reason}:{}}}})}getCode(){return this.publishedRuleCode}}class At extends h{constructor(o={}){super({contractName:"PublishedRuleRef",object:o,fields:["publishedRuleCode","publishedRuleVersion"],normalize(e,t){return{publishedRuleCode:u(e.publishedRuleCode,"publishedRuleCode",t),publishedRuleVersion:I(e.publishedRuleVersion,"publishedRuleVersion",t)}}})}}class Pt extends U{constructor(o={}){super({contractName:"RefundPolicy",object:o,fields:["refundPolicyCode","version","name"],normalize(e,t){return{refundPolicyCode:u(e.refundPolicyCode,"refundPolicyCode",t),version:I(e.version,"version",t),name:u(e.name,"name",t)}}})}getCode(){return this.refundPolicyCode}}function $e(n,o,e){const t=u(n,o,e);return t&&!Number.isFinite(Date.parse(t))&&e.push(`${o} must be an ISO-compatible timestamp`),t}class _t extends U{constructor(o={}){super({contractName:"SalesPeriod",object:o,fields:["salesPeriodCode","version","name","validFrom","validUntil"],normalize(e,t){const i=$e(e.validFrom,"validFrom",t),r=$e(e.validUntil,"validUntil",t);return i&&r&&Date.parse(i)>=Date.parse(r)&&t.push("validUntil must be later than validFrom"),{salesPeriodCode:u(e.salesPeriodCode,"salesPeriodCode",t),version:I(e.version,"version",t),name:u(e.name,"name",t),validFrom:i,validUntil:r}}})}getCode(){return this.salesPeriodCode}}class Mt extends U{constructor(o={}){super({contractName:"Variant",object:o,fields:["variantCode","version","productCode","productVersion","name","optionValues"],normalize(e,t){return(!e.optionValues||typeof e.optionValues!="object"||Array.isArray(e.optionValues))&&t.push("optionValues must be an object"),{variantCode:u(e.variantCode,"variantCode",t),version:I(e.version,"version",t),productCode:u(e.productCode,"productCode",t),productVersion:I(e.productVersion,"productVersion",t),name:u(e.name,"name",t),optionValues:e.optionValues||{}}}})}getCode(){return this.variantCode}}class ye extends h{constructor(o={}){super({contractName:"VariantRef",object:o,fields:["variantCode","variantVersion"],normalize(e,t){return{variantCode:u(e.variantCode,"variantCode",t),variantVersion:I(e.variantVersion,"variantVersion",t)}}})}}class Vt extends U{constructor(o={}){super({contractName:"WalletItem",object:o,fields:["walletItemCode","productCode","productVersion","state","quantity","acquisitionCode","eventRegistrationCode","variantCode","variantVersion","requirementPlans"],normalize(e,t){const i=V(e.variantCode,"variantCode",t),r=typeof e.variantVersion>"u"||e.variantVersion===null?void 0:I(e.variantVersion,"variantVersion",t);(i&&typeof r>"u"||!i&&typeof r<"u")&&t.push("variantCode and variantVersion must be provided together"),Array.isArray(e.requirementPlans||[])||t.push("requirementPlans must be an array");const s=u(e.state,"state",t);Object.values(P).includes(s)||t.push(`state "${s}" is not supported`);const c=(Array.isArray(e.requirementPlans)?e.requirementPlans:[]).flatMap((a,d)=>{try{return[(a instanceof J?a:new J(a)).toObject()]}catch(l){return t.push(`requirementPlans[${d}]: ${l.message}`),[]}});return{walletItemCode:u(e.walletItemCode,"walletItemCode",t),productCode:u(e.productCode,"productCode",t),productVersion:I(e.productVersion,"productVersion",t),state:s,quantity:I(e.quantity,"quantity",t),acquisitionCode:u(e.acquisitionCode,"acquisitionCode",t),...V(e.eventRegistrationCode,"eventRegistrationCode",t)?{eventRegistrationCode:e.eventRegistrationCode}:{},...i?{variantCode:i,variantVersion:r}:{},requirementPlans:c}}})}getCode(){return this.walletItemCode}}const ve=[M.CATEGORY,M.PRODUCT,M.MERCHANDISE,M.ACQUISITION_SOURCE];function we(n,o){return`${n}:${o}`}function qt({rule:n,relevantCategoryCodes:o,relevantProductCodes:e,merchandise:t}){if(n.sourceType===M.CATEGORY)return n.appliesTo.type===_.CATEGORY&&n.appliesTo.code===n.sourceCode;if(n.sourceType===M.PRODUCT)return n.appliesTo.type===_.PRODUCT&&n.appliesTo.code===n.sourceCode;if(n.sourceType===M.MERCHANDISE)return n.appliesTo.type===_.MERCHANDISE?n.appliesTo.code===t.merchandiseCode:n.appliesTo.type===_.PRODUCT?e.has(n.appliesTo.code):n.appliesTo.type===_.CATEGORY?o.has(n.appliesTo.code):!1;if(n.sourceType===M.ACQUISITION_SOURCE){if(n.appliesTo.type===_.MERCHANDISE)return n.appliesTo.code===t.merchandiseCode;if(n.appliesTo.type===_.PRODUCT)return e.has(n.appliesTo.code);if(n.appliesTo.type===_.CATEGORY)return o.has(n.appliesTo.code)}return!1}function Be({categories:n=[],products:o=[],merchandise:e,acquisitionSource:t,publishedRules:i=[]}){const r=new Set(e.components.map(p=>`${p.productCode}@${p.productVersion}`)),s=o.filter(p=>r.has(`${p.productCode}@${p.version}`)),c=new Set(s.map(p=>p.productCode)),a=new Set(s.flatMap(p=>p.categoryCodes||[])),l=[...n.filter(p=>a.has(p.categoryCode)).map(p=>({sourceType:M.CATEGORY,sourceCode:p.categoryCode})),...s.map(p=>({sourceType:M.PRODUCT,sourceCode:p.productCode})),{sourceType:M.MERCHANDISE,sourceCode:e.merchandiseCode},{sourceType:M.ACQUISITION_SOURCE,sourceCode:t}],f=new Set(l.map(p=>we(p.sourceType,p.sourceCode))),D=i.filter(p=>f.has(we(p.sourceType,p.sourceCode))).reduce((p,y)=>{const T=p.get(y.publishedRuleCode)||[];return T.push(y),p.set(y.publishedRuleCode,T),p},new Map),g=[],m=[],C=[],R=new Set;D.forEach((p,y)=>{if(p.length>1){g.push({code:"RULE_PUBLICATION_AMBIGUOUS",ruleCode:y,sources:p.map($=>({sourceType:$.sourceType,sourceCode:$.sourceCode})),versions:p.map($=>$.version)});return}const[T]=p;if(T.tenantCode!==e.tenantCode){g.push({code:"RULE_TENANT_MISMATCH",ruleCode:T.publishedRuleCode,ruleTenantCode:T.tenantCode,expectedTenantCode:e.tenantCode});return}if(!qt({rule:T,relevantCategoryCodes:a,relevantProductCodes:c,merchandise:e})){g.push({code:"RULE_TARGET_MISMATCH",ruleCode:T.publishedRuleCode,sourceType:T.sourceType,sourceCode:T.sourceCode,appliesTo:N(T.appliesTo)});return}const X=`${T.publishedRuleCode}@${T.version}`;R.has(X)||(R.add(X),C.push(T)),m.push({ruleCode:T.publishedRuleCode,ruleVersion:T.version,ruleType:T.ruleType,sourceType:T.sourceType,sourceCode:T.sourceCode})}),C.sort((p,y)=>ve.indexOf(p.sourceType)-ve.indexOf(y.sourceType)||p.publishedRuleCode.localeCompare(y.publishedRuleCode));const b=C.map(p=>typeof p.toObject=="function"?p.toObject():N(p)),E=Object.fromEntries(Object.values(A).map(p=>[p,b.filter(y=>y.ruleType===p)]));return q({passed:g.length===0,rules:b,byType:E,trace:m,errors:g})}const Fe=Object.freeze([P.CANCELLED,P.EXPIRED,P.REFUNDED,P.REVOKED]),ke=Object.freeze([P.PENDING_REQUIREMENT,P.RESERVED,P.VALID]),S=Object.freeze({DEFINITION_INVALID:"DEFINITION_INVALID",ELIGIBILITY_REJECTED:"ELIGIBILITY_REJECTED",ELIGIBILITY_REQUIRED:"ELIGIBILITY_REQUIRED",ELIGIBILITY_REVOKED:"ELIGIBILITY_REVOKED",ELIGIBILITY_UNDER_REVIEW:"ELIGIBILITY_UNDER_REVIEW",INVENTORY_UNAVAILABLE:"INVENTORY_UNAVAILABLE",PREREQUISITE_NOT_MET:"PREREQUISITE_NOT_MET",PRICE_COUNTRY_UNRESOLVED:"PRICE_COUNTRY_UNRESOLVED",PRICE_MATCH_CRITERIA_NOT_MET:"PRICE_MATCH_CRITERIA_NOT_MET",PRICE_ROW_AMBIGUOUS:"PRICE_ROW_AMBIGUOUS",PRICE_ROW_NOT_FOUND:"PRICE_ROW_NOT_FOUND",QUANTITY_LIMIT_EXCEEDED:"QUANTITY_LIMIT_EXCEEDED",REQUIREMENT_INCOMPLETE:"REQUIREMENT_INCOMPLETE",REVISION_CONFLICT:"REVISION_CONFLICT",VARIANT_SELECTION_REQUIRED:"VARIANT_SELECTION_REQUIRED"});function L({passed:n,code:o=null,message:e,details:t={}}){return q({passed:n,code:o,message:e,details:N(t)})}function j(n,o){return n.type===_.PRODUCT?o.productCode===n.code:n.type===_.CATEGORY?(o.categoryCodes||[]).includes(n.code):n.type===_.MERCHANDISE?o.merchandiseCode===n.code:!1}function te(n,o,e){return n.reduce((t,i)=>!j(o,i)||e&&!e.includes(i.state)?t:t+(i.quantity||1),0)}function Lt(n){return(n==null?void 0:n.state)===P.VALID}function Ge({rules:n=[],existingItems:o=[],candidateItems:e=[],activeItemStates:t=ke}){const i=n.filter(r=>r.ruleType===A.QUANTITY).filter(r=>e.some(s=>j(r.appliesTo,s))).map(r=>{const s=te(e,r.appliesTo);let c=0;r.details.limitType===k.HOLDING?c=te(o.filter(l=>!Fe.includes(l.state)),r.appliesTo):r.details.limitType===k.ACTIVE&&(c=te(o,r.appliesTo,t));const a=c+s,d=a<=r.details.limit;return L({passed:d,...d?{}:{code:S.QUANTITY_LIMIT_EXCEEDED},message:d?"Quantity rule passed":"Quantity limit would be exceeded",details:{ruleCode:r.publishedRuleCode,ruleVersion:r.version,limitType:r.details.limitType,target:r.appliesTo,current:c,addition:s,resulting:a,limit:r.details.limit,remaining:Math.max(0,r.details.limit-c)}})});return q({passed:i.every(r=>r.passed),decisions:i})}function Ut(n){return n===w.UNDER_REVIEW?S.ELIGIBILITY_UNDER_REVIEW:n===w.REJECTED?S.ELIGIBILITY_REJECTED:n===w.REVOKED?S.ELIGIBILITY_REVOKED:S.ELIGIBILITY_REQUIRED}function Ke({rules:n=[],eligibilityFacts:o=[],eventRegistrationCode:e,candidateItems:t=[]}){const i=n.filter(r=>r.ruleType===A.ELIGIBILITY).filter(r=>t.some(s=>j(r.appliesTo,s))).map(r=>{const s=o.find(d=>d.eligibilityType===r.details.eligibilityType&&(!e||!d.eventRegistrationCode||d.eventRegistrationCode===e)),c=(s==null?void 0:s.state)||w.NOT_SUBMITTED,a=(r.details.acceptedStates||[w.VALID]).includes(c);return L({passed:a,...a?{}:{code:Ut(c)},message:a?"Eligibility rule passed":"Required eligibility is not valid",details:{ruleCode:r.publishedRuleCode,eligibilityType:r.details.eligibilityType,eventRegistrationCode:e||null,state:c,factRevision:(s==null?void 0:s.revision)||null}})});return q({passed:i.every(r=>r.passed),decisions:i})}function $t(n,o){return Lt(n)&&j(o,n)}function vt(n){return Object.fromEntries(["walletItemCode","acquisitionCode","merchandiseCode","productCode","productVersion","categoryCodes","state","quantity","componentIndex"].flatMap(e=>typeof n[e]>"u"?[]:[[e,N(n[e])]]))}function We({rules:n=[],existingItems:o=[],candidateItems:e=[]}){const t=n.filter(i=>i.ruleType===A.PREREQUISITE).filter(i=>e.some(r=>j(i.appliesTo,r))).map(i=>{const r=i.details.evidenceSources||[B.EXISTING,B.SAME_ORDER],s=[...r.includes(B.EXISTING)?o:[],...r.includes(B.SAME_ORDER)?e:[]],c=(i.details.requires||[]).map(d=>({requirement:d,matched:s.filter(l=>$t(l,d)).map(vt)})),a=i.details.matchMode===oe.ALL?c.every(d=>d.matched.length>0):c.some(d=>d.matched.length>0);return L({passed:a,...a?{}:{code:S.PREREQUISITE_NOT_MET},message:a?"Prerequisite rule passed":"Prerequisite item was not found",details:{ruleCode:i.publishedRuleCode,matchMode:i.details.matchMode||oe.ANY,continuous:i.details.continuous||!1,requirementResults:c}})});return q({passed:t.every(i=>i.passed),decisions:t})}function He({rules:n=[],candidateItems:o=[],requirementInputs:e=[],requirementValues:t={},variantSelections:i=[]}){const r=n.filter(s=>s.ruleType===A.REQUIREMENT).filter(s=>o.some(c=>j(s.appliesTo,c))).flatMap(s=>o.filter(c=>j(s.appliesTo,c)).flatMap(c=>Array.from({length:c.quantity},(a,d)=>{var p;const l=s.details.requirement,f=l.requirementCode,O=e.find(y=>y.productCode===c.productCode&&y.requirementCode===f),D=t[f],g=Array.isArray(D)?D:[D||{}],C=O&&d<O.inputs.length?O.inputs[d]||{}:g[d]||{},R=(p=i.find(y=>y.productCode===c.productCode))==null?void 0:p.selections[d],b=Object.fromEntries(l.fields.map(y=>y.inputType==="VARIANT"?[y.fieldCode,(R==null?void 0:R.variantCode)||""]:[y.fieldCode,C[y.fieldCode]||""])),E=l.fields.map(y=>y.fieldCode).filter(y=>typeof b[y]!="string"||b[y].trim().length===0);return{ruleCode:s.publishedRuleCode,requirement:l,productCode:c.productCode,componentIndex:c.componentIndex,unitIndex:d,completionTiming:s.details.completionTiming||re.BEFORE_ITEM_VALID,modificationMode:s.details.modificationMode,...s.details.completionDeadline?{completionDeadline:s.details.completionDeadline}:{},...s.details.modificationDeadline?{modificationDeadline:s.details.modificationDeadline}:{},values:N(b),missingFields:E,complete:E.length===0}})));return q({passed:!0,itemValid:r.every(s=>s.complete),code:r.every(s=>s.complete)?null:S.REQUIREMENT_INCOMPLETE,plans:r})}function wt({requirementPlan:n={},rule:o,instant:e}){if(!o||o.ruleType!==A.REQUIREMENT)throw new TypeError("rule must be a REQUIREMENT PublishedRule");const t=Date.parse(e);if(!Number.isFinite(t))throw new TypeError("instant must be an ISO-8601 timestamp");const i=o.details,r=!!(i.completionDeadline&&t>=Date.parse(i.completionDeadline)),s=n.complete?Z.COMPLETE:r?Z.OVERDUE:Z.INCOMPLETE;let c=W.EDITABLE,a=null;return i.modificationMode===Y.LOCK_AFTER_COMPLETE&&n.complete?(c=W.LOCKED,a="REQUIREMENT_COMPLETE"):i.modificationMode===Y.UNTIL_DEADLINE&&t>=Date.parse(i.modificationDeadline)&&(c=W.LOCKED,a="MODIFICATION_DEADLINE_PASSED"),q({requirementCode:i.requirement.requirementCode,completionState:s,modificationState:c,canModify:c===W.EDITABLE,modificationReason:a,completionDeadline:i.completionDeadline||null,modificationDeadline:i.modificationDeadline||null,evaluated:e})}function jt(n,o){const e=Date.parse(o);return!(!Number.isFinite(e)||n.validFrom&&e<Date.parse(n.validFrom)||n.validUntil&&e>=Date.parse(n.validUntil))}function xt(n,o,e){const t=n.countryCodes||[],i=n.excludedCountryCodes||[];return t.length>0&&!t.includes(o)||i.includes(o)?!1:n.countryRank?!(!Number.isInteger(e)||e<1||n.countryRank.min&&e<n.countryRank.min||n.countryRank.max&&e>n.countryRank.max):!0}function Ie({match:n,countryCode:o,countryRank:e}){if(typeof o!="string"||o.trim().length===0||!Number.isInteger(e)||e<1)return L({passed:!1,code:S.PRICE_COUNTRY_UNRESOLVED,message:"Country code and rank are required to evaluate price match criteria",details:{countryCode:o||null,countryRank:e??null}});const t=xt(n,o,e);return L({passed:t,...t?{}:{code:S.PRICE_MATCH_CRITERIA_NOT_MET},message:t?"Price match criteria passed":"Price match criteria were not met",details:{countryCode:o,countryRank:e}})}function Je({priceSchedule:n,currency:o,countryCode:e,countryRank:t,acquisitionSource:i,instant:r}){const s=Ie({match:{},countryCode:e,countryRank:t});if(!s.passed)return s;const c=n.rows.filter(a=>a.currency===o&&Ie({match:a.match,countryCode:e,countryRank:t}).passed&&(a.acquisitionSources.length===0||a.acquisitionSources.includes(i))&&jt(a,r));return c.length===0?L({passed:!1,code:S.PRICE_ROW_NOT_FOUND,message:"No price row matches the acquisition context",details:{currency:o,countryCode:e,countryRank:t,acquisitionSource:i,instant:r}}):c.length>1?L({passed:!1,code:S.PRICE_ROW_AMBIGUOUS,message:"More than one price row matches the acquisition context",details:{matchingPriceRowCodes:c.map(a=>a.priceRowCode)}}):L({passed:!0,message:"Price row resolved",details:{countryCode:e,countryRank:t,matchedPriceRow:c[0]}})}function Xe({rules:n=[],candidateItems:o=[],inventoryFacts:e=[],variantSelections:t=[]}){const i=n.filter(r=>r.ruleType===A.INVENTORY).filter(r=>o.some(s=>j(r.appliesTo,s))).map(r=>{const s=te(o,r.appliesTo),c=t.find(m=>m.productCode===r.appliesTo.code),a=Array.from({length:s},(m,C)=>(c==null?void 0:c.selections[C])||null),d=a.length===s&&a.every(Boolean),f=[...a.reduce((m,C)=>{const b=(C==null?void 0:C.variantCode)||"UNSELECTED";return m.set(b,(m.get(b)||0)+1),m},new Map)].map(([m,C])=>{const R=e.find(b=>b.inventoryPoolCode===r.details.inventoryPoolCode&&(m==="UNSELECTED"||b.variantCode===m));return{variantCode:m==="UNSELECTED"?null:m,requested:C,available:(R==null?void 0:R.available)??0,revision:(R==null?void 0:R.revision)??null}}),O=r.details.inventoryMode===ne.STOCKED_VARIANT&&!d,D=f.every(m=>m.available>=m.requested),g=r.details.inventoryMode===ne.PRODUCTION_DEMAND||!O&&D;return L({passed:g,...g?{}:{code:O?S.VARIANT_SELECTION_REQUIRED:S.INVENTORY_UNAVAILABLE},message:g?"Inventory rule passed":O?"A Variant must be selected for every unit":"Inventory is unavailable",details:{ruleCode:r.publishedRuleCode,inventoryMode:r.details.inventoryMode,inventoryPoolCode:r.details.inventoryPoolCode,requested:s,requests:f,intent:g?{type:"RESERVE_OR_RECORD_DEMAND",requests:f}:null}})});return q({passed:i.every(r=>r.passed),decisions:i})}function Ze({merchandise:n,products:o,quantity:e}){const t=new Map(o.map(i=>[i.productCode,i]));return n.components.map((i,r)=>{const s=t.get(i.productCode);if(!s)throw new Error(`Product ${i.productCode} is not available for Merchandise ${n.merchandiseCode}`);return{productCode:s.productCode,productVersion:s.version,categoryCodes:s.categoryCodes,merchandiseCode:n.merchandiseCode,componentIndex:r,quantity:e*i.quantityPerUnit,state:P.VALID}})}function Yt(n,o){return n.flatMap(e=>Array.from({length:e.quantity},(t,i)=>{const r=o.filter(s=>s.componentIndex===e.componentIndex&&s.unitIndex===i);return{...e,quantity:1,state:r.every(s=>s.complete)?P.VALID:P.PENDING_REQUIREMENT}}))}function je({items:n,path:o,productDefinitions:e},t){return n.map((i,r)=>{const s=e.filter(a=>a.productCode===i.productCode&&a.version===i.productVersion);return s.length!==1&&t.push({path:`${o}[${r}].productCode`,message:s.length===0?`Product ${i.productCode}@${i.productVersion} is missing from recipient Product definitions`:`Product ${i.productCode}@${i.productVersion} is ambiguous in recipient Product definitions`}),{...typeof i.toObject=="function"?i.toObject():i,categoryCodes:s.length===1?[...s[0].categoryCodes]:[]}})}function zt({acquisitionSnapshots:n,items:o,path:e},t){return o.map((i,r)=>{var a,d;const s=n.filter(l=>l.id===i.acquisitionCode),c=(d=(a=s[0])==null?void 0:a.merchandise)==null?void 0:d.merchandiseCode;return(s.length!==1||!c)&&t.push({path:`${e}[${r}].acquisitionCode`,message:s.length===0?`Acquisition ${i.acquisitionCode} is missing from recipient Acquisition snapshots`:s.length>1?`Acquisition ${i.acquisitionCode} is ambiguous in recipient Acquisition snapshots`:`Acquisition ${i.acquisitionCode} does not contain a Merchandise code`}),{...i,...c?{merchandiseCode:c}:{}}})}function Qt(n,o){if(!Array.isArray(n))return o.push({path:"variantSelections",message:"variantSelections must be an array"}),[];const e=new Set;return n.flatMap((t,i)=>{const r=`variantSelections[${i}]`;if(!t||typeof t!="object"||Array.isArray(t))return o.push({path:r,message:"variant selection group must be an object"}),[];const s=typeof t.productCode=="string"?t.productCode.trim():"";if(s?e.has(s)?o.push({path:`${r}.productCode`,message:`duplicate Product ${s}`}):e.add(s):o.push({path:`${r}.productCode`,message:"productCode must be a non-empty string"}),!Array.isArray(t.selections))return o.push({path:`${r}.selections`,message:"selections must be an array"}),[{productCode:s,selections:[]}];const c=t.selections.flatMap((a,d)=>{if(a===null)return[null];try{return[(a instanceof ye?a:new ye(a)).toObject()]}catch(l){return o.push({path:`${r}.selections[${d}]`,message:l.message}),[]}});return[{productCode:s,selections:c}]})}function Bt(n,o){if(!Array.isArray(n))return o.push({path:"requirementInputs",message:"requirementInputs must be an array"}),[];const e=new Set;return n.flatMap((t,i)=>{const r=`requirementInputs[${i}]`;if(!t||typeof t!="object"||Array.isArray(t))return o.push({path:r,message:"requirement input group must be an object"}),[];const s=typeof t.productCode=="string"?t.productCode.trim():"",c=typeof t.requirementCode=="string"?t.requirementCode.trim():"";s||o.push({path:`${r}.productCode`,message:"productCode must be a non-empty string"}),c||o.push({path:`${r}.requirementCode`,message:"requirementCode must be a non-empty string"});const a=`${s}:${c}`;if(s&&c&&e.has(a)&&o.push({path:r,message:`duplicate Requirement ${c} for Product ${s}`}),e.add(a),!Array.isArray(t.inputs))return o.push({path:`${r}.inputs`,message:"inputs must be an array"}),[{productCode:s,requirementCode:c,inputs:[]}];const d=t.inputs.map((l,f)=>l===null?null:!l||typeof l!="object"||Array.isArray(l)?(o.push({path:`${r}.inputs[${f}]`,message:"input must be an object or null"}),null):N(l));return[{productCode:s,requirementCode:c,inputs:d}]})}function Ft({categories:n,merchandise:o,priceSchedule:e,products:t,variants:i},r){const s=o.tenantCode;[e,...n,...t,...i].forEach(a=>{var d;a.tenantCode!==s&&r.push({path:`${a._type||((d=a.constructor)==null?void 0:d.name)||"definition"}.tenantCode`,message:`expected ${s} but received ${a.tenantCode}`})})}function kt({merchandise:n,variants:o,variantSelections:e},t){const i=new Map(n.components.map(r=>[r.productCode,r]));e.forEach((r,s)=>{const{productCode:c,selections:a}=r,d=`variantSelections[${s}]`,l=i.get(c);if(!l){t.push({path:`${d}.productCode`,message:`Product ${c} is not a Merchandise component`});return}a.filter(Boolean).forEach((f,O)=>{const D=o.filter(m=>m.variantCode===f.variantCode&&m.version===f.variantVersion);if(D.length!==1){t.push({path:`${d}.selections[${O}]`,message:D.length===0?`Variant ${f.variantCode}@${f.variantVersion} is missing`:`Variant ${f.variantCode}@${f.variantVersion} is ambiguous`});return}const[g]=D;(g.productCode!==c||g.productVersion!==l.productVersion)&&t.push({path:`${d}.selections[${O}]`,message:`Variant ${f.variantCode}@${f.variantVersion} does not belong to Product ${c}@${l.productVersion}`})})})}function et({categories:n=[],merchandise:o,priceSchedule:e,products:t=[],quantity:i,requirementInputs:r=[],variants:s=[],variantSelections:c=[]}){const a=[],d=Qt(c,a),l=Bt(r,a);(!Number.isInteger(i)||i<1)&&a.push({path:"quantity",message:"quantity must be a positive integer"}),Ft({categories:n,merchandise:o,priceSchedule:e,products:t,variants:s},a),e.priceScheduleCode!==o.priceScheduleCode&&a.push({path:"priceSchedule.priceScheduleCode",message:`expected ${o.priceScheduleCode} but received ${e.priceScheduleCode}`});const f=t.reduce((m,C)=>{const R=m.get(C.productCode)||[];return R.push(C),m.set(C.productCode,R),m},new Map),O=n.reduce((m,C)=>(m.set(C.categoryCode,(m.get(C.categoryCode)||0)+1),m),new Map),D=new Set;o.components.forEach((m,C)=>{const R=`${m.productCode}@${m.productVersion}`;D.has(R)&&a.push({path:`merchandise.components[${C}]`,message:`duplicate component ${R}; use quantityPerUnit instead`}),D.add(R);const b=f.get(m.productCode)||[];b.length===0?a.push({path:`merchandise.components[${C}].productCode`,message:`Product ${m.productCode} is missing`}):b.length>1?a.push({path:`merchandise.components[${C}].productCode`,message:`Product ${m.productCode} is ambiguous`}):b[0].version!==m.productVersion?a.push({path:`merchandise.components[${C}].productVersion`,message:`expected Product version ${m.productVersion} but received ${b[0].version}`}):b[0].categoryCodes.forEach(E=>{const p=O.get(E)||0;p!==1&&a.push({path:`products.${m.productCode}.categoryCodes`,message:p===0?`Category ${E} is missing`:`Category ${E} is ambiguous`})})}),kt({merchandise:o,variants:s,variantSelections:d},a);const g=new Set(o.components.map(m=>m.productCode));return l.forEach((m,C)=>{g.has(m.productCode)||a.push({path:`requirementInputs[${C}].productCode`,message:`Product ${m.productCode} is not a Merchandise component`})}),L({passed:a.length===0,...a.length===0?{}:{code:S.DEFINITION_INVALID},message:a.length===0?"Acquisition definitions are consistent":"Acquisition definitions are inconsistent",details:{issues:a,requirementInputs:l,variantSelections:d}})}function Gt({acquisitionSource:n,categories:o,countryCode:e,countryRank:t,currency:i,eligibilityFacts:r=[],eventRegistrationCode:s,existingItems:c=[],instant:a,inventoryFacts:d=[],merchandise:l,priceSchedule:f,products:O,publishedRules:D,quantity:g=1,requirementInputs:m=[],requirementValues:C={},variants:R=[],variantSelections:b=[],recipientFacts:E}){const p=(E==null?void 0:E.eligibilityFacts)||r,y=(E==null?void 0:E.existingWalletItems)||(E==null?void 0:E.existingItems)||c,T=(E==null?void 0:E.projectedItems)||[],X=(E==null?void 0:E.eventRegistrationCode)||s,$=et({categories:o,merchandise:l,priceSchedule:f,products:O,quantity:g,requirementInputs:m,variants:R,variantSelections:b}),G=[],Re=(E==null?void 0:E.productDefinitions)||O,tt=je({items:y,path:"recipientFacts.existingWalletItems",productDefinitions:Re},G),Te=zt({acquisitionSnapshots:(E==null?void 0:E.acquisitionSnapshots)||[],items:tt,path:"recipientFacts.existingWalletItems"},G),nt=je({items:T,path:"recipientFacts.projectedItems",productDefinitions:Re},G),ot=[...$.details.issues,...G],Q=G.length===0?$:L({passed:!1,code:S.DEFINITION_INVALID,message:"Acquisition definitions are inconsistent",details:{...$.details,issues:ot}}),v=Be({categories:o,products:O,merchandise:l,acquisitionSource:n,publishedRules:D}),K=Q.passed?Ze({merchandise:l,products:O,quantity:g}):[],se=Q.details.variantSelections,he=Q.details.requirementInputs,ge=Ke({rules:v.rules,eligibilityFacts:p,eventRegistrationCode:X,candidateItems:K}),ce=He({rules:v.rules,candidateItems:K,requirementInputs:he,requirementValues:C,variantSelections:se}),be=[...nt,...Yt(K,ce.plans)],ae=Ge({rules:v.rules,existingItems:Te,candidateItems:be}),Oe=We({rules:v.rules,existingItems:Te,candidateItems:be}),Ne=Je({priceSchedule:f,currency:i,countryCode:e,countryRank:t,acquisitionSource:n,instant:a}),De=Xe({rules:v.rules,candidateItems:K,inventoryFacts:d,variantSelections:se}),it=ae.decisions.filter(x=>x.details.limitType===k.ORDER).every(x=>x.passed),rt=ae.decisions.filter(x=>x.details.limitType!==k.ORDER).every(x=>x.passed),Se=Q.passed&&v.passed&&it&&Ne.passed&&De.passed,Ae=rt,Pe=Q.passed&&v.passed&&ge.passed&&Ae&&Oe.passed,_e=Se&&Pe;return q({passed:_e,canPurchase:Se,canAcquire:Pe,canHold:Ae,itemValid:_e&&ce.itemValid,candidateItems:K,requirementInputs:he,variantSelections:se,effectiveRules:v,evaluations:{definitions:Q,eligibility:ge,quantity:ae,prerequisites:Oe,requirements:ce,price:Ne,inventory:De}})}function Kt({id:n,evaluated:o,preview:e,context:t}){if(!e.passed)throw new Error("Cannot snapshot a failed acquisition preview");const i=typeof t.merchandise.toObject=="function"?t.merchandise.toObject():N(t.merchandise),r=t.products.map(s=>typeof s.toObject=="function"?s.toObject():N(s));return new ze({id:n,contractVersion:2,eventRegistrationCode:t.eventRegistrationCode,purchaserEventRegistrationCode:t.purchaserEventRegistrationCode||t.eventRegistrationCode,payerEventRegistrationCode:t.payerEventRegistrationCode||t.eventRegistrationCode,acquisitionSource:t.acquisitionSource,merchandise:i,quantity:t.quantity,products:r,priceScheduleRef:{priceScheduleCode:t.priceSchedule.priceScheduleCode,priceScheduleVersion:t.priceSchedule.version},matchedPriceRow:e.evaluations.price.details.matchedPriceRow,priceEvaluationContext:{acquisitionSource:t.acquisitionSource,countryCode:e.evaluations.price.details.countryCode,countryRank:e.evaluations.price.details.countryRank,currency:e.evaluations.price.details.matchedPriceRow.currency,instant:t.instant},effectiveRules:e.effectiveRules,eligibilityDecisions:e.evaluations.eligibility.decisions,requirementPlans:e.evaluations.requirements.plans,inventoryDecisions:e.evaluations.inventory.decisions,variantSelections:e.variantSelections,evaluated:o})}function Wt({acquisitionSnapshot:n,walletItemIdFactory:o}){const e=[];return n.merchandise.components.forEach((t,i)=>{const r=n.quantity*t.quantityPerUnit;for(let s=0;s<r;s+=1){const c=n.requirementPlans.filter(l=>l.componentIndex===i&&l.unitIndex===s),a=n.variantSelections.find(l=>l.productCode===t.productCode),d=a==null?void 0:a.selections[s];e.push({walletItemCode:o({component:t,index:s,acquisitionSnapshot:n}),eventRegistrationCode:n.eventRegistrationCode,productCode:t.productCode,productVersion:t.productVersion,acquisitionCode:n.id,quantity:1,variantCode:(d==null?void 0:d.variantCode)||null,variantVersion:(d==null?void 0:d.variantVersion)||null,state:c.every(l=>l.complete)?P.VALID:P.PENDING_REQUIREMENT,requirementPlans:c.map(l=>({...l,unitIndex:0}))})}}),q(e)}const Ht=2;exports.AcquisitionSnapshot=ze;exports.Category=pt;exports.Currency=mt;exports.DECISION_CODES=S;exports.DEFAULT_ACTIVE_ITEM_STATES=ke;exports.ELIGIBILITY_STATES=w;exports.EligibilityFact=ft;exports.INVENTORY_MODES=ne;exports.MATCH_MODES=oe;exports.Merchandise=Et;exports.MerchandiseComponent=pe;exports.PREREQUISITE_EVIDENCE_SOURCES=B;exports.PriceEvaluationContext=de;exports.PriceMatchCriteria=me;exports.PriceRow=Ee;exports.PriceSchedule=Ct;exports.PriceScheduleRef=ue;exports.Product=yt;exports.PublishedRule=St;exports.PublishedRuleRef=At;exports.QUANTITY_LIMIT_TYPES=k;exports.REQUIREMENT_COMPLETION_STATES=Z;exports.REQUIREMENT_COMPLETION_TIMINGS=re;exports.REQUIREMENT_INPUT_TYPES=ee;exports.REQUIREMENT_MODIFICATION_MODES=Y;exports.REQUIREMENT_MODIFICATION_STATES=W;exports.RULE_SOURCES=M;exports.RULE_TYPES=A;exports.RefundPolicy=Pt;exports.RefundPolicyRef=Ce;exports.RequirementDefinition=H;exports.RequirementFieldDefinition=le;exports.RequirementPlan=J;exports.STORE_MODEL_V2_CONTRACT_VERSION=Ht;exports.SalesPeriod=_t;exports.SalesPeriodRef=fe;exports.StoreContractValidationError=F;exports.StoreEntity=U;exports.TARGET_TYPES=_;exports.TERMINAL_ITEM_STATES=Fe;exports.Variant=Mt;exports.VariantRef=ye;exports.WALLET_ITEM_STATES=P;exports.WalletItem=Vt;exports.collectEffectiveRules=Be;exports.createAcquisitionSnapshot=Kt;exports.evaluateAcquisitionPreview=Gt;exports.evaluateEligibilityRules=Ke;exports.evaluateInventoryRules=Xe;exports.evaluatePrerequisiteRules=We;exports.evaluatePriceMatchCriteria=Ie;exports.evaluateQuantityRules=Ge;exports.evaluateRequirementConfigurationState=wt;exports.expandCandidateItems=Ze;exports.planItemRequirements=He;exports.projectWalletItems=Wt;exports.resolvePrice=Je;exports.validateAcquisitionDefinitions=et;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Vt=require("@questwork/q-utilities"),nt=Object.freeze({CREATED:"CREATED",PAYMENT_REQUIRED:"PAYMENT_REQUIRED",PAYMENT_IN_PROGRESS:"PAYMENT_IN_PROGRESS",PAID:"PAID",COMPLETED:"COMPLETED",CANCELLED:"CANCELLED",EXPIRED:"EXPIRED"}),ot=Object.freeze({HELD_FOR_CHECKOUT:"HELD_FOR_CHECKOUT",HELD_FOR_PROVIDER:"HELD_FOR_PROVIDER",HELD_FOR_REVIEW:"HELD_FOR_REVIEW",CONSUMED:"CONSUMED",RELEASED:"RELEASED",EXPIRED:"EXPIRED"}),rt=Object.freeze({CREATED:"CREATED",PAYMENT_IN_PROGRESS:"PAYMENT_IN_PROGRESS",SUCCEEDED:"SUCCEEDED",FAILED:"FAILED",CANCELLED:"CANCELLED",EXPIRED:"EXPIRED"}),ce=Object.freeze({PURCHASE:"PURCHASE",ADMIN_ASSIGNMENT:"ADMIN_ASSIGNMENT",ROLE_BENEFIT:"ROLE_BENEFIT",PROMOTION_REDEMPTION:"PROMOTION_REDEMPTION"});class H extends Error{constructor({contractName:o,issues:e}){super(`${o} is invalid: ${e.join("; ")}`),this.name="StoreContractValidationError",this.code="STORE_CONTRACT_INVALID",this.contractName=o,this.issues=[...e]}}const Ut=["boolean","number","string"];function A(n,o="value"){if(n===null)return null;if(Array.isArray(n))return n.map((e,t)=>A(e,`${o}[${t}]`));if(Ut.includes(typeof n)){if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`${o} must be a finite number`);return n}if(typeof n=="object"&&Object.getPrototypeOf(n)===Object.prototype)return Object.fromEntries(Object.entries(n).map(([e,t])=>{if(typeof t>"u")throw new TypeError(`${o}.${e} must not be undefined`);return[e,A(t,`${o}.${e}`)]}));throw new TypeError(`${o} must contain JSON-safe values only`)}function L(n){return n&&typeof n=="object"&&!Object.isFrozen(n)&&(Object.values(n).forEach(L),Object.freeze(n)),n}function it({contractName:n,object:o,fields:e}){const t=Object.keys(o).filter(r=>!e.includes(r));if(t.length>0)throw new H({contractName:n,issues:t.map(r=>`unknown field "${r}"`)})}function s(n,o,e){return typeof n!="string"||n.trim().length===0?(e.push(`${o} must be a non-empty string`),""):n}function D(n,o,e){if(!(typeof n>"u"||n===null))return s(n,o,e)}function E(n,o,e,t=1){return!Number.isInteger(n)||n<1?(e.push(`${o} must be a positive integer`),t):n}function z(n,o,e,t=0){return typeof n!="number"||!Number.isFinite(n)||n<0?(e.push(`${o} must be a non-negative finite number`),t):n}function de(n,o,e,t=0){return!Number.isInteger(n)||n<0?(e.push(`${o} must be a non-negative integer`),t):n}function $(n,o,e){const t=s(n,o,e);return t&&!Number.isFinite(Date.parse(t))&&e.push(`${o} must be an ISO-compatible timestamp`),t}function me(n,o,e){if(!(typeof n>"u"||n===null))return $(n,o,e)}function B(n,o,e){return!n||typeof n!="object"||Array.isArray(n)?(e.push(`${o} must be an object`),{}):A(n,o)}function te(n,o,e){return Array.isArray(n)?A(n,o):(e.push(`${o} must be an array`),[])}function U(n,o,e){return Array.isArray(n)?n.map((t,r)=>s(t,`${o}[${r}]`,e)):(e.push(`${o} must be an array`),[])}const $t=["_id","_tenant","_type","id","meta","metadata","remarks","tenantCode"],ct=["active","created","creator","deleted","modified","owner","revision"];class S extends Vt.TenantAwareEntity{constructor({contractName:o,object:e,fields:t,normalize:r}){var p;if(!e||typeof e!="object"||Array.isArray(e))throw new H({contractName:o,issues:["input must be an object"]});it({contractName:o,object:e,fields:[...$t,...t]});const i=[],c=s(e.tenantCode,"tenantCode",i);wt(e.meta,i),He(e.metadata,"metadata",i),He(e.remarks,"remarks",i);const d=A(Object.fromEntries(t.flatMap(m=>Object.hasOwn(e,m)?[[m,e[m]]]:[]))),a=r(d,i,{meta:A(e.meta||{})});if(i.length>0)throw new H({contractName:o,issues:i});super({...e,tenantCode:c});const u=(p=e.meta)==null?void 0:p.revision;Number.isInteger(u)&&u>=0&&(this.meta.revision=u),this._type=e._type||o,Object.assign(this,a),Object.defineProperty(this,"_storeContractFields",{configurable:!1,enumerable:!1,value:Object.freeze([...t]),writable:!1})}getId(){return this.id===null||typeof this.id>"u"?"":this.id.toString()}toJSON(){return this.toObject()}toObject(){const o={_type:this._type,meta:ke(this.meta,ct),metadata:Ge(this.metadata),remarks:Ge(this.remarks),tenantCode:this.tenantCode,...ke(this,this._storeContractFields)},e=this.getId();return e&&(o.id=e),A(o)}}function wt(n,o){if(!(typeof n>"u")){if(!n||typeof n!="object"||Array.isArray(n)){o.push("meta must be an object");return}Object.keys(n).forEach(e=>{ct.includes(e)||o.push(`meta contains unknown field "${e}"`)}),["active","deleted"].forEach(e=>{typeof n[e]<"u"&&typeof n[e]!="boolean"&&o.push(`meta.${e} must be a boolean`)}),["created","modified"].forEach(e=>{typeof n[e]<"u"&&(!Number.isFinite(n[e])||n[e]<0)&&o.push(`meta.${e} must be a non-negative finite number`)}),["creator","owner"].forEach(e=>{typeof n[e]<"u"&&typeof n[e]!="string"&&o.push(`meta.${e} must be a string`)}),typeof n.revision<"u"&&(!Number.isInteger(n.revision)||n.revision<0)&&o.push("meta.revision must be a non-negative integer")}}function Ge(n){return Array.isArray(n)?n.map(o=>({key:o.key,value:A(o.value)})):[]}function ke(n,o){return Object.fromEntries(o.flatMap(e=>typeof n[e]>"u"?[]:[[e,A(n[e])]]))}function He(n,o,e){if(!(typeof n>"u")){if(!Array.isArray(n)){e.push(`${o} must be an array`);return}n.forEach((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t)){e.push(`${o}[${r}] must be an object`);return}Object.keys(t).forEach(i=>{["key","value"].includes(i)||e.push(`${o}[${r}] contains unknown field "${i}"`)}),s(t.key,`${o}[${r}].key`,e),Object.hasOwn(t,"value")?A(t.value,`${o}[${r}].value`):e.push(`${o}[${r}].value is required`)})}}class jt extends S{constructor(o={}){super({contractName:"Acquisition",object:o,fields:["acquisitionCode","commandCode","source","eventRegistrationCode","initiatedBy","orderCode","settlementCode","merchandiseSnapshot","productSnapshots","walletItemCodes","acquired"],normalize(e,t){const r=s(e.source,"source",t);Object.values(ce).includes(r)||t.push(`source "${r}" is not supported`);const i=D(e.orderCode,"orderCode",t),c=D(e.settlementCode,"settlementCode",t);return r===ce.PURCHASE&&!i&&t.push("orderCode is required for PURCHASE acquisition"),r!==ce.PURCHASE&&(i||c)&&t.push("non-purchase acquisition must not reference an Order or Settlement"),{acquisitionCode:s(e.acquisitionCode,"acquisitionCode",t),commandCode:s(e.commandCode,"commandCode",t),source:r,eventRegistrationCode:s(e.eventRegistrationCode,"eventRegistrationCode",t),initiatedBy:s(e.initiatedBy,"initiatedBy",t),...i?{orderCode:i}:{},...c?{settlementCode:c}:{},merchandiseSnapshot:e.merchandiseSnapshot||{},productSnapshots:te(e.productSnapshots,"productSnapshots",t),walletItemCodes:te(e.walletItemCodes,"walletItemCodes",t),acquired:$(e.acquired,"acquired",t)}}})}getCode(){return this.acquisitionCode}}class I{constructor({contractName:o,object:e,fields:t,normalize:r}){if(!e||typeof e!="object"||Array.isArray(e))throw new H({contractName:o,issues:["input must be an object"]});it({contractName:o,object:e,fields:t});const i=[],c=r(A(e),i);if(i.length>0)throw new H({contractName:o,issues:i});Object.assign(this,L(c)),Object.freeze(this)}toObject(){return A(Object.fromEntries(Object.entries(this)))}toJSON(){return this.toObject()}}class Ie extends I{constructor(o={}){super({contractName:"PriceEvaluationContext",object:o,fields:["acquisitionSource","countryCode","countryRank","currency","instant"],normalize(e,t){const r=s(e.instant,"instant",t);return r&&!Number.isFinite(Date.parse(r))&&t.push("instant must be an ISO-compatible timestamp"),{acquisitionSource:s(e.acquisitionSource,"acquisitionSource",t),countryCode:s(e.countryCode,"countryCode",t),countryRank:E(e.countryRank,"countryRank",t),currency:s(e.currency,"currency",t),instant:r}}})}}class he extends I{constructor(o={}){super({contractName:"PriceScheduleRef",object:o,fields:["priceScheduleCode","priceScheduleVersion"],normalize(e,t){return{priceScheduleCode:s(e.priceScheduleCode,"priceScheduleCode",t),priceScheduleVersion:E(e.priceScheduleVersion,"priceScheduleVersion",t)}}})}}const _=Object.freeze({ELIGIBILITY:"ELIGIBILITY",INVENTORY:"INVENTORY",PREREQUISITE:"PREREQUISITE",QUANTITY:"QUANTITY",REFUND:"REFUND",REQUIREMENT:"REQUIREMENT"}),q=Object.freeze({ACQUISITION_SOURCE:"ACQUISITION_SOURCE",CATEGORY:"CATEGORY",MERCHANDISE:"MERCHANDISE",PRODUCT:"PRODUCT"}),M=Object.freeze({CATEGORY:"CATEGORY",MERCHANDISE:"MERCHANDISE",PRODUCT:"PRODUCT"}),K=Object.freeze({ACTIVE:"ACTIVE",HOLDING:"HOLDING",ORDER:"ORDER"}),x=Object.freeze({NOT_SUBMITTED:"NOT_SUBMITTED",REOPENED:"REOPENED",REJECTED:"REJECTED",REVOKED:"REVOKED",UNDER_REVIEW:"UNDER_REVIEW",VALID:"VALID"}),ue=Object.freeze({CAPACITY_ADMISSION:"CAPACITY_ADMISSION",PRODUCTION_DEMAND:"PRODUCTION_DEMAND",STOCKED_VARIANT:"STOCKED_VARIANT"}),le=Object.freeze({ALL:"ALL",ANY:"ANY"}),G=Object.freeze({EXISTING:"EXISTING",SAME_ORDER:"SAME_ORDER"}),Ce=Object.freeze({BEFORE_ITEM_VALID:"BEFORE_ITEM_VALID"}),w=Object.freeze({ALWAYS:"ALWAYS",LOCK_AFTER_COMPLETE:"LOCK_AFTER_COMPLETE",UNTIL_DEADLINE:"UNTIL_DEADLINE"}),se=Object.freeze({COMPLETE:"COMPLETE",INCOMPLETE:"INCOMPLETE",OVERDUE:"OVERDUE"}),ee=Object.freeze({EDITABLE:"EDITABLE",LOCKED:"LOCKED"}),k=Object.freeze({EMAIL:"email",TEXT:"text",VARIANT:"VARIANT"}),b=Object.freeze({CANCELLED:"CANCELLED",EXPIRED:"EXPIRED",PENDING_REQUIREMENT:"PENDING_REQUIREMENT",REFUNDED:"REFUNDED",RESERVED:"RESERVED",REVOKED:"REVOKED",VALID:"VALID"});class Te extends I{constructor(o={}){super({contractName:"RequirementFieldDefinition",object:o,fields:["autocomplete","deferredLabel","fieldCode","inputType","label","optionValueKey"],normalize(e,t){const r=s(e.inputType,"inputType",t);Object.values(k).includes(r)||t.push(`inputType "${r}" is not supported`);const i=D(e.autocomplete,"autocomplete",t),c=D(e.deferredLabel,"deferredLabel",t),d=D(e.optionValueKey,"optionValueKey",t);return r===k.VARIANT&&!d&&t.push("optionValueKey is required when inputType is VARIANT"),r!==k.VARIANT&&d&&t.push("optionValueKey is only supported when inputType is VARIANT"),{fieldCode:s(e.fieldCode,"fieldCode",t),label:s(e.label,"label",t),inputType:r,...i?{autocomplete:i}:{},...c?{deferredLabel:c}:{},...d?{optionValueKey:d}:{}}}})}}class ne extends I{constructor(o={}){super({contractName:"RequirementDefinition",object:o,fields:["requirementCode","label","fields"],normalize(e,t){const r=(Array.isArray(e.fields)?e.fields:[]).flatMap((c,d)=>{try{return[(c instanceof Te?c:new Te(c)).toObject()]}catch(a){return t.push(`fields[${d}]: ${a.message}`),[]}});Array.isArray(e.fields)||t.push("fields must be an array"),r.length===0&&t.push("fields must contain at least one field");const i=new Set;return r.forEach((c,d)=>{i.has(c.fieldCode)&&t.push(`fields[${d}].fieldCode duplicates "${c.fieldCode}"`),i.add(c.fieldCode)}),{requirementCode:s(e.requirementCode,"requirementCode",t),label:s(e.label,"label",t),fields:r}}})}}function dt({values:n,allowedValues:o,path:e,issues:t}){n.forEach(r=>{o.includes(r)||t.push(`${e} contains unsupported value "${r}"`)})}function xt(n,o,e,t){return!n||typeof n!="object"||Array.isArray(n)?(e.push(`${o} must be an object`),{}):new I({contractName:o,object:n,fields:["code","type"],normalize(i,c){const d=typeof i.type=="string"?i.type:"",a=typeof i.code=="string"?i.code:"";return d.trim()||c.push("type must be a non-empty string"),a.trim()||c.push("code must be a non-empty string"),d&&!t.includes(d)&&c.push(`type "${d}" is not supported`),{type:d,code:a}}}).toObject()}function pe(n,o,e){if(!(typeof n>"u"||n===null||n==="")){if(typeof n!="string"||!Number.isFinite(Date.parse(n))){e.push(`${o} must be an ISO-8601 timestamp`);return}return n}}class oe extends I{constructor(o={}){super({contractName:"RequirementPlan",object:o,fields:["complete","completionDeadline","completionTiming","componentIndex","missingFields","modificationDeadline","modificationMode","productCode","requirement","ruleCode","unitIndex","values"],normalize(e,t){let r={};try{r=(e.requirement instanceof ne?e.requirement:new ne(e.requirement)).toObject()}catch(a){t.push(`requirement: ${a.message}`)}Object.values(Ce).includes(e.completionTiming)||t.push(`completionTiming "${e.completionTiming}" is not supported`),Object.values(w).includes(e.modificationMode)||t.push(`modificationMode "${e.modificationMode}" is not supported`);const i=pe(e.completionDeadline,"completionDeadline",t),c=pe(e.modificationDeadline,"modificationDeadline",t);(!Number.isInteger(e.componentIndex)||e.componentIndex<0)&&t.push("componentIndex must be a non-negative integer"),(!Number.isInteger(e.unitIndex)||e.unitIndex<0)&&t.push("unitIndex must be a non-negative integer"),typeof e.complete!="boolean"&&t.push("complete must be a boolean");let d={};try{!e.values||typeof e.values!="object"||Array.isArray(e.values)?t.push("values must be an object"):d=A(e.values)}catch(a){t.push(`values: ${a.message}`)}return{ruleCode:s(e.ruleCode,"ruleCode",t),requirement:r,productCode:s(e.productCode,"productCode",t),componentIndex:Number.isInteger(e.componentIndex)&&e.componentIndex>=0?e.componentIndex:0,unitIndex:Number.isInteger(e.unitIndex)&&e.unitIndex>=0?e.unitIndex:0,completionTiming:e.completionTiming,modificationMode:e.modificationMode,...i?{completionDeadline:i}:{},...c?{modificationDeadline:c}:{},values:d,missingFields:U(e.missingFields||[],"missingFields",t),complete:e.complete===!0}}})}}class st extends I{constructor(o={}){super({contractName:"AcquisitionSnapshot",object:o,fields:["id","contractVersion","eventRegistrationCode","purchaserEventRegistrationCode","payerEventRegistrationCode","acquisitionSource","merchandise","quantity","products","priceScheduleRef","matchedPriceRow","priceEvaluationContext","effectiveRules","eligibilityDecisions","requirementPlans","inventoryDecisions","variantSelections","evaluated"],normalize(e,t){let r={};try{r=(e.priceEvaluationContext instanceof Ie?e.priceEvaluationContext:new Ie(e.priceEvaluationContext)).toObject()}catch(d){t.push(`priceEvaluationContext: ${d.message}`)}let i={};try{i=(e.priceScheduleRef instanceof he?e.priceScheduleRef:new he(e.priceScheduleRef)).toObject()}catch(d){t.push(`priceScheduleRef: ${d.message}`)}const c=(Array.isArray(e.requirementPlans)?e.requirementPlans:[]).flatMap((d,a)=>{try{return[(d instanceof oe?d:new oe(d)).toObject()]}catch(u){return t.push(`requirementPlans[${a}]: ${u.message}`),[]}});return Array.isArray(e.requirementPlans)||t.push("requirementPlans must be an array"),{id:s(e.id,"id",t),contractVersion:E(e.contractVersion,"contractVersion",t,2),eventRegistrationCode:s(e.eventRegistrationCode,"eventRegistrationCode",t),purchaserEventRegistrationCode:s(e.purchaserEventRegistrationCode,"purchaserEventRegistrationCode",t),payerEventRegistrationCode:s(e.payerEventRegistrationCode,"payerEventRegistrationCode",t),acquisitionSource:s(e.acquisitionSource,"acquisitionSource",t),merchandise:e.merchandise||{},quantity:E(e.quantity,"quantity",t),products:e.products||[],priceScheduleRef:i,matchedPriceRow:e.matchedPriceRow||{},priceEvaluationContext:r,effectiveRules:e.effectiveRules||{},eligibilityDecisions:e.eligibilityDecisions||[],requirementPlans:c,inventoryDecisions:e.inventoryDecisions||[],variantSelections:e.variantSelections||[],evaluated:s(e.evaluated,"evaluated",t)}}})}getId(){return this.id}}class zt extends S{constructor(o={}){super({contractName:"Category",object:o,fields:["categoryCode","version","name","description"],normalize(e,t){return{categoryCode:s(e.categoryCode,"categoryCode",t),version:E(e.version,"version",t),name:s(e.name,"name",t),...D(e.description,"description",t)?{description:e.description}:{}}}})}getCode(){return this.categoryCode}}class ge extends I{constructor(o={}){super({contractName:"CommercialLifecycle",object:o,fields:["stateCode","changed","reasonCode","initiatedBy"],normalize(e,t){const r=D(e.reasonCode,"reasonCode",t),i=D(e.initiatedBy,"initiatedBy",t);return{stateCode:s(e.stateCode,"stateCode",t),changed:$(e.changed,"changed",t),...r?{reasonCode:r}:{},...i?{initiatedBy:i}:{}}}})}}function ve(n,o,e,t){try{const r=n instanceof ge?n:new ge(n);return e.includes(r.stateCode)||t.push(`${o}.stateCode "${r.stateCode}" is not supported`),r.toObject()}catch(r){return t.push(`${o}: ${r.message}`),{stateCode:"",changed:me(void 0,o,t)}}}class Qt extends S{constructor(o={}){super({contractName:"Currency",object:o,fields:["currencyCode","name","symbol","factor","unit"],normalize(e,t){const r=D(e.symbol,"symbol",t);return{currencyCode:s(e.currencyCode,"currencyCode",t),name:s(e.name,"name",t),...r?{symbol:r}:{},factor:E(e.factor,"factor",t),unit:s(e.unit,"unit",t)}}})}getCode(){return this.currencyCode}}class Yt extends I{constructor(o={}){super({contractName:"EligibilityFact",object:o,fields:["eligibilityType","state","revision","decisionReference","reasonCode"],normalize(e,t){const r=s(e.state,"state",t);return Object.values(x).includes(r)||t.push(`state "${r}" is not supported`),(!Number.isInteger(e.revision)||e.revision<0)&&t.push("revision must be a non-negative integer"),{eligibilityType:s(e.eligibilityType,"eligibilityType",t),state:r,revision:Number.isInteger(e.revision)&&e.revision>=0?e.revision:0,...D(e.decisionReference,"decisionReference",t)?{decisionReference:e.decisionReference}:{},...D(e.reasonCode,"reasonCode",t)?{reasonCode:e.reasonCode}:{}}}})}}class Bt extends S{constructor(o={}){super({contractName:"InventoryBalance",object:o,fields:["inventoryBalanceCode","inventoryPoolCode","productCode","variantCode","capacity","heldQuantity","consumedQuantity"],normalize(e,t){const r=D(e.variantCode,"variantCode",t),i=e.capacity===null?null:de(e.capacity,"capacity",t),c=de(e.heldQuantity,"heldQuantity",t),d=de(e.consumedQuantity,"consumedQuantity",t);return i!==null&&c+d>i&&t.push("heldQuantity plus consumedQuantity must not exceed capacity"),{inventoryBalanceCode:s(e.inventoryBalanceCode,"inventoryBalanceCode",t),inventoryPoolCode:s(e.inventoryPoolCode,"inventoryPoolCode",t),productCode:s(e.productCode,"productCode",t),...r?{variantCode:r}:{},capacity:i,heldQuantity:c,consumedQuantity:d}}})}getCode(){return this.inventoryBalanceCode}}const at=Object.freeze({HELD:"HELD",CONSUMED:"CONSUMED",RELEASED:"RELEASED"});class Ft extends S{constructor(o={}){super({contractName:"InventoryLedgerEntry",object:o,fields:["inventoryLedgerEntryCode","inventoryBalanceCode","reservationCode","orderCode","action","quantity","occurred"],normalize(e,t){const r=s(e.action,"action",t);Object.values(at).includes(r)||t.push(`action "${r}" is not supported`);const i=D(e.orderCode,"orderCode",t);return{inventoryLedgerEntryCode:s(e.inventoryLedgerEntryCode,"inventoryLedgerEntryCode",t),inventoryBalanceCode:s(e.inventoryBalanceCode,"inventoryBalanceCode",t),reservationCode:s(e.reservationCode,"reservationCode",t),...i?{orderCode:i}:{},action:r,quantity:E(e.quantity,"quantity",t),occurred:$(e.occurred,"occurred",t)}}})}getCode(){return this.inventoryLedgerEntryCode}}class Wt extends S{constructor(o={}){super({contractName:"Invoice",object:o,fields:["invoiceCode","invoiceNumber","orderCode","currentRevisionCode","currentRevisionNumber","issued"],normalize(e,t){return{invoiceCode:s(e.invoiceCode,"invoiceCode",t),invoiceNumber:s(e.invoiceNumber,"invoiceNumber",t),orderCode:s(e.orderCode,"orderCode",t),currentRevisionCode:s(e.currentRevisionCode,"currentRevisionCode",t),currentRevisionNumber:E(e.currentRevisionNumber,"currentRevisionNumber",t),issued:$(e.issued,"issued",t)}}})}getCode(){return this.invoiceCode}}class Gt extends S{constructor(o={}){super({contractName:"InvoiceRevision",object:o,fields:["invoiceRevisionCode","invoiceCode","revisionNumber","currency","amount","issuer","billTo","lines","instructions","issued","due"],normalize(e,t){const r=me(e.due,"due",t);return{invoiceRevisionCode:s(e.invoiceRevisionCode,"invoiceRevisionCode",t),invoiceCode:s(e.invoiceCode,"invoiceCode",t),revisionNumber:E(e.revisionNumber,"revisionNumber",t),currency:s(e.currency,"currency",t),amount:z(e.amount,"amount",t),issuer:B(e.issuer,"issuer",t),billTo:B(e.billTo,"billTo",t),lines:te(e.lines,"lines",t),instructions:B(e.instructions||{},"instructions",t),issued:$(e.issued,"issued",t),...r?{due:r}:{}}}})}getCode(){return this.invoiceRevisionCode}}class Ne extends I{constructor(o={}){super({contractName:"MerchandiseComponent",object:o,fields:["productCode","productVersion","quantityPerUnit"],normalize(e,t){return{productCode:s(e.productCode,"productCode",t),productVersion:E(e.productVersion,"productVersion",t),quantityPerUnit:E(e.quantityPerUnit,"quantityPerUnit",t)}}})}}class kt extends S{constructor(o={}){super({contractName:"Merchandise",object:o,fields:["merchandiseCode","version","name","description","components","priceScheduleCode"],normalize(e,t){let r=[];try{r=(e.components||[]).map(i=>(i instanceof Ne?i:new Ne(i)).toObject())}catch(i){t.push(`components: ${i.message}`)}return r.length===0&&t.push("components must contain at least one component"),{merchandiseCode:s(e.merchandiseCode,"merchandiseCode",t),version:E(e.version,"version",t),name:s(e.name,"name",t),...D(e.description,"description",t)?{description:e.description}:{},components:r,priceScheduleCode:s(e.priceScheduleCode,"priceScheduleCode",t)}}})}getCode(){return this.merchandiseCode}}class Ae extends I{constructor(o={}){super({contractName:"OrderLine",object:o,fields:["orderLineCode","merchandiseCode","merchandiseVersion","quantity","currency","unitAmount","totalAmount","products","commercialDecision"],normalize(e,t){return{orderLineCode:s(e.orderLineCode,"orderLineCode",t),merchandiseCode:s(e.merchandiseCode,"merchandiseCode",t),merchandiseVersion:E(e.merchandiseVersion,"merchandiseVersion",t),quantity:E(e.quantity,"quantity",t),currency:s(e.currency,"currency",t),unitAmount:z(e.unitAmount,"unitAmount",t),totalAmount:z(e.totalAmount,"totalAmount",t),products:te(e.products,"products",t),commercialDecision:B(e.commercialDecision,"commercialDecision",t)}}})}}class De extends I{constructor(o={}){super({contractName:"Reservation",object:o,fields:["reservationCode","lifecycle","heldUntil","inventoryCommitments"],normalize(e,t){const r=me(e.heldUntil,"heldUntil",t);return{reservationCode:s(e.reservationCode,"reservationCode",t),lifecycle:ve(e.lifecycle,"lifecycle",Object.values(ot),t),...r?{heldUntil:r}:{},inventoryCommitments:te(e.inventoryCommitments,"inventoryCommitments",t)}}})}}class Ht extends S{constructor(o={}){super({contractName:"Order",object:o,fields:["orderCode","submissionCode","eventRegistrationCode","purchaserEventRegistrationCode","payerEventRegistrationCode","currency","amount","catalogDecisionRevision","lines","lifecycle","reservation","invoiceCode","paymentAttemptCodes","settlementCode","acquisitionCodes","submitted"],normalize(e,t){const r=(Array.isArray(e.lines)?e.lines:[]).flatMap((d,a)=>{try{return[(d instanceof Ae?d:new Ae(d)).toObject()]}catch(u){return t.push(`lines[${a}]: ${u.message}`),[]}});r.length===0&&t.push("lines must contain at least one line");let i={};try{i=(e.reservation instanceof De?e.reservation:new De(e.reservation)).toObject()}catch(d){t.push(`reservation: ${d.message}`)}const c=D(e.settlementCode,"settlementCode",t);return{orderCode:s(e.orderCode,"orderCode",t),submissionCode:s(e.submissionCode,"submissionCode",t),eventRegistrationCode:s(e.eventRegistrationCode,"eventRegistrationCode",t),purchaserEventRegistrationCode:s(e.purchaserEventRegistrationCode,"purchaserEventRegistrationCode",t),payerEventRegistrationCode:s(e.payerEventRegistrationCode,"payerEventRegistrationCode",t),currency:s(e.currency,"currency",t),amount:z(e.amount,"amount",t),catalogDecisionRevision:s(e.catalogDecisionRevision,"catalogDecisionRevision",t),lines:r,lifecycle:ve(e.lifecycle,"lifecycle",Object.values(nt),t),reservation:i,invoiceCode:s(e.invoiceCode,"invoiceCode",t),paymentAttemptCodes:U(e.paymentAttemptCodes||[],"paymentAttemptCodes",t),...c?{settlementCode:c}:{},acquisitionCodes:U(e.acquisitionCodes||[],"acquisitionCodes",t),submitted:$(e.submitted,"submitted",t)}}})}getCode(){return this.orderCode}}function ut({paymentAttemptMeta:n,salesPeriodEnd:o}){const e=lt(n),t=pt(o,"salesPeriodEnd");return e<t}function Oe({paymentAttemptMeta:n,defaultPaymentDuration:o}){const e=lt(n);if(!Number.isInteger(o)||o<=0)throw new TypeError("defaultPaymentDuration must be a positive integer in milliseconds");return new Date(e+o).toISOString()}function lt(n){if(!n||typeof n!="object")throw new TypeError("paymentAttemptMeta must be an object");return pt(n.created,"paymentAttemptMeta.created")}function pt(n,o){const e=typeof n=="number"?n:Date.parse(n);if(!Number.isFinite(e)||e<0)throw new TypeError(`${o} must be an ISO-compatible timestamp`);return e}class Se extends I{constructor(o={}){super({contractName:"PaymentMethodConfigurationSnapshot",object:o,fields:["paymentMethodCode","version","adapterCode","display","supportedCurrencyCodes","defaultPaymentDuration","integrationBindingCode"],normalize(e,t){const r=de(e.defaultPaymentDuration,"defaultPaymentDuration",t);return r===0&&t.push("defaultPaymentDuration must be greater than zero"),{paymentMethodCode:s(e.paymentMethodCode,"paymentMethodCode",t),version:E(e.version,"version",t),adapterCode:s(e.adapterCode,"adapterCode",t),display:B(e.display,"display",t),supportedCurrencyCodes:U(e.supportedCurrencyCodes,"supportedCurrencyCodes",t),defaultPaymentDuration:r,integrationBindingCode:s(e.integrationBindingCode,"integrationBindingCode",t)}}})}}class Kt extends S{constructor(o={}){super({contractName:"PaymentAttempt",object:o,fields:["paymentAttemptCode","orderCode","invoiceCode","invoiceRevisionCode","currency","amount","paymentMethodConfigurationSnapshot","matchedCommercialDecision","paymentDeadline","lifecycle","providerReference","providerSession","providerState","providerOutcomeTime"],normalize(e,t,{meta:r}){let i={};try{i=(e.paymentMethodConfigurationSnapshot instanceof Se?e.paymentMethodConfigurationSnapshot:new Se(e.paymentMethodConfigurationSnapshot)).toObject()}catch(m){t.push(`paymentMethodConfigurationSnapshot: ${m.message}`)}let c="";try{c=i.defaultPaymentDuration?Oe({paymentAttemptMeta:r,defaultPaymentDuration:i.defaultPaymentDuration}):""}catch(m){t.push(m.message)}const d=$(e.paymentDeadline,"paymentDeadline",t);c&&d!==c&&t.push("paymentDeadline must equal meta.created plus paymentMethodConfigurationSnapshot.defaultPaymentDuration");const a=D(e.providerReference,"providerReference",t),u=D(e.providerState,"providerState",t),p=me(e.providerOutcomeTime,"providerOutcomeTime",t);return{paymentAttemptCode:s(e.paymentAttemptCode,"paymentAttemptCode",t),orderCode:s(e.orderCode,"orderCode",t),invoiceCode:s(e.invoiceCode,"invoiceCode",t),invoiceRevisionCode:s(e.invoiceRevisionCode,"invoiceRevisionCode",t),currency:s(e.currency,"currency",t),amount:z(e.amount,"amount",t),paymentMethodConfigurationSnapshot:i,matchedCommercialDecision:B(e.matchedCommercialDecision,"matchedCommercialDecision",t),paymentDeadline:d,lifecycle:ve(e.lifecycle,"lifecycle",Object.values(rt),t),...a?{providerReference:a}:{},providerSession:B(e.providerSession||{},"providerSession",t),...u?{providerState:u}:{},...p?{providerOutcomeTime:p}:{}}}})}getCode(){return this.paymentAttemptCode}static canStart(o){return ut(o)}static calculateDeadline(o){return Oe(o)}}function Ke(n,o,e){if(!(typeof n>"u"||n===null))return E(n,o,e)}class be extends I{constructor(o={}){super({contractName:"PriceMatchCriteria",object:o,fields:["countryCodes","excludedCountryCodes","countryRank"],normalize(e,t){const r=U(e.countryCodes||[],"countryCodes",t),i=U(e.excludedCountryCodes||[],"excludedCountryCodes",t),c=r.filter(a=>i.includes(a));c.length>0&&t.push(`countryCodes and excludedCountryCodes overlap: ${[...new Set(c)].join(", ")}`);let d;if(typeof e.countryRank<"u"&&e.countryRank!==null)if(typeof e.countryRank!="object"||Array.isArray(e.countryRank))t.push("countryRank must be an object");else{Object.keys(e.countryRank).filter(m=>!["min","max"].includes(m)).forEach(m=>t.push(`countryRank contains unknown field "${m}"`));const u=Ke(e.countryRank.min,"countryRank.min",t),p=Ke(e.countryRank.max,"countryRank.max",t);typeof u>"u"&&typeof p>"u"&&t.push("countryRank must contain min or max"),u&&p&&u>p&&t.push("countryRank.max must be greater than or equal to countryRank.min"),d={...u?{min:u}:{},...p?{max:p}:{}}}return{countryCodes:r,excludedCountryCodes:i,...d?{countryRank:d}:{}}}})}}class Pe extends I{constructor(o={}){super({contractName:"SalesPeriodRef",object:o,fields:["salesPeriodCode","salesPeriodVersion"],normalize(e,t){return{salesPeriodCode:s(e.salesPeriodCode,"salesPeriodCode",t),salesPeriodVersion:E(e.salesPeriodVersion,"salesPeriodVersion",t)}}})}}function Xe(n,o,e){if(typeof n>"u"||n===null)return;const t=D(n,o,e);return t&&!Number.isFinite(Date.parse(t))&&e.push(`${o} must be an ISO-compatible timestamp`),t}class _e extends I{constructor(o={}){super({contractName:"PriceRow",object:o,fields:["priceRowCode","currency","amount","match","salesPeriodRef","validFrom","validUntil","acquisitionSources"],normalize(e,t){const r=Xe(e.validFrom,"validFrom",t),i=Xe(e.validUntil,"validUntil",t);r&&i&&Date.parse(r)>=Date.parse(i)&&t.push("validUntil must be later than validFrom");let c;if(e.salesPeriodRef!==null&&typeof e.salesPeriodRef<"u")try{c=(e.salesPeriodRef instanceof Pe?e.salesPeriodRef:new Pe(e.salesPeriodRef)).toObject()}catch(a){t.push(`salesPeriodRef: ${a.message}`)}let d={};try{d=(e.match instanceof be?e.match:new be(e.match||{})).toObject()}catch(a){t.push(`match: ${a.message}`)}return{priceRowCode:s(e.priceRowCode,"priceRowCode",t),currency:s(e.currency,"currency",t),amount:z(e.amount,"amount",t),match:d,...c?{salesPeriodRef:c}:{},...r?{validFrom:r}:{},...i?{validUntil:i}:{},acquisitionSources:U(e.acquisitionSources||[],"acquisitionSources",t)}}})}}class Xt extends S{constructor(o={}){super({contractName:"PriceSchedule",object:o,fields:["priceScheduleCode","version","rows"],normalize(e,t){let r=[];try{r=(e.rows||[]).map(i=>(i instanceof _e?i:new _e(i)).toObject())}catch(i){t.push(`rows: ${i.message}`)}return r.length===0&&t.push("rows must contain at least one row"),{priceScheduleCode:s(e.priceScheduleCode,"priceScheduleCode",t),version:E(e.version,"version",t),rows:r}}})}getCode(){return this.priceScheduleCode}}class Jt extends S{constructor(o={}){super({contractName:"Product",object:o,fields:["productCode","version","name","description","categoryCodes"],normalize(e,t){return{productCode:s(e.productCode,"productCode",t),version:E(e.version,"version",t),name:s(e.name,"name",t),...D(e.description,"description",t)?{description:e.description}:{},categoryCodes:U(e.categoryCodes||[],"categoryCodes",t)}}})}getCode(){return this.productCode}}class Zt extends I{constructor(o={}){super({contractName:"EligibilityRuleDetails",object:o,fields:["acceptedStates","eligibilityType"],normalize(e,t){const r=U(e.acceptedStates||[],"acceptedStates",t);return r.length===0&&t.push("acceptedStates must contain at least one state"),dt({values:r,allowedValues:Object.values(x),path:"acceptedStates",issues:t}),{eligibilityType:s(e.eligibilityType,"eligibilityType",t),acceptedStates:r}}})}}class en extends I{constructor(o={}){super({contractName:"InventoryRuleDetails",object:o,fields:["inventoryMode","inventoryPoolCode"],normalize(e,t){return Object.values(ue).includes(e.inventoryMode)||t.push(`inventoryMode "${e.inventoryMode}" is not supported`),{inventoryMode:e.inventoryMode,inventoryPoolCode:s(e.inventoryPoolCode,"inventoryPoolCode",t)}}})}}class tn extends I{constructor(o={}){super({contractName:"PrerequisiteRuleDetails",object:o,fields:["continuous","evidenceSources","matchMode","requires"],normalize(e,t){(!Array.isArray(e.requires)||e.requires.length===0)&&t.push("requires must contain at least one target");const r=(e.requires||[]).map((c,d)=>{try{return xt(c,`requires[${d}]`,t,Object.values(M))}catch(a){return t.push(`requires[${d}]: ${a.message}`),{}}});Object.values(le).includes(e.matchMode)||t.push(`matchMode "${e.matchMode}" is not supported`);const i=U(e.evidenceSources||[],"evidenceSources",t);return dt({values:i,allowedValues:Object.values(G),path:"evidenceSources",issues:t}),{requires:r,matchMode:e.matchMode,evidenceSources:i,continuous:e.continuous===!0}}})}}class nn extends I{constructor(o={}){super({contractName:"QuantityRuleDetails",object:o,fields:["limit","limitType"],normalize(e,t){return Object.values(K).includes(e.limitType)||t.push(`limitType "${e.limitType}" is not supported`),{limitType:e.limitType,limit:E(e.limit,"limit",t)}}})}}class Me extends I{constructor(o={}){super({contractName:"RefundPolicyRef",object:o,fields:["refundPolicyCode","refundPolicyVersion"],normalize(e,t){return{refundPolicyCode:s(e.refundPolicyCode,"refundPolicyCode",t),refundPolicyVersion:E(e.refundPolicyVersion,"refundPolicyVersion",t)}}})}}class on extends I{constructor(o={}){super({contractName:"RefundRuleDetails",object:o,fields:["refundPolicyRef"],normalize(e,t){try{return{refundPolicyRef:(e.refundPolicyRef instanceof Me?e.refundPolicyRef:new Me(e.refundPolicyRef)).toObject()}}catch(r){return t.push(`refundPolicyRef: ${r.message}`),{refundPolicyRef:{}}}}})}}class rn extends I{constructor(o={}){super({contractName:"RequirementRuleDetails",object:o,fields:["completionDeadline","completionTiming","modificationDeadline","modificationMode","requirement"],normalize(e,t){let r={};try{r=(e.requirement instanceof ne?e.requirement:new ne(e.requirement)).toObject()}catch(d){t.push(`requirement: ${d.message}`)}Object.values(Ce).includes(e.completionTiming)||t.push(`completionTiming "${e.completionTiming}" is not supported`),Object.values(w).includes(e.modificationMode)||t.push(`modificationMode "${e.modificationMode}" is not supported`);const i=pe(e.completionDeadline,"completionDeadline",t),c=pe(e.modificationDeadline,"modificationDeadline",t);return e.modificationMode===w.UNTIL_DEADLINE&&!c&&t.push("modificationDeadline is required when modificationMode is UNTIL_DEADLINE"),e.modificationMode!==w.UNTIL_DEADLINE&&c&&t.push("modificationDeadline is only supported when modificationMode is UNTIL_DEADLINE"),{requirement:r,completionTiming:e.completionTiming,modificationMode:e.modificationMode,...i?{completionDeadline:i}:{},...c?{modificationDeadline:c}:{}}}})}}const cn=Object.freeze({[_.ELIGIBILITY]:Zt,[_.INVENTORY]:en,[_.PREREQUISITE]:tn,[_.QUANTITY]:nn,[_.REFUND]:on,[_.REQUIREMENT]:rn});function dn(n,o){const e=cn[n];if(!e)throw new TypeError(`Rule type "${n}" does not have a details contract`);return new e(o)}function sn(n,o,e){if(!n||typeof n!="object"||Array.isArray(n))return e.push(`${o} must be an object`),{};const t=s(n.type,`${o}.type`,e),r=s(n.code,`${o}.code`,e);return Object.keys(n).forEach(i=>{["code","type"].includes(i)||e.push(`${o} contains unknown field "${i}"`)}),Object.values(M).includes(t)||e.push(`${o}.type "${t}" is not supported`),{type:t,code:r}}class an extends S{constructor(o={}){super({contractName:"PublishedRule",object:o,fields:["publishedRuleCode","version","ruleType","sourceType","sourceCode","appliesTo","details","reason"],normalize(e,t){const r=s(e.ruleType,"ruleType",t);Object.values(_).includes(r)||t.push(`ruleType "${r}" is not supported`);const i=s(e.sourceType,"sourceType",t);Object.values(q).includes(i)||t.push(`sourceType "${i}" is not supported`);const c=sn(e.appliesTo,"appliesTo",t);let d={};try{d=dn(r,e.details).toObject()}catch(a){t.push(`details: ${a.message}`)}return{publishedRuleCode:s(e.publishedRuleCode,"publishedRuleCode",t),version:E(e.version,"version",t),ruleType:r,sourceType:i,sourceCode:s(e.sourceCode,"sourceCode",t),appliesTo:c,details:d,...e.reason?{reason:e.reason}:{}}}})}getCode(){return this.publishedRuleCode}}class un extends I{constructor(o={}){super({contractName:"PublishedRuleRef",object:o,fields:["publishedRuleCode","publishedRuleVersion"],normalize(e,t){return{publishedRuleCode:s(e.publishedRuleCode,"publishedRuleCode",t),publishedRuleVersion:E(e.publishedRuleVersion,"publishedRuleVersion",t)}}})}}class ln extends S{constructor(o={}){super({contractName:"Receipt",object:o,fields:["receiptCode","receiptNumber","settlementCode","orderCode","invoiceCode","invoiceRevisionCode","currency","amount","issued"],normalize(e,t){return{receiptCode:s(e.receiptCode,"receiptCode",t),receiptNumber:s(e.receiptNumber,"receiptNumber",t),settlementCode:s(e.settlementCode,"settlementCode",t),orderCode:s(e.orderCode,"orderCode",t),invoiceCode:s(e.invoiceCode,"invoiceCode",t),invoiceRevisionCode:s(e.invoiceRevisionCode,"invoiceRevisionCode",t),currency:s(e.currency,"currency",t),amount:z(e.amount,"amount",t),issued:$(e.issued,"issued",t)}}})}getCode(){return this.receiptCode}}class pn extends S{constructor(o={}){super({contractName:"RefundPolicy",object:o,fields:["refundPolicyCode","version","name"],normalize(e,t){return{refundPolicyCode:s(e.refundPolicyCode,"refundPolicyCode",t),version:E(e.version,"version",t),name:s(e.name,"name",t)}}})}getCode(){return this.refundPolicyCode}}function Je(n,o,e){const t=s(n,o,e);return t&&!Number.isFinite(Date.parse(t))&&e.push(`${o} must be an ISO-compatible timestamp`),t}class mn extends S{constructor(o={}){super({contractName:"SalesPeriod",object:o,fields:["salesPeriodCode","version","name","validFrom","validUntil"],normalize(e,t){const r=Je(e.validFrom,"validFrom",t),i=Je(e.validUntil,"validUntil",t);return r&&i&&Date.parse(r)>=Date.parse(i)&&t.push("validUntil must be later than validFrom"),{salesPeriodCode:s(e.salesPeriodCode,"salesPeriodCode",t),version:E(e.version,"version",t),name:s(e.name,"name",t),validFrom:r,validUntil:i}}})}getCode(){return this.salesPeriodCode}}class Cn extends S{constructor(o={}){super({contractName:"Settlement",object:o,fields:["settlementCode","settlementCommandCode","paymentAttemptCode","orderCode","invoiceCode","invoiceRevisionCode","currency","amount","providerCode","providerReference","providerEventCode","confirmed"],normalize(e,t){return{settlementCode:s(e.settlementCode,"settlementCode",t),settlementCommandCode:s(e.settlementCommandCode,"settlementCommandCode",t),paymentAttemptCode:s(e.paymentAttemptCode,"paymentAttemptCode",t),orderCode:s(e.orderCode,"orderCode",t),invoiceCode:s(e.invoiceCode,"invoiceCode",t),invoiceRevisionCode:s(e.invoiceRevisionCode,"invoiceRevisionCode",t),currency:s(e.currency,"currency",t),amount:z(e.amount,"amount",t),providerCode:s(e.providerCode,"providerCode",t),providerReference:s(e.providerReference,"providerReference",t),providerEventCode:s(e.providerEventCode,"providerEventCode",t),confirmed:$(e.confirmed,"confirmed",t)}}})}getCode(){return this.settlementCode}}class En extends S{constructor(o={}){super({contractName:"Variant",object:o,fields:["variantCode","version","productCode","productVersion","name","optionValues"],normalize(e,t){return(!e.optionValues||typeof e.optionValues!="object"||Array.isArray(e.optionValues))&&t.push("optionValues must be an object"),{variantCode:s(e.variantCode,"variantCode",t),version:E(e.version,"version",t),productCode:s(e.productCode,"productCode",t),productVersion:E(e.productVersion,"productVersion",t),name:s(e.name,"name",t),optionValues:e.optionValues||{}}}})}getCode(){return this.variantCode}}class qe extends I{constructor(o={}){super({contractName:"VariantRef",object:o,fields:["variantCode","variantVersion"],normalize(e,t){return{variantCode:s(e.variantCode,"variantCode",t),variantVersion:E(e.variantVersion,"variantVersion",t)}}})}}class re extends S{constructor(o={}){super({contractName:"WalletItem",object:o,fields:["walletItemCode","productCode","productVersion","state","quantity","acquisitionCode","eventRegistrationCode","variantCode","variantVersion","requirementPlans"],normalize(e,t){const r=D(e.variantCode,"variantCode",t),i=typeof e.variantVersion>"u"||e.variantVersion===null?void 0:E(e.variantVersion,"variantVersion",t);(r&&typeof i>"u"||!r&&typeof i<"u")&&t.push("variantCode and variantVersion must be provided together"),Array.isArray(e.requirementPlans||[])||t.push("requirementPlans must be an array");const c=s(e.state,"state",t);Object.values(b).includes(c)||t.push(`state "${c}" is not supported`);const d=(Array.isArray(e.requirementPlans)?e.requirementPlans:[]).flatMap((a,u)=>{try{return[(a instanceof oe?a:new oe(a)).toObject()]}catch(p){return t.push(`requirementPlans[${u}]: ${p.message}`),[]}});return{walletItemCode:s(e.walletItemCode,"walletItemCode",t),productCode:s(e.productCode,"productCode",t),productVersion:E(e.productVersion,"productVersion",t),state:c,quantity:E(e.quantity,"quantity",t),acquisitionCode:s(e.acquisitionCode,"acquisitionCode",t),...D(e.eventRegistrationCode,"eventRegistrationCode",t)?{eventRegistrationCode:e.eventRegistrationCode}:{},...r?{variantCode:r,variantVersion:i}:{},requirementPlans:d}}})}getCode(){return this.walletItemCode}}const Ze=[q.CATEGORY,q.PRODUCT,q.MERCHANDISE,q.ACQUISITION_SOURCE];function et(n,o){return`${n}:${o}`}function fn({rule:n,relevantCategoryCodes:o,relevantProductCodes:e,merchandise:t}){if(n.sourceType===q.CATEGORY)return n.appliesTo.type===M.CATEGORY&&n.appliesTo.code===n.sourceCode;if(n.sourceType===q.PRODUCT)return n.appliesTo.type===M.PRODUCT&&n.appliesTo.code===n.sourceCode;if(n.sourceType===q.MERCHANDISE)return n.appliesTo.type===M.MERCHANDISE?n.appliesTo.code===t.merchandiseCode:n.appliesTo.type===M.PRODUCT?e.has(n.appliesTo.code):n.appliesTo.type===M.CATEGORY?o.has(n.appliesTo.code):!1;if(n.sourceType===q.ACQUISITION_SOURCE){if(n.appliesTo.type===M.MERCHANDISE)return n.appliesTo.code===t.merchandiseCode;if(n.appliesTo.type===M.PRODUCT)return e.has(n.appliesTo.code);if(n.appliesTo.type===M.CATEGORY)return o.has(n.appliesTo.code)}return!1}function mt({categories:n=[],products:o=[],merchandise:e,acquisitionSource:t,publishedRules:r=[]}){const i=new Set(e.components.map(l=>`${l.productCode}@${l.productVersion}`)),c=o.filter(l=>i.has(`${l.productCode}@${l.version}`)),d=new Set(c.map(l=>l.productCode)),a=new Set(c.flatMap(l=>l.categoryCodes||[])),p=[...n.filter(l=>a.has(l.categoryCode)).map(l=>({sourceType:q.CATEGORY,sourceCode:l.categoryCode})),...c.map(l=>({sourceType:q.PRODUCT,sourceCode:l.productCode})),{sourceType:q.MERCHANDISE,sourceCode:e.merchandiseCode},{sourceType:q.ACQUISITION_SOURCE,sourceCode:t}],m=new Set(p.map(l=>et(l.sourceType,l.sourceCode))),y=r.filter(l=>m.has(et(l.sourceType,l.sourceCode))).reduce((l,R)=>{const N=l.get(R.publishedRuleCode)||[];return N.push(R),l.set(R.publishedRuleCode,N),l},new Map),T=[],C=[],f=[],g=new Set;y.forEach((l,R)=>{if(l.length>1){T.push({code:"RULE_PUBLICATION_AMBIGUOUS",ruleCode:R,sources:l.map(F=>({sourceType:F.sourceType,sourceCode:F.sourceCode})),versions:l.map(F=>F.version)});return}const[N]=l;if(N.tenantCode!==e.tenantCode){T.push({code:"RULE_TENANT_MISMATCH",ruleCode:N.publishedRuleCode,ruleTenantCode:N.tenantCode,expectedTenantCode:e.tenantCode});return}if(!fn({rule:N,relevantCategoryCodes:a,relevantProductCodes:d,merchandise:e})){T.push({code:"RULE_TARGET_MISMATCH",ruleCode:N.publishedRuleCode,sourceType:N.sourceType,sourceCode:N.sourceCode,appliesTo:A(N.appliesTo)});return}const ie=`${N.publishedRuleCode}@${N.version}`;g.has(ie)||(g.add(ie),f.push(N)),C.push({ruleCode:N.publishedRuleCode,ruleVersion:N.version,ruleType:N.ruleType,sourceType:N.sourceType,sourceCode:N.sourceCode})}),f.sort((l,R)=>Ze.indexOf(l.sourceType)-Ze.indexOf(R.sourceType)||l.publishedRuleCode.localeCompare(R.publishedRuleCode));const O=f.map(l=>typeof l.toObject=="function"?l.toObject():A(l)),V=Object.fromEntries(Object.values(_).map(l=>[l,O.filter(R=>R.ruleType===l)]));return L({passed:T.length===0,rules:O,byType:V,trace:C,errors:T})}const Ct=Object.freeze([b.CANCELLED,b.EXPIRED,b.REFUNDED,b.REVOKED]),Et=Object.freeze([b.PENDING_REQUIREMENT,b.RESERVED,b.VALID]),P=Object.freeze({DEFINITION_INVALID:"DEFINITION_INVALID",ELIGIBILITY_REJECTED:"ELIGIBILITY_REJECTED",ELIGIBILITY_REQUIRED:"ELIGIBILITY_REQUIRED",ELIGIBILITY_REVOKED:"ELIGIBILITY_REVOKED",ELIGIBILITY_UNDER_REVIEW:"ELIGIBILITY_UNDER_REVIEW",INVENTORY_UNAVAILABLE:"INVENTORY_UNAVAILABLE",PREREQUISITE_NOT_MET:"PREREQUISITE_NOT_MET",PRICE_COUNTRY_UNRESOLVED:"PRICE_COUNTRY_UNRESOLVED",PRICE_MATCH_CRITERIA_NOT_MET:"PRICE_MATCH_CRITERIA_NOT_MET",PRICE_ROW_AMBIGUOUS:"PRICE_ROW_AMBIGUOUS",PRICE_ROW_NOT_FOUND:"PRICE_ROW_NOT_FOUND",QUANTITY_LIMIT_EXCEEDED:"QUANTITY_LIMIT_EXCEEDED",REQUIREMENT_INCOMPLETE:"REQUIREMENT_INCOMPLETE",REVISION_CONFLICT:"REVISION_CONFLICT",VARIANT_SELECTION_REQUIRED:"VARIANT_SELECTION_REQUIRED"});function v({passed:n,code:o=null,message:e,details:t={}}){return L({passed:n,code:o,message:e,details:A(t)})}function Q(n,o){return n.type===M.PRODUCT?o.productCode===n.code:n.type===M.CATEGORY?(o.categoryCodes||[]).includes(n.code):n.type===M.MERCHANDISE?o.merchandiseCode===n.code:!1}function ae(n,o,e){return n.reduce((t,r)=>!Q(o,r)||e&&!e.includes(r.state)?t:t+(r.quantity||1),0)}function yn(n){return(n==null?void 0:n.state)===b.VALID}function ft({rules:n=[],existingItems:o=[],candidateItems:e=[],activeItemStates:t=Et}){const r=n.filter(i=>i.ruleType===_.QUANTITY).filter(i=>e.some(c=>Q(i.appliesTo,c))).map(i=>{const c=ae(e,i.appliesTo);let d=0;i.details.limitType===K.HOLDING?d=ae(o.filter(p=>!Ct.includes(p.state)),i.appliesTo):i.details.limitType===K.ACTIVE&&(d=ae(o,i.appliesTo,t));const a=d+c,u=a<=i.details.limit;return v({passed:u,...u?{}:{code:P.QUANTITY_LIMIT_EXCEEDED},message:u?"Quantity rule passed":"Quantity limit would be exceeded",details:{ruleCode:i.publishedRuleCode,ruleVersion:i.version,limitType:i.details.limitType,target:i.appliesTo,current:d,addition:c,resulting:a,limit:i.details.limit,remaining:Math.max(0,i.details.limit-d)}})});return L({passed:r.every(i=>i.passed),decisions:r})}function Rn(n){return n===x.UNDER_REVIEW?P.ELIGIBILITY_UNDER_REVIEW:n===x.REJECTED?P.ELIGIBILITY_REJECTED:n===x.REVOKED?P.ELIGIBILITY_REVOKED:P.ELIGIBILITY_REQUIRED}function yt({rules:n=[],eligibilityFacts:o=[],eventRegistrationCode:e,candidateItems:t=[]}){const r=n.filter(i=>i.ruleType===_.ELIGIBILITY).filter(i=>t.some(c=>Q(i.appliesTo,c))).map(i=>{const c=o.find(u=>u.eligibilityType===i.details.eligibilityType&&(!e||!u.eventRegistrationCode||u.eventRegistrationCode===e)),d=(c==null?void 0:c.state)||x.NOT_SUBMITTED,a=(i.details.acceptedStates||[x.VALID]).includes(d);return v({passed:a,...a?{}:{code:Rn(d)},message:a?"Eligibility rule passed":"Required eligibility is not valid",details:{ruleCode:i.publishedRuleCode,eligibilityType:i.details.eligibilityType,eventRegistrationCode:e||null,state:d,factRevision:(c==null?void 0:c.revision)||null}})});return L({passed:r.every(i=>i.passed),decisions:r})}function In(n,o){return yn(n)&&Q(o,n)}function hn(n){return Object.fromEntries(["walletItemCode","acquisitionCode","merchandiseCode","productCode","productVersion","categoryCodes","state","quantity","componentIndex"].flatMap(e=>typeof n[e]>"u"?[]:[[e,A(n[e])]]))}function Rt({rules:n=[],existingItems:o=[],candidateItems:e=[]}){const t=n.filter(r=>r.ruleType===_.PREREQUISITE).filter(r=>e.some(i=>Q(r.appliesTo,i))).map(r=>{const i=r.details.evidenceSources||[G.EXISTING,G.SAME_ORDER],c=[...i.includes(G.EXISTING)?o:[],...i.includes(G.SAME_ORDER)?e:[]],d=(r.details.requires||[]).map(u=>({requirement:u,matched:c.filter(p=>In(p,u)).map(hn)})),a=r.details.matchMode===le.ALL?d.every(u=>u.matched.length>0):d.some(u=>u.matched.length>0);return v({passed:a,...a?{}:{code:P.PREREQUISITE_NOT_MET},message:a?"Prerequisite rule passed":"Prerequisite item was not found",details:{ruleCode:r.publishedRuleCode,matchMode:r.details.matchMode||le.ANY,continuous:r.details.continuous||!1,requirementResults:d}})});return L({passed:t.every(r=>r.passed),decisions:t})}function It({rules:n=[],candidateItems:o=[],requirementInputs:e=[],requirementValues:t={},variantSelections:r=[]}){const i=n.filter(c=>c.ruleType===_.REQUIREMENT).filter(c=>o.some(d=>Q(c.appliesTo,d))).flatMap(c=>o.filter(d=>Q(c.appliesTo,d)).flatMap(d=>Array.from({length:d.quantity},(a,u)=>{var l;const p=c.details.requirement,m=p.requirementCode,h=e.find(R=>R.productCode===d.productCode&&R.requirementCode===m),y=t[m],T=Array.isArray(y)?y:[y||{}],f=h&&u<h.inputs.length?h.inputs[u]||{}:T[u]||{},g=(l=r.find(R=>R.productCode===d.productCode))==null?void 0:l.selections[u],O=Object.fromEntries(p.fields.map(R=>R.inputType==="VARIANT"?[R.fieldCode,(g==null?void 0:g.variantCode)||""]:[R.fieldCode,f[R.fieldCode]||""])),V=p.fields.map(R=>R.fieldCode).filter(R=>typeof O[R]!="string"||O[R].trim().length===0);return{ruleCode:c.publishedRuleCode,requirement:p,productCode:d.productCode,componentIndex:d.componentIndex,unitIndex:u,completionTiming:c.details.completionTiming||Ce.BEFORE_ITEM_VALID,modificationMode:c.details.modificationMode,...c.details.completionDeadline?{completionDeadline:c.details.completionDeadline}:{},...c.details.modificationDeadline?{modificationDeadline:c.details.modificationDeadline}:{},values:A(O),missingFields:V,complete:V.length===0}})));return L({passed:!0,itemValid:i.every(c=>c.complete),code:i.every(c=>c.complete)?null:P.REQUIREMENT_INCOMPLETE,plans:i})}function Tn({requirementPlan:n={},rule:o,instant:e}){if(!o||o.ruleType!==_.REQUIREMENT)throw new TypeError("rule must be a REQUIREMENT PublishedRule");const t=Date.parse(e);if(!Number.isFinite(t))throw new TypeError("instant must be an ISO-8601 timestamp");const r=o.details,i=!!(r.completionDeadline&&t>=Date.parse(r.completionDeadline)),c=n.complete?se.COMPLETE:i?se.OVERDUE:se.INCOMPLETE;let d=ee.EDITABLE,a=null;return r.modificationMode===w.LOCK_AFTER_COMPLETE&&n.complete?(d=ee.LOCKED,a="REQUIREMENT_COMPLETE"):r.modificationMode===w.UNTIL_DEADLINE&&t>=Date.parse(r.modificationDeadline)&&(d=ee.LOCKED,a="MODIFICATION_DEADLINE_PASSED"),L({requirementCode:r.requirement.requirementCode,completionState:c,modificationState:d,canModify:d===ee.EDITABLE,modificationReason:a,completionDeadline:r.completionDeadline||null,modificationDeadline:r.modificationDeadline||null,evaluated:e})}function gn(n,o){const e=Date.parse(o);return!(!Number.isFinite(e)||n.validFrom&&e<Date.parse(n.validFrom)||n.validUntil&&e>=Date.parse(n.validUntil))}function Nn({row:n,salesPeriods:o}){if(!n.salesPeriodRef)return{available:!0,salesPeriod:null,window:n};const e=o.find(r=>r.salesPeriodCode===n.salesPeriodRef.salesPeriodCode&&r.version===n.salesPeriodRef.salesPeriodVersion);if(e){const r={salesPeriodCode:e.salesPeriodCode,version:e.version,validFrom:e.validFrom,validUntil:e.validUntil};return{available:!0,salesPeriod:r,window:r}}const t=!!n.validFrom||!!n.validUntil;return o.length===0&&t?{available:!0,salesPeriod:null,window:n}:{available:!1,salesPeriod:null,window:null}}function An(n={},o,e){const t=n.countryCodes||[],r=n.excludedCountryCodes||[];return t.length>0&&!t.includes(o)||r.includes(o)?!1:n.countryRank?!(!Number.isInteger(e)||e<1||n.countryRank.min&&e<n.countryRank.min||n.countryRank.max&&e>n.countryRank.max):!0}function Le({match:n={},countryCode:o,countryRank:e}){if(typeof o!="string"||o.trim().length===0||!Number.isInteger(e)||e<1)return v({passed:!1,code:P.PRICE_COUNTRY_UNRESOLVED,message:"Country code and rank are required to evaluate price match criteria",details:{countryCode:o||null,countryRank:e??null}});const t=An(n,o,e);return v({passed:t,...t?{}:{code:P.PRICE_MATCH_CRITERIA_NOT_MET},message:t?"Price match criteria passed":"Price match criteria were not met",details:{countryCode:o,countryRank:e}})}function ht({priceSchedule:n,salesPeriods:o=[],currency:e,countryCode:t,countryRank:r,acquisitionSource:i,instant:c}){const d=Le({match:{},countryCode:t,countryRank:r});if(!d.passed)return d;const a=n.rows.flatMap(u=>{const p=Nn({row:u,salesPeriods:o});return u.currency===e&&Le({match:u.match,countryCode:t,countryRank:r}).passed&&(u.acquisitionSources.length===0||u.acquisitionSources.includes(i))&&p.available&&gn(p.window,c)?[{row:u,salesPeriod:p.salesPeriod}]:[]});return a.length===0?v({passed:!1,code:P.PRICE_ROW_NOT_FOUND,message:"No price row matches the acquisition context",details:{currency:e,countryCode:t,countryRank:r,acquisitionSource:i,instant:c}}):a.length>1?v({passed:!1,code:P.PRICE_ROW_AMBIGUOUS,message:"More than one price row matches the acquisition context",details:{matchingPriceRowCodes:a.map(({row:u})=>u.priceRowCode)}}):v({passed:!0,message:"Price row resolved",details:{countryCode:t,countryRank:r,matchedPriceRow:a[0].row,matchedSalesPeriod:a[0].salesPeriod}})}function Tt({rules:n=[],candidateItems:o=[],inventoryFacts:e=[],variantSelections:t=[]}){const r=n.filter(i=>i.ruleType===_.INVENTORY).filter(i=>o.some(c=>Q(i.appliesTo,c))).map(i=>{const c=ae(o,i.appliesTo),d=t.find(C=>C.productCode===i.appliesTo.code),a=Array.from({length:c},(C,f)=>(d==null?void 0:d.selections[f])||null),u=a.length===c&&a.every(Boolean),m=[...a.reduce((C,f)=>{const O=(f==null?void 0:f.variantCode)||"UNSELECTED";return C.set(O,(C.get(O)||0)+1),C},new Map)].map(([C,f])=>{const g=e.find(O=>O.inventoryPoolCode===i.details.inventoryPoolCode&&(C==="UNSELECTED"||O.variantCode===C));return{variantCode:C==="UNSELECTED"?null:C,requested:f,available:(g==null?void 0:g.available)??0,revision:(g==null?void 0:g.revision)??null}}),h=i.details.inventoryMode===ue.STOCKED_VARIANT&&!u,y=m.every(C=>C.available>=C.requested),T=i.details.inventoryMode===ue.PRODUCTION_DEMAND||!h&&y;return v({passed:T,...T?{}:{code:h?P.VARIANT_SELECTION_REQUIRED:P.INVENTORY_UNAVAILABLE},message:T?"Inventory rule passed":h?"A Variant must be selected for every unit":"Inventory is unavailable",details:{ruleCode:i.publishedRuleCode,inventoryMode:i.details.inventoryMode,inventoryPoolCode:i.details.inventoryPoolCode,requested:c,requests:m,intent:T?{type:"RESERVE_OR_RECORD_DEMAND",requests:m}:null}})});return L({passed:r.every(i=>i.passed),decisions:r})}function gt({merchandise:n,products:o,quantity:e}){const t=new Map(o.map(r=>[r.productCode,r]));return n.components.map((r,i)=>{const c=t.get(r.productCode);if(!c)throw new Error(`Product ${r.productCode} is not available for Merchandise ${n.merchandiseCode}`);return{productCode:c.productCode,productVersion:c.version,categoryCodes:c.categoryCodes,merchandiseCode:n.merchandiseCode,componentIndex:i,quantity:e*r.quantityPerUnit,state:b.VALID}})}function Dn(n,o){return n.flatMap(e=>Array.from({length:e.quantity},(t,r)=>{const i=o.filter(c=>c.componentIndex===e.componentIndex&&c.unitIndex===r);return{...e,quantity:1,state:i.every(c=>c.complete)?b.VALID:b.PENDING_REQUIREMENT}}))}function tt({items:n,path:o,productDefinitions:e},t){return n.map((r,i)=>{const c=e.filter(a=>a.productCode===r.productCode&&a.version===r.productVersion);return c.length!==1&&t.push({path:`${o}[${i}].productCode`,message:c.length===0?`Product ${r.productCode}@${r.productVersion} is missing from recipient Product definitions`:`Product ${r.productCode}@${r.productVersion} is ambiguous in recipient Product definitions`}),{...typeof r.toObject=="function"?r.toObject():r,categoryCodes:c.length===1?[...c[0].categoryCodes]:[]}})}function On({acquisitionSnapshots:n,items:o,path:e},t){return o.map((r,i)=>{var a,u;const c=n.filter(p=>p.id===r.acquisitionCode),d=(u=(a=c[0])==null?void 0:a.merchandise)==null?void 0:u.merchandiseCode;return(c.length!==1||!d)&&t.push({path:`${e}[${i}].acquisitionCode`,message:c.length===0?`Acquisition ${r.acquisitionCode} is missing from recipient Acquisition snapshots`:c.length>1?`Acquisition ${r.acquisitionCode} is ambiguous in recipient Acquisition snapshots`:`Acquisition ${r.acquisitionCode} does not contain a Merchandise code`}),{...r,...d?{merchandiseCode:d}:{}}})}function Sn(n,o){if(!Array.isArray(n))return o.push({path:"variantSelections",message:"variantSelections must be an array"}),[];const e=new Set;return n.flatMap((t,r)=>{const i=`variantSelections[${r}]`;if(!t||typeof t!="object"||Array.isArray(t))return o.push({path:i,message:"variant selection group must be an object"}),[];const c=typeof t.productCode=="string"?t.productCode.trim():"";if(c?e.has(c)?o.push({path:`${i}.productCode`,message:`duplicate Product ${c}`}):e.add(c):o.push({path:`${i}.productCode`,message:"productCode must be a non-empty string"}),!Array.isArray(t.selections))return o.push({path:`${i}.selections`,message:"selections must be an array"}),[{productCode:c,selections:[]}];const d=t.selections.flatMap((a,u)=>{if(a===null)return[null];try{return[(a instanceof qe?a:new qe(a)).toObject()]}catch(p){return o.push({path:`${i}.selections[${u}]`,message:p.message}),[]}});return[{productCode:c,selections:d}]})}function bn(n,o){if(!Array.isArray(n))return o.push({path:"requirementInputs",message:"requirementInputs must be an array"}),[];const e=new Set;return n.flatMap((t,r)=>{const i=`requirementInputs[${r}]`;if(!t||typeof t!="object"||Array.isArray(t))return o.push({path:i,message:"requirement input group must be an object"}),[];const c=typeof t.productCode=="string"?t.productCode.trim():"",d=typeof t.requirementCode=="string"?t.requirementCode.trim():"";c||o.push({path:`${i}.productCode`,message:"productCode must be a non-empty string"}),d||o.push({path:`${i}.requirementCode`,message:"requirementCode must be a non-empty string"});const a=`${c}:${d}`;if(c&&d&&e.has(a)&&o.push({path:i,message:`duplicate Requirement ${d} for Product ${c}`}),e.add(a),!Array.isArray(t.inputs))return o.push({path:`${i}.inputs`,message:"inputs must be an array"}),[{productCode:c,requirementCode:d,inputs:[]}];const u=t.inputs.map((p,m)=>p===null?null:!p||typeof p!="object"||Array.isArray(p)?(o.push({path:`${i}.inputs[${m}]`,message:"input must be an object or null"}),null):A(p));return[{productCode:c,requirementCode:d,inputs:u}]})}function Pn({categories:n,merchandise:o,priceSchedule:e,products:t,variants:r},i){const c=o.tenantCode;[e,...n,...t,...r].forEach(a=>{var u;a.tenantCode!==c&&i.push({path:`${a._type||((u=a.constructor)==null?void 0:u.name)||"definition"}.tenantCode`,message:`expected ${c} but received ${a.tenantCode}`})})}function _n({merchandise:n,variants:o,variantSelections:e},t){const r=new Map(n.components.map(i=>[i.productCode,i]));e.forEach((i,c)=>{const{productCode:d,selections:a}=i,u=`variantSelections[${c}]`,p=r.get(d);if(!p){t.push({path:`${u}.productCode`,message:`Product ${d} is not a Merchandise component`});return}a.filter(Boolean).forEach((m,h)=>{const y=o.filter(C=>C.variantCode===m.variantCode&&C.version===m.variantVersion);if(y.length!==1){t.push({path:`${u}.selections[${h}]`,message:y.length===0?`Variant ${m.variantCode}@${m.variantVersion} is missing`:`Variant ${m.variantCode}@${m.variantVersion} is ambiguous`});return}const[T]=y;(T.productCode!==d||T.productVersion!==p.productVersion)&&t.push({path:`${u}.selections[${h}]`,message:`Variant ${m.variantCode}@${m.variantVersion} does not belong to Product ${d}@${p.productVersion}`})})})}function Nt({categories:n=[],merchandise:o,priceSchedule:e,products:t=[],quantity:r,requirementInputs:i=[],variants:c=[],variantSelections:d=[]}){const a=[],u=Sn(d,a),p=bn(i,a);(!Number.isInteger(r)||r<1)&&a.push({path:"quantity",message:"quantity must be a positive integer"}),Pn({categories:n,merchandise:o,priceSchedule:e,products:t,variants:c},a),e.priceScheduleCode!==o.priceScheduleCode&&a.push({path:"priceSchedule.priceScheduleCode",message:`expected ${o.priceScheduleCode} but received ${e.priceScheduleCode}`});const m=t.reduce((C,f)=>{const g=C.get(f.productCode)||[];return g.push(f),C.set(f.productCode,g),C},new Map),h=n.reduce((C,f)=>(C.set(f.categoryCode,(C.get(f.categoryCode)||0)+1),C),new Map),y=new Set;o.components.forEach((C,f)=>{const g=`${C.productCode}@${C.productVersion}`;y.has(g)&&a.push({path:`merchandise.components[${f}]`,message:`duplicate component ${g}; use quantityPerUnit instead`}),y.add(g);const O=m.get(C.productCode)||[];O.length===0?a.push({path:`merchandise.components[${f}].productCode`,message:`Product ${C.productCode} is missing`}):O.length>1?a.push({path:`merchandise.components[${f}].productCode`,message:`Product ${C.productCode} is ambiguous`}):O[0].version!==C.productVersion?a.push({path:`merchandise.components[${f}].productVersion`,message:`expected Product version ${C.productVersion} but received ${O[0].version}`}):O[0].categoryCodes.forEach(V=>{const l=h.get(V)||0;l!==1&&a.push({path:`products.${C.productCode}.categoryCodes`,message:l===0?`Category ${V} is missing`:`Category ${V} is ambiguous`})})}),_n({merchandise:o,variants:c,variantSelections:u},a);const T=new Set(o.components.map(C=>C.productCode));return p.forEach((C,f)=>{T.has(C.productCode)||a.push({path:`requirementInputs[${f}].productCode`,message:`Product ${C.productCode} is not a Merchandise component`})}),v({passed:a.length===0,...a.length===0?{}:{code:P.DEFINITION_INVALID},message:a.length===0?"Acquisition definitions are consistent":"Acquisition definitions are inconsistent",details:{issues:a,requirementInputs:p,variantSelections:u}})}function Mn({acquisitionSource:n,categories:o,countryCode:e,countryRank:t,currency:r,eligibilityFacts:i=[],eventRegistrationCode:c,existingItems:d=[],instant:a,inventoryFacts:u=[],merchandise:p,priceSchedule:m,products:h,publishedRules:y,quantity:T=1,requirementInputs:C=[],requirementValues:f={},salesPeriods:g=[],variants:O=[],variantSelections:V=[],recipientFacts:l}){const R=(l==null?void 0:l.eligibilityFacts)||i,N=(l==null?void 0:l.existingWalletItems)||(l==null?void 0:l.existingItems)||d,ie=(l==null?void 0:l.projectedItems)||[],F=(l==null?void 0:l.eventRegistrationCode)||c,Ee=Nt({categories:o,merchandise:p,priceSchedule:m,products:h,quantity:T,requirementInputs:C,variants:O,variantSelections:V}),J=[],Ve=(l==null?void 0:l.productDefinitions)||h,_t=tt({items:N,path:"recipientFacts.existingWalletItems",productDefinitions:Ve},J),Ue=On({acquisitionSnapshots:(l==null?void 0:l.acquisitionSnapshots)||[],items:_t,path:"recipientFacts.existingWalletItems"},J),Mt=tt({items:ie,path:"recipientFacts.projectedItems",productDefinitions:Ve},J),qt=[...Ee.details.issues,...J],W=J.length===0?Ee:v({passed:!1,code:P.DEFINITION_INVALID,message:"Acquisition definitions are inconsistent",details:{...Ee.details,issues:qt}}),j=mt({categories:o,products:h,merchandise:p,acquisitionSource:n,publishedRules:y}),Z=W.passed?gt({merchandise:p,products:h,quantity:T}):[],fe=W.details.variantSelections,$e=W.details.requirementInputs,we=yt({rules:j.rules,eligibilityFacts:R,eventRegistrationCode:F,candidateItems:Z}),ye=It({rules:j.rules,candidateItems:Z,requirementInputs:$e,requirementValues:f,variantSelections:fe}),je=[...Mt,...Dn(Z,ye.plans)],Re=ft({rules:j.rules,existingItems:Ue,candidateItems:je}),xe=Rt({rules:j.rules,existingItems:Ue,candidateItems:je}),ze=ht({priceSchedule:m,salesPeriods:g,currency:r,countryCode:e,countryRank:t,acquisitionSource:n,instant:a}),Qe=Tt({rules:j.rules,candidateItems:Z,inventoryFacts:u,variantSelections:fe}),Lt=Re.decisions.filter(Y=>Y.details.limitType===K.ORDER).every(Y=>Y.passed),vt=Re.decisions.filter(Y=>Y.details.limitType!==K.ORDER).every(Y=>Y.passed),Ye=W.passed&&j.passed&&Lt&&ze.passed&&Qe.passed,Be=vt,Fe=W.passed&&j.passed&&we.passed&&Be&&xe.passed,We=Ye&&Fe;return L({passed:We,canPurchase:Ye,canAcquire:Fe,canHold:Be,itemValid:We&&ye.itemValid,candidateItems:Z,requirementInputs:$e,variantSelections:fe,effectiveRules:j,evaluations:{definitions:W,eligibility:we,quantity:Re,prerequisites:xe,requirements:ye,price:ze,inventory:Qe}})}function qn({id:n,evaluated:o,preview:e,context:t}){if(!e.passed)throw new Error("Cannot snapshot a failed acquisition preview");const r=typeof t.merchandise.toObject=="function"?t.merchandise.toObject():A(t.merchandise),i=t.products.map(c=>typeof c.toObject=="function"?c.toObject():A(c));return new st({id:n,contractVersion:2,eventRegistrationCode:t.eventRegistrationCode,purchaserEventRegistrationCode:t.purchaserEventRegistrationCode||t.eventRegistrationCode,payerEventRegistrationCode:t.payerEventRegistrationCode||t.eventRegistrationCode,acquisitionSource:t.acquisitionSource,merchandise:r,quantity:t.quantity,products:i,priceScheduleRef:{priceScheduleCode:t.priceSchedule.priceScheduleCode,priceScheduleVersion:t.priceSchedule.version},matchedPriceRow:e.evaluations.price.details.matchedPriceRow,priceEvaluationContext:{acquisitionSource:t.acquisitionSource,countryCode:e.evaluations.price.details.countryCode,countryRank:e.evaluations.price.details.countryRank,currency:e.evaluations.price.details.matchedPriceRow.currency,instant:t.instant},effectiveRules:e.effectiveRules,eligibilityDecisions:e.evaluations.eligibility.decisions,requirementPlans:e.evaluations.requirements.plans,inventoryDecisions:e.evaluations.inventory.decisions,variantSelections:e.variantSelections,evaluated:o})}function Ln({acquisitionSnapshot:n,walletItemIdFactory:o}){const e=[];return n.merchandise.components.forEach((t,r)=>{const i=n.quantity*t.quantityPerUnit;for(let c=0;c<i;c+=1){const d=n.requirementPlans.filter(p=>p.componentIndex===r&&p.unitIndex===c),a=n.variantSelections.find(p=>p.productCode===t.productCode),u=a==null?void 0:a.selections[c];e.push({walletItemCode:o({component:t,index:c,acquisitionSnapshot:n}),eventRegistrationCode:n.eventRegistrationCode,productCode:t.productCode,productVersion:t.productVersion,acquisitionCode:n.id,quantity:1,variantCode:(u==null?void 0:u.variantCode)||null,variantVersion:(u==null?void 0:u.variantVersion)||null,state:d.every(p=>p.complete)?b.VALID:b.PENDING_REQUIREMENT,requirementPlans:d.map(p=>({...p,unitIndex:0}))})}}),L(e)}function vn({now:n=Date.now(),requirementCode:o,values:e,walletItem:t}){const r=Dt(t),i=St(e,"values"),c=bt(o,"requirementCode"),d=r.requirementPlans.findIndex(y=>{var T;return((T=y.requirement)==null?void 0:T.requirementCode)===c});if(d<0)throw X("WALLET_ITEM_REQUIREMENT_NOT_FOUND","The Wallet Item Requirement was not found.");const a=r.requirementPlans[d];At({now:n,plan:a});const u=a.requirement.fields||[],p=new Set(u.map(y=>y.fieldCode)),m=Object.keys(i).find(y=>!p.has(y));if(m)throw X("WALLET_ITEM_REQUIREMENT_FIELD_UNKNOWN",`Requirement field "${m}" is not defined.`);const h=u.map(y=>y.fieldCode).filter(y=>!Pt(i[y]));return r.requirementPlans[d]={...a,complete:h.length===0,missingFields:h,values:structuredClone(i)},r.state=Ot(r.requirementPlans),new re(r).toObject()}function Vn({now:n=Date.now(),variant:o,walletItem:e}){const t=Dt(e),r=St(o,"variant"),i=bt(r.variantCode,"variant.variantCode"),c=Number(r.version);if(!Number.isSafeInteger(c)||c<=0)throw new TypeError("variant.version must be a positive integer.");if(r.productCode!==t.productCode||r.productVersion!==t.productVersion)throw X("WALLET_ITEM_VARIANT_PRODUCT_MISMATCH","The selected Variant does not belong to this Wallet Item Product version.");const d=t.requirementPlans.findIndex(m=>{var h;return(((h=m.requirement)==null?void 0:h.fields)||[]).some(y=>y.inputType===k.VARIANT)});if(d<0)throw X("WALLET_ITEM_VARIANT_REQUIREMENT_NOT_FOUND","The Wallet Item does not have a Variant Requirement.");const a=t.requirementPlans[d];At({now:n,plan:a});const u={...a.values||{}};a.requirement.fields.filter(m=>m.inputType===k.VARIANT).forEach(m=>{u[m.fieldCode]=r[m.optionValueKey]});const p=a.requirement.fields.map(m=>m.fieldCode).filter(m=>!Pt(u[m]));return t.requirementPlans[d]={...a,complete:p.length===0,missingFields:p,values:u},t.state=Ot(t.requirementPlans),t.variantCode=i,t.variantVersion=c,new re(t).toObject()}function At({now:n,plan:o}){if(o.modificationMode===w.LOCK_AFTER_COMPLETE&&o.complete)throw X("WALLET_ITEM_REQUIREMENT_LOCKED","The completed Wallet Item Requirement is locked.");if(o.modificationMode===w.UNTIL_DEADLINE&&(!o.modificationDeadline||Number(n)>=Date.parse(o.modificationDeadline)))throw X("WALLET_ITEM_REQUIREMENT_DEADLINE_PASSED","The Wallet Item Requirement modification deadline has passed.")}function Dt(n){return n instanceof re?n.toObject():new re(n).toObject()}function Ot(n){return n.every(o=>o.complete)?b.VALID:b.PENDING_REQUIREMENT}function St(n,o){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError(`${o} must be an object.`);return structuredClone(n)}function bt(n,o){if(typeof n!="string"||n.trim().length===0)throw new TypeError(`${o} is required.`);return n.trim()}function Pt(n){return!(n===null||typeof n>"u"||typeof n=="string"&&n.trim().length===0)}function X(n,o){return Object.assign(new Error(o),{code:n})}const Un=2;exports.ACQUISITION_SOURCES=ce;exports.Acquisition=jt;exports.AcquisitionSnapshot=st;exports.Category=zt;exports.CommercialLifecycle=ge;exports.Currency=Qt;exports.DECISION_CODES=P;exports.DEFAULT_ACTIVE_ITEM_STATES=Et;exports.ELIGIBILITY_STATES=x;exports.EligibilityFact=Yt;exports.INVENTORY_LEDGER_ACTIONS=at;exports.INVENTORY_MODES=ue;exports.InventoryBalance=Bt;exports.InventoryLedgerEntry=Ft;exports.Invoice=Wt;exports.InvoiceRevision=Gt;exports.MATCH_MODES=le;exports.Merchandise=kt;exports.MerchandiseComponent=Ne;exports.ORDER_STATES=nt;exports.Order=Ht;exports.OrderLine=Ae;exports.PAYMENT_ATTEMPT_STATES=rt;exports.PREREQUISITE_EVIDENCE_SOURCES=G;exports.PaymentAttempt=Kt;exports.PaymentMethodConfigurationSnapshot=Se;exports.PriceEvaluationContext=Ie;exports.PriceMatchCriteria=be;exports.PriceRow=_e;exports.PriceSchedule=Xt;exports.PriceScheduleRef=he;exports.Product=Jt;exports.PublishedRule=an;exports.PublishedRuleRef=un;exports.QUANTITY_LIMIT_TYPES=K;exports.REQUIREMENT_COMPLETION_STATES=se;exports.REQUIREMENT_COMPLETION_TIMINGS=Ce;exports.REQUIREMENT_INPUT_TYPES=k;exports.REQUIREMENT_MODIFICATION_MODES=w;exports.REQUIREMENT_MODIFICATION_STATES=ee;exports.RESERVATION_STATES=ot;exports.RULE_SOURCES=q;exports.RULE_TYPES=_;exports.Receipt=ln;exports.RefundPolicy=pn;exports.RefundPolicyRef=Me;exports.RequirementDefinition=ne;exports.RequirementFieldDefinition=Te;exports.RequirementPlan=oe;exports.Reservation=De;exports.STORE_MODEL_V2_CONTRACT_VERSION=Un;exports.SalesPeriod=mn;exports.SalesPeriodRef=Pe;exports.Settlement=Cn;exports.StoreContractValidationError=H;exports.StoreEntity=S;exports.TARGET_TYPES=M;exports.TERMINAL_ITEM_STATES=Ct;exports.Variant=En;exports.VariantRef=qe;exports.WALLET_ITEM_STATES=b;exports.WalletItem=re;exports.applyWalletItemRequirementValues=vn;exports.applyWalletItemVariantSelection=Vn;exports.calculatePaymentDeadline=Oe;exports.canStartPaymentAttempt=ut;exports.collectEffectiveRules=mt;exports.createAcquisitionSnapshot=qn;exports.evaluateAcquisitionPreview=Mn;exports.evaluateEligibilityRules=yt;exports.evaluateInventoryRules=Tt;exports.evaluatePrerequisiteRules=Rt;exports.evaluatePriceMatchCriteria=Le;exports.evaluateQuantityRules=ft;exports.evaluateRequirementConfigurationState=Tn;exports.expandCandidateItems=gt;exports.planItemRequirements=It;exports.projectWalletItems=Ln;exports.resolvePrice=ht;exports.validateAcquisitionDefinitions=Nt;
2
2
  //# sourceMappingURL=q-store-model-v2.cjs.map