@mark1russell7/market 0.1.3 → 0.1.4

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 ADDED
@@ -0,0 +1,440 @@
1
+ import { n as CONDITIONS, v as textSchema, x as offersOfPart, y as bestOffer } from "./records-hK1UCmpm.js";
2
+ import { compare, sum, valueIn } from "@mark1russell7/quantity";
3
+ import { z } from "zod";
4
+ import { evolve, frontOf, sweep } from "@mark1russell7/strategy-search";
5
+ import { STRATEGY_SPACE_SCHEMA, spaceSize } from "@mark1russell7/strategy-space";
6
+ import { compile, isFieldName, parse, space } from "@mark1russell7/vex";
7
+ import { BoolDomain, NumDomain, TextDomain } from "@mark1russell7/vex-domains";
8
+ // src/plan.ts
9
+ /** The format name of a need record. */
10
+ const NEED_FORMAT = "buy-need/1";
11
+ /** The format name of a plan record. */
12
+ const PLAN_FORMAT = "buy-plan/1";
13
+ /** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */
14
+ const NEED_KEY = "need";
15
+ /** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */
16
+ const SLOT_FIELDS = [
17
+ "slot",
18
+ "part",
19
+ "count",
20
+ "cost"
21
+ ];
22
+ /** The largest count of evaluations of a plan, when the options do not give a count. */
23
+ const PLAN_EVALUATIONS = 2e3;
24
+ /** The domains of the programs of a need: numbers, booleans and texts. */
25
+ const DOMAINS = [
26
+ NumDomain,
27
+ BoolDomain,
28
+ TextDomain
29
+ ];
30
+ const factSchema = z.union([
31
+ z.number().refine(Number.isFinite, "The number is not finite."),
32
+ z.string(),
33
+ z.boolean()
34
+ ]);
35
+ const factsSchema = z.record(textSchema, factSchema);
36
+ const wantSchema = z.strictObject({
37
+ brands: z.array(textSchema).min(1),
38
+ partNumbers: z.array(textSchema).min(1)
39
+ });
40
+ const wholeSchema = z.number().int().nonnegative();
41
+ /** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */
42
+ const buyNeedSchema = z.strictObject({
43
+ format: z.literal(NEED_FORMAT),
44
+ id: textSchema,
45
+ currency: textSchema,
46
+ conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),
47
+ inputs: factsSchema.optional(),
48
+ slots: z.array(z.strictObject({
49
+ name: textSchema,
50
+ parts: z.array(z.strictObject({
51
+ key: textSchema,
52
+ want: wantSchema,
53
+ facts: factsSchema.optional()
54
+ })).min(1),
55
+ count: z.strictObject({
56
+ min: wholeSchema,
57
+ max: wholeSchema
58
+ }).optional()
59
+ })).min(1),
60
+ measures: z.array(z.strictObject({
61
+ name: textSchema,
62
+ program: z.unknown(),
63
+ goal: z.enum(["min", "max"]).optional(),
64
+ unit: textSchema.optional(),
65
+ min: z.number().optional(),
66
+ max: z.number().optional()
67
+ })).optional(),
68
+ rules: z.array(z.strictObject({
69
+ name: textSchema,
70
+ program: z.unknown()
71
+ })).optional()
72
+ });
73
+ /** This function gives the count of a slot, with the default 1 to 1. */
74
+ function countOf(slot) {
75
+ return slot.count ?? {
76
+ min: 1,
77
+ max: 1
78
+ };
79
+ }
80
+ /** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */
81
+ function readProgram(program) {
82
+ const text = program === void 0 ? void 0 : JSON.stringify(program);
83
+ if (text === void 0) return {
84
+ ok: false,
85
+ why: "The program is missing."
86
+ };
87
+ const read = parse(text, DOMAINS);
88
+ return read.ok ? {
89
+ ok: true,
90
+ program: compile(read.value, { domains: DOMAINS })
91
+ } : {
92
+ ok: false,
93
+ why: read.error.message
94
+ };
95
+ }
96
+ /** This function compiles a program that `needProblems` accepts. */
97
+ function programOf(program) {
98
+ const read = readProgram(program);
99
+ if (!read.ok) throw new RangeError(read.why);
100
+ return read.program;
101
+ }
102
+ /**
103
+ * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad
104
+ * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field
105
+ * of a slot is a problem. A program that is not valid is a problem.
106
+ */
107
+ function needProblems(need) {
108
+ const problems = [];
109
+ const twice = (names, what) => {
110
+ const seen = /* @__PURE__ */ new Set();
111
+ for (const name of names) {
112
+ if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);
113
+ seen.add(name);
114
+ }
115
+ };
116
+ twice(need.slots.map((slot) => slot.name), "slots");
117
+ for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);
118
+ for (const slot of need.slots) {
119
+ if (slot.name === "need") problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);
120
+ else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);
121
+ twice(slot.parts.map((part) => part.key), `parts of the slot ${slot.name}`);
122
+ const { min, max } = countOf(slot);
123
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max) 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.`);
124
+ for (const part of slot.parts) for (const name of Object.keys(part.facts ?? {})) if (SLOT_FIELDS.includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);
125
+ else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);
126
+ }
127
+ const measures = need.measures ?? [];
128
+ const rules = need.rules ?? [];
129
+ twice(measures.map((measure) => measure.name), "measures");
130
+ twice(rules.map((rule) => rule.name), "rules");
131
+ for (const measure of measures) {
132
+ if (measure.name === "price") problems.push("A measure has the name price, which is the objective of the cost.");
133
+ if (measure.min !== void 0 && measure.max !== void 0 && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);
134
+ const read = readProgram(measure.program);
135
+ if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);
136
+ }
137
+ for (const rule of rules) {
138
+ const read = readProgram(rule.program);
139
+ if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);
140
+ }
141
+ return problems;
142
+ }
143
+ /**
144
+ * This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the
145
+ * shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.
146
+ */
147
+ function priceOf(observations, count, need) {
148
+ const choice = bestOffer(observations, {
149
+ currency: need.currency,
150
+ count,
151
+ ...need.conditions === void 0 ? {} : { conditions: need.conditions }
152
+ });
153
+ let pick;
154
+ for (const offer of choice.offers) {
155
+ const cost = offer.cost;
156
+ if (offer.inStock && cost !== null && (pick === void 0 || compare(cost, pick.cost) < 0)) pick = {
157
+ ...offer,
158
+ cost
159
+ };
160
+ }
161
+ if (pick !== void 0) return {
162
+ ok: true,
163
+ offerId: pick.observation.offer.id,
164
+ cost: pick.cost
165
+ };
166
+ if (choice.offers.length > 0) return {
167
+ ok: false,
168
+ why: `No offer of ${String(count)} units is in stock with a known cost.`
169
+ };
170
+ const first = choice.skipped[0];
171
+ return {
172
+ ok: false,
173
+ why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
174
+ };
175
+ }
176
+ /**
177
+ * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy
178
+ * 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
179
+ * of the cost of each item.
180
+ *
181
+ * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has
182
+ * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part
183
+ * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.
184
+ *
185
+ * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.
186
+ *
187
+ * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.
188
+ * The function also throws a RangeError when strategy-search refuses the options.
189
+ */
190
+ function planBuys(need, observations, options = {}) {
191
+ const shape = buyNeedSchema.safeParse(need);
192
+ if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(" ")}`);
193
+ const problems = needProblems(need);
194
+ if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(" ")}`);
195
+ const evaluations = options.evaluations ?? 2e3;
196
+ if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);
197
+ const measures = (need.measures ?? []).map((measure) => ({
198
+ measure,
199
+ program: programOf(measure.program)
200
+ }));
201
+ const rules = (need.rules ?? []).map((rule) => ({
202
+ rule,
203
+ program: programOf(rule.program)
204
+ }));
205
+ const objectives = [{
206
+ name: "price",
207
+ goal: "min",
208
+ unit: need.currency
209
+ }, ...measures.flatMap(({ measure }) => measure.goal === void 0 ? [] : [measure.unit === void 0 ? {
210
+ name: measure.name,
211
+ goal: measure.goal
212
+ } : {
213
+ name: measure.name,
214
+ goal: measure.goal,
215
+ unit: measure.unit
216
+ }])];
217
+ const prices = /* @__PURE__ */ new Map();
218
+ const unpriced = [];
219
+ const stages = [];
220
+ let blocked = false;
221
+ for (const slot of need.slots) {
222
+ const { min, max } = countOf(slot);
223
+ const low = Math.max(1, min);
224
+ const params = max > low ? [{
225
+ name: "count",
226
+ kind: "int",
227
+ min: low,
228
+ max,
229
+ default: low
230
+ }] : [];
231
+ const usable = [];
232
+ for (const part of slot.parts) {
233
+ const offers = offersOfPart(observations, part.want);
234
+ const byCount = /* @__PURE__ */ new Map();
235
+ for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));
236
+ prices.set(`${slot.name}\u0000${part.key}`, byCount);
237
+ const first = byCount.get(low);
238
+ if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);
239
+ else unpriced.push({
240
+ slot: slot.name,
241
+ part: part.key,
242
+ why: first === void 0 || first.ok ? "No offer is usable." : first.why
243
+ });
244
+ }
245
+ if (usable.length > 0) stages.push({
246
+ name: slot.name,
247
+ options: usable.map((id) => ({
248
+ id,
249
+ params
250
+ })),
251
+ ...min === 0 ? { optional: true } : {}
252
+ });
253
+ else if (min > 0) blocked = true;
254
+ }
255
+ const none = {
256
+ format: PLAN_FORMAT,
257
+ need: need.id,
258
+ currency: need.currency,
259
+ method: "none",
260
+ seed: null,
261
+ run: null,
262
+ objectives,
263
+ counts: {
264
+ feasible: 0,
265
+ breaks: 0,
266
+ unread: 0,
267
+ front: 0
268
+ },
269
+ front: [],
270
+ breaks: [],
271
+ unpriced
272
+ };
273
+ if (blocked || stages.length === 0) return none;
274
+ const strategySpace = {
275
+ schema: STRATEGY_SPACE_SCHEMA,
276
+ engine: "buy-plan",
277
+ version: "1",
278
+ stages
279
+ };
280
+ const assess = (config) => {
281
+ const breaks = [];
282
+ const items = [];
283
+ const records = { [NEED_KEY]: need.inputs ?? {} };
284
+ for (const slot of need.slots) {
285
+ const choice = config.stages[slot.name] ?? null;
286
+ if (choice === null) {
287
+ records[slot.name] = {
288
+ slot: slot.name,
289
+ count: 0,
290
+ cost: 0
291
+ };
292
+ continue;
293
+ }
294
+ const part = slot.parts.find((each) => each.key === choice.option);
295
+ const count = Number(choice.params?.["count"] ?? Math.max(1, countOf(slot).min));
296
+ const priced = prices.get(`${slot.name}\u0000${part.key}`)?.get(count) ?? {
297
+ ok: false,
298
+ why: `The count ${String(count)} is not a count of the slot.`
299
+ };
300
+ if (!priced.ok) {
301
+ breaks.push({
302
+ name: `price:${slot.name}`,
303
+ why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}`
304
+ });
305
+ records[slot.name] = {
306
+ ...part.facts,
307
+ slot: slot.name,
308
+ part: part.key,
309
+ count,
310
+ cost: 0
311
+ };
312
+ continue;
313
+ }
314
+ items.push({
315
+ slot: slot.name,
316
+ part: part.key,
317
+ count,
318
+ offerId: priced.offerId,
319
+ cost: priced.cost
320
+ });
321
+ records[slot.name] = {
322
+ ...part.facts,
323
+ slot: slot.name,
324
+ part: part.key,
325
+ count,
326
+ cost: valueIn(priced.cost, need.currency)
327
+ };
328
+ }
329
+ const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);
330
+ const values = price === null ? {} : { price: valueIn(price, need.currency) };
331
+ const basket = space.record(records);
332
+ for (const { measure, program } of measures) {
333
+ const result = program.run({
334
+ space: basket,
335
+ origin: NEED_KEY
336
+ });
337
+ if (!result.ok) breaks.push({
338
+ name: `measure:${measure.name}`,
339
+ why: result.error.message
340
+ });
341
+ else if (typeof result.value !== "number" || !Number.isFinite(result.value)) breaks.push({
342
+ name: `measure:${measure.name}`,
343
+ why: `The value ${String(result.value)} is not a finite number.`
344
+ });
345
+ else {
346
+ values[measure.name] = result.value;
347
+ if (measure.min !== void 0 && result.value < measure.min) breaks.push({
348
+ name: `limit:${measure.name}`,
349
+ why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.`
350
+ });
351
+ if (measure.max !== void 0 && result.value > measure.max) breaks.push({
352
+ name: `limit:${measure.name}`,
353
+ why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.`
354
+ });
355
+ }
356
+ }
357
+ for (const { rule, program } of rules) {
358
+ const result = program.run({
359
+ space: basket,
360
+ origin: NEED_KEY
361
+ });
362
+ if (!result.ok) breaks.push({
363
+ name: `rule:${rule.name}`,
364
+ why: result.error.message
365
+ });
366
+ else if (result.value !== true) breaks.push({
367
+ name: `rule:${rule.name}`,
368
+ why: result.value === false ? "The basket breaks the rule." : `The value ${String(result.value)} is not a boolean.`
369
+ });
370
+ }
371
+ return {
372
+ breaks,
373
+ values,
374
+ price,
375
+ items
376
+ };
377
+ };
378
+ const firstWhy = /* @__PURE__ */ new Map();
379
+ const evaluate = (config) => {
380
+ const assessed = assess(config);
381
+ for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);
382
+ return {
383
+ breaks: [...new Set(assessed.breaks.map((each) => each.name))],
384
+ values: assessed.values
385
+ };
386
+ };
387
+ const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));
388
+ const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);
389
+ const evaluator = `buy-need:${need.id}`;
390
+ const run = grid ? sweep(strategySpace, {
391
+ objectives,
392
+ evaluate,
393
+ enumerate: {
394
+ mode: "grid",
395
+ levels,
396
+ limit: evaluations
397
+ },
398
+ evaluator
399
+ }) : evolve(strategySpace, {
400
+ objectives,
401
+ evaluate,
402
+ seed: options.seed ?? need.id,
403
+ evaluations,
404
+ ...options.population === void 0 ? {} : { population: options.population },
405
+ evaluator
406
+ });
407
+ const front = frontOf(run).map(({ row, config }) => {
408
+ const assessed = assess(config);
409
+ const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== "price"));
410
+ return {
411
+ config: row.config,
412
+ price: assessed.price,
413
+ values,
414
+ items: assessed.items
415
+ };
416
+ }).sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));
417
+ return {
418
+ ...none,
419
+ method: grid ? "grid" : "evolve",
420
+ seed: run.seed,
421
+ run: run.run,
422
+ counts: run.counts,
423
+ front,
424
+ breaks: breaksOf(run.rows, firstWhy),
425
+ unpriced
426
+ };
427
+ }
428
+ /** This function counts the rows that break each constraint, in the order of the names. */
429
+ function breaksOf(rows, firstWhy) {
430
+ const counts = /* @__PURE__ */ new Map();
431
+ for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);
432
+ return [...counts.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, count]) => ({
433
+ name,
434
+ count,
435
+ why: firstWhy.get(name) ?? ""
436
+ }));
437
+ }
438
+ export { NEED_FORMAT, NEED_KEY, PLAN_EVALUATIONS, PLAN_FORMAT, SLOT_FIELDS, buyNeedSchema, needProblems, planBuys };
439
+
440
+ //# sourceMappingURL=plan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan.js","names":[],"sources":["../src/plan.ts"],"sourcesContent":["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 { bestOffer, offersOfPart, type Observation, type OfferChoice, type PartWant } 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\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/** The offer to buy for one count of a part, or the reason that no offer is usable. */\ntype Priced = { readonly ok: true; readonly offerId: string; readonly cost: Quantity } | { readonly ok: false; readonly why: string };\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 * This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the\n * shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.\n */\nfunction priceOf(observations: readonly Observation[], count: number, need: BuyNeed): Priced {\n const choice = bestOffer(observations, { currency: need.currency, count, ...(need.conditions === undefined ? {} : { conditions: need.conditions }) });\n let pick: (OfferChoice & { readonly cost: Quantity }) | undefined;\n for (const offer of choice.offers) {\n const cost = offer.cost;\n if (offer.inStock && cost !== null && (pick === undefined || compare(cost, pick.cost) < 0)) pick = { ...offer, cost };\n }\n if (pick !== undefined) return { ok: true, offerId: pick.observation.offer.id, cost: pick.cost };\n if (choice.offers.length > 0) return { ok: false, why: `No offer of ${String(count)} units is in stock with a known cost.` };\n const first = choice.skipped[0];\n return { ok: false, why: first === undefined ? \"No offer matches the part.\" : `No offer is usable. The first offer that the choice skipped: ${first.why}` };\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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