@bsv/overlay-express 0.1.7 → 0.1.9

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.
@@ -6,6 +6,8 @@ import Knex from 'knex'
6
6
  import { MongoClient, Db } from 'mongodb'
7
7
  import makeUserInterface, { type UIConfig } from './makeUserInterface.js'
8
8
  import * as DiscoveryServices from '@bsv/overlay-discovery-services'
9
+ import chalk from 'chalk'
10
+ import util from 'util'
9
11
 
10
12
  /**
11
13
  * Knex database migration.
@@ -114,7 +116,7 @@ export default class OverlayExpress {
114
116
  public hostingURL: string
115
117
  ) {
116
118
  this.app = express()
117
- this.logger.log(`${name} constructed`)
119
+ this.logger.log(chalk.green.bold(`${name} constructed 🎉`))
118
120
  }
119
121
 
120
122
  /**
@@ -123,7 +125,7 @@ export default class OverlayExpress {
123
125
  */
124
126
  configurePort(port: number) {
125
127
  this.port = port
126
- this.logger.log(`Server port set to ${port}`)
128
+ this.logger.log(chalk.blue(`🌐 Server port set to ${port}`))
127
129
  }
128
130
 
129
131
  /**
@@ -132,7 +134,7 @@ export default class OverlayExpress {
132
134
  */
133
135
  configureWebUI(config: UIConfig) {
134
136
  this.webUIConfig = config
135
- this.logger.log('Web UI has been configured.')
137
+ this.logger.log(chalk.blue('🖥️ Web UI has been configured.'))
136
138
  }
137
139
 
138
140
  /**
@@ -141,7 +143,7 @@ export default class OverlayExpress {
141
143
  */
142
144
  configureLogger(logger: typeof console) {
143
145
  this.logger = logger
144
- this.logger.log('Logger has been configured.')
146
+ this.logger.log(chalk.blue('🔍 Logger has been configured.'))
145
147
  }
146
148
 
147
149
  /**
@@ -151,7 +153,7 @@ export default class OverlayExpress {
151
153
  configureNetwork(network: 'main' | 'test') {
152
154
  this.network = network
153
155
  this.chainTracker = new WhatsOnChain(this.network)
154
- this.logger.log(`Network set to ${network}`)
156
+ this.logger.log(chalk.blue(`🔗 Network set to ${network}`))
155
157
  }
156
158
 
157
159
  /**
@@ -160,7 +162,7 @@ export default class OverlayExpress {
160
162
  */
161
163
  configureChainTracker(chainTracker: ChainTracker = new WhatsOnChain(this.network)) {
162
164
  this.chainTracker = chainTracker
163
- this.logger.log('ChainTracker has been configured.')
165
+ this.logger.log(chalk.blue('🔗 ChainTracker has been configured.'))
164
166
  }
165
167
 
166
168
  /**
@@ -169,7 +171,7 @@ export default class OverlayExpress {
169
171
  */
170
172
  configureArcApiKey(apiKey: string) {
171
173
  this.arcApiKey = apiKey
172
- this.logger.log('ARC API key has been configured.')
174
+ this.logger.log(chalk.blue('🔑 ARC API key has been configured.'))
173
175
  }
174
176
 
175
177
  /**
@@ -178,7 +180,7 @@ export default class OverlayExpress {
178
180
  */
179
181
  configureEnableGASPSync(enable: boolean) {
180
182
  this.enableGASPSync = enable
181
- this.logger.log(`GASP synchronization ${enable ? 'enabled' : 'disabled'}.`)
183
+ this.logger.log(chalk.blue(`🔄 GASP synchronization ${enable ? 'enabled' : 'disabled'}.`))
182
184
  }
183
185
 
184
186
  /**
@@ -187,7 +189,7 @@ export default class OverlayExpress {
187
189
  */
188
190
  configureVerboseRequestLogging(enable: boolean) {
189
191
  this.verboseRequestLogging = enable
190
- this.logger.log(`Verbose request logging ${enable ? 'enabled' : 'disabled'}.`)
192
+ this.logger.log(chalk.blue(`📝 Verbose request logging ${enable ? 'enabled' : 'disabled'}.`))
191
193
  }
192
194
 
193
195
  /**
@@ -202,7 +204,7 @@ export default class OverlayExpress {
202
204
  }
203
205
  }
204
206
  this.knex = Knex(config)
205
- this.logger.log('Knex successfully configured.')
207
+ this.logger.log(chalk.blue('📦 Knex successfully configured.'))
206
208
  }
207
209
 
208
210
  /**
@@ -214,7 +216,7 @@ export default class OverlayExpress {
214
216
  await mongoClient.connect()
215
217
  const db = mongoClient.db(`${this.name}_lookup_services`)
216
218
  this.mongoDb = db
217
- this.logger.log('MongoDB successfully configured and connected.')
219
+ this.logger.log(chalk.blue('🍃 MongoDB successfully configured and connected.'))
218
220
  }
219
221
 
220
222
  /**
@@ -224,7 +226,7 @@ export default class OverlayExpress {
224
226
  */
225
227
  configureTopicManager(name: string, manager: TopicManager) {
226
228
  this.managers[name] = manager
227
- this.logger.log(`Configured topic manager ${name}`)
229
+ this.logger.log(chalk.blue(`🗂️ Configured topic manager ${name}`))
228
230
  }
229
231
 
230
232
  /**
@@ -234,7 +236,7 @@ export default class OverlayExpress {
234
236
  */
235
237
  configureLookupService(name: string, service: LookupService) {
236
238
  this.services[name] = service
237
- this.logger.log(`Configured lookup service ${name}`)
239
+ this.logger.log(chalk.blue(`🔍 Configured lookup service ${name}`))
238
240
  }
239
241
 
240
242
  /**
@@ -250,7 +252,7 @@ export default class OverlayExpress {
250
252
  const factoryResult = serviceFactory(this.knex as Knex.Knex)
251
253
  this.services[name] = factoryResult.service
252
254
  this.migrationsToRun.push(...factoryResult.migrations)
253
- this.logger.log(`Configured lookup service ${name} with Knex`)
255
+ this.logger.log(chalk.blue(`🔍 Configured lookup service ${name} with Knex`))
254
256
  }
255
257
 
256
258
  /**
@@ -261,7 +263,7 @@ export default class OverlayExpress {
261
263
  configureLookupServiceWithMongo(name: string, serviceFactory: (mongoDb: Db) => LookupService) {
262
264
  this.ensureMongo()
263
265
  this.services[name] = serviceFactory(this.mongoDb as Db)
264
- this.logger.log(`Configured lookup service ${name} with MongoDB`)
266
+ this.logger.log(chalk.blue(`🔍 Configured lookup service ${name} with MongoDB`))
265
267
  }
266
268
 
267
269
  /**
@@ -309,7 +311,7 @@ export default class OverlayExpress {
309
311
  new DiscoveryServices.LegacyNinjaAdvertiser(this.privateKey, 'https://dojo.babbage.systems', this.hostingURL),
310
312
  syncConfig
311
313
  )
312
- this.logger.log('Engine has been configured.')
314
+ this.logger.log(chalk.green('🚀 Engine has been configured.'))
313
315
  }
314
316
 
315
317
  /**
@@ -352,33 +354,83 @@ export default class OverlayExpress {
352
354
  const engine = this.engine as Engine
353
355
  const knex = this.knex as Knex.Knex
354
356
 
357
+ this.app.use(bodyParser.json({ limit: '1gb', type: 'application/json' }))
358
+ this.app.use(bodyParser.raw({ limit: '1gb', type: 'application/octet-stream' }))
359
+
355
360
  if (this.verboseRequestLogging) {
356
361
  this.app.use((req, res, next) => {
357
362
  const startTime = Date.now();
358
363
 
359
364
  // Log incoming request details
360
- this.logger.log(`Incoming Request: ${req.method} ${req.originalUrl}`);
361
- this.logger.log(`Headers: ${JSON.stringify(req.headers)}`);
365
+ this.logger.log(chalk.magenta.bold(`📥 Incoming Request: ${req.method} ${req.originalUrl}`));
366
+
367
+ // Pretty-print headers
368
+ this.logger.log(chalk.cyan(`Headers:`));
369
+ this.logger.log(util.inspect(req.headers, { colors: true, depth: null }));
370
+
371
+ // Handle request body
362
372
  if (req.body && Object.keys(req.body).length > 0) {
363
- this.logger.log(`Request Body: ${JSON.stringify(req.body)}`);
373
+ let bodyContent;
374
+ let bodyString;
375
+ if (typeof req.body === 'object') {
376
+ bodyString = JSON.stringify(req.body, null, 2);
377
+ } else if (Buffer.isBuffer(req.body)) {
378
+ bodyString = req.body.toString('utf8');
379
+ } else {
380
+ bodyString = req.body.toString();
381
+ }
382
+ if (bodyString.length > 280) {
383
+ bodyContent = chalk.yellow(`(Body too long to display, length: ${bodyString.length} characters)`);
384
+ } else {
385
+ bodyContent = chalk.green(`Request Body:\n${bodyString}`);
386
+ }
387
+ this.logger.log(bodyContent);
364
388
  }
365
389
 
390
+ // Intercept the res.send method
391
+ const originalSend = res.send;
392
+ let responseBody: any;
393
+
394
+ res.send = function (body?: any): any {
395
+ responseBody = body;
396
+ return originalSend.call(this, body);
397
+ };
398
+
366
399
  // Log outgoing response details after the response is finished
367
400
  res.on('finish', () => {
368
401
  const duration = Date.now() - startTime;
369
402
  this.logger.log(
370
- `Outgoing Response: ${req.method} ${req.originalUrl} - Status: ${res.statusCode} - Duration: ${duration}ms`
403
+ chalk.magenta.bold(
404
+ `📤 Outgoing Response: ${req.method} ${req.originalUrl} - Status: ${res.statusCode} - Duration: ${duration}ms`
405
+ )
371
406
  );
372
- this.logger.log(`Response Headers: ${JSON.stringify(res.getHeaders())}`);
407
+ this.logger.log(chalk.cyan(`Response Headers:`));
408
+ this.logger.log(util.inspect(res.getHeaders(), { colors: true, depth: null }));
409
+
410
+ // Handle response body
411
+ if (responseBody) {
412
+ let bodyContent;
413
+ let bodyString;
414
+ if (typeof responseBody === 'object') {
415
+ bodyString = JSON.stringify(responseBody, null, 2);
416
+ } else if (Buffer.isBuffer(responseBody)) {
417
+ bodyString = responseBody.toString('utf8');
418
+ } else {
419
+ bodyString = responseBody.toString();
420
+ }
421
+ if (bodyString.length > 280) {
422
+ bodyContent = chalk.yellow(`(Response body too long to display, length: ${bodyString.length} characters)`);
423
+ } else {
424
+ bodyContent = chalk.green(`Response Body:\n${bodyString}`);
425
+ }
426
+ this.logger.log(bodyContent);
427
+ }
373
428
  });
374
429
 
375
430
  next();
376
431
  });
377
432
  }
378
433
 
379
- this.app.use(bodyParser.json({ limit: '1gb', type: 'application/json' }))
380
- this.app.use(bodyParser.raw({ limit: '1gb', type: 'application/octet-stream' }))
381
-
382
434
  // Enable CORS
383
435
  this.app.use((req, res, next) => {
384
436
  res.header('Access-Control-Allow-Origin', '*')
@@ -502,7 +554,7 @@ export default class OverlayExpress {
502
554
  return res.status(200).json(steak)
503
555
  })
504
556
  } catch (error) {
505
- console.error(error)
557
+ console.error(chalk.red('❌ Error in /submit:'), error)
506
558
  return res.status(400).json({
507
559
  status: 'error',
508
560
  message: error instanceof Error ? error.message : 'An unknown error occurred'
@@ -522,7 +574,7 @@ export default class OverlayExpress {
522
574
  const result = await engine.lookup(req.body)
523
575
  return res.status(200).json(result)
524
576
  } catch (error) {
525
- console.error(error)
577
+ console.error(chalk.red('❌ Error in /lookup:'), error)
526
578
  return res.status(400).json({
527
579
  status: 'error',
528
580
  message: error instanceof Error ? error.message : 'An unknown error occurred'
@@ -546,7 +598,7 @@ export default class OverlayExpress {
546
598
  await engine.handleNewMerkleProof(txid, merklePath, blockHeight)
547
599
  return res.status(200).json({ status: 'success', message: 'Transaction status updated' })
548
600
  } catch (error) {
549
- console.error(error)
601
+ console.error(chalk.red('❌ Error in /arc-ingest:'), error)
550
602
  return res.status(400).json({
551
603
  status: 'error',
552
604
  message: error instanceof Error ? error.message : 'An unknown error occurred'
@@ -560,7 +612,7 @@ export default class OverlayExpress {
560
612
  })
561
613
  })
562
614
  } else {
563
- this.logger.warn('Disabling ARC because no ARC API key was provided.')
615
+ this.logger.warn(chalk.yellow('⚠️ Disabling ARC because no ARC API key was provided.'))
564
616
  }
565
617
 
566
618
  if (this.enableGASPSync) {
@@ -572,7 +624,7 @@ export default class OverlayExpress {
572
624
  const response = await engine.provideForeignSyncResponse(req.body, topic)
573
625
  return res.status(200).json(response)
574
626
  } catch (error) {
575
- console.error(error)
627
+ console.error(chalk.red('❌ Error in /requestSyncResponse:'), error)
576
628
  return res.status(400).json({
577
629
  status: 'error',
578
630
  message: error instanceof Error ? error.message : 'An unknown error occurred'
@@ -592,7 +644,7 @@ export default class OverlayExpress {
592
644
  const response = await engine.provideForeignGASPNode(graphID, txid, outputIndex)
593
645
  return res.status(200).json(response)
594
646
  } catch (error) {
595
- console.error(error)
647
+ console.error(chalk.red('❌ Error in /requestForeignGASPNode:'), error)
596
648
  return res.status(400).json({
597
649
  status: 'error',
598
650
  message: error instanceof Error ? error.message : 'An unknown error occurred'
@@ -606,7 +658,7 @@ export default class OverlayExpress {
606
658
  })
607
659
  })
608
660
  } else {
609
- this.logger.warn('GASP sync is disabled.')
661
+ this.logger.warn(chalk.yellow('⚠️ GASP sync is disabled.'))
610
662
  }
611
663
 
612
664
  // Automatically handle migrations
@@ -614,36 +666,46 @@ export default class OverlayExpress {
614
666
  const result = await knex.migrate.latest({
615
667
  migrationSource
616
668
  })
617
- this.logger.log('Knex migrations run', result)
669
+ this.logger.log(chalk.green('🔄 Knex migrations run'), result)
618
670
 
619
671
  // 404 handler for all other routes
620
672
  this.app.use((req, res) => {
621
- this.logger.log('404', req.url)
673
+ this.logger.log(chalk.red('❌ 404 Not Found:'), req.url)
622
674
  res.status(404).json({
623
675
  status: 'error',
624
676
  code: 'ERR_ROUTE_NOT_FOUND',
625
677
  description: 'Route not found.'
626
678
  })
627
- })
628
-
629
- // Start listening on the configured port
630
- this.app.listen(this.port, async () => {
631
- this.logger.log(`${this.name} listening on local port ${this.port} and will now sync advertisements`);
632
-
633
- // The legacy Ninja advertiser has a setLookupEngine method.
679
+ });
680
+
681
+ // The legacy Ninja advertiser has a setLookupEngine method.
682
+ this.logger.log(chalk.cyan(`${this.name} will now advertise with SHIP and SLAP at ${this.hostingURL}`))
683
+ const numTopicManagers = Object.keys(this.managers).length
684
+ const numLookupServices = Object.keys(this.services).length
685
+ this.logger.log(chalk.blue(`Topic Managers: ${numTopicManagers}`))
686
+ this.logger.log(chalk.blue(`Lookup Services: ${numLookupServices}`));
687
+ try {
634
688
  (this.engine?.advertiser as DiscoveryServices.LegacyNinjaAdvertiser).setLookupEngine(this.engine!)
635
-
636
689
  await this.engine?.syncAdvertisements()
690
+ } catch (e) {
691
+ this.logger.log(chalk.red('❌ Error syncing advertisements:'), e)
692
+ }
637
693
 
638
- if (this.enableGASPSync) {
639
- try {
640
- await this.engine?.startGASPSync()
641
- } catch (e) {
642
- console.error('Failed to GASP sync', e)
643
- }
644
- } else {
645
- this.logger.log(`${this.name} will not GASP sync because it has been disabled`)
694
+ if (this.enableGASPSync) {
695
+ try {
696
+ this.logger.log(chalk.green('Starting GASP sync...'))
697
+ await this.engine?.startGASPSync()
698
+ this.logger.log(chalk.green('GASP sync complete!'))
699
+ } catch (e) {
700
+ console.error(chalk.red('❌ Failed to GASP sync'), e)
646
701
  }
702
+ } else {
703
+ this.logger.log(chalk.yellow(`${this.name} will not sync because GASP has been disabled.`))
704
+ }
705
+
706
+ // Start listening on the configured port
707
+ this.app.listen(this.port, async () => {
708
+ this.logger.log(chalk.green.bold(`🎧 ${this.name} is ready and listening on local port ${this.port}`));
647
709
  })
648
710
  }
649
711
  }