bcv-today 0.0.0-stage → 1.0.0

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/dist/index.cjs ADDED
@@ -0,0 +1,874 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
7
+ // src/errors.ts
8
+ var BCVError = class extends Error {
9
+ constructor(message, options) {
10
+ super(message);
11
+ // Explicit names survive bundlers that rename classes.
12
+ __publicField(this, "name", "BCVError");
13
+ if (options && "cause" in options) {
14
+ Object.defineProperty(this, "cause", { value: options.cause, writable: true, configurable: true });
15
+ }
16
+ }
17
+ };
18
+ var InvalidArgument = class extends BCVError {
19
+ constructor() {
20
+ super(...arguments);
21
+ __publicField(this, "name", "InvalidArgument");
22
+ }
23
+ };
24
+ var InvalidDate = class extends InvalidArgument {
25
+ constructor() {
26
+ super(...arguments);
27
+ __publicField(this, "name", "InvalidDate");
28
+ }
29
+ };
30
+ var InvalidCurrency = class extends InvalidArgument {
31
+ constructor() {
32
+ super(...arguments);
33
+ __publicField(this, "name", "InvalidCurrency");
34
+ }
35
+ };
36
+ var InvalidAmount = class extends InvalidArgument {
37
+ constructor() {
38
+ super(...arguments);
39
+ __publicField(this, "name", "InvalidAmount");
40
+ }
41
+ };
42
+ var DateOutOfRange = class extends BCVError {
43
+ constructor() {
44
+ super(...arguments);
45
+ __publicField(this, "name", "DateOutOfRange");
46
+ }
47
+ };
48
+ var CurrencyNotAvailable = class extends BCVError {
49
+ constructor() {
50
+ super(...arguments);
51
+ __publicField(this, "name", "CurrencyNotAvailable");
52
+ }
53
+ };
54
+ var NotFound = class extends BCVError {
55
+ constructor() {
56
+ super(...arguments);
57
+ __publicField(this, "name", "NotFound");
58
+ }
59
+ };
60
+ var UpstreamError = class extends BCVError {
61
+ constructor(message, status, options) {
62
+ super(message, options);
63
+ __publicField(this, "name", "UpstreamError");
64
+ /** HTTP status code, when the error came from an HTTP response. */
65
+ __publicField(this, "status");
66
+ this.status = status;
67
+ }
68
+ };
69
+
70
+ // src/rules.ts
71
+ var CURRENCIES = ["USD", "EUR", "CNY", "TRY", "RUB"];
72
+ var ANY_CURRENCIES = ["VES", ...CURRENCIES];
73
+ var SOURCE = "Banco Central de Venezuela (BCV), via https://bcv.today";
74
+ var UNIT = "VES (bolivars) per 1 unit of the currency";
75
+ var EARLIEST_SNAPSHOT = "2021-08-02";
76
+ var MAX_HISTORY_DAYS = 1830;
77
+ var MAX_AMOUNT = 1e15;
78
+ var STALE_AFTER_HOURS = 96;
79
+ var LATEST_PATH = "/api/v1/rate.json";
80
+ var HISTORY_PATH = "/api/v1/history.json";
81
+ var STATUS_PATH = "/api/v1/status.json";
82
+ var dayPath = (date) => `/api/v1/history/${date}.json`;
83
+ function rateOf(entry, currency) {
84
+ const v = entry[currency];
85
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
86
+ }
87
+ function ratesOf(entry) {
88
+ const out = {};
89
+ for (const c of CURRENCIES) {
90
+ const v = rateOf(entry, c);
91
+ if (v !== void 0) out[c] = v;
92
+ }
93
+ return out;
94
+ }
95
+ var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
96
+ var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
97
+ function isIsoDate(s) {
98
+ const m = ISO_DATE.exec(s);
99
+ if (!m) return false;
100
+ const d = /* @__PURE__ */ new Date(`${s}T00:00:00Z`);
101
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
102
+ }
103
+ function todayCaracas(now = Date.now()) {
104
+ return new Date(now - 4 * 3600 * 1e3).toISOString().slice(0, 10);
105
+ }
106
+ function addDays(date, days) {
107
+ const d = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
108
+ d.setUTCDate(d.getUTCDate() + days);
109
+ return d.toISOString().slice(0, 10);
110
+ }
111
+ function weekday(date) {
112
+ return WEEKDAYS[(/* @__PURE__ */ new Date(`${date}T00:00:00Z`)).getUTCDay()] ?? "";
113
+ }
114
+ function parseTimestamp(value) {
115
+ if (typeof value !== "string" || value === "") return void 0;
116
+ const t = Date.parse(value);
117
+ return Number.isFinite(t) ? new Date(t) : void 0;
118
+ }
119
+ var TOOL_HINTS = { latest: "get_latest_rates", onDay: "get_rate_by_date" };
120
+ var LIBRARY_HINTS = { latest: "latest()", onDay: "on()" };
121
+ function invalidDateMessage(label, value, example = true) {
122
+ return `Invalid ${label} "${value}": use a real calendar date in YYYY-MM-DD format${example ? ", e.g. 2026-01-02" : ""}.`;
123
+ }
124
+ function rangeOrderMessage(fromLabel, from, toLabel, to) {
125
+ return `"${fromLabel}" (${from}) must be on or before "${toLabel}" (${to}).`;
126
+ }
127
+ function sameCurrencyMessage(code) {
128
+ return `"from" and "to" are both ${code}; choose two different currencies.`;
129
+ }
130
+ function notPublishedMessage(date, latest, hints) {
131
+ return `No BCV rate published yet for ${date}. Daily snapshots are available from ${EARLIEST_SNAPSHOT}` + (latest ? ` to ${latest}.` : " to the latest business day.") + ` Use ${hints.latest} for the rate currently in effect.`;
132
+ }
133
+ function carryForwardNote(date, effective) {
134
+ if (!effective || effective === date) return void 0;
135
+ return `${date} (${weekday(date)}) uses the rate with effective date ${effective} (${weekday(effective)}): a published BCV rate stays in effect until the next publication (weekends and holidays carry it forward).`;
136
+ }
137
+ function checkDay(date, today = todayCaracas(), label = "date") {
138
+ if (!isIsoDate(date)) return { kind: "invalid_date", message: invalidDateMessage(label, date) };
139
+ if (date < EARLIEST_SNAPSHOT) {
140
+ return { kind: "out_of_range", message: `No BCV data for ${date}: daily snapshots start on ${EARLIEST_SNAPSHOT}.` };
141
+ }
142
+ if (date > addDays(today, 1)) {
143
+ return {
144
+ kind: "out_of_range",
145
+ message: `${date} is in the future (today in Caracas is ${today}); BCV rates are only known up to the next business day.`
146
+ };
147
+ }
148
+ return void 0;
149
+ }
150
+ function pickRates(entry, date, currency) {
151
+ const all = ratesOf(entry);
152
+ if (!currency) return { rates: all };
153
+ const v = all[currency];
154
+ if (v === void 0) {
155
+ const avail = Object.keys(all).join(", ") || "none";
156
+ return {
157
+ kind: "not_available",
158
+ message: `No ${currency} rate in the BCV data for ${date} (older entries may lack some currencies). Available that day: ${avail}.`
159
+ };
160
+ }
161
+ return { rates: { [currency]: v } };
162
+ }
163
+ function conversionRates(entry, from, to, day) {
164
+ const vesPer = (c) => c === "VES" ? 1 : rateOf(entry, c);
165
+ const rf = vesPer(from);
166
+ const rt = vesPer(to);
167
+ if (rf === void 0 || rt === void 0) {
168
+ const missing = [from, to].filter((_, i) => (i === 0 ? rf : rt) === void 0);
169
+ return {
170
+ kind: "not_available",
171
+ message: `No BCV rate for ${missing.join(" and ")} on ${day} (older entries may lack some currencies). Available: ${Object.keys(ratesOf(entry)).join(", ")}.`
172
+ };
173
+ }
174
+ const ratesUsed = {};
175
+ if (from !== "VES") ratesUsed[from] = rf;
176
+ if (to !== "VES") ratesUsed[to] = rt;
177
+ return { vesPerFrom: rf, vesPerTo: rt, ratesUsed };
178
+ }
179
+ function historyWindow(entries, currency, req, hints = TOOL_HINTS) {
180
+ const { days, from, to } = req;
181
+ const series = entries.filter((e) => typeof e.date === "string" && rateOf(e, currency) !== void 0).map((e) => ({ date: e.date, effective_date: e.effective_date ?? e.date, rate: rateOf(e, currency) }));
182
+ series.sort((a, b) => a.date < b.date ? -1 : a.date > b.date ? 1 : 0);
183
+ if (series.length === 0) return { kind: "not_available", message: `No ${currency} data in the BCV history.` };
184
+ const earliest = series[0].date;
185
+ const latest = series[series.length - 1].date;
186
+ let start;
187
+ let end;
188
+ if (from || to) {
189
+ start = from ?? earliest;
190
+ end = to ?? latest;
191
+ } else {
192
+ end = latest;
193
+ start = addDays(latest, -((days ?? 30) - 1));
194
+ }
195
+ const window = series.filter((p) => p.date >= start && p.date <= end);
196
+ if (window.length === 0) {
197
+ return {
198
+ kind: "out_of_range",
199
+ message: `No ${currency} rates between ${start} and ${end}. The history covers ${earliest} to ${latest} for ${currency} (latest ${MAX_HISTORY_DAYS} daily entries). For older single days use ${hints.onDay}.`
200
+ };
201
+ }
202
+ const first = window[0];
203
+ const last = window[window.length - 1];
204
+ let min = first;
205
+ let max = first;
206
+ for (const p of window) {
207
+ if (p.rate < min.rate) min = p;
208
+ if (p.rate > max.rate) max = p;
209
+ }
210
+ const notes = [];
211
+ if (start < earliest) notes.push(`History for ${currency} starts on ${earliest}; earlier dates were skipped.`);
212
+ if (end > latest) notes.push(`Latest available date is ${latest}.`);
213
+ return { series: window, first, last, min, max, notes };
214
+ }
215
+ function round(n, digits2 = 8) {
216
+ const f = 10 ** digits2;
217
+ return Math.round(n * f) / f;
218
+ }
219
+ function freshness(doc, now = Date.now()) {
220
+ const updated = doc.updated_at ? Date.parse(doc.updated_at) : Number.NaN;
221
+ const ageHours = Number.isFinite(updated) ? round((now - updated) / 36e5, 1) : void 0;
222
+ const stale = ageHours === void 0 || ageHours > STALE_AFTER_HOURS || doc.status !== "ok";
223
+ return { ageHours, stale };
224
+ }
225
+ function isProblem(v) {
226
+ return typeof v === "object" && v !== null && "kind" in v && "message" in v && !("series" in v);
227
+ }
228
+
229
+ // src/api.ts
230
+ var DEFAULT_BASE_URL = "https://bcv.today";
231
+ var _TTLCache = class _TTLCache {
232
+ constructor(ttlMs, clock = Date.now) {
233
+ __publicField(this, "ttlMs", ttlMs);
234
+ __publicField(this, "clock", clock);
235
+ __publicField(this, "data", /* @__PURE__ */ new Map());
236
+ }
237
+ get(key) {
238
+ if (this.ttlMs <= 0) return void 0;
239
+ const hit = this.data.get(key);
240
+ if (!hit) return void 0;
241
+ if (hit.expires <= this.clock()) {
242
+ this.data.delete(key);
243
+ return void 0;
244
+ }
245
+ return hit.value;
246
+ }
247
+ set(key, value) {
248
+ if (this.ttlMs <= 0) return;
249
+ if (this.data.size >= _TTLCache.MAX_ENTRIES) this.data.clear();
250
+ this.data.set(key, { expires: this.clock() + this.ttlMs, value });
251
+ }
252
+ clear() {
253
+ this.data.clear();
254
+ }
255
+ };
256
+ __publicField(_TTLCache, "MAX_ENTRIES", 64);
257
+ var TTLCache = _TTLCache;
258
+ function isBrowserLike() {
259
+ const nav = globalThis.navigator;
260
+ return typeof nav?.userAgent === "string" && nav.userAgent.startsWith("Mozilla/");
261
+ }
262
+ var Api = class {
263
+ constructor(opts = {}) {
264
+ __publicField(this, "baseUrl");
265
+ __publicField(this, "timeoutMs");
266
+ __publicField(this, "cache");
267
+ __publicField(this, "fetchImpl");
268
+ __publicField(this, "headersBase");
269
+ __publicField(this, "init");
270
+ __publicField(this, "inflight", /* @__PURE__ */ new Map());
271
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
272
+ this.timeoutMs = opts.timeoutMs ?? 1e4;
273
+ this.cache = opts.cache ?? new TTLCache(3e5);
274
+ this.fetchImpl = opts.fetch;
275
+ this.headersBase = opts.userAgent && !isBrowserLike() ? { "user-agent": opts.userAgent } : {};
276
+ this.init = opts.init ?? {};
277
+ }
278
+ async request(path, accept) {
279
+ const url = this.baseUrl + path;
280
+ const doFetch = this.fetchImpl ?? (typeof fetch === "function" ? fetch : void 0);
281
+ if (!doFetch) {
282
+ throw new UpstreamError("No fetch implementation available: pass { fetch } to the client.");
283
+ }
284
+ const init = { ...this.init, headers: { accept, ...this.headersBase } };
285
+ let timer;
286
+ let controller;
287
+ if (this.timeoutMs > 0 && typeof AbortController === "function") {
288
+ controller = new AbortController();
289
+ init.signal = controller.signal;
290
+ timer = setTimeout(() => controller?.abort(), this.timeoutMs);
291
+ }
292
+ try {
293
+ let res;
294
+ try {
295
+ res = await doFetch(url, init);
296
+ } catch (err) {
297
+ const reason = controller?.signal.aborted ? `timed out after ${this.timeoutMs} ms` : errorText(err);
298
+ throw new UpstreamError(
299
+ `Could not reach the BCV Today data API (${reason}). Try again in a moment.`,
300
+ void 0,
301
+ {
302
+ cause: err
303
+ }
304
+ );
305
+ }
306
+ if (res.status === 404) {
307
+ await discard(res);
308
+ throw new NotFound(`Not found: ${path}`);
309
+ }
310
+ if (!res.ok) {
311
+ await discard(res);
312
+ throw new UpstreamError(
313
+ `The BCV Today data API answered HTTP ${res.status} for ${path}. Try again in a moment.`,
314
+ res.status
315
+ );
316
+ }
317
+ try {
318
+ return await res.text();
319
+ } catch (err) {
320
+ const reason = controller?.signal.aborted ? `timed out after ${this.timeoutMs} ms` : errorText(err);
321
+ throw new UpstreamError(
322
+ `Could not reach the BCV Today data API (${reason}). Try again in a moment.`,
323
+ void 0,
324
+ {
325
+ cause: err
326
+ }
327
+ );
328
+ }
329
+ } finally {
330
+ if (timer !== void 0) clearTimeout(timer);
331
+ }
332
+ }
333
+ /** Memoised fetch: one network request per key while it is cached or in flight. */
334
+ memo(key, load) {
335
+ const hit = this.cache.get(key);
336
+ if (hit !== void 0) return Promise.resolve(hit);
337
+ const pending = this.inflight.get(key);
338
+ if (pending) return pending;
339
+ const p = load().then(
340
+ (value) => {
341
+ this.inflight.delete(key);
342
+ this.cache.set(key, value);
343
+ return value;
344
+ },
345
+ (err) => {
346
+ this.inflight.delete(key);
347
+ throw err;
348
+ }
349
+ );
350
+ this.inflight.set(key, p);
351
+ return p;
352
+ }
353
+ /** Raw text of any path on the origin (e.g. "/llms.txt"). */
354
+ text(path, accept = "text/plain") {
355
+ return this.memo(`${accept} ${path}`, () => this.request(path, accept));
356
+ }
357
+ /** Parsed JSON of a path; errors are never cached. */
358
+ json(path) {
359
+ return this.memo(`json ${path}`, async () => {
360
+ const text = await this.request(path, "application/json");
361
+ try {
362
+ return JSON.parse(text);
363
+ } catch {
364
+ throw new UpstreamError(`The BCV Today data API returned invalid JSON for ${path}.`);
365
+ }
366
+ });
367
+ }
368
+ latest() {
369
+ return this.json(LATEST_PATH);
370
+ }
371
+ status() {
372
+ return this.json(STATUS_PATH);
373
+ }
374
+ async history() {
375
+ const data = await this.json(HISTORY_PATH);
376
+ if (!Array.isArray(data)) {
377
+ throw new UpstreamError("Unexpected history.json shape (expected an array).");
378
+ }
379
+ return data;
380
+ }
381
+ /** Snapshot for one calendar day; rejects with NotFound when out of range. */
382
+ day(date) {
383
+ return this.json(dayPath(date));
384
+ }
385
+ };
386
+ function errorText(err) {
387
+ return err instanceof Error ? err.message : String(err);
388
+ }
389
+ async function discard(res) {
390
+ try {
391
+ await res.body?.cancel();
392
+ } catch {
393
+ }
394
+ }
395
+
396
+ // src/decimal.ts
397
+ var PRECISION = 28;
398
+ var TEN = BigInt(10);
399
+ var ZERO = BigInt(0);
400
+ var ONE = BigInt(1);
401
+ var TWO = BigInt(2);
402
+ var DECIMAL_RE = /^([+-])?(\d+)?(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
403
+ function pow10(n) {
404
+ return TEN ** BigInt(n);
405
+ }
406
+ function abs(n) {
407
+ return n < ZERO ? -n : n;
408
+ }
409
+ function digits(n) {
410
+ return n === ZERO ? 1 : abs(n).toString().length;
411
+ }
412
+ function parseDecimal(text) {
413
+ const m = DECIMAL_RE.exec(text);
414
+ if (!m) return void 0;
415
+ const [, sign, int = "", frac = "", e = "0"] = m;
416
+ if (int === "" && frac === "") return void 0;
417
+ const exp = Number(e) - frac.length;
418
+ if (!Number.isSafeInteger(exp) || Math.abs(exp) > 1e4) return void 0;
419
+ const coef = BigInt(`${int}${frac}` || "0");
420
+ return normalize({ coef: sign === "-" ? -coef : coef, exp });
421
+ }
422
+ function fromNumber(n) {
423
+ const d = parseDecimal(String(n));
424
+ if (!d) throw new RangeError(`Not a finite number: ${n}`);
425
+ return d;
426
+ }
427
+ function normalize(d) {
428
+ if (d.coef === ZERO) return { coef: ZERO, exp: 0 };
429
+ let { coef, exp } = d;
430
+ while (coef % TEN === ZERO) {
431
+ coef /= TEN;
432
+ exp += 1;
433
+ }
434
+ return { coef, exp };
435
+ }
436
+ function align(a, b) {
437
+ const exp = Math.min(a.exp, b.exp);
438
+ return [a.coef * pow10(a.exp - exp), b.coef * pow10(b.exp - exp), exp];
439
+ }
440
+ function sub(a, b) {
441
+ const [x, y, exp] = align(a, b);
442
+ return normalize({ coef: x - y, exp });
443
+ }
444
+ function mul(a, b) {
445
+ return normalize({ coef: a.coef * b.coef, exp: a.exp + b.exp });
446
+ }
447
+ function cmp(a, b) {
448
+ const [x, y] = align(a, b);
449
+ return x < y ? -1 : x > y ? 1 : 0;
450
+ }
451
+ function shiftRound(n, k) {
452
+ if (k <= 0) return n * pow10(-k);
453
+ const p = pow10(k);
454
+ const q = n / p;
455
+ const r = abs(n % p);
456
+ if (r * TWO < p) return q;
457
+ return n < ZERO ? q - ONE : q + ONE;
458
+ }
459
+ function roundSignificant(a, prec = PRECISION) {
460
+ const extra = digits(a.coef) - prec;
461
+ if (extra <= 0) return a;
462
+ return normalize({ coef: shiftRound(a.coef, extra), exp: a.exp + extra });
463
+ }
464
+ function div(a, b, prec = PRECISION) {
465
+ if (b.coef === ZERO) throw new RangeError("Division by zero");
466
+ if (a.coef === ZERO) return { coef: ZERO, exp: 0 };
467
+ const k = Math.max(0, prec + 2 + digits(b.coef) - digits(a.coef));
468
+ const num2 = a.coef * pow10(k);
469
+ const q = num2 / b.coef;
470
+ const exp = a.exp - b.exp - k;
471
+ const extra = digits(q) - prec;
472
+ if (extra <= 0) return normalize({ coef: q, exp });
473
+ return normalize({ coef: shiftRound(q, extra), exp: exp + extra });
474
+ }
475
+ function quantize(a, places) {
476
+ const target = -places;
477
+ if (a.exp >= target) return { coef: a.coef * pow10(a.exp - target), exp: target };
478
+ return { coef: shiftRound(a.coef, target - a.exp), exp: target };
479
+ }
480
+ function toFixed(a, places) {
481
+ const d = places === void 0 ? a : quantize(a, places);
482
+ const neg = d.coef < ZERO;
483
+ let s = abs(d.coef).toString();
484
+ let out;
485
+ if (d.exp >= 0) {
486
+ out = s + "0".repeat(d.exp);
487
+ } else {
488
+ const scale = -d.exp;
489
+ if (s.length <= scale) s = "0".repeat(scale - s.length + 1) + s;
490
+ out = `${s.slice(0, s.length - scale)}.${s.slice(s.length - scale)}`;
491
+ }
492
+ return neg && /[1-9]/.test(out) ? `-${out}` : out;
493
+ }
494
+ function toPlain(a) {
495
+ return toFixed(normalize(a));
496
+ }
497
+ function toNumber(a) {
498
+ return Number(toPlain(a));
499
+ }
500
+ function group(a, places) {
501
+ const fixed = toFixed(a, places);
502
+ const neg = fixed.startsWith("-");
503
+ const body = neg ? fixed.slice(1) : fixed;
504
+ const [int = "0", frac] = body.split(".");
505
+ const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
506
+ return `${neg ? "-" : ""}${grouped}${frac !== void 0 ? `.${frac}` : ""}`;
507
+ }
508
+
509
+ // src/version.ts
510
+ var VERSION = "1.0.0";
511
+
512
+ // src/client.ts
513
+ var DEFAULT_USER_AGENT = `bcv-today-js/${VERSION} (+https://bcv.today)`;
514
+ var HUNDRED = { coef: BigInt(100), exp: 0 };
515
+ var MAX_AMOUNT_DEC = fromNumber(MAX_AMOUNT);
516
+ function repr(value) {
517
+ if (typeof value === "string") return JSON.stringify(value);
518
+ if (typeof value === "bigint") return `${value}n`;
519
+ if (value instanceof Date) return `Date(${Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString()})`;
520
+ return String(value);
521
+ }
522
+ function parseDate(value, label = "date") {
523
+ if (value instanceof Date) {
524
+ if (Number.isNaN(value.getTime())) throw new InvalidDate(`Invalid ${label} ${repr(value)}: not a valid Date.`);
525
+ return value.toISOString().slice(0, 10);
526
+ }
527
+ if (typeof value === "string") {
528
+ const text = value.trim();
529
+ if (isIsoDate(text)) return text;
530
+ throw new InvalidDate(invalidDateMessage(label, value));
531
+ }
532
+ throw new InvalidDate(`Invalid ${label} ${repr(value)}: expected a Date or a YYYY-MM-DD string.`);
533
+ }
534
+ function normalizeCurrency(code, allowVes = false) {
535
+ const valid = allowVes ? ANY_CURRENCIES : CURRENCIES;
536
+ if (typeof code === "string") {
537
+ let upper = code.trim().toUpperCase();
538
+ if (upper === "VEF" && allowVes) upper = "VES";
539
+ if (valid.includes(upper)) return upper;
540
+ }
541
+ throw new InvalidCurrency(`Unsupported currency ${repr(code)}: use one of ${valid.join(", ")}.`);
542
+ }
543
+ function parseAmount(amount) {
544
+ let dec;
545
+ if (typeof amount === "number") {
546
+ if (!Number.isFinite(amount))
547
+ throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must be a finite number.`);
548
+ dec = fromNumber(amount);
549
+ } else if (typeof amount === "bigint") {
550
+ dec = { coef: amount, exp: 0 };
551
+ } else if (typeof amount === "string") {
552
+ const text = amount.trim().replace(/_/g, "");
553
+ if (/^[+-]?(nan|inf|infinity)$/i.test(text)) {
554
+ throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must be a finite number.`);
555
+ }
556
+ dec = parseDecimal(text);
557
+ }
558
+ if (!dec) throw new InvalidAmount(`Invalid amount ${repr(amount)}: expected a number.`);
559
+ if (dec.coef < BigInt(0)) throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must be zero or positive.`);
560
+ if (cmp(dec, MAX_AMOUNT_DEC) > 0) {
561
+ throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must not exceed 1e15.`);
562
+ }
563
+ return dec;
564
+ }
565
+ function checkDecimals(decimals) {
566
+ if (decimals === null) return null;
567
+ if (typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 12) {
568
+ throw new InvalidAmount(`Invalid decimals ${repr(decimals)}: use a whole number from 0 to 12, or null.`);
569
+ }
570
+ return decimals;
571
+ }
572
+ function checkDays(days) {
573
+ if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > MAX_HISTORY_DAYS) {
574
+ throw new InvalidDate(`Invalid days ${repr(days)}: use a whole number from 1 to ${MAX_HISTORY_DAYS}.`);
575
+ }
576
+ return days;
577
+ }
578
+ function raise(p) {
579
+ switch (p.kind) {
580
+ case "invalid_date":
581
+ throw new InvalidDate(p.message);
582
+ case "invalid_currency":
583
+ throw new InvalidCurrency(p.message);
584
+ case "not_available":
585
+ throw new CurrencyNotAvailable(p.message);
586
+ default:
587
+ throw new DateOutOfRange(p.message);
588
+ }
589
+ }
590
+ function expectObject(value, what) {
591
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
592
+ throw new UpstreamError(`Unexpected ${what} shape (expected an object).`);
593
+ }
594
+ return value;
595
+ }
596
+ function entryDates(entry, fallback) {
597
+ const valid = (v) => typeof v === "string" && isIsoDate(v);
598
+ const day = valid(entry.date) ? entry.date : fallback;
599
+ if (!day) throw new UpstreamError("Unexpected API response: the entry has no valid 'date'.");
600
+ return [day, valid(entry.effective_date) ? entry.effective_date : day];
601
+ }
602
+ function num(value, places = 4) {
603
+ return group(typeof value === "number" ? fromNumber(value) : value, places);
604
+ }
605
+ function ratesLine(rates) {
606
+ return Object.entries(rates).map(([c, v]) => `${c} ${num(v)}`).join(", ");
607
+ }
608
+ var BCV = class {
609
+ constructor(options = {}) {
610
+ __publicField(this, "baseUrl");
611
+ __publicField(this, "timeoutMs");
612
+ __publicField(this, "cacheTtlMs");
613
+ __publicField(this, "userAgent");
614
+ __publicField(this, "api");
615
+ __publicField(this, "cache");
616
+ __publicField(this, "clock");
617
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
618
+ if (typeof baseUrl !== "string" || !/^https?:\/\//.test(baseUrl)) {
619
+ throw new InvalidArgument(`Invalid baseUrl ${repr(baseUrl)}: it must start with https:// or http://.`);
620
+ }
621
+ const timeoutMs = options.timeoutMs ?? 1e4;
622
+ const cacheTtlMs = options.cacheTtlMs ?? 3e5;
623
+ for (const [label, v] of [
624
+ ["timeoutMs", timeoutMs],
625
+ ["cacheTtlMs", cacheTtlMs]
626
+ ]) {
627
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
628
+ throw new InvalidArgument(`Invalid ${label} ${repr(v)}: use a number of milliseconds >= 0.`);
629
+ }
630
+ }
631
+ if (options.fetch !== void 0 && typeof options.fetch !== "function") {
632
+ throw new InvalidArgument("Invalid fetch: expected a function.");
633
+ }
634
+ const now = options.now;
635
+ this.clock = now ? () => +now() : Date.now;
636
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
637
+ this.timeoutMs = timeoutMs;
638
+ this.cacheTtlMs = cacheTtlMs;
639
+ this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
640
+ this.cache = new TTLCache(cacheTtlMs, this.clock);
641
+ this.api = new Api({
642
+ baseUrl: this.baseUrl,
643
+ timeoutMs,
644
+ cache: this.cache,
645
+ userAgent: this.userAgent,
646
+ ...options.fetch ? { fetch: options.fetch } : {}
647
+ });
648
+ }
649
+ /** Forgets every cached response. */
650
+ clearCache() {
651
+ this.cache.clear();
652
+ }
653
+ today() {
654
+ return todayCaracas(this.clock());
655
+ }
656
+ async latestEntry() {
657
+ return expectObject(await this.api.latest(), "/api/v1/rate.json");
658
+ }
659
+ async dayEntry(date) {
660
+ const bad = checkDay(date, this.today());
661
+ if (bad) raise(bad);
662
+ try {
663
+ return expectObject(await this.api.day(date), "day snapshot");
664
+ } catch (err) {
665
+ if (!(err instanceof NotFound)) throw err;
666
+ let latest;
667
+ try {
668
+ latest = (await this.latest()).date;
669
+ } catch (e) {
670
+ if (!(e instanceof BCVError)) throw e;
671
+ }
672
+ throw new DateOutOfRange(notPublishedMessage(date, latest, LIBRARY_HINTS));
673
+ }
674
+ }
675
+ /** Official rates currently in effect (`/api/v1/rate.json`). */
676
+ async latest() {
677
+ const entry = await this.latestEntry();
678
+ const [date, effectiveDate] = entryDates(entry);
679
+ const rates = pickRates(entry, date).rates;
680
+ return {
681
+ rates,
682
+ date,
683
+ effectiveDate,
684
+ updatedAt: parseTimestamp(entry.updated_at) ?? null,
685
+ unit: UNIT,
686
+ source: SOURCE,
687
+ summary: `Official BCV rates (effective ${effectiveDate}, Bs. per unit): ${ratesLine(rates)}`,
688
+ raw: entry
689
+ };
690
+ }
691
+ /**
692
+ * Rate(s) in effect on a calendar day.
693
+ *
694
+ * BCV does not publish on weekends and holidays: the last published rate stays
695
+ * in effect, so `effectiveDate` may be earlier than `date` and `carriedForward`
696
+ * is then true (with an explanatory `note`). Data starts on 2021-08-02; dates
697
+ * after tomorrow (Caracas time) throw `DateOutOfRange`.
698
+ *
699
+ * @param date "YYYY-MM-DD" or a Date (its UTC calendar day).
700
+ * @param currency Restrict the result to one currency (throws `CurrencyNotAvailable` if it was not published that day).
701
+ */
702
+ async on(date, currency) {
703
+ const day = parseDate(date);
704
+ const code = currency !== void 0 && currency !== null ? normalizeCurrency(currency) : void 0;
705
+ const entry = await this.dayEntry(day);
706
+ const [, effectiveDate] = entryDates(entry, day);
707
+ const picked = pickRates(entry, day, code);
708
+ if (isProblem(picked)) raise(picked);
709
+ const { rates } = picked;
710
+ const note = carryForwardNote(day, effectiveDate) ?? null;
711
+ const values = Object.values(rates);
712
+ const text = `BCV rate in effect on ${day} (Bs. per unit): ${ratesLine(rates)}.`;
713
+ return {
714
+ date: day,
715
+ effectiveDate,
716
+ carriedForward: note !== null,
717
+ rates,
718
+ rate: values.length === 1 ? values[0] : void 0,
719
+ updatedAt: parseTimestamp(entry.updated_at) ?? null,
720
+ note,
721
+ unit: UNIT,
722
+ source: SOURCE,
723
+ summary: note ? `${text} ${note}` : text,
724
+ raw: entry
725
+ };
726
+ }
727
+ /**
728
+ * Daily series for one currency, oldest first: the last `days` calendar days
729
+ * ending on the latest published date (default 30, max 1830), or an inclusive
730
+ * `start`/`end` range (`days` is then ignored). Uses `/api/v1/history.json`,
731
+ * which keeps the latest 1830 daily entries; ranges are clipped to what it
732
+ * covers and `note` says so.
733
+ */
734
+ async history(currency, options = {}) {
735
+ const code = normalizeCurrency(currency);
736
+ const start = options.start !== void 0 ? parseDate(options.start, "start") : void 0;
737
+ const end = options.end !== void 0 ? parseDate(options.end, "end") : void 0;
738
+ const days = checkDays(options.days ?? 30);
739
+ if (start && end && start > end) throw new InvalidDate(rangeOrderMessage("start", start, "end", end));
740
+ const entries = (await this.api.history()).filter(
741
+ (e) => typeof e === "object" && e !== null && typeof e.date === "string" && isIsoDate(e.date)
742
+ );
743
+ const w = historyWindow(entries, code, { days, from: start, to: end }, LIBRARY_HINTS);
744
+ if (isProblem(w)) raise(w);
745
+ const point = (p) => ({
746
+ date: p.date,
747
+ effectiveDate: p.effective_date,
748
+ rate: p.rate,
749
+ carriedForward: p.effective_date !== p.date
750
+ });
751
+ const points = w.series.map(point);
752
+ const first = points[0];
753
+ const last = points[points.length - 1];
754
+ const firstDec = fromNumber(first.rate);
755
+ const changeDec = sub(fromNumber(last.rate), firstDec);
756
+ const pctDec = quantize(mul(div(changeDec, firstDec), HUNDRED), 4);
757
+ const min = point(w.min);
758
+ const max = point(w.max);
759
+ const note = w.notes.length ? w.notes.join(" ") : null;
760
+ const sign = changeDec.coef >= BigInt(0) ? "+" : "";
761
+ const text = `${code}/VES from ${first.date} to ${last.date} (${points.length} days): ${num(first.rate)} -> ${num(last.rate)} (${sign}${toFixed(pctDec, 2)}%). Min ${num(min.rate)} on ${min.date}, max ${num(max.rate)} on ${max.date}.`;
762
+ return {
763
+ currency: code,
764
+ points,
765
+ start: first.date,
766
+ end: last.date,
767
+ first,
768
+ last,
769
+ min,
770
+ max,
771
+ change: toNumber(changeDec),
772
+ changeExact: toPlain(changeDec),
773
+ changePct: toNumber(pctDec),
774
+ note,
775
+ unit: UNIT,
776
+ source: SOURCE,
777
+ summary: note ? `${text} ${note}` : text
778
+ };
779
+ }
780
+ /**
781
+ * Converts `amount` between VES, USD, EUR, CNY, TRY and RUB at the BCV rate.
782
+ *
783
+ * Cross rates go through the bolivar: `amount * vesPerFrom / vesPerTo`. The
784
+ * math is exact decimal (no float drift; divisions keep 28 significant
785
+ * digits, half-up), then `result` is rounded half-up to `decimals` places
786
+ * (default 2; `null` keeps full precision). `resultExact` is the unrounded
787
+ * value as a string. Numbers are read via their shortest decimal string
788
+ * (0.1 is exactly "0.1"); pass a string for amounts beyond float precision.
789
+ */
790
+ async convert(amount, from, to, options = {}) {
791
+ const value = parseAmount(amount);
792
+ const src = normalizeCurrency(from, true);
793
+ const dst = normalizeCurrency(to, true);
794
+ if (src === dst) throw new InvalidCurrency(sameCurrencyMessage(src));
795
+ const decimals = checkDecimals(options.decimals === void 0 ? 2 : options.decimals);
796
+ const date = options.date !== void 0 ? parseDate(options.date) : void 0;
797
+ const entry = date !== void 0 ? await this.dayEntry(date) : await this.latestEntry();
798
+ const [entryDay, effectiveDate] = entryDates(entry, date);
799
+ const day = date ?? entryDay;
800
+ const picked = conversionRates(entry, src, dst, day);
801
+ if (isProblem(picked)) raise(picked);
802
+ const rf = fromNumber(picked.vesPerFrom);
803
+ const rt = fromNumber(picked.vesPerTo);
804
+ const rate = div(rf, rt);
805
+ const exact = div(roundSignificant(mul(value, rf)), rt);
806
+ const result = decimals === null ? exact : quantize(exact, decimals);
807
+ const note = date !== void 0 ? carryForwardNote(date, effectiveDate) ?? null : null;
808
+ const places = decimals ?? 8;
809
+ const text = `${num(value, 2)} ${src} = ${num(result, places)} ${dst} at the official BCV rate (effective ${effectiveDate}; 1 ${src} = ${num(rate, 6)} ${dst}).`;
810
+ return {
811
+ amount: toNumber(value),
812
+ amountExact: toPlain(value),
813
+ from: src,
814
+ to: dst,
815
+ result: toNumber(result),
816
+ resultText: decimals === null ? toPlain(exact) : toFixed(result, decimals),
817
+ resultExact: toPlain(exact),
818
+ rate: toNumber(rate),
819
+ rateExact: toPlain(rate),
820
+ ratesUsed: picked.ratesUsed,
821
+ date: day,
822
+ effectiveDate,
823
+ carriedForward: note !== null,
824
+ decimals,
825
+ note,
826
+ source: SOURCE,
827
+ summary: note ? `${text} ${note}` : text
828
+ };
829
+ }
830
+ /** Freshness of the published data (`/api/v1/status.json`). */
831
+ async status() {
832
+ const doc = expectObject(await this.api.status(), "/api/v1/status.json");
833
+ const { ageHours, stale } = freshness(doc, this.clock());
834
+ const text = (v) => typeof v === "string" ? v : null;
835
+ const day = (v) => typeof v === "string" && isIsoDate(v) ? v : null;
836
+ const status = text(doc.status) ?? "unknown";
837
+ const age = ageHours !== void 0 ? ` (${ageHours} h ago)` : "";
838
+ return {
839
+ status,
840
+ updatedAt: parseTimestamp(doc.updated_at) ?? null,
841
+ generatedAt: parseTimestamp(doc.generated_at) ?? null,
842
+ date: day(doc.date),
843
+ effectiveDate: day(doc.effective_date),
844
+ ageHours: ageHours ?? null,
845
+ stale,
846
+ supportedCurrencies: Array.isArray(doc.supported_currencies) ? doc.supported_currencies.map(String) : [...CURRENCIES],
847
+ currencies: doc.currencies && typeof doc.currencies === "object" ? Object.fromEntries(Object.entries(doc.currencies).map(([k, v]) => [k, Boolean(v)])) : {},
848
+ timezone: text(doc.timezone),
849
+ apiVersion: text(doc.api_version),
850
+ summary: `Status ${status}${stale ? " (STALE)" : ""}: last capture ${text(doc.updated_at) ?? "unknown"}${age}, effective date ${day(doc.effective_date) ?? "unknown"}.`,
851
+ raw: doc
852
+ };
853
+ }
854
+ };
855
+
856
+ exports.ANY_CURRENCIES = ANY_CURRENCIES;
857
+ exports.BCV = BCV;
858
+ exports.BCVError = BCVError;
859
+ exports.CURRENCIES = CURRENCIES;
860
+ exports.CurrencyNotAvailable = CurrencyNotAvailable;
861
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
862
+ exports.DEFAULT_USER_AGENT = DEFAULT_USER_AGENT;
863
+ exports.DateOutOfRange = DateOutOfRange;
864
+ exports.EARLIEST_SNAPSHOT = EARLIEST_SNAPSHOT;
865
+ exports.InvalidAmount = InvalidAmount;
866
+ exports.InvalidArgument = InvalidArgument;
867
+ exports.InvalidCurrency = InvalidCurrency;
868
+ exports.InvalidDate = InvalidDate;
869
+ exports.MAX_HISTORY_DAYS = MAX_HISTORY_DAYS;
870
+ exports.NotFound = NotFound;
871
+ exports.SOURCE = SOURCE;
872
+ exports.UNIT = UNIT;
873
+ exports.UpstreamError = UpstreamError;
874
+ exports.VERSION = VERSION;