paymongo-cli 1.4.11 → 1.4.13

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 (46) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +4 -3
  3. package/biome.json +72 -0
  4. package/dist/.tsbuildinfo +1 -1
  5. package/dist/commands/config/actions.js +13 -5
  6. package/dist/commands/config/analytics.js +75 -0
  7. package/dist/commands/config/helpers.js +14 -25
  8. package/dist/commands/config/rate-limit.js +3 -3
  9. package/dist/commands/config.js +7 -1
  10. package/dist/commands/dev/logs.js +13 -4
  11. package/dist/commands/dev/status.js +1 -1
  12. package/dist/commands/dev/stop.js +2 -2
  13. package/dist/commands/dev.js +10 -258
  14. package/dist/commands/doctor.js +241 -0
  15. package/dist/commands/env.js +10 -19
  16. package/dist/commands/generate/templates/index.js +3 -3
  17. package/dist/commands/generate.js +6 -6
  18. package/dist/commands/init.js +22 -36
  19. package/dist/commands/login.js +18 -29
  20. package/dist/commands/payments/actions.js +15 -15
  21. package/dist/commands/payments/helpers.js +6 -24
  22. package/dist/commands/payments.js +1 -1
  23. package/dist/commands/shared/auth.js +23 -0
  24. package/dist/commands/shared/runtime.js +35 -0
  25. package/dist/commands/team/index.js +3 -3
  26. package/dist/commands/trigger/actions.js +2 -2
  27. package/dist/commands/trigger/helpers.js +13 -9
  28. package/dist/commands/trigger.js +2 -2
  29. package/dist/commands/webhooks/actions.js +11 -11
  30. package/dist/commands/webhooks/helpers.js +5 -23
  31. package/dist/commands/webhooks.js +1 -1
  32. package/dist/index.js +37 -14
  33. package/dist/services/analytics/service.js +3 -3
  34. package/dist/services/api/client.js +8 -4
  35. package/dist/services/config/manager.js +3 -3
  36. package/dist/services/dev/process-manager.js +4 -4
  37. package/dist/services/dev/server.js +4 -6
  38. package/dist/services/dev/session.js +353 -0
  39. package/dist/services/team/service.js +1 -1
  40. package/dist/utils/bulk.js +11 -11
  41. package/dist/utils/cache.js +5 -5
  42. package/dist/utils/constants.js +1 -1
  43. package/dist/utils/webhook-store.js +3 -3
  44. package/package.json +11 -25
  45. package/vitest.config.ts +18 -0
  46. package/eslint.config.ts +0 -70
@@ -1,14 +1,8 @@
1
1
  import chalk from 'chalk';
2
- import ApiClient from '../../services/api/client.js';
3
- import ConfigManager from '../../services/config/manager.js';
4
- import Spinner from '../../utils/spinner.js';
5
2
  import { PaymentSimulator } from '../../services/payments/simulator.js';
6
- import { CommandError } from '../../utils/errors.js';
3
+ import { createCommandContext, createApiClient as createSharedApiClient, failCommand, loadCommandConfig, } from '../shared/runtime.js';
7
4
  export function createPaymentsContext() {
8
- return {
9
- spinner: new Spinner(),
10
- configManager: new ConfigManager(),
11
- };
5
+ return createCommandContext();
12
6
  }
13
7
  export function getStatusColor(status) {
14
8
  switch (status) {
@@ -30,32 +24,20 @@ export function getStatusColor(status) {
30
24
  }
31
25
  }
32
26
  export async function loadPaymentsConfig(spinner, configManager) {
33
- spinner.start('Loading configuration...');
34
- const config = await configManager.load();
35
- if (!config) {
36
- spinner.fail('No configuration found');
37
- console.log(chalk.yellow('No PayMongo configuration found.'));
38
- console.log(chalk.gray("Run 'paymongo init' to set up your project first."));
39
- return null;
40
- }
41
- spinner.succeed('Configuration loaded');
42
- return config;
27
+ return loadCommandConfig(spinner, configManager);
43
28
  }
44
29
  export function createApiClient(config) {
45
- return new ApiClient({ config });
30
+ return createSharedApiClient(config);
46
31
  }
47
32
  export function createPaymentSimulator() {
48
33
  return new PaymentSimulator();
49
34
  }
50
35
  export function handlePaymentsError(prefix, spinner, error) {
51
- spinner.stop();
52
- const err = error;
53
- console.error(chalk.red(prefix), err.message);
54
- throw new CommandError();
36
+ return failCommand(prefix, error, spinner);
55
37
  }
56
38
  export function parseBoundedInt(value, fallback, errorMessage, validate) {
57
39
  const parsed = parseInt(value || fallback, 10);
58
- if (isNaN(parsed) || !validate(parsed)) {
40
+ if (Number.isNaN(parsed) || !validate(parsed)) {
59
41
  throw new Error(errorMessage);
60
42
  }
61
43
  return parsed;
@@ -54,5 +54,5 @@ command
54
54
  .option('-r, --reason <reason>', 'Refund reason: duplicate, fraudulent, requested_by_customer')
55
55
  .option('-j, --json', 'Output as JSON')
56
56
  .action(refundAction));
57
- export { exportAction, importAction, listAction, showAction, createIntentAction, attachAction, confirmAction, captureAction, refundAction, };
57
+ export { attachAction, captureAction, confirmAction, createIntentAction, exportAction, importAction, listAction, refundAction, showAction, };
58
58
  export default command;
@@ -0,0 +1,23 @@
1
+ export function createCredentialValidationConfig({ projectName = 'temp', environment, publicKey = '', secretKey, webhookUrl = '', events = [], port = 3000, }) {
2
+ return {
3
+ version: '1.0',
4
+ projectName,
5
+ environment,
6
+ apiKeys: {
7
+ [environment]: {
8
+ public: publicKey,
9
+ secret: secretKey,
10
+ },
11
+ },
12
+ webhooks: {
13
+ url: webhookUrl,
14
+ events,
15
+ },
16
+ webhookSecrets: {},
17
+ dev: {
18
+ port,
19
+ autoRegisterWebhook: true,
20
+ verifyWebhookSignatures: true,
21
+ },
22
+ };
23
+ }
@@ -0,0 +1,35 @@
1
+ import chalk from 'chalk';
2
+ import ApiClient from '../../services/api/client.js';
3
+ import ConfigManager from '../../services/config/manager.js';
4
+ import { CommandError } from '../../utils/errors.js';
5
+ import Spinner from '../../utils/spinner.js';
6
+ export function createCommandContext() {
7
+ return {
8
+ spinner: new Spinner(),
9
+ configManager: new ConfigManager(),
10
+ };
11
+ }
12
+ export function showNoConfigMessage(message = "Run 'paymongo init' to set up your project first.") {
13
+ console.log(chalk.yellow('No PayMongo configuration found.'));
14
+ console.log(chalk.gray(message));
15
+ }
16
+ export async function loadCommandConfig(spinner, configManager, loadingText = 'Loading configuration...', missingMessage) {
17
+ spinner.start(loadingText);
18
+ const config = await configManager.load();
19
+ if (!config) {
20
+ spinner.fail('No configuration found');
21
+ showNoConfigMessage(missingMessage);
22
+ return null;
23
+ }
24
+ spinner.succeed('Configuration loaded');
25
+ return config;
26
+ }
27
+ export function createApiClient(config) {
28
+ return new ApiClient({ config });
29
+ }
30
+ export function failCommand(prefix, error, spinner) {
31
+ spinner?.stop();
32
+ const err = error;
33
+ console.error(chalk.red(prefix), err.message);
34
+ throw new CommandError();
35
+ }
@@ -1,10 +1,10 @@
1
+ import chalk from 'chalk';
1
2
  import Table from 'cli-table3';
2
3
  import { Command } from 'commander';
3
- import Spinner from '../../utils/spinner.js';
4
- import chalk from 'chalk';
5
4
  import { ConfigManager } from '../../services/config/manager.js';
6
5
  import { TeamService } from '../../services/team/service.js';
7
6
  import { CommandError } from '../../utils/errors.js';
7
+ import Spinner from '../../utils/spinner.js';
8
8
  const command = new Command('team')
9
9
  .description('Team collaboration with API key sharing')
10
10
  .showHelpAfterError();
@@ -44,7 +44,7 @@ command
44
44
  console.log(chalk.gray(`Environments: ${bundle.environments.join(', ')}`));
45
45
  if (options.copy) {
46
46
  try {
47
- const { execSync } = await import('child_process');
47
+ const { execSync } = await import('node:child_process');
48
48
  const bundleJson = teamService.serializeBundle(bundle);
49
49
  try {
50
50
  execSync(`echo '${bundleJson.replace(/'/g, "'\\''")}' | clip`, { stdio: 'pipe' });
@@ -1,5 +1,5 @@
1
- import Table from 'cli-table3';
2
1
  import chalk from 'chalk';
2
+ import Table from 'cli-table3';
3
3
  import { CommandError } from '../../utils/errors.js';
4
4
  import { AVAILABLE_TRIGGER_EVENTS, createTriggerContext, failTriggerCommand, generateWebhookPayload, printJsonResponse, sendWebhookRequest, } from './helpers.js';
5
5
  export async function sendWebhookEvent(options) {
@@ -235,7 +235,7 @@ export async function replayWebhookEvent(eventId, options) {
235
235
  console.log(chalk.bold.blue(`\n📋 Recent "${options.event}" Events`));
236
236
  console.log(chalk.gray('─'.repeat(60)));
237
237
  matchingEvents.slice(0, 5).forEach((event, index) => {
238
- console.log(`${chalk.cyan((index + 1).toString() + '.')} ${chalk.yellow(event.id)} - ${chalk.gray(new Date(event.timestamp * 1000).toLocaleString())}`);
238
+ console.log(`${chalk.cyan(`${(index + 1).toString()}.`)} ${chalk.yellow(event.id)} - ${chalk.gray(new Date(event.timestamp * 1000).toLocaleString())}`);
239
239
  });
240
240
  console.log(chalk.gray('\n💡 Use "paymongo trigger replay <eventId>" to replay a specific event'));
241
241
  return;
@@ -1,14 +1,14 @@
1
- import crypto from 'crypto';
2
- import ConfigManager from '../../services/config/manager.js';
3
- import Spinner from '../../utils/spinner.js';
4
- import Logger from '../../utils/logger.js';
5
- import WebhookEventStore from '../../utils/webhook-store.js';
1
+ import crypto from 'node:crypto';
6
2
  import { CLI_VERSION } from '../../utils/constants.js';
7
3
  import { CommandError } from '../../utils/errors.js';
4
+ import Logger from '../../utils/logger.js';
5
+ import WebhookEventStore from '../../utils/webhook-store.js';
6
+ import { createCommandContext } from '../shared/runtime.js';
8
7
  export function createTriggerContext() {
8
+ const { spinner, configManager } = createCommandContext();
9
9
  return {
10
- spinner: new Spinner(),
11
- configManager: new ConfigManager(),
10
+ spinner,
11
+ configManager,
12
12
  logger: new Logger(),
13
13
  store: new WebhookEventStore(),
14
14
  };
@@ -46,7 +46,11 @@ export function buildSignatureHeader(config, webhookUrl, body, livemode) {
46
46
  .createHmac('sha256', secret)
47
47
  .update(`${timestamp}.${body}`)
48
48
  .digest('hex');
49
- const parts = [`t=${timestamp}`, livemode ? 'te=' : `te=${signature}`, livemode ? `li=${signature}` : 'li='];
49
+ const parts = [
50
+ `t=${timestamp}`,
51
+ livemode ? 'te=' : `te=${signature}`,
52
+ livemode ? `li=${signature}` : 'li=',
53
+ ];
50
54
  return parts.join(',');
51
55
  }
52
56
  export async function sendWebhookRequest(config, webhookUrl, payload) {
@@ -219,7 +223,7 @@ export function generateWebhookPayload(eventType) {
219
223
  }
220
224
  export async function printJsonResponse(response) {
221
225
  const contentType = response.headers['content-type'];
222
- if (contentType && contentType.includes('application/json')) {
226
+ if (contentType?.includes('application/json')) {
223
227
  return response.body.json();
224
228
  }
225
229
  return null;
@@ -1,6 +1,6 @@
1
+ import chalk from 'chalk';
1
2
  import { Command } from 'commander';
2
3
  import WebhookEventStore from '../utils/webhook-store.js';
3
- import chalk from 'chalk';
4
4
  import { replayWebhookEvent, sendWebhookEvent } from './trigger/actions.js';
5
5
  const command = new Command('trigger');
6
6
  command
@@ -40,5 +40,5 @@ command
40
40
  command.help();
41
41
  }
42
42
  });
43
- export { sendWebhookEvent, replayWebhookEvent };
43
+ export { replayWebhookEvent, sendWebhookEvent };
44
44
  export default command;
@@ -1,5 +1,5 @@
1
- import Table from 'cli-table3';
2
1
  import chalk from 'chalk';
2
+ import Table from 'cli-table3';
3
3
  import { BulkOperations } from '../../utils/bulk.js';
4
4
  import { CommandError } from '../../utils/errors.js';
5
5
  import { validateEventTypes, validateWebhookUrl } from '../../utils/validator.js';
@@ -24,7 +24,7 @@ export async function exportAction(options) {
24
24
  spinner.start(`Exporting to ${filename}...`);
25
25
  await BulkOperations.exportWebhooks(webhooks, filename, config.environment);
26
26
  spinner.succeed('Export completed');
27
- console.log('\n' + chalk.green('✅ Webhooks exported successfully!'));
27
+ console.log(`\n${chalk.green('✅ Webhooks exported successfully!')}`);
28
28
  console.log('');
29
29
  console.log(`${chalk.bold('File:')} ${filename}`);
30
30
  console.log(`${chalk.bold('Webhooks:')} ${webhooks.length}`);
@@ -51,7 +51,7 @@ export async function importAction(filename, options) {
51
51
  console.log(JSON.stringify({ webhooks, metadata }, null, 2));
52
52
  return;
53
53
  }
54
- console.log('\n' + chalk.green('✅ Webhooks loaded successfully!'));
54
+ console.log(`\n${chalk.green('✅ Webhooks loaded successfully!')}`);
55
55
  console.log('');
56
56
  console.log(`${chalk.bold('Source:')} ${filename}`);
57
57
  console.log(`${chalk.bold('Webhooks:')} ${webhooks.length}`);
@@ -61,7 +61,7 @@ export async function importAction(filename, options) {
61
61
  console.log(chalk.yellow('No webhooks found in the export file.'));
62
62
  return;
63
63
  }
64
- console.log('\n' + chalk.bold('Webhooks to import:'));
64
+ console.log(`\n${chalk.bold('Webhooks to import:')}`);
65
65
  console.log(chalk.gray('─'.repeat(80)));
66
66
  webhooks.forEach((webhook, index) => {
67
67
  const status = options.dryRun ? chalk.gray('pending') : chalk.yellow('will create');
@@ -105,14 +105,14 @@ export async function importAction(filename, options) {
105
105
  }
106
106
  const successful = results.filter((result) => result.success).length;
107
107
  const failed = results.filter((result) => !result.success).length;
108
- console.log('\n' + chalk.bold('Import Results:'));
108
+ console.log(`\n${chalk.bold('Import Results:')}`);
109
109
  console.log(chalk.gray('─'.repeat(50)));
110
110
  console.log(`${chalk.green('Successful:')} ${successful}`);
111
111
  if (failed > 0) {
112
112
  console.log(`${chalk.red('Failed:')} ${failed}`);
113
113
  }
114
114
  if (successful > 0) {
115
- console.log('\n' + chalk.green('✅ Successfully created webhooks:'));
115
+ console.log(`\n${chalk.green('✅ Successfully created webhooks:')}`);
116
116
  results
117
117
  .filter((result) => result.success)
118
118
  .forEach((result, index) => {
@@ -120,7 +120,7 @@ export async function importAction(filename, options) {
120
120
  });
121
121
  }
122
122
  if (failed > 0) {
123
- console.log('\n' + chalk.red('❌ Failed webhooks:'));
123
+ console.log(`\n${chalk.red('❌ Failed webhooks:')}`);
124
124
  results
125
125
  .filter((result) => !result.success)
126
126
  .forEach((result, index) => {
@@ -206,7 +206,7 @@ export async function createAction(options) {
206
206
  config.webhookSecrets[webhook.id] = webhook.attributes.secret;
207
207
  await configManager.save(config);
208
208
  }
209
- console.log('\n' + chalk.green('✓ Webhook created successfully!'));
209
+ console.log(`\n${chalk.green('✓ Webhook created successfully!')}`);
210
210
  console.log('');
211
211
  console.log(chalk.bold('ID:'), webhook.id);
212
212
  console.log(chalk.bold('URL:'), webhook.attributes.url);
@@ -276,7 +276,7 @@ export async function listAction(options) {
276
276
  console.log(JSON.stringify(filteredWebhooks, null, 2));
277
277
  return;
278
278
  }
279
- console.log('\n' + chalk.bold('Webhooks'));
279
+ console.log(`\n${chalk.bold('Webhooks')}`);
280
280
  console.log(chalk.gray('─'.repeat(95)));
281
281
  const table = new Table({
282
282
  head: [chalk.bold('ID'), chalk.bold('URL'), chalk.bold('Status'), chalk.bold('Events')],
@@ -289,7 +289,7 @@ export async function listAction(options) {
289
289
  filteredWebhooks.forEach((webhook) => {
290
290
  const id = webhook.id.substring(0, 12) + (webhook.id.length > 12 ? '...' : '');
291
291
  const url = webhook.attributes.url.length > 30
292
- ? webhook.attributes.url.substring(0, 27) + '...'
292
+ ? `${webhook.attributes.url.substring(0, 27)}...`
293
293
  : webhook.attributes.url;
294
294
  const events = webhook.attributes.events.length > 1
295
295
  ? `${webhook.attributes.events[0]} +${webhook.attributes.events.length - 1} more`
@@ -415,7 +415,7 @@ export async function showAction(id) {
415
415
  spinner.start('Fetching webhook details...');
416
416
  const webhook = await createApiClient(config).getWebhook(id);
417
417
  spinner.succeed('Webhook details loaded');
418
- console.log('\n' + chalk.bold('Webhook Details'));
418
+ console.log(`\n${chalk.bold('Webhook Details')}`);
419
419
  console.log('═'.repeat(50));
420
420
  console.log(chalk.bold('ID:'), webhook.id);
421
421
  console.log(chalk.bold('URL:'), webhook.attributes.url);
@@ -1,28 +1,13 @@
1
1
  import chalk from 'chalk';
2
- import ApiClient from '../../services/api/client.js';
3
- import ConfigManager from '../../services/config/manager.js';
4
- import Spinner from '../../utils/spinner.js';
5
- import { CommandError } from '../../utils/errors.js';
2
+ import { createCommandContext, createApiClient as createSharedApiClient, failCommand, loadCommandConfig, } from '../shared/runtime.js';
6
3
  export function createWebhooksContext() {
7
- return {
8
- spinner: new Spinner(),
9
- configManager: new ConfigManager(),
10
- };
4
+ return createCommandContext();
11
5
  }
12
6
  export async function loadWebhooksConfig(spinner, configManager) {
13
- spinner.start('Loading configuration...');
14
- const config = await configManager.load();
15
- if (!config) {
16
- spinner.fail('No configuration found');
17
- console.log(chalk.yellow('No PayMongo configuration found.'));
18
- console.log(chalk.gray("Run 'paymongo init' to set up your project first."));
19
- return null;
20
- }
21
- spinner.succeed('Configuration loaded');
22
- return config;
7
+ return loadCommandConfig(spinner, configManager);
23
8
  }
24
9
  export function createApiClient(config) {
25
- return new ApiClient({ config });
10
+ return createSharedApiClient(config);
26
11
  }
27
12
  export function getWebhookStatusColor(status) {
28
13
  switch (status) {
@@ -35,8 +20,5 @@ export function getWebhookStatusColor(status) {
35
20
  }
36
21
  }
37
22
  export function handleWebhooksError(prefix, spinner, error) {
38
- spinner.stop();
39
- const err = error;
40
- console.error(chalk.red(prefix), err.message);
41
- throw new CommandError();
23
+ return failCommand(prefix, error, spinner);
42
24
  }
@@ -37,5 +37,5 @@ const command = new Command('webhooks')
37
37
  .description('Show webhook details')
38
38
  .argument('<id>', 'Webhook ID to show')
39
39
  .action(async (id) => showAction(id)));
40
- export { exportAction, importAction, createAction, listAction, disableAction, enableAction, deleteAction, showAction, };
40
+ export { createAction, deleteAction, disableAction, enableAction, exportAction, importAction, listAction, showAction, };
41
41
  export default command;
package/dist/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from 'commander';
2
+ import { createRequire } from 'node:module';
3
3
  import chalk from 'chalk';
4
- import { createRequire } from 'module';
4
+ import { Command } from 'commander';
5
5
  import { CommandError } from './utils/errors.js';
6
6
  const require = createRequire(import.meta.url);
7
7
  const { version } = require('../package.json');
8
+ const uncaughtExceptionHandlerKey = Symbol.for('paymongo.cli.uncaughtExceptionHandler');
9
+ const unhandledRejectionHandlerKey = Symbol.for('paymongo.cli.unhandledRejectionHandler');
10
+ const globalHandlers = globalThis;
8
11
  const program = new Command();
9
12
  program
10
13
  .name('paymongo')
@@ -12,6 +15,15 @@ program
12
15
  .version(version)
13
16
  .option('--no-rate-limit', 'Disable rate limiting for this command')
14
17
  .showHelpAfterError('(add --help for additional information)');
18
+ program.hook('preAction', (actionCommand) => {
19
+ const options = actionCommand.optsWithGlobals();
20
+ if (options.rateLimit === false) {
21
+ process.env.PAYMONGO_DISABLE_RATE_LIMIT = '1';
22
+ }
23
+ else {
24
+ delete process.env.PAYMONGO_DISABLE_RATE_LIMIT;
25
+ }
26
+ });
15
27
  program.addCommand(await import('./commands/init.js').then((m) => m.default));
16
28
  program.addCommand((await import('./commands/dev.js')).command);
17
29
  program.addCommand((await import('./commands/login.js')).command);
@@ -20,6 +32,7 @@ program.addCommand(await import('./commands/webhooks.js').then((m) => m.default)
20
32
  program.addCommand(await import('./commands/payments.js').then((m) => m.default));
21
33
  program.addCommand(await import('./commands/trigger.js').then((m) => m.default));
22
34
  program.addCommand(await import('./commands/generate.js').then((m) => m.default));
35
+ program.addCommand(await import('./commands/doctor.js').then((m) => m.default));
23
36
  program.addCommand(await import('./commands/team/index.js').then((m) => m.default));
24
37
  program.addCommand(await import('./commands/env.js').then((m) => m.default));
25
38
  program.addHelpText('after', `
@@ -56,6 +69,10 @@ EXAMPLES
56
69
  $ paymongo generate payment-intent --language ts # Generate TypeScript payment intent code
57
70
  $ paymongo generate checkout-page --framework react # Generate React checkout component
58
71
 
72
+ Diagnostics:
73
+ $ paymongo doctor # Check config, keys, ngrok, and webhook setup
74
+ $ paymongo doctor --no-network # Run offline diagnostics only
75
+
59
76
  Team Collaboration:
60
77
  $ paymongo team create "My Team" # Create a new team
61
78
  $ paymongo team share live # Share live API keys with team
@@ -68,18 +85,24 @@ EXAMPLES
68
85
 
69
86
  For more information, visit: https://github.com/leodyversemilla07/paymongo-cli
70
87
  `);
71
- process.on('uncaughtException', (error) => {
72
- if (error instanceof CommandError) {
88
+ if (!globalHandlers[uncaughtExceptionHandlerKey]) {
89
+ globalHandlers[uncaughtExceptionHandlerKey] = (error) => {
90
+ if (error instanceof CommandError) {
91
+ process.exit(1);
92
+ }
93
+ console.error(chalk.red('An unexpected error occurred:'), error.message);
73
94
  process.exit(1);
74
- }
75
- console.error(chalk.red('An unexpected error occurred:'), error.message);
76
- process.exit(1);
77
- });
78
- process.on('unhandledRejection', (reason) => {
79
- if (reason instanceof CommandError) {
95
+ };
96
+ process.on('uncaughtException', globalHandlers[uncaughtExceptionHandlerKey]);
97
+ }
98
+ if (!globalHandlers[unhandledRejectionHandlerKey]) {
99
+ globalHandlers[unhandledRejectionHandlerKey] = (reason) => {
100
+ if (reason instanceof CommandError) {
101
+ process.exit(1);
102
+ }
103
+ console.error(chalk.red('An unexpected error occurred:'), reason instanceof Error ? reason.message : String(reason));
80
104
  process.exit(1);
81
- }
82
- console.error(chalk.red('An unexpected error occurred:'), reason instanceof Error ? reason.message : String(reason));
83
- process.exit(1);
84
- });
105
+ };
106
+ process.on('unhandledRejection', globalHandlers[unhandledRejectionHandlerKey]);
107
+ }
85
108
  program.parse();
@@ -1,6 +1,6 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import os from 'os';
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
4
  import Logger from '../../utils/logger.js';
5
5
  export class AnalyticsService {
6
6
  events = [];
@@ -1,8 +1,8 @@
1
1
  import { request } from 'undici';
2
- import { NetworkError, ApiKeyError, PayMongoError, withRetry } from '../../utils/errors.js';
3
2
  import Cache from '../../utils/cache.js';
3
+ import { CACHE_TTL, CLI_VERSION, PAYMONGO_API_BASE, RATE_LIMIT_DEFAULT_MAX, RATE_LIMIT_ENV_MULTIPLIER, RATE_LIMIT_PAYMENTS_MAX, RATE_LIMIT_REFUNDS_MAX, RATE_LIMIT_WEBHOOKS_MAX, RATE_LIMIT_WINDOW_MS, REQUEST_TIMEOUT, } from '../../utils/constants.js';
4
+ import { ApiKeyError, NetworkError, PayMongoError, withRetry } from '../../utils/errors.js';
4
5
  import RateLimiter from './rate-limiter.js';
5
- import { CLI_VERSION, REQUEST_TIMEOUT, CACHE_TTL, RATE_LIMIT_WINDOW_MS, RATE_LIMIT_DEFAULT_MAX, RATE_LIMIT_WEBHOOKS_MAX, RATE_LIMIT_PAYMENTS_MAX, RATE_LIMIT_REFUNDS_MAX, RATE_LIMIT_ENV_MULTIPLIER, PAYMONGO_API_BASE, } from '../../utils/constants.js';
6
6
  export class ApiClient {
7
7
  config;
8
8
  baseUrl;
@@ -19,7 +19,10 @@ export class ApiClient {
19
19
  'User-Agent': `paymongo-cli/${CLI_VERSION}`,
20
20
  };
21
21
  this.cache = new Cache({ ttl: CACHE_TTL });
22
- const rateLimitEnabled = options.enableRateLimiting !== false && this.config.rateLimiting?.enabled !== false;
22
+ const globalRateLimitDisabled = process.env.PAYMONGO_DISABLE_RATE_LIMIT === '1';
23
+ const rateLimitEnabled = options.enableRateLimiting !== false &&
24
+ !globalRateLimitDisabled &&
25
+ this.config.rateLimiting?.enabled !== false;
23
26
  if (rateLimitEnabled) {
24
27
  const rateLimitConfig = options.rateLimitConfig || this.getDefaultRateLimitConfig();
25
28
  if (this.config.rateLimiting) {
@@ -106,6 +109,7 @@ export class ApiClient {
106
109
  }
107
110
  const controller = new AbortController();
108
111
  const timeoutId = setTimeout(() => controller.abort(), this.timeout);
112
+ timeoutId.unref?.();
109
113
  try {
110
114
  const response = await request(url.toString(), {
111
115
  method,
@@ -120,7 +124,7 @@ export class ApiClient {
120
124
  }
121
125
  let data;
122
126
  const contentType = response.headers['content-type'];
123
- if (contentType && contentType.includes('application/json')) {
127
+ if (contentType?.includes('application/json')) {
124
128
  data = await response.body.json();
125
129
  }
126
130
  else {
@@ -1,8 +1,8 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
3
  import { cosmiconfig } from 'cosmiconfig';
4
- import { ConfigError, ValidationError } from '../../utils/errors.js';
5
4
  import { validateConfig as zodValidateConfig } from '../../types/schemas.js';
5
+ import { ConfigError, ValidationError } from '../../utils/errors.js';
6
6
  const CONFIG_FILE_NAME = '.paymongo';
7
7
  export class ConfigManager {
8
8
  explorer = cosmiconfig('paymongo');
@@ -1,7 +1,7 @@
1
- import fs from 'fs/promises';
2
- import * as path from 'path';
3
- import * as os from 'os';
4
- import { execSync } from 'child_process';
1
+ import { execSync } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import * as os from 'node:os';
4
+ import * as path from 'node:path';
5
5
  const STATE_DIR = path.join(os.homedir(), '.paymongo-cli');
6
6
  const STATE_FILE = path.join(STATE_DIR, 'dev-server.json');
7
7
  const LOG_FILE = path.join(STATE_DIR, 'dev-server.log');
@@ -1,8 +1,8 @@
1
- import * as http from 'http';
2
- import * as crypto from 'crypto';
1
+ import * as crypto from 'node:crypto';
2
+ import * as http from 'node:http';
3
3
  import chalk from 'chalk';
4
- import { AnalyticsService } from '../analytics/service.js';
5
4
  import Logger from '../../utils/logger.js';
5
+ import { AnalyticsService } from '../analytics/service.js';
6
6
  export class DevServer {
7
7
  server;
8
8
  port;
@@ -147,9 +147,7 @@ export class DevServer {
147
147
  break;
148
148
  }
149
149
  }
150
- catch (_error) {
151
- continue;
152
- }
150
+ catch (_error) { }
153
151
  }
154
152
  if (isValid) {
155
153
  this.logger.success('Signature verified successfully');