@nuelink/nuelink-cli 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/commands.js CHANGED
@@ -1,19 +1,34 @@
1
+ import { openAsBlob } from "node:fs";
1
2
  import { readFile, stat } from "node:fs/promises";
3
+ import readline from "node:readline";
2
4
  import path from "node:path";
3
5
  import chalk from "chalk";
4
6
 
5
- import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey } from "./config.js";
7
+ import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey, saveApiKey } from "./config.js";
6
8
  import { brandPath, collectionPath, nuelinkRequest } from "./http.js";
7
- import { buildPostPayload, parseCsv } from "./postPayload.js";
8
-
9
- function extractAuthArg(args) {
9
+ import { buildPostPayload, parseCsv, VALID_PUBLISH_MODES } from "./postPayload.js";
10
+ import {
11
+ VALID_AUTOMATION_SUB_TYPES,
12
+ VALID_AUTOMATION_TYPES,
13
+ VALID_IMPORT_AS_TYPES,
14
+ normalizeEnum,
15
+ parseJsonString,
16
+ parseOptionalPositiveInteger,
17
+ parsePositiveInteger,
18
+ splitCsv,
19
+ validateHttpUrl,
20
+ validateMediaFile,
21
+ validateQueueSlots,
22
+ } from "./validation.js";
23
+
24
+ function extractApiKeyArg(args) {
10
25
  const sanitizedArgs = [];
11
26
  let apiKey;
12
27
 
13
28
  for (let index = 0; index < args.length; index += 1) {
14
29
  const arg = args[index];
15
30
 
16
- if (arg === "--auth" || arg === "-a") {
31
+ if (arg === "--api-key" || arg === "--auth" || arg === "-a") {
17
32
  const next = args[index + 1];
18
33
  if (next && !next.startsWith("-")) {
19
34
  apiKey = next;
@@ -22,6 +37,11 @@ function extractAuthArg(args) {
22
37
  }
23
38
  }
24
39
 
40
+ if (arg.startsWith("--api-key=")) {
41
+ apiKey = arg.slice("--api-key=".length);
42
+ continue;
43
+ }
44
+
25
45
  if (arg.startsWith("--auth=")) {
26
46
  apiKey = arg.slice("--auth=".length);
27
47
  continue;
@@ -33,6 +53,107 @@ function extractAuthArg(args) {
33
53
  return { apiKey, sanitizedArgs };
34
54
  }
35
55
 
56
+ async function readStdinText() {
57
+ return new Promise((resolve, reject) => {
58
+ let payload = "";
59
+
60
+ process.stdin.setEncoding("utf8");
61
+ process.stdin.on("data", (chunk) => {
62
+ payload += chunk;
63
+ });
64
+ process.stdin.on("end", () => {
65
+ resolve(payload.trim());
66
+ });
67
+ process.stdin.on("error", reject);
68
+ process.stdin.resume();
69
+ });
70
+ }
71
+
72
+ async function promptHidden(promptText) {
73
+ return new Promise((resolve, reject) => {
74
+ const stdin = process.stdin;
75
+ const stdout = process.stdout;
76
+ const wasRaw = stdin.isTTY ? stdin.isRaw : false;
77
+ let value = "";
78
+
79
+ const cleanup = () => {
80
+ stdin.removeListener("keypress", onKeypress);
81
+
82
+ if (stdin.isTTY) {
83
+ stdin.setRawMode(Boolean(wasRaw));
84
+ }
85
+
86
+ stdout.write("\n");
87
+ };
88
+
89
+ const onKeypress = (character, key) => {
90
+ if (key?.ctrl && key.name === "c") {
91
+ cleanup();
92
+ reject(new Error("Authentication cancelled."));
93
+ return;
94
+ }
95
+
96
+ if (key?.name === "return" || key?.name === "enter") {
97
+ cleanup();
98
+ resolve(value.trim());
99
+ return;
100
+ }
101
+
102
+ if (key?.name === "backspace") {
103
+ value = value.slice(0, -1);
104
+ return;
105
+ }
106
+
107
+ if (character) {
108
+ value += character;
109
+ }
110
+ };
111
+
112
+ stdout.write(promptText);
113
+ readline.emitKeypressEvents(stdin);
114
+
115
+ if (stdin.isTTY) {
116
+ stdin.setRawMode(true);
117
+ }
118
+
119
+ stdin.resume();
120
+ stdin.on("keypress", onKeypress);
121
+ });
122
+ }
123
+
124
+ async function resolveLoginApiKey(options) {
125
+ if (options.apiKey) {
126
+ return options.apiKey.trim();
127
+ }
128
+
129
+ if (options.stdin || !process.stdin.isTTY) {
130
+ return readStdinText();
131
+ }
132
+
133
+ return promptHidden("API key: ");
134
+ }
135
+
136
+ function buildRequestOptions(program) {
137
+ const options = program.opts();
138
+
139
+ return {
140
+ dryRun: Boolean(options.dryRun),
141
+ outputMode: options.json ? "json" : "table",
142
+ quiet: Boolean(options.quiet),
143
+ };
144
+ }
145
+
146
+ async function executeRequest(program, runtimeApiKey, request) {
147
+ const requestOptions = buildRequestOptions(program);
148
+ const apiKey = requestOptions.dryRun ? undefined : await resolveApiKey(runtimeApiKey);
149
+
150
+ return nuelinkRequest({
151
+ apiKey,
152
+ ...request,
153
+ ...requestOptions,
154
+ });
155
+ }
156
+
36
157
  function withCommandErrorHandling(handler) {
37
158
  return async (...args) => {
38
159
  try {
@@ -44,12 +165,33 @@ function withCommandErrorHandling(handler) {
44
165
  };
45
166
  }
46
167
 
47
- function registerCommands(program, runtimeApiKey) {
168
+ function registerCommands(program, runtimeApiKey, cliVersion) {
48
169
  program
49
170
  .name("nuelink-cli")
50
- .version("1.0.0")
171
+ .version(cliVersion)
51
172
  .description("Nuelink CLI for the Public API")
52
- .option("-a, --auth <apiKey>", "Set and use API key");
173
+ .option("-a, --api-key <apiKey>", "Use API key for this invocation only")
174
+ .option("--auth <apiKey>", "Deprecated alias for --api-key")
175
+ .option("--dry-run", "Print the validated request without sending it")
176
+ .option("--json", "Output raw JSON instead of tables for list commands")
177
+ .option("--quiet", "Suppress non-essential success banners");
178
+
179
+ program
180
+ .command("auth:login")
181
+ .description("Persist an API key to local config")
182
+ .option("--api-key <apiKey>", "API key to save (prefer stdin or interactive prompt)")
183
+ .option("--stdin", "Read API key from stdin")
184
+ .action(withCommandErrorHandling(async (options) => {
185
+ const apiKey = await resolveLoginApiKey(options);
186
+
187
+ if (!apiKey) {
188
+ throw new Error("Missing API key. Provide --stdin, pipe a key to auth:login, or enter it interactively.");
189
+ }
190
+
191
+ process.env.NUELINK_API_KEY = apiKey;
192
+ await saveApiKey(apiKey);
193
+ console.log(chalk.green("API key saved to local config."));
194
+ }));
53
195
 
54
196
  program
55
197
  .command("auth:clear")
@@ -63,13 +205,13 @@ function registerCommands(program, runtimeApiKey) {
63
205
  .command("auth:status")
64
206
  .description("Show where auth is currently resolved from")
65
207
  .action(withCommandErrorHandling(async () => {
66
- if (runtimeApiKey) {
67
- console.log(chalk.green(`Auth source: CLI flag (${maskToken(runtimeApiKey)})`));
208
+ if (process.env.NUELINK_API_KEY) {
209
+ console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
68
210
  return;
69
211
  }
70
212
 
71
- if (process.env.NUELINK_API_KEY) {
72
- console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
213
+ if (runtimeApiKey) {
214
+ console.log(chalk.green(`Auth source: runtime CLI flag (${maskToken(runtimeApiKey)})`));
73
215
  return;
74
216
  }
75
217
 
@@ -89,15 +231,14 @@ function registerCommands(program, runtimeApiKey) {
89
231
  return;
90
232
  }
91
233
 
92
- console.log(chalk.yellow("No API key configured. Set one with --auth <api_key>."));
234
+ console.log(chalk.yellow("No API key configured. Use auth:login to save one, or pass --api-key for a single command."));
93
235
  }));
94
236
 
95
237
  program
96
238
  .command("me")
97
239
  .description("Get current profile")
98
240
  .action(withCommandErrorHandling(async () => {
99
- const apiKey = await resolveApiKey(runtimeApiKey);
100
- await nuelinkRequest({ apiKey, endpoint: "/me" });
241
+ await executeRequest(program, runtimeApiKey, { endpoint: "/me" });
101
242
  }));
102
243
 
103
244
  program
@@ -106,13 +247,11 @@ function registerCommands(program, runtimeApiKey) {
106
247
  .option("--per-page <number>", "Items per page", "25")
107
248
  .option("--page <number>", "Page number", "1")
108
249
  .action(withCommandErrorHandling(async (options) => {
109
- const apiKey = await resolveApiKey(runtimeApiKey);
110
- await nuelinkRequest({
111
- apiKey,
250
+ await executeRequest(program, runtimeApiKey, {
112
251
  endpoint: "/brands",
113
252
  query: {
114
- per_page: options.perPage,
115
- page: options.page,
253
+ per_page: parsePositiveInteger(options.perPage, "per-page"),
254
+ page: parsePositiveInteger(options.page, "page"),
116
255
  },
117
256
  });
118
257
  }));
@@ -124,13 +263,11 @@ function registerCommands(program, runtimeApiKey) {
124
263
  .option("--per-page <number>", "Items per page", "25")
125
264
  .option("--page <number>", "Page number", "1")
126
265
  .action(withCommandErrorHandling(async (options) => {
127
- const apiKey = await resolveApiKey(runtimeApiKey);
128
- await nuelinkRequest({
129
- apiKey,
130
- endpoint: `${brandPath(options.brandId)}/collections`,
266
+ await executeRequest(program, runtimeApiKey, {
267
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/collections`,
131
268
  query: {
132
- per_page: options.perPage,
133
- page: options.page,
269
+ per_page: parsePositiveInteger(options.perPage, "per-page"),
270
+ page: parsePositiveInteger(options.page, "page"),
134
271
  },
135
272
  });
136
273
  }));
@@ -145,17 +282,18 @@ function registerCommands(program, runtimeApiKey) {
145
282
  .option("--channels <ids>", "Comma-separated channel IDs")
146
283
  .option("--queues <slots>", "Comma-separated queue slots (e.g. Mon 10:10,Mon 12:12)")
147
284
  .action(withCommandErrorHandling(async (options) => {
148
- const apiKey = await resolveApiKey(runtimeApiKey);
149
- await nuelinkRequest({
150
- apiKey,
285
+ const channels = splitCsv(options.channels).map((id) => parsePositiveInteger(id, "channel-id"));
286
+ const queues = validateQueueSlots(splitCsv(options.queues));
287
+
288
+ await executeRequest(program, runtimeApiKey, {
151
289
  method: "POST",
152
- endpoint: `${brandPath(options.brandId)}/collections`,
290
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/collections`,
153
291
  body: {
154
292
  title: options.title,
155
293
  description: options.description,
156
- maxRepublish: options.maxRepublish ? Number(options.maxRepublish) : undefined,
157
- channels: parseCsv(options.channels).map((id) => Number(id)),
158
- queues: parseCsv(options.queues),
294
+ maxRepublish: parseOptionalPositiveInteger(options.maxRepublish, "max-republish"),
295
+ channels,
296
+ queues,
159
297
  },
160
298
  });
161
299
  }));
@@ -164,11 +302,15 @@ function registerCommands(program, runtimeApiKey) {
164
302
  .command("automations")
165
303
  .description("List automations for a brand")
166
304
  .requiredOption("--brand-id <id>", "Brand ID")
305
+ .option("--per-page <number>", "Items per page", "25")
306
+ .option("--page <number>", "Page number", "1")
167
307
  .action(withCommandErrorHandling(async (options) => {
168
- const apiKey = await resolveApiKey(runtimeApiKey);
169
- await nuelinkRequest({
170
- apiKey,
171
- endpoint: `${brandPath(options.brandId)}/automations`,
308
+ await executeRequest(program, runtimeApiKey, {
309
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
310
+ query: {
311
+ per_page: parsePositiveInteger(options.perPage, "per-page"),
312
+ page: parsePositiveInteger(options.page, "page"),
313
+ },
172
314
  });
173
315
  }));
174
316
 
@@ -186,18 +328,16 @@ function registerCommands(program, runtimeApiKey) {
186
328
  .option("--dynamic-body <text>", "Dynamic body", "{title} {link}")
187
329
  .option("--description <text>", "Automation description")
188
330
  .action(withCommandErrorHandling(async (options) => {
189
- const apiKey = await resolveApiKey(runtimeApiKey);
190
- await nuelinkRequest({
191
- apiKey,
331
+ await executeRequest(program, runtimeApiKey, {
192
332
  method: "POST",
193
- endpoint: `${brandPath(options.brandId)}/automations`,
333
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
194
334
  body: {
195
- collectionId: Number(options.collectionId),
196
- feedUrl: options.feedUrl,
197
- importAsType: options.importAsType,
198
- subType: options.subType,
335
+ collectionId: parsePositiveInteger(options.collectionId, "collection-id"),
336
+ feedUrl: validateHttpUrl(options.feedUrl, "feed-url"),
337
+ importAsType: normalizeEnum(options.importAsType, "import-as-type", VALID_IMPORT_AS_TYPES),
338
+ subType: normalizeEnum(options.subType, "sub-type", VALID_AUTOMATION_SUB_TYPES),
199
339
  title: options.title,
200
- type: options.type,
340
+ type: normalizeEnum(options.type, "type", VALID_AUTOMATION_TYPES),
201
341
  dynamicTitle: options.dynamicTitle,
202
342
  dynamicBody: options.dynamicBody,
203
343
  description: options.description,
@@ -212,13 +352,11 @@ function registerCommands(program, runtimeApiKey) {
212
352
  .option("--per-page <number>", "Items per page", "25")
213
353
  .option("--page <number>", "Page number", "1")
214
354
  .action(withCommandErrorHandling(async (options) => {
215
- const apiKey = await resolveApiKey(runtimeApiKey);
216
- await nuelinkRequest({
217
- apiKey,
218
- endpoint: `${brandPath(options.brandId)}/channels`,
355
+ await executeRequest(program, runtimeApiKey, {
356
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/channels`,
219
357
  query: {
220
- per_page: options.perPage,
221
- page: options.page,
358
+ per_page: parsePositiveInteger(options.perPage, "per-page"),
359
+ page: parsePositiveInteger(options.page, "page"),
222
360
  },
223
361
  });
224
362
  }));
@@ -227,11 +365,15 @@ function registerCommands(program, runtimeApiKey) {
227
365
  .command("media")
228
366
  .description("List media for a brand")
229
367
  .requiredOption("--brand-id <id>", "Brand ID")
368
+ .option("--per-page <number>", "Items per page", "25")
369
+ .option("--page <number>", "Page number", "1")
230
370
  .action(withCommandErrorHandling(async (options) => {
231
- const apiKey = await resolveApiKey(runtimeApiKey);
232
- await nuelinkRequest({
233
- apiKey,
234
- endpoint: `${brandPath(options.brandId)}/media`,
371
+ await executeRequest(program, runtimeApiKey, {
372
+ endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/media`,
373
+ query: {
374
+ per_page: parsePositiveInteger(options.perPage, "per-page"),
375
+ page: parsePositiveInteger(options.page, "page"),
376
+ },
235
377
  });
236
378
  }));
237
379
 
@@ -241,17 +383,22 @@ function registerCommands(program, runtimeApiKey) {
241
383
  .requiredOption("--brand-id <id>", "Brand ID")
242
384
  .requiredOption("--file <path>", "Path to local file")
243
385
  .action(withCommandErrorHandling(async (options) => {
244
- const apiKey = await resolveApiKey(runtimeApiKey);
245
-
246
- const fileBuffer = await readFile(options.file);
386
+ const brandId = parsePositiveInteger(options.brandId, "brand-id");
387
+ const fileStat = await stat(options.file);
388
+ const { mediaType, size } = validateMediaFile(options.file, fileStat);
247
389
  const formData = new FormData();
248
- formData.append("media", new Blob([fileBuffer]), path.basename(options.file));
390
+ const fileBlob = await openAsBlob(options.file, { type: mediaType });
391
+ formData.append("media", fileBlob, path.basename(options.file));
249
392
 
250
- await nuelinkRequest({
251
- apiKey,
393
+ await executeRequest(program, runtimeApiKey, {
252
394
  method: "POST",
253
- endpoint: `${brandPath(options.brandId)}/media`,
395
+ endpoint: `${brandPath(brandId)}/media`,
254
396
  multipart: formData,
397
+ dryRunBody: {
398
+ file: path.basename(options.file),
399
+ size,
400
+ type: mediaType,
401
+ },
255
402
  });
256
403
  }));
257
404
 
@@ -260,11 +407,18 @@ function registerCommands(program, runtimeApiKey) {
260
407
  .description("List posts in a collection")
261
408
  .requiredOption("--brand-id <id>", "Brand ID")
262
409
  .requiredOption("--collection-id <id>", "Collection ID")
410
+ .option("--per-page <number>", "Items per page", "25")
411
+ .option("--page <number>", "Page number", "1")
263
412
  .action(withCommandErrorHandling(async (options) => {
264
- const apiKey = await resolveApiKey(runtimeApiKey);
265
- await nuelinkRequest({
266
- apiKey,
267
- endpoint: `${collectionPath(options.brandId, options.collectionId)}/posts`,
413
+ await executeRequest(program, runtimeApiKey, {
414
+ endpoint: `${collectionPath(
415
+ parsePositiveInteger(options.brandId, "brand-id"),
416
+ parsePositiveInteger(options.collectionId, "collection-id"),
417
+ )}/posts`,
418
+ query: {
419
+ per_page: parsePositiveInteger(options.perPage, "per-page"),
420
+ page: parsePositiveInteger(options.page, "page"),
421
+ },
268
422
  });
269
423
  }));
270
424
 
@@ -275,14 +429,17 @@ function registerCommands(program, runtimeApiKey) {
275
429
  .requiredOption("--collection-id <id>", "Collection ID")
276
430
  .requiredOption("--payload <file>", "Path to JSON payload file")
277
431
  .action(withCommandErrorHandling(async (options) => {
278
- const apiKey = await resolveApiKey(runtimeApiKey);
279
- const payloadText = await readFile(options.payload, "utf8");
280
- const payload = JSON.parse(payloadText);
432
+ const payloadText = options.payload === "-"
433
+ ? await readStdinText()
434
+ : await readFile(options.payload, "utf8");
435
+ const payload = parseJsonString(payloadText, "payload");
281
436
 
282
- await nuelinkRequest({
283
- apiKey,
437
+ await executeRequest(program, runtimeApiKey, {
284
438
  method: "POST",
285
- endpoint: `${collectionPath(options.brandId, options.collectionId)}/posts`,
439
+ endpoint: `${collectionPath(
440
+ parsePositiveInteger(options.brandId, "brand-id"),
441
+ parsePositiveInteger(options.collectionId, "collection-id"),
442
+ )}/posts`,
286
443
  body: payload,
287
444
  });
288
445
  }));
@@ -296,7 +453,7 @@ function registerCommands(program, runtimeApiKey) {
296
453
  .option("--caption <text>", "Post caption/body")
297
454
  .option("--alt <text>", "Alt text")
298
455
  .option("--link <url>", "Post link")
299
- .option("--publish-mode <mode>", "Publish mode (e.g. DRAFT, NOW, SCHEDULE)", "DRAFT")
456
+ .option("--publish-mode <mode>", `Publish mode (${VALID_PUBLISH_MODES.join(", ")})`, "DRAFT")
300
457
  .option("--publish-at <value>", "Publish datetime (YYYY-MM-DD HH:mm:ss or ISO) or null")
301
458
  .option("--post-as-story <boolean>", "Post as story: true/false")
302
459
  .option("--post-type <type>", "Post type override")
@@ -321,19 +478,20 @@ function registerCommands(program, runtimeApiKey) {
321
478
  .option("--youtube-tags <tags>", "Comma-separated YouTube tags")
322
479
  .option("--youtube-playlists <json>", "YouTube playlists JSON string")
323
480
  .action(withCommandErrorHandling(async (options) => {
324
- const apiKey = await resolveApiKey(runtimeApiKey);
325
481
  const payload = buildPostPayload(options);
326
482
 
327
- await nuelinkRequest({
328
- apiKey,
483
+ await executeRequest(program, runtimeApiKey, {
329
484
  method: "POST",
330
- endpoint: `${collectionPath(options.brandId, options.collectionId)}/posts`,
485
+ endpoint: `${collectionPath(
486
+ parsePositiveInteger(options.brandId, "brand-id"),
487
+ parsePositiveInteger(options.collectionId, "collection-id"),
488
+ )}/posts`,
331
489
  body: payload,
332
490
  });
333
491
  }));
334
492
  }
335
493
 
336
494
  export {
337
- extractAuthArg,
495
+ extractApiKeyArg,
338
496
  registerCommands,
339
497
  };
package/src/config.js CHANGED
@@ -79,14 +79,15 @@ async function clearApiKey() {
79
79
  }
80
80
 
81
81
  async function resolveApiKey(runtimeApiKey) {
82
- if (runtimeApiKey) {
83
- return runtimeApiKey;
84
- }
85
-
86
82
  if (process.env.NUELINK_API_KEY) {
87
83
  return process.env.NUELINK_API_KEY;
88
84
  }
89
85
 
86
+ if (runtimeApiKey) {
87
+ process.env.NUELINK_API_KEY = runtimeApiKey;
88
+ return runtimeApiKey;
89
+ }
90
+
90
91
  const config = await readConfig();
91
92
  const storedApiKey = decryptApiKey(config);
92
93
 
@@ -94,6 +95,10 @@ async function resolveApiKey(runtimeApiKey) {
94
95
  await saveApiKey(storedApiKey);
95
96
  }
96
97
 
98
+ if (storedApiKey) {
99
+ process.env.NUELINK_API_KEY = storedApiKey;
100
+ }
101
+
97
102
  return storedApiKey;
98
103
  }
99
104
 
package/src/http.js CHANGED
@@ -1,7 +1,15 @@
1
+ import { createRequire } from "node:module";
1
2
  import chalk from "chalk";
3
+ import { printApiResponse } from "./output.js";
2
4
 
3
- const API_BASE_URL = "https://nuelink.com/api/public/v1";
5
+ const require = createRequire(import.meta.url);
6
+ const { version: cliVersion } = require("../package.json");
7
+
8
+ const API_BASE_URL = process.env.NUELINK_BASE_URL || "https://nuelink.com/api/public/v1";
4
9
  const REQUEST_TIMEOUT_MS = Number(process.env.NUELINK_TIMEOUT_MS || 30000);
10
+ const MAX_GET_RETRIES = Number(process.env.NUELINK_GET_RETRIES || 2);
11
+ const RETRY_BASE_DELAY_MS = Number(process.env.NUELINK_RETRY_BASE_MS || 500);
12
+ const RETRY_MAX_DELAY_MS = Number(process.env.NUELINK_RETRY_MAX_MS || 2000);
5
13
 
6
14
  function pathParam(value, label) {
7
15
  const stringValue = String(value ?? "").trim();
@@ -21,14 +29,54 @@ function collectionPath(brandId, collectionId) {
21
29
  return `${brandPath(brandId)}/collections/${pathParam(collectionId, "collection-id")}`;
22
30
  }
23
31
 
24
- async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart }) {
25
- if (!apiKey) {
26
- console.error(chalk.red("Missing API key. Use --auth <api_key> to set it."));
27
- process.exitCode = 1;
28
- return null;
32
+ function buildApiUrl(endpoint) {
33
+ return new URL(endpoint.replace(/^\//, ""), `${API_BASE_URL.replace(/\/?$/, "/")}`);
34
+ }
35
+
36
+ function shouldRetryRequest(method, statusCode, attempt) {
37
+ return method === "GET" && attempt < MAX_GET_RETRIES && (statusCode === 429 || statusCode >= 500);
38
+ }
39
+
40
+ function parseRetryAfterMs(headers, attempt) {
41
+ const retryAfter = headers.get("retry-after");
42
+
43
+ if (retryAfter) {
44
+ const seconds = Number(retryAfter);
45
+
46
+ if (!Number.isNaN(seconds)) {
47
+ return Math.min(Math.max(seconds * 1000, 0), RETRY_MAX_DELAY_MS);
48
+ }
49
+
50
+ const dateDelay = Date.parse(retryAfter) - Date.now();
51
+ if (!Number.isNaN(dateDelay)) {
52
+ return Math.min(Math.max(dateDelay, 0), RETRY_MAX_DELAY_MS);
53
+ }
29
54
  }
30
55
 
31
- const url = new URL(`${API_BASE_URL}${endpoint}`);
56
+ return Math.min(RETRY_BASE_DELAY_MS * (attempt + 1), RETRY_MAX_DELAY_MS);
57
+ }
58
+
59
+ async function sleep(ms) {
60
+ if (ms <= 0) {
61
+ return;
62
+ }
63
+
64
+ await new Promise((resolve) => setTimeout(resolve, ms));
65
+ }
66
+
67
+ function printDryRun({ method, url, query, body, multipart, dryRunBody }) {
68
+ console.log(JSON.stringify({
69
+ dryRun: true,
70
+ method,
71
+ url: url.toString(),
72
+ ...(query ? { query } : {}),
73
+ ...(body !== undefined ? { body } : {}),
74
+ ...(multipart ? { multipart: dryRunBody || true } : {}),
75
+ }, null, 2));
76
+ }
77
+
78
+ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart, outputMode = "json", quiet = false, dryRun = false, dryRunBody }) {
79
+ const url = buildApiUrl(endpoint);
32
80
 
33
81
  if (query) {
34
82
  Object.entries(query).forEach(([key, value]) => {
@@ -38,10 +86,21 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
38
86
  });
39
87
  }
40
88
 
89
+ if (dryRun) {
90
+ printDryRun({ method, url, query, body, multipart, dryRunBody });
91
+ return { dryRun: true };
92
+ }
93
+
94
+ if (!apiKey) {
95
+ console.error(chalk.red("Missing API key. Use --api-key <api_key> for a single command or auth:login to save one."));
96
+ process.exitCode = 1;
97
+ return null;
98
+ }
99
+
41
100
  const headers = {
42
101
  Authorization: `Bearer ${apiKey}`,
43
102
  Accept: "application/json",
44
- "User-Agent": "nuelink-cli/1.0.0",
103
+ "User-Agent": `nuelink-cli/${cliVersion}`,
45
104
  };
46
105
 
47
106
  const init = {
@@ -57,10 +116,21 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
57
116
  }
58
117
 
59
118
  try {
60
- const response = await fetch(url, {
61
- ...init,
62
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
63
- });
119
+ let response;
120
+
121
+ for (let attempt = 0; ; attempt += 1) {
122
+ response = await fetch(url, {
123
+ ...init,
124
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
125
+ });
126
+
127
+ if (!shouldRetryRequest(method, response.status, attempt)) {
128
+ break;
129
+ }
130
+
131
+ await sleep(parseRetryAfterMs(response.headers, attempt));
132
+ }
133
+
64
134
  const text = await response.text();
65
135
  let data = {};
66
136
 
@@ -79,8 +149,11 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
79
149
  return null;
80
150
  }
81
151
 
82
- console.log(chalk.green(`OK ${method} ${url.pathname}`));
83
- console.log(JSON.stringify(data, null, 2));
152
+ if (outputMode !== "json" && !quiet) {
153
+ console.log(chalk.green(`OK ${method} ${url.pathname}`));
154
+ }
155
+
156
+ printApiResponse(data, { outputMode });
84
157
  return data;
85
158
  } catch (error) {
86
159
  if (error?.name === "TimeoutError") {