@mark1russell7/market 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -1
- package/build/index.d.ts +2 -211
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2 -341
- package/build/index.js.map +1 -1
- package/build/offers-CVUAcRHs.d.ts +214 -0
- package/build/offers-CVUAcRHs.d.ts.map +1 -0
- package/build/plan.d.ts +151 -0
- package/build/plan.d.ts.map +1 -0
- package/build/plan.js +440 -0
- package/build/plan.js.map +1 -0
- package/build/records-hK1UCmpm.js +346 -0
- package/build/records-hK1UCmpm.js.map +1 -0
- package/package.json +14 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @mark1russell7/market
|
|
2
2
|
|
|
3
|
-
The records of a market: a product, an offer of a seller and a price reading, with their checks. The package also has the GTIN check, the match keys of a record, the cost of an order and the storage rules of a source. The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants. The board keeps the current prices within the terms of each source, and plans the reads of a watch.
|
|
3
|
+
The records of a market: a product, an offer of a seller and a price reading, with their checks. The package also has the GTIN check, the match keys of a record, the cost of an order and the storage rules of a source. The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants. The board keeps the current prices within the terms of each source, and plans the reads of a watch. A buy plan gives the best baskets of the parts that a need names.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
pnpm add @mark1russell7/market
|
|
@@ -77,6 +77,41 @@ board = settleBoard(board, { terms, now, names }, { name: "ups", at: now, observ
|
|
|
77
77
|
const chosen = bestOffer(offersOfPart(boardObservations(board, { terms, now }), want), { currency: "USD" });
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
+
## A buy plan
|
|
81
|
+
|
|
82
|
+
The entry `@mark1russell7/market/plan` chooses the parts of a purchase. A need names the slots of a basket and the parts that can fill each slot. Each part has facts, for example its watts. Vex programs over a basket give its measures and its rules. The plan searches the baskets with `@mark1russell7/strategy-search`. It gives the Pareto front of the price against the measures.
|
|
83
|
+
|
|
84
|
+
- `planBuys(need, observations, { evaluations, seed, population })` gives the plan. Each item of a basket is the offer in stock with the lowest cost for its part and its count.
|
|
85
|
+
- **The search.** A space with no more baskets than `evaluations` gets a grid of each basket. A larger space gets a genetic search. The seed of the search is `seed`, or else the id of the need.
|
|
86
|
+
- `needProblems(need)` gives the problems of a need. Examples are two slots with one name, a bad count, and a program that is not valid. `buyNeedSchema` examines the form of a need file.
|
|
87
|
+
- **The records of a basket.** A program evaluates at the key `need`, which has the inputs of the need. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. An empty slot has the count 0. The axis `others` gives the slots.
|
|
88
|
+
- **The breaks.** A basket breaks `price:<slot>` with no usable offer at its count. It breaks `measure:<name>` when a measure gives no number, and `limit:<name>` outside the limits of a measure. It breaks `rule:<name>` when a rule does not give `true`. The plan counts the baskets of each break, with the reason of the first basket.
|
|
89
|
+
- **The parts with no offer.** `unpriced` names each part with no usable offer at a count of its slot. A slot with a minimum of 1 or more and no such part gives the method `none` and an empty front.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { app, axes, each, lit, ref } from "@mark1russell7/vex";
|
|
93
|
+
import { NEED_FORMAT, planBuys, type BuyNeed } from "@mark1russell7/market/plan";
|
|
94
|
+
|
|
95
|
+
const part = (key: string, wattHours: number, outputWatts: number) => ({ key, want: { brands: ["Acme"], partNumbers: [key] }, facts: { wattHours, outputWatts } });
|
|
96
|
+
const need: BuyNeed = {
|
|
97
|
+
format: NEED_FORMAT,
|
|
98
|
+
id: "closet-ups",
|
|
99
|
+
currency: "USD",
|
|
100
|
+
inputs: { loadWatts: 300 },
|
|
101
|
+
slots: [
|
|
102
|
+
{ name: "ups", parts: [part("UPS-600", 100, 360), part("UPS-1000", 200, 600)] },
|
|
103
|
+
{ name: "battery", parts: [part("PACK-1", 150, 0)], count: { min: 0, max: 2 } },
|
|
104
|
+
],
|
|
105
|
+
// The minutes of the batteries at the load.
|
|
106
|
+
measures: [{ name: "minutes", goal: "max", unit: "min", program: app("multiply", app("divide", app("sum", each(axes.others, app("multiply", ref("wattHours"), ref("count")))), ref("loadWatts")), lit(60)) }],
|
|
107
|
+
// The largest output of a part is the load or more.
|
|
108
|
+
rules: [{ name: "output", program: app("gte", app("max", each(axes.others, ref("outputWatts"))), ref("loadWatts")) }],
|
|
109
|
+
};
|
|
110
|
+
// The offers: a UPS-600 for $120, a UPS-1000 for $260 and a PACK-1 for $80, each with free shipping.
|
|
111
|
+
const plan = planBuys(need, observations);
|
|
112
|
+
plan.front.map((choice) => [choice.price.value, choice.values["minutes"]]); // [[120, 20], [200, 50], [280, 80], [420, 100]]
|
|
113
|
+
```
|
|
114
|
+
|
|
80
115
|
## Example
|
|
81
116
|
|
|
82
117
|
```ts
|
|
@@ -106,5 +141,7 @@ isKept(terms, reading, "2026-11-16T00:00:00Z"); // false
|
|
|
106
141
|
- The match keys do not know the aliases of a brand. `Western Digital` and `WD` give two keys. A want of a part names each form of the brand.
|
|
107
142
|
- A part number of a want matches each longer part number that starts with it. A want gives the full part number of the maker.
|
|
108
143
|
- The money of the quantity package has one currency: the US dollar.
|
|
144
|
+
- The price of a basket adds the cost of each item. Each item is one order with its own shipping, so the plan does not know a shared shipping cost.
|
|
145
|
+
- A buy plan does not compare the count of an item with the count of the available units of its offer.
|
|
109
146
|
- The package has no history of prices yet. Roadmap item R5 adds it, after the owner chooses its source.
|
|
110
147
|
- The board does not know if an offer ended when a new read does not give it. It drops the offer from that read. Another read can still give it.
|
package/build/index.d.ts
CHANGED
|
@@ -4,218 +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
|
*/
|
|
7
|
+
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";
|
|
7
8
|
import { Quantity } from "@mark1russell7/quantity";
|
|
8
9
|
import { z } from "zod";
|
|
9
|
-
/** A part number of a maker: the brand, and the number that the maker gives to the part. */
|
|
10
|
-
interface PartNumber {
|
|
11
|
-
readonly brand: string;
|
|
12
|
-
readonly partNumber: string;
|
|
13
|
-
}
|
|
14
|
-
/** The identifiers of a product or of an offer. */
|
|
15
|
-
interface Identifiers {
|
|
16
|
-
readonly gtins: readonly string[];
|
|
17
|
-
readonly partNumbers: readonly PartNumber[];
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* This function folds a brand or a part number for a comparison. The result has only capital letters A to Z
|
|
21
|
-
* and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.
|
|
22
|
-
*/
|
|
23
|
-
export declare function foldCode(text: string): string;
|
|
24
|
-
/**
|
|
25
|
-
* This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,
|
|
26
|
-
* or `part:` with the folded brand and part number. Two records with a key in common name one product.
|
|
27
|
-
* The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.
|
|
28
|
-
*/
|
|
29
|
-
export declare function matchKeys(identifiers: Identifiers): string[];
|
|
30
|
-
/**
|
|
31
|
-
* The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
|
|
32
|
-
* the field `grade` of the offer.
|
|
33
|
-
*/
|
|
34
|
-
export declare const CONDITIONS: readonly ["new", "open-box", "refurbished", "used", "for-parts", "unknown"];
|
|
35
|
-
/** The condition of an offer. */
|
|
36
|
-
type Condition = (typeof CONDITIONS)[number];
|
|
37
|
-
/** The states of the stock of an offer at the time of a reading. */
|
|
38
|
-
export declare const AVAILABILITIES: readonly ["in-stock", "low-stock", "out-of-stock", "preorder", "unknown"];
|
|
39
|
-
/** The state of the stock of an offer. */
|
|
40
|
-
type Availability = (typeof AVAILABILITIES)[number];
|
|
41
|
-
/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
|
|
42
|
-
export declare const FORMATS: readonly ["fixed-price", "auction"];
|
|
43
|
-
/** The buying format of an offer. */
|
|
44
|
-
type Format = (typeof FORMATS)[number];
|
|
45
|
-
/** One specification of a product as text. */
|
|
46
|
-
interface Spec {
|
|
47
|
-
readonly name: string;
|
|
48
|
-
readonly value: string;
|
|
49
|
-
}
|
|
50
|
-
/** The feedback of a seller: the percent of good feedback, and the count of the feedback. */
|
|
51
|
-
interface Rating {
|
|
52
|
-
readonly percent: number;
|
|
53
|
-
readonly count: number;
|
|
54
|
-
}
|
|
55
|
-
/** A seller of an offer. A source gives some of these fields, or none. */
|
|
56
|
-
interface Seller {
|
|
57
|
-
readonly id?: string | undefined;
|
|
58
|
-
readonly name?: string | undefined;
|
|
59
|
-
readonly rating?: Rating | undefined;
|
|
60
|
-
}
|
|
61
|
-
/** A product of the catalog: one thing that a person can buy, with its identifiers and its specifications. */
|
|
62
|
-
interface Product {
|
|
63
|
-
readonly id: string;
|
|
64
|
-
readonly title: string;
|
|
65
|
-
readonly brand?: string | undefined;
|
|
66
|
-
readonly category?: readonly string[] | undefined;
|
|
67
|
-
readonly gtins: readonly string[];
|
|
68
|
-
readonly partNumbers: readonly PartNumber[];
|
|
69
|
-
readonly specs: readonly Spec[];
|
|
70
|
-
}
|
|
71
|
-
/** An offer of a seller: one product at one seller, with the identifiers that the source gives. */
|
|
72
|
-
interface Offer {
|
|
73
|
-
readonly id: string;
|
|
74
|
-
readonly source: string;
|
|
75
|
-
readonly sourceId: string;
|
|
76
|
-
readonly productId?: string | undefined;
|
|
77
|
-
readonly title: string;
|
|
78
|
-
readonly url?: string | undefined;
|
|
79
|
-
readonly seller: Seller;
|
|
80
|
-
readonly condition: Condition;
|
|
81
|
-
readonly grade?: string | undefined;
|
|
82
|
-
readonly format: Format;
|
|
83
|
-
readonly endsAt?: string | undefined;
|
|
84
|
-
readonly gtins: readonly string[];
|
|
85
|
-
readonly partNumbers: readonly PartNumber[];
|
|
86
|
-
readonly specs: readonly Spec[];
|
|
87
|
-
}
|
|
88
|
-
/** The shipping of a reading. A calculated cost depends on the address of the buyer. */
|
|
89
|
-
type Shipping = {
|
|
90
|
-
readonly kind: "free";
|
|
91
|
-
} | {
|
|
92
|
-
readonly kind: "fixed";
|
|
93
|
-
readonly cost: Quantity;
|
|
94
|
-
} | {
|
|
95
|
-
readonly kind: "calculated";
|
|
96
|
-
} | {
|
|
97
|
-
readonly kind: "unknown";
|
|
98
|
-
};
|
|
99
|
-
/** A price break of a reading: the unit price for an order of `quantity` units or more. */
|
|
100
|
-
interface PriceBreak {
|
|
101
|
-
readonly quantity: number;
|
|
102
|
-
readonly unitPrice: Quantity;
|
|
103
|
-
}
|
|
104
|
-
/** A price reading: the state of one offer at one instant. */
|
|
105
|
-
interface PriceReading {
|
|
106
|
-
readonly offerId: string;
|
|
107
|
-
readonly at: string;
|
|
108
|
-
readonly price: Quantity;
|
|
109
|
-
readonly listPrice?: Quantity | undefined;
|
|
110
|
-
readonly shipping: Shipping;
|
|
111
|
-
readonly availability: Availability;
|
|
112
|
-
readonly available?: number | undefined;
|
|
113
|
-
readonly minimumQuantity?: number | undefined;
|
|
114
|
-
readonly priceBreaks?: readonly PriceBreak[] | undefined;
|
|
115
|
-
}
|
|
116
|
-
/** This schema accepts a text with a character that is not a space, and with no space at an end. */
|
|
117
|
-
export declare const textSchema: z.ZodType<string>;
|
|
118
|
-
/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
|
|
119
|
-
export declare const sourceSchema: z.ZodType<string>;
|
|
120
|
-
/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
|
|
121
|
-
export declare const gtinSchema: z.ZodType<string>;
|
|
122
|
-
/** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
|
|
123
|
-
export declare const moneySchema: z.ZodType<Quantity, Quantity>;
|
|
124
|
-
/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
|
|
125
|
-
export declare const instantSchema: z.ZodType<string>;
|
|
126
|
-
/** This schema accepts a part number of a maker. */
|
|
127
|
-
export declare const partNumberSchema: z.ZodType<PartNumber>;
|
|
128
|
-
/** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
|
|
129
|
-
export declare const specSchema: z.ZodType<Spec>;
|
|
130
|
-
/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
|
|
131
|
-
export declare const sellerSchema: z.ZodType<Seller>;
|
|
132
|
-
/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
|
|
133
|
-
export declare const productSchema: z.ZodType<Product>;
|
|
134
|
-
/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
|
|
135
|
-
export declare function offerId(source: string, sourceId: string): string;
|
|
136
|
-
/** This function gives the name of the source of an offer id: the text before the first colon. */
|
|
137
|
-
export declare function sourceOfOffer(id: string): string;
|
|
138
|
-
/**
|
|
139
|
-
* This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
|
|
140
|
-
* `productId` names the product of the catalog after a match.
|
|
141
|
-
*/
|
|
142
|
-
export declare const offerSchema: z.ZodType<Offer>;
|
|
143
|
-
/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
|
|
144
|
-
export declare const shippingSchema: z.ZodType<Shipping>;
|
|
145
|
-
/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
|
|
146
|
-
export declare const priceBreakSchema: z.ZodType<PriceBreak>;
|
|
147
|
-
/**
|
|
148
|
-
* This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
|
|
149
|
-
* order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
|
|
150
|
-
* than the minimum.
|
|
151
|
-
*/
|
|
152
|
-
export declare const priceReadingSchema: z.ZodType<PriceReading>;
|
|
153
|
-
/** One offer of a source, and its price reading at one instant. */
|
|
154
|
-
interface Observation {
|
|
155
|
-
readonly offer: Offer;
|
|
156
|
-
readonly reading: PriceReading;
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* This record names a part that a buyer wants: the names of its maker, and its part numbers. A seller can write
|
|
160
|
-
* the brand of one maker in more than one form, so the want has a list of names.
|
|
161
|
-
*/
|
|
162
|
-
interface PartWant {
|
|
163
|
-
/** The names of the maker, as the sellers write the brand. */
|
|
164
|
-
readonly brands: readonly string[];
|
|
165
|
-
/** The part numbers of the maker. A part number of an offer matches when it starts with one of them, after the fold. */
|
|
166
|
-
readonly partNumbers: readonly string[];
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the
|
|
170
|
-
* want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number
|
|
171
|
-
* of another maker does not match: many makers use short numbers like `A1383`.
|
|
172
|
-
*/
|
|
173
|
-
export declare function offersPart(offer: Pick<Offer, "partNumbers">, want: PartWant): boolean;
|
|
174
|
-
/**
|
|
175
|
-
* This function gives the latest observation of each offer, in the order of the offer ids. When two readings of
|
|
176
|
-
* one offer have the same instant, the later one in the list applies.
|
|
177
|
-
*/
|
|
178
|
-
export declare function latestObservations(observations: readonly Observation[]): Observation[];
|
|
179
|
-
/** This function gives the latest observation of each offer of the part, in the order of the offer ids. */
|
|
180
|
-
export declare function offersOfPart(observations: readonly Observation[], want: PartWant): Observation[];
|
|
181
|
-
/** This record is one offer that a buyer can choose, with the price of an order in the currency of the buyer. */
|
|
182
|
-
interface OfferChoice {
|
|
183
|
-
readonly observation: Observation;
|
|
184
|
-
/** The unit price for the count, times the count. */
|
|
185
|
-
readonly goods: Quantity;
|
|
186
|
-
/** The goods and the shipping, or null when the shipping cost is not known. */
|
|
187
|
-
readonly cost: Quantity | null;
|
|
188
|
-
/** True when the availability is `in-stock` or `low-stock`. */
|
|
189
|
-
readonly inStock: boolean;
|
|
190
|
-
}
|
|
191
|
-
/** These options change the choice of an offer. */
|
|
192
|
-
interface BestOfferOptions {
|
|
193
|
-
/** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. An offer with a price in another currency is skipped. */
|
|
194
|
-
readonly currency: string;
|
|
195
|
-
/** The count of units of the order. The default is 1. */
|
|
196
|
-
readonly count?: number;
|
|
197
|
-
/** The conditions that the buyer accepts. The default is `new` only. */
|
|
198
|
-
readonly conditions?: readonly Condition[];
|
|
199
|
-
}
|
|
200
|
-
/** This record is the choice of an offer: the best offer, each offer in the order of the price, and each skipped offer. */
|
|
201
|
-
interface BestOffer {
|
|
202
|
-
/** The offer with the lowest price that is in stock, or else the offer with the lowest price, or null with no offer. */
|
|
203
|
-
readonly best: OfferChoice | null;
|
|
204
|
-
/** The offers, from the lowest price of the goods. Equal prices go in the order of the cost, then of the offer id. */
|
|
205
|
-
readonly offers: readonly OfferChoice[];
|
|
206
|
-
/** The offers that the choice skipped, each with the reason. */
|
|
207
|
-
readonly skipped: readonly {
|
|
208
|
-
readonly offerId: string;
|
|
209
|
-
readonly why: string;
|
|
210
|
-
}[];
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a
|
|
214
|
-
* condition that the buyer does not accept, a price in another currency, or a minimum above the count.
|
|
215
|
-
*
|
|
216
|
-
* @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.
|
|
217
|
-
*/
|
|
218
|
-
export declare function bestOffer(observations: readonly Observation[], options: BestOfferOptions): BestOffer;
|
|
219
10
|
/** The storage rule of a source, from its terms. */
|
|
220
11
|
type Retention = {
|
|
221
12
|
readonly kind: "keep";
|
|
@@ -426,5 +217,5 @@ export declare function unitPriceFor(reading: PriceReading, count: number): Quan
|
|
|
426
217
|
* @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
|
|
427
218
|
*/
|
|
428
219
|
export declare function costOf(reading: PriceReading, count: number): Quantity | null;
|
|
429
|
-
export type
|
|
220
|
+
export { AVAILABILITIES, type Availability, type BestOffer, type BestOfferOptions, type Board, type BoardDrop, type BoardRead, CONDITIONS, type Condition, type Dropped, FORMATS, type Format, type Identifiers, type KeepOptions, type Kept, type Observation, type Offer, type OfferChoice, type PartNumber, type PartWant, type PriceBreak, type PriceReading, 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 WatchEntry, bestOffer, foldCode, gtinSchema, instantSchema, latestObservations, matchKeys, moneySchema, offerId, offerSchema, offersOfPart, offersPart, partNumberSchema, priceBreakSchema, priceReadingSchema, productSchema, sellerSchema, shippingSchema, sourceOfOffer, sourceSchema, specSchema, textSchema };
|
|
430
221
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/gtin.ts","../src/price.ts"],"mappings":";;;;;;;;;;KAMY;WACG;;WACA;WAA0B,KAAK;;WAC/B;;;UAGE;WACN;WACA,WAAW;WACX;WACA;WACA;;;;;;qBAOE,iBAAiB,EAAE,QAAQ;;;;;qBAU3B,mBAAmB,EAAE,QAAQ;;;;;wBAY1B,UAAU,OAAO,aAAa;WAAoB;;;;;;wBAalD,OAAO,OAAO,aAAa;WAAoB;GAAc,aAAa;;wBAW1E,eAAe,OAAO;;wBAKtB,aAAa,OAAO;;qBC7DvB;;qBAGA,mBAAmB,EAAE,QAAQ;;UAKzB;WACN;WACA;WACA,uBAAuB;;;UAIjB;WACN,eAAe;WACf;WACA,gBAAgB;;;qBAId,iBAAiB,EAAE,QAAQ;;qBAO3B,aAAa,EAAE,QAAQ;;UAOnB;WACN;WACA;;;UAIM;;WAEN,gBAAgB;;WAEhB;;WAEA;;;UAIM;;WAEN,eAAe;;WAEf,kBAAkB;;;;;;;;;;;wBAyBb,iBAAiB,uBAAuB,eAAe,SAAS,cAAc;;UA0B7E,sBAAsB;;WAE5B;;;UAIM,kBAAkB;WACxB;;;UAIM;WACN,OAAO;WACP,kBAAkB;;;;;;;;;;wBAab,YAAY,OAAO,OAAO,SAAS,eAAe,OAAO,YAAY;;;;;wBAwBrE,kBAAkB,OAAO,OAAO,SAAS,cAAc;;wBAKvD,UAAU,OAAO,QAAQ;;UAKxB;;WAEN;;WAEA;;WAEA,OAAO;;;qBAIL,kBAAkB,EAAE,QAAQ;;UAOxB;;WAEN,gBAAgB;;;;;WAKhB,OAAO;;;KAIN;WAA0B;WAAmB;;WAA0B;WAAoB;;;;;;;;wBAQvF,aAAa,OAAO,YAAY,SAAS,kBAAkB;;wBAc3D,cAAc,kBAAkB,cAAc,SAAS;;UAatD;;WAEN;;;;;;WAMA;;WAEA;;;;;;;;;wBAUK,UAAU,kBAAkB,cAAc,MAAM,SAAS,yBAAyB,aAAa,SAAS,kBAAkB;;;;;;wBC5P1H,eAAe;;;;;wBAcf,UAAU;;;;;;;wBCjBV,aAAa,SAAS,cAAc,gBAAgB;;;;;;;wBAgBpD,OAAO,SAAS,cAAc,gBAAgB"}
|
package/build/index.js
CHANGED
|
@@ -1,346 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as costOf, D as gtinCheckDigit, E as matchKeys, O as parseGtin, S as offersPart, T as foldCode, _ 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, 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 unitPriceFor, x as offersOfPart, y as bestOffer } from "./records-hK1UCmpm.js";
|
|
2
|
+
import { valueIn } from "@mark1russell7/quantity";
|
|
2
3
|
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
3
4
|
import { z } from "zod";
|
|
4
|
-
// src/gtin.ts
|
|
5
|
-
/**
|
|
6
|
-
* This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.
|
|
7
|
-
* The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.
|
|
8
|
-
*/
|
|
9
|
-
const LENGTHS = /* @__PURE__ */ new Set([
|
|
10
|
-
8,
|
|
11
|
-
12,
|
|
12
|
-
13,
|
|
13
|
-
14
|
|
14
|
-
]);
|
|
15
|
-
/**
|
|
16
|
-
* This function gives the check digit of the digits of a GTIN without its last digit.
|
|
17
|
-
*
|
|
18
|
-
* @throws RangeError when the text has a character that is not a digit, or no character.
|
|
19
|
-
*/
|
|
20
|
-
function gtinCheckDigit(body) {
|
|
21
|
-
if (!/^\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);
|
|
22
|
-
let total = 0;
|
|
23
|
-
for (let i = 0; i < body.length; i += 1) {
|
|
24
|
-
const digit = body.charCodeAt(body.length - 1 - i) - 48;
|
|
25
|
-
total += i % 2 === 0 ? digit * 3 : digit;
|
|
26
|
-
}
|
|
27
|
-
return (10 - total % 10) % 10;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
|
|
31
|
-
* It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
|
|
32
|
-
*/
|
|
33
|
-
function parseGtin(text) {
|
|
34
|
-
const digits = text.replace(/[\s-]/g, "");
|
|
35
|
-
if (!/^\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;
|
|
36
|
-
if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;
|
|
37
|
-
return digits.padStart(14, "0");
|
|
38
|
-
}
|
|
39
|
-
// src/identifiers.ts
|
|
40
|
-
/**
|
|
41
|
-
* This function folds a brand or a part number for a comparison. The result has only capital letters A to Z
|
|
42
|
-
* and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.
|
|
43
|
-
*/
|
|
44
|
-
function foldCode(text) {
|
|
45
|
-
return text.normalize("NFKD").toUpperCase().replace(/[^A-Z0-9]/g, "");
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,
|
|
49
|
-
* or `part:` with the folded brand and part number. Two records with a key in common name one product.
|
|
50
|
-
* The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.
|
|
51
|
-
*/
|
|
52
|
-
function matchKeys(identifiers) {
|
|
53
|
-
const keys = /* @__PURE__ */ new Set();
|
|
54
|
-
for (const text of identifiers.gtins) {
|
|
55
|
-
const gtin = parseGtin(text);
|
|
56
|
-
if (gtin !== null) keys.add(`gtin:${gtin}`);
|
|
57
|
-
}
|
|
58
|
-
for (const { brand, partNumber } of identifiers.partNumbers) {
|
|
59
|
-
const folded = [foldCode(brand), foldCode(partNumber)];
|
|
60
|
-
if (folded.every((part) => part !== "")) keys.add(`part:${folded.join("/")}`);
|
|
61
|
-
}
|
|
62
|
-
return [...keys].sort();
|
|
63
|
-
}
|
|
64
|
-
// src/price.ts
|
|
65
|
-
/**
|
|
66
|
-
* This function gives the unit price for an order of `count` units. The price of the largest break at or
|
|
67
|
-
* below the count applies, or the price of the reading when no break applies.
|
|
68
|
-
*
|
|
69
|
-
* @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
|
|
70
|
-
*/
|
|
71
|
-
function unitPriceFor(reading, count) {
|
|
72
|
-
const minimum = reading.minimumQuantity ?? 1;
|
|
73
|
-
if (!Number.isSafeInteger(count) || count < minimum) throw new RangeError(`The count ${count} is not a whole number of ${minimum} or more.`);
|
|
74
|
-
let price = reading.price;
|
|
75
|
-
for (const entry of reading.priceBreaks ?? []) if (entry.quantity <= count) price = entry.unitPrice;
|
|
76
|
-
return price;
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* This function gives the cost of an order of `count` units with its shipping, or null when the shipping
|
|
80
|
-
* cost is not known. The cost is exact, and the function does not round it to the cent.
|
|
81
|
-
*
|
|
82
|
-
* @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
|
|
83
|
-
*/
|
|
84
|
-
function costOf(reading, count) {
|
|
85
|
-
const goods = scale(unitPriceFor(reading, count), count);
|
|
86
|
-
switch (reading.shipping.kind) {
|
|
87
|
-
case "free": return goods;
|
|
88
|
-
case "fixed": return add(goods, reading.shipping.cost);
|
|
89
|
-
default: return null;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
// src/offers.ts
|
|
93
|
-
/**
|
|
94
|
-
* This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the
|
|
95
|
-
* want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number
|
|
96
|
-
* of another maker does not match: many makers use short numbers like `A1383`.
|
|
97
|
-
*/
|
|
98
|
-
function offersPart(offer, want) {
|
|
99
|
-
const brands = new Set(want.brands.map(foldCode).filter((brand) => brand !== ""));
|
|
100
|
-
const parts = want.partNumbers.map(foldCode).filter((part) => part !== "");
|
|
101
|
-
return offer.partNumbers.some(({ brand, partNumber }) => {
|
|
102
|
-
const folded = foldCode(partNumber);
|
|
103
|
-
return brands.has(foldCode(brand)) && parts.some((part) => folded.startsWith(part));
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* This function gives the latest observation of each offer, in the order of the offer ids. When two readings of
|
|
108
|
-
* one offer have the same instant, the later one in the list applies.
|
|
109
|
-
*/
|
|
110
|
-
function latestObservations(observations) {
|
|
111
|
-
const latest = /* @__PURE__ */ new Map();
|
|
112
|
-
for (const each of observations) {
|
|
113
|
-
const seen = latest.get(each.offer.id);
|
|
114
|
-
if (seen === void 0 || Date.parse(seen.reading.at) <= Date.parse(each.reading.at)) latest.set(each.offer.id, each);
|
|
115
|
-
}
|
|
116
|
-
return [...latest.values()].sort((a, b) => order(a.offer.id, b.offer.id));
|
|
117
|
-
}
|
|
118
|
-
/** This function gives the latest observation of each offer of the part, in the order of the offer ids. */
|
|
119
|
-
function offersOfPart(observations, want) {
|
|
120
|
-
return latestObservations(observations.filter((each) => offersPart(each.offer, want)));
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a
|
|
124
|
-
* condition that the buyer does not accept, a price in another currency, or a minimum above the count.
|
|
125
|
-
*
|
|
126
|
-
* @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.
|
|
127
|
-
*/
|
|
128
|
-
function bestOffer(observations, options) {
|
|
129
|
-
const { currency, count = 1, conditions = ["new"] } = options;
|
|
130
|
-
if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The count ${count} is not a whole number of 1 or more.`);
|
|
131
|
-
if (!isMoney(currency)) throw new RangeError(`The currency ${currency} is not a unit of money of @mark1russell7/quantity.`);
|
|
132
|
-
const accepted = new Set(conditions);
|
|
133
|
-
const offers = [];
|
|
134
|
-
const skipped = [];
|
|
135
|
-
for (const observation of latestObservations(observations)) {
|
|
136
|
-
const { offer, reading } = observation;
|
|
137
|
-
const minimum = reading.minimumQuantity ?? 1;
|
|
138
|
-
if (!accepted.has(offer.condition)) skipped.push({
|
|
139
|
-
offerId: offer.id,
|
|
140
|
-
why: `The condition ${offer.condition} is not a condition that the buyer accepts.`
|
|
141
|
-
});
|
|
142
|
-
else if (!converts(reading.price.unit, currency)) skipped.push({
|
|
143
|
-
offerId: offer.id,
|
|
144
|
-
why: `The price is in ${reading.price.unit}, not in ${currency}.`
|
|
145
|
-
});
|
|
146
|
-
else if (count < minimum) skipped.push({
|
|
147
|
-
offerId: offer.id,
|
|
148
|
-
why: `The minimum order is ${minimum} units, more than the count ${count}.`
|
|
149
|
-
});
|
|
150
|
-
else {
|
|
151
|
-
const goods = convert(scale(unitPriceFor(reading, count), count), currency);
|
|
152
|
-
const total = reading.shipping.kind !== "fixed" || converts(reading.shipping.cost.unit, currency) ? costOf(reading, count) : null;
|
|
153
|
-
const cost = total === null ? null : convert(total, currency);
|
|
154
|
-
const inStock = reading.availability === "in-stock" || reading.availability === "low-stock";
|
|
155
|
-
offers.push({
|
|
156
|
-
observation,
|
|
157
|
-
goods,
|
|
158
|
-
cost,
|
|
159
|
-
inStock
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
offers.sort((a, b) => compare(a.goods, b.goods) || byCost(a.cost, b.cost) || order(a.observation.offer.id, b.observation.offer.id));
|
|
164
|
-
return {
|
|
165
|
-
best: offers.find((choice) => choice.inStock) ?? offers[0] ?? null,
|
|
166
|
-
offers,
|
|
167
|
-
skipped
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
/** This function tells if a unit is a unit of money that the quantity package knows. */
|
|
171
|
-
function isMoney(unit) {
|
|
172
|
-
try {
|
|
173
|
-
return kindOf(unit) === "money";
|
|
174
|
-
} catch (error) {
|
|
175
|
-
if (error instanceof UnitError) return false;
|
|
176
|
-
throw error;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
/** 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. */
|
|
180
|
-
function converts(from, to) {
|
|
181
|
-
try {
|
|
182
|
-
return convertible(from, to);
|
|
183
|
-
} catch (error) {
|
|
184
|
-
if (error instanceof UnitError) return false;
|
|
185
|
-
throw error;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
/** This function orders two costs. A known cost comes before a cost that is not known. */
|
|
189
|
-
function byCost(a, b) {
|
|
190
|
-
if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;
|
|
191
|
-
return compare(a, b);
|
|
192
|
-
}
|
|
193
|
-
/** This function orders two texts by their code units, so the order does not depend on the locale. */
|
|
194
|
-
function order(a, b) {
|
|
195
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
196
|
-
}
|
|
197
|
-
// src/records.ts
|
|
198
|
-
/**
|
|
199
|
-
* The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
|
|
200
|
-
* the field `grade` of the offer.
|
|
201
|
-
*/
|
|
202
|
-
const CONDITIONS = [
|
|
203
|
-
"new",
|
|
204
|
-
"open-box",
|
|
205
|
-
"refurbished",
|
|
206
|
-
"used",
|
|
207
|
-
"for-parts",
|
|
208
|
-
"unknown"
|
|
209
|
-
];
|
|
210
|
-
/** The states of the stock of an offer at the time of a reading. */
|
|
211
|
-
const AVAILABILITIES = [
|
|
212
|
-
"in-stock",
|
|
213
|
-
"low-stock",
|
|
214
|
-
"out-of-stock",
|
|
215
|
-
"preorder",
|
|
216
|
-
"unknown"
|
|
217
|
-
];
|
|
218
|
-
/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
|
|
219
|
-
const FORMATS = ["fixed-price", "auction"];
|
|
220
|
-
/** This schema accepts a text with a character that is not a space, and with no space at an end. */
|
|
221
|
-
const textSchema = z.string().refine((text) => text !== "" && text === text.trim(), "The text is empty, or it has a space at an end.");
|
|
222
|
-
/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
|
|
223
|
-
const sourceSchema = z.string().regex(/^[a-z][a-z0-9-]*$/, "The name of a source has small letters, digits and hyphens, with a letter first.");
|
|
224
|
-
/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
|
|
225
|
-
const gtinSchema = z.string().refine((text) => /^\d{14}$/.test(text) && parseGtin(text) === text, "The GTIN is not a GTIN-14 with a correct check digit.");
|
|
226
|
-
/** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
|
|
227
|
-
const moneySchema = quantitySchema("money", { nonnegative: true });
|
|
228
|
-
/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
|
|
229
|
-
const instantSchema = z.iso.datetime();
|
|
230
|
-
/** This schema accepts a part number of a maker. */
|
|
231
|
-
const partNumberSchema = z.strictObject({
|
|
232
|
-
brand: textSchema,
|
|
233
|
-
partNumber: textSchema
|
|
234
|
-
});
|
|
235
|
-
/** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
|
|
236
|
-
const specSchema = z.strictObject({
|
|
237
|
-
name: textSchema,
|
|
238
|
-
value: textSchema
|
|
239
|
-
});
|
|
240
|
-
/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
|
|
241
|
-
const sellerSchema = z.strictObject({
|
|
242
|
-
id: textSchema.optional(),
|
|
243
|
-
name: textSchema.optional(),
|
|
244
|
-
rating: z.strictObject({
|
|
245
|
-
percent: z.number().min(0).max(100),
|
|
246
|
-
count: z.int().nonnegative()
|
|
247
|
-
}).optional()
|
|
248
|
-
});
|
|
249
|
-
/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
|
|
250
|
-
const productSchema = z.strictObject({
|
|
251
|
-
id: textSchema,
|
|
252
|
-
title: textSchema,
|
|
253
|
-
brand: textSchema.optional(),
|
|
254
|
-
category: z.array(textSchema).optional(),
|
|
255
|
-
gtins: z.array(gtinSchema),
|
|
256
|
-
partNumbers: z.array(partNumberSchema),
|
|
257
|
-
specs: z.array(specSchema)
|
|
258
|
-
});
|
|
259
|
-
/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
|
|
260
|
-
function offerId(source, sourceId) {
|
|
261
|
-
return `${source}:${sourceId}`;
|
|
262
|
-
}
|
|
263
|
-
/** This function gives the name of the source of an offer id: the text before the first colon. */
|
|
264
|
-
function sourceOfOffer(id) {
|
|
265
|
-
const colon = id.indexOf(":");
|
|
266
|
-
if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);
|
|
267
|
-
return id.slice(0, colon);
|
|
268
|
-
}
|
|
269
|
-
/**
|
|
270
|
-
* This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
|
|
271
|
-
* `productId` names the product of the catalog after a match.
|
|
272
|
-
*/
|
|
273
|
-
const offerSchema = z.strictObject({
|
|
274
|
-
id: textSchema,
|
|
275
|
-
source: sourceSchema,
|
|
276
|
-
sourceId: textSchema,
|
|
277
|
-
productId: textSchema.optional(),
|
|
278
|
-
title: textSchema,
|
|
279
|
-
url: z.url({ protocol: /^https$/ }).optional(),
|
|
280
|
-
seller: sellerSchema,
|
|
281
|
-
condition: z.enum(CONDITIONS),
|
|
282
|
-
grade: textSchema.optional(),
|
|
283
|
-
format: z.enum(FORMATS),
|
|
284
|
-
endsAt: instantSchema.optional(),
|
|
285
|
-
gtins: z.array(gtinSchema),
|
|
286
|
-
partNumbers: z.array(partNumberSchema),
|
|
287
|
-
specs: z.array(specSchema)
|
|
288
|
-
}).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
|
|
289
|
-
message: "The id of an offer is its source and its source id, with a colon between them.",
|
|
290
|
-
path: ["id"]
|
|
291
|
-
});
|
|
292
|
-
/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
|
|
293
|
-
const shippingSchema = z.discriminatedUnion("kind", [
|
|
294
|
-
z.strictObject({ kind: z.literal("free") }),
|
|
295
|
-
z.strictObject({
|
|
296
|
-
kind: z.literal("fixed"),
|
|
297
|
-
cost: moneySchema
|
|
298
|
-
}),
|
|
299
|
-
z.strictObject({ kind: z.literal("calculated") }),
|
|
300
|
-
z.strictObject({ kind: z.literal("unknown") })
|
|
301
|
-
]);
|
|
302
|
-
/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
|
|
303
|
-
const priceBreakSchema = z.strictObject({
|
|
304
|
-
quantity: z.int().min(2),
|
|
305
|
-
unitPrice: moneySchema
|
|
306
|
-
});
|
|
307
|
-
/**
|
|
308
|
-
* This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
|
|
309
|
-
* order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
|
|
310
|
-
* than the minimum.
|
|
311
|
-
*/
|
|
312
|
-
const priceReadingSchema = z.strictObject({
|
|
313
|
-
offerId: textSchema,
|
|
314
|
-
at: instantSchema,
|
|
315
|
-
price: moneySchema,
|
|
316
|
-
listPrice: moneySchema.optional(),
|
|
317
|
-
shipping: shippingSchema,
|
|
318
|
-
availability: z.enum(AVAILABILITIES),
|
|
319
|
-
available: z.int().nonnegative().optional(),
|
|
320
|
-
minimumQuantity: z.int().min(1).optional(),
|
|
321
|
-
priceBreaks: z.array(priceBreakSchema).optional()
|
|
322
|
-
}).superRefine((reading, context) => {
|
|
323
|
-
let last = reading.minimumQuantity ?? 1;
|
|
324
|
-
for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {
|
|
325
|
-
if (entry.quantity <= last) context.addIssue({
|
|
326
|
-
code: "custom",
|
|
327
|
-
message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,
|
|
328
|
-
path: [
|
|
329
|
-
"priceBreaks",
|
|
330
|
-
index,
|
|
331
|
-
"quantity"
|
|
332
|
-
]
|
|
333
|
-
});
|
|
334
|
-
last = Math.max(last, entry.quantity);
|
|
335
|
-
}
|
|
336
|
-
const { availability, available } = reading;
|
|
337
|
-
if (available === void 0 || availability === "unknown" || availability === "preorder") return;
|
|
338
|
-
if (availability === "out-of-stock" !== (available === 0)) context.addIssue({
|
|
339
|
-
code: "custom",
|
|
340
|
-
message: `The availability ${availability} does not agree with the count ${available}.`,
|
|
341
|
-
path: ["available"]
|
|
342
|
-
});
|
|
343
|
-
});
|
|
344
5
|
// src/terms.ts
|
|
345
6
|
/**
|
|
346
7
|
* This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the
|