@mark1russell7/market 0.3.3 → 0.3.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/{average-B29bynFb.js → average-BXyKRj8R.js} +5 -26
- package/build/average-BXyKRj8R.js.map +1 -0
- package/build/average-Bj0GkSLo.d.ts.map +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +5 -8
- package/build/index.js.map +1 -1
- package/build/supplies-entry.d.ts.map +1 -1
- package/build/supplies-entry.js +3 -3
- package/build/supplies-entry.js.map +1 -1
- package/package.json +2 -2
- package/build/average-B29bynFb.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as instantSchema, g as sourceSchema, v as textSchema } from "./records-W6sPyhTQ.js";
|
|
2
|
-
import { UnitError, parseUnit } from "@mark1russell7/quantity";
|
|
2
|
+
import { UnitError, atomAbove, parseUnit } from "@mark1russell7/quantity";
|
|
3
3
|
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
// src/average.ts
|
|
@@ -21,7 +21,7 @@ function unitPriceProblem(unit) {
|
|
|
21
21
|
if (error instanceof UnitError) return refused;
|
|
22
22
|
throw error;
|
|
23
23
|
}
|
|
24
|
-
if (
|
|
24
|
+
if (atomAbove(parsed, "money") === void 0) return refused;
|
|
25
25
|
const below = parsed.components.filter((component) => component.exponent < 0);
|
|
26
26
|
const amountOf = (component) => {
|
|
27
27
|
const dimensions = component.atom?.vector;
|
|
@@ -33,32 +33,11 @@ function unitPriceProblem(unit) {
|
|
|
33
33
|
if (below.length === 0 || !below.every(amountOf)) return refused;
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
|
-
* This function gives the symbol of the money of a unit that has one unit of money above, for example `USD` for
|
|
37
|
-
* `USD/wk`. It gives undefined for each other unit, and for a unit that does not parse.
|
|
38
|
-
*
|
|
39
|
-
* This is unit algebra, so its home is `@mark1russell7/quantity`. It stays here, out of the exports of the package,
|
|
40
|
-
* until quantity has it. Then this function goes away.
|
|
41
|
-
*/
|
|
42
|
-
function moneyAbove(unit) {
|
|
43
|
-
let parsed;
|
|
44
|
-
try {
|
|
45
|
-
parsed = parseUnit(unit);
|
|
46
|
-
} catch (error) {
|
|
47
|
-
if (error instanceof UnitError) return void 0;
|
|
48
|
-
throw error;
|
|
49
|
-
}
|
|
50
|
-
const above = parsed.components.filter((component) => component.exponent > 0);
|
|
51
|
-
const [money] = above;
|
|
52
|
-
const vector = money?.atom?.vector;
|
|
53
|
-
const isMoney = vector !== void 0 && Object.keys(vector).length === 1 && vector.money === 1;
|
|
54
|
-
return above.length === 1 && money?.exponent === 1 && money.annotation === void 0 && isMoney ? money.atom?.symbol : void 0;
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
36
|
* This function gives the symbol of the money of a price for each unit of an amount, for example `USD` for `USD/lb`.
|
|
58
37
|
* It gives undefined for each other unit.
|
|
59
38
|
*/
|
|
60
39
|
function moneyOf(unit) {
|
|
61
|
-
return unitPriceProblem(unit) === void 0 ?
|
|
40
|
+
return unitPriceProblem(unit) === void 0 ? atomAbove(unit, "money") : void 0;
|
|
62
41
|
}
|
|
63
42
|
/** This schema accepts a price of more than 0 for each unit of an amount, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
|
|
64
43
|
const unitPriceSchema = quantitySchema(void 0, { positive: true }).superRefine((price, context) => {
|
|
@@ -101,6 +80,6 @@ function latestAverages(prices) {
|
|
|
101
80
|
}
|
|
102
81
|
return [...last.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, price]) => price);
|
|
103
82
|
}
|
|
104
|
-
export {
|
|
83
|
+
export { monthSchema as a, moneyOf as i, averagePriceSchema as n, unitPriceSchema as o, latestAverages as r, averagePriceId as t };
|
|
105
84
|
|
|
106
|
-
//# sourceMappingURL=average-
|
|
85
|
+
//# sourceMappingURL=average-BXyKRj8R.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"average-BXyKRj8R.js","names":[],"sources":["../src/average.ts"],"sourcesContent":["import { atomAbove, parseUnit, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { instantSchema, sourceSchema, textSchema } from \"./records.ts\";\n\n/*\n * This module has the average prices of a market. An average price is not an offer of a seller. It is the mean price\n * of one item in one area and one month, from an official statistic, for example the average prices of the Consumer\n * Price Index. A buyer uses it as the price of a product that has no offer, and as a check of the price of an offer.\n */\n\n/** The average price of one item in one area and one month, from one series of a source. */\nexport interface AveragePrice {\n /** The id `source:series:period`. `averagePriceId` gives it. */\n readonly id: string;\n readonly source: string;\n /** The id of the series in the source, for example `APU0000701312`. */\n readonly series: string;\n /** The item of the series, as the source names it. */\n readonly item: string;\n /** The area of the series, as the source names it, for example `U.S. city average`. */\n readonly area: string;\n /** The month of the price, in the form `YYYY-MM`. */\n readonly period: string;\n /** The price for each unit of the item, for example `{ \"value\": 1.101, \"unit\": \"USD/lb\" }`. */\n readonly price: Quantity;\n /** The instant of the read of the source. */\n readonly at: string;\n /** The footnotes of the source for this price, for example a preliminary value. */\n readonly footnotes?: readonly string[] | undefined;\n}\n\n/** This function gives the id of an average price: the source, the series and the month, with colons. */\nexport function averagePriceId(source: string, series: string, period: string): string {\n return `${source}:${series}:${period}`;\n}\n\n/**\n * This function reads the unit of a price for each unit of an amount of an item. The unit has one unit of money\n * above. Below, it has a unit of an amount that is not money and not a pure time, for example `USD/lb`, `USD/L` or `USD/kWh`.\n * A count below must have an annotation, for example `USD/{each}`. Thus `USD/%` and `USD/h` are not prices of an item.\n */\nfunction unitPriceProblem(unit: string): string | undefined {\n const refused = `The unit ${unit} is not a price for each unit of an amount, for example USD/lb.`;\n let parsed: ReturnType<typeof parseUnit>;\n try {\n parsed = parseUnit(unit);\n } catch (error) {\n if (error instanceof UnitError) return refused;\n throw error;\n }\n if (atomAbove(parsed, \"money\") === undefined) return refused;\n const below = parsed.components.filter((component) => component.exponent < 0);\n const amountOf = (component: (typeof below)[number]): boolean => {\n const dimensions = component.atom?.vector;\n if (dimensions === undefined) return component.annotation !== undefined;\n const names = Object.keys(dimensions);\n const pureTime = names.length === 1 && names[0] === \"time\";\n return names.length > 0 && !names.includes(\"money\") && !pureTime;\n };\n if (below.length === 0 || !below.every(amountOf)) return refused;\n return undefined;\n}\n\n/**\n * This function gives the symbol of the money of a price for each unit of an amount, for example `USD` for `USD/lb`.\n * It gives undefined for each other unit.\n */\nexport function moneyOf(unit: string): string | undefined {\n return unitPriceProblem(unit) === undefined ? atomAbove(unit, \"money\") : undefined;\n}\n\n/** This schema accepts a price of more than 0 for each unit of an amount, for example `{ \"value\": 1.101, \"unit\": \"USD/lb\" }`. */\nexport const unitPriceSchema: z.ZodType<Quantity, Quantity> = quantitySchema(undefined, { positive: true }).superRefine((price, context) => {\n const problem = unitPriceProblem(price.unit);\n if (problem !== undefined) context.addIssue({ code: \"custom\", message: problem });\n});\n\n/** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */\nexport const monthSchema: z.ZodType<string> = z.string().regex(/^(?!0000)\\d{4}-(0[1-9]|1[0-2])$/, \"The month is not in the form YYYY-MM.\");\n\n/** This schema accepts an average price. Its id must be the id of its source, its series and its month. */\nexport const averagePriceSchema: z.ZodType<AveragePrice> = z\n .strictObject({\n id: textSchema,\n source: sourceSchema,\n series: textSchema,\n item: textSchema,\n area: textSchema,\n period: monthSchema,\n price: unitPriceSchema,\n at: instantSchema,\n footnotes: z.array(textSchema).optional(),\n })\n .refine((record) => record.id === averagePriceId(record.source, record.series, record.period), {\n message: \"The id is not the id of the source, the series and the month.\",\n path: [\"id\"],\n });\n\n/**\n * This function gives the last average price of each series, by its month. A later read of the same month replaces\n * an earlier one, because a source can revise a value.\n *\n * @param prices - The average prices, from one or more reads\n * @returns One price for each series, in the order of the series ids\n */\nexport function latestAverages(prices: readonly AveragePrice[]): readonly AveragePrice[] {\n const last = new Map<string, AveragePrice>();\n for (const price of prices) {\n const key = `${price.source}:${price.series}`;\n const held = last.get(key);\n if (held === undefined || price.period > held.period || (price.period === held.period && price.at > held.at)) last.set(key, price);\n }\n return [...last.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, price]) => price);\n}\n"],"mappings":";;;;;;AAiCA,SAAgB,eAAe,QAAgB,QAAgB,QAAwB;CACrF,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG;AAChC;;;;;;AAOA,SAAS,iBAAiB,MAAkC;CAC1D,MAAM,UAAU,YAAY,KAAK;CACjC,IAAI;CACJ,IAAI;EACF,SAAS,UAAU,IAAI;CACzB,SAAS,OAAO;EACd,IAAI,iBAAiB,WAAW,OAAO;EACvC,MAAM;CACR;CACA,IAAI,UAAU,QAAQ,OAAO,MAAM,KAAA,GAAW,OAAO;CACrD,MAAM,QAAQ,OAAO,WAAW,QAAQ,cAAc,UAAU,WAAW,CAAC;CAC5E,MAAM,YAAY,cAA+C;EAC/D,MAAM,aAAa,UAAU,MAAM;EACnC,IAAI,eAAe,KAAA,GAAW,OAAO,UAAU,eAAe,KAAA;EAC9D,MAAM,QAAQ,OAAO,KAAK,UAAU;EACpC,MAAM,WAAW,MAAM,WAAW,KAAK,MAAM,OAAO;EACpD,OAAO,MAAM,SAAS,KAAK,CAAC,MAAM,SAAS,OAAO,KAAK,CAAC;CAC1D;CACA,IAAI,MAAM,WAAW,KAAK,CAAC,MAAM,MAAM,QAAQ,GAAG,OAAO;AAE3D;;;;;AAMA,SAAgB,QAAQ,MAAkC;CACxD,OAAO,iBAAiB,IAAI,MAAM,KAAA,IAAY,UAAU,MAAM,OAAO,IAAI,KAAA;AAC3E;;AAGA,MAAa,kBAAiD,eAAe,KAAA,GAAW,EAAE,UAAU,KAAK,CAAC,CAAC,CAAC,aAAa,OAAO,YAAY;CAC1I,MAAM,UAAU,iBAAiB,MAAM,IAAI;CAC3C,IAAI,YAAY,KAAA,GAAW,QAAQ,SAAS;EAAE,MAAM;EAAU,SAAS;CAAQ,CAAC;AAClF,CAAC;;AAGD,MAAa,cAAiC,EAAE,OAAO,CAAC,CAAC,MAAM,mCAAmC,uCAAuC;;AAGzI,MAAa,qBAA8C,EACxD,aAAa;CACZ,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,MAAM;CACN,MAAM;CACN,QAAQ;CACR,OAAO;CACP,IAAI;CACJ,WAAW,EAAE,MAAM,UAAU,CAAC,CAAC,SAAS;AAC1C,CAAC,CAAC,CACD,QAAQ,WAAW,OAAO,OAAO,eAAe,OAAO,QAAQ,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC7F,SAAS;CACT,MAAM,CAAC,IAAI;AACb,CAAC;;;;;;;;AASH,SAAgB,eAAe,QAA0D;CACvF,MAAM,uBAAO,IAAI,IAA0B;CAC3C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,GAAG,MAAM,OAAO,GAAG,MAAM;EACrC,MAAM,OAAO,KAAK,IAAI,GAAG;EACzB,IAAI,SAAS,KAAA,KAAa,MAAM,SAAS,KAAK,UAAW,MAAM,WAAW,KAAK,UAAU,MAAM,KAAK,KAAK,IAAK,KAAK,IAAI,KAAK,KAAK;CACnI;CACA,OAAO,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAAC,KAAK,GAAG,WAAW,KAAK;AACtG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"average-Bj0GkSLo.d.ts","names":[],"sources":["../src/average.ts"],"mappings":";;;UAYiB;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,OAAO;;WAEP;;WAEA;;;iBAIK,eAAe,gBAAgB,gBAAgB;;
|
|
1
|
+
{"version":3,"file":"average-Bj0GkSLo.d.ts","names":[],"sources":["../src/average.ts"],"mappings":";;;UAYiB;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,OAAO;;WAEP;;WAEA;;;iBAIK,eAAe,gBAAgB,gBAAgB;;cAwClD,iBAAiB,EAAE,QAAQ,UAAU;;cAMrC,aAAa,EAAE;;cAGf,oBAAoB,EAAE,QAAQ;;;;;;;;iBAwB3B,eAAe,iBAAiB,0BAA0B"}
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/gtin.ts","../src/metered.ts","../src/price.ts"],"mappings":";;;;;;;;;;;;;KAMY;WACG;;WACA;WAA0B,KAAK;;WAC/B;;;UAGE;WACN;WACA,WAAW;WACX;WACA;WACA;;;;;;qBAOE,iBAAiB,EAAE,QAAQ;;;;;qBAU3B,mBAAmB,EAAE,QAAQ;;;;;wBAY1B,UAAU,OAAO,aAAa;WAAoB;;;;;;wBAalD,OAAO,OAAO,aAAa;WAAoB;GAAc,aAAa;;wBAW1E,eAAe,OAAO;;wBAKtB,aAAa,OAAO;;qBC7DvB;;qBAGA,mBAAmB,EAAE,QAAQ;;UAKzB;WACN;WACA;WACA,uBAAuB;;;UAIjB;WACN,eAAe;WACf;WACA,gBAAgB;;;qBAId,iBAAiB,EAAE,QAAQ;;qBAO3B,aAAa,EAAE,QAAQ;;UAOnB;WACN;WACA;;;UAIM;;WAEN,gBAAgB;;WAEhB;;WAEA;;;UAIM;;WAEN,eAAe;;WAEf,kBAAkB;;;;;;;;;;;wBAyBb,iBAAiB,uBAAuB,eAAe,SAAS,cAAc;;UA0B7E,sBAAsB;;WAE5B;;;UAIM,kBAAkB;WACxB;;;UAIM;WACN,OAAO;WACP,kBAAkB;;;;;;;;;;wBAab,YAAY,OAAO,OAAO,SAAS,eAAe,OAAO,YAAY;;;;;wBAwBrE,kBAAkB,OAAO,OAAO,SAAS,cAAc;;wBAKvD,UAAU,OAAO,QAAQ;;UAKxB;;WAEN;;WAEA;;WAEA,OAA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;;qBA4CvB,sBAAsB,EAAE,QAAQ;;qBAchC,0BAA0B,EAAE,QAAQ;;;;;;;;;;;;wBAqFjC,YAAY,aAAa,oBAAoB,OAAO,cAAc,UAAS,qBAA0B;;;;;;;wBCnarG,aAAa,SAAS,cAAc,gBAAgB;;;;;;;wBAgBpD,OAAO,SAAS,cAAc,gBAAgB"}
|
package/build/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as averagePriceSchema, o as
|
|
1
|
+
import { a as monthSchema, n as averagePriceSchema, o as unitPriceSchema, r as latestAverages, t as averagePriceId } from "./average-BXyKRj8R.js";
|
|
2
2
|
import { c as foldCode, i as offersPart, l as matchKeys, n as latestObservations, o as costOf, r as offersOfPart, s as unitPriceFor, t as bestOffer } from "./offers-h_HvMkH_.js";
|
|
3
3
|
import { _ as specSchema, a as instantSchema, b as parseGtin, c as offerSchema, d as priceReadingSchema, f as productSchema, g as sourceSchema, h as sourceOfOffer, i as gtinSchema, l as partNumberSchema, m as shippingSchema, n as CONDITIONS, o as moneySchema, p as sellerSchema, r as FORMATS, s as offerId, t as AVAILABILITIES, u as priceBreakSchema, v as textSchema, y as gtinCheckDigit } from "./records-W6sPyhTQ.js";
|
|
4
|
-
import { UnitError, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
|
|
4
|
+
import { UnitError, atomAbove, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
|
|
5
5
|
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
// src/terms.ts
|
|
@@ -323,16 +323,13 @@ function readPriceUnit(unit) {
|
|
|
323
323
|
if (error instanceof UnitError) return refused;
|
|
324
324
|
throw error;
|
|
325
325
|
}
|
|
326
|
-
const
|
|
327
|
-
const [money] = above;
|
|
328
|
-
const atom = money?.atom;
|
|
329
|
-
const isMoney = atom !== void 0 && Object.keys(atom.vector).length === 1 && atom.vector.money === 1;
|
|
326
|
+
const money = atomAbove(parsed, "money");
|
|
330
327
|
const below = parsed.components.some((component) => component.exponent < 0);
|
|
331
|
-
if (
|
|
328
|
+
if (money === void 0 || !below) return refused;
|
|
332
329
|
const { money: units = 0, data = 0, time = 0, ...others } = parsed.vector;
|
|
333
330
|
const kind = Object.values(others).every((exponent) => exponent === 0) && units === 1 ? kindOfExponents(-data, -time) : void 0;
|
|
334
331
|
return kind === void 0 ? refused : {
|
|
335
|
-
money
|
|
332
|
+
money,
|
|
336
333
|
kind
|
|
337
334
|
};
|
|
338
335
|
}
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/metered.ts"],"sourcesContent":["import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { sourceSchema, textSchema } from \"./records.ts\";\n\n/** The storage rule of a source, from its terms. */\nexport type Retention =\n | { readonly kind: \"keep\" }\n | { readonly kind: \"max-age\"; readonly age: Quantity }\n | { readonly kind: \"no-store\" };\n\n/** The rules of the terms of one source. */\nexport interface SourceTerms {\n readonly source: string;\n readonly retention: Retention;\n readonly deleteWhenEnded: boolean;\n readonly priceModel: boolean;\n readonly clause: string;\n}\n\n/**\n * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the\n * time. With `max-age`, a store keeps a reading for `age` at most. With `no-store`, a reading serves one request.\n */\nexport const retentionSchema: z.ZodType<Retention> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"keep\") }),\n z.strictObject({ kind: z.literal(\"max-age\"), age: quantitySchema(\"time\", { positive: true }) }),\n z.strictObject({ kind: z.literal(\"no-store\") }),\n]);\n\n/**\n * This schema accepts the rules of the terms of one source. `deleteWhenEnded` deletes the readings of an offer\n * when the offer ends. `priceModel` permits a trend or a forecast of prices. `clause` names the text of the terms.\n */\nexport const sourceTermsSchema: z.ZodType<SourceTerms> = z.strictObject({\n source: sourceSchema,\n retention: retentionSchema,\n deleteWhenEnded: z.boolean(),\n priceModel: z.boolean(),\n clause: textSchema,\n});\n\n/**\n * This function gives the last instant at which a store keeps a reading, or null when the terms set no\n * limit. For a source with `no-store`, the instant is the instant of the reading.\n */\nexport function keepUntil(terms: SourceTerms, reading: { readonly at: string }): string | null {\n const { retention } = terms;\n if (retention.kind === \"keep\") return null;\n const at = Date.parse(reading.at);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(reading.at)} is not an instant.`);\n if (retention.kind === \"no-store\") return new Date(at).toISOString();\n return new Date(at + Math.floor(valueIn(retention.age, \"ms\"))).toISOString();\n}\n\n/**\n * This function tells if a store keeps a reading at the instant `now`. A store keeps no reading of a source with\n * `no-store`, and no reading of an ended offer when the terms delete them.\n */\nexport function isKept(terms: SourceTerms, reading: { readonly at: string }, now: string, ended = false): boolean {\n if (ended && terms.deleteWhenEnded) return false;\n if (terms.retention.kind === \"no-store\") return false;\n const until = keepUntil(terms, reading);\n if (until === null) return true;\n const instant = Date.parse(now);\n if (Number.isNaN(instant)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n return instant <= Date.parse(until);\n}\n\n/** This function tells if the terms permit a stored history of the readings of a source. */\nexport function permitsHistory(terms: SourceTerms): boolean {\n return terms.retention.kind === \"keep\" && !terms.deleteWhenEnded;\n}\n\n/** This function tells if the terms permit a trend of the prices of a source: a history and a model of prices. */\nexport function permitsTrend(terms: SourceTerms): boolean {\n return permitsHistory(terms) && terms.priceModel;\n}\n","import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { latestObservations, type Observation } from \"./offers.ts\";\nimport { instantSchema, offerSchema, priceReadingSchema, sourceSchema, textSchema } from \"./records.ts\";\nimport { isKept, keepUntil, type SourceTerms } from \"./terms.ts\";\n\n/*\n * This module calculates a board of current prices. A watch reads its sources on a schedule. The board keeps the\n * last read of each entry of the watch, within the terms of each source. Each function of this module is a\n * calculation with no effect. A host does the reads and writes the board.\n */\n\n/** The format name of a board record. */\nexport const BOARD_FORMAT = \"price-board/1\";\n\n/** This schema accepts an observation: an offer, and a reading of that offer. */\nexport const observationSchema: z.ZodType<Observation> = z\n .strictObject({ offer: offerSchema, reading: priceReadingSchema })\n .refine((each) => each.reading.offerId === each.offer.id, { message: \"The reading is not a reading of the offer.\" });\n\n/** This record is the last read of one entry of a watch: the name of the entry, the instant, and the observations. */\nexport interface BoardRead {\n readonly name: string;\n readonly at: string;\n readonly observations: readonly Observation[];\n}\n\n/** This record is a board: the instant of its last settle, and the last read of each entry, in the order of the names. */\nexport interface Board {\n readonly format: typeof BOARD_FORMAT;\n readonly at: string;\n readonly reads: readonly BoardRead[];\n}\n\n/** This schema accepts the read of an entry. The read has one observation of each offer at most. */\nexport const boardReadSchema: z.ZodType<BoardRead> = z\n .strictObject({ name: textSchema, at: instantSchema, observations: z.array(observationSchema) })\n .refine((read) => new Set(read.observations.map((each) => each.offer.id)).size === read.observations.length, {\n message: \"The read has two observations of one offer.\",\n });\n\n/** This schema accepts a board. The board has one read of each entry at most. */\nexport const boardSchema: z.ZodType<Board> = z\n .strictObject({ format: z.literal(BOARD_FORMAT), at: instantSchema, reads: z.array(boardReadSchema) })\n .refine((board) => new Set(board.reads.map((each) => each.name)).size === board.reads.length, {\n message: \"The board has two reads of one entry.\",\n });\n\n/** This record is an offer that the store does not keep, with the reason. */\nexport interface Dropped {\n readonly offerId: string;\n readonly why: string;\n}\n\n/** These options give the rules of a store: the terms of each source, the instant, and the offers that ended. */\nexport interface KeepOptions {\n /** The terms of the sources. A store keeps no reading of a source without terms. */\n readonly terms: readonly SourceTerms[];\n /** The instant of the decision. */\n readonly now: string;\n /** The ids of the offers that ended, as their sources tell. An offer with `endsAt` at or before `now` also ended. */\n readonly ended?: readonly string[] | undefined;\n}\n\n/** This record is the decision of a store: the observations that it keeps, and each offer that it drops. */\nexport interface Kept {\n /** The latest observation of each kept offer, in the order of the offer ids. */\n readonly kept: readonly Observation[];\n /** Each dropped offer, in the order of the offer ids. */\n readonly dropped: readonly Dropped[];\n}\n\n/** This function gives the terms of each source by its name. Two terms of one source are a problem of the input. */\nfunction termsBySource(terms: readonly SourceTerms[]): ReadonlyMap<string, SourceTerms> {\n const map = new Map<string, SourceTerms>();\n for (const each of terms) {\n if (map.has(each.source)) throw new RangeError(`The terms of the source ${each.source} are in the list two times.`);\n map.set(each.source, each);\n }\n return map;\n}\n\n/** This function gives the text of an amount of time, for example `6 h`. */\nconst timeText = (age: Quantity): string => `${age.value} ${age.unit}`;\n\n/**\n * This function decides which observations a store keeps. It takes the latest observation of each offer. It keeps\n * an observation while the terms of its source permit it, and while its offer has not ended. A current price is\n * a price that a buyer can pay, so the store drops an ended offer for each source.\n *\n * `settleBoard` applies this function to each read of a board.\n *\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function keepObservations(observations: readonly Observation[], options: KeepOptions): Kept {\n const terms = termsBySource(options.terms);\n const now = Date.parse(options.now);\n if (Number.isNaN(now)) throw new RangeError(`The instant ${JSON.stringify(options.now)} is not an instant.`);\n const ended = new Set(options.ended ?? []);\n const kept: Observation[] = [];\n const dropped: Dropped[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const rules = terms.get(offer.source);\n const endsAt = offer.endsAt === undefined ? Number.NaN : Date.parse(offer.endsAt);\n const over = ended.has(offer.id) || endsAt <= now;\n if (rules === undefined) dropped.push({ offerId: offer.id, why: `The terms of the source ${offer.source} are not known, so a store keeps no reading of it.` });\n else if (rules.retention.kind === \"no-store\") dropped.push({ offerId: offer.id, why: `The terms of ${offer.source} permit no store: a reading serves one request.` });\n else if (over) {\n const rule = rules.deleteWhenEnded ? `, and the terms of ${offer.source} delete its readings` : \"\";\n dropped.push({ offerId: offer.id, why: `The offer ended${rule}.` });\n } else if (!isKept(rules, reading, options.now)) {\n const age = rules.retention.kind === \"max-age\" ? timeText(rules.retention.age) : \"\";\n dropped.push({ offerId: offer.id, why: `The reading of ${reading.at} passed the limit of ${age} of the terms of ${offer.source} at ${keepUntil(rules, reading)}.` });\n } else kept.push(observation);\n }\n return { kept, dropped };\n}\n\n/** These options give the rules of a settle: the rules of a store, and the names of the entries of the watch. */\nexport interface SettleOptions extends KeepOptions {\n /** The names of the entries of the watch. The board drops the read of each other name. With no list, it keeps each read. */\n readonly names?: readonly string[] | undefined;\n}\n\n/** This record is an offer that the board drops, with the name of the entry of its read. */\nexport interface BoardDrop extends Dropped {\n readonly entry: string;\n}\n\n/** This record is the result of a settle: the new board, and each offer that it dropped. */\nexport interface Settled {\n readonly board: Board;\n readonly dropped: readonly BoardDrop[];\n}\n\nconst byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/**\n * This function settles a board at `now`. A new read replaces the last read of its entry, so an offer that the new\n * read does not give leaves the read. Then `keepObservations` applies the terms to each read. The board drops the\n * read of an entry that the watch does not have. Write the new board in place of the old board.\n *\n * @param read - A new read of an entry, or none to settle the board alone\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function settleBoard(board: Board, options: SettleOptions, read?: BoardRead): Settled {\n const names = options.names === undefined ? undefined : new Set(options.names);\n const reads = new Map(board.reads.map((each) => [each.name, each]));\n if (read !== undefined) reads.set(read.name, read);\n const settled: BoardRead[] = [];\n const dropped: BoardDrop[] = [];\n for (const name of [...reads.keys()].sort(byText)) {\n const each = reads.get(name);\n if (each === undefined) continue;\n if (names !== undefined && !names.has(name)) {\n for (const gone of latestObservations(each.observations)) dropped.push({ entry: name, offerId: gone.offer.id, why: `The watch has no entry ${name}.` });\n continue;\n }\n const decision = keepObservations(each.observations, options);\n settled.push({ name, at: each.at, observations: decision.kept });\n for (const drop of decision.dropped) dropped.push({ entry: name, ...drop });\n }\n return { board: { format: BOARD_FORMAT, at: options.now, reads: settled }, dropped };\n}\n\n/**\n * This function gives the current observations of a board at `now`. Each is the latest observation of an offer over\n * the reads, while the terms of its source permit it. Give them to `offersOfPart` and `bestOffer`.\n */\nexport function boardObservations(board: Board, options: KeepOptions): Observation[] {\n return [...keepObservations(board.reads.flatMap((each) => each.observations), options).kept];\n}\n\n/** This function gives the instant of the last read of each entry of a board, by name, for `planReads`. */\nexport function lastReads(board: Board): Record<string, string> {\n return Object.fromEntries(board.reads.map((each) => [each.name, each.at]));\n}\n\n/** This record is one entry of a watch: a read of one source that repeats. */\nexport interface WatchEntry {\n /** The name of the entry. Each entry of a watch has its own name. */\n readonly name: string;\n /** The source of the read. */\n readonly source: string;\n /** The time from one read of the entry to the next, a time of `@mark1russell7/quantity`. */\n readonly every: Quantity;\n}\n\n/** This schema accepts an entry of a watch. */\nexport const watchEntrySchema: z.ZodType<WatchEntry> = z.strictObject({\n name: textSchema,\n source: sourceSchema,\n every: quantitySchema(\"time\", { positive: true }),\n});\n\n/** These options give the rules of a schedule: the terms of each source, and the slack of the loop. */\nexport interface ScheduleOptions {\n /** The terms of the sources. */\n readonly terms: readonly SourceTerms[];\n /**\n * The longest time from the instant of a due read to the instant that its reading is on the board. It is the\n * time between two passes of the loop, plus the longest pass.\n */\n readonly slack: Quantity;\n}\n\n/** This record is the interval of an entry, in milliseconds, or the reason that the entry has no interval. */\nexport type ReadInterval = { readonly ok: true; readonly ms: number } | { readonly ok: false; readonly why: string };\n\n/**\n * This function gives the time from one read of an entry to the next, in milliseconds. A reading of a source with\n * the limit `L` stays on the board until `L` after the read. The next reading arrives `slack` after the next read\n * is due, at most. Thus the interval is the shorter of `every` and `L - slack`. Then the board has a current\n * reading of the entry at each instant after its first read.\n */\nexport function readInterval(entry: WatchEntry, options: ScheduleOptions): ReadInterval {\n const terms = termsBySource(options.terms).get(entry.source);\n const every = valueIn(entry.every, \"ms\");\n if (!(every > 0)) return { ok: false, why: `The time every of the entry ${entry.name} is not more than 0.` };\n if (terms === undefined) return { ok: false, why: `The terms of the source ${entry.source} of the entry ${entry.name} are not known.` };\n const { retention } = terms;\n if (retention.kind === \"no-store\") return { ok: false, why: `The terms of ${entry.source} permit no store, so a watch cannot keep the prices of the entry ${entry.name}. Read the source for each request.` };\n if (retention.kind === \"keep\") return { ok: true, ms: every };\n const room = valueIn(retention.age, \"ms\") - valueIn(options.slack, \"ms\");\n if (!(room > 0)) return { ok: false, why: `The slack ${timeText(options.slack)} is not less than the limit ${timeText(retention.age)} of the terms of ${entry.source}, so the board has gaps in the prices of the entry ${entry.name}.` };\n return { ok: true, ms: Math.min(every, room) };\n}\n\n/** This function gives the problems of a watch: an entry with no interval, and two entries with one name. */\nexport function watchProblems(entries: readonly WatchEntry[], options: ScheduleOptions): string[] {\n const problems: string[] = [];\n const names = new Set<string>();\n for (const entry of entries) {\n if (names.has(entry.name)) problems.push(`Two entries have the name ${entry.name}.`);\n names.add(entry.name);\n const interval = readInterval(entry, options);\n if (!interval.ok) problems.push(interval.why);\n }\n return problems;\n}\n\n/** This record is the plan of one pass of a watch: the due entries, and the instant of the next due read. */\nexport interface ReadPlan {\n /** The names of the due entries, in the order of the entries. An entry with no read is due. */\n readonly due: readonly string[];\n /**\n * The names of the due entries, the entry that is due for the longest time first. An entry with no read comes\n * first. Entries that became due at the same instant keep the order of the entries. Read the entries in this order.\n * Then each due entry comes before the next read of a later due entry.\n */\n readonly queue: readonly string[];\n /** The first instant after `now` that an entry is due, or null when no entry has an interval. */\n readonly next: string | null;\n}\n\n/**\n * This function plans one pass of a watch. An entry is due when it has no last read, or when its interval has\n * passed since its last read. An entry with no interval is not due at any time. `watchProblems` gives its reason.\n *\n * @param last - The instant of the last read of each entry, by name\n * @throws RangeError when `now` or a last read is not an instant.\n */\nexport function planReads(entries: readonly WatchEntry[], last: Readonly<Record<string, string>>, now: string, options: ScheduleOptions): ReadPlan {\n const at = Date.parse(now);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n const due: string[] = [];\n const since: { readonly name: string; readonly at: number }[] = [];\n let next = Number.POSITIVE_INFINITY;\n for (const entry of entries) {\n const interval = readInterval(entry, options);\n if (!interval.ok) continue;\n const before = Object.hasOwn(last, entry.name) ? last[entry.name] : undefined;\n const read = before === undefined ? Number.NaN : Date.parse(before);\n if (before !== undefined && Number.isNaN(read)) throw new RangeError(`The last read ${JSON.stringify(before)} of the entry ${entry.name} is not an instant.`);\n const isDue = Number.isNaN(read) || read + interval.ms <= at;\n if (isDue) {\n due.push(entry.name);\n since.push({ name: entry.name, at: Number.isNaN(read) ? Number.NEGATIVE_INFINITY : read + interval.ms });\n }\n // A planned read happens at `now`, so the next read of a due entry is one interval after `now`.\n next = Math.min(next, (isDue ? at : read) + interval.ms);\n }\n // The sort of an array is stable, so equal instants keep the order of the entries.\n const queue = since.sort((a, b) => a.at - b.at).map((each) => each.name);\n return { due, queue, next: Number.isFinite(next) ? new Date(next).toISOString() : null };\n}\n","import {\n canonicalUnit,\n convertExact,\n convertible,\n parseUnit,\n quantity,\n rationals,\n UnitError,\n type Quantity,\n type Rational,\n} from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { instantSchema, moneySchema, offerId, sourceSchema, specSchema, textSchema, type Spec } from \"./records.ts\";\n\n/*\n * This module has the metered prices of a market. A provider meters an amount, for example the hours of a machine,\n * the stored data of each month, the data that goes out, or the requests. A metered price is a price for each unit\n * of that amount, in tiers, with a free amount for each billing period and a term.\n */\n\n/**\n * The kinds of a metered amount: a time (the hours of a machine), data times time (stored data), data (a transfer)\n * and a count (requests).\n */\nexport const METERED_KINDS = [\"time\", \"data-time\", \"data\", \"count\"] as const;\n/** The kind of a metered amount. */\nexport type MeteredKind = (typeof METERED_KINDS)[number];\n\n/**\n * The scopes of a free amount. With `account`, all the usage of the account in all regions shares one free amount.\n * With `region`, each region has its own free amount. With `resource`, each resource has its own free amount.\n */\nexport const FREE_SCOPES = [\"account\", \"region\", \"resource\"] as const;\n/** The scope of a free amount: the usage that shares it. */\nexport type FreeScope = (typeof FREE_SCOPES)[number];\n\n/** The location of a metered offer: the provider, and its region and zone, as the provider names them. */\nexport interface Location {\n readonly provider: string;\n readonly region: string;\n readonly zone?: string | undefined;\n}\n\n/**\n * The term of a metered price. A `spot` price is also a preemptible price: the provider can end the use at any time,\n * after the `notice`. A `committed` price binds the buyer for its `length`.\n */\nexport type PriceTerm =\n | { readonly kind: \"on-demand\" }\n | { readonly kind: \"spot\"; readonly notice?: Quantity | undefined }\n | { readonly kind: \"committed\"; readonly length: Quantity };\n\n/** A metered offer: one resource of a provider in one location, on one term, with the identifiers that the source gives. */\nexport interface MeteredOffer {\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 location: Location;\n readonly term: PriceTerm;\n readonly specs: readonly Spec[];\n}\n\n/** A tier of a meter: the price for each unit of the usage from `from` to the start of the next tier, in one period. */\nexport interface Tier {\n readonly from: Quantity;\n readonly unitPrice: Quantity;\n}\n\n/** A free amount of a meter for each period, and the scope that shares it. */\nexport interface FreeAmount {\n readonly amount: Quantity;\n readonly scope: FreeScope;\n}\n\n/** A meter of a metered reading: the tiers of the price of one metered amount, and its free amount. */\nexport interface Meter {\n readonly name: string;\n readonly tiers: readonly Tier[];\n readonly free?: FreeAmount | undefined;\n}\n\n/** A metered reading: the metered prices of one offer at one instant. */\nexport interface MeteredReading {\n readonly offerId: string;\n readonly at: string;\n readonly period: Quantity;\n readonly meters: readonly Meter[];\n readonly upfront?: Quantity | undefined;\n}\n\n/** One metered offer of a source, and its metered reading at one instant. */\nexport interface MeteredObservation {\n readonly offer: MeteredOffer;\n readonly reading: MeteredReading;\n}\n\n/** The usage of each meter in one period, by the name of the meter. */\nexport type MeteredUsage = Readonly<Record<string, Quantity>>;\n\n/** These options change the cost of a metered offer. */\nexport interface MeteredCostOptions {\n /**\n * The part of the free amount of each meter that other usage in its scope used in the same period. The keys are\n * the names of the meters. The default is none.\n */\n readonly freeUsed?: MeteredUsage | undefined;\n}\n\n/** The cost of the usage of one meter in one period. */\nexport interface MeterCost {\n readonly name: string;\n readonly cost: Quantity;\n}\n\n/** The cost of a metered offer for one period. */\nexport interface MeteredCost {\n /** The cost of each meter, in the order of the meters of the reading. */\n readonly meters: readonly MeterCost[];\n /** The part of the upfront money of a committed term for one period, or zero. */\n readonly upfront: Quantity;\n /** The sum of the cost of each meter and the part of the upfront money. */\n readonly total: Quantity;\n}\n\n/** The parts of the unit of a metered price: its unit of money, and the kind of its metered amount. */\ninterface PriceParts {\n readonly money: string;\n readonly kind: MeteredKind;\n}\n\n/** This function gives the kind of a metered amount from the exponents of its data and its time, or undefined. */\nfunction kindOfExponents(data: number, time: number): MeteredKind | undefined {\n if (data === 0 && time === 0) return \"count\";\n if (data === 0 && time === 1) return \"time\";\n if (data === 1 && time === 0) return \"data\";\n if (data === 1 && time === 1) return \"data-time\";\n return undefined;\n}\n\n/** This function reads the unit of a metered price. It gives the parts of the unit, or the problem as a text. */\nfunction readPriceUnit(unit: string): PriceParts | string {\n const refused = `The unit ${unit} is not a price for each unit of a metered amount, for example USD/h.`;\n let parsed: ReturnType<typeof parseUnit>;\n try {\n parsed = parseUnit(unit);\n } catch (error) {\n if (error instanceof UnitError) return refused;\n throw error;\n }\n const above = parsed.components.filter((component) => component.exponent > 0);\n const [money] = above;\n const atom = money?.atom;\n const isMoney = atom !== undefined && Object.keys(atom.vector).length === 1 && atom.vector.money === 1;\n const below = parsed.components.some((component) => component.exponent < 0);\n if (above.length !== 1 || money?.exponent !== 1 || money.annotation !== undefined || !isMoney || !below) return refused;\n const { money: units = 0, data = 0, time = 0, ...others } = parsed.vector;\n const kind = Object.values(others).every((exponent) => exponent === 0) && units === 1 ? kindOfExponents(-data, -time) : undefined;\n return kind === undefined ? refused : { money: atom.symbol, kind };\n}\n\n/** This function gives the unit of a price for each unit of an amount, for example `USD/(GiB·mo)` for `GiB·mo`. */\nfunction priceUnitFor(money: string, amountUnit: string): string | undefined {\n try {\n return canonicalUnit(`${money}/${amountUnit}`);\n } catch (error) {\n if (error instanceof UnitError) return undefined;\n throw error;\n }\n}\n\n/** This function tells if an amount in one unit converts to another unit. A unit that the quantity package does not know does not convert. */\nfunction converts(from: string, to: string): boolean {\n try {\n return convertible(from, to);\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** This function gives the start of each tier in one unit, or undefined when a start does not convert to it. */\nfunction startsOf(tiers: readonly Tier[], unit: string): Rational[] | undefined {\n try {\n return tiers.map((tier) => convertExact(rationals.fromNumber(tier.from.value), tier.from.unit, unit));\n } catch (error) {\n if (error instanceof UnitError || error instanceof RangeError) return undefined;\n throw error;\n }\n}\n\n/** This function tells if a unit of an amount measures the metered amount of a unit of price. */\nfunction measures(amountUnit: string, priceUnit: string, money: string): boolean {\n const unit = priceUnitFor(money, amountUnit);\n return unit !== undefined && converts(unit, priceUnit);\n}\n\n/**\n * This function gives the kind of the metered amount of the unit of a metered price, for example `time` for `USD/h`\n * and `data-time` for `USD/(GiB·mo)`.\n *\n * @throws RangeError when the unit is not a price for each unit of a metered amount.\n */\nexport function meteredKindOf(unit: string): MeteredKind {\n const parts = readPriceUnit(unit);\n if (typeof parts === \"string\") throw new RangeError(parts);\n return parts.kind;\n}\n\n/**\n * This schema accepts the location of a metered offer. The name of the provider has small letters, digits and\n * hyphens, as the name of a source. The region and the zone are the ids of the provider.\n */\nexport const locationSchema: z.ZodType<Location> = z.strictObject({\n provider: sourceSchema,\n region: textSchema,\n zone: textSchema.optional(),\n});\n\n/**\n * This schema accepts the term of a metered price. A `spot` term can have the notice before the provider ends the\n * use. A `committed` term has its length.\n */\nexport const priceTermSchema: z.ZodType<PriceTerm> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"on-demand\") }),\n z.strictObject({ kind: z.literal(\"spot\"), notice: quantitySchema(\"time\", { nonnegative: true }).optional() }),\n z.strictObject({ kind: z.literal(\"committed\"), length: quantitySchema(\"time\", { positive: true }) }),\n]);\n\n/**\n * This schema accepts a metered offer: one resource of a provider in one location, on one term. The id is the\n * source and the source id, with a colon between them.\n */\nexport const meteredOfferSchema: z.ZodType<MeteredOffer> = 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 location: locationSchema,\n term: priceTermSchema,\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/**\n * This schema accepts a metered price of zero or more: an amount of money for each unit of a metered amount, for\n * example `{ \"value\": 0.0116, \"unit\": \"USD/h\" }`.\n */\nexport const meteredPriceSchema: z.ZodType<Quantity, Quantity> = quantitySchema(undefined, { nonnegative: true }).superRefine(\n (price, context) => {\n const parts = readPriceUnit(price.unit);\n if (typeof parts === \"string\") context.addIssue({ code: \"custom\", message: parts });\n },\n);\n\n/** This schema accepts a tier: the start of its usage, and its price for each unit. The start measures the metered amount of the price. */\nexport const tierSchema: z.ZodType<Tier> = z\n .strictObject({ from: quantitySchema(undefined, { nonnegative: true }), unitPrice: meteredPriceSchema })\n .superRefine((tier, context) => {\n const parts = readPriceUnit(tier.unitPrice.unit);\n if (typeof parts === \"string\" || measures(tier.from.unit, tier.unitPrice.unit, parts.money)) return;\n context.addIssue({\n code: \"custom\",\n message: `The start ${tier.from.unit} does not measure the metered amount of the price ${tier.unitPrice.unit}.`,\n path: [\"from\"],\n });\n });\n\n/** This schema accepts a free amount of more than zero for each period, and its scope. */\nexport const freeAmountSchema: z.ZodType<FreeAmount> = z.strictObject({\n amount: quantitySchema(undefined, { positive: true }),\n scope: z.enum(FREE_SCOPES),\n});\n\n/**\n * This schema accepts a meter. The first tier starts at zero, and the starts increase. The prices of the tiers and\n * the free amount measure one metered amount.\n */\nexport const meterSchema: z.ZodType<Meter> = z\n .strictObject({ name: textSchema, tiers: z.array(tierSchema).min(1), free: freeAmountSchema.optional() })\n .superRefine((meter, context) => {\n const [first] = meter.tiers;\n if (first === undefined) return;\n const parts = readPriceUnit(first.unitPrice.unit);\n if (typeof parts === \"string\") return;\n let units = true;\n for (const [index, tier] of meter.tiers.entries()) {\n if (converts(tier.unitPrice.unit, first.unitPrice.unit) && measures(tier.from.unit, first.unitPrice.unit, parts.money)) continue;\n units = false;\n context.addIssue({\n code: \"custom\",\n message: `The tier ${index} does not measure the metered amount of the price ${first.unitPrice.unit}.`,\n path: [\"tiers\", index],\n });\n }\n if (meter.free !== undefined && !measures(meter.free.amount.unit, first.unitPrice.unit, parts.money)) {\n context.addIssue({\n code: \"custom\",\n message: `The free amount ${meter.free.amount.unit} does not measure the metered amount of the price ${first.unitPrice.unit}.`,\n path: [\"free\", \"amount\"],\n });\n }\n if (!units) return;\n const starts = startsOf(meter.tiers, first.from.unit);\n if (starts === undefined) return;\n if (rationals.sign(starts[0] ?? rationals.ZERO) !== 0) {\n context.addIssue({ code: \"custom\", message: \"The first tier does not start at zero.\", path: [\"tiers\", 0, \"from\"] });\n }\n for (let index = 1; index < starts.length; index += 1) {\n if (rationals.cmp(starts[index] ?? rationals.ZERO, starts[index - 1] ?? rationals.ZERO) > 0) continue;\n context.addIssue({\n code: \"custom\",\n message: `The tier ${index} does not start after the tier ${index - 1}.`,\n path: [\"tiers\", index, \"from\"],\n });\n }\n });\n\n/**\n * This schema accepts a metered reading: the metered prices of one offer at one instant. The tiers and the free\n * amounts count the usage of one `period`. Each meter has its own name.\n */\nexport const meteredReadingSchema: z.ZodType<MeteredReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n period: quantitySchema(\"time\", { positive: true }),\n meters: z.array(meterSchema).min(1),\n upfront: moneySchema.optional(),\n })\n .refine((reading) => new Set(reading.meters.map((meter) => meter.name)).size === reading.meters.length, {\n message: \"The reading has two meters with one name.\",\n path: [\"meters\"],\n });\n\n/** This schema accepts a metered observation: an offer, and a reading of that offer. Only a committed term has upfront money. */\nexport const meteredObservationSchema: z.ZodType<MeteredObservation> = z\n .strictObject({ offer: meteredOfferSchema, reading: meteredReadingSchema })\n .superRefine((each, context) => {\n if (each.reading.offerId !== each.offer.id) {\n context.addIssue({ code: \"custom\", message: \"The reading is not a reading of the offer.\", path: [\"reading\", \"offerId\"] });\n }\n if (each.reading.upfront !== undefined && each.offer.term.kind !== \"committed\") {\n context.addIssue({\n code: \"custom\",\n message: `The term ${each.offer.term.kind} has no upfront money.`,\n path: [\"reading\", \"upfront\"],\n });\n }\n });\n\n/** This function gives the value of an amount in a unit, as an exact rational. */\nfunction exactIn(amount: Quantity, unit: string): Rational {\n return convertExact(rationals.fromNumber(amount.value), amount.unit, unit);\n}\n\n/** This function gives the larger of two rationals. */\nfunction larger(a: Rational, b: Rational): Rational {\n return rationals.cmp(a, b) >= 0 ? a : b;\n}\n\n/** This function gives the smaller of two rationals. */\nfunction smaller(a: Rational, b: Rational): Rational {\n return rationals.cmp(a, b) <= 0 ? a : b;\n}\n\n/** This function examines an amount of usage of a meter, and gives its value in its own unit. */\nfunction usageValue(meter: Meter, amount: Quantity, priceUnit: string, money: string, what: string): Rational {\n if (!Number.isFinite(amount.value) || amount.value < 0) {\n throw new RangeError(`The ${what} of the meter ${meter.name} is ${amount.value}, not an amount of zero or more.`);\n }\n if (!measures(amount.unit, priceUnit, money)) {\n throw new RangeError(`The ${what} of the meter ${meter.name} is in ${amount.unit}, which does not measure the price ${priceUnit}.`);\n }\n return rationals.fromNumber(amount.value);\n}\n\n/**\n * This function gives the exact cost of the usage of one meter, in the unit of money of its first tier. The free\n * amount comes off the usage first. The tiers then count the rest of the usage from zero.\n */\nfunction costOfMeter(meter: Meter, used: Quantity | undefined, freeUsed: Quantity | undefined): { money: string; cost: Rational } {\n const [first] = meter.tiers;\n if (first === undefined) throw new RangeError(`The meter ${meter.name} has no tier.`);\n const parts = readPriceUnit(first.unitPrice.unit);\n if (typeof parts === \"string\") throw new RangeError(parts);\n const { money } = parts;\n if (used === undefined) return { money, cost: rationals.ZERO };\n const amount = usageValue(meter, used, first.unitPrice.unit, money, \"usage\");\n const unit = used.unit;\n const perUnit = priceUnitFor(money, unit);\n if (perUnit === undefined) throw new RangeError(`The usage of the meter ${meter.name} is in ${unit}, which has no price unit.`);\n let free: Rational = rationals.ZERO;\n if (meter.free !== undefined) free = exactIn(meter.free.amount, unit);\n if (freeUsed !== undefined) {\n usageValue(meter, freeUsed, first.unitPrice.unit, money, \"used free amount\");\n free = larger(rationals.ZERO, rationals.sub(free, exactIn(freeUsed, unit)));\n }\n const billed = larger(rationals.ZERO, rationals.sub(amount, free));\n let cost: Rational = rationals.ZERO;\n for (const [index, tier] of meter.tiers.entries()) {\n const start = exactIn(tier.from, unit);\n const next = meter.tiers[index + 1];\n const end = next === undefined ? billed : smaller(billed, exactIn(next.from, unit));\n if (rationals.cmp(end, start) <= 0) continue;\n cost = rationals.add(cost, rationals.mul(rationals.sub(end, start), exactIn(tier.unitPrice, perUnit)));\n }\n return { money, cost };\n}\n\n/**\n * This function gives the cost of a metered offer for one period, from the usage of each meter in that period. A\n * meter with no usage costs zero. The free amount of a meter comes off its usage first, less `freeUsed`. The tiers\n * then count the rest of the usage from zero. A committed term adds its upfront money times the period over the length.\n *\n * The arithmetic is exact, and the function does not round the cost to the cent. Each value is the nearest number to\n * the exact cost. The function converts the units with the exact factors of `@mark1russell7/quantity`.\n *\n * @throws RangeError when the usage names a meter that the reading does not have. It also throws when an amount\n * of usage is negative, or does not measure the metered amount of its meter.\n */\nexport function meteredCost(observation: MeteredObservation, usage: MeteredUsage, options: MeteredCostOptions = {}): MeteredCost {\n const { offer, reading } = observation;\n const { freeUsed = {} } = options;\n const names = new Set(reading.meters.map((meter) => meter.name));\n for (const name of [...Object.keys(usage), ...Object.keys(freeUsed)]) {\n if (!names.has(name)) throw new RangeError(`The reading of ${reading.offerId} has no meter ${name}.`);\n }\n const at = (record: MeteredUsage, name: string): Quantity | undefined => (Object.hasOwn(record, name) ? record[name] : undefined);\n const costs = reading.meters.map((meter) => ({ name: meter.name, ...costOfMeter(meter, at(usage, meter.name), at(freeUsed, meter.name)) }));\n const unit = costs[0]?.money;\n if (unit === undefined) throw new RangeError(`The reading of ${reading.offerId} has no meter.`);\n let total: Rational = rationals.ZERO;\n for (const each of costs) total = rationals.add(total, convertExact(each.cost, each.money, unit));\n const meters = costs.map((each): MeterCost => ({ name: each.name, cost: quantity(rationals.toNumber(each.cost), each.money) }));\n let upfront: Rational = rationals.ZERO;\n if (offer.term.kind === \"committed\" && reading.upfront !== undefined) {\n const { length } = offer.term;\n const share = rationals.div(exactIn(reading.period, length.unit), rationals.fromNumber(length.value));\n upfront = rationals.mul(exactIn(reading.upfront, unit), share);\n }\n total = rationals.add(total, upfront);\n return { meters, upfront: quantity(rationals.toNumber(upfront), unit), total: quantity(rationals.toNumber(total), unit) };\n}\n"],"mappings":";;;;;;;;;;;AAwBA,MAAa,kBAAwC,EAAE,mBAAmB,QAAQ;CAChF,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,MAAM,EAAE,CAAC;CAC1C,EAAE,aAAa;EAAE,MAAM,EAAE,QAAQ,SAAS;EAAG,KAAK,eAAe,QAAQ,EAAE,UAAU,KAAK,CAAC;CAAE,CAAC;CAC9F,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAChD,CAAC;;;;;AAMD,MAAa,oBAA4C,EAAE,aAAa;CACtE,QAAQ;CACR,WAAW;CACX,iBAAiB,EAAE,QAAQ;CAC3B,YAAY,EAAE,QAAQ;CACtB,QAAQ;AACV,CAAC;;;;;AAMD,SAAgB,UAAU,OAAoB,SAAiD;CAC7F,MAAM,EAAE,cAAc;CACtB,IAAI,UAAU,SAAS,QAAQ,OAAO;CACtC,MAAM,KAAK,KAAK,MAAM,QAAQ,EAAE;CAChC,IAAI,OAAO,MAAM,EAAE,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,UAAU,QAA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AAQ,SAAS,IAAI,GAAG,KAAK;CAC/D;CACA,QAAQ,UAAU,IAAI,OAAO,OAAO;CACpC,OAAO;EAAE;EAAQ,SAAS,SAAS,UAAU,SAAS,OAAO,GAAG,IAAI;EAAG,OAAO,SAAS,UAAU,SAAS,KAAK,GAAG,IAAI;CAAE;AAC1H"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/metered.ts"],"sourcesContent":["import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { sourceSchema, textSchema } from \"./records.ts\";\n\n/** The storage rule of a source, from its terms. */\nexport type Retention =\n | { readonly kind: \"keep\" }\n | { readonly kind: \"max-age\"; readonly age: Quantity }\n | { readonly kind: \"no-store\" };\n\n/** The rules of the terms of one source. */\nexport interface SourceTerms {\n readonly source: string;\n readonly retention: Retention;\n readonly deleteWhenEnded: boolean;\n readonly priceModel: boolean;\n readonly clause: string;\n}\n\n/**\n * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the\n * time. With `max-age`, a store keeps a reading for `age` at most. With `no-store`, a reading serves one request.\n */\nexport const retentionSchema: z.ZodType<Retention> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"keep\") }),\n z.strictObject({ kind: z.literal(\"max-age\"), age: quantitySchema(\"time\", { positive: true }) }),\n z.strictObject({ kind: z.literal(\"no-store\") }),\n]);\n\n/**\n * This schema accepts the rules of the terms of one source. `deleteWhenEnded` deletes the readings of an offer\n * when the offer ends. `priceModel` permits a trend or a forecast of prices. `clause` names the text of the terms.\n */\nexport const sourceTermsSchema: z.ZodType<SourceTerms> = z.strictObject({\n source: sourceSchema,\n retention: retentionSchema,\n deleteWhenEnded: z.boolean(),\n priceModel: z.boolean(),\n clause: textSchema,\n});\n\n/**\n * This function gives the last instant at which a store keeps a reading, or null when the terms set no\n * limit. For a source with `no-store`, the instant is the instant of the reading.\n */\nexport function keepUntil(terms: SourceTerms, reading: { readonly at: string }): string | null {\n const { retention } = terms;\n if (retention.kind === \"keep\") return null;\n const at = Date.parse(reading.at);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(reading.at)} is not an instant.`);\n if (retention.kind === \"no-store\") return new Date(at).toISOString();\n return new Date(at + Math.floor(valueIn(retention.age, \"ms\"))).toISOString();\n}\n\n/**\n * This function tells if a store keeps a reading at the instant `now`. A store keeps no reading of a source with\n * `no-store`, and no reading of an ended offer when the terms delete them.\n */\nexport function isKept(terms: SourceTerms, reading: { readonly at: string }, now: string, ended = false): boolean {\n if (ended && terms.deleteWhenEnded) return false;\n if (terms.retention.kind === \"no-store\") return false;\n const until = keepUntil(terms, reading);\n if (until === null) return true;\n const instant = Date.parse(now);\n if (Number.isNaN(instant)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n return instant <= Date.parse(until);\n}\n\n/** This function tells if the terms permit a stored history of the readings of a source. */\nexport function permitsHistory(terms: SourceTerms): boolean {\n return terms.retention.kind === \"keep\" && !terms.deleteWhenEnded;\n}\n\n/** This function tells if the terms permit a trend of the prices of a source: a history and a model of prices. */\nexport function permitsTrend(terms: SourceTerms): boolean {\n return permitsHistory(terms) && terms.priceModel;\n}\n","import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { latestObservations, type Observation } from \"./offers.ts\";\nimport { instantSchema, offerSchema, priceReadingSchema, sourceSchema, textSchema } from \"./records.ts\";\nimport { isKept, keepUntil, type SourceTerms } from \"./terms.ts\";\n\n/*\n * This module calculates a board of current prices. A watch reads its sources on a schedule. The board keeps the\n * last read of each entry of the watch, within the terms of each source. Each function of this module is a\n * calculation with no effect. A host does the reads and writes the board.\n */\n\n/** The format name of a board record. */\nexport const BOARD_FORMAT = \"price-board/1\";\n\n/** This schema accepts an observation: an offer, and a reading of that offer. */\nexport const observationSchema: z.ZodType<Observation> = z\n .strictObject({ offer: offerSchema, reading: priceReadingSchema })\n .refine((each) => each.reading.offerId === each.offer.id, { message: \"The reading is not a reading of the offer.\" });\n\n/** This record is the last read of one entry of a watch: the name of the entry, the instant, and the observations. */\nexport interface BoardRead {\n readonly name: string;\n readonly at: string;\n readonly observations: readonly Observation[];\n}\n\n/** This record is a board: the instant of its last settle, and the last read of each entry, in the order of the names. */\nexport interface Board {\n readonly format: typeof BOARD_FORMAT;\n readonly at: string;\n readonly reads: readonly BoardRead[];\n}\n\n/** This schema accepts the read of an entry. The read has one observation of each offer at most. */\nexport const boardReadSchema: z.ZodType<BoardRead> = z\n .strictObject({ name: textSchema, at: instantSchema, observations: z.array(observationSchema) })\n .refine((read) => new Set(read.observations.map((each) => each.offer.id)).size === read.observations.length, {\n message: \"The read has two observations of one offer.\",\n });\n\n/** This schema accepts a board. The board has one read of each entry at most. */\nexport const boardSchema: z.ZodType<Board> = z\n .strictObject({ format: z.literal(BOARD_FORMAT), at: instantSchema, reads: z.array(boardReadSchema) })\n .refine((board) => new Set(board.reads.map((each) => each.name)).size === board.reads.length, {\n message: \"The board has two reads of one entry.\",\n });\n\n/** This record is an offer that the store does not keep, with the reason. */\nexport interface Dropped {\n readonly offerId: string;\n readonly why: string;\n}\n\n/** These options give the rules of a store: the terms of each source, the instant, and the offers that ended. */\nexport interface KeepOptions {\n /** The terms of the sources. A store keeps no reading of a source without terms. */\n readonly terms: readonly SourceTerms[];\n /** The instant of the decision. */\n readonly now: string;\n /** The ids of the offers that ended, as their sources tell. An offer with `endsAt` at or before `now` also ended. */\n readonly ended?: readonly string[] | undefined;\n}\n\n/** This record is the decision of a store: the observations that it keeps, and each offer that it drops. */\nexport interface Kept {\n /** The latest observation of each kept offer, in the order of the offer ids. */\n readonly kept: readonly Observation[];\n /** Each dropped offer, in the order of the offer ids. */\n readonly dropped: readonly Dropped[];\n}\n\n/** This function gives the terms of each source by its name. Two terms of one source are a problem of the input. */\nfunction termsBySource(terms: readonly SourceTerms[]): ReadonlyMap<string, SourceTerms> {\n const map = new Map<string, SourceTerms>();\n for (const each of terms) {\n if (map.has(each.source)) throw new RangeError(`The terms of the source ${each.source} are in the list two times.`);\n map.set(each.source, each);\n }\n return map;\n}\n\n/** This function gives the text of an amount of time, for example `6 h`. */\nconst timeText = (age: Quantity): string => `${age.value} ${age.unit}`;\n\n/**\n * This function decides which observations a store keeps. It takes the latest observation of each offer. It keeps\n * an observation while the terms of its source permit it, and while its offer has not ended. A current price is\n * a price that a buyer can pay, so the store drops an ended offer for each source.\n *\n * `settleBoard` applies this function to each read of a board.\n *\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function keepObservations(observations: readonly Observation[], options: KeepOptions): Kept {\n const terms = termsBySource(options.terms);\n const now = Date.parse(options.now);\n if (Number.isNaN(now)) throw new RangeError(`The instant ${JSON.stringify(options.now)} is not an instant.`);\n const ended = new Set(options.ended ?? []);\n const kept: Observation[] = [];\n const dropped: Dropped[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const rules = terms.get(offer.source);\n const endsAt = offer.endsAt === undefined ? Number.NaN : Date.parse(offer.endsAt);\n const over = ended.has(offer.id) || endsAt <= now;\n if (rules === undefined) dropped.push({ offerId: offer.id, why: `The terms of the source ${offer.source} are not known, so a store keeps no reading of it.` });\n else if (rules.retention.kind === \"no-store\") dropped.push({ offerId: offer.id, why: `The terms of ${offer.source} permit no store: a reading serves one request.` });\n else if (over) {\n const rule = rules.deleteWhenEnded ? `, and the terms of ${offer.source} delete its readings` : \"\";\n dropped.push({ offerId: offer.id, why: `The offer ended${rule}.` });\n } else if (!isKept(rules, reading, options.now)) {\n const age = rules.retention.kind === \"max-age\" ? timeText(rules.retention.age) : \"\";\n dropped.push({ offerId: offer.id, why: `The reading of ${reading.at} passed the limit of ${age} of the terms of ${offer.source} at ${keepUntil(rules, reading)}.` });\n } else kept.push(observation);\n }\n return { kept, dropped };\n}\n\n/** These options give the rules of a settle: the rules of a store, and the names of the entries of the watch. */\nexport interface SettleOptions extends KeepOptions {\n /** The names of the entries of the watch. The board drops the read of each other name. With no list, it keeps each read. */\n readonly names?: readonly string[] | undefined;\n}\n\n/** This record is an offer that the board drops, with the name of the entry of its read. */\nexport interface BoardDrop extends Dropped {\n readonly entry: string;\n}\n\n/** This record is the result of a settle: the new board, and each offer that it dropped. */\nexport interface Settled {\n readonly board: Board;\n readonly dropped: readonly BoardDrop[];\n}\n\nconst byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/**\n * This function settles a board at `now`. A new read replaces the last read of its entry, so an offer that the new\n * read does not give leaves the read. Then `keepObservations` applies the terms to each read. The board drops the\n * read of an entry that the watch does not have. Write the new board in place of the old board.\n *\n * @param read - A new read of an entry, or none to settle the board alone\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function settleBoard(board: Board, options: SettleOptions, read?: BoardRead): Settled {\n const names = options.names === undefined ? undefined : new Set(options.names);\n const reads = new Map(board.reads.map((each) => [each.name, each]));\n if (read !== undefined) reads.set(read.name, read);\n const settled: BoardRead[] = [];\n const dropped: BoardDrop[] = [];\n for (const name of [...reads.keys()].sort(byText)) {\n const each = reads.get(name);\n if (each === undefined) continue;\n if (names !== undefined && !names.has(name)) {\n for (const gone of latestObservations(each.observations)) dropped.push({ entry: name, offerId: gone.offer.id, why: `The watch has no entry ${name}.` });\n continue;\n }\n const decision = keepObservations(each.observations, options);\n settled.push({ name, at: each.at, observations: decision.kept });\n for (const drop of decision.dropped) dropped.push({ entry: name, ...drop });\n }\n return { board: { format: BOARD_FORMAT, at: options.now, reads: settled }, dropped };\n}\n\n/**\n * This function gives the current observations of a board at `now`. Each is the latest observation of an offer over\n * the reads, while the terms of its source permit it. Give them to `offersOfPart` and `bestOffer`.\n */\nexport function boardObservations(board: Board, options: KeepOptions): Observation[] {\n return [...keepObservations(board.reads.flatMap((each) => each.observations), options).kept];\n}\n\n/** This function gives the instant of the last read of each entry of a board, by name, for `planReads`. */\nexport function lastReads(board: Board): Record<string, string> {\n return Object.fromEntries(board.reads.map((each) => [each.name, each.at]));\n}\n\n/** This record is one entry of a watch: a read of one source that repeats. */\nexport interface WatchEntry {\n /** The name of the entry. Each entry of a watch has its own name. */\n readonly name: string;\n /** The source of the read. */\n readonly source: string;\n /** The time from one read of the entry to the next, a time of `@mark1russell7/quantity`. */\n readonly every: Quantity;\n}\n\n/** This schema accepts an entry of a watch. */\nexport const watchEntrySchema: z.ZodType<WatchEntry> = z.strictObject({\n name: textSchema,\n source: sourceSchema,\n every: quantitySchema(\"time\", { positive: true }),\n});\n\n/** These options give the rules of a schedule: the terms of each source, and the slack of the loop. */\nexport interface ScheduleOptions {\n /** The terms of the sources. */\n readonly terms: readonly SourceTerms[];\n /**\n * The longest time from the instant of a due read to the instant that its reading is on the board. It is the\n * time between two passes of the loop, plus the longest pass.\n */\n readonly slack: Quantity;\n}\n\n/** This record is the interval of an entry, in milliseconds, or the reason that the entry has no interval. */\nexport type ReadInterval = { readonly ok: true; readonly ms: number } | { readonly ok: false; readonly why: string };\n\n/**\n * This function gives the time from one read of an entry to the next, in milliseconds. A reading of a source with\n * the limit `L` stays on the board until `L` after the read. The next reading arrives `slack` after the next read\n * is due, at most. Thus the interval is the shorter of `every` and `L - slack`. Then the board has a current\n * reading of the entry at each instant after its first read.\n */\nexport function readInterval(entry: WatchEntry, options: ScheduleOptions): ReadInterval {\n const terms = termsBySource(options.terms).get(entry.source);\n const every = valueIn(entry.every, \"ms\");\n if (!(every > 0)) return { ok: false, why: `The time every of the entry ${entry.name} is not more than 0.` };\n if (terms === undefined) return { ok: false, why: `The terms of the source ${entry.source} of the entry ${entry.name} are not known.` };\n const { retention } = terms;\n if (retention.kind === \"no-store\") return { ok: false, why: `The terms of ${entry.source} permit no store, so a watch cannot keep the prices of the entry ${entry.name}. Read the source for each request.` };\n if (retention.kind === \"keep\") return { ok: true, ms: every };\n const room = valueIn(retention.age, \"ms\") - valueIn(options.slack, \"ms\");\n if (!(room > 0)) return { ok: false, why: `The slack ${timeText(options.slack)} is not less than the limit ${timeText(retention.age)} of the terms of ${entry.source}, so the board has gaps in the prices of the entry ${entry.name}.` };\n return { ok: true, ms: Math.min(every, room) };\n}\n\n/** This function gives the problems of a watch: an entry with no interval, and two entries with one name. */\nexport function watchProblems(entries: readonly WatchEntry[], options: ScheduleOptions): string[] {\n const problems: string[] = [];\n const names = new Set<string>();\n for (const entry of entries) {\n if (names.has(entry.name)) problems.push(`Two entries have the name ${entry.name}.`);\n names.add(entry.name);\n const interval = readInterval(entry, options);\n if (!interval.ok) problems.push(interval.why);\n }\n return problems;\n}\n\n/** This record is the plan of one pass of a watch: the due entries, and the instant of the next due read. */\nexport interface ReadPlan {\n /** The names of the due entries, in the order of the entries. An entry with no read is due. */\n readonly due: readonly string[];\n /**\n * The names of the due entries, the entry that is due for the longest time first. An entry with no read comes\n * first. Entries that became due at the same instant keep the order of the entries. Read the entries in this order.\n * Then each due entry comes before the next read of a later due entry.\n */\n readonly queue: readonly string[];\n /** The first instant after `now` that an entry is due, or null when no entry has an interval. */\n readonly next: string | null;\n}\n\n/**\n * This function plans one pass of a watch. An entry is due when it has no last read, or when its interval has\n * passed since its last read. An entry with no interval is not due at any time. `watchProblems` gives its reason.\n *\n * @param last - The instant of the last read of each entry, by name\n * @throws RangeError when `now` or a last read is not an instant.\n */\nexport function planReads(entries: readonly WatchEntry[], last: Readonly<Record<string, string>>, now: string, options: ScheduleOptions): ReadPlan {\n const at = Date.parse(now);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n const due: string[] = [];\n const since: { readonly name: string; readonly at: number }[] = [];\n let next = Number.POSITIVE_INFINITY;\n for (const entry of entries) {\n const interval = readInterval(entry, options);\n if (!interval.ok) continue;\n const before = Object.hasOwn(last, entry.name) ? last[entry.name] : undefined;\n const read = before === undefined ? Number.NaN : Date.parse(before);\n if (before !== undefined && Number.isNaN(read)) throw new RangeError(`The last read ${JSON.stringify(before)} of the entry ${entry.name} is not an instant.`);\n const isDue = Number.isNaN(read) || read + interval.ms <= at;\n if (isDue) {\n due.push(entry.name);\n since.push({ name: entry.name, at: Number.isNaN(read) ? Number.NEGATIVE_INFINITY : read + interval.ms });\n }\n // A planned read happens at `now`, so the next read of a due entry is one interval after `now`.\n next = Math.min(next, (isDue ? at : read) + interval.ms);\n }\n // The sort of an array is stable, so equal instants keep the order of the entries.\n const queue = since.sort((a, b) => a.at - b.at).map((each) => each.name);\n return { due, queue, next: Number.isFinite(next) ? new Date(next).toISOString() : null };\n}\n","import {\n atomAbove,\n canonicalUnit,\n convertExact,\n convertible,\n parseUnit,\n quantity,\n rationals,\n UnitError,\n type Quantity,\n type Rational,\n} from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { instantSchema, moneySchema, offerId, sourceSchema, specSchema, textSchema, type Spec } from \"./records.ts\";\n\n/*\n * This module has the metered prices of a market. A provider meters an amount, for example the hours of a machine,\n * the stored data of each month, the data that goes out, or the requests. A metered price is a price for each unit\n * of that amount, in tiers, with a free amount for each billing period and a term.\n */\n\n/**\n * The kinds of a metered amount: a time (the hours of a machine), data times time (stored data), data (a transfer)\n * and a count (requests).\n */\nexport const METERED_KINDS = [\"time\", \"data-time\", \"data\", \"count\"] as const;\n/** The kind of a metered amount. */\nexport type MeteredKind = (typeof METERED_KINDS)[number];\n\n/**\n * The scopes of a free amount. With `account`, all the usage of the account in all regions shares one free amount.\n * With `region`, each region has its own free amount. With `resource`, each resource has its own free amount.\n */\nexport const FREE_SCOPES = [\"account\", \"region\", \"resource\"] as const;\n/** The scope of a free amount: the usage that shares it. */\nexport type FreeScope = (typeof FREE_SCOPES)[number];\n\n/** The location of a metered offer: the provider, and its region and zone, as the provider names them. */\nexport interface Location {\n readonly provider: string;\n readonly region: string;\n readonly zone?: string | undefined;\n}\n\n/**\n * The term of a metered price. A `spot` price is also a preemptible price: the provider can end the use at any time,\n * after the `notice`. A `committed` price binds the buyer for its `length`.\n */\nexport type PriceTerm =\n | { readonly kind: \"on-demand\" }\n | { readonly kind: \"spot\"; readonly notice?: Quantity | undefined }\n | { readonly kind: \"committed\"; readonly length: Quantity };\n\n/** A metered offer: one resource of a provider in one location, on one term, with the identifiers that the source gives. */\nexport interface MeteredOffer {\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 location: Location;\n readonly term: PriceTerm;\n readonly specs: readonly Spec[];\n}\n\n/** A tier of a meter: the price for each unit of the usage from `from` to the start of the next tier, in one period. */\nexport interface Tier {\n readonly from: Quantity;\n readonly unitPrice: Quantity;\n}\n\n/** A free amount of a meter for each period, and the scope that shares it. */\nexport interface FreeAmount {\n readonly amount: Quantity;\n readonly scope: FreeScope;\n}\n\n/** A meter of a metered reading: the tiers of the price of one metered amount, and its free amount. */\nexport interface Meter {\n readonly name: string;\n readonly tiers: readonly Tier[];\n readonly free?: FreeAmount | undefined;\n}\n\n/** A metered reading: the metered prices of one offer at one instant. */\nexport interface MeteredReading {\n readonly offerId: string;\n readonly at: string;\n readonly period: Quantity;\n readonly meters: readonly Meter[];\n readonly upfront?: Quantity | undefined;\n}\n\n/** One metered offer of a source, and its metered reading at one instant. */\nexport interface MeteredObservation {\n readonly offer: MeteredOffer;\n readonly reading: MeteredReading;\n}\n\n/** The usage of each meter in one period, by the name of the meter. */\nexport type MeteredUsage = Readonly<Record<string, Quantity>>;\n\n/** These options change the cost of a metered offer. */\nexport interface MeteredCostOptions {\n /**\n * The part of the free amount of each meter that other usage in its scope used in the same period. The keys are\n * the names of the meters. The default is none.\n */\n readonly freeUsed?: MeteredUsage | undefined;\n}\n\n/** The cost of the usage of one meter in one period. */\nexport interface MeterCost {\n readonly name: string;\n readonly cost: Quantity;\n}\n\n/** The cost of a metered offer for one period. */\nexport interface MeteredCost {\n /** The cost of each meter, in the order of the meters of the reading. */\n readonly meters: readonly MeterCost[];\n /** The part of the upfront money of a committed term for one period, or zero. */\n readonly upfront: Quantity;\n /** The sum of the cost of each meter and the part of the upfront money. */\n readonly total: Quantity;\n}\n\n/** The parts of the unit of a metered price: its unit of money, and the kind of its metered amount. */\ninterface PriceParts {\n readonly money: string;\n readonly kind: MeteredKind;\n}\n\n/** This function gives the kind of a metered amount from the exponents of its data and its time, or undefined. */\nfunction kindOfExponents(data: number, time: number): MeteredKind | undefined {\n if (data === 0 && time === 0) return \"count\";\n if (data === 0 && time === 1) return \"time\";\n if (data === 1 && time === 0) return \"data\";\n if (data === 1 && time === 1) return \"data-time\";\n return undefined;\n}\n\n/** This function reads the unit of a metered price. It gives the parts of the unit, or the problem as a text. */\nfunction readPriceUnit(unit: string): PriceParts | string {\n const refused = `The unit ${unit} is not a price for each unit of a metered amount, for example USD/h.`;\n let parsed: ReturnType<typeof parseUnit>;\n try {\n parsed = parseUnit(unit);\n } catch (error) {\n if (error instanceof UnitError) return refused;\n throw error;\n }\n const money = atomAbove(parsed, \"money\");\n const below = parsed.components.some((component) => component.exponent < 0);\n if (money === undefined || !below) return refused;\n const { money: units = 0, data = 0, time = 0, ...others } = parsed.vector;\n const kind = Object.values(others).every((exponent) => exponent === 0) && units === 1 ? kindOfExponents(-data, -time) : undefined;\n return kind === undefined ? refused : { money, kind };\n}\n\n/** This function gives the unit of a price for each unit of an amount, for example `USD/(GiB·mo)` for `GiB·mo`. */\nfunction priceUnitFor(money: string, amountUnit: string): string | undefined {\n try {\n return canonicalUnit(`${money}/${amountUnit}`);\n } catch (error) {\n if (error instanceof UnitError) return undefined;\n throw error;\n }\n}\n\n/** This function tells if an amount in one unit converts to another unit. A unit that the quantity package does not know does not convert. */\nfunction converts(from: string, to: string): boolean {\n try {\n return convertible(from, to);\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** This function gives the start of each tier in one unit, or undefined when a start does not convert to it. */\nfunction startsOf(tiers: readonly Tier[], unit: string): Rational[] | undefined {\n try {\n return tiers.map((tier) => convertExact(rationals.fromNumber(tier.from.value), tier.from.unit, unit));\n } catch (error) {\n if (error instanceof UnitError || error instanceof RangeError) return undefined;\n throw error;\n }\n}\n\n/** This function tells if a unit of an amount measures the metered amount of a unit of price. */\nfunction measures(amountUnit: string, priceUnit: string, money: string): boolean {\n const unit = priceUnitFor(money, amountUnit);\n return unit !== undefined && converts(unit, priceUnit);\n}\n\n/**\n * This function gives the kind of the metered amount of the unit of a metered price, for example `time` for `USD/h`\n * and `data-time` for `USD/(GiB·mo)`.\n *\n * @throws RangeError when the unit is not a price for each unit of a metered amount.\n */\nexport function meteredKindOf(unit: string): MeteredKind {\n const parts = readPriceUnit(unit);\n if (typeof parts === \"string\") throw new RangeError(parts);\n return parts.kind;\n}\n\n/**\n * This schema accepts the location of a metered offer. The name of the provider has small letters, digits and\n * hyphens, as the name of a source. The region and the zone are the ids of the provider.\n */\nexport const locationSchema: z.ZodType<Location> = z.strictObject({\n provider: sourceSchema,\n region: textSchema,\n zone: textSchema.optional(),\n});\n\n/**\n * This schema accepts the term of a metered price. A `spot` term can have the notice before the provider ends the\n * use. A `committed` term has its length.\n */\nexport const priceTermSchema: z.ZodType<PriceTerm> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"on-demand\") }),\n z.strictObject({ kind: z.literal(\"spot\"), notice: quantitySchema(\"time\", { nonnegative: true }).optional() }),\n z.strictObject({ kind: z.literal(\"committed\"), length: quantitySchema(\"time\", { positive: true }) }),\n]);\n\n/**\n * This schema accepts a metered offer: one resource of a provider in one location, on one term. The id is the\n * source and the source id, with a colon between them.\n */\nexport const meteredOfferSchema: z.ZodType<MeteredOffer> = 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 location: locationSchema,\n term: priceTermSchema,\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/**\n * This schema accepts a metered price of zero or more: an amount of money for each unit of a metered amount, for\n * example `{ \"value\": 0.0116, \"unit\": \"USD/h\" }`.\n */\nexport const meteredPriceSchema: z.ZodType<Quantity, Quantity> = quantitySchema(undefined, { nonnegative: true }).superRefine(\n (price, context) => {\n const parts = readPriceUnit(price.unit);\n if (typeof parts === \"string\") context.addIssue({ code: \"custom\", message: parts });\n },\n);\n\n/** This schema accepts a tier: the start of its usage, and its price for each unit. The start measures the metered amount of the price. */\nexport const tierSchema: z.ZodType<Tier> = z\n .strictObject({ from: quantitySchema(undefined, { nonnegative: true }), unitPrice: meteredPriceSchema })\n .superRefine((tier, context) => {\n const parts = readPriceUnit(tier.unitPrice.unit);\n if (typeof parts === \"string\" || measures(tier.from.unit, tier.unitPrice.unit, parts.money)) return;\n context.addIssue({\n code: \"custom\",\n message: `The start ${tier.from.unit} does not measure the metered amount of the price ${tier.unitPrice.unit}.`,\n path: [\"from\"],\n });\n });\n\n/** This schema accepts a free amount of more than zero for each period, and its scope. */\nexport const freeAmountSchema: z.ZodType<FreeAmount> = z.strictObject({\n amount: quantitySchema(undefined, { positive: true }),\n scope: z.enum(FREE_SCOPES),\n});\n\n/**\n * This schema accepts a meter. The first tier starts at zero, and the starts increase. The prices of the tiers and\n * the free amount measure one metered amount.\n */\nexport const meterSchema: z.ZodType<Meter> = z\n .strictObject({ name: textSchema, tiers: z.array(tierSchema).min(1), free: freeAmountSchema.optional() })\n .superRefine((meter, context) => {\n const [first] = meter.tiers;\n if (first === undefined) return;\n const parts = readPriceUnit(first.unitPrice.unit);\n if (typeof parts === \"string\") return;\n let units = true;\n for (const [index, tier] of meter.tiers.entries()) {\n if (converts(tier.unitPrice.unit, first.unitPrice.unit) && measures(tier.from.unit, first.unitPrice.unit, parts.money)) continue;\n units = false;\n context.addIssue({\n code: \"custom\",\n message: `The tier ${index} does not measure the metered amount of the price ${first.unitPrice.unit}.`,\n path: [\"tiers\", index],\n });\n }\n if (meter.free !== undefined && !measures(meter.free.amount.unit, first.unitPrice.unit, parts.money)) {\n context.addIssue({\n code: \"custom\",\n message: `The free amount ${meter.free.amount.unit} does not measure the metered amount of the price ${first.unitPrice.unit}.`,\n path: [\"free\", \"amount\"],\n });\n }\n if (!units) return;\n const starts = startsOf(meter.tiers, first.from.unit);\n if (starts === undefined) return;\n if (rationals.sign(starts[0] ?? rationals.ZERO) !== 0) {\n context.addIssue({ code: \"custom\", message: \"The first tier does not start at zero.\", path: [\"tiers\", 0, \"from\"] });\n }\n for (let index = 1; index < starts.length; index += 1) {\n if (rationals.cmp(starts[index] ?? rationals.ZERO, starts[index - 1] ?? rationals.ZERO) > 0) continue;\n context.addIssue({\n code: \"custom\",\n message: `The tier ${index} does not start after the tier ${index - 1}.`,\n path: [\"tiers\", index, \"from\"],\n });\n }\n });\n\n/**\n * This schema accepts a metered reading: the metered prices of one offer at one instant. The tiers and the free\n * amounts count the usage of one `period`. Each meter has its own name.\n */\nexport const meteredReadingSchema: z.ZodType<MeteredReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n period: quantitySchema(\"time\", { positive: true }),\n meters: z.array(meterSchema).min(1),\n upfront: moneySchema.optional(),\n })\n .refine((reading) => new Set(reading.meters.map((meter) => meter.name)).size === reading.meters.length, {\n message: \"The reading has two meters with one name.\",\n path: [\"meters\"],\n });\n\n/** This schema accepts a metered observation: an offer, and a reading of that offer. Only a committed term has upfront money. */\nexport const meteredObservationSchema: z.ZodType<MeteredObservation> = z\n .strictObject({ offer: meteredOfferSchema, reading: meteredReadingSchema })\n .superRefine((each, context) => {\n if (each.reading.offerId !== each.offer.id) {\n context.addIssue({ code: \"custom\", message: \"The reading is not a reading of the offer.\", path: [\"reading\", \"offerId\"] });\n }\n if (each.reading.upfront !== undefined && each.offer.term.kind !== \"committed\") {\n context.addIssue({\n code: \"custom\",\n message: `The term ${each.offer.term.kind} has no upfront money.`,\n path: [\"reading\", \"upfront\"],\n });\n }\n });\n\n/** This function gives the value of an amount in a unit, as an exact rational. */\nfunction exactIn(amount: Quantity, unit: string): Rational {\n return convertExact(rationals.fromNumber(amount.value), amount.unit, unit);\n}\n\n/** This function gives the larger of two rationals. */\nfunction larger(a: Rational, b: Rational): Rational {\n return rationals.cmp(a, b) >= 0 ? a : b;\n}\n\n/** This function gives the smaller of two rationals. */\nfunction smaller(a: Rational, b: Rational): Rational {\n return rationals.cmp(a, b) <= 0 ? a : b;\n}\n\n/** This function examines an amount of usage of a meter, and gives its value in its own unit. */\nfunction usageValue(meter: Meter, amount: Quantity, priceUnit: string, money: string, what: string): Rational {\n if (!Number.isFinite(amount.value) || amount.value < 0) {\n throw new RangeError(`The ${what} of the meter ${meter.name} is ${amount.value}, not an amount of zero or more.`);\n }\n if (!measures(amount.unit, priceUnit, money)) {\n throw new RangeError(`The ${what} of the meter ${meter.name} is in ${amount.unit}, which does not measure the price ${priceUnit}.`);\n }\n return rationals.fromNumber(amount.value);\n}\n\n/**\n * This function gives the exact cost of the usage of one meter, in the unit of money of its first tier. The free\n * amount comes off the usage first. The tiers then count the rest of the usage from zero.\n */\nfunction costOfMeter(meter: Meter, used: Quantity | undefined, freeUsed: Quantity | undefined): { money: string; cost: Rational } {\n const [first] = meter.tiers;\n if (first === undefined) throw new RangeError(`The meter ${meter.name} has no tier.`);\n const parts = readPriceUnit(first.unitPrice.unit);\n if (typeof parts === \"string\") throw new RangeError(parts);\n const { money } = parts;\n if (used === undefined) return { money, cost: rationals.ZERO };\n const amount = usageValue(meter, used, first.unitPrice.unit, money, \"usage\");\n const unit = used.unit;\n const perUnit = priceUnitFor(money, unit);\n if (perUnit === undefined) throw new RangeError(`The usage of the meter ${meter.name} is in ${unit}, which has no price unit.`);\n let free: Rational = rationals.ZERO;\n if (meter.free !== undefined) free = exactIn(meter.free.amount, unit);\n if (freeUsed !== undefined) {\n usageValue(meter, freeUsed, first.unitPrice.unit, money, \"used free amount\");\n free = larger(rationals.ZERO, rationals.sub(free, exactIn(freeUsed, unit)));\n }\n const billed = larger(rationals.ZERO, rationals.sub(amount, free));\n let cost: Rational = rationals.ZERO;\n for (const [index, tier] of meter.tiers.entries()) {\n const start = exactIn(tier.from, unit);\n const next = meter.tiers[index + 1];\n const end = next === undefined ? billed : smaller(billed, exactIn(next.from, unit));\n if (rationals.cmp(end, start) <= 0) continue;\n cost = rationals.add(cost, rationals.mul(rationals.sub(end, start), exactIn(tier.unitPrice, perUnit)));\n }\n return { money, cost };\n}\n\n/**\n * This function gives the cost of a metered offer for one period, from the usage of each meter in that period. A\n * meter with no usage costs zero. The free amount of a meter comes off its usage first, less `freeUsed`. The tiers\n * then count the rest of the usage from zero. A committed term adds its upfront money times the period over the length.\n *\n * The arithmetic is exact, and the function does not round the cost to the cent. Each value is the nearest number to\n * the exact cost. The function converts the units with the exact factors of `@mark1russell7/quantity`.\n *\n * @throws RangeError when the usage names a meter that the reading does not have. It also throws when an amount\n * of usage is negative, or does not measure the metered amount of its meter.\n */\nexport function meteredCost(observation: MeteredObservation, usage: MeteredUsage, options: MeteredCostOptions = {}): MeteredCost {\n const { offer, reading } = observation;\n const { freeUsed = {} } = options;\n const names = new Set(reading.meters.map((meter) => meter.name));\n for (const name of [...Object.keys(usage), ...Object.keys(freeUsed)]) {\n if (!names.has(name)) throw new RangeError(`The reading of ${reading.offerId} has no meter ${name}.`);\n }\n const at = (record: MeteredUsage, name: string): Quantity | undefined => (Object.hasOwn(record, name) ? record[name] : undefined);\n const costs = reading.meters.map((meter) => ({ name: meter.name, ...costOfMeter(meter, at(usage, meter.name), at(freeUsed, meter.name)) }));\n const unit = costs[0]?.money;\n if (unit === undefined) throw new RangeError(`The reading of ${reading.offerId} has no meter.`);\n let total: Rational = rationals.ZERO;\n for (const each of costs) total = rationals.add(total, convertExact(each.cost, each.money, unit));\n const meters = costs.map((each): MeterCost => ({ name: each.name, cost: quantity(rationals.toNumber(each.cost), each.money) }));\n let upfront: Rational = rationals.ZERO;\n if (offer.term.kind === \"committed\" && reading.upfront !== undefined) {\n const { length } = offer.term;\n const share = rationals.div(exactIn(reading.period, length.unit), rationals.fromNumber(length.value));\n upfront = rationals.mul(exactIn(reading.upfront, unit), share);\n }\n total = rationals.add(total, upfront);\n return { meters, upfront: quantity(rationals.toNumber(upfront), unit), total: quantity(rationals.toNumber(total), unit) };\n}\n"],"mappings":";;;;;;;;;;;AAwBA,MAAa,kBAAwC,EAAE,mBAAmB,QAAQ;CAChF,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,MAAM,EAAE,CAAC;CAC1C,EAAE,aAAa;EAAE,MAAM,EAAE,QAAQ,SAAS;EAAG,KAAK,eAAe,QAAQ,EAAE,UAAU,KAAK,CAAC;CAAE,CAAC;CAC9F,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAChD,CAAC;;;;;AAMD,MAAa,oBAA4C,EAAE,aAAa;CACtE,QAAQ;CACR,WAAW;CACX,iBAAiB,EAAE,QAAQ;CAC3B,YAAY,EAAE,QAAQ;CACtB,QAAQ;AACV,CAAC;;;;;AAMD,SAAgB,UAAU,OAAoB,SAAiD;CAC7F,MAAM,EAAE,cAAc;CACtB,IAAI,UAAU,SAAS,QAAQ,OAAO;CACtC,MAAM,KAAK,KAAK,MAAM,QAAQ,EAAE;CAChC,IAAI,OAAO,MAAM,EAAE,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,UAAU,QAAQ,EAAE,EAAE,oBAAoB;CACzG,IAAI,UAAU,SAAS,YAAY,OAAO,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;CACnE,OAAO,IAAI,KAAK,KAAK,KAAK,MAAM,QAAQ,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY;AAC7E;;;;;AAMA,SAAgB,OAAO,OAAoB,SAAkC,KAAa,QAAQ,OAAgB;CAChH,IAAI,SAAS,MAAM,iBAAiB,OAAO;CAC3C,IAAI,MAAM,UAAU,SAAS,YA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AG,UAAU,MAAM,IAAI,CAAC;CAAE,EAAE;CAC1I,MAAM,OAAO,MAAM,EAAE,EAAE;CACvB,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,WAAW,kBAAkB,QAAQ,QAAQ,eAAe;CAC9F,IAAI,QAAkB,UAAU;CAChC,KAAK,MAAM,QAAQ,OAAO,QAAQ,UAAU,IAAI,OAAO,aAAa,KAAK,MAAM,KAAK,OAAO,IAAI,CAAC;CAChG,MAAM,SAAS,MAAM,KAAK,UAAqB;EAAE,MAAM,KAAK;EAAM,MAAM,SAAS,UAAU,SAAS,KAAK,IAAI,GAAG,KAAK,KAAK;CAAE,EAAE;CAC9H,IAAI,UAAoB,UAAU;CAClC,IAAI,MAAM,KAAK,SAAS,eAAe,QAAQ,YAAY,KAAA,GAAW;EACpE,MAAM,EAAE,WAAW,MAAM;EACzB,MAAM,QAAQ,UAAU,IAAI,QAAQ,QAAQ,QAAQ,OAAO,IAAI,GAAG,UAAU,WAAW,OAAO,KAAK,CAAC;EACpG,UAAU,UAAU,IAAI,QAAQ,QAAQ,SAAS,IAAI,GAAG,KAAK;CAC/D;CACA,QAAQ,UAAU,IAAI,OAAO,OAAO;CACpC,OAAO;EAAE;EAAQ,SAAS,SAAS,UAAU,SAAS,OAAO,GAAG,IAAI;EAAG,OAAO,SAAS,UAAU,SAAS,KAAK,GAAG,IAAI;CAAE;AAC1H"}
|
|
@@ -1 +1 @@
|
|
|
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","../src/buy-list-energy.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;IAAuB;;;;;;UAO5E;WACN;;WAEA;;WAEA;;WAEA,KAAK;;;UAIC;WACN;WACA;WACA,MAAM;;WAEN,OAAO;;WAEP,gBAAgB;;WAEhB;;;;;WAKA,YAAY;;WAEZ,SAAS,cAAc;;;;;;WAMvB,OAAO,cAAc;WACrB,OAAO;;;;;WAKP,UAAU,cAAc;;;UAIlB;WACN,eAAe;WACf,kBAAkB;WAClB,gBAAgB;WAChB,oBAAoB;WACpB,mBAAmB;;;qBAIjB;;KAgBD,qBAAqB;;KAGrB,gBAAgB,QAAQ,aAAa;;;;UAKhC,0BAA0B;;;;;;WAMhC,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAwDR,cAAc,SAAS,eAAe,UAAS,oBAAyB;;;;;;;;wBAoGxE,YAAY,SAAS,eAAe,OAAM,SAAS,2BAAqC;;;;;;;;;;wBAaxF,OAAO,kBAAkB,SAAS;;KAOtC;WAAoB;WAA2B;WAAqB;WAAyB;;WAA4B;WAA2B;WAAsB;;;;;;;;;;;;;wBAatK,QAAQ,SAAS,eAAe,YAAY,gBAAgB;;KAahE;WACG;WAA0B;WAAqB,OAAO;WAAmB;WAA0B;;WACnG;WAA0B;WAAsB;;;;;;;;;;;;;;;;;wBAiB/C,oBAAoB,SAAS,eAAe,iBAAiB,gBAAgB;WAAoB;IAAoC;;qBClWxI,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","../src/buy-list-energy.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;IAAuB;;;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CQtB;WACG;WAA0B;WAAwB;WAAuC;WAAqB,QAAQ;;WACtH;WAA0B;WAAwB;WAAuC;WAAsB;;;UAG7G;;WAEN,gBAAgB;;WAEhB;;WAEA,QAAQ;;;;;;;;;;;;;;;;;;;;;wBAsBH,cAAc,SAAS,eAAe,OAAO,SAAS,0BAA0B"}
|
package/build/supplies-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { convertible, kindOf, quantity, rationals, valueIn, whyNotConvertible } from "@mark1russell7/quantity";
|
|
1
|
+
import { a as monthSchema, i as moneyOf, r as latestAverages } from "./average-BXyKRj8R.js";
|
|
2
|
+
import { atomAbove, convertible, kindOf, quantity, rationals, valueIn, whyNotConvertible } from "@mark1russell7/quantity";
|
|
3
3
|
import { checkSources, checkUnits } from "@mark1russell7/guidebook";
|
|
4
4
|
// src/supplies.ts
|
|
5
5
|
/** The format of a catalog of supplies. */
|
|
@@ -816,7 +816,7 @@ const SUPPLY_CATALOG = {
|
|
|
816
816
|
// src/food-plan.ts
|
|
817
817
|
/** This function gives the money of a cost for each unit of time, for example `USD` for `USD/wk`. */
|
|
818
818
|
function moneyOfRate(unit) {
|
|
819
|
-
const money =
|
|
819
|
+
const money = atomAbove(unit, "money");
|
|
820
820
|
return money !== void 0 && convertible(unit, `${money}/d`) ? money : void 0;
|
|
821
821
|
}
|
|
822
822
|
/** The age and sex groups of a food plan of USDA. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"supplies-entry.js","names":["ENERGY_UNIT"],"sources":["../src/supplies.ts","../src/supplies-data.ts","../src/food-plan.ts","../src/food-plan-data.ts","../src/buy-list-energy.ts"],"sourcesContent":["import { checkSources, checkUnits, type CitedUnit, type Finding, type FindingCode, type GateOptions, type Source } from \"@mark1russell7/guidebook\";\nimport { convertible, kindOf, quantity, rationals, valueIn, whyNotConvertible, type Quantity } from \"@mark1russell7/quantity\";\nimport { latestAverages, moneyOf, monthSchema, type AveragePrice } from \"./average.ts\";\nimport type { PartWant } from \"./offers.ts\";\nimport type { ProductWant } from \"./order.ts\";\n\n/*\n * This module is the format and the gate of a catalog of supplies: the products that a household keeps for an\n * emergency, the resource and the amount that one unit gives, and its shelf life. Each value has a cited fact, the\n * definition of the product, or an explicit no read. The facts and their sources are the records of\n * `@mark1russell7/guidebook`, and its gate examines them. The module names no person and no place.\n */\n\n/** The format of a catalog of supplies. */\nexport const SUPPLY_FORMAT = \"supply-catalog/1\";\n\n/** The kinds of the supplies. */\nexport const SUPPLY_KINDS = [\"water\", \"food\", \"power\", \"light\", \"heat\", \"first-aid\", \"communication\"] as const;\n\n/** A kind of a supply. */\nexport type SupplyKind = (typeof SUPPLY_KINDS)[number];\n\n/** A value that no source gives yet. The reason tells what is missing. */\nexport interface NoRead {\n readonly read: false;\n readonly why: string;\n}\n\n/**\n * An amount with its reason. The reason is a cited fact: the `id` of a unit of the catalog with the use `fact`.\n * Or it is the definition of the product, for example the 1 gal of a jug of 1 gal.\n */\nexport type CitedAmount =\n | { readonly read: true; readonly amount: number; readonly unit: string; readonly fact: string; readonly definition?: never }\n | { readonly read: true; readonly amount: number; readonly unit: string; readonly definition: string; readonly fact?: never };\n\n/** A resource that a supply gives, with its unit, for example `water.stored` in `L`. The codes are the resource codes of a store. */\nexport interface SupplyResource {\n readonly code: string;\n readonly unit: string;\n readonly title: string;\n}\n\n/** The gift of one unit of a product: an amount of one resource, or no read. */\nexport interface SupplyGift {\n readonly resource: string;\n readonly amount: CitedAmount | NoRead;\n}\n\n/**\n * The shelf life of a product: a cited amount of time, the `id` of a product of the FoodKeeper data of USDA FSIS, or no read.\n * The entry `/foodkeeper` of `@mark1russell7/stock` gives the due rule of a FoodKeeper product.\n */\nexport type ShelfLife = CitedAmount | { readonly read: true; readonly foodKeeper: number } | NoRead;\n\n/**\n * The join of a product to a series of average prices. It names the source and the series. It also gives the amount\n * 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\n * rice in USD/lb.\n */\nexport interface AverageJoin {\n readonly read: true;\n /** The source of the average prices, for example `bls-ap`. */\n readonly source: string;\n /** The id of the series in the source, for example `APU0000701312`. */\n readonly series: string;\n /** The amount of the item of the series in one unit of the product, with its reason. */\n readonly per: CitedAmount;\n}\n\n/** A product of the catalog. */\nexport interface SupplyProduct {\n readonly id: string;\n readonly title: string;\n readonly kind: SupplyKind;\n /** The part that the offers of a seller must match. A product with no part has no offer, so it has no price. */\n readonly want?: PartWant | undefined;\n /** The resources that one unit gives. A product that gives no stored resource, for example a radio, gives none. */\n readonly gives: readonly SupplyGift[];\n /** The `id` of a fact that tells why a kit has the product, for example the kit list of a public agency. */\n readonly basis?: string | undefined;\n /**\n * The count of units for each person of the household, in one bare count unit, for example 1 `{each}` of a sleeping\n * bag. A product with no field `perPerson` is one for the household. `kitMax` gives the count of units from it.\n */\n readonly perPerson?: CitedAmount | undefined;\n /** The food energy of one unit, in a unit of energy. A cooking converter gives it. */\n readonly energy?: CitedAmount | NoRead | undefined;\n /**\n * The amount of one unit as sold: a mass, a volume or a count, for example 1 kg, 530 g or 1 gal.\n * A product with no known size has no field `size`. A no read is for a product that has a size, when the source\n * of the size is not read yet, for example a label.\n */\n readonly size?: CitedAmount | NoRead | undefined;\n readonly shelf: ShelfLife;\n /**\n * The series of average prices that gives the price of one unit, or no read with the reason. A product with no join\n * and no part has no price.\n */\n readonly average?: AverageJoin | NoRead | undefined;\n}\n\n/** A catalog of supplies: the sources, the cited facts, the resources and the products. */\nexport interface SupplyCatalog {\n readonly format: typeof SUPPLY_FORMAT;\n readonly sources: readonly Source[];\n readonly facts: readonly CitedUnit[];\n readonly resources: readonly SupplyResource[];\n readonly products: readonly SupplyProduct[];\n}\n\n/** The codes of the findings of the catalog gate. */\nexport const SUPPLY_CODES = [\n \"supplies-format\",\n \"supplies-twice\",\n \"supplies-kind\",\n \"supplies-resource\",\n \"supplies-fact\",\n \"supplies-basis\",\n \"supplies-amount\",\n \"supplies-unit\",\n \"supplies-shelf\",\n \"supplies-unused\",\n \"supplies-no-read\",\n \"supplies-no-reason\",\n] as const;\n\n/** A code of a finding of the catalog gate. */\nexport type SupplyCode = (typeof SUPPLY_CODES)[number];\n\n/** A finding of the catalog gate, or of the gate of the facts and their sources. */\nexport type SupplyFinding = Finding<SupplyCode | FindingCode, \"source\" | \"unit\" | \"resource\" | \"product\">;\n\n/**\n * The options of the catalog gate: the options of the gate of the sources, and the known FoodKeeper ids.\n */\nexport interface SupplyGateOptions extends GateOptions {\n /**\n * The ids of the products of the FoodKeeper data, for example the ids of `FOODKEEPER_PRODUCTS` of the entry\n * `/foodkeeper` of `@mark1russell7/stock`. With this option, a shelf life with an id that is not in the set is an\n * error. With no option, the gate does not examine the ids against the data.\n */\n readonly foodKeeper?: ReadonlySet<number> | readonly number[] | undefined;\n}\n\n/** This function tells if a text is a unit of `@mark1russell7/quantity`. `convertible` throws for an unknown unit. */\nfunction known(unit: unknown): boolean {\n if (typeof unit !== \"string\") return false;\n try {\n return convertible(unit, unit);\n } catch {\n return false;\n }\n}\n\n/** The unit that each food energy converts to. */\nconst ENERGY_UNIT = \"kcal\";\n/** The unit that each shelf life converts to. */\nconst SHELF_UNIT = \"d\";\n/**\n * This function gives true for the unit of a size. That is a mass or a volume that converts to `kg` or `L`, or one\n * bare count, for example `{each}`. The kind of a unit is not sufficient. For example, `g/{each}` has the kind\n * mass, and it does not convert to `kg`.\n */\nfunction sizeUnit(unit: string): boolean {\n return convertible(unit, \"kg\") || convertible(unit, \"L\") || countUnit(unit);\n}\n\n/** This function gives true for one bare count unit, for example `{each}`. */\nfunction countUnit(unit: string): boolean {\n return /^{[^{}/]+}$/.test(unit) && kindOf(unit) === \"count\";\n}\n\n/**\n * This function examines a catalog. It gives the findings of the sources and the facts (the gate of\n * `@mark1russell7/guidebook`), and the findings of the products:\n *\n * - 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.\n * - An error for a product that gives no resource and has no basis.\n * - An error for a field `energy` on a product that is not food. The field is the food energy of one unit.\n * - 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\n * product is also a fact.\n * - An error for an amount with no reason, with two reasons, or with a blank definition. A catalog from JSON can have them.\n * - An error for a unit that is not a unit of `@mark1russell7/quantity`.\n * - An error for a unit that does not convert to the unit of its resource.\n * - An error for a size in a unit that is not a mass, a volume or a count, for example `h` or `kcal`.\n * - An error for a count for each person in a unit that is not one bare count, for example `kg` or `{each}/{person}`.\n * - The amount of the item of an average price has the same checks as each other amount.\n * - With the option `foodKeeper`, an error for a FoodKeeper id of a shelf life that is not in the known ids.\n * - A warning for each value with no read, and for a no read with a blank reason.\n * - A warning for each fact and each source that no product uses.\n *\n * The function takes a decoded catalog: each record has the fields of its type. Decode a catalog from JSON first, for\n * example with the entry `/read` of `@mark1russell7/optional`. The gate then finds the values that the type does not hold.\n *\n * @param catalog - The catalog\n * @param options - The options of the gate of the sources, for example the date of the gate, and the known FoodKeeper ids\n */\nexport function checkSupplies(catalog: SupplyCatalog, options: SupplyGateOptions = {}): SupplyFinding[] {\n const { foodKeeper: knownFoodKeeper, ...gate } = options;\n const foodKeeper = knownFoodKeeper === undefined ? undefined : new Set<number>(knownFoodKeeper);\n const out: SupplyFinding[] = [...checkSources(catalog.sources, gate), ...checkUnits(catalog.facts, catalog.sources, gate)];\n const error = (code: SupplyCode, record: \"resource\" | \"product\", id: string, message: string): void => {\n out.push({ level: \"error\", code, record, id, message });\n };\n const warning = (code: SupplyCode, record: \"source\" | \"unit\" | \"product\", id: string, message: string): void => {\n out.push({ level: \"warning\", code, record, id, message });\n };\n if (catalog.format !== SUPPLY_FORMAT) error(\"supplies-format\", \"product\", \"\", `The format is ${String(catalog.format)}. It must be ${SUPPLY_FORMAT}.`);\n\n const resources = new Map<string, SupplyResource>();\n for (const resource of catalog.resources) {\n if (resources.has(resource.code)) error(\"supplies-twice\", \"resource\", resource.code, `The resource ${resource.code} is two times in the catalog.`);\n if (!known(resource.unit)) error(\"supplies-unit\", \"resource\", resource.code, `The unit ${String(resource.unit)} of the resource ${resource.code} is not a known unit.`);\n resources.set(resource.code, resource);\n }\n const facts = new Map(catalog.facts.map((fact) => [fact.id, fact]));\n const used = new Set<string>();\n\n /** This function examines one cited amount, and gives the unit check to `units`. */\n const amount = (product: string, what: string, value: CitedAmount | NoRead, unit: string): void => {\n if (!value.read) {\n warning(\"supplies-no-read\", \"product\", product, `The ${what} of the product ${product} is no read: ${String(value.why)}`);\n if (typeof value.why !== \"string\" || value.why.trim() === \"\") warning(\"supplies-no-reason\", \"product\", product, `The no read of the ${what} of the product ${product} has no reason.`);\n return;\n }\n // The type permits one reason only. A catalog from JSON can have no reason, two reasons or a blank definition.\n const reasons = (value.fact === undefined ? 0 : 1) + (value.definition === undefined ? 0 : 1);\n if (reasons !== 1) error(\"supplies-fact\", \"product\", product, `The ${what} of the product ${product} has ${String(reasons)} reasons. It must have a fact or a definition, not the two.`);\n else if (value.definition !== undefined && (typeof value.definition !== \"string\" || value.definition.trim() === \"\")) error(\"supplies-fact\", \"product\", product, `The definition of the ${what} of the product ${product} is blank.`);\n if (value.fact !== undefined) {\n const fact = facts.get(value.fact);\n if (fact === undefined || fact.use !== \"fact\") error(\"supplies-fact\", \"product\", product, `The ${what} of the product ${product} cites ${value.fact}, and the catalog has no fact with that id.`);\n used.add(value.fact);\n }\n if (!(Number.isFinite(value.amount) && value.amount > 0)) error(\"supplies-amount\", \"product\", product, `The ${what} of the product ${product} is ${String(value.amount)}. It must be a finite number more than 0.`);\n if (!known(value.unit)) error(\"supplies-unit\", \"product\", product, `The unit ${String(value.unit)} of the ${what} of the product ${product} is not a known unit.`);\n else if (known(unit) && !convertible(value.unit, unit)) error(\"supplies-unit\", \"product\", product, `The ${what} of the product ${product} is in ${value.unit}, and ${value.unit} does not convert to ${unit}.`);\n };\n\n const products = new Set<string>();\n for (const product of catalog.products) {\n if (products.has(product.id)) error(\"supplies-twice\", \"product\", product.id, `The product ${product.id} is two times in the catalog.`);\n products.add(product.id);\n if (!(SUPPLY_KINDS as readonly string[]).includes(product.kind)) error(\"supplies-kind\", \"product\", product.id, `The kind ${String(product.kind)} of the product ${product.id} is not a supply kind.`);\n const gifts = new Set<string>();\n for (const gift of product.gives) {\n if (gifts.has(gift.resource)) error(\"supplies-twice\", \"product\", product.id, `The product ${product.id} gives the resource ${gift.resource} two times.`);\n gifts.add(gift.resource);\n const resource = resources.get(gift.resource);\n if (resource === undefined) error(\"supplies-resource\", \"product\", product.id, `The product ${product.id} gives the resource ${gift.resource}, and the catalog has no such resource.`);\n else amount(product.id, `gift of ${gift.resource}`, gift.amount, resource.unit);\n }\n if (product.gives.length === 0 && product.basis === undefined) error(\"supplies-basis\", \"product\", product.id, `The product ${product.id} gives no resource and has no basis. A product that gives no resource cites a fact in its basis.`);\n if (product.basis !== undefined) {\n const fact = facts.get(product.basis);\n if (fact === undefined || fact.use !== \"fact\") error(\"supplies-fact\", \"product\", product.id, `The basis of the product ${product.id} cites ${String(product.basis)}, and the catalog has no fact with that id.`);\n used.add(product.basis);\n }\n // An unknown kind has its own error above, so this rule examines only a known kind that is not food.\n if (product.energy !== undefined && product.kind !== \"food\" && (SUPPLY_KINDS as readonly string[]).includes(product.kind)) error(\"supplies-kind\", \"product\", product.id, `The product ${product.id} has a food energy, and its kind is ${String(product.kind)}. Only a product of the kind food has a food energy.`);\n if (product.energy !== undefined) amount(product.id, \"food energy\", product.energy, ENERGY_UNIT);\n if (product.size !== undefined) {\n // The size has no single unit to convert to. Its unit must be a mass, a volume or one bare count. An unknown unit\n // has its own error.\n amount(product.id, \"size\", product.size, \"\");\n if (product.size.read && known(product.size.unit) && !sizeUnit(product.size.unit))\n error(\"supplies-unit\", \"product\", product.id, `The size of the product ${product.id} is in ${product.size.unit}. It must be a mass, a volume or a count.`);\n }\n if (product.perPerson !== undefined) {\n // The count has no single unit to convert to. Its unit must be one bare count. An unknown unit has its own error.\n // A count that is not read gives no count of units, so the gate refuses it. A catalog from JSON can have one.\n if (product.perPerson.read !== true) error(\"supplies-amount\", \"product\", product.id, `The count for each person of the product ${product.id} is not read. A product with no known count has no field perPerson.`);\n else amount(product.id, \"count for each person\", product.perPerson, \"\");\n if (product.perPerson.read === true && known(product.perPerson.unit) && !countUnit(product.perPerson.unit))\n error(\"supplies-unit\", \"product\", product.id, `The count for each person of the product ${product.id} is in ${product.perPerson.unit}. It must be one bare count, for example {each}.`);\n }\n if (product.average !== undefined) amount(product.id, \"average price\", product.average.read ? product.average.per : product.average, product.average.read ? product.average.per.unit : \"\");\n if (\"foodKeeper\" in product.shelf) {\n if (!(Number.isSafeInteger(product.shelf.foodKeeper) && product.shelf.foodKeeper > 0)) error(\"supplies-shelf\", \"product\", product.id, `The FoodKeeper id of the product ${product.id} is ${String(product.shelf.foodKeeper)}. It must be a whole number more than 0.`);\n else if (foodKeeper !== undefined && !foodKeeper.has(product.shelf.foodKeeper))\n error(\"supplies-shelf\", \"product\", product.id, `The FoodKeeper id ${String(product.shelf.foodKeeper)} of the product ${product.id} is not in the known FoodKeeper ids.`);\n } else amount(product.id, \"shelf life\", product.shelf, SHELF_UNIT);\n }\n\n for (const fact of catalog.facts) if (!used.has(fact.id)) warning(\"supplies-unused\", \"unit\", fact.id, `No product uses the fact ${fact.id}.`);\n const cited = new Set(catalog.facts.map((fact) => fact.source));\n for (const source of catalog.sources) if (!cited.has(source.id)) warning(\"supplies-unused\", \"source\", source.id, `No fact cites the source ${source.id}.`);\n return out;\n}\n\n/**\n * This function gives the wants of the products with a part, in the order of the catalog, for `buyCandidates`.\n * A product with no part has no offer, so it is not in the result.\n *\n * @param catalog - The catalog\n * @param max - The largest count of units of a product. The default is 1 for each product\n */\nexport function supplyWants(catalog: SupplyCatalog, max: (product: SupplyProduct) => number = () => 1): ProductWant[] {\n return catalog.products.flatMap((product) => (product.want === undefined ? [] : [{ product: product.id, want: product.want, max: max(product) }]));\n}\n\n/**\n * This function gives the largest count of units of each product for a household, for `supplyWants`. A product with a\n * count for each person has that count times the persons, up to the next whole unit. Each other product has 1. The\n * product is exact: the count is the decimal of its number, so 1.1 for each person of 50 persons gives 55, not 56.\n *\n * @param people - The count of persons of the household. The persons are input data of the user.\n * @returns The function `max` of `supplyWants`\n * @throws RangeError when the count of persons is not a whole number of 0 or more\n */\nexport function kitMax(people: number): (product: SupplyProduct) => number {\n if (!(Number.isSafeInteger(people) && people >= 0)) throw new RangeError(`The count of persons is ${String(people)}. It must be a whole number of 0 or more.`);\n const persons = rationals.fromNumber(people);\n return (product) => (product.perPerson === undefined ? 1 : rationals.toNumber(rationals.ceil(rationals.mul(rationals.fromNumber(product.perPerson.amount), persons))));\n}\n\n/** The gift of a count of units: an amount in the unit of its resource, or no read. */\nexport type GiftOf = { readonly resource: string; readonly read: true; readonly amount: number; readonly unit: string } | { readonly resource: string; readonly read: false; readonly why: string };\n\n/**\n * This function gives the resources of a count of units of a product, each in the unit of its resource.\n * A gift with no read stays no read: it is not 0.\n *\n * @param catalog - The catalog\n * @param id - The `id` of the product\n * @param units - The count of units\n * @throws RangeError when the count of units is not a finite number of 0 or more\n * @throws RangeError when the catalog has no such product, or a gift of an unknown resource\n * @throws The error of `valueIn` of `@mark1russell7/quantity` when the unit of a gift does not convert to the unit of its resource\n */\nexport function giftsOf(catalog: SupplyCatalog, id: string, units: number): GiftOf[] {\n if (!(Number.isFinite(units) && units >= 0)) throw new RangeError(`The count of units is ${String(units)}. It must be a finite number of 0 or more.`);\n const product = catalog.products.find((each) => each.id === id);\n if (product === undefined) throw new RangeError(`The catalog has no product ${id}.`);\n return product.gives.map((gift): GiftOf => {\n const resource = catalog.resources.find((each) => each.code === gift.resource);\n if (resource === undefined) throw new RangeError(`The product ${id} gives the resource ${gift.resource}, and the catalog has no such resource.`);\n if (!gift.amount.read) return { resource: gift.resource, read: false, why: gift.amount.why };\n return { resource: gift.resource, read: true, amount: units * valueIn(quantity(gift.amount.amount, gift.amount.unit), resource.unit), unit: resource.unit };\n });\n}\n\n/** The price of one unit of a product from an average price, or no read with the reason. */\nexport type SupplyPrice =\n | { readonly product: string; readonly read: true; readonly price: Quantity; readonly average: string; readonly period: string }\n | { readonly product: string; readonly read: false; readonly why: string };\n\n/**\n * This function gives the price of one unit of each product with a join to a series, in the order of the catalog.\n * It takes the last month of each series (`latestAverages`). The price is in the money of the average price.\n *\n * - A product with no join is not in the result.\n * - 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.\n * - The unit of the series must convert to the unit of the product, for example USD/lb to 1 kg.\n * - With the option `since`, a last price before that month gives no read. A series that stops then gives no old price.\n *\n * @param catalog - The catalog\n * @param prices - The average prices, from one or more reads\n * @param options - The option `since`: the first month of a price that the result can use, in the form `YYYY-MM`\n * @returns The price of one unit of each product with a join, or no read with the reason\n * @throws RangeError when `since` is not a month in the form `YYYY-MM`\n */\nexport function averageSupplyPrices(catalog: SupplyCatalog, prices: readonly AveragePrice[], options: { readonly since?: string | undefined } = {}): SupplyPrice[] {\n const { since } = options;\n if (since !== undefined && !monthSchema.safeParse(since).success) throw new RangeError(`The month ${String(since)} is not in the form YYYY-MM.`);\n const last = new Map(latestAverages(prices).map((price) => [`${price.source}:${price.series}`, price]));\n return catalog.products.flatMap((product): SupplyPrice[] => {\n const join = product.average;\n if (join === undefined) return [];\n const none = (why: string): SupplyPrice[] => [{ product: product.id, read: false, why }];\n if (!join.read) return none(join.why);\n const average = last.get(`${join.source}:${join.series}`);\n if (average === undefined) return none(`The prices have no average price of the series ${join.series} of ${join.source}.`);\n if (since !== undefined && average.period < since) return none(`The last average price of the series ${join.series} of ${join.source} is for ${average.period}, before ${since}.`);\n const money = moneyOf(average.price.unit);\n if (money === undefined) return none(`The unit ${average.price.unit} of ${average.id} is not a price for each unit of an amount.`);\n if (!known(join.per.unit)) return none(`The unit ${String(join.per.unit)} of the product ${product.id} is not a known unit.`);\n const unit = `${money}/${join.per.unit}`;\n const why = whyNotConvertible(average.price.unit, unit);\n if (why !== undefined) return none(`The average price ${average.id} is in ${average.price.unit}, and it does not convert to ${unit}: ${why}.`);\n const price = quantity(valueIn(average.price, unit) * join.per.amount, money);\n return [{ product: product.id, read: true, price, average: average.id, period: average.period }];\n });\n}\n","import { SUPPLY_FORMAT, type SupplyCatalog } from \"./supplies.ts\";\n\n// The reference catalog of supplies. Each value has a cited fact, the definition of the product, or a no read.\n// Each fact is in own words, not a quote. The shelf life of a food is a product of the FoodKeeper data of USDA FSIS:\n// the entry `/foodkeeper` of `@mark1russell7/stock` gives its due rule, so this catalog does not copy its times.\n\nconst CHECKED = \"2026-11-22\";\n\n/** The reference catalog of supplies. A household adds its own products to a copy of it. */\nexport const SUPPLY_CATALOG: SupplyCatalog = {\n format: SUPPLY_FORMAT,\n sources: [\n { id: \"ready.water\", title: \"Water\", url: \"https://www.ready.gov/water\", license: \"us-public-domain\", checked: CHECKED, by: \"FEMA (Ready.gov)\" },\n { id: \"ready.kit\", title: \"Build A Kit\", url: \"https://www.ready.gov/kit\", license: \"us-public-domain\", checked: CHECKED, by: \"FEMA (Ready.gov)\" },\n { id: \"fdc.sr-legacy\", title: \"FoodData Central, SR Legacy\", url: \"https://fdc.nal.usda.gov/\", license: \"cc0\", checked: CHECKED, by: \"USDA Agricultural Research Service\" },\n ],\n facts: [\n {\n id: \"ready.water-replace\",\n use: \"fact\",\n text: \"The page tells to replace the stored water that is not commercially bottled each six months.\",\n source: \"ready.water\",\n locator: \"Water storage\",\n },\n {\n id: \"fdc.rice-white\",\n use: \"fact\",\n text: \"The item 168877 (white long-grain rice, raw, enriched) gives 365 kcal in 100 g. Thus 1 kg gives 3650 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 168877\",\n },\n {\n id: \"fdc.oats\",\n use: \"fact\",\n text: \"The item 173904 (oats, regular and quick, not fortified, dry) gives 379 kcal in 100 g. Thus 1 kg gives 3790 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 173904\",\n },\n {\n id: \"fdc.beans-black\",\n use: \"fact\",\n text: \"The item 173734 (black beans, mature seeds, raw) gives 341 kcal in 100 g. Thus 1 kg gives 3410 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 173734\",\n },\n {\n id: \"fdc.peanut-butter\",\n use: \"fact\",\n text: \"The item 174266 (peanut butter, smooth style, with salt) gives 598 kcal in 100 g. Thus 1 kg gives 5980 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 174266\",\n },\n {\n id: \"fdc.pasta\",\n use: \"fact\",\n text: \"The item 168927 (pasta, dry, unenriched) gives 371 kcal in 100 g. Thus 1 kg gives 3710 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 168927\",\n },\n {\n id: \"fdc.flour-white\",\n use: \"fact\",\n text: \"The item 169761 (wheat flour, white, all-purpose, unenriched) gives 364 kcal in 100 g. Thus 1 kg gives 3640 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 169761\",\n },\n {\n id: \"fdc.soup-chicken-noodle\",\n use: \"fact\",\n text: \"The item 171148 (chunky chicken noodle soup, canned, ready-to-serve) gives 41 kcal in 100 g. Its portion of 1 can is 530 g. Thus 1 can gives 217.3 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 171148, portion 1 can (530 g)\",\n },\n {\n id: \"ready.kit-flashlight\",\n use: \"fact\",\n text: \"The basic kit of the page has a flashlight and extra batteries.\",\n source: \"ready.kit\",\n locator: \"Basic Disaster Supplies Kit\",\n },\n {\n id: \"ready.kit-first-aid\",\n use: \"fact\",\n text: \"The basic kit of the page has a first aid kit.\",\n source: \"ready.kit\",\n locator: \"Basic Disaster Supplies Kit\",\n },\n {\n id: \"ready.kit-radio\",\n use: \"fact\",\n text: \"The basic kit of the page has a radio on batteries or a hand crank, and a NOAA Weather Radio with tone alert.\",\n source: \"ready.kit\",\n locator: \"Basic Disaster Supplies Kit\",\n },\n {\n id: \"ready.kit-sleeping-bag\",\n use: \"fact\",\n text: \"The page tells to add a sleeping bag or a warm blanket for each person.\",\n source: \"ready.kit\",\n locator: \"Additional Emergency Supplies\",\n },\n ],\n resources: [\n { code: \"water.stored\", unit: \"L\", title: \"Stored drinking water\" },\n { code: \"food.grain-dry\", unit: \"kg\", title: \"Dry grain, to cook with water and fuel\" },\n { code: \"food.legume-dry\", unit: \"kg\", title: \"Dry beans, to cook with water and fuel\" },\n { code: \"food.pasta-dry\", unit: \"kg\", title: \"Dry pasta, to boil in water that the cook drains\" },\n { code: \"food.flour\", unit: \"kg\", title: \"Flour, to bake or cook with water and fuel\" },\n { code: \"food.no-cook\", unit: \"kcal\", title: \"Food energy to eat with no water and no fuel\" },\n { code: \"energy.battery\", unit: \"Wh\", title: \"Energy in a battery\" },\n ],\n products: [\n {\n id: \"water.jug-1gal\",\n title: \"Drinking water, commercially bottled, in a jug of 1 gal\",\n kind: \"water\",\n gives: [{ resource: \"water.stored\", amount: { read: true, amount: 1, unit: \"gal\", definition: \"The product is a jug of 1 gal.\" } }],\n size: { read: true, amount: 1, unit: \"gal\", definition: \"The catalog item is defined as a jug of 1 gal.\" },\n shelf: { read: false, why: \"The source tells to keep commercially bottled water sealed, and it gives no time. The date on the label applies.\" },\n },\n {\n id: \"water.container-1gal\",\n title: \"A water container of 1 gal, filled from the tap\",\n kind: \"water\",\n gives: [{ resource: \"water.stored\", amount: { read: true, amount: 1, unit: \"gal\", definition: \"The product is a container of 1 gal.\" } }],\n shelf: { read: true, amount: 6, unit: \"mo\", fact: \"ready.water-replace\" },\n },\n {\n id: \"food.rice-white-1kg\",\n title: \"White long-grain rice, dry, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.grain-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry rice.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry rice.\" },\n energy: { read: true, amount: 3650, unit: \"kcal\", fact: \"fdc.rice-white\" },\n shelf: { read: true, foodKeeper: 338 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000701312\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry white long-grain rice, the item of the series.\" },\n },\n },\n {\n id: \"food.oats-1kg\",\n title: \"Rolled oats, dry, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.grain-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry oats.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry oats.\" },\n energy: { read: true, amount: 3790, unit: \"kcal\", fact: \"fdc.oats\" },\n shelf: { read: true, foodKeeper: 375 },\n average: { read: false, why: \"The known series of average prices have no series of oats yet.\" },\n },\n {\n id: \"food.beans-dry-1kg\",\n title: \"Dry beans, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.legume-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry beans.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry beans.\" },\n energy: { read: true, amount: 3410, unit: \"kcal\", fact: \"fdc.beans-black\" },\n shelf: { read: true, foodKeeper: 333 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000714233\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry beans of any type, the item of the series.\" },\n },\n },\n {\n id: \"food.peanut-butter-1kg\",\n title: \"Peanut butter, smooth, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.no-cook\", amount: { read: true, amount: 5980, unit: \"kcal\", fact: \"fdc.peanut-butter\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of peanut butter.\" },\n energy: { read: true, amount: 5980, unit: \"kcal\", fact: \"fdc.peanut-butter\" },\n shelf: { read: true, foodKeeper: 387 },\n average: { read: false, why: \"The known series of average prices have no series of peanut butter yet.\" },\n },\n {\n id: \"food.pasta-dry-1kg\",\n title: \"Dry pasta, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.pasta-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry pasta.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry pasta.\" },\n energy: { read: true, amount: 3710, unit: \"kcal\", fact: \"fdc.pasta\" },\n shelf: { read: true, foodKeeper: 335 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000701322\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry spaghetti or macaroni, the item of the series.\" },\n },\n },\n {\n id: \"food.flour-white-1kg\",\n title: \"White all-purpose flour, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.flour\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of white flour.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of white flour.\" },\n energy: { read: true, amount: 3640, unit: \"kcal\", fact: \"fdc.flour-white\" },\n shelf: { read: true, foodKeeper: 222 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000701111\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of white all-purpose flour, the item of the series.\" },\n },\n },\n {\n id: \"food.soup-can\",\n title: \"Chunky chicken noodle soup, ready-to-serve, 1 can (530 g)\",\n kind: \"food\",\n gives: [{ resource: \"food.no-cook\", amount: { read: true, amount: 217.3, unit: \"kcal\", fact: \"fdc.soup-chicken-noodle\" } }],\n size: { read: true, amount: 530, unit: \"g\", fact: \"fdc.soup-chicken-noodle\" },\n energy: { read: true, amount: 217.3, unit: \"kcal\", fact: \"fdc.soup-chicken-noodle\" },\n shelf: { read: true, foodKeeper: 372 },\n average: { read: false, why: \"The known series of average prices have no series of canned soup yet.\" },\n },\n {\n id: \"light.flashlight\",\n title: \"A flashlight on batteries\",\n kind: \"light\",\n basis: \"ready.kit-flashlight\",\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life. The batteries have the date on their label.\" },\n },\n {\n id: \"heat.sleeping-bag\",\n title: \"A sleeping bag for each person\",\n kind: \"heat\",\n basis: \"ready.kit-sleeping-bag\",\n perPerson: { read: true, amount: 1, unit: \"{each}\", fact: \"ready.kit-sleeping-bag\" },\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life.\" },\n },\n {\n id: \"first-aid.kit\",\n title: \"A first aid kit\",\n kind: \"first-aid\",\n basis: \"ready.kit-first-aid\",\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life. Each item of the kit has the date on its label.\" },\n },\n {\n id: \"communication.noaa-radio\",\n title: \"A NOAA Weather Radio with tone alert, on batteries or a hand crank\",\n kind: \"communication\",\n basis: \"ready.kit-radio\",\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life.\" },\n },\n {\n id: \"power.anker-737\",\n title: \"Anker 737 Power Bank (PowerCore 24K)\",\n kind: \"power\",\n want: { brands: [\"Anker\"], partNumbers: [\"A1289\"] },\n gives: [{ resource: \"energy.battery\", amount: { read: false, why: \"The page of the maker gives 24,000 mAh and no Wh. A charge does not convert to energy without its voltage.\" } }],\n shelf: { read: false, why: \"No source is read yet.\" },\n },\n ],\n};\n","import type { Source } from \"@mark1russell7/guidebook\";\nimport { convertible, quantity, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { moneyAbove } from \"./average.ts\";\n\n/** This function gives the money of a cost for each unit of time, for example `USD` for `USD/wk`. */\nfunction moneyOfRate(unit: string): string | undefined {\n const money = moneyAbove(unit);\n return money !== undefined && convertible(unit, `${money}/d`) ? money : undefined;\n}\n\n/*\n * This module has the cost of a food plan: the cost of the food of one week for one person of each age and sex, from\n * an official source. A check compares the food of a buy list with the cost of the plan for the same people and days.\n * The module names no person. The members of a household are input data.\n */\n\n/** The age and sex groups of a food plan of USDA. */\nexport const FOOD_PLAN_GROUPS = [\n \"child-1\",\n \"child-2-3\",\n \"child-4-5\",\n \"child-6-8\",\n \"child-9-11\",\n \"female-12-13\",\n \"female-14-19\",\n \"female-20-50\",\n \"female-51-70\",\n \"female-71-up\",\n \"male-12-13\",\n \"male-14-19\",\n \"male-20-50\",\n \"male-51-70\",\n \"male-71-up\",\n] as const;\n\n/** An age and sex group of a food plan. */\nexport type FoodPlanGroup = (typeof FOOD_PLAN_GROUPS)[number];\n\n/** The change of the cost for a size of household, for example 0.2 for one person. */\nexport interface FoodPlanSize {\n /** The smallest count of persons. */\n readonly from: number;\n /** The largest count of persons. Without it, the change applies to each larger household. */\n readonly to?: number | undefined;\n /** The change of the cost, as a fraction: 0.2 adds 20 percent, and -0.05 subtracts 5 percent. */\n readonly change: number;\n}\n\n/** The cost of a food plan in one area and one month, from one source. */\nexport interface FoodPlan {\n /** The id, for example `usda.thrifty:2026-10`. */\n readonly id: string;\n readonly title: string;\n /** The area, as the source names it, for example `U.S. average`. */\n readonly area: string;\n /** The month of the costs, in the form `YYYY-MM`. */\n readonly period: string;\n readonly source: Source;\n /** The place of the table in the source. */\n readonly locator: string;\n /** The cost of the food of one week for one person of each group, for example `{ \"value\": 58.7, \"unit\": \"USD/wk\" }`. */\n readonly weekly: Readonly<Record<FoodPlanGroup, Quantity>>;\n /** The change of the cost for each size of household. The costs of `weekly` are for the size with the change 0. */\n readonly sizes: readonly FoodPlanSize[];\n}\n\n/** A group of the members of a household, and the count of its persons. */\nexport interface FoodPlanMember {\n readonly group: FoodPlanGroup;\n readonly count: number;\n}\n\n/** The result of a check of the cost of food against a food plan. */\nexport interface FoodPlanCheck {\n /** The cost of the plan for the same members and days. */\n readonly plan: Quantity;\n /** The cost of the food, in the money of the plan. */\n readonly cost: Quantity;\n /** The cost of the food divided by the cost of the plan. */\n readonly ratio: number;\n /**\n * True when the food costs more than the plan. The Thrifty plan is the lowest of the four plans of USDA. Thus a list\n * above the cost of the Thrifty plan is not wrong when it has foods that cost more than staples.\n */\n readonly above: boolean;\n}\n\n/**\n * 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\n * each person, and then it applies the change for the size of the household.\n *\n * @param plan - The food plan\n * @param members - The groups of the members of the household, each with its count of persons\n * @param days - The count of days, a finite number of 0 or more\n * @throws RangeError when a count of persons is not a whole number of 0 or more, or when the household has no person\n * @throws RangeError when a group is not in the plan, or when the plan has no change for the size of the household\n * @throws RangeError when the count of days is not a finite number of 0 or more\n */\nexport function foodPlanCost(plan: FoodPlan, members: readonly FoodPlanMember[], days: number): Quantity {\n if (!(Number.isFinite(days) && days >= 0)) throw new RangeError(`The count of days is ${String(days)}. It must be a finite number of 0 or more.`);\n let persons = 0;\n let money: string | undefined;\n let total = 0;\n for (const member of members) {\n if (!(Number.isSafeInteger(member.count) && member.count >= 0)) throw new RangeError(`The count of the group ${member.group} is ${String(member.count)}. It must be a whole number of 0 or more.`);\n const weekly = plan.weekly[member.group] as Quantity | undefined;\n const symbol = weekly === undefined ? undefined : moneyOfRate(weekly.unit);\n if (weekly === undefined || symbol === undefined) throw new RangeError(`The plan ${plan.id} has no cost for each unit of time of the group ${String(member.group)}.`);\n if (money !== undefined && symbol !== money) throw new RangeError(`The plan ${plan.id} has costs in ${money} and in ${symbol}.`);\n money = symbol;\n persons += member.count;\n total += member.count * valueIn(weekly, `${symbol}/d`) * days;\n }\n if (persons === 0 || money === undefined) throw new RangeError(\"The household has no person.\");\n const size = plan.sizes.find((each) => persons >= each.from && (each.to === undefined || persons <= each.to));\n if (size === undefined) throw new RangeError(`The plan ${plan.id} has no change for a household of ${String(persons)} persons.`);\n return quantity(total * (1 + size.change), money);\n}\n\n/**\n * This function compares the cost of the food of a buy list with the cost of a food plan for the same members and\n * days. A list of dry staples costs less than the plan, because the plan is a full diet. A ratio above 1 tells that\n * 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.\n * The check of the amount of food is a check of its energy, not of its cost.\n *\n * @param cost - The cost of the food, in a money that converts to the money of the plan\n * @param plan - The food plan\n * @param members - The groups of the members of the household, each with its count of persons\n * @param days - The count of days of the food\n * @throws RangeError for the errors of `foodPlanCost`\n * @throws The error of `valueIn` of `@mark1russell7/quantity` when the money of the cost does not convert to the money of the plan\n */\nexport function foodPlanCheck(cost: Quantity, plan: FoodPlan, members: readonly FoodPlanMember[], days: number): FoodPlanCheck {\n const planned = foodPlanCost(plan, members, days);\n const value = valueIn(cost, planned.unit);\n const ratio = planned.value === 0 ? (value === 0 ? 0 : Number.POSITIVE_INFINITY) : value / planned.value;\n return { plan: planned, cost: quantity(value, planned.unit), ratio, above: ratio > 1 };\n}\n","import type { FoodPlan } from \"./food-plan.ts\";\n\n// The costs of the food plans of USDA. Each value is from the table of the report, read on 2026-11-22. The report\n// rounds each weekly cost to 10 cents. Footnote 2 of the report gives the change for each size of household.\n\nconst week = (value: number): { readonly value: number; readonly unit: string } => ({ value, unit: \"USD/wk\" });\n\n/** The costs of the food plans of USDA, one record for each plan and month. */\nexport const FOOD_PLANS: readonly FoodPlan[] = [\n {\n id: \"usda.thrifty:2026-10\",\n title: \"Official USDA Thrifty Food Plan: U.S. Average, October 2026\",\n area: \"U.S. average\",\n period: \"2026-10\",\n source: {\n id: \"usda.food-plans\",\n title: \"USDA Food Plans: Monthly Cost of Food Reports\",\n url: \"https://www.fna.usda.gov/research/cnpp/usda-food-plans/cost-food-monthly-reports\",\n license: \"us-public-domain\",\n checked: \"2026-11-22\",\n by: \"USDA Food and Nutrition Administration\",\n },\n locator: \"CostofFoodOct2026Thrifty.pdf, the column Weekly Cost of the table of age-sex groups\",\n weekly: {\n \"child-1\": week(26.4),\n \"child-2-3\": week(39.8),\n \"child-4-5\": week(43.5),\n \"child-6-8\": week(48.3),\n \"child-9-11\": week(55.8),\n \"female-12-13\": week(51.7),\n \"female-14-19\": week(60.1),\n \"female-20-50\": week(58.7),\n \"female-51-70\": week(54.6),\n \"female-71-up\": week(60.3),\n \"male-12-13\": week(59.7),\n \"male-14-19\": week(75.3),\n \"male-20-50\": week(73.7),\n \"male-51-70\": week(65),\n \"male-71-up\": week(62),\n },\n sizes: [\n { from: 1, to: 1, change: 0.2 },\n { from: 2, to: 2, change: 0.1 },\n { from: 3, to: 3, change: 0.05 },\n { from: 4, to: 4, change: 0 },\n { from: 5, to: 6, change: -0.05 },\n { from: 7, change: -0.1 },\n ],\n },\n];\n","import { quantity, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { giftsOf, type SupplyCatalog } from \"./supplies.ts\";\n\n/*\n * This module has the food energy of a buy list, from the catalog of supplies. It gives the energy of each line and\n * their sum. The energy need of the members, the days of food and the shortfall are not in this package. The days\n * depend on the water and the fuel that a case leaves, so the model of the endurance of the stores gives them.\n */\n\n/** The unit of each food energy. */\nconst ENERGY_UNIT = \"kcal\";\n\n/**\n * The food energy of the units of one product of a buy list, or no read with the reason. A no read is not 0.\n * The resources are the codes of the gifts of the product, for example `food.no-cook` or `food.grain-dry`.\n */\nexport type BuyListEnergyLine =\n | { readonly product: string; readonly units: number; readonly resources: readonly string[]; readonly read: true; readonly energy: Quantity }\n | { readonly product: string; readonly units: number; readonly resources: readonly string[]; readonly read: false; readonly why: string };\n\n/** The food energy of a buy list. */\nexport interface BuyListEnergy {\n /** The food energy of each product of the list, in the order of the list. */\n readonly lines: readonly BuyListEnergyLine[];\n /** True when each line has a read. When it is false, `energy` is a lower limit. */\n readonly read: boolean;\n /** The sum of the food energy of the lines with a read, in `kcal`. */\n readonly energy: Quantity;\n}\n\n/**\n * This function gives the food energy of a buy list, from the catalog. The energy of each product is its field\n * `energy` times its count of units. Each line has the resources of the product. Thus a caller can split the energy\n * of `food.no-cook` from the energy of the dry food.\n *\n * - A product with a no read for its energy gives a line with no read. A no read is not 0.\n * - A food product with no field `energy` also gives a line with no read.\n * - A product of another kind is not food, for example water or a battery. It gives no line, also when it has a\n * field `energy`. The gate of the catalog refuses that field on a product that is not food.\n * - A product with 0 units gives no line.\n *\n * The list can be the `units` of a buy order.\n *\n * @param catalog - The catalog of supplies\n * @param units - The count of units of each product of the list, by the `id` of the product\n * @throws RangeError when a count of units is not a finite number of 0 or more, or when the catalog has no such product\n * @throws RangeError when a product gives a resource that the catalog does not have, as for `giftsOf`\n * @throws The error of `valueIn` of `@mark1russell7/quantity` when the unit of an energy does not convert to `kcal`\n */\nexport function buyListEnergy(catalog: SupplyCatalog, units: Readonly<Record<string, number>>): BuyListEnergy {\n const lines: BuyListEnergyLine[] = [];\n for (const [id, count] of Object.entries(units)) {\n // `giftsOf` refuses a bad count of units and an unknown product.\n const resources = giftsOf(catalog, id, count).map((gift) => gift.resource);\n const product = catalog.products.find((each) => each.id === id);\n if (product === undefined || count === 0 || product.kind !== \"food\") continue;\n const energy = product.energy;\n if (energy === undefined) {\n lines.push({ product: id, units: count, resources, read: false, why: `The catalog has no food energy for the product ${id}.` });\n continue;\n }\n if (!energy.read) lines.push({ product: id, units: count, resources, read: false, why: energy.why });\n else lines.push({ product: id, units: count, resources, read: true, energy: quantity(count * valueIn(quantity(energy.amount, energy.unit), ENERGY_UNIT), ENERGY_UNIT) });\n }\n const total = lines.reduce((sum, line) => sum + (line.read ? line.energy.value : 0), 0);\n return { lines, read: lines.every((line) => line.read), energy: quantity(total, ENERGY_UNIT) };\n}\n"],"mappings":";;;;;AAcA,MAAa,gBAAgB;;AAG7B,MAAa,eAAe;CAAC;CAAS;CAAQ;CAAS;CAAS;CAAQ;CAAa;AAAe;;AA+FpG,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAqBA,SAAS,MAAM,MAAwB;CACrC,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,IAAI;EACF,OAAO,YAAY,MAAM,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAMA,gBAAc;;AAEpB,MAAM,aAAa;;;;;;AAMnB,SAAS,SAAS,MAAuB;CACvC,OAAO,YAAY,MAAM,IAAI,KAAK,YAAY,MAAM,GAAG,KAAK,UAAU,IAAI;AAC5E;;AAGA,SAAS,UAAU,MAAuB;CACxC,OAAO,cAAc,KAAK,IAAI,KAAK,OAAO,IAAI,MAAM;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,cAAc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AU,QAAQ,SAAS,MAAM,SAAS,KAAK,OAAO,EAAE;EAC9D,IAAI,YAAY,KAAA,KAAa,UAAU,KAAK,QAAQ,SAAS,QAAQ;EACrE,MAAM,SAAS,QAAQ;EACvB,IAAI,WAAW,KAAA,GAAW;GACxB,MAAM,KAAK;IAAE,SAAS;IAAI,OAAO;IAAO;IAAW,MAAM;IAAO,KAAK,kDAAkD,GAAG;GAAG,CAAC;GAC9H;EACF;EACA,IAAI,CAAC,OAAO,MAAM,MAAM,KAAK;GAAE,SAAS;GAAI,OAAO;GAAO;GAAW,MAAM;GAAO,KAAK,OAAO;EAAI,CAAC;OAC9F,MAAM,KAAK;GAAE,SAAS;GAAI,OAAO;GAAO;GAAW,MAAM;GAAM,QAAQ,SAAS,QAAQ,QAAQ,SAAS,OAAO,QAAQ,OAAO,IAAI,GAAG,WAAW,GAAG,WAAW;EAAE,CAAC;CACzK;CACA,MAAM,QAAQ,MAAM,QAAQ,KAAK,SAAS,OAAO,KAAK,OAAO,KAAK,OAAO,QAAQ,IAAI,CAAC;CACtF,OAAO;EAAE;EAAO,MAAM,MAAM,OAAO,SAAS,KAAK,IAAI;EAAG,QAAQ,SAAS,OAAO,WAAW;CAAE;AAC/F"}
|
|
1
|
+
{"version":3,"file":"supplies-entry.js","names":["ENERGY_UNIT"],"sources":["../src/supplies.ts","../src/supplies-data.ts","../src/food-plan.ts","../src/food-plan-data.ts","../src/buy-list-energy.ts"],"sourcesContent":["import { checkSources, checkUnits, type CitedUnit, type Finding, type FindingCode, type GateOptions, type Source } from \"@mark1russell7/guidebook\";\nimport { convertible, kindOf, quantity, rationals, valueIn, whyNotConvertible, type Quantity } from \"@mark1russell7/quantity\";\nimport { latestAverages, moneyOf, monthSchema, type AveragePrice } from \"./average.ts\";\nimport type { PartWant } from \"./offers.ts\";\nimport type { ProductWant } from \"./order.ts\";\n\n/*\n * This module is the format and the gate of a catalog of supplies: the products that a household keeps for an\n * emergency, the resource and the amount that one unit gives, and its shelf life. Each value has a cited fact, the\n * definition of the product, or an explicit no read. The facts and their sources are the records of\n * `@mark1russell7/guidebook`, and its gate examines them. The module names no person and no place.\n */\n\n/** The format of a catalog of supplies. */\nexport const SUPPLY_FORMAT = \"supply-catalog/1\";\n\n/** The kinds of the supplies. */\nexport const SUPPLY_KINDS = [\"water\", \"food\", \"power\", \"light\", \"heat\", \"first-aid\", \"communication\"] as const;\n\n/** A kind of a supply. */\nexport type SupplyKind = (typeof SUPPLY_KINDS)[number];\n\n/** A value that no source gives yet. The reason tells what is missing. */\nexport interface NoRead {\n readonly read: false;\n readonly why: string;\n}\n\n/**\n * An amount with its reason. The reason is a cited fact: the `id` of a unit of the catalog with the use `fact`.\n * Or it is the definition of the product, for example the 1 gal of a jug of 1 gal.\n */\nexport type CitedAmount =\n | { readonly read: true; readonly amount: number; readonly unit: string; readonly fact: string; readonly definition?: never }\n | { readonly read: true; readonly amount: number; readonly unit: string; readonly definition: string; readonly fact?: never };\n\n/** A resource that a supply gives, with its unit, for example `water.stored` in `L`. The codes are the resource codes of a store. */\nexport interface SupplyResource {\n readonly code: string;\n readonly unit: string;\n readonly title: string;\n}\n\n/** The gift of one unit of a product: an amount of one resource, or no read. */\nexport interface SupplyGift {\n readonly resource: string;\n readonly amount: CitedAmount | NoRead;\n}\n\n/**\n * The shelf life of a product: a cited amount of time, the `id` of a product of the FoodKeeper data of USDA FSIS, or no read.\n * The entry `/foodkeeper` of `@mark1russell7/stock` gives the due rule of a FoodKeeper product.\n */\nexport type ShelfLife = CitedAmount | { readonly read: true; readonly foodKeeper: number } | NoRead;\n\n/**\n * The join of a product to a series of average prices. It names the source and the series. It also gives the amount\n * 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\n * rice in USD/lb.\n */\nexport interface AverageJoin {\n readonly read: true;\n /** The source of the average prices, for example `bls-ap`. */\n readonly source: string;\n /** The id of the series in the source, for example `APU0000701312`. */\n readonly series: string;\n /** The amount of the item of the series in one unit of the product, with its reason. */\n readonly per: CitedAmount;\n}\n\n/** A product of the catalog. */\nexport interface SupplyProduct {\n readonly id: string;\n readonly title: string;\n readonly kind: SupplyKind;\n /** The part that the offers of a seller must match. A product with no part has no offer, so it has no price. */\n readonly want?: PartWant | undefined;\n /** The resources that one unit gives. A product that gives no stored resource, for example a radio, gives none. */\n readonly gives: readonly SupplyGift[];\n /** The `id` of a fact that tells why a kit has the product, for example the kit list of a public agency. */\n readonly basis?: string | undefined;\n /**\n * The count of units for each person of the household, in one bare count unit, for example 1 `{each}` of a sleeping\n * bag. A product with no field `perPerson` is one for the household. `kitMax` gives the count of units from it.\n */\n readonly perPerson?: CitedAmount | undefined;\n /** The food energy of one unit, in a unit of energy. A cooking converter gives it. */\n readonly energy?: CitedAmount | NoRead | undefined;\n /**\n * The amount of one unit as sold: a mass, a volume or a count, for example 1 kg, 530 g or 1 gal.\n * A product with no known size has no field `size`. A no read is for a product that has a size, when the source\n * of the size is not read yet, for example a label.\n */\n readonly size?: CitedAmount | NoRead | undefined;\n readonly shelf: ShelfLife;\n /**\n * The series of average prices that gives the price of one unit, or no read with the reason. A product with no join\n * and no part has no price.\n */\n readonly average?: AverageJoin | NoRead | undefined;\n}\n\n/** A catalog of supplies: the sources, the cited facts, the resources and the products. */\nexport interface SupplyCatalog {\n readonly format: typeof SUPPLY_FORMAT;\n readonly sources: readonly Source[];\n readonly facts: readonly CitedUnit[];\n readonly resources: readonly SupplyResource[];\n readonly products: readonly SupplyProduct[];\n}\n\n/** The codes of the findings of the catalog gate. */\nexport const SUPPLY_CODES = [\n \"supplies-format\",\n \"supplies-twice\",\n \"supplies-kind\",\n \"supplies-resource\",\n \"supplies-fact\",\n \"supplies-basis\",\n \"supplies-amount\",\n \"supplies-unit\",\n \"supplies-shelf\",\n \"supplies-unused\",\n \"supplies-no-read\",\n \"supplies-no-reason\",\n] as const;\n\n/** A code of a finding of the catalog gate. */\nexport type SupplyCode = (typeof SUPPLY_CODES)[number];\n\n/** A finding of the catalog gate, or of the gate of the facts and their sources. */\nexport type SupplyFinding = Finding<SupplyCode | FindingCode, \"source\" | \"unit\" | \"resource\" | \"product\">;\n\n/**\n * The options of the catalog gate: the options of the gate of the sources, and the known FoodKeeper ids.\n */\nexport interface SupplyGateOptions extends GateOptions {\n /**\n * The ids of the products of the FoodKeeper data, for example the ids of `FOODKEEPER_PRODUCTS` of the entry\n * `/foodkeeper` of `@mark1russell7/stock`. With this option, a shelf life with an id that is not in the set is an\n * error. With no option, the gate does not examine the ids against the data.\n */\n readonly foodKeeper?: ReadonlySet<number> | readonly number[] | undefined;\n}\n\n/** This function tells if a text is a unit of `@mark1russell7/quantity`. `convertible` throws for an unknown unit. */\nfunction known(unit: unknown): boolean {\n if (typeof unit !== \"string\") return false;\n try {\n return convertible(unit, unit);\n } catch {\n return false;\n }\n}\n\n/** The unit that each food energy converts to. */\nconst ENERGY_UNIT = \"kcal\";\n/** The unit that each shelf life converts to. */\nconst SHELF_UNIT = \"d\";\n/**\n * This function gives true for the unit of a size. That is a mass or a volume that converts to `kg` or `L`, or one\n * bare count, for example `{each}`. The kind of a unit is not sufficient. For example, `g/{each}` has the kind\n * mass, and it does not convert to `kg`.\n */\nfunction sizeUnit(unit: string): boolean {\n return convertible(unit, \"kg\") || convertible(unit, \"L\") || countUnit(unit);\n}\n\n/** This function gives true for one bare count unit, for example `{each}`. */\nfunction countUnit(unit: string): boolean {\n return /^{[^{}/]+}$/.test(unit) && kindOf(unit) === \"count\";\n}\n\n/**\n * This function examines a catalog. It gives the findings of the sources and the facts (the gate of\n * `@mark1russell7/guidebook`), and the findings of the products:\n *\n * - 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.\n * - An error for a product that gives no resource and has no basis.\n * - An error for a field `energy` on a product that is not food. The field is the food energy of one unit.\n * - 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\n * product is also a fact.\n * - An error for an amount with no reason, with two reasons, or with a blank definition. A catalog from JSON can have them.\n * - An error for a unit that is not a unit of `@mark1russell7/quantity`.\n * - An error for a unit that does not convert to the unit of its resource.\n * - An error for a size in a unit that is not a mass, a volume or a count, for example `h` or `kcal`.\n * - An error for a count for each person in a unit that is not one bare count, for example `kg` or `{each}/{person}`.\n * - The amount of the item of an average price has the same checks as each other amount.\n * - With the option `foodKeeper`, an error for a FoodKeeper id of a shelf life that is not in the known ids.\n * - A warning for each value with no read, and for a no read with a blank reason.\n * - A warning for each fact and each source that no product uses.\n *\n * The function takes a decoded catalog: each record has the fields of its type. Decode a catalog from JSON first, for\n * example with the entry `/read` of `@mark1russell7/optional`. The gate then finds the values that the type does not hold.\n *\n * @param catalog - The catalog\n * @param options - The options of the gate of the sources, for example the date of the gate, and the known FoodKeeper ids\n */\nexport function checkSupplies(catalog: SupplyCatalog, options: SupplyGateOptions = {}): SupplyFinding[] {\n const { foodKeeper: knownFoodKeeper, ...gate } = options;\n const foodKeeper = knownFoodKeeper === undefined ? undefined : new Set<number>(knownFoodKeeper);\n const out: SupplyFinding[] = [...checkSources(catalog.sources, gate), ...checkUnits(catalog.facts, catalog.sources, gate)];\n const error = (code: SupplyCode, record: \"resource\" | \"product\", id: string, message: string): void => {\n out.push({ level: \"error\", code, record, id, message });\n };\n const warning = (code: SupplyCode, record: \"source\" | \"unit\" | \"product\", id: string, message: string): void => {\n out.push({ level: \"warning\", code, record, id, message });\n };\n if (catalog.format !== SUPPLY_FORMAT) error(\"supplies-format\", \"product\", \"\", `The format is ${String(catalog.format)}. It must be ${SUPPLY_FORMAT}.`);\n\n const resources = new Map<string, SupplyResource>();\n for (const resource of catalog.resources) {\n if (resources.has(resource.code)) error(\"supplies-twice\", \"resource\", resource.code, `The resource ${resource.code} is two times in the catalog.`);\n if (!known(resource.unit)) error(\"supplies-unit\", \"resource\", resource.code, `The unit ${String(resource.unit)} of the resource ${resource.code} is not a known unit.`);\n resources.set(resource.code, resource);\n }\n const facts = new Map(catalog.facts.map((fact) => [fact.id, fact]));\n const used = new Set<string>();\n\n /** This function examines one cited amount, and gives the unit check to `units`. */\n const amount = (product: string, what: string, value: CitedAmount | NoRead, unit: string): void => {\n if (!value.read) {\n warning(\"supplies-no-read\", \"product\", product, `The ${what} of the product ${product} is no read: ${String(value.why)}`);\n if (typeof value.why !== \"string\" || value.why.trim() === \"\") warning(\"supplies-no-reason\", \"product\", product, `The no read of the ${what} of the product ${product} has no reason.`);\n return;\n }\n // The type permits one reason only. A catalog from JSON can have no reason, two reasons or a blank definition.\n const reasons = (value.fact === undefined ? 0 : 1) + (value.definition === undefined ? 0 : 1);\n if (reasons !== 1) error(\"supplies-fact\", \"product\", product, `The ${what} of the product ${product} has ${String(reasons)} reasons. It must have a fact or a definition, not the two.`);\n else if (value.definition !== undefined && (typeof value.definition !== \"string\" || value.definition.trim() === \"\")) error(\"supplies-fact\", \"product\", product, `The definition of the ${what} of the product ${product} is blank.`);\n if (value.fact !== undefined) {\n const fact = facts.get(value.fact);\n if (fact === undefined || fact.use !== \"fact\") error(\"supplies-fact\", \"product\", product, `The ${what} of the product ${product} cites ${value.fact}, and the catalog has no fact with that id.`);\n used.add(value.fact);\n }\n if (!(Number.isFinite(value.amount) && value.amount > 0)) error(\"supplies-amount\", \"product\", product, `The ${what} of the product ${product} is ${String(value.amount)}. It must be a finite number more than 0.`);\n if (!known(value.unit)) error(\"supplies-unit\", \"product\", product, `The unit ${String(value.unit)} of the ${what} of the product ${product} is not a known unit.`);\n else if (known(unit) && !convertible(value.unit, unit)) error(\"supplies-unit\", \"product\", product, `The ${what} of the product ${product} is in ${value.unit}, and ${value.unit} does not convert to ${unit}.`);\n };\n\n const products = new Set<string>();\n for (const product of catalog.products) {\n if (products.has(product.id)) error(\"supplies-twice\", \"product\", product.id, `The product ${product.id} is two times in the catalog.`);\n products.add(product.id);\n if (!(SUPPLY_KINDS as readonly string[]).includes(product.kind)) error(\"supplies-kind\", \"product\", product.id, `The kind ${String(product.kind)} of the product ${product.id} is not a supply kind.`);\n const gifts = new Set<string>();\n for (const gift of product.gives) {\n if (gifts.has(gift.resource)) error(\"supplies-twice\", \"product\", product.id, `The product ${product.id} gives the resource ${gift.resource} two times.`);\n gifts.add(gift.resource);\n const resource = resources.get(gift.resource);\n if (resource === undefined) error(\"supplies-resource\", \"product\", product.id, `The product ${product.id} gives the resource ${gift.resource}, and the catalog has no such resource.`);\n else amount(product.id, `gift of ${gift.resource}`, gift.amount, resource.unit);\n }\n if (product.gives.length === 0 && product.basis === undefined) error(\"supplies-basis\", \"product\", product.id, `The product ${product.id} gives no resource and has no basis. A product that gives no resource cites a fact in its basis.`);\n if (product.basis !== undefined) {\n const fact = facts.get(product.basis);\n if (fact === undefined || fact.use !== \"fact\") error(\"supplies-fact\", \"product\", product.id, `The basis of the product ${product.id} cites ${String(product.basis)}, and the catalog has no fact with that id.`);\n used.add(product.basis);\n }\n // An unknown kind has its own error above, so this rule examines only a known kind that is not food.\n if (product.energy !== undefined && product.kind !== \"food\" && (SUPPLY_KINDS as readonly string[]).includes(product.kind)) error(\"supplies-kind\", \"product\", product.id, `The product ${product.id} has a food energy, and its kind is ${String(product.kind)}. Only a product of the kind food has a food energy.`);\n if (product.energy !== undefined) amount(product.id, \"food energy\", product.energy, ENERGY_UNIT);\n if (product.size !== undefined) {\n // The size has no single unit to convert to. Its unit must be a mass, a volume or one bare count. An unknown unit\n // has its own error.\n amount(product.id, \"size\", product.size, \"\");\n if (product.size.read && known(product.size.unit) && !sizeUnit(product.size.unit))\n error(\"supplies-unit\", \"product\", product.id, `The size of the product ${product.id} is in ${product.size.unit}. It must be a mass, a volume or a count.`);\n }\n if (product.perPerson !== undefined) {\n // The count has no single unit to convert to. Its unit must be one bare count. An unknown unit has its own error.\n // A count that is not read gives no count of units, so the gate refuses it. A catalog from JSON can have one.\n if (product.perPerson.read !== true) error(\"supplies-amount\", \"product\", product.id, `The count for each person of the product ${product.id} is not read. A product with no known count has no field perPerson.`);\n else amount(product.id, \"count for each person\", product.perPerson, \"\");\n if (product.perPerson.read === true && known(product.perPerson.unit) && !countUnit(product.perPerson.unit))\n error(\"supplies-unit\", \"product\", product.id, `The count for each person of the product ${product.id} is in ${product.perPerson.unit}. It must be one bare count, for example {each}.`);\n }\n if (product.average !== undefined) amount(product.id, \"average price\", product.average.read ? product.average.per : product.average, product.average.read ? product.average.per.unit : \"\");\n if (\"foodKeeper\" in product.shelf) {\n if (!(Number.isSafeInteger(product.shelf.foodKeeper) && product.shelf.foodKeeper > 0)) error(\"supplies-shelf\", \"product\", product.id, `The FoodKeeper id of the product ${product.id} is ${String(product.shelf.foodKeeper)}. It must be a whole number more than 0.`);\n else if (foodKeeper !== undefined && !foodKeeper.has(product.shelf.foodKeeper))\n error(\"supplies-shelf\", \"product\", product.id, `The FoodKeeper id ${String(product.shelf.foodKeeper)} of the product ${product.id} is not in the known FoodKeeper ids.`);\n } else amount(product.id, \"shelf life\", product.shelf, SHELF_UNIT);\n }\n\n for (const fact of catalog.facts) if (!used.has(fact.id)) warning(\"supplies-unused\", \"unit\", fact.id, `No product uses the fact ${fact.id}.`);\n const cited = new Set(catalog.facts.map((fact) => fact.source));\n for (const source of catalog.sources) if (!cited.has(source.id)) warning(\"supplies-unused\", \"source\", source.id, `No fact cites the source ${source.id}.`);\n return out;\n}\n\n/**\n * This function gives the wants of the products with a part, in the order of the catalog, for `buyCandidates`.\n * A product with no part has no offer, so it is not in the result.\n *\n * @param catalog - The catalog\n * @param max - The largest count of units of a product. The default is 1 for each product\n */\nexport function supplyWants(catalog: SupplyCatalog, max: (product: SupplyProduct) => number = () => 1): ProductWant[] {\n return catalog.products.flatMap((product) => (product.want === undefined ? [] : [{ product: product.id, want: product.want, max: max(product) }]));\n}\n\n/**\n * This function gives the largest count of units of each product for a household, for `supplyWants`. A product with a\n * count for each person has that count times the persons, up to the next whole unit. Each other product has 1. The\n * product is exact: the count is the decimal of its number, so 1.1 for each person of 50 persons gives 55, not 56.\n *\n * @param people - The count of persons of the household. The persons are input data of the user.\n * @returns The function `max` of `supplyWants`\n * @throws RangeError when the count of persons is not a whole number of 0 or more\n */\nexport function kitMax(people: number): (product: SupplyProduct) => number {\n if (!(Number.isSafeInteger(people) && people >= 0)) throw new RangeError(`The count of persons is ${String(people)}. It must be a whole number of 0 or more.`);\n const persons = rationals.fromNumber(people);\n return (product) => (product.perPerson === undefined ? 1 : rationals.toNumber(rationals.ceil(rationals.mul(rationals.fromNumber(product.perPerson.amount), persons))));\n}\n\n/** The gift of a count of units: an amount in the unit of its resource, or no read. */\nexport type GiftOf = { readonly resource: string; readonly read: true; readonly amount: number; readonly unit: string } | { readonly resource: string; readonly read: false; readonly why: string };\n\n/**\n * This function gives the resources of a count of units of a product, each in the unit of its resource.\n * A gift with no read stays no read: it is not 0.\n *\n * @param catalog - The catalog\n * @param id - The `id` of the product\n * @param units - The count of units\n * @throws RangeError when the count of units is not a finite number of 0 or more\n * @throws RangeError when the catalog has no such product, or a gift of an unknown resource\n * @throws The error of `valueIn` of `@mark1russell7/quantity` when the unit of a gift does not convert to the unit of its resource\n */\nexport function giftsOf(catalog: SupplyCatalog, id: string, units: number): GiftOf[] {\n if (!(Number.isFinite(units) && units >= 0)) throw new RangeError(`The count of units is ${String(units)}. It must be a finite number of 0 or more.`);\n const product = catalog.products.find((each) => each.id === id);\n if (product === undefined) throw new RangeError(`The catalog has no product ${id}.`);\n return product.gives.map((gift): GiftOf => {\n const resource = catalog.resources.find((each) => each.code === gift.resource);\n if (resource === undefined) throw new RangeError(`The product ${id} gives the resource ${gift.resource}, and the catalog has no such resource.`);\n if (!gift.amount.read) return { resource: gift.resource, read: false, why: gift.amount.why };\n return { resource: gift.resource, read: true, amount: units * valueIn(quantity(gift.amount.amount, gift.amount.unit), resource.unit), unit: resource.unit };\n });\n}\n\n/** The price of one unit of a product from an average price, or no read with the reason. */\nexport type SupplyPrice =\n | { readonly product: string; readonly read: true; readonly price: Quantity; readonly average: string; readonly period: string }\n | { readonly product: string; readonly read: false; readonly why: string };\n\n/**\n * This function gives the price of one unit of each product with a join to a series, in the order of the catalog.\n * It takes the last month of each series (`latestAverages`). The price is in the money of the average price.\n *\n * - A product with no join is not in the result.\n * - 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.\n * - The unit of the series must convert to the unit of the product, for example USD/lb to 1 kg.\n * - With the option `since`, a last price before that month gives no read. A series that stops then gives no old price.\n *\n * @param catalog - The catalog\n * @param prices - The average prices, from one or more reads\n * @param options - The option `since`: the first month of a price that the result can use, in the form `YYYY-MM`\n * @returns The price of one unit of each product with a join, or no read with the reason\n * @throws RangeError when `since` is not a month in the form `YYYY-MM`\n */\nexport function averageSupplyPrices(catalog: SupplyCatalog, prices: readonly AveragePrice[], options: { readonly since?: string | undefined } = {}): SupplyPrice[] {\n const { since } = options;\n if (since !== undefined && !monthSchema.safeParse(since).success) throw new RangeError(`The month ${String(since)} is not in the form YYYY-MM.`);\n const last = new Map(latestAverages(prices).map((price) => [`${price.source}:${price.series}`, price]));\n return catalog.products.flatMap((product): SupplyPrice[] => {\n const join = product.average;\n if (join === undefined) return [];\n const none = (why: string): SupplyPrice[] => [{ product: product.id, read: false, why }];\n if (!join.read) return none(join.why);\n const average = last.get(`${join.source}:${join.series}`);\n if (average === undefined) return none(`The prices have no average price of the series ${join.series} of ${join.source}.`);\n if (since !== undefined && average.period < since) return none(`The last average price of the series ${join.series} of ${join.source} is for ${average.period}, before ${since}.`);\n const money = moneyOf(average.price.unit);\n if (money === undefined) return none(`The unit ${average.price.unit} of ${average.id} is not a price for each unit of an amount.`);\n if (!known(join.per.unit)) return none(`The unit ${String(join.per.unit)} of the product ${product.id} is not a known unit.`);\n const unit = `${money}/${join.per.unit}`;\n const why = whyNotConvertible(average.price.unit, unit);\n if (why !== undefined) return none(`The average price ${average.id} is in ${average.price.unit}, and it does not convert to ${unit}: ${why}.`);\n const price = quantity(valueIn(average.price, unit) * join.per.amount, money);\n return [{ product: product.id, read: true, price, average: average.id, period: average.period }];\n });\n}\n","import { SUPPLY_FORMAT, type SupplyCatalog } from \"./supplies.ts\";\n\n// The reference catalog of supplies. Each value has a cited fact, the definition of the product, or a no read.\n// Each fact is in own words, not a quote. The shelf life of a food is a product of the FoodKeeper data of USDA FSIS:\n// the entry `/foodkeeper` of `@mark1russell7/stock` gives its due rule, so this catalog does not copy its times.\n\nconst CHECKED = \"2026-11-22\";\n\n/** The reference catalog of supplies. A household adds its own products to a copy of it. */\nexport const SUPPLY_CATALOG: SupplyCatalog = {\n format: SUPPLY_FORMAT,\n sources: [\n { id: \"ready.water\", title: \"Water\", url: \"https://www.ready.gov/water\", license: \"us-public-domain\", checked: CHECKED, by: \"FEMA (Ready.gov)\" },\n { id: \"ready.kit\", title: \"Build A Kit\", url: \"https://www.ready.gov/kit\", license: \"us-public-domain\", checked: CHECKED, by: \"FEMA (Ready.gov)\" },\n { id: \"fdc.sr-legacy\", title: \"FoodData Central, SR Legacy\", url: \"https://fdc.nal.usda.gov/\", license: \"cc0\", checked: CHECKED, by: \"USDA Agricultural Research Service\" },\n ],\n facts: [\n {\n id: \"ready.water-replace\",\n use: \"fact\",\n text: \"The page tells to replace the stored water that is not commercially bottled each six months.\",\n source: \"ready.water\",\n locator: \"Water storage\",\n },\n {\n id: \"fdc.rice-white\",\n use: \"fact\",\n text: \"The item 168877 (white long-grain rice, raw, enriched) gives 365 kcal in 100 g. Thus 1 kg gives 3650 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 168877\",\n },\n {\n id: \"fdc.oats\",\n use: \"fact\",\n text: \"The item 173904 (oats, regular and quick, not fortified, dry) gives 379 kcal in 100 g. Thus 1 kg gives 3790 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 173904\",\n },\n {\n id: \"fdc.beans-black\",\n use: \"fact\",\n text: \"The item 173734 (black beans, mature seeds, raw) gives 341 kcal in 100 g. Thus 1 kg gives 3410 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 173734\",\n },\n {\n id: \"fdc.peanut-butter\",\n use: \"fact\",\n text: \"The item 174266 (peanut butter, smooth style, with salt) gives 598 kcal in 100 g. Thus 1 kg gives 5980 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 174266\",\n },\n {\n id: \"fdc.pasta\",\n use: \"fact\",\n text: \"The item 168927 (pasta, dry, unenriched) gives 371 kcal in 100 g. Thus 1 kg gives 3710 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 168927\",\n },\n {\n id: \"fdc.flour-white\",\n use: \"fact\",\n text: \"The item 169761 (wheat flour, white, all-purpose, unenriched) gives 364 kcal in 100 g. Thus 1 kg gives 3640 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 169761\",\n },\n {\n id: \"fdc.soup-chicken-noodle\",\n use: \"fact\",\n text: \"The item 171148 (chunky chicken noodle soup, canned, ready-to-serve) gives 41 kcal in 100 g. Its portion of 1 can is 530 g. Thus 1 can gives 217.3 kcal.\",\n source: \"fdc.sr-legacy\",\n locator: \"FDC ID 171148, portion 1 can (530 g)\",\n },\n {\n id: \"ready.kit-flashlight\",\n use: \"fact\",\n text: \"The basic kit of the page has a flashlight and extra batteries.\",\n source: \"ready.kit\",\n locator: \"Basic Disaster Supplies Kit\",\n },\n {\n id: \"ready.kit-first-aid\",\n use: \"fact\",\n text: \"The basic kit of the page has a first aid kit.\",\n source: \"ready.kit\",\n locator: \"Basic Disaster Supplies Kit\",\n },\n {\n id: \"ready.kit-radio\",\n use: \"fact\",\n text: \"The basic kit of the page has a radio on batteries or a hand crank, and a NOAA Weather Radio with tone alert.\",\n source: \"ready.kit\",\n locator: \"Basic Disaster Supplies Kit\",\n },\n {\n id: \"ready.kit-sleeping-bag\",\n use: \"fact\",\n text: \"The page tells to add a sleeping bag or a warm blanket for each person.\",\n source: \"ready.kit\",\n locator: \"Additional Emergency Supplies\",\n },\n ],\n resources: [\n { code: \"water.stored\", unit: \"L\", title: \"Stored drinking water\" },\n { code: \"food.grain-dry\", unit: \"kg\", title: \"Dry grain, to cook with water and fuel\" },\n { code: \"food.legume-dry\", unit: \"kg\", title: \"Dry beans, to cook with water and fuel\" },\n { code: \"food.pasta-dry\", unit: \"kg\", title: \"Dry pasta, to boil in water that the cook drains\" },\n { code: \"food.flour\", unit: \"kg\", title: \"Flour, to bake or cook with water and fuel\" },\n { code: \"food.no-cook\", unit: \"kcal\", title: \"Food energy to eat with no water and no fuel\" },\n { code: \"energy.battery\", unit: \"Wh\", title: \"Energy in a battery\" },\n ],\n products: [\n {\n id: \"water.jug-1gal\",\n title: \"Drinking water, commercially bottled, in a jug of 1 gal\",\n kind: \"water\",\n gives: [{ resource: \"water.stored\", amount: { read: true, amount: 1, unit: \"gal\", definition: \"The product is a jug of 1 gal.\" } }],\n size: { read: true, amount: 1, unit: \"gal\", definition: \"The catalog item is defined as a jug of 1 gal.\" },\n shelf: { read: false, why: \"The source tells to keep commercially bottled water sealed, and it gives no time. The date on the label applies.\" },\n },\n {\n id: \"water.container-1gal\",\n title: \"A water container of 1 gal, filled from the tap\",\n kind: \"water\",\n gives: [{ resource: \"water.stored\", amount: { read: true, amount: 1, unit: \"gal\", definition: \"The product is a container of 1 gal.\" } }],\n shelf: { read: true, amount: 6, unit: \"mo\", fact: \"ready.water-replace\" },\n },\n {\n id: \"food.rice-white-1kg\",\n title: \"White long-grain rice, dry, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.grain-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry rice.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry rice.\" },\n energy: { read: true, amount: 3650, unit: \"kcal\", fact: \"fdc.rice-white\" },\n shelf: { read: true, foodKeeper: 338 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000701312\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry white long-grain rice, the item of the series.\" },\n },\n },\n {\n id: \"food.oats-1kg\",\n title: \"Rolled oats, dry, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.grain-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry oats.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry oats.\" },\n energy: { read: true, amount: 3790, unit: \"kcal\", fact: \"fdc.oats\" },\n shelf: { read: true, foodKeeper: 375 },\n average: { read: false, why: \"The known series of average prices have no series of oats yet.\" },\n },\n {\n id: \"food.beans-dry-1kg\",\n title: \"Dry beans, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.legume-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry beans.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry beans.\" },\n energy: { read: true, amount: 3410, unit: \"kcal\", fact: \"fdc.beans-black\" },\n shelf: { read: true, foodKeeper: 333 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000714233\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry beans of any type, the item of the series.\" },\n },\n },\n {\n id: \"food.peanut-butter-1kg\",\n title: \"Peanut butter, smooth, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.no-cook\", amount: { read: true, amount: 5980, unit: \"kcal\", fact: \"fdc.peanut-butter\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of peanut butter.\" },\n energy: { read: true, amount: 5980, unit: \"kcal\", fact: \"fdc.peanut-butter\" },\n shelf: { read: true, foodKeeper: 387 },\n average: { read: false, why: \"The known series of average prices have no series of peanut butter yet.\" },\n },\n {\n id: \"food.pasta-dry-1kg\",\n title: \"Dry pasta, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.pasta-dry\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry pasta.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of dry pasta.\" },\n energy: { read: true, amount: 3710, unit: \"kcal\", fact: \"fdc.pasta\" },\n shelf: { read: true, foodKeeper: 335 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000701322\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of dry spaghetti or macaroni, the item of the series.\" },\n },\n },\n {\n id: \"food.flour-white-1kg\",\n title: \"White all-purpose flour, 1 kg\",\n kind: \"food\",\n gives: [{ resource: \"food.flour\", amount: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of white flour.\" } }],\n size: { read: true, amount: 1, unit: \"kg\", definition: \"The catalog item is defined as a package of 1 kg of white flour.\" },\n energy: { read: true, amount: 3640, unit: \"kcal\", fact: \"fdc.flour-white\" },\n shelf: { read: true, foodKeeper: 222 },\n average: {\n read: true,\n source: \"bls-ap\",\n series: \"APU0000701111\",\n per: { read: true, amount: 1, unit: \"kg\", definition: \"The product is 1 kg of white all-purpose flour, the item of the series.\" },\n },\n },\n {\n id: \"food.soup-can\",\n title: \"Chunky chicken noodle soup, ready-to-serve, 1 can (530 g)\",\n kind: \"food\",\n gives: [{ resource: \"food.no-cook\", amount: { read: true, amount: 217.3, unit: \"kcal\", fact: \"fdc.soup-chicken-noodle\" } }],\n size: { read: true, amount: 530, unit: \"g\", fact: \"fdc.soup-chicken-noodle\" },\n energy: { read: true, amount: 217.3, unit: \"kcal\", fact: \"fdc.soup-chicken-noodle\" },\n shelf: { read: true, foodKeeper: 372 },\n average: { read: false, why: \"The known series of average prices have no series of canned soup yet.\" },\n },\n {\n id: \"light.flashlight\",\n title: \"A flashlight on batteries\",\n kind: \"light\",\n basis: \"ready.kit-flashlight\",\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life. The batteries have the date on their label.\" },\n },\n {\n id: \"heat.sleeping-bag\",\n title: \"A sleeping bag for each person\",\n kind: \"heat\",\n basis: \"ready.kit-sleeping-bag\",\n perPerson: { read: true, amount: 1, unit: \"{each}\", fact: \"ready.kit-sleeping-bag\" },\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life.\" },\n },\n {\n id: \"first-aid.kit\",\n title: \"A first aid kit\",\n kind: \"first-aid\",\n basis: \"ready.kit-first-aid\",\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life. Each item of the kit has the date on its label.\" },\n },\n {\n id: \"communication.noaa-radio\",\n title: \"A NOAA Weather Radio with tone alert, on batteries or a hand crank\",\n kind: \"communication\",\n basis: \"ready.kit-radio\",\n gives: [],\n shelf: { read: false, why: \"The source gives no shelf life.\" },\n },\n {\n id: \"power.anker-737\",\n title: \"Anker 737 Power Bank (PowerCore 24K)\",\n kind: \"power\",\n want: { brands: [\"Anker\"], partNumbers: [\"A1289\"] },\n gives: [{ resource: \"energy.battery\", amount: { read: false, why: \"The page of the maker gives 24,000 mAh and no Wh. A charge does not convert to energy without its voltage.\" } }],\n shelf: { read: false, why: \"No source is read yet.\" },\n },\n ],\n};\n","import type { Source } from \"@mark1russell7/guidebook\";\nimport { atomAbove, convertible, quantity, valueIn, type Quantity } from \"@mark1russell7/quantity\";\n\n/** This function gives the money of a cost for each unit of time, for example `USD` for `USD/wk`. */\nfunction moneyOfRate(unit: string): string | undefined {\n const money = atomAbove(unit, \"money\");\n return money !== undefined && convertible(unit, `${money}/d`) ? money : undefined;\n}\n\n/*\n * This module has the cost of a food plan: the cost of the food of one week for one person of each age and sex, from\n * an official source. A check compares the food of a buy list with the cost of the plan for the same people and days.\n * The module names no person. The members of a household are input data.\n */\n\n/** The age and sex groups of a food plan of USDA. */\nexport const FOOD_PLAN_GROUPS = [\n \"child-1\",\n \"child-2-3\",\n \"child-4-5\",\n \"child-6-8\",\n \"child-9-11\",\n \"female-12-13\",\n \"female-14-19\",\n \"female-20-50\",\n \"female-51-70\",\n \"female-71-up\",\n \"male-12-13\",\n \"male-14-19\",\n \"male-20-50\",\n \"male-51-70\",\n \"male-71-up\",\n] as const;\n\n/** An age and sex group of a food plan. */\nexport type FoodPlanGroup = (typeof FOOD_PLAN_GROUPS)[number];\n\n/** The change of the cost for a size of household, for example 0.2 for one person. */\nexport interface FoodPlanSize {\n /** The smallest count of persons. */\n readonly from: number;\n /** The largest count of persons. Without it, the change applies to each larger household. */\n readonly to?: number | undefined;\n /** The change of the cost, as a fraction: 0.2 adds 20 percent, and -0.05 subtracts 5 percent. */\n readonly change: number;\n}\n\n/** The cost of a food plan in one area and one month, from one source. */\nexport interface FoodPlan {\n /** The id, for example `usda.thrifty:2026-10`. */\n readonly id: string;\n readonly title: string;\n /** The area, as the source names it, for example `U.S. average`. */\n readonly area: string;\n /** The month of the costs, in the form `YYYY-MM`. */\n readonly period: string;\n readonly source: Source;\n /** The place of the table in the source. */\n readonly locator: string;\n /** The cost of the food of one week for one person of each group, for example `{ \"value\": 58.7, \"unit\": \"USD/wk\" }`. */\n readonly weekly: Readonly<Record<FoodPlanGroup, Quantity>>;\n /** The change of the cost for each size of household. The costs of `weekly` are for the size with the change 0. */\n readonly sizes: readonly FoodPlanSize[];\n}\n\n/** A group of the members of a household, and the count of its persons. */\nexport interface FoodPlanMember {\n readonly group: FoodPlanGroup;\n readonly count: number;\n}\n\n/** The result of a check of the cost of food against a food plan. */\nexport interface FoodPlanCheck {\n /** The cost of the plan for the same members and days. */\n readonly plan: Quantity;\n /** The cost of the food, in the money of the plan. */\n readonly cost: Quantity;\n /** The cost of the food divided by the cost of the plan. */\n readonly ratio: number;\n /**\n * True when the food costs more than the plan. The Thrifty plan is the lowest of the four plans of USDA. Thus a list\n * above the cost of the Thrifty plan is not wrong when it has foods that cost more than staples.\n */\n readonly above: boolean;\n}\n\n/**\n * 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\n * each person, and then it applies the change for the size of the household.\n *\n * @param plan - The food plan\n * @param members - The groups of the members of the household, each with its count of persons\n * @param days - The count of days, a finite number of 0 or more\n * @throws RangeError when a count of persons is not a whole number of 0 or more, or when the household has no person\n * @throws RangeError when a group is not in the plan, or when the plan has no change for the size of the household\n * @throws RangeError when the count of days is not a finite number of 0 or more\n */\nexport function foodPlanCost(plan: FoodPlan, members: readonly FoodPlanMember[], days: number): Quantity {\n if (!(Number.isFinite(days) && days >= 0)) throw new RangeError(`The count of days is ${String(days)}. It must be a finite number of 0 or more.`);\n let persons = 0;\n let money: string | undefined;\n let total = 0;\n for (const member of members) {\n if (!(Number.isSafeInteger(member.count) && member.count >= 0)) throw new RangeError(`The count of the group ${member.group} is ${String(member.count)}. It must be a whole number of 0 or more.`);\n const weekly = plan.weekly[member.group] as Quantity | undefined;\n const symbol = weekly === undefined ? undefined : moneyOfRate(weekly.unit);\n if (weekly === undefined || symbol === undefined) throw new RangeError(`The plan ${plan.id} has no cost for each unit of time of the group ${String(member.group)}.`);\n if (money !== undefined && symbol !== money) throw new RangeError(`The plan ${plan.id} has costs in ${money} and in ${symbol}.`);\n money = symbol;\n persons += member.count;\n total += member.count * valueIn(weekly, `${symbol}/d`) * days;\n }\n if (persons === 0 || money === undefined) throw new RangeError(\"The household has no person.\");\n const size = plan.sizes.find((each) => persons >= each.from && (each.to === undefined || persons <= each.to));\n if (size === undefined) throw new RangeError(`The plan ${plan.id} has no change for a household of ${String(persons)} persons.`);\n return quantity(total * (1 + size.change), money);\n}\n\n/**\n * This function compares the cost of the food of a buy list with the cost of a food plan for the same members and\n * days. A list of dry staples costs less than the plan, because the plan is a full diet. A ratio above 1 tells that\n * 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.\n * The check of the amount of food is a check of its energy, not of its cost.\n *\n * @param cost - The cost of the food, in a money that converts to the money of the plan\n * @param plan - The food plan\n * @param members - The groups of the members of the household, each with its count of persons\n * @param days - The count of days of the food\n * @throws RangeError for the errors of `foodPlanCost`\n * @throws The error of `valueIn` of `@mark1russell7/quantity` when the money of the cost does not convert to the money of the plan\n */\nexport function foodPlanCheck(cost: Quantity, plan: FoodPlan, members: readonly FoodPlanMember[], days: number): FoodPlanCheck {\n const planned = foodPlanCost(plan, members, days);\n const value = valueIn(cost, planned.unit);\n const ratio = planned.value === 0 ? (value === 0 ? 0 : Number.POSITIVE_INFINITY) : value / planned.value;\n return { plan: planned, cost: quantity(value, planned.unit), ratio, above: ratio > 1 };\n}\n","import type { FoodPlan } from \"./food-plan.ts\";\n\n// The costs of the food plans of USDA. Each value is from the table of the report, read on 2026-11-22. The report\n// rounds each weekly cost to 10 cents. Footnote 2 of the report gives the change for each size of household.\n\nconst week = (value: number): { readonly value: number; readonly unit: string } => ({ value, unit: \"USD/wk\" });\n\n/** The costs of the food plans of USDA, one record for each plan and month. */\nexport const FOOD_PLANS: readonly FoodPlan[] = [\n {\n id: \"usda.thrifty:2026-10\",\n title: \"Official USDA Thrifty Food Plan: U.S. Average, October 2026\",\n area: \"U.S. average\",\n period: \"2026-10\",\n source: {\n id: \"usda.food-plans\",\n title: \"USDA Food Plans: Monthly Cost of Food Reports\",\n url: \"https://www.fna.usda.gov/research/cnpp/usda-food-plans/cost-food-monthly-reports\",\n license: \"us-public-domain\",\n checked: \"2026-11-22\",\n by: \"USDA Food and Nutrition Administration\",\n },\n locator: \"CostofFoodOct2026Thrifty.pdf, the column Weekly Cost of the table of age-sex groups\",\n weekly: {\n \"child-1\": week(26.4),\n \"child-2-3\": week(39.8),\n \"child-4-5\": week(43.5),\n \"child-6-8\": week(48.3),\n \"child-9-11\": week(55.8),\n \"female-12-13\": week(51.7),\n \"female-14-19\": week(60.1),\n \"female-20-50\": week(58.7),\n \"female-51-70\": week(54.6),\n \"female-71-up\": week(60.3),\n \"male-12-13\": week(59.7),\n \"male-14-19\": week(75.3),\n \"male-20-50\": week(73.7),\n \"male-51-70\": week(65),\n \"male-71-up\": week(62),\n },\n sizes: [\n { from: 1, to: 1, change: 0.2 },\n { from: 2, to: 2, change: 0.1 },\n { from: 3, to: 3, change: 0.05 },\n { from: 4, to: 4, change: 0 },\n { from: 5, to: 6, change: -0.05 },\n { from: 7, change: -0.1 },\n ],\n },\n];\n","import { quantity, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { giftsOf, type SupplyCatalog } from \"./supplies.ts\";\n\n/*\n * This module has the food energy of a buy list, from the catalog of supplies. It gives the energy of each line and\n * their sum. The energy need of the members, the days of food and the shortfall are not in this package. The days\n * depend on the water and the fuel that a case leaves, so the model of the endurance of the stores gives them.\n */\n\n/** The unit of each food energy. */\nconst ENERGY_UNIT = \"kcal\";\n\n/**\n * The food energy of the units of one product of a buy list, or no read with the reason. A no read is not 0.\n * The resources are the codes of the gifts of the product, for example `food.no-cook` or `food.grain-dry`.\n */\nexport type BuyListEnergyLine =\n | { readonly product: string; readonly units: number; readonly resources: readonly string[]; readonly read: true; readonly energy: Quantity }\n | { readonly product: string; readonly units: number; readonly resources: readonly string[]; readonly read: false; readonly why: string };\n\n/** The food energy of a buy list. */\nexport interface BuyListEnergy {\n /** The food energy of each product of the list, in the order of the list. */\n readonly lines: readonly BuyListEnergyLine[];\n /** True when each line has a read. When it is false, `energy` is a lower limit. */\n readonly read: boolean;\n /** The sum of the food energy of the lines with a read, in `kcal`. */\n readonly energy: Quantity;\n}\n\n/**\n * This function gives the food energy of a buy list, from the catalog. The energy of each product is its field\n * `energy` times its count of units. Each line has the resources of the product. Thus a caller can split the energy\n * of `food.no-cook` from the energy of the dry food.\n *\n * - A product with a no read for its energy gives a line with no read. A no read is not 0.\n * - A food product with no field `energy` also gives a line with no read.\n * - A product of another kind is not food, for example water or a battery. It gives no line, also when it has a\n * field `energy`. The gate of the catalog refuses that field on a product that is not food.\n * - A product with 0 units gives no line.\n *\n * The list can be the `units` of a buy order.\n *\n * @param catalog - The catalog of supplies\n * @param units - The count of units of each product of the list, by the `id` of the product\n * @throws RangeError when a count of units is not a finite number of 0 or more, or when the catalog has no such product\n * @throws RangeError when a product gives a resource that the catalog does not have, as for `giftsOf`\n * @throws The error of `valueIn` of `@mark1russell7/quantity` when the unit of an energy does not convert to `kcal`\n */\nexport function buyListEnergy(catalog: SupplyCatalog, units: Readonly<Record<string, number>>): BuyListEnergy {\n const lines: BuyListEnergyLine[] = [];\n for (const [id, count] of Object.entries(units)) {\n // `giftsOf` refuses a bad count of units and an unknown product.\n const resources = giftsOf(catalog, id, count).map((gift) => gift.resource);\n const product = catalog.products.find((each) => each.id === id);\n if (product === undefined || count === 0 || product.kind !== \"food\") continue;\n const energy = product.energy;\n if (energy === undefined) {\n lines.push({ product: id, units: count, resources, read: false, why: `The catalog has no food energy for the product ${id}.` });\n continue;\n }\n if (!energy.read) lines.push({ product: id, units: count, resources, read: false, why: energy.why });\n else lines.push({ product: id, units: count, resources, read: true, energy: quantity(count * valueIn(quantity(energy.amount, energy.unit), ENERGY_UNIT), ENERGY_UNIT) });\n }\n const total = lines.reduce((sum, line) => sum + (line.read ? line.energy.value : 0), 0);\n return { lines, read: lines.every((line) => line.read), energy: quantity(total, ENERGY_UNIT) };\n}\n"],"mappings":";;;;;AAcA,MAAa,gBAAgB;;AAG7B,MAAa,eAAe;CAAC;CAAS;CAAQ;CAAS;CAAS;CAAQ;CAAa;AAAe;;AA+FpG,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAqBA,SAAS,MAAM,MAAwB;CACrC,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,IAAI;EACF,OAAO,YAAY,MAAM,IAAI;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAMA,gBAAc;;AAEpB,MAAM,aAAa;;;;;;AAMnB,SAAS,SAAS,MAAuB;CACvC,OAAO,YAAY,MAAM,IAAI,KAAK,YAAY,MAAM,GAAG,KAAK,UAAU,IAAI;AAC5E;;AAGA,SAAS,UAAU,MAAuB;CACxC,OAAO,cAAc,KAAK,IAAI,KAAK,OAAO,IAAI,MAAM;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,cAAc,SAAwB,UAA6B,CAAC,GAAoB;CACtG,MAAM,EAAE,YAAY,iBAAiB,GAAG,SAAS;CACjD,MAAM,aAAa,oBAAoB,KAAA,IAAY,KAAA,IAAY,IAAI,IAAY,eAAe;CAC9F,MAAM,MAAuB,CAAC,G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;GACxB,MAAM,KAAK;IAAE,SAAS;IAAI,OAAO;IAAO;IAAW,MAAM;IAAO,KAAK,kDAAkD,GAAG;GAAG,CAAC;GAC9H;EACF;EACA,IAAI,CAAC,OAAO,MAAM,MAAM,KAAK;GAAE,SAAS;GAAI,OAAO;GAAO;GAAW,MAAM;GAAO,KAAK,OAAO;EAAI,CAAC;OAC9F,MAAM,KAAK;GAAE,SAAS;GAAI,OAAO;GAAO;GAAW,MAAM;GAAM,QAAQ,SAAS,QAAQ,QAAQ,SAAS,OAAO,QAAQ,OAAO,IAAI,GAAG,WAAW,GAAG,WAAW;EAAE,CAAC;CACzK;CACA,MAAM,QAAQ,MAAM,QAAQ,KAAK,SAAS,OAAO,KAAK,OAAO,KAAK,OAAO,QAAQ,IAAI,CAAC;CACtF,OAAO;EAAE;EAAO,MAAM,MAAM,OAAO,SAAS,KAAK,IAAI;EAAG,QAAQ,SAAS,OAAO,WAAW;CAAE;AAC/F"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/market",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.4",
|
|
5
5
|
"description": "The records of a market: a product, an offer of a seller and a price reading, with their checks, the GTIN check, match keys, the cost of an order, the storage rules of a source, the best offer of a part, a board of current prices within the terms of each source, a buy plan: the Pareto front of the baskets of a need, and metered prices of cloud resources with tiers, free amounts, terms and their cost.",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
],
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@mark1russell7/guidebook": "^0.1.1",
|
|
54
|
-
"@mark1russell7/quantity": "^0.4.
|
|
54
|
+
"@mark1russell7/quantity": "^0.4.5",
|
|
55
55
|
"@mark1russell7/strategy-search": "^0.1.2",
|
|
56
56
|
"@mark1russell7/strategy-space": "^0.1.0",
|
|
57
57
|
"@mark1russell7/vex": "^0.19.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"average-B29bynFb.js","names":[],"sources":["../src/average.ts"],"sourcesContent":["import { parseUnit, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { instantSchema, sourceSchema, textSchema } from \"./records.ts\";\n\n/*\n * This module has the average prices of a market. An average price is not an offer of a seller. It is the mean price\n * of one item in one area and one month, from an official statistic, for example the average prices of the Consumer\n * Price Index. A buyer uses it as the price of a product that has no offer, and as a check of the price of an offer.\n */\n\n/** The average price of one item in one area and one month, from one series of a source. */\nexport interface AveragePrice {\n /** The id `source:series:period`. `averagePriceId` gives it. */\n readonly id: string;\n readonly source: string;\n /** The id of the series in the source, for example `APU0000701312`. */\n readonly series: string;\n /** The item of the series, as the source names it. */\n readonly item: string;\n /** The area of the series, as the source names it, for example `U.S. city average`. */\n readonly area: string;\n /** The month of the price, in the form `YYYY-MM`. */\n readonly period: string;\n /** The price for each unit of the item, for example `{ \"value\": 1.101, \"unit\": \"USD/lb\" }`. */\n readonly price: Quantity;\n /** The instant of the read of the source. */\n readonly at: string;\n /** The footnotes of the source for this price, for example a preliminary value. */\n readonly footnotes?: readonly string[] | undefined;\n}\n\n/** This function gives the id of an average price: the source, the series and the month, with colons. */\nexport function averagePriceId(source: string, series: string, period: string): string {\n return `${source}:${series}:${period}`;\n}\n\n/**\n * This function reads the unit of a price for each unit of an amount of an item. The unit has one unit of money\n * above. Below, it has a unit of an amount that is not money and not a pure time, for example `USD/lb`, `USD/L` or `USD/kWh`.\n * A count below must have an annotation, for example `USD/{each}`. Thus `USD/%` and `USD/h` are not prices of an item.\n */\nfunction unitPriceProblem(unit: string): string | undefined {\n const refused = `The unit ${unit} is not a price for each unit of an amount, for example USD/lb.`;\n let parsed: ReturnType<typeof parseUnit>;\n try {\n parsed = parseUnit(unit);\n } catch (error) {\n if (error instanceof UnitError) return refused;\n throw error;\n }\n if (moneyAbove(unit) === undefined) return refused;\n const below = parsed.components.filter((component) => component.exponent < 0);\n const amountOf = (component: (typeof below)[number]): boolean => {\n const dimensions = component.atom?.vector;\n if (dimensions === undefined) return component.annotation !== undefined;\n const names = Object.keys(dimensions);\n const pureTime = names.length === 1 && names[0] === \"time\";\n return names.length > 0 && !names.includes(\"money\") && !pureTime;\n };\n if (below.length === 0 || !below.every(amountOf)) return refused;\n return undefined;\n}\n\n/**\n * This function gives the symbol of the money of a unit that has one unit of money above, for example `USD` for\n * `USD/wk`. It gives undefined for each other unit, and for a unit that does not parse.\n *\n * This is unit algebra, so its home is `@mark1russell7/quantity`. It stays here, out of the exports of the package,\n * until quantity has it. Then this function goes away.\n */\nexport function moneyAbove(unit: string): string | undefined {\n let parsed: ReturnType<typeof parseUnit>;\n try {\n parsed = parseUnit(unit);\n } catch (error) {\n if (error instanceof UnitError) return undefined;\n throw error;\n }\n const above = parsed.components.filter((component) => component.exponent > 0);\n const [money] = above;\n const vector = money?.atom?.vector;\n const isMoney = vector !== undefined && Object.keys(vector).length === 1 && vector.money === 1;\n return above.length === 1 && money?.exponent === 1 && money.annotation === undefined && isMoney ? money.atom?.symbol : undefined;\n}\n\n/**\n * This function gives the symbol of the money of a price for each unit of an amount, for example `USD` for `USD/lb`.\n * It gives undefined for each other unit.\n */\nexport function moneyOf(unit: string): string | undefined {\n return unitPriceProblem(unit) === undefined ? moneyAbove(unit) : undefined;\n}\n\n/** This schema accepts a price of more than 0 for each unit of an amount, for example `{ \"value\": 1.101, \"unit\": \"USD/lb\" }`. */\nexport const unitPriceSchema: z.ZodType<Quantity, Quantity> = quantitySchema(undefined, { positive: true }).superRefine((price, context) => {\n const problem = unitPriceProblem(price.unit);\n if (problem !== undefined) context.addIssue({ code: \"custom\", message: problem });\n});\n\n/** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */\nexport const monthSchema: z.ZodType<string> = z.string().regex(/^(?!0000)\\d{4}-(0[1-9]|1[0-2])$/, \"The month is not in the form YYYY-MM.\");\n\n/** This schema accepts an average price. Its id must be the id of its source, its series and its month. */\nexport const averagePriceSchema: z.ZodType<AveragePrice> = z\n .strictObject({\n id: textSchema,\n source: sourceSchema,\n series: textSchema,\n item: textSchema,\n area: textSchema,\n period: monthSchema,\n price: unitPriceSchema,\n at: instantSchema,\n footnotes: z.array(textSchema).optional(),\n })\n .refine((record) => record.id === averagePriceId(record.source, record.series, record.period), {\n message: \"The id is not the id of the source, the series and the month.\",\n path: [\"id\"],\n });\n\n/**\n * This function gives the last average price of each series, by its month. A later read of the same month replaces\n * an earlier one, because a source can revise a value.\n *\n * @param prices - The average prices, from one or more reads\n * @returns One price for each series, in the order of the series ids\n */\nexport function latestAverages(prices: readonly AveragePrice[]): readonly AveragePrice[] {\n const last = new Map<string, AveragePrice>();\n for (const price of prices) {\n const key = `${price.source}:${price.series}`;\n const held = last.get(key);\n if (held === undefined || price.period > held.period || (price.period === held.period && price.at > held.at)) last.set(key, price);\n }\n return [...last.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, price]) => price);\n}\n"],"mappings":";;;;;;AAiCA,SAAgB,eAAe,QAAgB,QAAgB,QAAwB;CACrF,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG;AAChC;;;;;;AAOA,SAAS,iBAAiB,MAAkC;CAC1D,MAAM,UAAU,YAAY,KAAK;CACjC,IAAI;CACJ,IAAI;EACF,SAAS,UAAU,IAAI;CACzB,SAAS,OAAO;EACd,IAAI,iBAAiB,WAAW,OAAO;EACvC,MAAM;CACR;CACA,IAAI,WAAW,IAAI,MAAM,KAAA,GAAW,OAAO;CAC3C,MAAM,QAAQ,OAAO,WAAW,QAAQ,cAAc,UAAU,WAAW,CAAC;CAC5E,MAAM,YAAY,cAA+C;EAC/D,MAAM,aAAa,UAAU,MAAM;EACnC,IAAI,eAAe,KAAA,GAAW,OAAO,UAAU,eAAe,KAAA;EAC9D,MAA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