@allratestoday/exchange-plugins 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +180 -2
- package/adapters/edge-rates-server/README.md +16 -0
- package/adapters/edge-rates-server/allratestoday.ts +118 -0
- package/dist/allratestoday-exchange-plugins.global.js +2 -0
- package/dist/allratestoday-exchange-plugins.global.js.map +1 -0
- package/dist/index.d.mts +266 -0
- package/dist/index.d.ts +266 -0
- package/dist/index.js +479 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +440 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +60 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AllRatesToday
|
|
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,181 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AllRatesToday Exchange Plugins
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@allratestoday/exchange-plugins)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
[](./tsconfig.json)
|
|
6
|
+
[](https://allratestoday.com/api/open/central-banks)
|
|
7
|
+
|
|
8
|
+
This library exports a collection of exchange-rate source plugins for [AllRatesToday](https://allratestoday.com):
|
|
9
|
+
live mid-market rates, the daily 16:00 London reference rate, and the official tables of [122 central banks and 4 tax
|
|
10
|
+
authorities](https://allratestoday.com/central-bank-rates-api/institutions/). Every source implements one small `RatePlugin` interface, so you can register the ones you
|
|
11
|
+
want and fall through them in order. It also ships a drop-in provider for
|
|
12
|
+
[edge-rates-server](./adapters/edge-rates-server/).
|
|
13
|
+
|
|
14
|
+
Please see [src/index.ts](./src/index.ts) for the list of plugins in this repo.
|
|
15
|
+
|
|
16
|
+
## 🚀 Features
|
|
17
|
+
|
|
18
|
+
- **One interface, many sources** — `fetchRates(hints)` on every plugin; unanswered pairs are left out, never thrown.
|
|
19
|
+
- **Keyless by default** — the reference rate and every central-bank table work without an API key.
|
|
20
|
+
- **Live rates with a key** — `allratestoday` adds real-time mid-market rates (free tier: 300 requests, no card).
|
|
21
|
+
- **Pairs the institution never published** — inverted or crossed through its home currency, and the answer says which (`method: 'published' | 'inverse' | 'cross'`).
|
|
22
|
+
- **Ordered fallback** — `makeRateEngine([...])` asks plugins in order and stops at the first answer per pair.
|
|
23
|
+
- **Zero runtime dependencies**, ESM + CommonJS + a self-registering browser bundle, strict TypeScript types.
|
|
24
|
+
|
|
25
|
+
## 🔑 Get your API key
|
|
26
|
+
|
|
27
|
+
Keyless plugins need nothing. For live mid-market rates and dated tables, register at
|
|
28
|
+
[allratestoday.com/register](https://allratestoday.com/register) (free, no card) and pass `{ apiKey }`.
|
|
29
|
+
Agents can issue themselves a 100-call trial key with `POST https://allratestoday.com/api/agent/keys`.
|
|
30
|
+
|
|
31
|
+
## 📦 Installing
|
|
32
|
+
|
|
33
|
+
First, add this library to your project:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
npm install @allratestoday/exchange-plugins
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Node.js
|
|
40
|
+
|
|
41
|
+
Build the plugins you want, in preference order, and hand them to an engine:
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
const { makeRateEngine, plugins } = require('@allratestoday/exchange-plugins')
|
|
45
|
+
|
|
46
|
+
const engine = makeRateEngine([
|
|
47
|
+
plugins.allratestoday({ apiKey: process.env.ALLRATESTODAY_API_KEY }), // live, needs a key
|
|
48
|
+
plugins.referenceRate(), // daily 16:00 London table, keyless
|
|
49
|
+
plugins.ecb() // official ECB table, keyless
|
|
50
|
+
])
|
|
51
|
+
|
|
52
|
+
const pairs = await engine.fetchRates([
|
|
53
|
+
{ fromCurrency: 'USD', toCurrency: 'EUR' },
|
|
54
|
+
{ fromCurrency: 'GBP', toCurrency: 'JPY' }
|
|
55
|
+
])
|
|
56
|
+
// [{ fromCurrency: 'USD', toCurrency: 'EUR', rate: 0.8927, date: '2026-10-15',
|
|
57
|
+
// pluginId: 'referenceRate', rateType: 'reference', method: 'published' }, ...]
|
|
58
|
+
|
|
59
|
+
const { result } = await engine.convert(100, 'GBP', 'JPY')
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
You can also add plugins individually if you want to be more picky:
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
const { makeCentralBankPlugin } = require('@allratestoday/exchange-plugins')
|
|
66
|
+
|
|
67
|
+
const hmrc = makeCentralBankPlugin('hmrc')
|
|
68
|
+
const [gbpUsd] = await hmrc.fetchRates([{ fromCurrency: 'GBP', toCurrency: 'USD' }])
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Or take the recommended stack in one call (live when a key is set, then the reference rate, then the cross-bank composite table):
|
|
72
|
+
|
|
73
|
+
```js
|
|
74
|
+
const { makeRateEngine, makeDefaultPlugins } = require('@allratestoday/exchange-plugins')
|
|
75
|
+
const engine = makeRateEngine(makeDefaultPlugins({ apiKey: process.env.ALLRATESTODAY_API_KEY }))
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Browser
|
|
79
|
+
|
|
80
|
+
The bundle at `dist/allratestoday-exchange-plugins.global.js` exposes `window.allratestodayExchangePlugins`.
|
|
81
|
+
If the page defines `window.addAllRatesTodayPlugins` before the script loads, the bundle calls it with the
|
|
82
|
+
plugin map, so a host app can register the sources without importing anything:
|
|
83
|
+
|
|
84
|
+
```html
|
|
85
|
+
<script>
|
|
86
|
+
window.addAllRatesTodayPlugins = plugins => {
|
|
87
|
+
window.fx = allratestodayExchangePlugins.makeRateEngine([plugins.referenceRate(), plugins.ecb()])
|
|
88
|
+
}
|
|
89
|
+
</script>
|
|
90
|
+
<script src="https://cdn.jsdelivr.net/npm/@allratestoday/exchange-plugins/dist/allratestoday-exchange-plugins.global.js"></script>
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### React Native / other runtimes
|
|
94
|
+
|
|
95
|
+
The package uses the global `fetch`. Pass your own with `{ fetch }` where the runtime has none, and
|
|
96
|
+
`{ timeoutMs }` to change the 10 s request timeout.
|
|
97
|
+
|
|
98
|
+
## 🧩 Plugins
|
|
99
|
+
|
|
100
|
+
| pluginId | Source | Key | Dates |
|
|
101
|
+
|---|---|---|---|
|
|
102
|
+
| `allratestoday` | Live mid-market rates, `GET /api/v1/rates` | required | latest only |
|
|
103
|
+
| `referenceRate` | AllRatesToday daily reference rate, fixed 16:00 London, USD base | keyless (latest), key for dated | `/api/v1/reference-rate/{date}` |
|
|
104
|
+
| `ecb`, `boe`, `fed`, `rbi`, `hmrc`, … (125) | Official tables as published by each institution | keyless (latest), paid key for dated | `/api/v1/central-bank/{bank}/{date}` |
|
|
105
|
+
| `composite` | Cross-bank USD table built from the official sources | keyless | latest only |
|
|
106
|
+
|
|
107
|
+
`CENTRAL_BANK_CODES` lists every source code the package knows; the live list is
|
|
108
|
+
[`/api/open/central-banks`](https://allratestoday.com/api/open/central-banks).
|
|
109
|
+
`makeCentralBankPlugin(code)` works for any code the API serves, including ones added after this release.
|
|
110
|
+
|
|
111
|
+
## 📚 API reference
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
interface RateHint { fromCurrency: string; toCurrency: string; date?: string } // date = YYYY-MM-DD
|
|
115
|
+
|
|
116
|
+
interface RatePair {
|
|
117
|
+
fromCurrency: string; toCurrency: string
|
|
118
|
+
rate: number // units of toCurrency per 1 fromCurrency
|
|
119
|
+
date: string // the table date actually answered (weekends resolve to the previous business day)
|
|
120
|
+
pluginId: string
|
|
121
|
+
rateType: string // 'mid-market' | 'reference' | 'official' | ...
|
|
122
|
+
method: 'published' | 'inverse' | 'cross'
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface RatePlugin {
|
|
126
|
+
rateInfo: { pluginId: string; displayName: string; keyless: boolean; homepage: string }
|
|
127
|
+
fetchRates(hints: RateHint[]): Promise<RatePair[]>
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface PluginOptions { apiKey?: string; baseUrl?: string; fetch?: typeof fetch; timeoutMs?: number }
|
|
131
|
+
|
|
132
|
+
makeRateEngine(plugins): { fetchRates, getRate(from, to, date?), convert(amount, from, to, date?) }
|
|
133
|
+
makePlugins(ids, options) // instantiate by pluginId, in order
|
|
134
|
+
makeDefaultPlugins(options) // live (if key) → referenceRate → composite
|
|
135
|
+
makeCentralBankPlugin(code, options)
|
|
136
|
+
resolvePair(rows, from, to) // the table resolver, exported for your own tables
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## 🛡️ Error handling
|
|
140
|
+
|
|
141
|
+
A plugin never throws for a pair it cannot answer; it leaves the pair out so the engine can try the next source.
|
|
142
|
+
Network and HTTP failures inside a plugin are swallowed the same way. `ExchangePluginError` (with `status` and
|
|
143
|
+
`body`) is exported for code that calls the HTTP layer directly.
|
|
144
|
+
|
|
145
|
+
| Situation | Result |
|
|
146
|
+
|---|---|
|
|
147
|
+
| Pair not in the table and not crossable | left out |
|
|
148
|
+
| Dated hint, no key | left out (dated tables need a key) |
|
|
149
|
+
| `allratestoday` plugin without a key | returns `[]` |
|
|
150
|
+
| 403 `market_rates_not_in_plan` / `historical_requires_paid_plan` | left out |
|
|
151
|
+
|
|
152
|
+
## 🔌 Adding your own source
|
|
153
|
+
|
|
154
|
+
Implement `RatePlugin` and put it anywhere in the engine's list. A plugin that reads a published table can reuse
|
|
155
|
+
`answerFromTable(rows, hints, date, pluginId)`, which handles direct, inverse and cross pairs.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
import { answerFromTable, type RatePlugin } from '@allratestoday/exchange-plugins'
|
|
159
|
+
|
|
160
|
+
export const myBank: RatePlugin = {
|
|
161
|
+
rateInfo: { pluginId: 'mybank', displayName: 'My Bank', keyless: true, homepage: 'https://example.org' },
|
|
162
|
+
async fetchRates(hints) {
|
|
163
|
+
const rows = [{ base: 'XYZ', quote: 'USD', value: 0.5, type: 'official' }]
|
|
164
|
+
return answerFromTable(rows, hints, '2026-10-19', 'mybank')
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## 🔗 Links
|
|
170
|
+
|
|
171
|
+
- Docs: https://allratestoday.com/docs/
|
|
172
|
+
- Central bank sources: https://allratestoday.com/central-bank-rates-api/
|
|
173
|
+
- Daily reference rate: https://allratestoday.com/reference-rate/
|
|
174
|
+
- JavaScript SDK: https://github.com/AllRates-Today/exchange-rates-api
|
|
175
|
+
- MCP server for AI agents: https://github.com/AllRates-Today/mcp-server
|
|
176
|
+
- edge-rates-server adapter: [adapters/edge-rates-server](./adapters/edge-rates-server/)
|
|
177
|
+
|
|
178
|
+
## 📜 License
|
|
179
|
+
|
|
180
|
+
MIT. Official tables are republished from each institution with attribution; see each source page on
|
|
181
|
+
allratestoday.com for the publisher's own terms.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# edge-rates-server provider
|
|
2
|
+
|
|
3
|
+
`allratestoday.ts` is a fiat/fiat rate provider in the shape
|
|
4
|
+
[edge-rates-server](https://github.com/EdgeApp/edge-rates-server) expects
|
|
5
|
+
(`(rateObj: ReturnRate[], currentTime: string) => Promise<NewRates>`).
|
|
6
|
+
|
|
7
|
+
1. Copy `allratestoday.ts` to `src/providers/allratestoday.ts`.
|
|
8
|
+
2. In `src/config.ts`, read `ALLRATESTODAY_API_KEY` from `process.env` and add
|
|
9
|
+
`allratestoday: { uri: 'https://allratestoday.com', apiKey: ALLRATESTODAY_API_KEY }`
|
|
10
|
+
to `providerDefaults`.
|
|
11
|
+
3. In `src/rates.ts`, import it and add `allratestoday` to `rateProviders`
|
|
12
|
+
(before `currencyConverter` to prefer it, after `openExchangeRates` to use
|
|
13
|
+
it as a last-resort fallback).
|
|
14
|
+
|
|
15
|
+
Without a key the provider answers today's pairs from the keyless daily
|
|
16
|
+
reference rate. With a key it also answers historical dates.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AllRatesToday provider for EdgeApp/edge-rates-server.
|
|
3
|
+
*
|
|
4
|
+
* Drop this file into `src/providers/` and register it in the
|
|
5
|
+
* `rateProviders` list in `src/rates.ts`, next to `currencyConverter` and
|
|
6
|
+
* `openExchangeRates`. It is a fiat/fiat provider: without a key it serves
|
|
7
|
+
* today's table from the keyless daily reference rate
|
|
8
|
+
* (https://allratestoday.com/api/open/reference-rate, 16:00 London, USD base);
|
|
9
|
+
* with ALLRATESTODAY_API_KEY set it also answers historical dates from
|
|
10
|
+
* `/api/v1/reference-rate/{date}`.
|
|
11
|
+
*
|
|
12
|
+
* Config (add to `providerDefaults` in `src/config.ts`):
|
|
13
|
+
*
|
|
14
|
+
* allratestoday: {
|
|
15
|
+
* uri: 'https://allratestoday.com',
|
|
16
|
+
* apiKey: ALLRATESTODAY_API_KEY
|
|
17
|
+
* }
|
|
18
|
+
*/
|
|
19
|
+
import { asArray, asNumber, asObject, asString } from 'cleaners'
|
|
20
|
+
import fetch from 'node-fetch'
|
|
21
|
+
|
|
22
|
+
import { config } from './../config'
|
|
23
|
+
import type { NewRates, ReturnRate } from './../rates'
|
|
24
|
+
import {
|
|
25
|
+
combineRates,
|
|
26
|
+
dateOnly,
|
|
27
|
+
fromCode,
|
|
28
|
+
isIsoCode,
|
|
29
|
+
logger,
|
|
30
|
+
subIso,
|
|
31
|
+
toCode
|
|
32
|
+
} from './../utils/utils'
|
|
33
|
+
|
|
34
|
+
const {
|
|
35
|
+
providers: {
|
|
36
|
+
allratestoday: { uri, apiKey }
|
|
37
|
+
}
|
|
38
|
+
} = config as unknown as {
|
|
39
|
+
providers: { allratestoday: { uri: string; apiKey?: string } }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const asAllRatesTodayResponse = asObject({
|
|
43
|
+
rate_date: asString,
|
|
44
|
+
base: asString,
|
|
45
|
+
rates: asArray(asObject({ quote: asString, value: asNumber }))
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const query = async (date: string, pairs: string[]): Promise<NewRates> => {
|
|
49
|
+
const rates: NewRates = { [date]: {} }
|
|
50
|
+
if (pairs.length === 0) return rates
|
|
51
|
+
const today = dateOnly(new Date().toISOString())
|
|
52
|
+
const day = dateOnly(date)
|
|
53
|
+
const isToday = day === today
|
|
54
|
+
if (!isToday && apiKey == null) return rates // dated tables need a key
|
|
55
|
+
|
|
56
|
+
const url = isToday
|
|
57
|
+
? `${uri}/api/open/reference-rate`
|
|
58
|
+
: `${uri}/api/v1/reference-rate/${day}`
|
|
59
|
+
const headers: Record<string, string> = {}
|
|
60
|
+
if (apiKey != null) headers.Authorization = `Bearer ${apiKey}`
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
const response = await fetch(url, { headers })
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`allratestoday returned with status: ${response.status} and error: ${response.statusText}`
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
const json = asAllRatesTodayResponse(await response.json())
|
|
70
|
+
// usdPer[X] = units of X per 1 USD
|
|
71
|
+
const usdPer: Record<string, number> = { [json.base]: 1 }
|
|
72
|
+
for (const r of json.rates) usdPer[r.quote] = r.value
|
|
73
|
+
|
|
74
|
+
for (const pair of pairs) {
|
|
75
|
+
const from = subIso(fromCode(pair))
|
|
76
|
+
const to = subIso(toCode(pair))
|
|
77
|
+
const a = usdPer[from]
|
|
78
|
+
const b = usdPer[to]
|
|
79
|
+
if (a == null || b == null || a === 0) continue
|
|
80
|
+
// units of `to` per 1 `from`
|
|
81
|
+
rates[date][pair] = (b / a).toString()
|
|
82
|
+
}
|
|
83
|
+
} catch (e) {
|
|
84
|
+
logger(`Failed to get ${pairs.length} pairs from allratestoday at ${date}`, e)
|
|
85
|
+
}
|
|
86
|
+
return rates
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const allratestoday = async (
|
|
90
|
+
rateObj: ReturnRate[],
|
|
91
|
+
currentTime: string
|
|
92
|
+
): Promise<NewRates> => {
|
|
93
|
+
const rates = {}
|
|
94
|
+
|
|
95
|
+
// Gather fiat/fiat pairs by date
|
|
96
|
+
const datesAndPairsWanted: Record<string, string[]> = {}
|
|
97
|
+
for (const pair of rateObj) {
|
|
98
|
+
const fromCurrency = fromCode(pair.currency_pair)
|
|
99
|
+
const toCurrency = toCode(pair.currency_pair)
|
|
100
|
+
if (!isIsoCode(fromCurrency) || !isIsoCode(toCurrency)) continue
|
|
101
|
+
if (datesAndPairsWanted[pair.date] == null)
|
|
102
|
+
datesAndPairsWanted[pair.date] = []
|
|
103
|
+
if (!datesAndPairsWanted[pair.date].includes(pair.currency_pair))
|
|
104
|
+
datesAndPairsWanted[pair.date].push(pair.currency_pair)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const providers = Object.keys(datesAndPairsWanted).map(
|
|
108
|
+
async date => await query(date, datesAndPairsWanted[date])
|
|
109
|
+
)
|
|
110
|
+
try {
|
|
111
|
+
const response = await Promise.all(providers)
|
|
112
|
+
combineRates(rates, response)
|
|
113
|
+
} catch (e) {
|
|
114
|
+
logger('Failed to query allratestoday with error', e)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return rates
|
|
118
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var allratestodayExchangePlugins=(()=>{var x=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var S=(t,n)=>{for(var a in n)x(t,a,{get:n[a],enumerable:!0})},H=(t,n,a,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of U(n))!q.call(t,r)&&r!==a&&x(t,r,{get:()=>n[r],enumerable:!(o=_(n,r))||o.enumerable});return t};var I=t=>H(x({},"__esModule",{value:!0}),t);var M={};S(M,{CENTRAL_BANK_CODES:()=>O,DEFAULT_BASE_URL:()=>A,ExchangePluginError:()=>f,answerFromTable:()=>y,centralBanks:()=>T,makeAllRatesTodayPlugin:()=>d,makeCentralBankPlugin:()=>h,makeDefaultPlugins:()=>D,makePlugins:()=>L,makeRateEngine:()=>E,makeReferenceRatePlugin:()=>P,plugins:()=>v,resolvePair:()=>B});var A="https://allratestoday.com",f=class extends Error{constructor(n,a,o){super(n),this.name="ExchangePluginError",this.status=a,this.body=o}};function g(t={}){let n=(t.baseUrl??A).replace(/\/$/,""),a=t.fetch??globalThis.fetch;if(typeof a!="function")throw new Error("No fetch available: pass { fetch } in the plugin options");let o=t.timeoutMs??1e4,r=t.apiKey;return{hasKey:typeof r=="string"&&r.length>0,async getJson(s,i={},e=!1){if(e&&!r)throw new f(`${s} needs an API key`,401,null);let u=new URL(n+s);for(let[b,m]of Object.entries(i))m!==""&&u.searchParams.set(b,m);let c={Accept:"application/json","User-Agent":"@allratestoday/exchange-plugins"};r&&(c.Authorization=`Bearer ${r}`);let p=typeof AbortController=="function"?new AbortController:void 0,R=p?setTimeout(()=>p.abort(),o):void 0;try{let b=await a(u.toString(),{headers:c,signal:p?.signal}),m=await b.text(),l=null;try{l=m?JSON.parse(m):null}catch{l=m}if(!b.ok){let $=l&&typeof l=="object"&&"error"in l?String(l.error):`HTTP ${b.status}`;throw new f($,b.status,l)}return l}finally{R&&clearTimeout(R)}}}}var d=(t={})=>{let n=g(t);return{rateInfo:{pluginId:"allratestoday",displayName:"AllRatesToday live mid-market",keyless:!1,homepage:"https://allratestoday.com/docs/"},async fetchRates(a){if(!n.hasKey)return[];let o=new Map;for(let s of a){if(s.date)continue;let i=s.fromCurrency.toUpperCase(),e=s.toCurrency.toUpperCase();if(i===e)continue;let u=o.get(i)??new Set;u.add(e),o.set(i,u)}let r=[];await Promise.all([...o].map(async([s,i])=>{let e;try{e=await n.getJson("/api/v1/rates",{source:s,target:[...i].join(",")},!0)}catch{return}let u=Array.isArray(e)?e:e?[e]:[];for(let c of u)typeof c?.rate!="number"||!c.target||r.push({fromCurrency:s,toCurrency:c.target.toUpperCase(),rate:c.rate,date:(c.time??new Date().toISOString()).slice(0,10),pluginId:"allratestoday",rateType:"mid-market",method:"published"})}));for(let s of a){if(s.date)continue;let i=s.fromCurrency.toUpperCase();i===s.toCurrency.toUpperCase()&&r.push({fromCurrency:i,toCurrency:i,rate:1,date:new Date().toISOString().slice(0,10),pluginId:"allratestoday",rateType:"mid-market",method:"published"})}return r}}};var k=t=>Number(t.toPrecision(12));function B(t,n,a){if(n===a)return{rate:1,method:"published",type:t[0]?.type??"reference"};let o=t.find(e=>e.base===n&&e.quote===a&&e.value>0);if(o)return{rate:o.value,method:"published",type:o.type};let r=t.find(e=>e.base===a&&e.quote===n&&e.value>0);if(r)return{rate:k(1/r.value),method:"inverse",type:r.type};let s=new Map,i=new Map;for(let e of t)e.value<=0||(e.quote===n&&s.set(e.base,e.value),e.base===n&&s.set(e.quote,k(1/e.value)),e.quote===a&&i.set(e.base,e.value),e.base===a&&i.set(e.quote,k(1/e.value)));for(let[e,u]of s){let c=i.get(e);if(c!==void 0){let p=t.find(R=>R.base===e||R.quote===e)?.type??"reference";return{rate:k(c/u),method:"cross",type:p}}}return null}function y(t,n,a,o,r){let s=[];for(let i of n){let e=i.fromCurrency.toUpperCase(),u=i.toCurrency.toUpperCase(),c=B(t,e,u);c&&s.push({fromCurrency:e,toCurrency:u,rate:c.rate,date:a,pluginId:o,rateType:r??c.type,method:c.method})}return s}function C(t){let n=new Map;for(let a of t){let o=a.date??"",r=n.get(o)??[];r.push(a),n.set(o,r)}return n}var N=new Set(["hmrc","bazg","ustreasury"]),h=(t,n={})=>{let a=t.toLowerCase(),o=N.has(a)?"tax-authority-rates-api":"central-bank-rates-api",r=g(n),s=i=>i.rates.map(e=>({base:e.base,quote:e.quote,value:e.value,type:e.type}));return{rateInfo:{pluginId:a,displayName:`Official rates: ${a.toUpperCase()}`,keyless:!0,homepage:`https://allratestoday.com/${o}/${a}/`},async fetchRates(i){let e=[];return await Promise.all([...C(i)].map(async([u,c])=>{let p;try{p=u?await r.getJson(`/api/v1/central-bank/${a}/${u}`,{},!0):await r.getJson(`/api/open/central-bank/${a}`)}catch{return}p?.rates?.length&&e.push(...y(s(p),c,p.rate_date,a))})),e}}},O=["amcm","bam","banguat","banxico","bazg","bb","bcb","bcbol","bcc","bcch","bccr","bccu","bceao","bch","bcm","bcn","bcp","bcra","bcrd","bcrp","bcstp","bct","bcu","bcv","bda","bdi","bdm","beac","bfm","bi","bmu","bna","bnb","bnm","bnr","bnrw","boa","bob","boc","boe","bog","bogy","boi","boj","bojm","bok","bol","bom","bon","bot","botz","bou","boz","brh","bsl","bsp","cba","cbar","cbb","cbbd","cbbh","cbbz","cbc","cbe","cbg","cbi","cbiq","cbj","cbk","cbke","cbl","cbm","cbn","cbo","cbr","cbsl","cbt","cbtt","cbu","cbuae","cbvs","cnb","composite","dnb","ecb","fed","hkma","hmrc","lb","mas","mma","mnb","nbc","nbe","nbg","nbk","nbkr","nbm","nbp","nbrb","nbrm","nbs","nbt","nbu","norges","nrb","pboc","pma","qcb","rba","rbf","rbi","rbm","rbnz","rbz","riksbank","rma","sama","sarb","sbp","sbv","sfc","snb","tcmb","ustreasury"],T=Object.fromEntries(O.map(t=>[t,n=>h(t,n)]));var P=(t={})=>{let n=g(t),a=o=>o.rates.map(r=>({base:r.base,quote:r.quote,value:r.value,type:"reference"}));return{rateInfo:{pluginId:"referenceRate",displayName:"AllRatesToday daily reference rate (16:00 London)",keyless:!0,homepage:"https://allratestoday.com/reference-rate/"},async fetchRates(o){let r=[];return await Promise.all([...C(o)].map(async([s,i])=>{let e;try{e=s?await n.getJson(`/api/v1/reference-rate/${s}`,{},!0):await n.getJson("/api/open/reference-rate")}catch{return}e?.rates?.length&&r.push(...y(a(e),i,e.rate_date,"referenceRate","reference"))})),r}}};var w=t=>`${t.fromCurrency.toUpperCase()}_${t.toCurrency.toUpperCase()}_${t.date??""}`;function E(t){let n=Array.isArray(t)?t:Object.values(t);return{plugins:n,async fetchRates(a){let o=new Map,r=a.slice();for(let s of n){if(r.length===0)break;let i=[];try{i=await s.fetchRates(r)}catch{continue}for(let e of i){let u=`${e.fromCurrency}_${e.toCurrency}_`;for(let c of r)w(c).startsWith(u)&&!o.has(w(c))&&o.set(w(c),e)}r=r.filter(e=>!o.has(w(e)))}return a.map(s=>o.get(w(s))).filter(s=>s!=null)},async getRate(a,o,r){let[s]=await this.fetchRates([{fromCurrency:a,toCurrency:o,date:r}]);return s??null},async convert(a,o,r,s){let i=await this.getRate(o,r,s);if(!i)throw new Error(`No plugin covers ${o}/${r}${s?` on ${s}`:""}`);return{amount:a,result:Number((a*i.rate).toPrecision(12)),pair:i}}}}var v={allratestoday:d,referenceRate:P,...T};function L(t,n={}){return t.map(a=>{let o=v[a];if(!o)throw new Error(`Unknown plugin: ${a}`);return o(n)})}function D(t={}){let n=[];return t.apiKey&&n.push(d(t)),n.push(P(t),h("composite",t)),n}typeof window<"u"&&typeof window.addAllRatesTodayPlugins=="function"&&window.addAllRatesTodayPlugins(v);return I(M);})();
|
|
2
|
+
//# sourceMappingURL=allratestoday-exchange-plugins.global.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/browser.ts","../src/http.ts","../src/plugins/allratestoday.ts","../src/table.ts","../src/plugins/centralBank.ts","../src/plugins/referenceRate.ts","../src/engine.ts","../src/index.ts"],"sourcesContent":["import * as api from './index';\n\n/**\n * Browser bundle. Loading `dist/allratestoday-exchange-plugins.global.js` exposes\n * `window.allratestodayExchangePlugins` and, if the page defined\n * `window.addAllRatesTodayPlugins` before the script ran, calls it with the\n * plugin map (the same hand-off edge-exchange-plugins makes to edge-core-js).\n */\ndeclare global {\n interface Window {\n addAllRatesTodayPlugins?: (plugins: typeof api.plugins) => void;\n }\n}\n\nif (typeof window !== 'undefined' && typeof window.addAllRatesTodayPlugins === 'function') {\n window.addAllRatesTodayPlugins(api.plugins);\n}\n\nexport * from './index';\n","import type { PluginOptions } from './types';\n\nexport const DEFAULT_BASE_URL = 'https://allratestoday.com';\n\nexport class ExchangePluginError extends Error {\n readonly status: number;\n readonly body: unknown;\n constructor(message: string, status: number, body: unknown) {\n super(message);\n this.name = 'ExchangePluginError';\n this.status = status;\n this.body = body;\n }\n}\n\nexport interface Http {\n getJson: (path: string, params?: Record<string, string>, requireKey?: boolean) => Promise<unknown>;\n hasKey: boolean;\n}\n\nexport function makeHttp(options: PluginOptions = {}): Http {\n const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n const doFetch = options.fetch ?? globalThis.fetch;\n if (typeof doFetch !== 'function') {\n throw new Error('No fetch available: pass { fetch } in the plugin options');\n }\n const timeoutMs = options.timeoutMs ?? 10_000;\n const apiKey = options.apiKey;\n\n return {\n hasKey: typeof apiKey === 'string' && apiKey.length > 0,\n async getJson(path, params = {}, requireKey = false) {\n if (requireKey && !apiKey) {\n throw new ExchangePluginError(`${path} needs an API key`, 401, null);\n }\n const url = new URL(base + path);\n for (const [k, v] of Object.entries(params)) if (v !== '') url.searchParams.set(k, v);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': '@allratestoday/exchange-plugins',\n };\n if (apiKey) headers.Authorization = `Bearer ${apiKey}`;\n const controller = typeof AbortController === 'function' ? new AbortController() : undefined;\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : undefined;\n try {\n const res = await doFetch(url.toString(), { headers, signal: controller?.signal });\n const text = await res.text();\n let body: unknown = null;\n try {\n body = text ? JSON.parse(text) : null;\n } catch {\n body = text;\n }\n if (!res.ok) {\n const msg =\n body && typeof body === 'object' && 'error' in body\n ? String((body as { error: unknown }).error)\n : `HTTP ${res.status}`;\n throw new ExchangePluginError(msg, res.status, body);\n }\n return body;\n } finally {\n if (timer) clearTimeout(timer);\n }\n },\n };\n}\n","import { makeHttp } from '../http';\nimport type { PluginOptions, RatePair, RatePlugin } from '../types';\n\ninterface LiveRate {\n rate: number;\n source: string;\n target: string;\n time: string;\n}\n\n/**\n * Live mid-market rates from `GET /api/v1/rates`. Needs an API key (the free\n * tier is 300 requests, no card). Answers only undated hints; dated hints are\n * left for the reference-rate or central-bank plugins.\n */\nexport const makeAllRatesTodayPlugin = (options: PluginOptions = {}): RatePlugin => {\n const http = makeHttp(options);\n return {\n rateInfo: {\n pluginId: 'allratestoday',\n displayName: 'AllRatesToday live mid-market',\n keyless: false,\n homepage: 'https://allratestoday.com/docs/',\n },\n async fetchRates(hints) {\n if (!http.hasKey) return [];\n const bySource = new Map<string, Set<string>>();\n for (const h of hints) {\n if (h.date) continue;\n const from = h.fromCurrency.toUpperCase();\n const to = h.toCurrency.toUpperCase();\n if (from === to) continue;\n const set = bySource.get(from) ?? new Set<string>();\n set.add(to);\n bySource.set(from, set);\n }\n const out: RatePair[] = [];\n await Promise.all(\n [...bySource].map(async ([source, targets]) => {\n let raw: unknown;\n try {\n raw = await http.getJson('/api/v1/rates', { source, target: [...targets].join(',') }, true);\n } catch {\n return;\n }\n const rows: LiveRate[] = Array.isArray(raw) ? raw : raw ? [raw as LiveRate] : [];\n for (const r of rows) {\n if (typeof r?.rate !== 'number' || !r.target) continue;\n out.push({\n fromCurrency: source,\n toCurrency: r.target.toUpperCase(),\n rate: r.rate,\n date: (r.time ?? new Date().toISOString()).slice(0, 10),\n pluginId: 'allratestoday',\n rateType: 'mid-market',\n method: 'published',\n });\n }\n }),\n );\n for (const h of hints) {\n if (h.date) continue;\n const from = h.fromCurrency.toUpperCase();\n if (from === h.toCurrency.toUpperCase()) {\n out.push({ fromCurrency: from, toCurrency: from, rate: 1, date: new Date().toISOString().slice(0, 10), pluginId: 'allratestoday', rateType: 'mid-market', method: 'published' });\n }\n }\n return out;\n },\n };\n};\n","import type { RateHint, RateMethod, RatePair } from './types';\n\n/** One row of a published table: `value` units of `quote` per 1 `base`. */\nexport interface TableRow {\n base: string;\n quote: string;\n value: number;\n type: string;\n}\n\nconst round = (n: number): number => Number(n.toPrecision(12));\n\n/**\n * Resolve a pair from a full table: direct row, inverted row, or a cross\n * through a currency both sides are quoted against. Returns null when the\n * table does not cover the pair.\n */\nexport function resolvePair(\n rows: TableRow[],\n from: string,\n to: string,\n): { rate: number; method: RateMethod; type: string } | null {\n if (from === to) return { rate: 1, method: 'published', type: rows[0]?.type ?? 'reference' };\n const direct = rows.find((r) => r.base === from && r.quote === to && r.value > 0);\n if (direct) return { rate: direct.value, method: 'published', type: direct.type };\n const inverse = rows.find((r) => r.base === to && r.quote === from && r.value > 0);\n if (inverse) return { rate: round(1 / inverse.value), method: 'inverse', type: inverse.type };\n\n // Cross: find a base B with rows B->from and B->to (the usual table shape),\n // or any mix of directions through B.\n const perBase = new Map<string, number>(); // B -> units of `from` per 1 B\n const perBaseTo = new Map<string, number>(); // B -> units of `to` per 1 B\n for (const r of rows) {\n if (r.value <= 0) continue;\n if (r.quote === from) perBase.set(r.base, r.value);\n if (r.base === from) perBase.set(r.quote, round(1 / r.value));\n if (r.quote === to) perBaseTo.set(r.base, r.value);\n if (r.base === to) perBaseTo.set(r.quote, round(1 / r.value));\n }\n for (const [b, fromPerB] of perBase) {\n const toPerB = perBaseTo.get(b);\n if (toPerB !== undefined) {\n const type = rows.find((r) => r.base === b || r.quote === b)?.type ?? 'reference';\n return { rate: round(toPerB / fromPerB), method: 'cross', type };\n }\n }\n return null;\n}\n\nexport function answerFromTable(\n rows: TableRow[],\n hints: RateHint[],\n date: string,\n pluginId: string,\n rateType?: string,\n): RatePair[] {\n const out: RatePair[] = [];\n for (const h of hints) {\n const from = h.fromCurrency.toUpperCase();\n const to = h.toCurrency.toUpperCase();\n const hit = resolvePair(rows, from, to);\n if (!hit) continue;\n out.push({\n fromCurrency: from,\n toCurrency: to,\n rate: hit.rate,\n date,\n pluginId,\n rateType: rateType ?? hit.type,\n method: hit.method,\n });\n }\n return out;\n}\n\n/** Group hints by requested date; `''` holds the \"latest\" hints. */\nexport function groupByDate(hints: RateHint[]): Map<string, RateHint[]> {\n const m = new Map<string, RateHint[]>();\n for (const h of hints) {\n const key = h.date ?? '';\n const list = m.get(key) ?? [];\n list.push(h);\n m.set(key, list);\n }\n return m;\n}\n","import { makeHttp } from '../http';\nimport { answerFromTable, groupByDate, type TableRow } from '../table';\nimport type { PluginOptions, RatePair, RatePlugin } from '../types';\n\ninterface TableResponse {\n bank: string;\n rate_date: string;\n rates: Array<{ base: string; quote: string; type: string; value: number }>;\n}\n\n/**\n * Official exchange-rate tables published by a central bank or tax authority,\n * served by AllRatesToday. The latest table is keyless\n * (`/api/open/central-bank/{bank}`); dated tables\n * (`/api/v1/central-bank/{bank}/{date}`) need a paid key. Pairs the\n * institution does not publish directly are inverted or crossed through its\n * home currency, and the answer says so in `method`.\n *\n * `bank` is an AllRatesToday source code, e.g. `ecb`, `boe`, `rbi`, `hmrc`.\n * The full list is `GET https://allratestoday.com/api/open/central-banks`.\n */\n/** Tax authorities live under a different page base on allratestoday.com. */\nconst TAX_AUTHORITIES = new Set(['hmrc', 'bazg', 'ustreasury']);\n\nexport const makeCentralBankPlugin = (bank: string, options: PluginOptions = {}): RatePlugin => {\n const code = bank.toLowerCase();\n const pageBase = TAX_AUTHORITIES.has(code) ? 'tax-authority-rates-api' : 'central-bank-rates-api';\n const http = makeHttp(options);\n const toRows = (r: TableResponse): TableRow[] =>\n r.rates.map((x) => ({ base: x.base, quote: x.quote, value: x.value, type: x.type }));\n return {\n rateInfo: {\n pluginId: code,\n displayName: `Official rates: ${code.toUpperCase()}`,\n keyless: true,\n homepage: `https://allratestoday.com/${pageBase}/${code}/`,\n },\n async fetchRates(hints) {\n const out: RatePair[] = [];\n await Promise.all(\n [...groupByDate(hints)].map(async ([date, group]) => {\n let raw: TableResponse;\n try {\n raw = (\n date\n ? await http.getJson(`/api/v1/central-bank/${code}/${date}`, {}, true)\n : await http.getJson(`/api/open/central-bank/${code}`)\n ) as TableResponse;\n } catch {\n return;\n }\n if (!raw?.rates?.length) return;\n out.push(...answerFromTable(toRows(raw), group, raw.rate_date, code));\n }),\n );\n return out;\n },\n };\n};\n\n/**\n * Source codes served by AllRatesToday on 2026-10-19 (125). `composite` is the\n * cross-bank USD table. Refresh with `GET /api/open/central-banks`.\n */\nexport const CENTRAL_BANK_CODES = [\n 'amcm', 'bam', 'banguat', 'banxico', 'bazg', 'bb', 'bcb', 'bcbol', 'bcc', 'bcch', 'bccr', 'bccu', 'bceao', 'bch',\n 'bcm', 'bcn', 'bcp', 'bcra', 'bcrd', 'bcrp', 'bcstp', 'bct', 'bcu', 'bcv', 'bda', 'bdi', 'bdm', 'beac', 'bfm', 'bi',\n 'bmu', 'bna', 'bnb', 'bnm', 'bnr', 'bnrw', 'boa', 'bob', 'boc', 'boe', 'bog', 'bogy', 'boi', 'boj', 'bojm', 'bok',\n 'bol', 'bom', 'bon', 'bot', 'botz', 'bou', 'boz', 'brh', 'bsl', 'bsp', 'cba', 'cbar', 'cbb', 'cbbd', 'cbbh', 'cbbz',\n 'cbc', 'cbe', 'cbg', 'cbi', 'cbiq', 'cbj', 'cbk', 'cbke', 'cbl', 'cbm', 'cbn', 'cbo', 'cbr', 'cbsl', 'cbt', 'cbtt',\n 'cbu', 'cbuae', 'cbvs', 'cnb', 'composite', 'dnb', 'ecb', 'fed', 'hkma', 'hmrc', 'lb', 'mas', 'mma', 'mnb', 'nbc',\n 'nbe', 'nbg', 'nbk', 'nbkr', 'nbm', 'nbp', 'nbrb', 'nbrm', 'nbs', 'nbt', 'nbu', 'norges', 'nrb', 'pboc', 'pma',\n 'qcb', 'rba', 'rbf', 'rbi', 'rbm', 'rbnz', 'rbz', 'riksbank', 'rma', 'sama', 'sarb', 'sbp', 'sbv', 'sfc', 'snb',\n 'tcmb', 'ustreasury',\n] as const;\n\nexport type CentralBankCode = (typeof CENTRAL_BANK_CODES)[number];\n\n/** One factory per source, keyed by code: `centralBanks.ecb()`, `centralBanks.boe()`, ... */\nexport const centralBanks = Object.fromEntries(\n CENTRAL_BANK_CODES.map((code) => [code, (options?: PluginOptions) => makeCentralBankPlugin(code, options)]),\n) as Record<CentralBankCode, (options?: PluginOptions) => RatePlugin>;\n","import { makeHttp } from '../http';\nimport { answerFromTable, groupByDate, type TableRow } from '../table';\nimport type { PluginOptions, RatePair, RatePlugin } from '../types';\n\ninterface ReferenceResponse {\n rate_date: string;\n base: string;\n rates: Array<{ base: string; quote: string; value: number }>;\n}\n\n/**\n * The AllRatesToday daily reference rate: one USD-based table a day, fixed at\n * 16:00 London. The latest table is keyless (`/api/open/reference-rate`);\n * dated tables (`/api/v1/reference-rate/{date}`) need an API key. Any pair is\n * crossed through USD.\n */\nexport const makeReferenceRatePlugin = (options: PluginOptions = {}): RatePlugin => {\n const http = makeHttp(options);\n const toRows = (r: ReferenceResponse): TableRow[] =>\n r.rates.map((x) => ({ base: x.base, quote: x.quote, value: x.value, type: 'reference' }));\n return {\n rateInfo: {\n pluginId: 'referenceRate',\n displayName: 'AllRatesToday daily reference rate (16:00 London)',\n keyless: true,\n homepage: 'https://allratestoday.com/reference-rate/',\n },\n async fetchRates(hints) {\n const out: RatePair[] = [];\n await Promise.all(\n [...groupByDate(hints)].map(async ([date, group]) => {\n let raw: ReferenceResponse;\n try {\n raw = (\n date\n ? await http.getJson(`/api/v1/reference-rate/${date}`, {}, true)\n : await http.getJson('/api/open/reference-rate')\n ) as ReferenceResponse;\n } catch {\n return;\n }\n if (!raw?.rates?.length) return;\n out.push(...answerFromTable(toRows(raw), group, raw.rate_date, 'referenceRate', 'reference'));\n }),\n );\n return out;\n },\n };\n};\n","import type { RateHint, RatePair, RatePlugin } from './types';\n\nexport interface RateEngine {\n readonly plugins: RatePlugin[];\n /** Ask each plugin in order; a hint answered by an earlier plugin is not asked again. */\n fetchRates: (hints: RateHint[]) => Promise<RatePair[]>;\n /** One pair, or null when no plugin covers it. */\n getRate: (fromCurrency: string, toCurrency: string, date?: string) => Promise<RatePair | null>;\n /** Convert an amount; throws when no plugin covers the pair. */\n convert: (amount: number, fromCurrency: string, toCurrency: string, date?: string) => Promise<{ amount: number; result: number; pair: RatePair }>;\n}\n\nconst key = (h: RateHint): string =>\n `${h.fromCurrency.toUpperCase()}_${h.toCurrency.toUpperCase()}_${h.date ?? ''}`;\n\n/**\n * Ordered fallback over plugins. Pass the plugins in preference order, e.g.\n * live first, then the daily reference rate, then an official table.\n */\nexport function makeRateEngine(plugins: RatePlugin[] | Record<string, RatePlugin>): RateEngine {\n const list = Array.isArray(plugins) ? plugins : Object.values(plugins);\n return {\n plugins: list,\n async fetchRates(hints) {\n const answered = new Map<string, RatePair>();\n let remaining = hints.slice();\n for (const plugin of list) {\n if (remaining.length === 0) break;\n let pairs: RatePair[] = [];\n try {\n pairs = await plugin.fetchRates(remaining);\n } catch {\n continue;\n }\n for (const p of pairs) {\n const k = `${p.fromCurrency}_${p.toCurrency}_`;\n // Match on the requested date, not the answered one (weekends\n // resolve to the previous business day).\n for (const h of remaining) {\n if (key(h).startsWith(k) && !answered.has(key(h))) answered.set(key(h), p);\n }\n }\n remaining = remaining.filter((h) => !answered.has(key(h)));\n }\n return hints.map((h) => answered.get(key(h))).filter((p): p is RatePair => p != null);\n },\n async getRate(fromCurrency, toCurrency, date) {\n const [pair] = await this.fetchRates([{ fromCurrency, toCurrency, date }]);\n return pair ?? null;\n },\n async convert(amount, fromCurrency, toCurrency, date) {\n const pair = await this.getRate(fromCurrency, toCurrency, date);\n if (!pair) throw new Error(`No plugin covers ${fromCurrency}/${toCurrency}${date ? ` on ${date}` : ''}`);\n return { amount, result: Number((amount * pair.rate).toPrecision(12)), pair };\n },\n };\n}\n","import { makeAllRatesTodayPlugin } from './plugins/allratestoday';\nimport { centralBanks, makeCentralBankPlugin } from './plugins/centralBank';\nimport { makeReferenceRatePlugin } from './plugins/referenceRate';\nimport type { PluginOptions, RatePlugin } from './types';\n\nexport * from './types';\nexport { ExchangePluginError, DEFAULT_BASE_URL } from './http';\nexport { resolvePair, answerFromTable } from './table';\nexport type { TableRow } from './table';\nexport { makeRateEngine } from './engine';\nexport type { RateEngine } from './engine';\nexport { makeAllRatesTodayPlugin } from './plugins/allratestoday';\nexport { makeReferenceRatePlugin } from './plugins/referenceRate';\nexport { makeCentralBankPlugin, centralBanks, CENTRAL_BANK_CODES } from './plugins/centralBank';\nexport type { CentralBankCode } from './plugins/centralBank';\n\n/**\n * Every plugin factory in this package, keyed by pluginId. Mirrors the\n * `plugins` export of edge-exchange-plugins: pick the ones you want, or\n * register them all.\n */\nexport const plugins = {\n // Live:\n allratestoday: makeAllRatesTodayPlugin,\n // Daily reference:\n referenceRate: makeReferenceRatePlugin,\n // Official tables (125 sources):\n ...centralBanks,\n};\n\nexport type PluginId = keyof typeof plugins;\n\n/**\n * Instantiate a set of plugins with shared options. Pass ids in preference\n * order; the result is ready for `makeRateEngine`.\n */\nexport function makePlugins(ids: PluginId[], options: PluginOptions = {}): RatePlugin[] {\n return ids.map((id) => {\n const factory = plugins[id];\n if (!factory) throw new Error(`Unknown plugin: ${id}`);\n return factory(options);\n });\n}\n\n/** The recommended default stack: live when a key is set, then reference rate, then the composite table. */\nexport function makeDefaultPlugins(options: PluginOptions = {}): RatePlugin[] {\n const list: RatePlugin[] = [];\n if (options.apiKey) list.push(makeAllRatesTodayPlugin(options));\n list.push(makeReferenceRatePlugin(options), makeCentralBankPlugin('composite', options));\n return list;\n}\n\nexport default plugins;\n"],"mappings":"gdAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,qBAAAC,EAAA,wBAAAC,EAAA,oBAAAC,EAAA,iBAAAC,EAAA,4BAAAC,EAAA,0BAAAC,EAAA,uBAAAC,EAAA,gBAAAC,EAAA,mBAAAC,EAAA,4BAAAC,EAAA,YAAAC,EAAA,gBAAAC,ICEO,IAAMC,EAAmB,4BAEnBC,EAAN,cAAkC,KAAM,CAG7C,YAAYC,EAAiBC,EAAgBC,EAAe,CAC1D,MAAMF,CAAO,EACb,KAAK,KAAO,sBACZ,KAAK,OAASC,EACd,KAAK,KAAOC,CACd,CACF,EAOO,SAASC,EAASC,EAAyB,CAAC,EAAS,CAC1D,IAAMC,GAAQD,EAAQ,SAAWN,GAAkB,QAAQ,MAAO,EAAE,EAC9DQ,EAAUF,EAAQ,OAAS,WAAW,MAC5C,GAAI,OAAOE,GAAY,WACrB,MAAM,IAAI,MAAM,0DAA0D,EAE5E,IAAMC,EAAYH,EAAQ,WAAa,IACjCI,EAASJ,EAAQ,OAEvB,MAAO,CACL,OAAQ,OAAOI,GAAW,UAAYA,EAAO,OAAS,EACtD,MAAM,QAAQC,EAAMC,EAAS,CAAC,EAAGC,EAAa,GAAO,CACnD,GAAIA,GAAc,CAACH,EACjB,MAAM,IAAIT,EAAoB,GAAGU,CAAI,oBAAqB,IAAK,IAAI,EAErE,IAAMG,EAAM,IAAI,IAAIP,EAAOI,CAAI,EAC/B,OAAW,CAACI,EAAGC,CAAC,IAAK,OAAO,QAAQJ,CAAM,EAAOI,IAAM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,CAAC,EAC5B,OAAIJ,EAAQ,QAAQI,EAAK,KAAKT,EAAwBK,CAAO,CAAC,EAC9DI,EAAK,KAAKR,EAAwBI,CAAO,EAAGK,EAAsB,YAAaL,CAAO,CAAC,EAChFI,CACT,CPpCI,OAAO,OAAW,KAAe,OAAO,OAAO,yBAA4B,YAC7E,OAAO,wBAA4BE,CAAO","names":["browser_exports","__export","CENTRAL_BANK_CODES","DEFAULT_BASE_URL","ExchangePluginError","answerFromTable","centralBanks","makeAllRatesTodayPlugin","makeCentralBankPlugin","makeDefaultPlugins","makePlugins","makeRateEngine","makeReferenceRatePlugin","plugins","resolvePair","DEFAULT_BASE_URL","ExchangePluginError","message","status","body","makeHttp","options","base","doFetch","timeoutMs","apiKey","path","params","requireKey","url","k","v","headers","controller","timer","res","text","msg","makeAllRatesTodayPlugin","options","http","makeHttp","hints","bySource","h","from","to","set","out","source","targets","raw","rows","r","round","n","resolvePair","rows","from","to","direct","r","inverse","perBase","perBaseTo","b","fromPerB","toPerB","type","answerFromTable","hints","date","pluginId","rateType","out","h","hit","groupByDate","m","key","list","TAX_AUTHORITIES","makeCentralBankPlugin","bank","options","code","pageBase","http","makeHttp","toRows","r","x","hints","out","groupByDate","date","group","raw","answerFromTable","CENTRAL_BANK_CODES","centralBanks","makeReferenceRatePlugin","options","http","makeHttp","toRows","r","x","hints","out","groupByDate","date","group","raw","answerFromTable","key","h","makeRateEngine","plugins","list","hints","answered","remaining","plugin","pairs","p","k","fromCurrency","toCurrency","date","pair","amount","plugins","makeAllRatesTodayPlugin","makeReferenceRatePlugin","centralBanks","makePlugins","ids","options","id","factory","makeDefaultPlugins","list","makeCentralBankPlugin","plugins"]}
|