@mark1russell7/market 0.1.8 → 0.1.9

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/README.md CHANGED
@@ -145,6 +145,7 @@ The entry `@mark1russell7/market/supplies` has the format and the gate of a cata
145
145
  - The facts and their sources are the records of [`@mark1russell7/guidebook`](https://www.npmjs.com/package/@mark1russell7/guidebook). Its gate examines each license and each address.
146
146
  - The shelf life of a food is the id of a product of the FoodKeeper data of USDA FSIS. The entry `/foodkeeper` of `@mark1russell7/stock` gives its due rule.
147
147
  - The resource codes are the codes of a store of `@mark1russell7/stack-endurance`, for example `water.stored` in `L`.
148
+ - A product can join a series of average prices. The join names the source, the series and the amount of the item in one unit, with its reason. A product with no series has a no read with its reason.
148
149
  - The gate does not examine the joins to other packages. It does not find a FoodKeeper id that is not in `@mark1russell7/stock`, or a resource code that a layer of stores does not have. The code that joins the catalog to stock or to a layer of stores gives those gates. market depends on neither package.
149
150
 
150
151
  | Function | What it does |
@@ -152,12 +153,18 @@ The entry `@mark1russell7/market/supplies` has the format and the gate of a cata
152
153
  | `checkSupplies(catalog, options)` | It gives the findings of the catalog: the errors of the gate, and a warning for each no read and for each fact or source that no product uses. |
153
154
  | `supplyWants(catalog, max)` | It gives the wants of the products with a part, for `buyCandidates`. A product with no part has no offer, so it has no price. |
154
155
  | `giftsOf(catalog, id, units)` | It gives the resources of a count of units, each in the unit of its resource. A unit converts exactly, so 1 gal gives 3.785411784 L. |
156
+ | `averageSupplyPrices(catalog, prices, { since })` | It gives the price of one unit of each product with a join, from the last month of its series. A series with no price and a unit that does not fit give a no read. With `since`, so does a last price before that month. |
157
+ | `foodPlanCost(plan, members, days)` | It gives the cost of a food plan for the members of a household and a count of days. It applies the change for the size of the household. |
158
+ | `foodPlanCheck(cost, plan, members, days)` | It compares the cost of the food of a buy list with the cost of the plan. A ratio above 1 tells that a price or an amount is possibly wrong. |
155
159
 
156
160
  `SUPPLY_CATALOG` is the reference catalog. Its facts come from Ready.gov (FEMA, a US federal work) and from FoodData Central (USDA, CC0 1.0). It has gaps:
157
161
 
158
162
  - The energy of the power bank is no read. The page of the maker gives 24,000 mAh and no Wh, and a charge does not convert to energy without its voltage.
159
163
  - The kinds `light`, `heat`, `first-aid` and `communication` have no product yet.
160
164
  - The shelf life of commercially bottled water is no read. The source gives no time, so the date on the label applies.
165
+ - The oats have no series of average prices. The rice joins the BLS series `APU0000701312` in `USD/lb`, so 1 kg of rice costs 2.2046 times the price of 1 lb.
166
+
167
+ `FOOD_PLANS` has the costs of the Thrifty Food Plan of USDA for October 2026, in the U.S. average. The costs come from the monthly report of the cost of food (a US federal work). Each cost is for one person of an age and sex group, in a household of four. The changes for the other sizes come from footnote 2 of the report. The plan is a full diet, so a list of dry staples costs much less than the plan. A low ratio is normal. The check of the amount of food is a check of its energy, not of its cost. The members of a household are input data.
161
168
 
162
169
  ## Metered prices
163
170
 
@@ -0,0 +1,106 @@
1
+ import { a as instantSchema, g as sourceSchema, v as textSchema } from "./records-W6sPyhTQ.js";
2
+ import { UnitError, parseUnit } from "@mark1russell7/quantity";
3
+ import { quantitySchema } from "@mark1russell7/quantity/schema";
4
+ import { z } from "zod";
5
+ // src/average.ts
6
+ /** This function gives the id of an average price: the source, the series and the month, with colons. */
7
+ function averagePriceId(source, series, period) {
8
+ return `${source}:${series}:${period}`;
9
+ }
10
+ /**
11
+ * This function reads the unit of a price for each unit of an amount of an item. The unit has one unit of money
12
+ * 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`.
13
+ * A count below must have an annotation, for example `USD/{each}`. Thus `USD/%` and `USD/h` are not prices of an item.
14
+ */
15
+ function unitPriceProblem(unit) {
16
+ const refused = `The unit ${unit} is not a price for each unit of an amount, for example USD/lb.`;
17
+ let parsed;
18
+ try {
19
+ parsed = parseUnit(unit);
20
+ } catch (error) {
21
+ if (error instanceof UnitError) return refused;
22
+ throw error;
23
+ }
24
+ if (moneyAbove(unit) === void 0) return refused;
25
+ const below = parsed.components.filter((component) => component.exponent < 0);
26
+ const amountOf = (component) => {
27
+ const dimensions = component.atom?.vector;
28
+ if (dimensions === void 0) return component.annotation !== void 0;
29
+ const names = Object.keys(dimensions);
30
+ const pureTime = names.length === 1 && names[0] === "time";
31
+ return names.length > 0 && !names.includes("money") && !pureTime;
32
+ };
33
+ if (below.length === 0 || !below.every(amountOf)) return refused;
34
+ }
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
+ * This function gives the symbol of the money of a price for each unit of an amount, for example `USD` for `USD/lb`.
58
+ * It gives undefined for each other unit.
59
+ */
60
+ function moneyOf(unit) {
61
+ return unitPriceProblem(unit) === void 0 ? moneyAbove(unit) : void 0;
62
+ }
63
+ /** This schema accepts a price of more than 0 for each unit of an amount, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
64
+ const unitPriceSchema = quantitySchema(void 0, { positive: true }).superRefine((price, context) => {
65
+ const problem = unitPriceProblem(price.unit);
66
+ if (problem !== void 0) context.addIssue({
67
+ code: "custom",
68
+ message: problem
69
+ });
70
+ });
71
+ /** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */
72
+ const monthSchema = z.string().regex(/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/, "The month is not in the form YYYY-MM.");
73
+ /** This schema accepts an average price. Its id must be the id of its source, its series and its month. */
74
+ const averagePriceSchema = z.strictObject({
75
+ id: textSchema,
76
+ source: sourceSchema,
77
+ series: textSchema,
78
+ item: textSchema,
79
+ area: textSchema,
80
+ period: monthSchema,
81
+ price: unitPriceSchema,
82
+ at: instantSchema,
83
+ footnotes: z.array(textSchema).optional()
84
+ }).refine((record) => record.id === averagePriceId(record.source, record.series, record.period), {
85
+ message: "The id is not the id of the source, the series and the month.",
86
+ path: ["id"]
87
+ });
88
+ /**
89
+ * This function gives the last average price of each series, by its month. A later read of the same month replaces
90
+ * an earlier one, because a source can revise a value.
91
+ *
92
+ * @param prices - The average prices, from one or more reads
93
+ * @returns One price for each series, in the order of the series ids
94
+ */
95
+ function latestAverages(prices) {
96
+ const last = /* @__PURE__ */ new Map();
97
+ for (const price of prices) {
98
+ const key = `${price.source}:${price.series}`;
99
+ const held = last.get(key);
100
+ if (held === void 0 || price.period > held.period || price.period === held.period && price.at > held.at) last.set(key, price);
101
+ }
102
+ return [...last.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, price]) => price);
103
+ }
104
+ export { moneyOf as a, moneyAbove as i, averagePriceSchema as n, monthSchema as o, latestAverages as r, unitPriceSchema as s, averagePriceId as t };
105
+
106
+ //# sourceMappingURL=average-B29bynFb.js.map
@@ -0,0 +1 @@
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,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;;;;;;;;AASA,SAAgB,WAAW,MAAkC;CAC3D,IAAI;CACJ,IAAI;EACF,SAAS,UAAU,IAAI;CACzB,SAAS,OAAO;EACd,IAAI,iBAAiB,WAAW,OAAO,KAAA;EACvC,MAAM;CACR;CACA,MAAM,QAAQ,OAAO,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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"}
@@ -0,0 +1,40 @@
1
+ import { Quantity } from "@mark1russell7/quantity";
2
+ import { z } from "zod";
3
+ /** The average price of one item in one area and one month, from one series of a source. */
4
+ interface AveragePrice {
5
+ /** The id `source:series:period`. `averagePriceId` gives it. */
6
+ readonly id: string;
7
+ readonly source: string;
8
+ /** The id of the series in the source, for example `APU0000701312`. */
9
+ readonly series: string;
10
+ /** The item of the series, as the source names it. */
11
+ readonly item: string;
12
+ /** The area of the series, as the source names it, for example `U.S. city average`. */
13
+ readonly area: string;
14
+ /** The month of the price, in the form `YYYY-MM`. */
15
+ readonly period: string;
16
+ /** The price for each unit of the item, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
17
+ readonly price: Quantity;
18
+ /** The instant of the read of the source. */
19
+ readonly at: string;
20
+ /** The footnotes of the source for this price, for example a preliminary value. */
21
+ readonly footnotes?: readonly string[] | undefined;
22
+ }
23
+ /** This function gives the id of an average price: the source, the series and the month, with colons. */
24
+ declare function averagePriceId(source: string, series: string, period: string): string;
25
+ /** This schema accepts a price of more than 0 for each unit of an amount, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
26
+ declare const unitPriceSchema: z.ZodType<Quantity, Quantity>;
27
+ /** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */
28
+ declare const monthSchema: z.ZodType<string>;
29
+ /** This schema accepts an average price. Its id must be the id of its source, its series and its month. */
30
+ declare const averagePriceSchema: z.ZodType<AveragePrice>;
31
+ /**
32
+ * This function gives the last average price of each series, by its month. A later read of the same month replaces
33
+ * an earlier one, because a source can revise a value.
34
+ *
35
+ * @param prices - The average prices, from one or more reads
36
+ * @returns One price for each series, in the order of the series ids
37
+ */
38
+ declare function latestAverages(prices: readonly AveragePrice[]): readonly AveragePrice[];
39
+ export { monthSchema as a, latestAverages as i, averagePriceId as n, unitPriceSchema as o, averagePriceSchema as r, AveragePrice as t };
40
+ //# sourceMappingURL=average-Bj0GkSLo.d.ts.map
@@ -0,0 +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;;cA8DlD,iBAAiB,EAAE,QAAQ,UAAU;;cAMrC,aAAa,EAAE;;cAGf,oBAAoB,EAAE,QAAQ;;;;;;;;iBAwB3B,eAAe,iBAAiB,0BAA0B"}
package/build/index.d.ts CHANGED
@@ -6,45 +6,10 @@
6
6
  * A metered offer has a price for each unit of a metered amount, in tiers, with a free amount and a term.
7
7
  * An average price is the mean price of one item in one area and one month, from an official statistic.
8
8
  */
9
+ import { a as monthSchema, i as latestAverages, n as averagePriceId, o as unitPriceSchema, r as averagePriceSchema, t as AveragePrice } from "./average-Bj0GkSLo.js";
9
10
  import { A as priceBreakSchema, B as PartNumber, C as Spec, D as offerId, E as moneySchema, F as sourceOfOffer, H as matchKeys, I as sourceSchema, L as specSchema, M as productSchema, N as sellerSchema, O as offerSchema, P as shippingSchema, R as textSchema, S as Shipping, T as instantSchema, V as foldCode, _ as PriceBreak, a as PartWant, b as Rating, c as offersOfPart, d as Availability, f as CONDITIONS, g as Offer, h as Format, i as OfferChoice, j as priceReadingSchema, k as partNumberSchema, l as offersPart, m as FORMATS, n as BestOfferOptions, o as bestOffer, p as Condition, r as Observation, s as latestObservations, t as BestOffer, u as AVAILABILITIES, v as PriceReading, w as gtinSchema, x as Seller, y as Product, z as Identifiers } from "./offers-CVUAcRHs.js";
10
11
  import { Quantity } from "@mark1russell7/quantity";
11
12
  import { z } from "zod";
12
- /** The average price of one item in one area and one month, from one series of a source. */
13
- interface AveragePrice {
14
- /** The id `source:series:period`. `averagePriceId` gives it. */
15
- readonly id: string;
16
- readonly source: string;
17
- /** The id of the series in the source, for example `APU0000701312`. */
18
- readonly series: string;
19
- /** The item of the series, as the source names it. */
20
- readonly item: string;
21
- /** The area of the series, as the source names it, for example `U.S. city average`. */
22
- readonly area: string;
23
- /** The month of the price, in the form `YYYY-MM`. */
24
- readonly period: string;
25
- /** The price for each unit of the item, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
26
- readonly price: Quantity;
27
- /** The instant of the read of the source. */
28
- readonly at: string;
29
- /** The footnotes of the source for this price, for example a preliminary value. */
30
- readonly footnotes?: readonly string[] | undefined;
31
- }
32
- /** This function gives the id of an average price: the source, the series and the month, with colons. */
33
- export declare function averagePriceId(source: string, series: string, period: string): string;
34
- /** This schema accepts a price of more than 0 for each unit of an amount, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
35
- export declare const unitPriceSchema: z.ZodType<Quantity, Quantity>;
36
- /** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */
37
- export declare const monthSchema: z.ZodType<string>;
38
- /** This schema accepts an average price. Its id must be the id of its source, its series and its month. */
39
- export declare const averagePriceSchema: z.ZodType<AveragePrice>;
40
- /**
41
- * This function gives the last average price of each series, by its month. A later read of the same month replaces
42
- * an earlier one, because a source can revise a value.
43
- *
44
- * @param prices - The average prices, from one or more reads
45
- * @returns One price for each series, in the order of the series ids
46
- */
47
- export declare function latestAverages(prices: readonly AveragePrice[]): readonly AveragePrice[];
48
13
  /** The storage rule of a source, from its terms. */
49
14
  type Retention = {
50
15
  readonly kind: "keep";
@@ -408,5 +373,5 @@ export declare function unitPriceFor(reading: PriceReading, count: number): Quan
408
373
  * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
409
374
  */
410
375
  export declare function costOf(reading: PriceReading, count: number): Quantity | null;
411
- export { AVAILABILITIES, type Availability, type AveragePrice, type BestOffer, type BestOfferOptions, type Board, type BoardDrop, type BoardRead, CONDITIONS, type Condition, type Dropped, FORMATS, type Format, type FreeAmount, type FreeScope, type Identifiers, type KeepOptions, type Kept, type Location, type Meter, type MeterCost, type MeteredCost, type MeteredCostOptions, type MeteredKind, type MeteredObservation, type MeteredOffer, type MeteredReading, type MeteredUsage, type Observation, type Offer, type OfferChoice, type PartNumber, type PartWant, type PriceBreak, type PriceReading, type PriceTerm, type Product, type Rating, type ReadInterval, type ReadPlan, type Retention, type ScheduleOptions, type Seller, type SettleOptions, type Settled, type Shipping, type SourceTerms, type Spec, type Tier, type WatchEntry, bestOffer, foldCode, gtinSchema, instantSchema, latestObservations, matchKeys, moneySchema, offerId, offerSchema, offersOfPart, offersPart, partNumberSchema, priceBreakSchema, priceReadingSchema, productSchema, sellerSchema, shippingSchema, sourceOfOffer, sourceSchema, specSchema, textSchema };
376
+ export { AVAILABILITIES, type Availability, type AveragePrice, type BestOffer, type BestOfferOptions, type Board, type BoardDrop, type BoardRead, CONDITIONS, type Condition, type Dropped, FORMATS, type Format, type FreeAmount, type FreeScope, type Identifiers, type KeepOptions, type Kept, type Location, type Meter, type MeterCost, type MeteredCost, type MeteredCostOptions, type MeteredKind, type MeteredObservation, type MeteredOffer, type MeteredReading, type MeteredUsage, type Observation, type Offer, type OfferChoice, type PartNumber, type PartWant, type PriceBreak, type PriceReading, type PriceTerm, type Product, type Rating, type ReadInterval, type ReadPlan, type Retention, type ScheduleOptions, type Seller, type SettleOptions, type Settled, type Shipping, type SourceTerms, type Spec, type Tier, type WatchEntry, averagePriceId, averagePriceSchema, bestOffer, foldCode, gtinSchema, instantSchema, latestAverages, latestObservations, matchKeys, moneySchema, monthSchema, offerId, offerSchema, offersOfPart, offersPart, partNumberSchema, priceBreakSchema, priceReadingSchema, productSchema, sellerSchema, shippingSchema, sourceOfOffer, sourceSchema, specSchema, textSchema, unitPriceSchema };
412
377
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/average.ts","../src/terms.ts","../src/board.ts","../src/gtin.ts","../src/metered.ts","../src/price.ts"],"mappings":";;;;;;;;;;;;UAYiB;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA,OAAO;;WAEP;;WAEA;;;wBAIK,eAAe,gBAAgB,gBAAgB;;qBAoClD,iBAAiB,EAAE,QAAQ,UAAU;;qBAMrC,aAAa,EAAE;;qBAGf,oBAAoB,EAAE,QAAQ;;;;;;;;wBAwB3B,eAAe,iBAAiB,0BAA0B;;KChG9D;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;;WA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/build/index.js CHANGED
@@ -1,82 +1,9 @@
1
- import { C as shippingSchema, D as textSchema, E as specSchema, O as gtinCheckDigit, S as sellerSchema, T as sourceSchema, _ as offerSchema, b as priceReadingSchema, c as foldCode, d as CONDITIONS, f as FORMATS, g as offerId, h as moneySchema, i as offersPart, k as parseGtin, l as matchKeys, m as instantSchema, n as latestObservations, o as costOf, p as gtinSchema, r as offersOfPart, s as unitPriceFor, t as bestOffer, u as AVAILABILITIES, v as partNumberSchema, w as sourceOfOffer, x as productSchema, y as priceBreakSchema } from "./offers-B_8DqLSA.js";
1
+ import { n as averagePriceSchema, o as monthSchema, r as latestAverages, s as unitPriceSchema, t as averagePriceId } from "./average-B29bynFb.js";
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
+ 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";
2
4
  import { UnitError, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
3
5
  import { quantitySchema } from "@mark1russell7/quantity/schema";
4
6
  import { z } from "zod";
5
- // src/average.ts
6
- /** This function gives the id of an average price: the source, the series and the month, with colons. */
7
- function averagePriceId(source, series, period) {
8
- return `${source}:${series}:${period}`;
9
- }
10
- /**
11
- * This function reads the unit of a price for each unit of an amount of an item. The unit has one unit of money
12
- * 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`.
13
- * A count below must have an annotation, for example `USD/{each}`. Thus `USD/%` and `USD/h` are not prices of an item.
14
- */
15
- function unitPriceProblem(unit) {
16
- const refused = `The unit ${unit} is not a price for each unit of an amount, for example USD/lb.`;
17
- let parsed;
18
- try {
19
- parsed = parseUnit(unit);
20
- } catch (error) {
21
- if (error instanceof UnitError) return refused;
22
- throw error;
23
- }
24
- const above = parsed.components.filter((component) => component.exponent > 0);
25
- const [money] = above;
26
- const vector = money?.atom?.vector;
27
- const isMoney = vector !== void 0 && Object.keys(vector).length === 1 && vector.money === 1;
28
- if (above.length !== 1 || money?.exponent !== 1 || money.annotation !== void 0 || !isMoney) return refused;
29
- const below = parsed.components.filter((component) => component.exponent < 0);
30
- const amountOf = (component) => {
31
- const dimensions = component.atom?.vector;
32
- if (dimensions === void 0) return component.annotation !== void 0;
33
- const names = Object.keys(dimensions);
34
- const pureTime = names.length === 1 && names[0] === "time";
35
- return names.length > 0 && !names.includes("money") && !pureTime;
36
- };
37
- if (below.length === 0 || !below.every(amountOf)) return refused;
38
- }
39
- /** This schema accepts a price of more than 0 for each unit of an amount, for example `{ "value": 1.101, "unit": "USD/lb" }`. */
40
- const unitPriceSchema = quantitySchema(void 0, { positive: true }).superRefine((price, context) => {
41
- const problem = unitPriceProblem(price.unit);
42
- if (problem !== void 0) context.addIssue({
43
- code: "custom",
44
- message: problem
45
- });
46
- });
47
- /** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */
48
- const monthSchema = z.string().regex(/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/, "The month is not in the form YYYY-MM.");
49
- /** This schema accepts an average price. Its id must be the id of its source, its series and its month. */
50
- const averagePriceSchema = z.strictObject({
51
- id: textSchema,
52
- source: sourceSchema,
53
- series: textSchema,
54
- item: textSchema,
55
- area: textSchema,
56
- period: monthSchema,
57
- price: unitPriceSchema,
58
- at: instantSchema,
59
- footnotes: z.array(textSchema).optional()
60
- }).refine((record) => record.id === averagePriceId(record.source, record.series, record.period), {
61
- message: "The id is not the id of the source, the series and the month.",
62
- path: ["id"]
63
- });
64
- /**
65
- * This function gives the last average price of each series, by its month. A later read of the same month replaces
66
- * an earlier one, because a source can revise a value.
67
- *
68
- * @param prices - The average prices, from one or more reads
69
- * @returns One price for each series, in the order of the series ids
70
- */
71
- function latestAverages(prices) {
72
- const last = /* @__PURE__ */ new Map();
73
- for (const price of prices) {
74
- const key = `${price.source}:${price.series}`;
75
- const held = last.get(key);
76
- if (held === void 0 || price.period > held.period || price.period === held.period && price.at > held.at) last.set(key, price);
77
- }
78
- return [...last.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, price]) => price);
79
- }
80
7
  // src/terms.ts
81
8
  /**
82
9
  * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the