values.ts (2657B)
1 // Strict authored values from public Radroots Lib189 Food Availability v1. 2 // Tolerant inbound normalization belongs to the separate reader adapter. 3 export const foodUnits = Object.freeze([ 4 'g', 5 'kg', 6 'lb', 7 'oz', 8 'each', 9 'dozen', 10 'bunch', 11 'punnet', 12 'bag', 13 'basket' 14 ] as const); 15 export type FoodUnit = (typeof foodUnits)[number]; 16 17 declare const decimalValue: unique symbol; 18 export type CanonicalFoodAmount = string & { 19 readonly [decimalValue]: true; 20 }; 21 declare const currencyValue: unique symbol; 22 export type FoodCurrency = string & { readonly [currencyValue]: true }; 23 24 export function canonicalFoodAmount( 25 value: unknown 26 ): CanonicalFoodAmount | undefined { 27 // Twenty-eight ASCII digits and at most one decimal point. Check length 28 // before regex work; keep the exact string rather than convert to Number. 29 if ( 30 typeof value !== 'string' || 31 value.length === 0 || 32 value.length > 29 || 33 !/^(?:0|[1-9][0-9]*)(?:\.[0-9]*[1-9])?$/u.test(value) 34 ) 35 return undefined; 36 const digits = value.length - (value.includes('.') ? 1 : 0); 37 if (digits > 28) return undefined; 38 return value as CanonicalFoodAmount; 39 } 40 41 export function foodCurrency(value: unknown): FoodCurrency | undefined { 42 if ( 43 typeof value !== 'string' || 44 value.length !== 3 || 45 !/^[A-Z]{3}$/u.test(value) 46 ) 47 return undefined; 48 return value as FoodCurrency; 49 } 50 51 export function foodUnit(value: unknown): FoodUnit | undefined { 52 if ( 53 typeof value !== 'string' || 54 value.length > 6 || 55 !foodUnits.includes(value as FoodUnit) 56 ) 57 return undefined; 58 return value as FoodUnit; 59 } 60 61 export type FoodPrice = Readonly<{ 62 amount: CanonicalFoodAmount; 63 currency: FoodCurrency; 64 unit: FoodUnit; 65 }>; 66 export function foodPrice( 67 amountValue: unknown, 68 currencyInput: unknown, 69 unitInput: unknown 70 ): FoodPrice | undefined { 71 const amount = canonicalFoodAmount(amountValue); 72 const currency = foodCurrency(currencyInput); 73 const unit = foodUnit(unitInput); 74 if (amount === undefined || currency === undefined || unit === undefined) 75 return undefined; 76 return { amount, currency, unit }; 77 } 78 79 export type FoodQuantity = Readonly<{ 80 amount: CanonicalFoodAmount; 81 unit: FoodUnit; 82 }>; 83 export function foodQuantity( 84 amountValue: unknown, 85 unitInput: unknown 86 ): FoodQuantity | undefined { 87 const amount = canonicalFoodAmount(amountValue); 88 const unit = foodUnit(unitInput); 89 // Canonical zero has exactly one spelling. Missing/invalid data remains 90 // absent; it is never converted into zero inventory. 91 if (amount === undefined || amount === '0' || unit === undefined) 92 return undefined; 93 return { amount, unit }; 94 }