@mark1russell7/market 0.1.7 → 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
 
@@ -219,6 +226,21 @@ const observation: MeteredObservation = {
219
226
  meteredCost(observation, { egress: { value: 10_341, unit: "GiB" } }).total; // { value: 921.685, unit: "USD" }
220
227
  ```
221
228
 
229
+ ## Average prices
230
+
231
+ An average price is the mean price of one item in one area and one month, from an official statistic. An example is the average prices of the Consumer Price Index. It is not an offer of a seller. A buyer uses it as the price of a product with no offer, and as a check of the price of an offer.
232
+
233
+ | Record | Schema | What it has |
234
+ | --- | --- | --- |
235
+ | Average price | `averagePriceSchema` | The source and its series. The item and the area, as the source names them. The month `YYYY-MM`, and the price for each unit of the item. The instant of the read, and the footnotes. |
236
+
237
+ - **Price.** The unit has one unit of money above. Below, it has the unit of an amount of the item, for example `USD/lb`, `USD/L` or `USD/{each}`. A pure time, a bare number and money below are refused, for example `USD/h` and `USD/%`. An energy is accepted, for example `USD/kWh`. `unitPriceSchema` examines it. The value is more than 0.
238
+ - **The fit to a product.** The schema does not examine the fit of the unit to a product, for example `USD/lb` to a dry grain in `kg`. The join of a product to a series examines it.
239
+ - **Id.** `averagePriceId(source, series, month)` gives the id `source:series:month`.
240
+ - **The last price.** `latestAverages(prices)` gives the last month of each series. A later read of the same month replaces an earlier read, because a source can revise a value.
241
+
242
+ The adapter of the average prices of BLS is in `@mark1russell7/market-sources`.
243
+
222
244
  ## Example
223
245
 
224
246
  ```ts
@@ -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,O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AGA,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"}
@@ -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
@@ -4,7 +4,9 @@
4
4
  * The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants.
5
5
  * The board keeps the current prices within the terms of each source, and plans the reads of a watch.
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
+ * An average price is the mean price of one item in one area and one month, from an official statistic.
7
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";
8
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";
9
11
  import { Quantity } from "@mark1russell7/quantity";
10
12
  import { z } from "zod";
@@ -371,5 +373,5 @@ export declare function unitPriceFor(reading: PriceReading, count: number): Quan
371
373
  * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
372
374
  */
373
375
  export declare function costOf(reading: PriceReading, count: number): Quantity | null;
374
- export { AVAILABILITIES, type Availability, 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 };
375
377
  //# sourceMappingURL=index.d.ts.map
@@ -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":";;;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AsB;;;;;qBAMrB;;KAED,oBAAoB;;UAGf;WACN;WACA;WACA;;;;;;KAOC;WACG;;WACA;WAAuB,SAAS;;WAChC;WAA4B,QAAQ;;;UAGlC;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU;WACV,MAAM;WACN,gBAAgB;;;UAIV;WACN,MAAM;WACN,WAAW;;;UAIL;WACN,QAAQ;WACR,OAAO;;;UAID;WACN;WACA,gBAAgB;WAChB,OAAO;;;UAID;WACN;WACA;WACA,QAAQ;WACR,iBAAiB;WACjB,UAAU;;;UAIJ;WACN,OAAO;WACP,SAAS;;;KAIR,eAAe,SAAS,eAAe;;UAGlC;;;;;WAKN,WAAW;;;UAIL;WACN;WACA,MAAM;;;UAIA;;WAEN,iBAAiB;;WAEjB,SAAS;;WAET,OAAO;;;;;;;;wBAiFF,cAAc,eAAe;;;;;qBAUhC,gBAAgB,EAAE,QAAQ;;;;;qBAU1B,iBAAiB,EAAE,QAAQ;;;;;qBAU3B,oBAAoB,EAAE,QAAQ;;;;;qBAqB9B,oBAAoB,EAAE,QAAQ,UAAU;;qBAQxC,YAAY,EAAE,QAAQ;;qBAatB,kBAAkB,EAAE,QAAQ;;;;;qBAS5B,aAAa,EAAE,QAAQ;;;;;qBA4CvB,sBAAsB,EAAE,QAAQ;;qBAchC,0BAA0B,EAAE,QAAQ;;;;;;;;;;;;wBAqFjC,YAAY,aAAa,oBAAoB,OAAO,cAAc,UAAS,qBAA0B;;;;;;;wBCrarG,aAAa,SAAS,cAAc,gBAAgB;;;;;;;wBAgBpD,OAAO,SAAS,cAAc,gBAAgB"}
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,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A;WACA;WACA,UAAU;WACV,MAAM;WACN,gBAAgB;;;UAIV;WACN,MAAM;WACN,WAAW;;;UAIL;WACN,QAAQ;WACR,OAAO;;;UAID;WACN;WACA,gBAAgB;WAChB,OAAO;;;UAID;WACN;WACA;WACA,QAAQ;WACR,iBAAiB;WACjB,UAAU;;;UAIJ;WACN,OAAO;WACP,SAAS;;;KAIR,eAAe,SAAS,eAAe;;UAGlC;;;;;WAKN,WAAW;;;UAIL;WACN;WACA,MAAM;;;UAIA;;WAEN,iBAAiB;;WAEjB,SAAS;;WAET,OAAO;;;;;;;;wBAiFF,cAAc,eAAe;;;;;qBAUhC,gBAAgB,EAAE,QAAQ;;;;;qBAU1B,iBAAiB,EAAE,QAAQ;;;;;qBAU3B,oBAAoB,EAAE,QAAQ;;;;;qBAqB9B,oBAAoB,EAAE,QAAQ,UAAU;;qBAQxC,YAAY,EAAE,QAAQ;;qBAatB,kBAAkB,EAAE,QAAQ;;;;;qBAS5B,aAAa,EAAE,QAAQ;;;;;qBA4CvB,sBAAsB,EAAE,QAAQ;;qBAchC,0BAA0B,EAAE,QAAQ;;;;;;;;;;;;wBAqFjC,YAAY,aAAa,oBAAoB,OAAO,cAAc,UAAS,qBAA0B;;;;;;;wBCrarG,aAAa,SAAS,cAAc,gBAAgB;;;;;;;wBAgBpD,OAAO,SAAS,cAAc,gBAAgB"}
package/build/index.js CHANGED
@@ -1,4 +1,6 @@
1
- import { D as matchKeys, E as foldCode, O as gtinCheckDigit, S as offersPart, T as unitPriceFor, _ as specSchema, a as instantSchema, b as latestObservations, c as offerSchema, d as priceReadingSchema, f as productSchema, g as sourceSchema, h as sourceOfOffer, i as gtinSchema, k as parseGtin, 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, w as costOf, x as offersOfPart, y as bestOffer } from "./records-DU5uvTYJ.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";
@@ -629,6 +631,6 @@ function meteredCost(observation, usage, options = {}) {
629
631
  total: quantity(rationals.toNumber(total), unit)
630
632
  };
631
633
  }
632
- export { AVAILABILITIES, BOARD_FORMAT, CONDITIONS, FORMATS, FREE_SCOPES, METERED_KINDS, bestOffer, boardObservations, boardReadSchema, boardSchema, costOf, foldCode, freeAmountSchema, gtinCheckDigit, gtinSchema, instantSchema, isKept, keepObservations, keepUntil, lastReads, latestObservations, locationSchema, matchKeys, meterSchema, meteredCost, meteredKindOf, meteredObservationSchema, meteredOfferSchema, meteredPriceSchema, meteredReadingSchema, moneySchema, observationSchema, offerId, offerSchema, offersOfPart, offersPart, parseGtin, partNumberSchema, permitsHistory, permitsTrend, planReads, priceBreakSchema, priceReadingSchema, priceTermSchema, productSchema, readInterval, retentionSchema, sellerSchema, settleBoard, shippingSchema, sourceOfOffer, sourceSchema, sourceTermsSchema, specSchema, textSchema, tierSchema, unitPriceFor, watchEntrySchema, watchProblems };
634
+ export { AVAILABILITIES, BOARD_FORMAT, CONDITIONS, FORMATS, FREE_SCOPES, METERED_KINDS, averagePriceId, averagePriceSchema, bestOffer, boardObservations, boardReadSchema, boardSchema, costOf, foldCode, freeAmountSchema, gtinCheckDigit, gtinSchema, instantSchema, isKept, keepObservations, keepUntil, lastReads, latestAverages, latestObservations, locationSchema, matchKeys, meterSchema, meteredCost, meteredKindOf, meteredObservationSchema, meteredOfferSchema, meteredPriceSchema, meteredReadingSchema, moneySchema, monthSchema, observationSchema, offerId, offerSchema, offersOfPart, offersPart, parseGtin, partNumberSchema, permitsHistory, permitsTrend, planReads, priceBreakSchema, priceReadingSchema, priceTermSchema, productSchema, readInterval, retentionSchema, sellerSchema, settleBoard, shippingSchema, sourceOfOffer, sourceSchema, sourceTermsSchema, specSchema, textSchema, tierSchema, unitPriceFor, unitPriceSchema, watchEntrySchema, watchProblems };
633
635
 
634
636
  //# sourceMappingURL=index.js.map
@@ -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;CA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AAI,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
+ {"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,QAAQ,EAAE,EAAE,oBAAoB;CACzG,IAAI,UAAU,SAAS,YAAY,OAAO,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;CACnE,OAAO,IAAI,KAAK,KAAK,KAAK,MAAM,QAA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