resend-cli 1.2.2 → 1.3.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.
Files changed (182) hide show
  1. package/README.md +25 -10
  2. package/dist/cli.cjs +562 -0
  3. package/package.json +31 -12
  4. package/.claude/settings.local.json +0 -5
  5. package/.github/scripts/pr-title-check.js +0 -34
  6. package/.github/workflows/ci.yml +0 -32
  7. package/.github/workflows/pr-title-check.yml +0 -13
  8. package/.github/workflows/release.yml +0 -120
  9. package/.github/workflows/test-install-windows.yml +0 -48
  10. package/CHANGELOG.md +0 -31
  11. package/biome.json +0 -36
  12. package/bun.lock +0 -73
  13. package/bunfig.toml +0 -2
  14. package/docs/agent-dx-gaps.md +0 -167
  15. package/docs/missing-commands.md +0 -58
  16. package/docs/production-readiness.md +0 -99
  17. package/docs/secure-key-storage.md +0 -174
  18. package/install.ps1 +0 -141
  19. package/install.sh +0 -301
  20. package/renovate.json +0 -4
  21. package/src/cli.ts +0 -92
  22. package/src/commands/api-keys/create.ts +0 -114
  23. package/src/commands/api-keys/delete.ts +0 -47
  24. package/src/commands/api-keys/index.ts +0 -26
  25. package/src/commands/api-keys/list.ts +0 -35
  26. package/src/commands/api-keys/utils.ts +0 -8
  27. package/src/commands/auth/index.ts +0 -20
  28. package/src/commands/auth/login.ts +0 -234
  29. package/src/commands/auth/logout.ts +0 -105
  30. package/src/commands/broadcasts/create.ts +0 -196
  31. package/src/commands/broadcasts/delete.ts +0 -46
  32. package/src/commands/broadcasts/get.ts +0 -59
  33. package/src/commands/broadcasts/index.ts +0 -43
  34. package/src/commands/broadcasts/list.ts +0 -60
  35. package/src/commands/broadcasts/send.ts +0 -56
  36. package/src/commands/broadcasts/update.ts +0 -95
  37. package/src/commands/broadcasts/utils.ts +0 -35
  38. package/src/commands/contact-properties/create.ts +0 -118
  39. package/src/commands/contact-properties/delete.ts +0 -48
  40. package/src/commands/contact-properties/get.ts +0 -46
  41. package/src/commands/contact-properties/index.ts +0 -48
  42. package/src/commands/contact-properties/list.ts +0 -68
  43. package/src/commands/contact-properties/update.ts +0 -88
  44. package/src/commands/contact-properties/utils.ts +0 -17
  45. package/src/commands/contacts/add-segment.ts +0 -78
  46. package/src/commands/contacts/create.ts +0 -122
  47. package/src/commands/contacts/delete.ts +0 -49
  48. package/src/commands/contacts/get.ts +0 -53
  49. package/src/commands/contacts/index.ts +0 -58
  50. package/src/commands/contacts/list.ts +0 -57
  51. package/src/commands/contacts/remove-segment.ts +0 -48
  52. package/src/commands/contacts/segments.ts +0 -39
  53. package/src/commands/contacts/topics.ts +0 -45
  54. package/src/commands/contacts/update-topics.ts +0 -90
  55. package/src/commands/contacts/update.ts +0 -77
  56. package/src/commands/contacts/utils.ts +0 -119
  57. package/src/commands/doctor.ts +0 -216
  58. package/src/commands/domains/create.ts +0 -83
  59. package/src/commands/domains/delete.ts +0 -42
  60. package/src/commands/domains/get.ts +0 -47
  61. package/src/commands/domains/index.ts +0 -35
  62. package/src/commands/domains/list.ts +0 -53
  63. package/src/commands/domains/update.ts +0 -75
  64. package/src/commands/domains/utils.ts +0 -44
  65. package/src/commands/domains/verify.ts +0 -38
  66. package/src/commands/emails/batch.ts +0 -140
  67. package/src/commands/emails/index.ts +0 -24
  68. package/src/commands/emails/receiving/attachment.ts +0 -55
  69. package/src/commands/emails/receiving/attachments.ts +0 -68
  70. package/src/commands/emails/receiving/get.ts +0 -58
  71. package/src/commands/emails/receiving/index.ts +0 -28
  72. package/src/commands/emails/receiving/list.ts +0 -59
  73. package/src/commands/emails/receiving/utils.ts +0 -38
  74. package/src/commands/emails/send.ts +0 -189
  75. package/src/commands/open.ts +0 -24
  76. package/src/commands/segments/create.ts +0 -50
  77. package/src/commands/segments/delete.ts +0 -47
  78. package/src/commands/segments/get.ts +0 -38
  79. package/src/commands/segments/index.ts +0 -36
  80. package/src/commands/segments/list.ts +0 -58
  81. package/src/commands/segments/utils.ts +0 -7
  82. package/src/commands/teams/index.ts +0 -10
  83. package/src/commands/teams/list.ts +0 -35
  84. package/src/commands/teams/remove.ts +0 -86
  85. package/src/commands/teams/switch.ts +0 -76
  86. package/src/commands/topics/create.ts +0 -73
  87. package/src/commands/topics/delete.ts +0 -47
  88. package/src/commands/topics/get.ts +0 -42
  89. package/src/commands/topics/index.ts +0 -42
  90. package/src/commands/topics/list.ts +0 -34
  91. package/src/commands/topics/update.ts +0 -59
  92. package/src/commands/topics/utils.ts +0 -16
  93. package/src/commands/webhooks/create.ts +0 -128
  94. package/src/commands/webhooks/delete.ts +0 -49
  95. package/src/commands/webhooks/get.ts +0 -42
  96. package/src/commands/webhooks/index.ts +0 -44
  97. package/src/commands/webhooks/list.ts +0 -55
  98. package/src/commands/webhooks/update.ts +0 -83
  99. package/src/commands/webhooks/utils.ts +0 -36
  100. package/src/commands/whoami.ts +0 -71
  101. package/src/lib/actions.ts +0 -157
  102. package/src/lib/client.ts +0 -37
  103. package/src/lib/config.ts +0 -217
  104. package/src/lib/files.ts +0 -15
  105. package/src/lib/help-text.ts +0 -38
  106. package/src/lib/output.ts +0 -54
  107. package/src/lib/pagination.ts +0 -36
  108. package/src/lib/prompts.ts +0 -149
  109. package/src/lib/spinner.ts +0 -100
  110. package/src/lib/table.ts +0 -57
  111. package/src/lib/tty.ts +0 -28
  112. package/src/lib/update-check.ts +0 -172
  113. package/src/lib/version.ts +0 -4
  114. package/tests/commands/api-keys/create.test.ts +0 -195
  115. package/tests/commands/api-keys/delete.test.ts +0 -156
  116. package/tests/commands/api-keys/list.test.ts +0 -133
  117. package/tests/commands/auth/login.test.ts +0 -156
  118. package/tests/commands/auth/logout.test.ts +0 -146
  119. package/tests/commands/broadcasts/create.test.ts +0 -447
  120. package/tests/commands/broadcasts/delete.test.ts +0 -182
  121. package/tests/commands/broadcasts/get.test.ts +0 -146
  122. package/tests/commands/broadcasts/list.test.ts +0 -196
  123. package/tests/commands/broadcasts/send.test.ts +0 -161
  124. package/tests/commands/broadcasts/update.test.ts +0 -283
  125. package/tests/commands/contact-properties/create.test.ts +0 -250
  126. package/tests/commands/contact-properties/delete.test.ts +0 -183
  127. package/tests/commands/contact-properties/get.test.ts +0 -144
  128. package/tests/commands/contact-properties/list.test.ts +0 -180
  129. package/tests/commands/contact-properties/update.test.ts +0 -216
  130. package/tests/commands/contacts/add-segment.test.ts +0 -188
  131. package/tests/commands/contacts/create.test.ts +0 -270
  132. package/tests/commands/contacts/delete.test.ts +0 -192
  133. package/tests/commands/contacts/get.test.ts +0 -148
  134. package/tests/commands/contacts/list.test.ts +0 -175
  135. package/tests/commands/contacts/remove-segment.test.ts +0 -166
  136. package/tests/commands/contacts/segments.test.ts +0 -167
  137. package/tests/commands/contacts/topics.test.ts +0 -163
  138. package/tests/commands/contacts/update-topics.test.ts +0 -247
  139. package/tests/commands/contacts/update.test.ts +0 -205
  140. package/tests/commands/doctor.test.ts +0 -165
  141. package/tests/commands/domains/create.test.ts +0 -192
  142. package/tests/commands/domains/delete.test.ts +0 -156
  143. package/tests/commands/domains/get.test.ts +0 -137
  144. package/tests/commands/domains/list.test.ts +0 -164
  145. package/tests/commands/domains/update.test.ts +0 -223
  146. package/tests/commands/domains/verify.test.ts +0 -117
  147. package/tests/commands/emails/batch.test.ts +0 -313
  148. package/tests/commands/emails/receiving/attachment.test.ts +0 -140
  149. package/tests/commands/emails/receiving/attachments.test.ts +0 -168
  150. package/tests/commands/emails/receiving/get.test.ts +0 -140
  151. package/tests/commands/emails/receiving/list.test.ts +0 -181
  152. package/tests/commands/emails/send.test.ts +0 -309
  153. package/tests/commands/segments/create.test.ts +0 -163
  154. package/tests/commands/segments/delete.test.ts +0 -182
  155. package/tests/commands/segments/get.test.ts +0 -137
  156. package/tests/commands/segments/list.test.ts +0 -173
  157. package/tests/commands/teams/list.test.ts +0 -63
  158. package/tests/commands/teams/remove.test.ts +0 -103
  159. package/tests/commands/teams/switch.test.ts +0 -96
  160. package/tests/commands/topics/create.test.ts +0 -191
  161. package/tests/commands/topics/delete.test.ts +0 -156
  162. package/tests/commands/topics/get.test.ts +0 -125
  163. package/tests/commands/topics/list.test.ts +0 -124
  164. package/tests/commands/topics/update.test.ts +0 -177
  165. package/tests/commands/webhooks/create.test.ts +0 -224
  166. package/tests/commands/webhooks/delete.test.ts +0 -156
  167. package/tests/commands/webhooks/get.test.ts +0 -125
  168. package/tests/commands/webhooks/list.test.ts +0 -177
  169. package/tests/commands/webhooks/update.test.ts +0 -206
  170. package/tests/commands/whoami.test.ts +0 -99
  171. package/tests/helpers.ts +0 -93
  172. package/tests/lib/client.test.ts +0 -71
  173. package/tests/lib/config.test.ts +0 -445
  174. package/tests/lib/files.test.ts +0 -65
  175. package/tests/lib/help-text.test.ts +0 -97
  176. package/tests/lib/output.test.ts +0 -127
  177. package/tests/lib/prompts.test.ts +0 -178
  178. package/tests/lib/spinner.test.ts +0 -146
  179. package/tests/lib/table.test.ts +0 -63
  180. package/tests/lib/tty.test.ts +0 -85
  181. package/tests/lib/update-check.test.ts +0 -169
  182. package/tsconfig.json +0 -14
@@ -1,83 +0,0 @@
1
- import { Command, Option } from '@commander-js/extra-typings';
2
- import type { WebhookEvent } from 'resend';
3
- import { runWrite } from '../../lib/actions';
4
- import type { GlobalOpts } from '../../lib/client';
5
- import { buildHelpText } from '../../lib/help-text';
6
- import { outputError } from '../../lib/output';
7
- import { ALL_WEBHOOK_EVENTS } from './utils';
8
-
9
- export const updateWebhookCommand = new Command('update')
10
- .description(
11
- "Update a webhook's endpoint URL, event subscriptions, or enabled status",
12
- )
13
- .argument('<id>', 'Webhook UUID')
14
- .option('--endpoint <endpoint>', 'New HTTPS URL for this webhook')
15
- .option(
16
- '--events <events...>',
17
- 'Replace the full event subscription list. Use "all" for all 17 events.',
18
- )
19
- .addOption(
20
- new Option(
21
- '--status <status>',
22
- 'Enable or disable event delivery for this webhook',
23
- ).choices(['enabled', 'disabled'] as const),
24
- )
25
- .addHelpText(
26
- 'after',
27
- buildHelpText({
28
- context: `At least one of --endpoint, --events, or --status must be provided.
29
-
30
- --events replaces the entire event list (it is not additive).
31
- Use "all" as a shorthand for all 17 event types.
32
-
33
- --status controls whether events are delivered to this endpoint:
34
- enabled Events are delivered (default on creation)
35
- disabled Events are suppressed without deleting the webhook`,
36
- output: ` {"object":"webhook","id":"<uuid>"}`,
37
- errorCodes: ['auth_error', 'no_changes', 'update_error'],
38
- examples: [
39
- 'resend webhooks update wh_abc123 --endpoint https://new-app.example.com/hooks/resend',
40
- 'resend webhooks update wh_abc123 --events email.sent email.bounced',
41
- 'resend webhooks update wh_abc123 --events all',
42
- 'resend webhooks update wh_abc123 --status disabled',
43
- 'resend webhooks update wh_abc123 --endpoint https://new-app.example.com/hooks/resend --events all --json',
44
- ],
45
- }),
46
- )
47
- .action(async (id, opts, cmd) => {
48
- const globalOpts = cmd.optsWithGlobals() as GlobalOpts;
49
-
50
- if (!opts.endpoint && !opts.events?.length && !opts.status) {
51
- outputError(
52
- {
53
- message:
54
- 'Provide at least one option to update: --endpoint, --events, or --status.',
55
- code: 'no_changes',
56
- },
57
- { json: globalOpts.json },
58
- );
59
- }
60
-
61
- const selectedEvents = opts.events?.includes('all')
62
- ? ALL_WEBHOOK_EVENTS
63
- : (opts.events as WebhookEvent[] | undefined);
64
-
65
- await runWrite(
66
- {
67
- spinner: {
68
- loading: 'Updating webhook...',
69
- success: 'Webhook updated',
70
- fail: 'Failed to update webhook',
71
- },
72
- sdkCall: (resend) =>
73
- resend.webhooks.update(id, {
74
- ...(opts.endpoint && { endpoint: opts.endpoint }),
75
- ...(selectedEvents?.length && { events: selectedEvents }),
76
- ...(opts.status && { status: opts.status }),
77
- }),
78
- errorCode: 'update_error',
79
- successMsg: `Webhook updated: ${id}`,
80
- },
81
- globalOpts,
82
- );
83
- });
@@ -1,36 +0,0 @@
1
- import type { Webhook, WebhookEvent } from 'resend';
2
- import { renderTable } from '../../lib/table';
3
-
4
- export const ALL_WEBHOOK_EVENTS: WebhookEvent[] = [
5
- 'email.sent',
6
- 'email.delivered',
7
- 'email.delivery_delayed',
8
- 'email.bounced',
9
- 'email.complained',
10
- 'email.opened',
11
- 'email.clicked',
12
- 'email.failed',
13
- 'email.scheduled',
14
- 'email.suppressed',
15
- 'email.received',
16
- 'contact.created',
17
- 'contact.updated',
18
- 'contact.deleted',
19
- 'domain.created',
20
- 'domain.updated',
21
- 'domain.deleted',
22
- ];
23
-
24
- export function renderWebhooksTable(webhooks: Webhook[]): string {
25
- const rows = webhooks.map((w) => {
26
- const eventsStr = (w.events ?? []).join(', ');
27
- const events =
28
- eventsStr.length > 60 ? `${eventsStr.slice(0, 57)}...` : eventsStr;
29
- return [w.endpoint, events, w.status, w.id];
30
- });
31
- return renderTable(
32
- ['Endpoint', 'Events', 'Status', 'ID'],
33
- rows,
34
- '(no webhooks)',
35
- );
36
- }
@@ -1,71 +0,0 @@
1
- import { Command } from '@commander-js/extra-typings';
2
- import type { GlobalOpts } from '../lib/client';
3
- import { maskKey, resolveApiKey, resolveTeamName } from '../lib/config';
4
- import { buildHelpText } from '../lib/help-text';
5
- import { outputError, outputResult } from '../lib/output';
6
- import { isInteractive } from '../lib/tty';
7
-
8
- export const whoamiCommand = new Command('whoami')
9
- .description('Show current authentication status')
10
- .addHelpText(
11
- 'after',
12
- buildHelpText({
13
- setup: true,
14
- context: `Local only — no network calls.
15
- Shows which team is active and where the API key comes from.`,
16
- output: ` {"authenticated":true,"team":"production","api_key":"re_...abcd","source":"config"}
17
- {"authenticated":false}`,
18
- examples: [
19
- 'resend whoami',
20
- 'resend whoami --json',
21
- 'resend whoami --team production',
22
- ],
23
- }),
24
- )
25
- .action((_opts, cmd) => {
26
- const globalOpts = cmd.optsWithGlobals() as GlobalOpts;
27
- const teamName = globalOpts.team;
28
- const resolved = resolveApiKey(globalOpts.apiKey, teamName);
29
-
30
- if (!resolved) {
31
- if (globalOpts.json || !isInteractive()) {
32
- outputResult(
33
- { authenticated: false },
34
- { json: globalOpts.json, exitCode: 1 },
35
- );
36
- // outputResult with exitCode calls process.exit, but TS doesn't know
37
- return;
38
- }
39
- outputError(
40
- {
41
- message: 'Not authenticated.\nRun `resend login` to get started.',
42
- code: 'not_authenticated',
43
- },
44
- { json: false },
45
- );
46
- return;
47
- }
48
-
49
- const team = resolved.team ?? resolveTeamName(teamName);
50
-
51
- if (globalOpts.json || !isInteractive()) {
52
- outputResult(
53
- {
54
- authenticated: true,
55
- team,
56
- api_key: maskKey(resolved.key),
57
- source: resolved.source,
58
- },
59
- { json: globalOpts.json },
60
- );
61
- return;
62
- }
63
-
64
- console.log('');
65
- console.log(` Team: ${team}`);
66
- console.log(` API Key: ${maskKey(resolved.key)}`);
67
- console.log(
68
- ` Source: ${resolved.source === 'config' ? 'config file' : resolved.source === 'env' ? 'environment variable' : 'flag'}`,
69
- );
70
- console.log('');
71
- });
@@ -1,157 +0,0 @@
1
- import type { Resend } from 'resend';
2
- import type { GlobalOpts } from './client';
3
- import { requireClient } from './client';
4
- import { outputResult } from './output';
5
- import { confirmDelete } from './prompts';
6
- import { withSpinner } from './spinner';
7
- import { isInteractive } from './tty';
8
-
9
- type SdkCall<T> = (
10
- resend: Resend,
11
- ) => Promise<{ data: T | null; error: { message: string } | null }>;
12
- type SpinnerMessages = { loading: string; success: string; fail: string };
13
-
14
- /**
15
- * Shared pattern for all get commands:
16
- * requireClient → withSpinner(fetch_error) → if/else output
17
- */
18
- export async function runGet<T>(
19
- config: {
20
- spinner: SpinnerMessages;
21
- sdkCall: SdkCall<T>;
22
- onInteractive: (data: T) => void;
23
- },
24
- globalOpts: GlobalOpts,
25
- ): Promise<void> {
26
- const resend = requireClient(globalOpts);
27
- const data = await withSpinner(
28
- config.spinner,
29
- () => config.sdkCall(resend),
30
- 'fetch_error',
31
- globalOpts,
32
- );
33
- if (!globalOpts.json && isInteractive()) {
34
- config.onInteractive(data);
35
- } else {
36
- outputResult(data, { json: globalOpts.json });
37
- }
38
- }
39
-
40
- /**
41
- * Shared pattern for all delete commands:
42
- * requireClient → confirmDelete (if needed) → withSpinner → if/else output
43
- */
44
- export async function runDelete(
45
- id: string,
46
- skipConfirm: boolean,
47
- config: {
48
- confirmMessage: string;
49
- spinner: SpinnerMessages;
50
- object: string;
51
- successMsg: string;
52
- sdkCall: SdkCall<unknown>;
53
- },
54
- globalOpts: GlobalOpts,
55
- ): Promise<void> {
56
- const resend = requireClient(globalOpts);
57
- if (!skipConfirm) {
58
- await confirmDelete(id, config.confirmMessage, globalOpts);
59
- }
60
- await withSpinner(
61
- config.spinner,
62
- () => config.sdkCall(resend),
63
- 'delete_error',
64
- globalOpts,
65
- );
66
- if (!globalOpts.json && isInteractive()) {
67
- console.log(config.successMsg);
68
- } else {
69
- outputResult(
70
- { object: config.object, id, deleted: true },
71
- { json: globalOpts.json },
72
- );
73
- }
74
- }
75
-
76
- /**
77
- * Shared pattern for create commands:
78
- * requireClient → withSpinner('create_error') → if/else output
79
- */
80
- export async function runCreate<T>(
81
- config: {
82
- spinner: SpinnerMessages;
83
- sdkCall: SdkCall<T>;
84
- onInteractive: (data: T) => void;
85
- },
86
- globalOpts: GlobalOpts,
87
- ): Promise<void> {
88
- const resend = requireClient(globalOpts);
89
- const data = await withSpinner(
90
- config.spinner,
91
- () => config.sdkCall(resend),
92
- 'create_error',
93
- globalOpts,
94
- );
95
- if (!globalOpts.json && isInteractive()) {
96
- config.onInteractive(data);
97
- } else {
98
- outputResult(data, { json: globalOpts.json });
99
- }
100
- }
101
-
102
- /**
103
- * Shared pattern for write commands (update/verify/remove-segment) where
104
- * interactive output is a single status message:
105
- * requireClient → withSpinner(errorCode) → if/else output
106
- */
107
- export async function runWrite<T>(
108
- config: {
109
- spinner: SpinnerMessages;
110
- sdkCall: SdkCall<T>;
111
- errorCode: string;
112
- successMsg: string;
113
- },
114
- globalOpts: GlobalOpts,
115
- ): Promise<void> {
116
- const resend = requireClient(globalOpts);
117
- const data = await withSpinner(
118
- config.spinner,
119
- () => config.sdkCall(resend),
120
- config.errorCode,
121
- globalOpts,
122
- );
123
- if (!globalOpts.json && isInteractive()) {
124
- console.log(config.successMsg);
125
- } else {
126
- outputResult(data, { json: globalOpts.json });
127
- }
128
- }
129
-
130
- /**
131
- * Shared pattern for all list commands:
132
- * requireClient → withSpinner → if/else output
133
- *
134
- * Callers pass pagination opts (if any) via the sdkCall closure.
135
- * The onInteractive callback handles table rendering and pagination hints.
136
- */
137
- export async function runList<T>(
138
- config: {
139
- spinner: SpinnerMessages;
140
- sdkCall: SdkCall<T>;
141
- onInteractive: (result: T) => void;
142
- },
143
- globalOpts: GlobalOpts,
144
- ): Promise<void> {
145
- const resend = requireClient(globalOpts);
146
- const result = await withSpinner(
147
- config.spinner,
148
- () => config.sdkCall(resend),
149
- 'list_error',
150
- globalOpts,
151
- );
152
- if (!globalOpts.json && isInteractive()) {
153
- config.onInteractive(result);
154
- } else {
155
- outputResult(result, { json: globalOpts.json });
156
- }
157
- }
package/src/lib/client.ts DELETED
@@ -1,37 +0,0 @@
1
- import { Resend } from 'resend';
2
- import { resolveApiKey } from './config';
3
- import { errorMessage, outputError } from './output';
4
- import { VERSION } from './version';
5
-
6
- export type GlobalOpts = {
7
- apiKey?: string;
8
- json?: boolean;
9
- quiet?: boolean;
10
- team?: string;
11
- };
12
-
13
- process.env.RESEND_USER_AGENT = `resend-cli:${VERSION}`;
14
-
15
- export function createClient(flagValue?: string, teamName?: string): Resend {
16
- const resolved = resolveApiKey(flagValue, teamName);
17
- if (!resolved) {
18
- throw new Error(
19
- 'No API key found. Set RESEND_API_KEY, use --api-key, or run: resend login',
20
- );
21
- }
22
- return new Resend(resolved.key);
23
- }
24
-
25
- export function requireClient(opts: GlobalOpts): Resend {
26
- try {
27
- return createClient(opts.apiKey, opts.team);
28
- } catch (err) {
29
- outputError(
30
- {
31
- message: errorMessage(err, 'Failed to create client'),
32
- code: 'auth_error',
33
- },
34
- { json: opts.json },
35
- );
36
- }
37
- }
package/src/lib/config.ts DELETED
@@ -1,217 +0,0 @@
1
- import {
2
- chmodSync,
3
- existsSync,
4
- mkdirSync,
5
- readFileSync,
6
- unlinkSync,
7
- writeFileSync,
8
- } from 'node:fs';
9
- import { homedir } from 'node:os';
10
- import { join } from 'node:path';
11
-
12
- export type ApiKeySource = 'flag' | 'env' | 'config';
13
- export type ResolvedKey = { key: string; source: ApiKeySource; team?: string };
14
-
15
- export type TeamProfile = { api_key: string };
16
- export type CredentialsFile = {
17
- active_team: string;
18
- teams: Record<string, TeamProfile>;
19
- };
20
-
21
- export function getConfigDir(): string {
22
- if (process.env.XDG_CONFIG_HOME) {
23
- return join(process.env.XDG_CONFIG_HOME, 'resend');
24
- }
25
- if (process.platform === 'win32' && process.env.APPDATA) {
26
- return join(process.env.APPDATA, 'resend');
27
- }
28
- return join(homedir(), '.config', 'resend');
29
- }
30
-
31
- function getCredentialsPath(): string {
32
- return join(getConfigDir(), 'credentials.json');
33
- }
34
-
35
- export function readCredentials(): CredentialsFile | null {
36
- try {
37
- const data = JSON.parse(readFileSync(getCredentialsPath(), 'utf-8'));
38
- // Support legacy format: { api_key: "re_xxx" }
39
- if (data.api_key && !data.teams) {
40
- return {
41
- active_team: 'default',
42
- teams: { default: { api_key: data.api_key } },
43
- };
44
- }
45
- if (data.teams) {
46
- return data as CredentialsFile;
47
- }
48
- return null;
49
- } catch {
50
- return null;
51
- }
52
- }
53
-
54
- export function writeCredentials(creds: CredentialsFile): string {
55
- const configDir = getConfigDir();
56
- mkdirSync(configDir, { recursive: true, mode: 0o700 });
57
-
58
- const configPath = getCredentialsPath();
59
- writeFileSync(configPath, `${JSON.stringify(creds, null, 2)}\n`, {
60
- mode: 0o600,
61
- });
62
- chmodSync(configPath, 0o600);
63
-
64
- return configPath;
65
- }
66
-
67
- export function resolveTeamName(flagValue?: string): string {
68
- if (flagValue) {
69
- return flagValue;
70
- }
71
-
72
- const envTeam = process.env.RESEND_TEAM;
73
- if (envTeam) {
74
- return envTeam;
75
- }
76
-
77
- const creds = readCredentials();
78
- if (creds?.active_team) {
79
- return creds.active_team;
80
- }
81
-
82
- return 'default';
83
- }
84
-
85
- export function resolveApiKey(
86
- flagValue?: string,
87
- teamName?: string,
88
- ): ResolvedKey | null {
89
- if (flagValue) {
90
- return { key: flagValue, source: 'flag' };
91
- }
92
-
93
- const envKey = process.env.RESEND_API_KEY;
94
- if (envKey) {
95
- return { key: envKey, source: 'env' };
96
- }
97
-
98
- const creds = readCredentials();
99
- if (creds) {
100
- const team = resolveTeamName(teamName);
101
- const profile = creds.teams[team];
102
- if (profile?.api_key) {
103
- return { key: profile.api_key, source: 'config', team };
104
- }
105
- }
106
-
107
- return null;
108
- }
109
-
110
- export function storeApiKey(apiKey: string, teamName?: string): string {
111
- const team = teamName || 'default';
112
- const validationError = validateTeamName(team);
113
- if (validationError) {
114
- throw new Error(validationError);
115
- }
116
- const creds = readCredentials() || { active_team: 'default', teams: {} };
117
-
118
- creds.teams[team] = { api_key: apiKey };
119
-
120
- // If this is the first team, set it as active
121
- if (Object.keys(creds.teams).length === 1) {
122
- creds.active_team = team;
123
- }
124
-
125
- return writeCredentials(creds);
126
- }
127
-
128
- export function removeAllApiKeys(): string {
129
- const configPath = getCredentialsPath();
130
- unlinkSync(configPath);
131
- return configPath;
132
- }
133
-
134
- export function removeApiKey(teamName?: string): string {
135
- const creds = readCredentials();
136
- if (!creds) {
137
- const configPath = getCredentialsPath();
138
- if (!existsSync(configPath)) {
139
- throw new Error('No credentials file found.');
140
- }
141
- // Try to delete legacy file
142
- unlinkSync(configPath);
143
- return configPath;
144
- }
145
-
146
- const team = teamName || resolveTeamName();
147
- if (!creds.teams[team]) {
148
- throw new Error(
149
- `Team "${team}" not found. Available teams: ${Object.keys(creds.teams).join(', ')}`,
150
- );
151
- }
152
- delete creds.teams[team];
153
-
154
- // If we removed the active team, switch to first available or "default"
155
- if (creds.active_team === team) {
156
- const remaining = Object.keys(creds.teams);
157
- creds.active_team = remaining[0] || 'default';
158
- }
159
-
160
- // If no teams left, delete the file
161
- if (Object.keys(creds.teams).length === 0) {
162
- const configPath = getCredentialsPath();
163
- unlinkSync(configPath);
164
- return configPath;
165
- }
166
-
167
- return writeCredentials(creds);
168
- }
169
-
170
- export function setActiveTeam(teamName: string): void {
171
- const validationError = validateTeamName(teamName);
172
- if (validationError) {
173
- throw new Error(validationError);
174
- }
175
- const creds = readCredentials();
176
- if (!creds) {
177
- throw new Error('No credentials file found. Run: resend login');
178
- }
179
- if (!creds.teams[teamName]) {
180
- throw new Error(
181
- `Team "${teamName}" not found. Available teams: ${Object.keys(creds.teams).join(', ')}`,
182
- );
183
- }
184
- creds.active_team = teamName;
185
- writeCredentials(creds);
186
- }
187
-
188
- export function listTeams(): Array<{ name: string; active: boolean }> {
189
- const creds = readCredentials();
190
- if (!creds) {
191
- return [];
192
- }
193
- return Object.keys(creds.teams).map((name) => ({
194
- name,
195
- active: name === creds.active_team,
196
- }));
197
- }
198
-
199
- export function validateTeamName(name: string): string | undefined {
200
- if (!name || name.length === 0) {
201
- return 'Team name must not be empty';
202
- }
203
- if (name.length > 64) {
204
- return 'Team name must be 64 characters or fewer';
205
- }
206
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
207
- return 'Team name must contain only letters, numbers, dashes, and underscores';
208
- }
209
- return undefined;
210
- }
211
-
212
- export function maskKey(key: string): string {
213
- if (key.length <= 7) {
214
- return `${key.slice(0, 3)}...`;
215
- }
216
- return `${key.slice(0, 3)}...${key.slice(-4)}`;
217
- }
package/src/lib/files.ts DELETED
@@ -1,15 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import type { GlobalOpts } from './client';
3
- import { outputError } from './output';
4
-
5
- /** Read a text file, exiting with file_read_error if unreadable. */
6
- export function readFile(filePath: string, globalOpts: GlobalOpts): string {
7
- try {
8
- return readFileSync(filePath, 'utf-8');
9
- } catch {
10
- outputError(
11
- { message: `Failed to read file: ${filePath}`, code: 'file_read_error' },
12
- { json: globalOpts.json },
13
- );
14
- }
15
- }
@@ -1,38 +0,0 @@
1
- export interface HelpTextOptions {
2
- context?: string; // All text before Global options (includes Non-interactive line if needed)
3
- output?: string; // Content after "Output (--json or piped):" header (raw string, may be multi-line)
4
- errorCodes?: string[]; // ['auth_error', 'list_error'] — joined with ' | '
5
- examples: string[]; // Command strings without '$ ' prefix (added automatically)
6
- setup?: boolean; // true = --json only (no --api-key); default false = full API variant
7
- }
8
-
9
- const GLOBAL_OPTS_FULL = `Global options:
10
- --api-key <key> API key (or set RESEND_API_KEY env var)
11
- --team <name> Team profile to use (overrides RESEND_TEAM)
12
- --json Force JSON output (also auto-enabled when stdout is piped)
13
- -q, --quiet Suppress spinners and status output (implies --json)`;
14
-
15
- const GLOBAL_OPTS_SETUP = `Global options:
16
- --team <name> Team profile to save the key to
17
- --json Force JSON output
18
- -q, --quiet Suppress spinners and status output (implies --json)`;
19
-
20
- const ERROR_ENVELOPE = ` {"error":{"message":"<message>","code":"<code>"}}`;
21
-
22
- export function buildHelpText(opts: HelpTextOptions): string {
23
- const parts: string[] = [];
24
- if (opts.context != null) {
25
- parts.push(opts.context);
26
- }
27
- parts.push(opts.setup ? GLOBAL_OPTS_SETUP : GLOBAL_OPTS_FULL);
28
- if (opts.output != null) {
29
- parts.push(`Output (--json or piped):\n${opts.output}`);
30
- }
31
- if (opts.errorCodes != null) {
32
- parts.push(
33
- `Errors (exit code 1):\n${ERROR_ENVELOPE}\n Codes: ${opts.errorCodes.join(' | ')}`,
34
- );
35
- }
36
- parts.push(`Examples:\n${opts.examples.map((e) => ` $ ${e}`).join('\n')}`);
37
- return `\n${parts.join('\n\n')}`;
38
- }