@routstr/sdk 0.3.6 → 0.3.7

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.
Files changed (39) hide show
  1. package/package.json +2 -2
  2. package/dist/client/index.d.mts +0 -411
  3. package/dist/client/index.d.ts +0 -411
  4. package/dist/client/index.js +0 -4824
  5. package/dist/client/index.js.map +0 -1
  6. package/dist/client/index.mjs +0 -4818
  7. package/dist/client/index.mjs.map +0 -1
  8. package/dist/discovery/index.d.mts +0 -213
  9. package/dist/discovery/index.d.ts +0 -213
  10. package/dist/discovery/index.js +0 -735
  11. package/dist/discovery/index.js.map +0 -1
  12. package/dist/discovery/index.mjs +0 -732
  13. package/dist/discovery/index.mjs.map +0 -1
  14. package/dist/index.d.mts +0 -192
  15. package/dist/index.d.ts +0 -192
  16. package/dist/index.js +0 -6240
  17. package/dist/index.js.map +0 -1
  18. package/dist/index.mjs +0 -6191
  19. package/dist/index.mjs.map +0 -1
  20. package/dist/interfaces-Bp0Ngmqv.d.mts +0 -176
  21. package/dist/interfaces-Cqkt41QR.d.mts +0 -118
  22. package/dist/interfaces-D2FDCLyP.d.ts +0 -176
  23. package/dist/interfaces-D9qI1ym6.d.ts +0 -118
  24. package/dist/storage/index.d.mts +0 -87
  25. package/dist/storage/index.d.ts +0 -87
  26. package/dist/storage/index.js +0 -1740
  27. package/dist/storage/index.js.map +0 -1
  28. package/dist/storage/index.mjs +0 -1718
  29. package/dist/storage/index.mjs.map +0 -1
  30. package/dist/store-BFUGGr_v.d.ts +0 -172
  31. package/dist/store-C4FyyOnO.d.mts +0 -172
  32. package/dist/types-DPQM6tIG.d.mts +0 -234
  33. package/dist/types-DPQM6tIG.d.ts +0 -234
  34. package/dist/wallet/index.d.mts +0 -245
  35. package/dist/wallet/index.d.ts +0 -245
  36. package/dist/wallet/index.js +0 -1329
  37. package/dist/wallet/index.js.map +0 -1
  38. package/dist/wallet/index.mjs +0 -1326
  39. package/dist/wallet/index.mjs.map +0 -1
@@ -1,732 +0,0 @@
1
- import { RelayPool, onlyEvents } from 'applesauce-relay';
2
- import { EventStore } from 'applesauce-core';
3
- import { tap } from 'rxjs';
4
-
5
- // core/types.ts
6
- function makeConsoleLogger(prefix) {
7
- const fmt = (args) => prefix ? [prefix, ...args] : args;
8
- return {
9
- log: (...args) => console.log(...fmt(args)),
10
- warn: (...args) => console.warn(...fmt(args)),
11
- error: (...args) => console.error(...fmt(args)),
12
- debug: (...args) => console.log(...fmt(args)),
13
- child: (p) => makeConsoleLogger(prefix ? `${prefix}:${p}` : p)
14
- };
15
- }
16
- var consoleLogger = makeConsoleLogger();
17
-
18
- // core/errors.ts
19
- var ProviderBootstrapError = class extends Error {
20
- constructor(failedProviders, message) {
21
- super(
22
- message || `Failed to bootstrap providers. Tried: ${failedProviders.join(", ")}`
23
- );
24
- this.failedProviders = failedProviders;
25
- this.name = "ProviderBootstrapError";
26
- }
27
- };
28
- var NoProvidersAvailableError = class extends Error {
29
- constructor() {
30
- super("No providers are available for model discovery");
31
- this.name = "NoProvidersAvailableError";
32
- }
33
- };
34
- var ModelManager = class _ModelManager {
35
- constructor(adapter, config = {}) {
36
- this.adapter = adapter;
37
- this.providerDirectoryUrl = config.providerDirectoryUrl || "https://api.routstr.com/v1/providers/";
38
- this.cacheTTL = config.cacheTTL || 210 * 60 * 1e3;
39
- this.includeProviderUrls = config.includeProviderUrls || [];
40
- this.excludeProviderUrls = config.excludeProviderUrls || [];
41
- this.routstrPubkey = config.routstrPubkey || "4ad6fa2d16e2a9b576c863b4cf7404a70d4dc320c0c447d10ad6ff58993eacc8";
42
- this.logger = (config.logger ?? consoleLogger).child("ModelManager");
43
- }
44
- cacheTTL;
45
- providerDirectoryUrl;
46
- includeProviderUrls;
47
- excludeProviderUrls;
48
- routstrPubkey;
49
- logger;
50
- providerNodePubkeysByUrl = /* @__PURE__ */ new Map();
51
- /**
52
- * Get the list of bootstrapped provider base URLs
53
- * @returns Array of provider base URLs
54
- */
55
- getBaseUrls() {
56
- return this.adapter.getBaseUrlsList();
57
- }
58
- static async init(adapter, config = {}, options = {}) {
59
- const manager = new _ModelManager(adapter, config);
60
- const torMode = options.torMode ?? false;
61
- const forceRefresh = options.forceRefresh ?? false;
62
- const providers = await manager.bootstrapProviders(torMode, forceRefresh);
63
- await manager.fetchModels(providers, forceRefresh);
64
- return manager;
65
- }
66
- /**
67
- * Bootstrap provider list from the provider directory
68
- * First tries to fetch from Nostr (kind 30421), falls back to HTTP
69
- * @param torMode Whether running in Tor context
70
- * @param forceRefresh Ignore provider cache and refresh provider sources
71
- * @returns Array of provider base URLs
72
- * @throws ProviderBootstrapError if all providers fail to fetch
73
- */
74
- async bootstrapProviders(torMode = false, forceRefresh = false) {
75
- if (!forceRefresh) {
76
- const cachedUrls = this.adapter.getBaseUrlsList();
77
- if (cachedUrls.length > 0) {
78
- const lastUpdate = this.adapter.getBaseUrlsLastUpdate();
79
- const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
80
- if (cacheValid) {
81
- const filteredCachedUrls = this.filterBaseUrlsForTor(
82
- cachedUrls,
83
- torMode
84
- );
85
- await this.fetchRoutstr21Models(forceRefresh);
86
- await this.syncReviewedProvidersFromNostr(filteredCachedUrls);
87
- return filteredCachedUrls;
88
- }
89
- }
90
- }
91
- try {
92
- const nostrProviders = await this.bootstrapFromNostr(38421, torMode);
93
- if (nostrProviders.length > 0) {
94
- const filtered = this.filterBaseUrlsForTor(nostrProviders, torMode);
95
- this.adapter.setBaseUrlsList(filtered);
96
- this.adapter.setBaseUrlsLastUpdate(Date.now());
97
- await this.fetchRoutstr21Models(forceRefresh);
98
- await this.syncReviewedProvidersFromNostr(filtered);
99
- return filtered;
100
- }
101
- } catch (e) {
102
- this.logger.warn("Nostr bootstrap failed, falling back to HTTP:", e);
103
- }
104
- return this.bootstrapFromHttp(torMode, forceRefresh);
105
- }
106
- /**
107
- * Bootstrap providers from Nostr network (kind 30421)
108
- * @param kind The Nostr kind to fetch
109
- * @param torMode Whether running in Tor context
110
- * @returns Array of provider base URLs
111
- */
112
- async bootstrapFromNostr(kind, torMode) {
113
- const DEFAULT_RELAYS = [
114
- "wss://relay.primal.net",
115
- "wss://nos.lol",
116
- "wss://relay.damus.io"
117
- ];
118
- const pool = new RelayPool();
119
- const localEventStore = new EventStore();
120
- const timeoutMs = 5e3;
121
- await new Promise((resolve) => {
122
- pool.req(DEFAULT_RELAYS, {
123
- kinds: [kind],
124
- limit: 100
125
- }).pipe(
126
- onlyEvents(),
127
- tap((event) => {
128
- localEventStore.add(event);
129
- })
130
- ).subscribe({
131
- complete: () => {
132
- resolve();
133
- }
134
- });
135
- setTimeout(() => {
136
- resolve();
137
- }, timeoutMs);
138
- });
139
- const timeline = localEventStore.getTimeline({ kinds: [kind] });
140
- const bases = /* @__PURE__ */ new Set();
141
- this.providerNodePubkeysByUrl = /* @__PURE__ */ new Map();
142
- for (const event of timeline) {
143
- const eventUrls = [];
144
- for (const tag of event.tags) {
145
- if (tag[0] === "u" && typeof tag[1] === "string") {
146
- eventUrls.push(tag[1]);
147
- }
148
- }
149
- if (eventUrls.length > 0) {
150
- for (const url of eventUrls) {
151
- const normalized = this.normalizeUrl(url);
152
- if (!torMode || normalized.includes(".onion")) {
153
- bases.add(normalized);
154
- this.addProviderNode(
155
- this.providerNodePubkeysByUrl,
156
- normalized,
157
- event.pubkey
158
- );
159
- }
160
- }
161
- continue;
162
- }
163
- try {
164
- const content = JSON.parse(event.content);
165
- const providers = Array.isArray(content) ? content : content.providers || [];
166
- for (const p of providers) {
167
- const endpoints = this.getProviderEndpoints(p, torMode);
168
- for (const endpoint of endpoints) {
169
- bases.add(endpoint);
170
- this.addProviderNode(
171
- this.providerNodePubkeysByUrl,
172
- endpoint,
173
- p?.pubkey || event.pubkey
174
- );
175
- }
176
- }
177
- } catch {
178
- try {
179
- const providers = JSON.parse(event.content);
180
- if (Array.isArray(providers)) {
181
- for (const p of providers) {
182
- const endpoints = this.getProviderEndpoints(p, torMode);
183
- for (const endpoint of endpoints) {
184
- bases.add(endpoint);
185
- this.addProviderNode(
186
- this.providerNodePubkeysByUrl,
187
- endpoint,
188
- p?.pubkey || event.pubkey
189
- );
190
- }
191
- }
192
- }
193
- } catch {
194
- this.logger.warn(
195
- "NostrBootstrap: failed to parse event content:",
196
- event.id
197
- );
198
- }
199
- }
200
- }
201
- for (const url of this.includeProviderUrls) {
202
- const normalized = this.normalizeUrl(url);
203
- if (!torMode || normalized.includes(".onion")) {
204
- bases.add(normalized);
205
- }
206
- }
207
- const excluded = new Set(
208
- this.excludeProviderUrls.map((url) => this.normalizeUrl(url))
209
- );
210
- const result = Array.from(bases).filter((base) => !excluded.has(base));
211
- return result;
212
- }
213
- /**
214
- * Bootstrap providers from HTTP endpoint
215
- * @param torMode Whether running in Tor context
216
- * @param forceRefresh Ignore routstr21 cache and fetch fresh data
217
- * @returns Array of provider base URLs
218
- */
219
- async bootstrapFromHttp(torMode, forceRefresh = false) {
220
- try {
221
- const res = await fetch(this.providerDirectoryUrl);
222
- if (!res.ok) {
223
- throw new Error(`Failed to fetch providers: ${res.status}`);
224
- }
225
- const data = await res.json();
226
- const providers = Array.isArray(data?.providers) ? data.providers : [];
227
- const bases = /* @__PURE__ */ new Set();
228
- this.providerNodePubkeysByUrl = /* @__PURE__ */ new Map();
229
- for (const p of providers) {
230
- const endpoints = this.getProviderEndpoints(p, torMode);
231
- for (const endpoint of endpoints) {
232
- bases.add(endpoint);
233
- this.addProviderNode(this.providerNodePubkeysByUrl, endpoint, p?.pubkey);
234
- }
235
- }
236
- for (const url of this.includeProviderUrls) {
237
- const normalized = this.normalizeUrl(url);
238
- if (!torMode || normalized.includes(".onion")) {
239
- bases.add(normalized);
240
- }
241
- }
242
- const excluded = new Set(
243
- this.excludeProviderUrls.map((url) => this.normalizeUrl(url))
244
- );
245
- const list = Array.from(bases).filter((base) => !excluded.has(base));
246
- if (list.length > 0) {
247
- this.adapter.setBaseUrlsList(list);
248
- this.adapter.setBaseUrlsLastUpdate(Date.now());
249
- await this.fetchRoutstr21Models(forceRefresh);
250
- await this.syncReviewedProvidersFromNostr(list);
251
- }
252
- return list;
253
- } catch (e) {
254
- this.logger.error("Failed to bootstrap providers", e);
255
- throw new ProviderBootstrapError([], `Provider bootstrap failed: ${e}`);
256
- }
257
- }
258
- /**
259
- * Fetch Routstr review events from Nostr (kind 38425) and disable providers
260
- * whose 38421 node pubkey does not have at least one review tagged `t=lgtm`.
261
- *
262
- * Review events are expected to have:
263
- * - `node`: the reviewed 38421 provider event pubkey
264
- * - `t`: review label, where `lgtm` means the node looks good
265
- *
266
- * @param baseUrls Current provider base URLs to evaluate
267
- * @returns Array of provider base URLs disabled by the review set
268
- */
269
- async syncReviewedProvidersFromNostr(baseUrls = this.adapter.getBaseUrlsList(), providerNodes = this.providerNodePubkeysByUrl) {
270
- if (baseUrls.length === 0) return [];
271
- if (!this.adapter.setDisabledProviders) {
272
- this.logger.warn(
273
- "NostrReviews: adapter does not support setDisabledProviders; skipping provider disable sync"
274
- );
275
- return [];
276
- }
277
- const LGTM_RELAYS = [
278
- "wss://relay.primal.net",
279
- "wss://nos.lol",
280
- "wss://relay.damus.io",
281
- "wss://relay.routstr.com"
282
- ];
283
- const reviewedNodePubkeys = /* @__PURE__ */ new Set();
284
- {
285
- const pool = new RelayPool();
286
- const store = new EventStore();
287
- const timeoutMs = 5e3;
288
- await new Promise((resolve) => {
289
- pool.req(LGTM_RELAYS, {
290
- kinds: [38425],
291
- "#t": ["lgtm"],
292
- limit: 500,
293
- authors: [this.routstrPubkey]
294
- }).pipe(
295
- onlyEvents(),
296
- tap((event) => store.add(event))
297
- ).subscribe({ complete: () => resolve() });
298
- setTimeout(() => resolve(), timeoutMs);
299
- });
300
- for (const event of store.getTimeline({ kinds: [38425] })) {
301
- const hasLgtmTag = event.tags.some(
302
- (tag) => tag[0] === "t" && tag[1]?.toLowerCase() === "lgtm"
303
- );
304
- if (!hasLgtmTag) continue;
305
- for (const tag of event.tags) {
306
- if (tag[0] === "node" && typeof tag[1] === "string" && tag[1]) {
307
- reviewedNodePubkeys.add(tag[1]);
308
- }
309
- }
310
- }
311
- }
312
- if (reviewedNodePubkeys.size === 0) {
313
- this.logger.warn(
314
- "NostrReviews: no kind 38425 lgtm reviews found; keeping disabled providers unchanged"
315
- );
316
- return [];
317
- }
318
- if (providerNodes.size === 0) {
319
- this.logger.warn(
320
- "NostrReviews: no kind 38421 provider node metadata found; keeping disabled providers unchanged"
321
- );
322
- return [];
323
- }
324
- const disabledByReview = [];
325
- for (const url of baseUrls) {
326
- const normalized = this.normalizeUrl(url);
327
- const nodePubkeys = providerNodes.get(normalized) || /* @__PURE__ */ new Set();
328
- const hasLgtmReview = Array.from(nodePubkeys).some(
329
- (pubkey) => reviewedNodePubkeys.has(pubkey)
330
- );
331
- if (!hasLgtmReview) {
332
- disabledByReview.push(normalized);
333
- }
334
- }
335
- this.adapter.setDisabledProviders(Array.from(new Set(disabledByReview)));
336
- return disabledByReview;
337
- }
338
- addProviderNode(map, url, pubkey) {
339
- if (!pubkey) return;
340
- const normalized = this.normalizeUrl(url);
341
- const existing = map.get(normalized) || /* @__PURE__ */ new Set();
342
- existing.add(pubkey);
343
- map.set(normalized, existing);
344
- }
345
- /**
346
- * Fetch models from all providers and select best-priced options
347
- * Uses cache if available and not expired
348
- * @param baseUrls List of provider base URLs to fetch from
349
- * @param forceRefresh Ignore cache and fetch fresh data
350
- * @param onProgress Callback fired after each provider completes with current combined models
351
- * @returns Array of unique models with best prices selected
352
- */
353
- async fetchModels(baseUrls, forceRefresh = false, onProgress) {
354
- if (baseUrls.length === 0) {
355
- throw new NoProvidersAvailableError();
356
- }
357
- const bestById = /* @__PURE__ */ new Map();
358
- const modelsFromAllProviders = {};
359
- const disabledProviders = this.adapter.getDisabledProviders();
360
- const estimateMinCost = (m) => {
361
- return m?.sats_pricing?.completion ?? 0;
362
- };
363
- const emitProgress = () => {
364
- if (onProgress) {
365
- const currentModels = Array.from(bestById.values()).map((v) => v.model);
366
- onProgress(currentModels);
367
- }
368
- };
369
- const fetchPromises = baseUrls.map(async (url) => {
370
- const base = url.endsWith("/") ? url : `${url}/`;
371
- try {
372
- let list;
373
- if (!forceRefresh) {
374
- const lastUpdate = this.adapter.getProviderLastUpdate(base);
375
- const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
376
- if (cacheValid) {
377
- const cachedModels = this.adapter.getCachedModels();
378
- const cachedList = cachedModels[base] || [];
379
- list = cachedList;
380
- } else {
381
- list = await this.fetchModelsFromProvider(base);
382
- }
383
- } else {
384
- list = await this.fetchModelsFromProvider(base);
385
- }
386
- modelsFromAllProviders[base] = list;
387
- this.adapter.setProviderLastUpdate(base, Date.now());
388
- if (!disabledProviders.includes(base)) {
389
- for (const m of list) {
390
- const existing = bestById.get(m.id);
391
- if (!m.sats_pricing) continue;
392
- if (!existing) {
393
- bestById.set(m.id, { model: m, base });
394
- continue;
395
- }
396
- const currentCost = estimateMinCost(m);
397
- const existingCost = estimateMinCost(existing.model);
398
- if (currentCost < existingCost && m.sats_pricing) {
399
- bestById.set(m.id, { model: m, base });
400
- }
401
- }
402
- }
403
- emitProgress();
404
- return { success: true, base, list };
405
- } catch (error) {
406
- if (this.isProviderDownError(error)) {
407
- this.logger.warn(`Provider ${base} is down right now.`);
408
- } else {
409
- this.logger.warn(`Failed to fetch models from ${base}:`, error);
410
- }
411
- this.adapter.setProviderLastUpdate(base, Date.now());
412
- return { success: false, base };
413
- }
414
- });
415
- await Promise.allSettled(fetchPromises);
416
- const existingCache = this.adapter.getCachedModels();
417
- this.adapter.setCachedModels({
418
- ...existingCache,
419
- ...modelsFromAllProviders
420
- });
421
- return Array.from(bestById.values()).map((v) => v.model);
422
- }
423
- /**
424
- * Fetch models from a single provider
425
- * @param baseUrl Provider base URL
426
- * @returns Array of models from provider
427
- */
428
- async fetchModelsFromProvider(baseUrl) {
429
- const res = await fetch(`${baseUrl}v1/models`);
430
- if (!res.ok) {
431
- throw new Error(`Failed to fetch models: ${res.status}`);
432
- }
433
- const json = await res.json();
434
- const list = Array.isArray(json?.data) ? json.data : [];
435
- return list;
436
- }
437
- isProviderDownError(error) {
438
- if (!(error instanceof Error)) return false;
439
- const msg = error.message.toLowerCase();
440
- if (msg.includes("fetch failed")) return true;
441
- if (msg.includes("429")) return true;
442
- if (msg.includes("502")) return true;
443
- if (msg.includes("503")) return true;
444
- if (msg.includes("504")) return true;
445
- const cause = error.cause;
446
- return cause?.code === "ENOTFOUND";
447
- }
448
- /**
449
- * Get all cached models from all providers
450
- * @returns Record mapping baseUrl -> models
451
- */
452
- getAllCachedModels() {
453
- return this.adapter.getCachedModels();
454
- }
455
- /**
456
- * Clear cache for a specific provider
457
- * @param baseUrl Provider base URL
458
- */
459
- clearProviderCache(baseUrl) {
460
- const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
461
- const cached = this.adapter.getCachedModels();
462
- delete cached[base];
463
- this.adapter.setCachedModels(cached);
464
- this.adapter.setProviderLastUpdate(base, 0);
465
- }
466
- /**
467
- * Clear all model caches
468
- */
469
- clearAllCache() {
470
- this.adapter.setCachedModels({});
471
- }
472
- /**
473
- * Filter base URLs based on Tor context
474
- * @param baseUrls Provider URLs to filter
475
- * @param torMode Whether in Tor context
476
- * @returns Filtered URLs appropriate for Tor mode
477
- */
478
- filterBaseUrlsForTor(baseUrls, torMode) {
479
- if (!torMode) {
480
- return baseUrls.filter((url) => !url.includes(".onion"));
481
- }
482
- return baseUrls.filter((url) => url.includes(".onion"));
483
- }
484
- /**
485
- * Get provider endpoints from provider info
486
- * @param provider Provider object from directory
487
- * @param torMode Whether in Tor context
488
- * @returns Array of endpoint URLs
489
- */
490
- getProviderEndpoints(provider, torMode) {
491
- const endpoints = [];
492
- if (torMode && provider.onion_url) {
493
- endpoints.push(this.normalizeUrl(provider.onion_url));
494
- } else if (provider.endpoint_url) {
495
- endpoints.push(this.normalizeUrl(provider.endpoint_url));
496
- }
497
- return endpoints;
498
- }
499
- /**
500
- * Normalize provider URL with trailing slash
501
- * @param url URL to normalize
502
- * @returns Normalized URL
503
- */
504
- normalizeUrl(url) {
505
- if (!url.startsWith("http")) {
506
- url = `https://${url}`;
507
- }
508
- return url.endsWith("/") ? url : `${url}/`;
509
- }
510
- /**
511
- * Fetch routstr21 models from Nostr network (kind 38423)
512
- * Uses cache if available and not expired
513
- * @returns Array of model IDs or empty array if not found
514
- */
515
- async fetchRoutstr21Models(forceRefresh = false) {
516
- const cachedModels = this.adapter.getRoutstr21Models();
517
- if (!forceRefresh && cachedModels.length > 0) {
518
- const lastUpdate = this.adapter.getRoutstr21ModelsLastUpdate();
519
- const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
520
- if (cacheValid) {
521
- return cachedModels;
522
- }
523
- }
524
- const DEFAULT_RELAYS = [
525
- "wss://relay.damus.io",
526
- "wss://nos.lol",
527
- "wss://relay.routstr.com"
528
- ];
529
- const pool = new RelayPool();
530
- const localEventStore = new EventStore();
531
- const timeoutMs = 5e3;
532
- await new Promise((resolve) => {
533
- pool.req(DEFAULT_RELAYS, {
534
- kinds: [38423],
535
- "#d": ["routstr-21-models"],
536
- limit: 1,
537
- authors: [this.routstrPubkey]
538
- }).pipe(
539
- onlyEvents(),
540
- tap((event2) => {
541
- localEventStore.add(event2);
542
- })
543
- ).subscribe({
544
- complete: () => {
545
- resolve();
546
- }
547
- });
548
- setTimeout(() => {
549
- resolve();
550
- }, timeoutMs);
551
- });
552
- const timeline = localEventStore.getTimeline({ kinds: [38423] });
553
- if (timeline.length === 0) {
554
- return cachedModels.length > 0 ? cachedModels : [];
555
- }
556
- const event = timeline[0];
557
- try {
558
- const content = JSON.parse(event.content);
559
- const models = Array.isArray(content?.models) ? content.models : [];
560
- this.adapter.setRoutstr21Models(models);
561
- this.adapter.setRoutstr21ModelsLastUpdate(Date.now());
562
- return models;
563
- } catch {
564
- this.logger.warn(
565
- "Routstr21Models: failed to parse Nostr event content:",
566
- event.id
567
- );
568
- return cachedModels.length > 0 ? cachedModels : [];
569
- }
570
- }
571
- };
572
-
573
- // discovery/MintDiscovery.ts
574
- var MintDiscovery = class {
575
- constructor(adapter, config = {}) {
576
- this.adapter = adapter;
577
- this.cacheTTL = config.cacheTTL || 21 * 60 * 1e3;
578
- this.logger = (config.logger ?? consoleLogger).child("MintDiscovery");
579
- }
580
- cacheTTL;
581
- logger;
582
- /**
583
- * Fetch mints from all providers via their /v1/info endpoints
584
- * Caches mints and full provider info for later access
585
- * @param baseUrls List of provider base URLs to fetch from
586
- * @returns Object with mints and provider info from all providers
587
- */
588
- async discoverMints(baseUrls, options = {}) {
589
- if (baseUrls.length === 0) {
590
- return { mintsFromProviders: {}, infoFromProviders: {} };
591
- }
592
- const mintsFromAllProviders = {};
593
- const infoFromAllProviders = {};
594
- const forceRefresh = options.forceRefresh ?? false;
595
- const fetchPromises = baseUrls.map(async (url) => {
596
- const base = url.endsWith("/") ? url : `${url}/`;
597
- try {
598
- if (!forceRefresh) {
599
- const lastUpdate = this.adapter.getProviderLastUpdate(base);
600
- const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
601
- if (cacheValid) {
602
- const cachedMints = this.adapter.getCachedMints()[base] || [];
603
- const cachedInfo = this.adapter.getCachedProviderInfo()[base];
604
- mintsFromAllProviders[base] = cachedMints;
605
- if (cachedInfo) {
606
- infoFromAllProviders[base] = cachedInfo;
607
- }
608
- return {
609
- success: true,
610
- base,
611
- mints: cachedMints,
612
- info: cachedInfo
613
- };
614
- }
615
- }
616
- const res = await fetch(`${base}v1/info`);
617
- if (!res.ok) {
618
- throw new Error(`Failed to fetch info: ${res.status}`);
619
- }
620
- const json = await res.json();
621
- const mints = Array.isArray(json?.mints) ? json.mints : [];
622
- const normalizedMints = mints.map(
623
- (mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint
624
- );
625
- mintsFromAllProviders[base] = normalizedMints;
626
- infoFromAllProviders[base] = json;
627
- this.adapter.setProviderLastUpdate(base, Date.now());
628
- return { success: true, base, mints: normalizedMints, info: json };
629
- } catch (error) {
630
- this.adapter.setProviderLastUpdate(base, Date.now());
631
- if (this.isProviderDownError(error)) {
632
- this.logger.warn(`Provider ${base} is down right now.`);
633
- } else {
634
- this.logger.warn(`Failed to fetch mints from ${base}:`, error);
635
- }
636
- return { success: false, base, mints: [], info: null };
637
- }
638
- });
639
- const results = await Promise.allSettled(fetchPromises);
640
- for (const result of results) {
641
- if (result.status === "fulfilled") {
642
- const { base, mints, info } = result.value;
643
- mintsFromAllProviders[base] = mints;
644
- if (info) {
645
- infoFromAllProviders[base] = info;
646
- }
647
- } else {
648
- this.logger.error("Mint discovery error:", result.reason);
649
- }
650
- }
651
- try {
652
- this.adapter.setCachedMints(mintsFromAllProviders);
653
- this.adapter.setCachedProviderInfo(infoFromAllProviders);
654
- } catch (error) {
655
- this.logger.error("Error caching mint discovery results:", error);
656
- }
657
- return {
658
- mintsFromProviders: mintsFromAllProviders,
659
- infoFromProviders: infoFromAllProviders
660
- };
661
- }
662
- /**
663
- * Get cached mints from all providers
664
- * @returns Record mapping baseUrl -> mint URLs
665
- */
666
- getCachedMints() {
667
- return this.adapter.getCachedMints();
668
- }
669
- /**
670
- * Get cached provider info from all providers
671
- * @returns Record mapping baseUrl -> provider info
672
- */
673
- getCachedProviderInfo() {
674
- return this.adapter.getCachedProviderInfo();
675
- }
676
- /**
677
- * Get mints for a specific provider
678
- * @param baseUrl Provider base URL
679
- * @returns Array of mint URLs for the provider
680
- */
681
- getProviderMints(baseUrl) {
682
- const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
683
- const allMints = this.getCachedMints();
684
- return allMints[normalized] || [];
685
- }
686
- /**
687
- * Get info for a specific provider
688
- * @param baseUrl Provider base URL
689
- * @returns Provider info object or null if not found
690
- */
691
- getProviderInfo(baseUrl) {
692
- const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
693
- const allInfo = this.getCachedProviderInfo();
694
- return allInfo[normalized] || null;
695
- }
696
- /**
697
- * Clear mint cache for a specific provider
698
- * @param baseUrl Provider base URL
699
- */
700
- clearProviderMintCache(baseUrl) {
701
- const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
702
- const mints = this.getCachedMints();
703
- delete mints[normalized];
704
- this.adapter.setCachedMints(mints);
705
- const info = this.getCachedProviderInfo();
706
- delete info[normalized];
707
- this.adapter.setCachedProviderInfo(info);
708
- }
709
- /**
710
- * Clear all mint caches
711
- */
712
- clearAllCache() {
713
- this.adapter.setCachedMints({});
714
- this.adapter.setCachedProviderInfo({});
715
- }
716
- isProviderDownError(error) {
717
- if (!(error instanceof Error)) return false;
718
- const msg = error.message.toLowerCase();
719
- if (msg.includes("fetch failed")) return true;
720
- if (msg.includes("429")) return true;
721
- if (msg.includes("502")) return true;
722
- if (msg.includes("503")) return true;
723
- if (msg.includes("504")) return true;
724
- const cause = error.cause;
725
- if (cause?.code === "ENOTFOUND") return true;
726
- return false;
727
- }
728
- };
729
-
730
- export { MintDiscovery, ModelManager };
731
- //# sourceMappingURL=index.mjs.map
732
- //# sourceMappingURL=index.mjs.map