@mark1russell7/market 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/plan.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plan.js","names":[],"sources":["../src/order.ts","../src/plan.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport { greedy, type Goal, type GreedyStop, type Selection } from \"@mark1russell7/strategy-search\";\nimport { offersOfPart, priceOf, type Observation, type PartWant } from \"./offers.ts\";\nimport type { Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy order: the purchases that give the most value for each unit of money under a budget.\n * The candidates come from the offers. The order is a budgeted greedy choice of strategy-search, in stages, for\n * example a first target and then a second target. The module knows no topic: the caller gives the value of a choice.\n */\n\n/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */\nexport interface ProductWant {\n readonly product: string;\n readonly want: PartWant;\n /** The largest count of units to buy. The default is 1. */\n readonly max?: number | undefined;\n}\n\n/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */\nexport interface BuyCandidate {\n readonly product: string;\n /** The cost of one unit with its shipping, in the currency of the order. */\n readonly price: number;\n readonly max: number;\n /** The `id` of the offer of the price. */\n readonly quote: string;\n}\n\n/** The candidates of a buy order, and the products that have no usable offer. */\nexport interface BuyCandidates {\n readonly currency: string;\n readonly candidates: readonly BuyCandidate[];\n readonly unpriced: readonly { readonly product: string; readonly why: string }[];\n}\n\n/** The options of the candidates: the currency and the conditions that the buyer accepts. */\nexport interface CandidateOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n}\n\n/**\n * This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its\n * shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an\n * upper limit of the cost of more units.\n *\n * @param wants - The products, in the order of the result\n * @param observations - The observations of the offers\n * @param options - The currency and the conditions\n * @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`\n */\nexport function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates {\n const seen = new Set<string>();\n const candidates: BuyCandidate[] = [];\n const unpriced: { product: string; why: string }[] = [];\n for (const want of wants) {\n if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);\n seen.add(want.product);\n const max = want.max ?? 1;\n if (!(Number.isSafeInteger(max) && max >= 0)) throw new RangeError(`The max of the product ${want.product} is ${String(max)}. It must be a whole number of 0 or more.`);\n const priced = priceOf(offersOfPart(observations, want.want), 1, options);\n if (priced.ok) candidates.push({ product: want.product, price: valueIn(priced.cost, options.currency), max, quote: priced.offerId });\n else unpriced.push({ product: want.product, why: priced.why });\n }\n return { currency: options.currency, candidates, unpriced };\n}\n\n/** One stage of a buy order: its name and the value of a choice, the most important number first. */\nexport interface OrderStage {\n readonly name: string;\n /** The value of the units of each product. It is a pure function. */\n readonly value: (units: Selection) => readonly number[];\n}\n\n/** The options of a buy order. */\nexport interface OrderOptions {\n /** The money of the order, in the currency of the candidates. */\n readonly budget: number;\n /** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */\n readonly stages: readonly OrderStage[];\n /** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */\n readonly goal?: Goal | undefined;\n /** The units that the buyer has before the order. Their cost is not in the budget. */\n readonly start?: Selection | undefined;\n /** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */\n readonly lazy?: boolean | undefined;\n}\n\n/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */\nexport interface OrderBuy {\n readonly stage: string;\n readonly product: string;\n readonly quote: string;\n readonly cost: number;\n readonly gain: readonly number[];\n}\n\n/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */\nexport interface OrderStageResult {\n readonly name: string;\n readonly method: \"greedy\" | \"single\";\n readonly before: readonly number[];\n readonly after: readonly number[];\n readonly spent: number;\n readonly stop: GreedyStop;\n readonly evaluations: number;\n}\n\n/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */\nexport interface BuyOrder {\n readonly budget: number;\n readonly spent: number;\n readonly buys: readonly OrderBuy[];\n /** The units of each product after the order, with the units of `start`. */\n readonly units: Selection;\n readonly stages: readonly OrderStageResult[];\n}\n\n/**\n * This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the\n * product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.\n *\n * - A stage starts from the units of the stage before it, and it spends only the money that is left.\n * - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: \"single\"`).\n *\n * @param candidates - The candidates, from `buyCandidates`\n * @param options - The budget, the stages, the goal and the start\n * @returns The buy order\n * @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length\n */\nexport function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder {\n if (options.stages.length === 0) throw new RangeError(\"The order has no stage.\");\n if (!(Number.isFinite(options.budget) && options.budget >= 0)) throw new RangeError(`The budget is ${String(options.budget)}. It must be a finite number of 0 or more.`);\n const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));\n const items = candidates.map((candidate) => ({ id: candidate.product, cost: candidate.price, max: candidate.max }));\n const start: Selection = options.start ?? {};\n let units: Selection = start;\n let left = options.budget;\n let spent = 0;\n const buys: OrderBuy[] = [];\n const stages: OrderStageResult[] = [];\n for (const stage of options.stages) {\n // The max of each item is what is left after the stages before.\n const open = items.map((item) => ({ ...item, max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0)) }));\n const run = greedy({\n items: open,\n budget: Math.max(0, left),\n value: stage.value,\n start: units,\n ...(options.goal === undefined ? {} : { goal: options.goal }),\n ...(options.lazy === undefined ? {} : { lazy: options.lazy }),\n });\n for (const pick of run.picks) buys.push({ stage: stage.name, product: pick.id, quote: byProduct.get(pick.id)?.quote ?? \"\", cost: pick.cost, gain: pick.gain });\n units = run.selection;\n left -= run.spent;\n spent += run.spent;\n stages.push({ name: stage.name, method: run.method, before: run.before, after: run.after, spent: run.spent, stop: run.stop, evaluations: run.evaluations });\n }\n return { budget: options.budget, spent, buys, units, stages };\n}\n","import { compare, sum, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { evolve, frontOf, sweep, type EvaluationRow, type Measure, type Objective, type SweepCounts } from \"@mark1russell7/strategy-search\";\nimport { spaceSize, STRATEGY_SPACE_SCHEMA, type SpaceParam, type StrategyConfig, type StrategySpace } from \"@mark1russell7/strategy-space\";\nimport { compile, isFieldName, parse, space, type AnyDomain, type Program } from \"@mark1russell7/vex\";\nimport { BoolDomain, NumDomain, TextDomain } from \"@mark1russell7/vex-domains\";\nimport { z } from \"zod\";\nimport { offersOfPart, priceOf, type Observation, type PartWant, type Priced } from \"./offers.ts\";\nimport { CONDITIONS, textSchema, type Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy plan. A need names the slots of a purchase, the parts that can fill each slot, and\n * the measures and the rules of a basket as Vex programs. The plan searches the baskets with strategy-search, and it\n * gives the front of the price against the measures. The module knows no part class: the facts of each part and the\n * programs come from the need. Each function of this module is a calculation with no effect.\n */\n\n/** The format name of a need record. */\nexport const NEED_FORMAT = \"buy-need/1\";\n\n/** The format name of a plan record. */\nexport const PLAN_FORMAT = \"buy-plan/1\";\n\n/** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */\nexport const NEED_KEY = \"need\";\n\n/** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */\nexport const SLOT_FIELDS = [\"slot\", \"part\", \"count\", \"cost\"] as const;\n\n/** The largest count of evaluations of a plan, when the options do not give a count. */\nexport const PLAN_EVALUATIONS = 2000;\n\n/** The domains of the programs of a need: numbers, booleans and texts. */\nconst DOMAINS: readonly AnyDomain[] = [NumDomain, BoolDomain, TextDomain];\n\n/** A fact of a part, or an input of a need: a number, a text or a boolean. */\nexport type Fact = number | string | boolean;\n\n/** One part that can fill a slot: its key in the slot, the part that the offers must match, and its facts. */\nexport interface NeedPart {\n readonly key: string;\n readonly want: PartWant;\n /** The facts of the part that the programs read, for example its watts. */\n readonly facts?: Readonly<Record<string, Fact>> | undefined;\n}\n\n/** The count of units of a slot. With `min` 0, a basket can leave the slot empty. */\nexport interface SlotCount {\n readonly min: number;\n readonly max: number;\n}\n\n/** One slot of a need: its name, the parts that can fill it, and the count of its units. The default count is 1. */\nexport interface NeedSlot {\n readonly name: string;\n readonly parts: readonly NeedPart[];\n readonly count?: SlotCount | undefined;\n}\n\n/**\n * One measure of a basket: a Vex program that gives a number. With `goal`, the measure is an objective of the search.\n * A value below `min` or above `max` breaks the basket.\n */\nexport interface NeedMeasure {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n readonly goal?: \"min\" | \"max\" | undefined;\n /** The unit of the values, as text for a reader. */\n readonly unit?: string | undefined;\n readonly min?: number | undefined;\n readonly max?: number | undefined;\n}\n\n/** One rule of a basket: a Vex program that gives `true` when the basket keeps the rule. */\nexport interface NeedRule {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n}\n\n/** This record is a need: the currency and the conditions of the offers, the inputs, the slots, the measures and the rules. */\nexport interface BuyNeed {\n readonly format: typeof NEED_FORMAT;\n readonly id: string;\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n /** The inputs that the programs read at the key `need`, for example the load in watts. */\n readonly inputs?: Readonly<Record<string, Fact>> | undefined;\n readonly slots: readonly NeedSlot[];\n readonly measures?: readonly NeedMeasure[] | undefined;\n readonly rules?: readonly NeedRule[] | undefined;\n}\n\nconst factSchema: z.ZodType<Fact> = z.union([z.number().refine(Number.isFinite, \"The number is not finite.\"), z.string(), z.boolean()]);\nconst factsSchema: z.ZodType<Readonly<Record<string, Fact>>> = z.record(textSchema, factSchema);\nconst wantSchema: z.ZodType<PartWant> = z.strictObject({ brands: z.array(textSchema).min(1), partNumbers: z.array(textSchema).min(1) });\nconst wholeSchema = z.number().int().nonnegative();\n\n/** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */\nexport const buyNeedSchema: z.ZodType<BuyNeed> = z.strictObject({\n format: z.literal(NEED_FORMAT),\n id: textSchema,\n currency: textSchema,\n conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),\n inputs: factsSchema.optional(),\n slots: z\n .array(\n z.strictObject({\n name: textSchema,\n parts: z.array(z.strictObject({ key: textSchema, want: wantSchema, facts: factsSchema.optional() })).min(1),\n count: z.strictObject({ min: wholeSchema, max: wholeSchema }).optional(),\n }),\n )\n .min(1),\n measures: z\n .array(\n z.strictObject({\n name: textSchema,\n program: z.unknown(),\n goal: z.enum([\"min\", \"max\"]).optional(),\n unit: textSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n )\n .optional(),\n rules: z.array(z.strictObject({ name: textSchema, program: z.unknown() })).optional(),\n});\n\n/** This function gives the count of a slot, with the default 1 to 1. */\nfunction countOf(slot: NeedSlot): SlotCount {\n return slot.count ?? { min: 1, max: 1 };\n}\n\n/** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */\nfunction readProgram(program: unknown): { readonly ok: true; readonly program: Program } | { readonly ok: false; readonly why: string } {\n const text = program === undefined ? undefined : JSON.stringify(program);\n if (text === undefined) return { ok: false, why: \"The program is missing.\" };\n const read = parse(text, DOMAINS);\n return read.ok ? { ok: true, program: compile(read.value, { domains: DOMAINS }) } : { ok: false, why: read.error.message };\n}\n\n/** This function compiles a program that `needProblems` accepts. */\nfunction programOf(program: unknown): Program {\n const read = readProgram(program);\n if (!read.ok) throw new RangeError(read.why);\n return read.program;\n}\n\n/**\n * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad\n * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field\n * of a slot is a problem. A program that is not valid is a problem.\n */\nexport function needProblems(need: BuyNeed): string[] {\n const problems: string[] = [];\n const twice = (names: readonly string[], what: string): void => {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);\n seen.add(name);\n }\n };\n twice(\n need.slots.map((slot) => slot.name),\n \"slots\",\n );\n for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);\n for (const slot of need.slots) {\n if (slot.name === NEED_KEY) problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);\n else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);\n twice(\n slot.parts.map((part) => part.key),\n `parts of the slot ${slot.name}`,\n );\n const { min, max } = countOf(slot);\n if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max)\n problems.push(`The count of the slot ${slot.name} is ${String(min)} to ${String(max)}. It must be whole numbers, with a maximum of 1 or more and not below the minimum.`);\n for (const part of slot.parts) {\n for (const name of Object.keys(part.facts ?? {})) {\n if ((SLOT_FIELDS as readonly string[]).includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);\n else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);\n }\n }\n }\n const measures = need.measures ?? [];\n const rules = need.rules ?? [];\n twice(\n measures.map((measure) => measure.name),\n \"measures\",\n );\n twice(\n rules.map((rule) => rule.name),\n \"rules\",\n );\n for (const measure of measures) {\n if (measure.name === \"price\") problems.push(\"A measure has the name price, which is the objective of the cost.\");\n if (measure.min !== undefined && measure.max !== undefined && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);\n const read = readProgram(measure.program);\n if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);\n }\n for (const rule of rules) {\n const read = readProgram(rule.program);\n if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);\n }\n return problems;\n}\n\n/** This record is one item of a basket: the slot, the part, the count, the offer to buy and the cost with the shipping. */\nexport interface BuyItem {\n readonly slot: string;\n readonly part: string;\n readonly count: number;\n readonly offerId: string;\n readonly cost: Quantity;\n}\n\n/** This record is one basket of the front: its config id, its price, the value of each measure and its items. */\nexport interface BuyChoice {\n readonly config: string;\n /** The sum of the cost of each item. Each item is one order, with its own shipping. */\n readonly price: Quantity;\n readonly values: Readonly<Record<string, number>>;\n readonly items: readonly BuyItem[];\n}\n\n/** This record counts the baskets that break one constraint, with the reason of the first such basket. */\nexport interface BuyBreak {\n /** The constraint: `price:<slot>`, `measure:<name>`, `limit:<name>` or `rule:<name>`. */\n readonly name: string;\n readonly count: number;\n readonly why: string;\n}\n\n/** This record is a part that no basket can have, because no offer of the part is usable at a count of its slot. */\nexport interface UnpricedPart {\n readonly slot: string;\n readonly part: string;\n readonly why: string;\n}\n\n/** This record is a buy plan: the method of the search, its counts, the front of the baskets and the reasons of the breaks. */\nexport interface BuyPlan {\n readonly format: typeof PLAN_FORMAT;\n /** The id of the need. */\n readonly need: string;\n readonly currency: string;\n /** `grid` evaluates each basket. `evolve` is a genetic search. `none` tells that a slot that must have a part has no part with an offer. */\n readonly method: \"grid\" | \"evolve\" | \"none\";\n /** The seed of a genetic search, or null. */\n readonly seed: number | null;\n /** The id of the run of strategy-search, or null for `none`. */\n readonly run: string | null;\n readonly objectives: readonly Objective[];\n readonly counts: SweepCounts;\n /** The baskets on the Pareto front, from the lowest price. Equal prices go in the order of the config id. */\n readonly front: readonly BuyChoice[];\n /** The constraints that the evaluated baskets break, in the order of their names. */\n readonly breaks: readonly BuyBreak[];\n /** The parts with no usable offer, in the order of the slots and of their parts. */\n readonly unpriced: readonly UnpricedPart[];\n}\n\nexport { buyCandidates, orderBuys, type BuyCandidate, type BuyCandidates, type BuyOrder, type CandidateOptions, type OrderBuy, type OrderOptions, type OrderStage, type OrderStageResult, type ProductWant } from \"./order.ts\";\n\n/** These options change the search of a plan. */\nexport interface PlanOptions {\n /** The largest count of evaluations. A space with no more baskets gets a grid of each basket. The default is `PLAN_EVALUATIONS`. */\n readonly evaluations?: number | undefined;\n /** The seed of a genetic search. The default is the id of the need. */\n readonly seed?: number | string | undefined;\n /** The count of the baskets of a generation of a genetic search. The default is the default of strategy-search. */\n readonly population?: number | undefined;\n}\n\n\n/** The breaks, the values and the items of one basket. */\ninterface Assessed {\n readonly breaks: readonly { readonly name: string; readonly why: string }[];\n readonly values: Readonly<Record<string, number>>;\n readonly price: Quantity | null;\n readonly items: readonly BuyItem[];\n}\n\n\n/**\n * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy\n * space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum\n * of the cost of each item.\n *\n * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has\n * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part\n * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.\n *\n * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.\n *\n * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.\n * The function also throws a RangeError when strategy-search refuses the options.\n */\nexport function planBuys(need: BuyNeed, observations: readonly Observation[], options: PlanOptions = {}): BuyPlan {\n const shape = buyNeedSchema.safeParse(need);\n if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\" \")}`);\n const problems = needProblems(need);\n if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(\" \")}`);\n const evaluations = options.evaluations ?? PLAN_EVALUATIONS;\n if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);\n\n const measures = (need.measures ?? []).map((measure) => ({ measure, program: programOf(measure.program) }));\n const rules = (need.rules ?? []).map((rule) => ({ rule, program: programOf(rule.program) }));\n const objectives: Objective[] = [\n { name: \"price\", goal: \"min\", unit: need.currency },\n ...measures.flatMap(({ measure }) => (measure.goal === undefined ? [] : [measure.unit === undefined ? { name: measure.name, goal: measure.goal } : { name: measure.name, goal: measure.goal, unit: measure.unit }])),\n ];\n\n // The price of each count of each part, once. A part with no usable offer at any count is not an option.\n const prices = new Map<string, Map<number, Priced>>();\n const unpriced: UnpricedPart[] = [];\n const stages: StrategySpace[\"stages\"][number][] = [];\n let blocked = false;\n for (const slot of need.slots) {\n const { min, max } = countOf(slot);\n const low = Math.max(1, min);\n const params: SpaceParam[] = max > low ? [{ name: \"count\", kind: \"int\", min: low, max, default: low }] : [];\n const usable: string[] = [];\n for (const part of slot.parts) {\n const offers = offersOfPart(observations, part.want);\n const byCount = new Map<number, Priced>();\n for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));\n prices.set(`${slot.name}\\u0000${part.key}`, byCount);\n const first = byCount.get(low);\n if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);\n else unpriced.push({ slot: slot.name, part: part.key, why: first === undefined || first.ok ? \"No offer is usable.\" : first.why });\n }\n if (usable.length > 0) stages.push({ name: slot.name, options: usable.map((id) => ({ id, params })), ...(min === 0 ? { optional: true } : {}) });\n else if (min > 0) blocked = true;\n }\n const none: BuyPlan = { format: PLAN_FORMAT, need: need.id, currency: need.currency, method: \"none\", seed: null, run: null, objectives, counts: { feasible: 0, breaks: 0, unread: 0, front: 0 }, front: [], breaks: [], unpriced };\n if (blocked || stages.length === 0) return none;\n\n const strategySpace: StrategySpace = { schema: STRATEGY_SPACE_SCHEMA, engine: \"buy-plan\", version: \"1\", stages };\n\n const assess = (config: StrategyConfig): Assessed => {\n const breaks: { name: string; why: string }[] = [];\n const items: BuyItem[] = [];\n const records: Record<string, Readonly<Record<string, Fact>>> = { [NEED_KEY]: need.inputs ?? {} };\n for (const slot of need.slots) {\n const choice = config.stages[slot.name] ?? null;\n if (choice === null) {\n records[slot.name] = { slot: slot.name, count: 0, cost: 0 };\n continue;\n }\n const part = slot.parts.find((each) => each.key === choice.option) as NeedPart;\n const count = Number(choice.params?.[\"count\"] ?? Math.max(1, countOf(slot).min));\n const priced = prices.get(`${slot.name}\\u0000${part.key}`)?.get(count) ?? { ok: false, why: `The count ${String(count)} is not a count of the slot.` };\n if (!priced.ok) {\n breaks.push({ name: `price:${slot.name}`, why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}` });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: 0 };\n continue;\n }\n items.push({ slot: slot.name, part: part.key, count, offerId: priced.offerId, cost: priced.cost });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: valueIn(priced.cost, need.currency) };\n }\n const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);\n const values: Record<string, number> = price === null ? {} : { price: valueIn(price, need.currency) };\n const basket = space.record(records);\n for (const { measure, program } of measures) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `measure:${measure.name}`, why: result.error.message });\n else if (typeof result.value !== \"number\" || !Number.isFinite(result.value)) breaks.push({ name: `measure:${measure.name}`, why: `The value ${String(result.value)} is not a finite number.` });\n else {\n values[measure.name] = result.value;\n if (measure.min !== undefined && result.value < measure.min) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.` });\n if (measure.max !== undefined && result.value > measure.max) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.` });\n }\n }\n for (const { rule, program } of rules) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `rule:${rule.name}`, why: result.error.message });\n else if (result.value !== true) breaks.push({ name: `rule:${rule.name}`, why: result.value === false ? \"The basket breaks the rule.\" : `The value ${String(result.value)} is not a boolean.` });\n }\n return { breaks, values, price, items };\n };\n\n // The reason of the first basket that breaks each constraint.\n const firstWhy = new Map<string, string>();\n const evaluate = (config: StrategyConfig): Measure => {\n const assessed = assess(config);\n for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);\n return { breaks: [...new Set(assessed.breaks.map((each) => each.name))], values: assessed.values };\n };\n\n const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));\n const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);\n const evaluator = `buy-need:${need.id}`;\n const run = grid\n ? sweep(strategySpace, { objectives, evaluate, enumerate: { mode: \"grid\", levels, limit: evaluations }, evaluator })\n : evolve(strategySpace, {\n objectives,\n evaluate,\n seed: options.seed ?? need.id,\n evaluations,\n ...(options.population === undefined ? {} : { population: options.population }),\n evaluator,\n });\n\n const front = frontOf(run)\n .map(({ row, config }): BuyChoice => {\n const assessed = assess(config);\n const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== \"price\"));\n return { config: row.config, price: assessed.price as Quantity, values, items: assessed.items };\n })\n .sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));\n return {\n ...none,\n method: grid ? \"grid\" : \"evolve\",\n seed: run.seed,\n run: run.run,\n counts: run.counts,\n front,\n breaks: breaksOf(run.rows, firstWhy),\n unpriced,\n };\n}\n\n/** This function counts the rows that break each constraint, in the order of the names. */\nfunction breaksOf(rows: readonly EvaluationRow[], firstWhy: ReadonlyMap<string, string>): BuyBreak[] {\n const counts = new Map<string, number>();\n for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);\n return [...counts.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([name, count]) => ({ name, count, why: firstWhy.get(name) ?? \"\" }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,SAAgB,cAAc,OAA+B,cAAsC,SAA0C;CAC3I,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,aAA6B,CAAC;CACpC,MAAM,WAA+C,CAAC;CACtD,KAAK,MAAM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YAAY,OAAO,QAAQ,SAAS,MAAM,CAAC,CAAC,QAAQ,CAAC,UAAU,SAAS,OAAO,CAAC;EACtG,OAAO;GAAE,QAAQ,IAAI;GAAQ,OAAO,SAAS;GAAmB;GAAQ,OAAO,SAAS;EAAM;CAChG,CAAC,CAAC,CACD,MAAM,GAAG,MAAM,QAAQ,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,EAAE;CACvG,OAAO;EACL,GAAG;EACH,QAAQ,OAAO,SAAS;EACxB,MAAM,IAAI;EACV,KAAK,IAAI;EACT,QAAQ,IAAI;EACZ;EACA,QAAQ,SAAS,IAAI,MAAM,QAAQ;EACnC;CACF;AACF;;AAGA,SAAS,SAAS,MAAgC,UAAmD;CACnG,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,OAAO,MAAM,KAAK,MAAM,QAAQ,IAAI,QAAQ,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,KAAK,KAAK,CAAC;CACnG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,MAAM,YAAY;EAAE;EAAM;EAAO,KAAK,SAAS,IAAI,IAAI,KAAK;CAAG,EAAE;AAC5E"}
1
+ {"version":3,"file":"plan.js","names":[],"sources":["../src/order.ts","../src/plan.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport { greedy, type Goal, type GreedyStop, type Selection } from \"@mark1russell7/strategy-search\";\nimport { offersOfPart, priceOf, type Observation, type PartWant } from \"./offers.ts\";\nimport type { Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy order: the purchases that give the most value for each unit of money under a budget.\n * The candidates come from the offers. The order is a budgeted greedy choice of strategy-search, in stages, for\n * example a first target and then a second target. The module knows no topic: the caller gives the value of a choice.\n */\n\n/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */\nexport interface ProductWant {\n readonly product: string;\n readonly want: PartWant;\n /** The largest count of units to buy. The default is 1. */\n readonly max?: number | undefined;\n}\n\n/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */\nexport interface BuyCandidate {\n readonly product: string;\n /** The cost of one unit with its shipping, in the currency of the order. */\n readonly price: number;\n readonly max: number;\n /** The `id` of the offer of the price. */\n readonly quote: string;\n}\n\n/** The candidates of a buy order, and the products that have no usable offer. */\nexport interface BuyCandidates {\n readonly currency: string;\n readonly candidates: readonly BuyCandidate[];\n readonly unpriced: readonly { readonly product: string; readonly why: string }[];\n}\n\n/** The options of the candidates: the currency and the conditions that the buyer accepts. */\nexport interface CandidateOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n}\n\n/**\n * This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its\n * shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an\n * upper limit of the cost of more units.\n *\n * @param wants - The products, in the order of the result\n * @param observations - The observations of the offers\n * @param options - The currency and the conditions\n * @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`\n */\nexport function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates {\n const seen = new Set<string>();\n const candidates: BuyCandidate[] = [];\n const unpriced: { product: string; why: string }[] = [];\n for (const want of wants) {\n if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);\n seen.add(want.product);\n const max = want.max ?? 1;\n if (!(Number.isSafeInteger(max) && max >= 0)) throw new RangeError(`The max of the product ${want.product} is ${String(max)}. It must be a whole number of 0 or more.`);\n const priced = priceOf(offersOfPart(observations, want.want), 1, options);\n if (priced.ok) candidates.push({ product: want.product, price: valueIn(priced.cost, options.currency), max, quote: priced.offerId });\n else unpriced.push({ product: want.product, why: priced.why });\n }\n return { currency: options.currency, candidates, unpriced };\n}\n\n/** One stage of a buy order: its name and the value of a choice, the most important number first. */\nexport interface OrderStage {\n readonly name: string;\n /** The value of the units of each product. It is a pure function. */\n readonly value: (units: Selection) => readonly number[];\n}\n\n/** The options of a buy order. */\nexport interface OrderOptions {\n /** The money of the order, in the currency of the candidates. */\n readonly budget: number;\n /** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */\n readonly stages: readonly OrderStage[];\n /** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */\n readonly goal?: Goal | undefined;\n /** The units that the buyer has before the order. Their cost is not in the budget. */\n readonly start?: Selection | undefined;\n /** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */\n readonly lazy?: boolean | undefined;\n}\n\n/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */\nexport interface OrderBuy {\n readonly stage: string;\n readonly product: string;\n readonly quote: string;\n readonly cost: number;\n readonly gain: readonly number[];\n}\n\n/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */\nexport interface OrderStageResult {\n readonly name: string;\n readonly method: \"greedy\" | \"single\";\n readonly before: readonly number[];\n readonly after: readonly number[];\n readonly spent: number;\n readonly stop: GreedyStop;\n readonly evaluations: number;\n}\n\n/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */\nexport interface BuyOrder {\n readonly budget: number;\n readonly spent: number;\n readonly buys: readonly OrderBuy[];\n /** The units of each product after the order, with the units of `start`. */\n readonly units: Selection;\n readonly stages: readonly OrderStageResult[];\n}\n\n/**\n * This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the\n * product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.\n *\n * - A stage starts from the units of the stage before it, and it spends only the money that is left.\n * - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: \"single\"`).\n *\n * @param candidates - The candidates, from `buyCandidates`\n * @param options - The budget, the stages, the goal and the start\n * @returns The buy order\n * @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length\n */\nexport function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder {\n if (options.stages.length === 0) throw new RangeError(\"The order has no stage.\");\n if (!(Number.isFinite(options.budget) && options.budget >= 0)) throw new RangeError(`The budget is ${String(options.budget)}. It must be a finite number of 0 or more.`);\n const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));\n const items = candidates.map((candidate) => ({ id: candidate.product, cost: candidate.price, max: candidate.max }));\n const start: Selection = options.start ?? {};\n let units: Selection = start;\n let left = options.budget;\n let spent = 0;\n const buys: OrderBuy[] = [];\n const stages: OrderStageResult[] = [];\n for (const stage of options.stages) {\n // The max of each item is what is left after the stages before.\n const open = items.map((item) => ({ ...item, max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0)) }));\n const run = greedy({\n items: open,\n budget: Math.max(0, left),\n value: stage.value,\n start: units,\n ...(options.goal === undefined ? {} : { goal: options.goal }),\n ...(options.lazy === undefined ? {} : { lazy: options.lazy }),\n });\n for (const pick of run.picks) buys.push({ stage: stage.name, product: pick.id, quote: byProduct.get(pick.id)?.quote ?? \"\", cost: pick.cost, gain: pick.gain });\n units = run.selection;\n left -= run.spent;\n spent += run.spent;\n stages.push({ name: stage.name, method: run.method, before: run.before, after: run.after, spent: run.spent, stop: run.stop, evaluations: run.evaluations });\n }\n return { budget: options.budget, spent, buys, units, stages };\n}\n","import { compare, sum, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { evolve, frontOf, sweep, type EvaluationRow, type Measure, type Objective, type SweepCounts } from \"@mark1russell7/strategy-search\";\nimport { spaceSize, STRATEGY_SPACE_SCHEMA, type SpaceParam, type StrategyConfig, type StrategySpace } from \"@mark1russell7/strategy-space\";\nimport { compile, isFieldName, parse, space, type AnyDomain, type Program } from \"@mark1russell7/vex\";\nimport { BoolDomain, NumDomain, TextDomain } from \"@mark1russell7/vex-domains\";\nimport { z } from \"zod\";\nimport { offersOfPart, priceOf, type Observation, type PartWant, type Priced } from \"./offers.ts\";\nimport { CONDITIONS, textSchema, type Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy plan. A need names the slots of a purchase, the parts that can fill each slot, and\n * the measures and the rules of a basket as Vex programs. The plan searches the baskets with strategy-search, and it\n * gives the front of the price against the measures. The module knows no part class: the facts of each part and the\n * programs come from the need. Each function of this module is a calculation with no effect.\n */\n\n/** The format name of a need record. */\nexport const NEED_FORMAT = \"buy-need/1\";\n\n/** The format name of a plan record. */\nexport const PLAN_FORMAT = \"buy-plan/1\";\n\n/** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */\nexport const NEED_KEY = \"need\";\n\n/** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */\nexport const SLOT_FIELDS = [\"slot\", \"part\", \"count\", \"cost\"] as const;\n\n/** The largest count of evaluations of a plan, when the options do not give a count. */\nexport const PLAN_EVALUATIONS = 2000;\n\n/** The domains of the programs of a need: numbers, booleans and texts. */\nconst DOMAINS: readonly AnyDomain[] = [NumDomain, BoolDomain, TextDomain];\n\n/** A fact of a part, or an input of a need: a number, a text or a boolean. */\nexport type Fact = number | string | boolean;\n\n/** One part that can fill a slot: its key in the slot, the part that the offers must match, and its facts. */\nexport interface NeedPart {\n readonly key: string;\n readonly want: PartWant;\n /** The facts of the part that the programs read, for example its watts. */\n readonly facts?: Readonly<Record<string, Fact>> | undefined;\n}\n\n/** The count of units of a slot. With `min` 0, a basket can leave the slot empty. */\nexport interface SlotCount {\n readonly min: number;\n readonly max: number;\n}\n\n/** One slot of a need: its name, the parts that can fill it, and the count of its units. The default count is 1. */\nexport interface NeedSlot {\n readonly name: string;\n readonly parts: readonly NeedPart[];\n readonly count?: SlotCount | undefined;\n}\n\n/**\n * One measure of a basket: a Vex program that gives a number. With `goal`, the measure is an objective of the search.\n * A value below `min` or above `max` breaks the basket.\n */\nexport interface NeedMeasure {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n readonly goal?: \"min\" | \"max\" | undefined;\n /** The unit of the values, as text for a reader. */\n readonly unit?: string | undefined;\n readonly min?: number | undefined;\n readonly max?: number | undefined;\n}\n\n/** One rule of a basket: a Vex program that gives `true` when the basket keeps the rule. */\nexport interface NeedRule {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n}\n\n/** This record is a need: the currency and the conditions of the offers, the inputs, the slots, the measures and the rules. */\nexport interface BuyNeed {\n readonly format: typeof NEED_FORMAT;\n readonly id: string;\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n /** The inputs that the programs read at the key `need`, for example the load in watts. */\n readonly inputs?: Readonly<Record<string, Fact>> | undefined;\n readonly slots: readonly NeedSlot[];\n readonly measures?: readonly NeedMeasure[] | undefined;\n readonly rules?: readonly NeedRule[] | undefined;\n}\n\nconst factSchema: z.ZodType<Fact> = z.union([z.number().refine(Number.isFinite, \"The number is not finite.\"), z.string(), z.boolean()]);\nconst factsSchema: z.ZodType<Readonly<Record<string, Fact>>> = z.record(textSchema, factSchema);\nconst wantSchema: z.ZodType<PartWant> = z.strictObject({ brands: z.array(textSchema).min(1), partNumbers: z.array(textSchema).min(1) });\nconst wholeSchema = z.number().int().nonnegative();\n\n/** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */\nexport const buyNeedSchema: z.ZodType<BuyNeed> = z.strictObject({\n format: z.literal(NEED_FORMAT),\n id: textSchema,\n currency: textSchema,\n conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),\n inputs: factsSchema.optional(),\n slots: z\n .array(\n z.strictObject({\n name: textSchema,\n parts: z.array(z.strictObject({ key: textSchema, want: wantSchema, facts: factsSchema.optional() })).min(1),\n count: z.strictObject({ min: wholeSchema, max: wholeSchema }).optional(),\n }),\n )\n .min(1),\n measures: z\n .array(\n z.strictObject({\n name: textSchema,\n program: z.unknown(),\n goal: z.enum([\"min\", \"max\"]).optional(),\n unit: textSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n )\n .optional(),\n rules: z.array(z.strictObject({ name: textSchema, program: z.unknown() })).optional(),\n});\n\n/** This function gives the count of a slot, with the default 1 to 1. */\nfunction countOf(slot: NeedSlot): SlotCount {\n return slot.count ?? { min: 1, max: 1 };\n}\n\n/** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */\nfunction readProgram(program: unknown): { readonly ok: true; readonly program: Program } | { readonly ok: false; readonly why: string } {\n const text = program === undefined ? undefined : JSON.stringify(program);\n if (text === undefined) return { ok: false, why: \"The program is missing.\" };\n const read = parse(text, DOMAINS);\n return read.ok ? { ok: true, program: compile(read.value, { domains: DOMAINS }) } : { ok: false, why: read.error.message };\n}\n\n/** This function compiles a program that `needProblems` accepts. */\nfunction programOf(program: unknown): Program {\n const read = readProgram(program);\n if (!read.ok) throw new RangeError(read.why);\n return read.program;\n}\n\n/**\n * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad\n * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field\n * of a slot is a problem. A program that is not valid is a problem.\n */\nexport function needProblems(need: BuyNeed): string[] {\n const problems: string[] = [];\n const twice = (names: readonly string[], what: string): void => {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);\n seen.add(name);\n }\n };\n twice(\n need.slots.map((slot) => slot.name),\n \"slots\",\n );\n for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);\n for (const slot of need.slots) {\n if (slot.name === NEED_KEY) problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);\n else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);\n twice(\n slot.parts.map((part) => part.key),\n `parts of the slot ${slot.name}`,\n );\n const { min, max } = countOf(slot);\n if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max)\n problems.push(`The count of the slot ${slot.name} is ${String(min)} to ${String(max)}. It must be whole numbers, with a maximum of 1 or more and not below the minimum.`);\n for (const part of slot.parts) {\n for (const name of Object.keys(part.facts ?? {})) {\n if ((SLOT_FIELDS as readonly string[]).includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);\n else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);\n }\n }\n }\n const measures = need.measures ?? [];\n const rules = need.rules ?? [];\n twice(\n measures.map((measure) => measure.name),\n \"measures\",\n );\n twice(\n rules.map((rule) => rule.name),\n \"rules\",\n );\n for (const measure of measures) {\n if (measure.name === \"price\") problems.push(\"A measure has the name price, which is the objective of the cost.\");\n if (measure.min !== undefined && measure.max !== undefined && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);\n const read = readProgram(measure.program);\n if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);\n }\n for (const rule of rules) {\n const read = readProgram(rule.program);\n if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);\n }\n return problems;\n}\n\n/** This record is one item of a basket: the slot, the part, the count, the offer to buy and the cost with the shipping. */\nexport interface BuyItem {\n readonly slot: string;\n readonly part: string;\n readonly count: number;\n readonly offerId: string;\n readonly cost: Quantity;\n}\n\n/** This record is one basket of the front: its config id, its price, the value of each measure and its items. */\nexport interface BuyChoice {\n readonly config: string;\n /** The sum of the cost of each item. Each item is one order, with its own shipping. */\n readonly price: Quantity;\n readonly values: Readonly<Record<string, number>>;\n readonly items: readonly BuyItem[];\n}\n\n/** This record counts the baskets that break one constraint, with the reason of the first such basket. */\nexport interface BuyBreak {\n /** The constraint: `price:<slot>`, `measure:<name>`, `limit:<name>` or `rule:<name>`. */\n readonly name: string;\n readonly count: number;\n readonly why: string;\n}\n\n/** This record is a part that no basket can have, because no offer of the part is usable at a count of its slot. */\nexport interface UnpricedPart {\n readonly slot: string;\n readonly part: string;\n readonly why: string;\n}\n\n/** This record is a buy plan: the method of the search, its counts, the front of the baskets and the reasons of the breaks. */\nexport interface BuyPlan {\n readonly format: typeof PLAN_FORMAT;\n /** The id of the need. */\n readonly need: string;\n readonly currency: string;\n /** `grid` evaluates each basket. `evolve` is a genetic search. `none` tells that a slot that must have a part has no part with an offer. */\n readonly method: \"grid\" | \"evolve\" | \"none\";\n /** The seed of a genetic search, or null. */\n readonly seed: number | null;\n /** The id of the run of strategy-search, or null for `none`. */\n readonly run: string | null;\n readonly objectives: readonly Objective[];\n readonly counts: SweepCounts;\n /** The baskets on the Pareto front, from the lowest price. Equal prices go in the order of the config id. */\n readonly front: readonly BuyChoice[];\n /** The constraints that the evaluated baskets break, in the order of their names. */\n readonly breaks: readonly BuyBreak[];\n /** The parts with no usable offer, in the order of the slots and of their parts. */\n readonly unpriced: readonly UnpricedPart[];\n}\n\nexport { buyCandidates, orderBuys, type BuyCandidate, type BuyCandidates, type BuyOrder, type CandidateOptions, type OrderBuy, type OrderOptions, type OrderStage, type OrderStageResult, type ProductWant } from \"./order.ts\";\n\n/** These options change the search of a plan. */\nexport interface PlanOptions {\n /** The largest count of evaluations. A space with no more baskets gets a grid of each basket. The default is `PLAN_EVALUATIONS`. */\n readonly evaluations?: number | undefined;\n /** The seed of a genetic search. The default is the id of the need. */\n readonly seed?: number | string | undefined;\n /** The count of the baskets of a generation of a genetic search. The default is the default of strategy-search. */\n readonly population?: number | undefined;\n}\n\n\n/** The breaks, the values and the items of one basket. */\ninterface Assessed {\n readonly breaks: readonly { readonly name: string; readonly why: string }[];\n readonly values: Readonly<Record<string, number>>;\n readonly price: Quantity | null;\n readonly items: readonly BuyItem[];\n}\n\n\n/**\n * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy\n * space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum\n * of the cost of each item.\n *\n * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has\n * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part\n * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.\n *\n * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.\n *\n * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.\n * The function also throws a RangeError when strategy-search refuses the options.\n */\nexport function planBuys(need: BuyNeed, observations: readonly Observation[], options: PlanOptions = {}): BuyPlan {\n const shape = buyNeedSchema.safeParse(need);\n if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\" \")}`);\n const problems = needProblems(need);\n if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(\" \")}`);\n const evaluations = options.evaluations ?? PLAN_EVALUATIONS;\n if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);\n\n const measures = (need.measures ?? []).map((measure) => ({ measure, program: programOf(measure.program) }));\n const rules = (need.rules ?? []).map((rule) => ({ rule, program: programOf(rule.program) }));\n const objectives: Objective[] = [\n { name: \"price\", goal: \"min\", unit: need.currency },\n ...measures.flatMap(({ measure }) => (measure.goal === undefined ? [] : [measure.unit === undefined ? { name: measure.name, goal: measure.goal } : { name: measure.name, goal: measure.goal, unit: measure.unit }])),\n ];\n\n // The price of each count of each part, once. A part with no usable offer at any count is not an option.\n const prices = new Map<string, Map<number, Priced>>();\n const unpriced: UnpricedPart[] = [];\n const stages: StrategySpace[\"stages\"][number][] = [];\n let blocked = false;\n for (const slot of need.slots) {\n const { min, max } = countOf(slot);\n const low = Math.max(1, min);\n const params: SpaceParam[] = max > low ? [{ name: \"count\", kind: \"int\", min: low, max, default: low }] : [];\n const usable: string[] = [];\n for (const part of slot.parts) {\n const offers = offersOfPart(observations, part.want);\n const byCount = new Map<number, Priced>();\n for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));\n prices.set(`${slot.name}\\u0000${part.key}`, byCount);\n const first = byCount.get(low);\n if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);\n else unpriced.push({ slot: slot.name, part: part.key, why: first === undefined || first.ok ? \"No offer is usable.\" : first.why });\n }\n if (usable.length > 0) stages.push({ name: slot.name, options: usable.map((id) => ({ id, params })), ...(min === 0 ? { optional: true } : {}) });\n else if (min > 0) blocked = true;\n }\n const none: BuyPlan = { format: PLAN_FORMAT, need: need.id, currency: need.currency, method: \"none\", seed: null, run: null, objectives, counts: { feasible: 0, breaks: 0, unread: 0, front: 0 }, front: [], breaks: [], unpriced };\n if (blocked || stages.length === 0) return none;\n\n const strategySpace: StrategySpace = { schema: STRATEGY_SPACE_SCHEMA, engine: \"buy-plan\", version: \"1\", stages };\n\n const assess = (config: StrategyConfig): Assessed => {\n const breaks: { name: string; why: string }[] = [];\n const items: BuyItem[] = [];\n const records: Record<string, Readonly<Record<string, Fact>>> = { [NEED_KEY]: need.inputs ?? {} };\n for (const slot of need.slots) {\n const choice = config.stages[slot.name] ?? null;\n if (choice === null) {\n records[slot.name] = { slot: slot.name, count: 0, cost: 0 };\n continue;\n }\n const part = slot.parts.find((each) => each.key === choice.option) as NeedPart;\n const count = Number(choice.params?.[\"count\"] ?? Math.max(1, countOf(slot).min));\n const priced = prices.get(`${slot.name}\\u0000${part.key}`)?.get(count) ?? { ok: false, why: `The count ${String(count)} is not a count of the slot.` };\n if (!priced.ok) {\n breaks.push({ name: `price:${slot.name}`, why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}` });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: 0 };\n continue;\n }\n items.push({ slot: slot.name, part: part.key, count, offerId: priced.offerId, cost: priced.cost });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: valueIn(priced.cost, need.currency) };\n }\n const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);\n const values: Record<string, number> = price === null ? {} : { price: valueIn(price, need.currency) };\n const basket = space.record(records);\n for (const { measure, program } of measures) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `measure:${measure.name}`, why: result.error.message });\n else if (typeof result.value !== \"number\" || !Number.isFinite(result.value)) breaks.push({ name: `measure:${measure.name}`, why: `The value ${String(result.value)} is not a finite number.` });\n else {\n values[measure.name] = result.value;\n if (measure.min !== undefined && result.value < measure.min) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.` });\n if (measure.max !== undefined && result.value > measure.max) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.` });\n }\n }\n for (const { rule, program } of rules) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `rule:${rule.name}`, why: result.error.message });\n else if (result.value !== true) breaks.push({ name: `rule:${rule.name}`, why: result.value === false ? \"The basket breaks the rule.\" : `The value ${String(result.value)} is not a boolean.` });\n }\n return { breaks, values, price, items };\n };\n\n // The reason of the first basket that breaks each constraint.\n const firstWhy = new Map<string, string>();\n const evaluate = (config: StrategyConfig): Measure => {\n const assessed = assess(config);\n for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);\n return { breaks: [...new Set(assessed.breaks.map((each) => each.name))], values: assessed.values };\n };\n\n const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));\n const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);\n const evaluator = `buy-need:${need.id}`;\n const run = grid\n ? sweep(strategySpace, { objectives, evaluate, enumerate: { mode: \"grid\", levels, limit: evaluations }, evaluator })\n : evolve(strategySpace, {\n objectives,\n evaluate,\n seed: options.seed ?? need.id,\n evaluations,\n ...(options.population === undefined ? {} : { population: options.population }),\n evaluator,\n });\n\n const front = frontOf(run)\n .map(({ row, config }): BuyChoice => {\n const assessed = assess(config);\n const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== \"price\"));\n return { config: row.config, price: assessed.price as Quantity, values, items: assessed.items };\n })\n .sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));\n return {\n ...none,\n method: grid ? \"grid\" : \"evolve\",\n seed: run.seed,\n run: run.run,\n counts: run.counts,\n front,\n breaks: breaksOf(run.rows, firstWhy),\n unpriced,\n };\n}\n\n/** This function counts the rows that break each constraint, in the order of the names. */\nfunction breaksOf(rows: readonly EvaluationRow[], firstWhy: ReadonlyMap<string, string>): BuyBreak[] {\n const counts = new Map<string, number>();\n for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);\n return [...counts.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([name, count]) => ({ name, count, why: firstWhy.get(name) ?? \"\" }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,cAAc,OAA+B,cAAsC,SAA0C;CAC3I,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,aAA6B,CAAC;CACpC,MAAM,WAA+C,CAAC;CACtD,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,IAAI,KAAK,OAAO,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,QAAQ,wBAAwB;EACrG,KAAK,IAAI,KAAK,OAAO;EACrB,MAAM,MAAM,KAAK,OAAO;EACxB,IAAI,EAAE,OAAO,cAAc,GAAG,KAAK,OAAO,IAAI,MAAM,IAAI,WAAW,0BAA0B,KAAK,QAAQ,MAAM,OAAO,GAAG,EAAE,0CAA0C;EACtK,MAAM,SAAS,QAAQ,aAAa,cAAc,KAAK,IAAI,GAAG,GAAG,OAAO;EACxE,IAAI,OAAO,IAAI,WAAW,KAAK;GAAE,SAAS,KAAK;GAAS,OAAO,QAAQ,OAAO,MAAM,QAAQ,QAAQ;GAAG;GAAK,OAAO,OAAO;EAAQ,CAA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C,UAAmD;CACnG,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,OAAO,MAAM,KAAK,MAAM,QAAQ,IAAI,QAAQ,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,KAAK,KAAK,CAAC;CACnG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,MAAM,YAAY;EAAE;EAAM;EAAO,KAAK,SAAS,IAAI,IAAI,KAAK;CAAG,EAAE;AAC5E"}
@@ -0,0 +1,187 @@
1
+ import { quantitySchema } from "@mark1russell7/quantity/schema";
2
+ import { z } from "zod";
3
+ // src/gtin.ts
4
+ /**
5
+ * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.
6
+ * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.
7
+ */
8
+ const LENGTHS = /* @__PURE__ */ new Set([
9
+ 8,
10
+ 12,
11
+ 13,
12
+ 14
13
+ ]);
14
+ /**
15
+ * This function gives the check digit of the digits of a GTIN without its last digit.
16
+ *
17
+ * @throws RangeError when the text has a character that is not a digit, or no character.
18
+ */
19
+ function gtinCheckDigit(body) {
20
+ if (!/^\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);
21
+ let total = 0;
22
+ for (let i = 0; i < body.length; i += 1) {
23
+ const digit = body.charCodeAt(body.length - 1 - i) - 48;
24
+ total += i % 2 === 0 ? digit * 3 : digit;
25
+ }
26
+ return (10 - total % 10) % 10;
27
+ }
28
+ /**
29
+ * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
30
+ * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
31
+ */
32
+ function parseGtin(text) {
33
+ const digits = text.replace(/[\s-]/g, "");
34
+ if (!/^\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;
35
+ if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;
36
+ return digits.padStart(14, "0");
37
+ }
38
+ // src/records.ts
39
+ /**
40
+ * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
41
+ * the field `grade` of the offer.
42
+ */
43
+ const CONDITIONS = [
44
+ "new",
45
+ "open-box",
46
+ "refurbished",
47
+ "used",
48
+ "for-parts",
49
+ "unknown"
50
+ ];
51
+ /** The states of the stock of an offer at the time of a reading. */
52
+ const AVAILABILITIES = [
53
+ "in-stock",
54
+ "low-stock",
55
+ "out-of-stock",
56
+ "preorder",
57
+ "unknown"
58
+ ];
59
+ /** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
60
+ const FORMATS = ["fixed-price", "auction"];
61
+ /** This schema accepts a text with a character that is not a space, and with no space at an end. */
62
+ const textSchema = z.string().refine((text) => text !== "" && text === text.trim(), "The text is empty, or it has a space at an end.");
63
+ /** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
64
+ const sourceSchema = z.string().regex(/^[a-z][a-z0-9-]*$/, "The name of a source has small letters, digits and hyphens, with a letter first.");
65
+ /** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
66
+ const gtinSchema = z.string().refine((text) => /^\d{14}$/.test(text) && parseGtin(text) === text, "The GTIN is not a GTIN-14 with a correct check digit.");
67
+ /** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
68
+ const moneySchema = quantitySchema("money", { nonnegative: true });
69
+ /** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
70
+ const instantSchema = z.iso.datetime();
71
+ /** This schema accepts a part number of a maker. */
72
+ const partNumberSchema = z.strictObject({
73
+ brand: textSchema,
74
+ partNumber: textSchema
75
+ });
76
+ /** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
77
+ const specSchema = z.strictObject({
78
+ name: textSchema,
79
+ value: textSchema
80
+ });
81
+ /** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
82
+ const sellerSchema = z.strictObject({
83
+ id: textSchema.optional(),
84
+ name: textSchema.optional(),
85
+ rating: z.strictObject({
86
+ percent: z.number().min(0).max(100),
87
+ count: z.int().nonnegative()
88
+ }).optional()
89
+ });
90
+ /** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
91
+ const productSchema = z.strictObject({
92
+ id: textSchema,
93
+ title: textSchema,
94
+ brand: textSchema.optional(),
95
+ category: z.array(textSchema).optional(),
96
+ gtins: z.array(gtinSchema),
97
+ partNumbers: z.array(partNumberSchema),
98
+ specs: z.array(specSchema)
99
+ });
100
+ /** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
101
+ function offerId(source, sourceId) {
102
+ return `${source}:${sourceId}`;
103
+ }
104
+ /** This function gives the name of the source of an offer id: the text before the first colon. */
105
+ function sourceOfOffer(id) {
106
+ const colon = id.indexOf(":");
107
+ if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);
108
+ return id.slice(0, colon);
109
+ }
110
+ /**
111
+ * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
112
+ * `productId` names the product of the catalog after a match.
113
+ */
114
+ const offerSchema = z.strictObject({
115
+ id: textSchema,
116
+ source: sourceSchema,
117
+ sourceId: textSchema,
118
+ productId: textSchema.optional(),
119
+ title: textSchema,
120
+ url: z.url({ protocol: /^https$/ }).optional(),
121
+ seller: sellerSchema,
122
+ condition: z.enum(CONDITIONS),
123
+ grade: textSchema.optional(),
124
+ format: z.enum(FORMATS),
125
+ endsAt: instantSchema.optional(),
126
+ gtins: z.array(gtinSchema),
127
+ partNumbers: z.array(partNumberSchema),
128
+ specs: z.array(specSchema)
129
+ }).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
130
+ message: "The id of an offer is its source and its source id, with a colon between them.",
131
+ path: ["id"]
132
+ });
133
+ /** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
134
+ const shippingSchema = z.discriminatedUnion("kind", [
135
+ z.strictObject({ kind: z.literal("free") }),
136
+ z.strictObject({
137
+ kind: z.literal("fixed"),
138
+ cost: moneySchema
139
+ }),
140
+ z.strictObject({ kind: z.literal("calculated") }),
141
+ z.strictObject({ kind: z.literal("unknown") })
142
+ ]);
143
+ /** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
144
+ const priceBreakSchema = z.strictObject({
145
+ quantity: z.int().min(2),
146
+ unitPrice: moneySchema
147
+ });
148
+ /**
149
+ * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
150
+ * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
151
+ * than the minimum.
152
+ */
153
+ const priceReadingSchema = z.strictObject({
154
+ offerId: textSchema,
155
+ at: instantSchema,
156
+ price: moneySchema,
157
+ listPrice: moneySchema.optional(),
158
+ shipping: shippingSchema,
159
+ availability: z.enum(AVAILABILITIES),
160
+ available: z.int().nonnegative().optional(),
161
+ minimumQuantity: z.int().min(1).optional(),
162
+ priceBreaks: z.array(priceBreakSchema).optional()
163
+ }).superRefine((reading, context) => {
164
+ let last = reading.minimumQuantity ?? 1;
165
+ for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {
166
+ if (entry.quantity <= last) context.addIssue({
167
+ code: "custom",
168
+ message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,
169
+ path: [
170
+ "priceBreaks",
171
+ index,
172
+ "quantity"
173
+ ]
174
+ });
175
+ last = Math.max(last, entry.quantity);
176
+ }
177
+ const { availability, available } = reading;
178
+ if (available === void 0 || availability === "unknown" || availability === "preorder") return;
179
+ if (availability === "out-of-stock" !== (available === 0)) context.addIssue({
180
+ code: "custom",
181
+ message: `The availability ${availability} does not agree with the count ${available}.`,
182
+ path: ["available"]
183
+ });
184
+ });
185
+ export { specSchema as _, instantSchema as a, parseGtin as b, offerSchema as c, priceReadingSchema as d, productSchema as f, sourceSchema as g, sourceOfOffer as h, gtinSchema as i, partNumberSchema as l, shippingSchema as m, CONDITIONS as n, moneySchema as o, sellerSchema as p, FORMATS as r, offerId as s, AVAILABILITIES as t, priceBreakSchema as u, textSchema as v, gtinCheckDigit as y };
186
+
187
+ //# sourceMappingURL=records-W6sPyhTQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"records-W6sPyhTQ.js","names":[],"sources":["../src/gtin.ts","../src/records.ts"],"sourcesContent":["/**\n * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.\n * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.\n */\n\nconst LENGTHS: ReadonlySet<number> = new Set([8, 12, 13, 14]);\n\n/**\n * This function gives the check digit of the digits of a GTIN without its last digit.\n *\n * @throws RangeError when the text has a character that is not a digit, or no character.\n */\nexport function gtinCheckDigit(body: string): number {\n if (!/^\\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);\n let total = 0;\n for (let i = 0; i < body.length; i += 1) {\n const digit = body.charCodeAt(body.length - 1 - i) - 48;\n total += i % 2 === 0 ? digit * 3 : digit;\n }\n return (10 - (total % 10)) % 10;\n}\n\n/**\n * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.\n * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.\n */\nexport function parseGtin(text: string): string | null {\n const digits = text.replace(/[\\s-]/g, \"\");\n if (!/^\\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;\n if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;\n return digits.padStart(14, \"0\");\n}\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { parseGtin } from \"./gtin.ts\";\nimport type { PartNumber } from \"./identifiers.ts\";\n\n/**\n * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in\n * the field `grade` of the offer.\n */\nexport const CONDITIONS = [\"new\", \"open-box\", \"refurbished\", \"used\", \"for-parts\", \"unknown\"] as const;\n/** The condition of an offer. */\nexport type Condition = (typeof CONDITIONS)[number];\n\n/** The states of the stock of an offer at the time of a reading. */\nexport const AVAILABILITIES = [\"in-stock\", \"low-stock\", \"out-of-stock\", \"preorder\", \"unknown\"] as const;\n/** The state of the stock of an offer. */\nexport type Availability = (typeof AVAILABILITIES)[number];\n\n/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */\nexport const FORMATS = [\"fixed-price\", \"auction\"] as const;\n/** The buying format of an offer. */\nexport type Format = (typeof FORMATS)[number];\n\n/** One specification of a product as text. */\nexport interface Spec {\n readonly name: string;\n readonly value: string;\n}\n\n/** The feedback of a seller: the percent of good feedback, and the count of the feedback. */\nexport interface Rating {\n readonly percent: number;\n readonly count: number;\n}\n\n/** A seller of an offer. A source gives some of these fields, or none. */\nexport interface Seller {\n readonly id?: string | undefined;\n readonly name?: string | undefined;\n readonly rating?: Rating | undefined;\n}\n\n/** A product of the catalog: one thing that a person can buy, with its identifiers and its specifications. */\nexport interface Product {\n readonly id: string;\n readonly title: string;\n readonly brand?: string | undefined;\n readonly category?: readonly string[] | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** An offer of a seller: one product at one seller, with the identifiers that the source gives. */\nexport interface Offer {\n readonly id: string;\n readonly source: string;\n readonly sourceId: string;\n readonly productId?: string | undefined;\n readonly title: string;\n readonly url?: string | undefined;\n readonly seller: Seller;\n readonly condition: Condition;\n readonly grade?: string | undefined;\n readonly format: Format;\n readonly endsAt?: string | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** The shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport type Shipping =\n | { readonly kind: \"free\" }\n | { readonly kind: \"fixed\"; readonly cost: Quantity }\n | { readonly kind: \"calculated\" }\n | { readonly kind: \"unknown\" };\n\n/** A price break of a reading: the unit price for an order of `quantity` units or more. */\nexport interface PriceBreak {\n readonly quantity: number;\n readonly unitPrice: Quantity;\n}\n\n/** A price reading: the state of one offer at one instant. */\nexport interface PriceReading {\n readonly offerId: string;\n readonly at: string;\n readonly price: Quantity;\n readonly listPrice?: Quantity | undefined;\n readonly shipping: Shipping;\n readonly availability: Availability;\n readonly available?: number | undefined;\n readonly minimumQuantity?: number | undefined;\n readonly priceBreaks?: readonly PriceBreak[] | undefined;\n}\n\n/** This schema accepts a text with a character that is not a space, and with no space at an end. */\nexport const textSchema: z.ZodType<string> = z\n .string()\n .refine((text) => text !== \"\" && text === text.trim(), \"The text is empty, or it has a space at an end.\");\n\n/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */\nexport const sourceSchema: z.ZodType<string> = z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/, \"The name of a source has small letters, digits and hyphens, with a letter first.\");\n\n/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */\nexport const gtinSchema: z.ZodType<string> = z\n .string()\n .refine((text) => /^\\d{14}$/.test(text) && parseGtin(text) === text, \"The GTIN is not a GTIN-14 with a correct check digit.\");\n\n/** This schema accepts an amount of money of zero or more, for example `{ \"value\": 129.99, \"unit\": \"USD\" }`. */\nexport const moneySchema: z.ZodType<Quantity, Quantity> = quantitySchema(\"money\", { nonnegative: true });\n\n/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */\nexport const instantSchema: z.ZodType<string> = z.iso.datetime();\n\n/** This schema accepts a part number of a maker. */\nexport const partNumberSchema: z.ZodType<PartNumber> = z.strictObject({ brand: textSchema, partNumber: textSchema });\n\n/** This schema accepts one specification as text, for example `{ \"name\": \"Capacity\", \"value\": \"1 TB\" }`. */\nexport const specSchema: z.ZodType<Spec> = z.strictObject({ name: textSchema, value: textSchema });\n\n/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */\nexport const sellerSchema: z.ZodType<Seller> = z.strictObject({\n id: textSchema.optional(),\n name: textSchema.optional(),\n rating: z.strictObject({ percent: z.number().min(0).max(100), count: z.int().nonnegative() }).optional(),\n});\n\n/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */\nexport const productSchema: z.ZodType<Product> = z.strictObject({\n id: textSchema,\n title: textSchema,\n brand: textSchema.optional(),\n category: z.array(textSchema).optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n});\n\n/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */\nexport function offerId(source: string, sourceId: string): string {\n return `${source}:${sourceId}`;\n}\n\n/** This function gives the name of the source of an offer id: the text before the first colon. */\nexport function sourceOfOffer(id: string): string {\n const colon = id.indexOf(\":\");\n if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);\n return id.slice(0, colon);\n}\n\n/**\n * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.\n * `productId` names the product of the catalog after a match.\n */\nexport const offerSchema: z.ZodType<Offer> = z\n .strictObject({\n id: textSchema,\n source: sourceSchema,\n sourceId: textSchema,\n productId: textSchema.optional(),\n title: textSchema,\n url: z.url({ protocol: /^https$/ }).optional(),\n seller: sellerSchema,\n condition: z.enum(CONDITIONS),\n grade: textSchema.optional(),\n format: z.enum(FORMATS),\n endsAt: instantSchema.optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n })\n .refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {\n message: \"The id of an offer is its source and its source id, with a colon between them.\",\n path: [\"id\"],\n });\n\n/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport const shippingSchema: z.ZodType<Shipping> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"free\") }),\n z.strictObject({ kind: z.literal(\"fixed\"), cost: moneySchema }),\n z.strictObject({ kind: z.literal(\"calculated\") }),\n z.strictObject({ kind: z.literal(\"unknown\") }),\n]);\n\n/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */\nexport const priceBreakSchema: z.ZodType<PriceBreak> = z.strictObject({ quantity: z.int().min(2), unitPrice: moneySchema });\n\n/**\n * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an\n * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more\n * than the minimum.\n */\nexport const priceReadingSchema: z.ZodType<PriceReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n price: moneySchema,\n listPrice: moneySchema.optional(),\n shipping: shippingSchema,\n availability: z.enum(AVAILABILITIES),\n available: z.int().nonnegative().optional(),\n minimumQuantity: z.int().min(1).optional(),\n priceBreaks: z.array(priceBreakSchema).optional(),\n })\n .superRefine((reading, context) => {\n let last = reading.minimumQuantity ?? 1;\n for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {\n if (entry.quantity <= last) {\n context.addIssue({\n code: \"custom\",\n message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,\n path: [\"priceBreaks\", index, \"quantity\"],\n });\n }\n last = Math.max(last, entry.quantity);\n }\n const { availability, available } = reading;\n if (available === undefined || availability === \"unknown\" || availability === \"preorder\") return;\n if ((availability === \"out-of-stock\") !== (available === 0)) {\n context.addIssue({\n code: \"custom\",\n message: `The availability ${availability} does not agree with the count ${available}.`,\n path: [\"available\"],\n });\n }\n });\n"],"mappings":";;;;;;;AAKA,MAAM,0BAA+B,IAAI,IAAI;CAAC;CAAG;CAAI;CAAI;AAAE,CAAC;;;;;;AAO5D,SAAgB,eAAe,MAAsB;CACnD,IAAI,CAAC,QAAQ,KAAK,IAAI,GAAG,MAAM,IAAI,WAAW,YAAY,KAAK,UAAU,IAAI,EAAE,4BAA4B;CAC3G,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,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,oBAAqB,cAAc,IACvD,QAAQ,SAAS;EACf,MAAM;EACN,SAAS,oBAAoB,aAAa,iCAAiC,UAAU;EACrF,MAAM,CAAC,WAAW;CACpB,CAAC;AAEL,CAAC"}
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * The catalog of supplies: the format, the gate, the wants of its products and the gifts of their units, and the
3
- * reference catalog. Each value has a cited fact, the definition of the product, or a no read.
3
+ * reference catalog. It also gives the price of a product from an average price, and the cost of a food plan of USDA.
4
+ * Each value has a cited fact, the definition of the product, or a no read.
4
5
  */
6
+ import { t as AveragePrice } from "./average-Bj0GkSLo.js";
5
7
  import { a as PartWant } from "./offers-CVUAcRHs.js";
6
8
  import { l as ProductWant } from "./order-BAbk8QQA.js";
9
+ import { Quantity } from "@mark1russell7/quantity";
7
10
  import { CitedUnit, Finding, FindingCode, GateOptions, Source } from "@mark1russell7/guidebook";
8
11
  /** The format of a catalog of supplies. */
9
12
  export declare const SUPPLY_FORMAT = "supply-catalog/1";
@@ -52,6 +55,20 @@ type ShelfLife = CitedAmount | {
52
55
  readonly read: true;
53
56
  readonly foodKeeper: number;
54
57
  } | NoRead;
58
+ /**
59
+ * The join of a product to a series of average prices. It names the source and the series. It also gives the amount
60
+ * of the item of the series in one unit of the product. For example, 1 kg of dry rice is the amount of a series of
61
+ * rice in USD/lb.
62
+ */
63
+ interface AverageJoin {
64
+ readonly read: true;
65
+ /** The source of the average prices, for example `bls-ap`. */
66
+ readonly source: string;
67
+ /** The id of the series in the source, for example `APU0000701312`. */
68
+ readonly series: string;
69
+ /** The amount of the item of the series in one unit of the product, with its reason. */
70
+ readonly per: CitedAmount;
71
+ }
55
72
  /** A product of the catalog. */
56
73
  interface SupplyProduct {
57
74
  readonly id: string;
@@ -59,11 +76,18 @@ interface SupplyProduct {
59
76
  readonly kind: SupplyKind;
60
77
  /** The part that the offers of a seller must match. A product with no part has no offer, so it has no price. */
61
78
  readonly want?: PartWant | undefined;
62
- /** The resources that one unit gives. */
79
+ /** The resources that one unit gives. A product that gives no stored resource, for example a radio, gives none. */
63
80
  readonly gives: readonly SupplyGift[];
81
+ /** The `id` of a fact that tells why a kit has the product, for example the kit list of a public agency. */
82
+ readonly basis?: string | undefined;
64
83
  /** The food energy of one unit, in a unit of energy. A cooking converter gives it. */
65
84
  readonly energy?: CitedAmount | NoRead | undefined;
66
85
  readonly shelf: ShelfLife;
86
+ /**
87
+ * The series of average prices that gives the price of one unit, or no read with the reason. A product with no join
88
+ * and no part has no price.
89
+ */
90
+ readonly average?: AverageJoin | NoRead | undefined;
67
91
  }
68
92
  /** A catalog of supplies: the sources, the cited facts, the resources and the products. */
69
93
  interface SupplyCatalog {
@@ -74,7 +98,7 @@ interface SupplyCatalog {
74
98
  readonly products: readonly SupplyProduct[];
75
99
  }
76
100
  /** The codes of the findings of the catalog gate. */
77
- export declare const SUPPLY_CODES: readonly ["supplies-format", "supplies-twice", "supplies-kind", "supplies-resource", "supplies-fact", "supplies-amount", "supplies-unit", "supplies-shelf", "supplies-unused", "supplies-no-read", "supplies-no-reason"];
101
+ export declare const SUPPLY_CODES: readonly ["supplies-format", "supplies-twice", "supplies-kind", "supplies-resource", "supplies-fact", "supplies-basis", "supplies-amount", "supplies-unit", "supplies-shelf", "supplies-unused", "supplies-no-read", "supplies-no-reason"];
78
102
  /** A code of a finding of the catalog gate. */
79
103
  type SupplyCode = (typeof SUPPLY_CODES)[number];
80
104
  /** A finding of the catalog gate, or of the gate of the facts and their sources. */
@@ -84,10 +108,13 @@ type SupplyFinding = Finding<SupplyCode | FindingCode, "source" | "unit" | "reso
84
108
  * `@mark1russell7/guidebook`), and the findings of the products:
85
109
  *
86
110
  * - An error for a product or a resource two times, a kind that is not a supply kind, and a gift of an unknown resource.
87
- * - An error for a fact that is not a fact of the catalog, and for an amount that is not more than 0.
111
+ * - An error for a product that gives no resource and has no basis.
112
+ * - An error for a fact that is not a fact of the catalog, and for an amount that is not more than 0. The basis of a
113
+ * product is also a fact.
88
114
  * - An error for an amount with no reason, with two reasons, or with a blank definition. A catalog from JSON can have them.
89
115
  * - An error for a unit that is not a unit of `@mark1russell7/quantity`.
90
116
  * - An error for a unit that does not convert to the unit of its resource.
117
+ * - The amount of the item of an average price has the same checks as each other amount.
91
118
  * - A warning for each value with no read, and for a no read with a blank reason.
92
119
  * - A warning for each fact and each source that no product uses.
93
120
  *
@@ -129,7 +156,114 @@ type GiftOf = {
129
156
  * @throws The error of `valueIn` of `@mark1russell7/quantity` when the unit of a gift does not convert to the unit of its resource
130
157
  */
131
158
  export declare function giftsOf(catalog: SupplyCatalog, id: string, units: number): GiftOf[];
159
+ /** The price of one unit of a product from an average price, or no read with the reason. */
160
+ type SupplyPrice = {
161
+ readonly product: string;
162
+ readonly read: true;
163
+ readonly price: Quantity;
164
+ readonly average: string;
165
+ readonly period: string;
166
+ } | {
167
+ readonly product: string;
168
+ readonly read: false;
169
+ readonly why: string;
170
+ };
171
+ /**
172
+ * This function gives the price of one unit of each product with a join to a series, in the order of the catalog.
173
+ * It takes the last month of each series (`latestAverages`). The price is in the money of the average price.
174
+ *
175
+ * - A product with no join is not in the result.
176
+ * - A join with no read, a series with no price, and a unit that does not fit give no read. A no read is not 0.
177
+ * - The unit of the series must convert to the unit of the product, for example USD/lb to 1 kg.
178
+ * - With the option `since`, a last price before that month gives no read. A series that stops then gives no old price.
179
+ *
180
+ * @param catalog - The catalog
181
+ * @param prices - The average prices, from one or more reads
182
+ * @param options - The option `since`: the first month of a price that the result can use, in the form `YYYY-MM`
183
+ * @returns The price of one unit of each product with a join, or no read with the reason
184
+ * @throws RangeError when `since` is not a month in the form `YYYY-MM`
185
+ */
186
+ export declare function averageSupplyPrices(catalog: SupplyCatalog, prices: readonly AveragePrice[], options?: {
187
+ readonly since?: string | undefined;
188
+ }): SupplyPrice[];
132
189
  /** The reference catalog of supplies. A household adds its own products to a copy of it. */
133
190
  export declare const SUPPLY_CATALOG: SupplyCatalog;
134
- export type { CitedAmount, GiftOf, NoRead, ShelfLife, SupplyCatalog, SupplyCode, SupplyFinding, SupplyGift, SupplyKind, SupplyProduct, SupplyResource };
191
+ /** The age and sex groups of a food plan of USDA. */
192
+ export declare const FOOD_PLAN_GROUPS: readonly ["child-1", "child-2-3", "child-4-5", "child-6-8", "child-9-11", "female-12-13", "female-14-19", "female-20-50", "female-51-70", "female-71-up", "male-12-13", "male-14-19", "male-20-50", "male-51-70", "male-71-up"];
193
+ /** An age and sex group of a food plan. */
194
+ type FoodPlanGroup = (typeof FOOD_PLAN_GROUPS)[number];
195
+ /** The change of the cost for a size of household, for example 0.2 for one person. */
196
+ interface FoodPlanSize {
197
+ /** The smallest count of persons. */
198
+ readonly from: number;
199
+ /** The largest count of persons. Without it, the change applies to each larger household. */
200
+ readonly to?: number | undefined;
201
+ /** The change of the cost, as a fraction: 0.2 adds 20 percent, and -0.05 subtracts 5 percent. */
202
+ readonly change: number;
203
+ }
204
+ /** The cost of a food plan in one area and one month, from one source. */
205
+ interface FoodPlan {
206
+ /** The id, for example `usda.thrifty:2026-10`. */
207
+ readonly id: string;
208
+ readonly title: string;
209
+ /** The area, as the source names it, for example `U.S. average`. */
210
+ readonly area: string;
211
+ /** The month of the costs, in the form `YYYY-MM`. */
212
+ readonly period: string;
213
+ readonly source: Source;
214
+ /** The place of the table in the source. */
215
+ readonly locator: string;
216
+ /** The cost of the food of one week for one person of each group, for example `{ "value": 58.7, "unit": "USD/wk" }`. */
217
+ readonly weekly: Readonly<Record<FoodPlanGroup, Quantity>>;
218
+ /** The change of the cost for each size of household. The costs of `weekly` are for the size with the change 0. */
219
+ readonly sizes: readonly FoodPlanSize[];
220
+ }
221
+ /** A group of the members of a household, and the count of its persons. */
222
+ interface FoodPlanMember {
223
+ readonly group: FoodPlanGroup;
224
+ readonly count: number;
225
+ }
226
+ /** The result of a check of the cost of food against a food plan. */
227
+ interface FoodPlanCheck {
228
+ /** The cost of the plan for the same members and days. */
229
+ readonly plan: Quantity;
230
+ /** The cost of the food, in the money of the plan. */
231
+ readonly cost: Quantity;
232
+ /** The cost of the food divided by the cost of the plan. */
233
+ readonly ratio: number;
234
+ /**
235
+ * True when the food costs more than the plan. The Thrifty plan is the lowest of the four plans of USDA. Thus a list
236
+ * above the cost of the Thrifty plan is not wrong when it has foods that cost more than staples.
237
+ */
238
+ readonly above: boolean;
239
+ }
240
+ /**
241
+ * This function gives the cost of a food plan for the members of a household and a count of days. It adds the cost of
242
+ * each person, and then it applies the change for the size of the household.
243
+ *
244
+ * @param plan - The food plan
245
+ * @param members - The groups of the members of the household, each with its count of persons
246
+ * @param days - The count of days, a finite number of 0 or more
247
+ * @throws RangeError when a count of persons is not a whole number of 0 or more, or when the household has no person
248
+ * @throws RangeError when a group is not in the plan, or when the plan has no change for the size of the household
249
+ * @throws RangeError when the count of days is not a finite number of 0 or more
250
+ */
251
+ export declare function foodPlanCost(plan: FoodPlan, members: readonly FoodPlanMember[], days: number): Quantity;
252
+ /**
253
+ * This function compares the cost of the food of a buy list with the cost of a food plan for the same members and
254
+ * days. A list of dry staples costs less than the plan, because the plan is a full diet. A ratio above 1 tells that
255
+ * a price or an amount of the list is possibly wrong. A low ratio is normal, because a list can be any part of a diet.
256
+ * The check of the amount of food is a check of its energy, not of its cost.
257
+ *
258
+ * @param cost - The cost of the food, in a money that converts to the money of the plan
259
+ * @param plan - The food plan
260
+ * @param members - The groups of the members of the household, each with its count of persons
261
+ * @param days - The count of days of the food
262
+ * @throws RangeError for the errors of `foodPlanCost`
263
+ * @throws The error of `valueIn` of `@mark1russell7/quantity` when the money of the cost does not convert to the money of the plan
264
+ */
265
+ export declare function foodPlanCheck(cost: Quantity, plan: FoodPlan, members: readonly FoodPlanMember[], days: number): FoodPlanCheck;
266
+ /** The costs of the food plans of USDA, one record for each plan and month. */
267
+ export declare const FOOD_PLANS: readonly FoodPlan[];
268
+ export type { AverageJoin, CitedAmount, FoodPlan, FoodPlanCheck, FoodPlanGroup, FoodPlanMember, FoodPlanSize, GiftOf, NoRead, ShelfLife, SupplyCatalog, SupplyCode, SupplyFinding, SupplyGift, SupplyKind, SupplyPrice, SupplyProduct, SupplyResource };
135
269
  //# sourceMappingURL=supplies-entry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"supplies-entry.d.ts","names":[],"sources":["../src/supplies.ts","../src/supplies-data.ts"],"mappings":";;;;;;;;qBAaa;;qBAGA;;KAGD,qBAAqB;;UAGhB;WACN;WACA;;;;;;KAOC;WACG;WAAqB;WAAyB;WAAuB;WAAuB;;WAC5F;WAAqB;WAAyB;WAAuB;WAA6B;;;UAGhG;WACN;WACA;WACA;;;UAIM;WACN;WACA,QAAQ,cAAc;;;;;;KAOrB,YAAY;WAAyB;WAAqB;IAAuB;;UAG5E;WACN;WACA;WACA,MAAM;;WAEN,OAAO;;WAEP,gBAAgB;;WAEhB,SAAS,cAAc;WACvB,OAAO;;;UAID;WACN,eAAe;WACf,kBAAkB;WAClB,gBAAgB;WAChB,oBAAoB;WACpB,mBAAmB;;;qBAIjB;;KAeD,qBAAqB;;KAGrB,gBAAgB,QAAQ,aAAa;;;;;;;;;;;;;;;;;;;wBAmCjC,cAAc,SAAS,eAAe,UAAS,cAAmB;;;;;;;;wBAwElE,YAAY,SAAS,eAAe,OAAM,SAAS,2BAAqC;;KAK5F;WAAoB;WAA2B;WAAqB;WAAyB;;WAA4B;WAA2B;WAAsB;;;;;;;;;;;;;wBAatK,QAAQ,SAAS,eAAe,YAAY,gBAAgB;;qBCpN/D,gBAAgB"}
1
+ {"version":3,"file":"supplies-entry.d.ts","names":[],"sources":["../src/supplies.ts","../src/supplies-data.ts","../src/food-plan.ts","../src/food-plan-data.ts"],"mappings":";;;;;;;;;;;qBAca;;qBAGA;;KAGD,qBAAqB;;UAGhB;WACN;WACA;;;;;;KAOC;WACG;WAAqB;WAAyB;WAAuB;WAAuB;;WAC5F;WAAqB;WAAyB;WAAuB;WAA6B;;;UAGhG;WACN;WACA;WACA;;;UAIM;WACN;WACA,QAAQ,cAAc;;;;;;KAOrB,YAAY;WAAyB;WAAqB;IAAu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