@mark1russell7/market 0.0.0-bootstrap.0 → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mark Russell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
1
  # @mark1russell7/market
2
2
 
3
- This version is a placeholder. The release workflow of https://github.com/mark1russell7/market publishes the real versions. Use a later version.
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.
4
+
5
+ ```sh
6
+ pnpm add @mark1russell7/market
7
+ ```
8
+
9
+ The records come from the hand crawl ([`docs/HAND-CRAWL.md`](../../docs/HAND-CRAWL.md)). The fields are the common fields of the official APIs of the sellers.
10
+
11
+ ## The records
12
+
13
+ Each record has a `zod` schema. A schema refuses an unknown field, an empty text and a text with a space at an end. An adapter of a source gives records in their final form, and the schema examines them.
14
+
15
+ | Record | Schema | What it has |
16
+ | --- | --- | --- |
17
+ | Product | `productSchema` | An id of the catalog, a title, a brand, a category path, GTINs, part numbers and specifications as text. |
18
+ | Offer | `offerSchema` | One product at one seller: the source, the id at the source, the seller, the condition, the buying format and the identifiers that the source gives. |
19
+ | Price reading | `priceReadingSchema` | The state of one offer at one instant: the unit price, the list price, the shipping, the availability, the minimum quantity and the price breaks. |
20
+ | Terms of a source | `sourceTermsSchema` | The storage rule of the source, the deletion of ended offers, and the permission of a model of prices. |
21
+
22
+ - **Money.** An amount of money is a quantity of [`@mark1russell7/quantity`](https://www.npmjs.com/package/@mark1russell7/quantity), for example `{ "value": 64.99, "unit": "USD" }`. A price is zero or more.
23
+ - **Instants.** An instant is an ISO 8601 text in UTC, for example `2026-11-12T18:00:00Z`.
24
+ - **Ids.** The id of an offer is the name of its source, a colon and the id at the source: `offerId("ebay", "1234")` gives `ebay:1234`. A source name has small letters, digits and hyphens.
25
+ - **Conditions.** A source maps its own condition to `new`, `open-box`, `refurbished`, `used`, `for-parts` or `unknown`. The field `grade` keeps the text of the source, for example `excellent`.
26
+ - **Shipping.** The shipping is `free`, `fixed` with a cost, `calculated` (it depends on the address) or `unknown`.
27
+ - **Price breaks.** `price` is the unit price for an order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more than the minimum.
28
+ - **Stock.** A count of `available` units agrees with the availability: `out-of-stock` has the count 0, and `in-stock` and `low-stock` have a count of 1 or more.
29
+
30
+ ## The functions
31
+
32
+ - `parseGtin(text)` gives the GTIN-14 form of a GTIN-8, a UPC-A, an EAN-13 or a GTIN-14, or null. It examines the check digit, and it refuses a GTIN of zeros only.
33
+ - `matchKeys({ gtins, partNumbers })` gives the keys of a record. A key is `gtin:` with the GTIN-14, or `part:` with the folded brand and part number. Two records with a key in common name one product.
34
+ - `unitPriceFor(reading, count)` gives the unit price for an order of `count` units. `costOf(reading, count)` adds the shipping, or it gives null when the shipping cost is not known. The cost is exact and not rounded.
35
+ - `keepUntil(terms, reading)` gives the last instant at which a store keeps a reading, or null with no limit. `isKept(terms, reading, now, ended)` tells if a store keeps it at `now`.
36
+ - `permitsHistory(terms)` and `permitsTrend(terms)` tell if the terms of a source permit a stored history and a trend of its prices.
37
+
38
+ ## The offers of a part
39
+
40
+ An observation is one offer and its price reading at one instant. The parsers of `@mark1russell7/market-sources` give observations.
41
+
42
+ - `offersPart(offer, want)` tells if an offer is an offer of a part. A want has the names of the maker and the part numbers of the maker. One part number of the offer must have a brand of the want and start with a part number of the want, after the fold.
43
+ - `offersOfPart(observations, want)` gives the latest observation of each offer of the part. `latestObservations(observations)` does the same for each offer.
44
+ - `bestOffer(observations, { currency, count, conditions })` chooses the offer to buy. It skips an offer with another condition, another currency, or a minimum above the count. Each skipped offer has its reason. The offers go from the lowest price of the goods, then the lowest cost with the shipping. The best offer is the first offer in stock, or else the first offer.
45
+
46
+ The brand is necessary, because many makers use short part numbers. A search for the number of a power bank found a solder tip and a fan of other makers.
47
+
48
+ ```ts
49
+ import { bestOffer, offersOfPart, type PartWant } from "@mark1russell7/market";
50
+
51
+ const want: PartWant = { brands: ["Acme", "Acme Power Inc."], partNumbers: ["UPS-600X"] };
52
+ const chosen = bestOffer(offersOfPart(observations, want), { currency: "USD" });
53
+ chosen.best?.goods; // { value: 89.99, unit: "USD" }
54
+ chosen.skipped; // [{ offerId: "ebay:1234", why: "The condition used is not a condition that the buyer accepts." }]
55
+ ```
56
+
57
+ ## Example
58
+
59
+ ```ts
60
+ import { costOf, isKept, priceReadingSchema, type SourceTerms } from "@mark1russell7/market";
61
+
62
+ const reading = priceReadingSchema.parse({
63
+ offerId: "example:sku-1",
64
+ at: "2026-11-12T18:00:00Z",
65
+ price: { value: 0.1, unit: "USD" },
66
+ shipping: { kind: "fixed", cost: { value: 0.2, unit: "USD" } },
67
+ availability: "in-stock",
68
+ });
69
+ costOf(reading, 3); // { value: 0.5, unit: "USD" }
70
+
71
+ const terms: SourceTerms = {
72
+ source: "example",
73
+ retention: { kind: "max-age", age: { value: 72, unit: "h" } },
74
+ deleteWhenEnded: false,
75
+ priceModel: false,
76
+ clause: "a cache of 72 hours at most",
77
+ };
78
+ isKept(terms, reading, "2026-11-16T00:00:00Z"); // false
79
+ ```
80
+
81
+ ## Limits
82
+
83
+ - 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.
84
+ - 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.
85
+ - The money of the quantity package has one currency: the US dollar.
86
+ - The package has no history of prices yet. Roadmap item R5 adds it, after the owner chooses its source.
@@ -0,0 +1,289 @@
1
+ /**
2
+ * The records of the market: a product, an offer of a seller and a price reading, with their checks. The module
3
+ * also has the GTIN check, the match keys of a record, the cost of an order and the storage rules of a source.
4
+ * The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants.
5
+ */
6
+ import { Quantity } from "@mark1russell7/quantity";
7
+ import { z } from "zod";
8
+ /**
9
+ * This function gives the check digit of the digits of a GTIN without its last digit.
10
+ *
11
+ * @throws RangeError when the text has a character that is not a digit, or no character.
12
+ */
13
+ export declare function gtinCheckDigit(body: string): number;
14
+ /**
15
+ * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
16
+ * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
17
+ */
18
+ export declare function parseGtin(text: string): string | null;
19
+ /** A part number of a maker: the brand, and the number that the maker gives to the part. */
20
+ interface PartNumber {
21
+ readonly brand: string;
22
+ readonly partNumber: string;
23
+ }
24
+ /** The identifiers of a product or of an offer. */
25
+ interface Identifiers {
26
+ readonly gtins: readonly string[];
27
+ readonly partNumbers: readonly PartNumber[];
28
+ }
29
+ /**
30
+ * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z
31
+ * and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.
32
+ */
33
+ export declare function foldCode(text: string): string;
34
+ /**
35
+ * This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,
36
+ * or `part:` with the folded brand and part number. Two records with a key in common name one product.
37
+ * The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.
38
+ */
39
+ export declare function matchKeys(identifiers: Identifiers): string[];
40
+ /**
41
+ * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
42
+ * the field `grade` of the offer.
43
+ */
44
+ export declare const CONDITIONS: readonly ["new", "open-box", "refurbished", "used", "for-parts", "unknown"];
45
+ /** The condition of an offer. */
46
+ type Condition = (typeof CONDITIONS)[number];
47
+ /** The states of the stock of an offer at the time of a reading. */
48
+ export declare const AVAILABILITIES: readonly ["in-stock", "low-stock", "out-of-stock", "preorder", "unknown"];
49
+ /** The state of the stock of an offer. */
50
+ type Availability = (typeof AVAILABILITIES)[number];
51
+ /** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
52
+ export declare const FORMATS: readonly ["fixed-price", "auction"];
53
+ /** The buying format of an offer. */
54
+ type Format = (typeof FORMATS)[number];
55
+ /** One specification of a product as text. */
56
+ interface Spec {
57
+ readonly name: string;
58
+ readonly value: string;
59
+ }
60
+ /** The feedback of a seller: the percent of good feedback, and the count of the feedback. */
61
+ interface Rating {
62
+ readonly percent: number;
63
+ readonly count: number;
64
+ }
65
+ /** A seller of an offer. A source gives some of these fields, or none. */
66
+ interface Seller {
67
+ readonly id?: string | undefined;
68
+ readonly name?: string | undefined;
69
+ readonly rating?: Rating | undefined;
70
+ }
71
+ /** A product of the catalog: one thing that a person can buy, with its identifiers and its specifications. */
72
+ interface Product {
73
+ readonly id: string;
74
+ readonly title: string;
75
+ readonly brand?: string | undefined;
76
+ readonly category?: readonly string[] | undefined;
77
+ readonly gtins: readonly string[];
78
+ readonly partNumbers: readonly PartNumber[];
79
+ readonly specs: readonly Spec[];
80
+ }
81
+ /** An offer of a seller: one product at one seller, with the identifiers that the source gives. */
82
+ interface Offer {
83
+ readonly id: string;
84
+ readonly source: string;
85
+ readonly sourceId: string;
86
+ readonly productId?: string | undefined;
87
+ readonly title: string;
88
+ readonly url?: string | undefined;
89
+ readonly seller: Seller;
90
+ readonly condition: Condition;
91
+ readonly grade?: string | undefined;
92
+ readonly format: Format;
93
+ readonly endsAt?: string | undefined;
94
+ readonly gtins: readonly string[];
95
+ readonly partNumbers: readonly PartNumber[];
96
+ readonly specs: readonly Spec[];
97
+ }
98
+ /** The shipping of a reading. A calculated cost depends on the address of the buyer. */
99
+ type Shipping = {
100
+ readonly kind: "free";
101
+ } | {
102
+ readonly kind: "fixed";
103
+ readonly cost: Quantity;
104
+ } | {
105
+ readonly kind: "calculated";
106
+ } | {
107
+ readonly kind: "unknown";
108
+ };
109
+ /** A price break of a reading: the unit price for an order of `quantity` units or more. */
110
+ interface PriceBreak {
111
+ readonly quantity: number;
112
+ readonly unitPrice: Quantity;
113
+ }
114
+ /** A price reading: the state of one offer at one instant. */
115
+ interface PriceReading {
116
+ readonly offerId: string;
117
+ readonly at: string;
118
+ readonly price: Quantity;
119
+ readonly listPrice?: Quantity | undefined;
120
+ readonly shipping: Shipping;
121
+ readonly availability: Availability;
122
+ readonly available?: number | undefined;
123
+ readonly minimumQuantity?: number | undefined;
124
+ readonly priceBreaks?: readonly PriceBreak[] | undefined;
125
+ }
126
+ /** This schema accepts a text with a character that is not a space, and with no space at an end. */
127
+ export declare const textSchema: z.ZodType<string>;
128
+ /** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
129
+ export declare const sourceSchema: z.ZodType<string>;
130
+ /** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
131
+ export declare const gtinSchema: z.ZodType<string>;
132
+ /** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
133
+ export declare const moneySchema: z.ZodType<Quantity, Quantity>;
134
+ /** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
135
+ export declare const instantSchema: z.ZodType<string>;
136
+ /** This schema accepts a part number of a maker. */
137
+ export declare const partNumberSchema: z.ZodType<PartNumber>;
138
+ /** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
139
+ export declare const specSchema: z.ZodType<Spec>;
140
+ /** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
141
+ export declare const sellerSchema: z.ZodType<Seller>;
142
+ /** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
143
+ export declare const productSchema: z.ZodType<Product>;
144
+ /** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
145
+ export declare function offerId(source: string, sourceId: string): string;
146
+ /** This function gives the name of the source of an offer id: the text before the first colon. */
147
+ export declare function sourceOfOffer(id: string): string;
148
+ /**
149
+ * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
150
+ * `productId` names the product of the catalog after a match.
151
+ */
152
+ export declare const offerSchema: z.ZodType<Offer>;
153
+ /** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
154
+ export declare const shippingSchema: z.ZodType<Shipping>;
155
+ /** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
156
+ export declare const priceBreakSchema: z.ZodType<PriceBreak>;
157
+ /**
158
+ * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
159
+ * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
160
+ * than the minimum.
161
+ */
162
+ export declare const priceReadingSchema: z.ZodType<PriceReading>;
163
+ /** One offer of a source, and its price reading at one instant. */
164
+ interface Observation {
165
+ readonly offer: Offer;
166
+ readonly reading: PriceReading;
167
+ }
168
+ /**
169
+ * This record names a part that a buyer wants: the names of its maker, and its part numbers. A seller can write
170
+ * the brand of one maker in more than one form, so the want has a list of names.
171
+ */
172
+ interface PartWant {
173
+ /** The names of the maker, as the sellers write the brand. */
174
+ readonly brands: readonly string[];
175
+ /** The part numbers of the maker. A part number of an offer matches when it starts with one of them, after the fold. */
176
+ readonly partNumbers: readonly string[];
177
+ }
178
+ /**
179
+ * This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the
180
+ * want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number
181
+ * of another maker does not match: many makers use short numbers like `A1383`.
182
+ */
183
+ export declare function offersPart(offer: Pick<Offer, "partNumbers">, want: PartWant): boolean;
184
+ /**
185
+ * This function gives the latest observation of each offer, in the order of the offer ids. When two readings of
186
+ * one offer have the same instant, the later one in the list applies.
187
+ */
188
+ export declare function latestObservations(observations: readonly Observation[]): Observation[];
189
+ /** This function gives the latest observation of each offer of the part, in the order of the offer ids. */
190
+ export declare function offersOfPart(observations: readonly Observation[], want: PartWant): Observation[];
191
+ /** This record is one offer that a buyer can choose, with the price of an order in the currency of the buyer. */
192
+ interface OfferChoice {
193
+ readonly observation: Observation;
194
+ /** The unit price for the count, times the count. */
195
+ readonly goods: Quantity;
196
+ /** The goods and the shipping, or null when the shipping cost is not known. */
197
+ readonly cost: Quantity | null;
198
+ /** True when the availability is `in-stock` or `low-stock`. */
199
+ readonly inStock: boolean;
200
+ }
201
+ /** These options change the choice of an offer. */
202
+ interface BestOfferOptions {
203
+ /** 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. */
204
+ readonly currency: string;
205
+ /** The count of units of the order. The default is 1. */
206
+ readonly count?: number;
207
+ /** The conditions that the buyer accepts. The default is `new` only. */
208
+ readonly conditions?: readonly Condition[];
209
+ }
210
+ /** This record is the choice of an offer: the best offer, each offer in the order of the price, and each skipped offer. */
211
+ interface BestOffer {
212
+ /** The offer with the lowest price that is in stock, or else the offer with the lowest price, or null with no offer. */
213
+ readonly best: OfferChoice | null;
214
+ /** The offers, from the lowest price of the goods. Equal prices go in the order of the cost, then of the offer id. */
215
+ readonly offers: readonly OfferChoice[];
216
+ /** The offers that the choice skipped, each with the reason. */
217
+ readonly skipped: readonly {
218
+ readonly offerId: string;
219
+ readonly why: string;
220
+ }[];
221
+ }
222
+ /**
223
+ * This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a
224
+ * condition that the buyer does not accept, a price in another currency, or a minimum above the count.
225
+ *
226
+ * @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.
227
+ */
228
+ export declare function bestOffer(observations: readonly Observation[], options: BestOfferOptions): BestOffer;
229
+ /**
230
+ * This function gives the unit price for an order of `count` units. The price of the largest break at or
231
+ * below the count applies, or the price of the reading when no break applies.
232
+ *
233
+ * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
234
+ */
235
+ export declare function unitPriceFor(reading: PriceReading, count: number): Quantity;
236
+ /**
237
+ * This function gives the cost of an order of `count` units with its shipping, or null when the shipping
238
+ * cost is not known. The cost is exact, and the function does not round it to the cent.
239
+ *
240
+ * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
241
+ */
242
+ export declare function costOf(reading: PriceReading, count: number): Quantity | null;
243
+ /** The storage rule of a source, from its terms. */
244
+ type Retention = {
245
+ readonly kind: "keep";
246
+ } | {
247
+ readonly kind: "max-age";
248
+ readonly age: Quantity;
249
+ } | {
250
+ readonly kind: "no-store";
251
+ };
252
+ /** The rules of the terms of one source. */
253
+ interface SourceTerms {
254
+ readonly source: string;
255
+ readonly retention: Retention;
256
+ readonly deleteWhenEnded: boolean;
257
+ readonly priceModel: boolean;
258
+ readonly clause: string;
259
+ }
260
+ /**
261
+ * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the
262
+ * time. With `max-age`, a store keeps a reading for `age` at most. With `no-store`, a reading serves one request.
263
+ */
264
+ export declare const retentionSchema: z.ZodType<Retention>;
265
+ /**
266
+ * This schema accepts the rules of the terms of one source. `deleteWhenEnded` deletes the readings of an offer
267
+ * when the offer ends. `priceModel` permits a trend or a forecast of prices. `clause` names the text of the terms.
268
+ */
269
+ export declare const sourceTermsSchema: z.ZodType<SourceTerms>;
270
+ /**
271
+ * This function gives the last instant at which a store keeps a reading, or null when the terms set no
272
+ * limit. For a source with `no-store`, the instant is the instant of the reading.
273
+ */
274
+ export declare function keepUntil(terms: SourceTerms, reading: {
275
+ readonly at: string;
276
+ }): string | null;
277
+ /**
278
+ * This function tells if a store keeps a reading at the instant `now`. A store keeps no reading of a source with
279
+ * `no-store`, and no reading of an ended offer when the terms delete them.
280
+ */
281
+ export declare function isKept(terms: SourceTerms, reading: {
282
+ readonly at: string;
283
+ }, now: string, ended?: boolean): boolean;
284
+ /** This function tells if the terms permit a stored history of the readings of a source. */
285
+ export declare function permitsHistory(terms: SourceTerms): boolean;
286
+ /** This function tells if the terms permit a trend of the prices of a source: a history and a model of prices. */
287
+ export declare function permitsTrend(terms: SourceTerms): boolean;
288
+ export type { Availability, BestOffer, BestOfferOptions, Condition, Format, Identifiers, Observation, Offer, OfferChoice, PartNumber, PartWant, PriceBreak, PriceReading, Product, Rating, Retention, Seller, Shipping, SourceTerms, Spec };
289
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/gtin.ts","../src/identifiers.ts","../src/records.ts","../src/offers.ts","../src/price.ts","../src/terms.ts"],"mappings":";;;;;;;;;;;;wBAYgB,eAAe;;;;;wBAcf,UAAU;;UCvBT;WACN;WACA;;;UAIM;WACN;WACA,sBAAsB;;;;;;wBAOjB,SAAS;;;;;;wBAST,UAAU,aAAa;;;;;qBCjB1B;;KAED,oBAAoB;;qBAGnB;;KAED,uBAAuB;;qBAGtB;;KAED,iBAAiB;;UAGZ;WACN;WACA;;;UAIM;WACN;WACA;;;UAIM;WACN;WACA;WACA,SAAS;;;UAIH;WACN;WACA;WACA;WACA;WACA;WACA,sBAAsB;WACtB,gBAAgB;;;UAIV;WACN;WACA;WACA;WACA;WACA;WACA;WACA,QAAQ;WACR,WAAW;WACX;WACA,QAAQ;WACR;WACA;WACA,sBAAsB;WACtB,gBAAgB;;;KAIf;WACG;;WACA;WAAwB,MAAM;;WAC9B;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Ac,aAAa;;wBAW1E,eAAe,OAAO;;wBAKtB,aAAa,OAAO"}
package/build/index.js ADDED
@@ -0,0 +1,403 @@
1
+ import { UnitError, add, compare, convert, convertible, kindOf, scale, valueIn } from "@mark1russell7/quantity";
2
+ import { quantitySchema } from "@mark1russell7/quantity/schema";
3
+ 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
+ // src/terms.ts
345
+ /**
346
+ * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the
347
+ * time. With `max-age`, a store keeps a reading for `age` at most. With `no-store`, a reading serves one request.
348
+ */
349
+ const retentionSchema = z.discriminatedUnion("kind", [
350
+ z.strictObject({ kind: z.literal("keep") }),
351
+ z.strictObject({
352
+ kind: z.literal("max-age"),
353
+ age: quantitySchema("time", { positive: true })
354
+ }),
355
+ z.strictObject({ kind: z.literal("no-store") })
356
+ ]);
357
+ /**
358
+ * This schema accepts the rules of the terms of one source. `deleteWhenEnded` deletes the readings of an offer
359
+ * when the offer ends. `priceModel` permits a trend or a forecast of prices. `clause` names the text of the terms.
360
+ */
361
+ const sourceTermsSchema = z.strictObject({
362
+ source: sourceSchema,
363
+ retention: retentionSchema,
364
+ deleteWhenEnded: z.boolean(),
365
+ priceModel: z.boolean(),
366
+ clause: textSchema
367
+ });
368
+ /**
369
+ * This function gives the last instant at which a store keeps a reading, or null when the terms set no
370
+ * limit. For a source with `no-store`, the instant is the instant of the reading.
371
+ */
372
+ function keepUntil(terms, reading) {
373
+ const { retention } = terms;
374
+ if (retention.kind === "keep") return null;
375
+ const at = Date.parse(reading.at);
376
+ if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(reading.at)} is not an instant.`);
377
+ if (retention.kind === "no-store") return new Date(at).toISOString();
378
+ return new Date(at + Math.floor(valueIn(retention.age, "ms"))).toISOString();
379
+ }
380
+ /**
381
+ * This function tells if a store keeps a reading at the instant `now`. A store keeps no reading of a source with
382
+ * `no-store`, and no reading of an ended offer when the terms delete them.
383
+ */
384
+ function isKept(terms, reading, now, ended = false) {
385
+ if (ended && terms.deleteWhenEnded) return false;
386
+ if (terms.retention.kind === "no-store") return false;
387
+ const until = keepUntil(terms, reading);
388
+ if (until === null) return true;
389
+ const instant = Date.parse(now);
390
+ if (Number.isNaN(instant)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);
391
+ return instant <= Date.parse(until);
392
+ }
393
+ /** This function tells if the terms permit a stored history of the readings of a source. */
394
+ function permitsHistory(terms) {
395
+ return terms.retention.kind === "keep" && !terms.deleteWhenEnded;
396
+ }
397
+ /** This function tells if the terms permit a trend of the prices of a source: a history and a model of prices. */
398
+ function permitsTrend(terms) {
399
+ return permitsHistory(terms) && terms.priceModel;
400
+ }
401
+ export { AVAILABILITIES, CONDITIONS, FORMATS, bestOffer, costOf, foldCode, gtinCheckDigit, gtinSchema, instantSchema, isKept, keepUntil, latestObservations, matchKeys, moneySchema, offerId, offerSchema, offersOfPart, offersPart, parseGtin, partNumberSchema, permitsHistory, permitsTrend, priceBreakSchema, priceReadingSchema, productSchema, retentionSchema, sellerSchema, shippingSchema, sourceOfOffer, sourceSchema, sourceTermsSchema, specSchema, textSchema, unitPriceFor };
402
+
403
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/gtin.ts","../src/identifiers.ts","../src/price.ts","../src/offers.ts","../src/records.ts","../src/terms.ts"],"sourcesContent":["/**\n * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.\n * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.\n */\n\nconst LENGTHS: ReadonlySet<number> = new Set([8, 12, 13, 14]);\n\n/**\n * This function gives the check digit of the digits of a GTIN without its last digit.\n *\n * @throws RangeError when the text has a character that is not a digit, or no character.\n */\nexport function gtinCheckDigit(body: string): number {\n if (!/^\\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);\n let total = 0;\n for (let i = 0; i < body.length; i += 1) {\n const digit = body.charCodeAt(body.length - 1 - i) - 48;\n total += i % 2 === 0 ? digit * 3 : digit;\n }\n return (10 - (total % 10)) % 10;\n}\n\n/**\n * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.\n * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.\n */\nexport function parseGtin(text: string): string | null {\n const digits = text.replace(/[\\s-]/g, \"\");\n if (!/^\\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;\n if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;\n return digits.padStart(14, \"0\");\n}\n","import { parseGtin } from \"./gtin.ts\";\n\n/** A part number of a maker: the brand, and the number that the maker gives to the part. */\nexport interface PartNumber {\n readonly brand: string;\n readonly partNumber: string;\n}\n\n/** The identifiers of a product or of an offer. */\nexport interface Identifiers {\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n}\n\n/**\n * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z\n * and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.\n */\nexport function foldCode(text: string): string {\n return text.normalize(\"NFKD\").toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n}\n\n/**\n * This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,\n * or `part:` with the folded brand and part number. Two records with a key in common name one product.\n * The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.\n */\nexport function matchKeys(identifiers: Identifiers): string[] {\n const keys = new Set<string>();\n for (const text of identifiers.gtins) {\n const gtin = parseGtin(text);\n if (gtin !== null) keys.add(`gtin:${gtin}`);\n }\n for (const { brand, partNumber } of identifiers.partNumbers) {\n const folded = [foldCode(brand), foldCode(partNumber)];\n if (folded.every((part) => part !== \"\")) keys.add(`part:${folded.join(\"/\")}`);\n }\n return [...keys].sort();\n}\n","import { add, scale, type Quantity } from \"@mark1russell7/quantity\";\nimport type { PriceReading } from \"./records.ts\";\n\n/**\n * This function gives the unit price for an order of `count` units. The price of the largest break at or\n * below the count applies, or the price of the reading when no break applies.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function unitPriceFor(reading: PriceReading, count: number): Quantity {\n const minimum = reading.minimumQuantity ?? 1;\n if (!Number.isSafeInteger(count) || count < minimum) {\n throw new RangeError(`The count ${count} is not a whole number of ${minimum} or more.`);\n }\n let price: Quantity = reading.price;\n for (const entry of reading.priceBreaks ?? []) if (entry.quantity <= count) price = entry.unitPrice;\n return price;\n}\n\n/**\n * This function gives the cost of an order of `count` units with its shipping, or null when the shipping\n * cost is not known. The cost is exact, and the function does not round it to the cent.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function costOf(reading: PriceReading, count: number): Quantity | null {\n const goods = scale(unitPriceFor(reading, count), count);\n switch (reading.shipping.kind) {\n case \"free\":\n return goods;\n case \"fixed\":\n return add(goods, reading.shipping.cost);\n default:\n return null;\n }\n}\n","import { compare, convert, convertible, kindOf, scale, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { foldCode } from \"./identifiers.ts\";\nimport { costOf, unitPriceFor } from \"./price.ts\";\nimport type { Condition, Offer, PriceReading } from \"./records.ts\";\n\n/** One offer of a source, and its price reading at one instant. */\nexport interface Observation {\n readonly offer: Offer;\n readonly reading: PriceReading;\n}\n\n/**\n * This record names a part that a buyer wants: the names of its maker, and its part numbers. A seller can write\n * the brand of one maker in more than one form, so the want has a list of names.\n */\nexport interface PartWant {\n /** The names of the maker, as the sellers write the brand. */\n readonly brands: readonly string[];\n /** The part numbers of the maker. A part number of an offer matches when it starts with one of them, after the fold. */\n readonly partNumbers: readonly string[];\n}\n\n/**\n * This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the\n * want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number\n * of another maker does not match: many makers use short numbers like `A1383`.\n */\nexport function offersPart(offer: Pick<Offer, \"partNumbers\">, want: PartWant): boolean {\n const brands = new Set(want.brands.map(foldCode).filter((brand) => brand !== \"\"));\n const parts = want.partNumbers.map(foldCode).filter((part) => part !== \"\");\n return offer.partNumbers.some(({ brand, partNumber }) => {\n const folded = foldCode(partNumber);\n return brands.has(foldCode(brand)) && parts.some((part) => folded.startsWith(part));\n });\n}\n\n/**\n * This function gives the latest observation of each offer, in the order of the offer ids. When two readings of\n * one offer have the same instant, the later one in the list applies.\n */\nexport function latestObservations(observations: readonly Observation[]): Observation[] {\n const latest = new Map<string, Observation>();\n for (const each of observations) {\n const seen = latest.get(each.offer.id);\n if (seen === undefined || Date.parse(seen.reading.at) <= Date.parse(each.reading.at)) latest.set(each.offer.id, each);\n }\n return [...latest.values()].sort((a, b) => order(a.offer.id, b.offer.id));\n}\n\n/** This function gives the latest observation of each offer of the part, in the order of the offer ids. */\nexport function offersOfPart(observations: readonly Observation[], want: PartWant): Observation[] {\n return latestObservations(observations.filter((each) => offersPart(each.offer, want)));\n}\n\n/** This record is one offer that a buyer can choose, with the price of an order in the currency of the buyer. */\nexport interface OfferChoice {\n readonly observation: Observation;\n /** The unit price for the count, times the count. */\n readonly goods: Quantity;\n /** The goods and the shipping, or null when the shipping cost is not known. */\n readonly cost: Quantity | null;\n /** True when the availability is `in-stock` or `low-stock`. */\n readonly inStock: boolean;\n}\n\n/** These options change the choice of an offer. */\nexport interface BestOfferOptions {\n /** 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. */\n readonly currency: string;\n /** The count of units of the order. The default is 1. */\n readonly count?: number;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[];\n}\n\n/** This record is the choice of an offer: the best offer, each offer in the order of the price, and each skipped offer. */\nexport interface BestOffer {\n /** The offer with the lowest price that is in stock, or else the offer with the lowest price, or null with no offer. */\n readonly best: OfferChoice | null;\n /** The offers, from the lowest price of the goods. Equal prices go in the order of the cost, then of the offer id. */\n readonly offers: readonly OfferChoice[];\n /** The offers that the choice skipped, each with the reason. */\n readonly skipped: readonly { readonly offerId: string; readonly why: string }[];\n}\n\n/**\n * This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a\n * condition that the buyer does not accept, a price in another currency, or a minimum above the count.\n *\n * @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.\n */\nexport function bestOffer(observations: readonly Observation[], options: BestOfferOptions): BestOffer {\n const { currency, count = 1, conditions = [\"new\"] } = options;\n if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The count ${count} is not a whole number of 1 or more.`);\n if (!isMoney(currency)) throw new RangeError(`The currency ${currency} is not a unit of money of @mark1russell7/quantity.`);\n const accepted = new Set<Condition>(conditions);\n const offers: OfferChoice[] = [];\n const skipped: { offerId: string; why: string }[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const minimum = reading.minimumQuantity ?? 1;\n if (!accepted.has(offer.condition)) skipped.push({ offerId: offer.id, why: `The condition ${offer.condition} is not a condition that the buyer accepts.` });\n else if (!converts(reading.price.unit, currency)) skipped.push({ offerId: offer.id, why: `The price is in ${reading.price.unit}, not in ${currency}.` });\n else if (count < minimum) skipped.push({ offerId: offer.id, why: `The minimum order is ${minimum} units, more than the count ${count}.` });\n else {\n const goods = convert(scale(unitPriceFor(reading, count), count), currency);\n // A shipping cost in another currency is not known in the currency of the buyer.\n const shipping = reading.shipping.kind !== \"fixed\" || converts(reading.shipping.cost.unit, currency);\n const total = shipping ? costOf(reading, count) : null;\n const cost = total === null ? null : convert(total, currency);\n const inStock = reading.availability === \"in-stock\" || reading.availability === \"low-stock\";\n offers.push({ observation, goods, cost, inStock });\n }\n }\n offers.sort((a, b) => compare(a.goods, b.goods) || byCost(a.cost, b.cost) || order(a.observation.offer.id, b.observation.offer.id));\n const best = offers.find((choice) => choice.inStock) ?? offers[0] ?? null;\n return { best, offers, skipped };\n}\n\n/** This function tells if a unit is a unit of money that the quantity package knows. */\nfunction isMoney(unit: string): boolean {\n try {\n return kindOf(unit) === \"money\";\n } catch (error) {\n if (error instanceof UnitError) return false;\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 orders two costs. A known cost comes before a cost that is not known. */\nfunction byCost(a: Quantity | null, b: Quantity | null): number {\n if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;\n return compare(a, b);\n}\n\n/** This function orders two texts by their code units, so the order does not depend on the locale. */\nfunction order(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { parseGtin } from \"./gtin.ts\";\nimport type { PartNumber } from \"./identifiers.ts\";\n\n/**\n * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in\n * the field `grade` of the offer.\n */\nexport const CONDITIONS = [\"new\", \"open-box\", \"refurbished\", \"used\", \"for-parts\", \"unknown\"] as const;\n/** The condition of an offer. */\nexport type Condition = (typeof CONDITIONS)[number];\n\n/** The states of the stock of an offer at the time of a reading. */\nexport const AVAILABILITIES = [\"in-stock\", \"low-stock\", \"out-of-stock\", \"preorder\", \"unknown\"] as const;\n/** The state of the stock of an offer. */\nexport type Availability = (typeof AVAILABILITIES)[number];\n\n/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */\nexport const FORMATS = [\"fixed-price\", \"auction\"] as const;\n/** The buying format of an offer. */\nexport type Format = (typeof FORMATS)[number];\n\n/** One specification of a product as text. */\nexport interface Spec {\n readonly name: string;\n readonly value: string;\n}\n\n/** The feedback of a seller: the percent of good feedback, and the count of the feedback. */\nexport interface Rating {\n readonly percent: number;\n readonly count: number;\n}\n\n/** A seller of an offer. A source gives some of these fields, or none. */\nexport interface Seller {\n readonly id?: string | undefined;\n readonly name?: string | undefined;\n readonly rating?: Rating | undefined;\n}\n\n/** A product of the catalog: one thing that a person can buy, with its identifiers and its specifications. */\nexport interface Product {\n readonly id: string;\n readonly title: string;\n readonly brand?: string | undefined;\n readonly category?: readonly string[] | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** An offer of a seller: one product at one seller, with the identifiers that the source gives. */\nexport interface Offer {\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 seller: Seller;\n readonly condition: Condition;\n readonly grade?: string | undefined;\n readonly format: Format;\n readonly endsAt?: string | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** The shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport type Shipping =\n | { readonly kind: \"free\" }\n | { readonly kind: \"fixed\"; readonly cost: Quantity }\n | { readonly kind: \"calculated\" }\n | { readonly kind: \"unknown\" };\n\n/** A price break of a reading: the unit price for an order of `quantity` units or more. */\nexport interface PriceBreak {\n readonly quantity: number;\n readonly unitPrice: Quantity;\n}\n\n/** A price reading: the state of one offer at one instant. */\nexport interface PriceReading {\n readonly offerId: string;\n readonly at: string;\n readonly price: Quantity;\n readonly listPrice?: Quantity | undefined;\n readonly shipping: Shipping;\n readonly availability: Availability;\n readonly available?: number | undefined;\n readonly minimumQuantity?: number | undefined;\n readonly priceBreaks?: readonly PriceBreak[] | undefined;\n}\n\n/** This schema accepts a text with a character that is not a space, and with no space at an end. */\nexport const textSchema: z.ZodType<string> = z\n .string()\n .refine((text) => text !== \"\" && text === text.trim(), \"The text is empty, or it has a space at an end.\");\n\n/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */\nexport const sourceSchema: z.ZodType<string> = z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/, \"The name of a source has small letters, digits and hyphens, with a letter first.\");\n\n/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */\nexport const gtinSchema: z.ZodType<string> = z\n .string()\n .refine((text) => /^\\d{14}$/.test(text) && parseGtin(text) === text, \"The GTIN is not a GTIN-14 with a correct check digit.\");\n\n/** This schema accepts an amount of money of zero or more, for example `{ \"value\": 129.99, \"unit\": \"USD\" }`. */\nexport const moneySchema: z.ZodType<Quantity, Quantity> = quantitySchema(\"money\", { nonnegative: true });\n\n/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */\nexport const instantSchema: z.ZodType<string> = z.iso.datetime();\n\n/** This schema accepts a part number of a maker. */\nexport const partNumberSchema: z.ZodType<PartNumber> = z.strictObject({ brand: textSchema, partNumber: textSchema });\n\n/** This schema accepts one specification as text, for example `{ \"name\": \"Capacity\", \"value\": \"1 TB\" }`. */\nexport const specSchema: z.ZodType<Spec> = z.strictObject({ name: textSchema, value: textSchema });\n\n/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */\nexport const sellerSchema: z.ZodType<Seller> = z.strictObject({\n id: textSchema.optional(),\n name: textSchema.optional(),\n rating: z.strictObject({ percent: z.number().min(0).max(100), count: z.int().nonnegative() }).optional(),\n});\n\n/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */\nexport const productSchema: z.ZodType<Product> = z.strictObject({\n id: textSchema,\n title: textSchema,\n brand: textSchema.optional(),\n category: z.array(textSchema).optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n});\n\n/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */\nexport function offerId(source: string, sourceId: string): string {\n return `${source}:${sourceId}`;\n}\n\n/** This function gives the name of the source of an offer id: the text before the first colon. */\nexport function sourceOfOffer(id: string): string {\n const colon = id.indexOf(\":\");\n if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);\n return id.slice(0, colon);\n}\n\n/**\n * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.\n * `productId` names the product of the catalog after a match.\n */\nexport const offerSchema: z.ZodType<Offer> = 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 seller: sellerSchema,\n condition: z.enum(CONDITIONS),\n grade: textSchema.optional(),\n format: z.enum(FORMATS),\n endsAt: instantSchema.optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\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/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport const shippingSchema: z.ZodType<Shipping> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"free\") }),\n z.strictObject({ kind: z.literal(\"fixed\"), cost: moneySchema }),\n z.strictObject({ kind: z.literal(\"calculated\") }),\n z.strictObject({ kind: z.literal(\"unknown\") }),\n]);\n\n/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */\nexport const priceBreakSchema: z.ZodType<PriceBreak> = z.strictObject({ quantity: z.int().min(2), unitPrice: moneySchema });\n\n/**\n * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an\n * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more\n * than the minimum.\n */\nexport const priceReadingSchema: z.ZodType<PriceReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n price: moneySchema,\n listPrice: moneySchema.optional(),\n shipping: shippingSchema,\n availability: z.enum(AVAILABILITIES),\n available: z.int().nonnegative().optional(),\n minimumQuantity: z.int().min(1).optional(),\n priceBreaks: z.array(priceBreakSchema).optional(),\n })\n .superRefine((reading, context) => {\n let last = reading.minimumQuantity ?? 1;\n for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {\n if (entry.quantity <= last) {\n context.addIssue({\n code: \"custom\",\n message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,\n path: [\"priceBreaks\", index, \"quantity\"],\n });\n }\n last = Math.max(last, entry.quantity);\n }\n const { availability, available } = reading;\n if (available === undefined || availability === \"unknown\" || availability === \"preorder\") return;\n if ((availability === \"out-of-stock\") !== (available === 0)) {\n context.addIssue({\n code: \"custom\",\n message: `The availability ${availability} does not agree with the count ${available}.`,\n path: [\"available\"],\n });\n }\n });\n","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"],"mappings":";;;;;;;;AAKA,MAAM,0BAA+B,IAAI,IAAI;CAAC;CAAG;CAAI;CAAI;AAAE,CAAC;;;;;;AAO5D,SAAgB,eAAe,MAAsB;CACnD,IAAI,CAAC,QAAQ,KAAK,IAAI,GAAG,MAAM,IAAI,WAAW,YAAY,KAAK,UAAU,IAAI,EAAE,4BAA4B;CAC3G,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,MAAM,QAAQ,KAAK,WAAW,KAAK,SAAS,IAAI,CAAC,IAAI;EACrD,SAAS,IAAI,MAAM,IAAI,QAAQ,IAAI;CACrC;CACA,QAAQ,KAAM,QAAQ,MAAO;AAC/B;;;;;AAMA,SAAgB,UAAU,MAA6B;CACrD,MAAM,SAAS,KAAK,QAAQ,UAAU,EAAE;CACxC,IAAI,CAAC,QAAQ,KAAK,MAAM,KAAK,CAAC,QAAQ,IAAI,OAAO,MAAM,KAAK,OAAO,KAAK,MAAM,GAAG,OAAO;CACxF,IAAI,eAAe,OAAO,MAAM,GAAG,EAAE,CAAC,MAAM,OAAO,OAAO,MAAM,EAAE,CAAC,GAAG,OAAO;CAC7E,OAAO,OAAO,SAAS,IAAI,GAAG;AAChC;;;;;;ACbA,SAAgB,SAAS,MAAsB;CAC7C,O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AAM,KAAK;AACpC;;AAGA,SAAgB,eAAe,OAA6B;CAC1D,OAAO,MAAM,UAAU,SAAS,UAAU,CAAC,MAAM;AACnD;;AAGA,SAAgB,aAAa,OAA6B;CACxD,OAAO,eAAe,KAAK,KAAK,MAAM;AACxC"}
package/package.json CHANGED
@@ -1,13 +1,64 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@mark1russell7/market",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "A placeholder that lets npm trust the release workflow of mark1russell7/market. Use a later version.",
4
+ "version": "0.1.1",
5
+ "description": "The records of a market: a product, an offer of a seller and a price reading, with their checks, the GTIN check, match keys, the cost of an order, the storage rules of a source, and the best offer of a part.",
6
+ "license": "MIT",
5
7
  "repository": {
6
8
  "type": "git",
7
- "url": "git+https://github.com/mark1russell7/market.git"
9
+ "url": "git+https://github.com/mark1russell7/market.git",
10
+ "directory": "packages/market"
11
+ },
12
+ "homepage": "https://github.com/mark1russell7/market/tree/main/packages/market#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/mark1russell7/market/issues"
15
+ },
16
+ "keywords": [
17
+ "market",
18
+ "prices",
19
+ "offers",
20
+ "price-history",
21
+ "products",
22
+ "catalog",
23
+ "parts"
24
+ ],
25
+ "type": "module",
26
+ "main": "./build/index.js",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./build/index.d.ts",
30
+ "import": "./build/index.js",
31
+ "default": "./build/index.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "build"
37
+ ],
38
+ "dependencies": {
39
+ "@mark1russell7/quantity": "^0.4.0",
40
+ "zod": "^4.6.7"
41
+ },
42
+ "devDependencies": {
43
+ "@mark1russell7/cue": "^2.0.0",
44
+ "@types/node": "^26.6.5",
45
+ "@vitest/coverage-v8": "^5.0.3",
46
+ "fast-check": "^4.10.2",
47
+ "tsdown": "^0.23.1",
48
+ "typescript": "^7.0.2",
49
+ "vitest": "^5.0.3"
50
+ },
51
+ "engines": {
52
+ "node": ">=22"
8
53
  },
9
- "license": "MIT",
10
54
  "publishConfig": {
11
55
  "access": "public"
12
- }
13
- }
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "test": "vitest run",
60
+ "test:watch": "vitest",
61
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
62
+ },
63
+ "types": "./build/index.d.ts"
64
+ }