@nuelink/nuelink-cli 1.0.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.
Files changed (3) hide show
  1. package/README.md +328 -0
  2. package/package.json +33 -0
  3. package/src/main.js +617 -0
package/README.md ADDED
@@ -0,0 +1,328 @@
1
+ # Nuelink CLI
2
+
3
+ Official command-line interface for the Nuelink Public API.
4
+
5
+ Published by the Nuelink organization as the scoped npm package `@nuelink/nuelink-cli`.
6
+
7
+ Use this CLI to manage brands, collections, automations, channels, media, and posts from local scripts, CI/CD pipelines, and terminal workflows.
8
+
9
+ ## Features
10
+
11
+ - Global auth with local token persistence
12
+ - Bearer auth support via flag, env var, or saved config
13
+ - JSON output for easy piping into automation
14
+ - Built-in timeout support for safer production usage
15
+ - Command coverage for key Nuelink Public API resources
16
+
17
+ ## Requirements
18
+
19
+ - Node.js 18.17 or higher
20
+
21
+ ## Installation
22
+
23
+ ### Global install from npm
24
+
25
+ ```bash
26
+ npm install -g @nuelink/nuelink-cli
27
+ ```
28
+
29
+ ### Run without global install
30
+
31
+ ```bash
32
+ npx @nuelink/nuelink-cli --help
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ### 1. Save your API key
38
+
39
+ ```bash
40
+ nuelink-cli --auth YOUR_API_KEY
41
+ ```
42
+
43
+ ### 2. Verify auth source
44
+
45
+ ```bash
46
+ nuelink-cli auth:status
47
+ ```
48
+
49
+ ### 3. Make your first request
50
+
51
+ ```bash
52
+ nuelink-cli me
53
+ ```
54
+
55
+ ## Authentication Resolution Order
56
+
57
+ The CLI resolves auth in this order:
58
+
59
+ 1. CLI flag: `--auth <api_key>`
60
+ 2. Environment variable: `NUELINK_API_KEY`
61
+ 3. Saved config file in your user home
62
+
63
+ If a key is passed with `--auth`, it is persisted for future commands.
64
+
65
+ ### Clear saved auth
66
+
67
+ ```bash
68
+ nuelink-cli auth:clear
69
+ ```
70
+
71
+ ## Config Storage
72
+
73
+ The token is stored in:
74
+
75
+ - Windows: `%USERPROFILE%/.nuelink-cli/config.json`
76
+ - macOS/Linux: `$HOME/.nuelink-cli/config.json`
77
+
78
+ The file stores:
79
+
80
+ ```json
81
+ {
82
+ "apiKey": "..."
83
+ }
84
+ ```
85
+
86
+ ## Global Options
87
+
88
+ - `-a, --auth <apiKey>`: Set and use API key
89
+ - `-h, --help`: Show help
90
+ - `-V, --version`: Show version
91
+
92
+ ## Commands
93
+
94
+ ### Profile
95
+
96
+ ```bash
97
+ nuelink-cli me
98
+ ```
99
+
100
+ ### Auth
101
+
102
+ ```bash
103
+ nuelink-cli auth:status
104
+ nuelink-cli auth:clear
105
+ ```
106
+
107
+ ### Brands
108
+
109
+ ```bash
110
+ nuelink-cli brands --per-page 5 --page 1
111
+ ```
112
+
113
+ ### Collections
114
+
115
+ ```bash
116
+ nuelink-cli collections --brand-id 13493 --per-page 5 --page 1
117
+ ```
118
+
119
+ Create collection:
120
+
121
+ ```bash
122
+ nuelink-cli collections:create \
123
+ --brand-id 13493 \
124
+ --title "API Brand" \
125
+ --description "Collection from CLI" \
126
+ --max-republish 5 \
127
+ --channels "300294,60112" \
128
+ --queues "Mon 10:10,Mon 12:12"
129
+ ```
130
+
131
+ ### Automations
132
+
133
+ ```bash
134
+ nuelink-cli automations --brand-id 13493
135
+ ```
136
+
137
+ Create automation:
138
+
139
+ ```bash
140
+ nuelink-cli automations:create \
141
+ --brand-id 13493 \
142
+ --collection-id 720 \
143
+ --feed-url "https://www.nasa.gov/rss/dyn/breaking_news.rss" \
144
+ --import-as-type IMAGE \
145
+ --sub-type RSS \
146
+ --title "NASA Breaking News" \
147
+ --type FEED \
148
+ --dynamic-title "{{title}}" \
149
+ --dynamic-body "{title} {link}"
150
+ ```
151
+
152
+ ### Channels
153
+
154
+ ```bash
155
+ nuelink-cli channels --brand-id 13493 --per-page 5 --page 1
156
+ ```
157
+
158
+ ### Media
159
+
160
+ List media:
161
+
162
+ ```bash
163
+ nuelink-cli media --brand-id 13493
164
+ ```
165
+
166
+ Upload media:
167
+
168
+ ```bash
169
+ nuelink-cli media:upload --brand-id 13493 --file ./assets/image.jpg
170
+ ```
171
+
172
+ ### Posts
173
+
174
+ List posts:
175
+
176
+ ```bash
177
+ nuelink-cli posts --brand-id 13493 --collection-id 33273
178
+ ```
179
+
180
+ Create post from JSON payload file:
181
+
182
+ ```bash
183
+ nuelink-cli posts:add-json --brand-id 13493 --collection-id 33273 --payload ./post.json
184
+ ```
185
+
186
+ Example `post.json`:
187
+
188
+ ```json
189
+ {
190
+ "title": "CLI Post Title",
191
+ "caption": "Post body from CLI",
192
+ "publishMode": "DRAFT"
193
+ }
194
+ ```
195
+
196
+ Create post with CLI options:
197
+
198
+ ```bash
199
+ nuelink-cli posts:create \
200
+ --brand-id 13493 \
201
+ --collection-id 33273 \
202
+ --title "title here" \
203
+ --caption "body here as well" \
204
+ --alt "is this fine" \
205
+ --link "https://nuelink.com" \
206
+ --publish-mode DRAFT \
207
+ --post-as-story true \
208
+ --comment "this is a comment" \
209
+ --comment-delay 30 \
210
+ --media-ids "media-id-1" \
211
+ --media-urls "https://media.nuelink.com/media/abc" \
212
+ --poll-question "what is the new role?" \
213
+ --poll-options "iron,dudee" \
214
+ --poll-period 3d \
215
+ --poll-correct-option-index 1 \
216
+ --poll-explanation "iwa ash idir lwaaa7ad" \
217
+ --instagram-collab "karim.chamlal" \
218
+ --instagram-location-id "abc123" \
219
+ --instagram-location-name "bentaib" \
220
+ --instagram-trial-reel MANUAL \
221
+ --instagram-share-to-feed true \
222
+ --facebook-collab "karim.chamlal" \
223
+ --facebook-location-id "abc123" \
224
+ --facebook-location-name "bentaib" \
225
+ --tiktok-send-to-inbox true \
226
+ --youtube-tags "tag1,tag2,tag3" \
227
+ --youtube-playlists '[{"channelId":"1","playlistIds":["1","2"]}]'
228
+ ```
229
+
230
+ ## Output and Exit Codes
231
+
232
+ - Successful requests print `OK <METHOD> <PATH>` plus JSON response body
233
+ - Failed requests print HTTP status and response payload when available
234
+ - Exit code is non-zero on failure
235
+
236
+ ## Environment Variables
237
+
238
+ - `NUELINK_API_KEY`: API key fallback if not passed via CLI flag
239
+ - `NUELINK_TIMEOUT_MS`: request timeout in milliseconds (default: `30000`)
240
+
241
+ Example:
242
+
243
+ ```bash
244
+ NUELINK_TIMEOUT_MS=60000 nuelink-cli brands
245
+ ```
246
+
247
+ ## Production Usage Patterns
248
+
249
+ ### Shell script usage
250
+
251
+ ```bash
252
+ #!/usr/bin/env bash
253
+ set -euo pipefail
254
+
255
+ export NUELINK_API_KEY="${NUELINK_API_KEY:?NUELINK_API_KEY is required}"
256
+
257
+ nuelink-cli brands --per-page 10 --page 1
258
+ nuelink-cli collections --brand-id 13493 --per-page 10 --page 1
259
+ ```
260
+
261
+ ### CI usage
262
+
263
+ Store `NUELINK_API_KEY` as a repository or org secret and run commands in non-interactive jobs.
264
+
265
+ ## Development
266
+
267
+ ### Install dependencies
268
+
269
+ ```bash
270
+ npm ci
271
+ ```
272
+
273
+ ### Run tests
274
+
275
+ ```bash
276
+ npm test
277
+ ```
278
+
279
+ ### Package validation
280
+
281
+ ```bash
282
+ npm run check:pack
283
+ ```
284
+
285
+ ## Release Checklist
286
+
287
+ 1. Update version in `package.json`
288
+ 2. Run `npm test`
289
+ 3. Run `npm run check:pack`
290
+ 4. Publish with `npm publish --access public`
291
+
292
+ ## Troubleshooting
293
+
294
+ ### Invalid Token
295
+
296
+ - Run `nuelink-cli auth:status` to confirm active auth source
297
+ - Re-save your token with `nuelink-cli --auth YOUR_API_KEY`
298
+ - Ensure no stale `NUELINK_API_KEY` is overriding your saved config
299
+
300
+ ### Request timeout
301
+
302
+ Increase timeout for slower operations:
303
+
304
+ ```bash
305
+ NUELINK_TIMEOUT_MS=120000 nuelink-cli media --brand-id 13493
306
+ ```
307
+
308
+ ### Command help
309
+
310
+ ```bash
311
+ nuelink-cli --help
312
+ nuelink-cli help collections
313
+ ```
314
+
315
+ ## Security Notes
316
+
317
+ - Treat API keys as secrets
318
+ - Do not commit tokens to source control
319
+ - Prefer environment-based secrets in CI/CD
320
+
321
+ ## License
322
+
323
+ MIT
324
+
325
+ ## Additional Docs
326
+
327
+ - Contribution guide: [CONTRIBUTING.md](CONTRIBUTING.md)
328
+ - Security policy: [SECURITY.md](SECURITY.md)
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@nuelink/nuelink-cli",
3
+ "version": "1.0.0",
4
+ "description": "The official Nuelink CLI for automating social media workflows from your terminal. Schedule posts, upload media, manage brands, and integrate Nuelink into scripts, CI/CD pipelines, and AI agents.",
5
+ "license": "MIT",
6
+ "author": "Nuelink",
7
+ "type": "module",
8
+ "main": "./src/main.js",
9
+ "scripts": {
10
+ "test": "node --test test/cli.test.mjs",
11
+ "smoke:auth": "node src/main.js auth:status",
12
+ "check:pack": "npm pack --dry-run"
13
+ },
14
+ "engines": {
15
+ "node": ">=18.17"
16
+ },
17
+ "files": [
18
+ "src"
19
+ ],
20
+ "keywords": [
21
+ "nuelink",
22
+ "cli",
23
+ "social-media",
24
+ "automation"
25
+ ],
26
+ "dependencies": {
27
+ "chalk": "^5.6.2",
28
+ "commander": "^15.0.0"
29
+ },
30
+ "bin": {
31
+ "nuelink-cli": "./src/main.js"
32
+ }
33
+ }
package/src/main.js ADDED
@@ -0,0 +1,617 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from "commander";
4
+ import chalk from "chalk";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { readFile, writeFile, mkdir, chmod, stat } from "node:fs/promises";
8
+
9
+ const API_BASE_URL = "https://nuelink.com/api/public/v1";
10
+ const CONFIG_DIR = path.join(os.homedir(), ".nuelink-cli");
11
+ const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
12
+ const REQUEST_TIMEOUT_MS = Number(process.env.NUELINK_TIMEOUT_MS || 30000);
13
+
14
+ async function readConfig() {
15
+ try {
16
+ const content = await readFile(CONFIG_FILE, "utf8");
17
+ return JSON.parse(content);
18
+ } catch {
19
+ return {};
20
+ }
21
+ }
22
+
23
+ async function writeConfig(config) {
24
+ await mkdir(CONFIG_DIR, { recursive: true });
25
+ await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), "utf8");
26
+
27
+ // Best effort to keep token readable only by the current user on POSIX systems.
28
+ try {
29
+ await chmod(CONFIG_FILE, 0o600);
30
+ } catch {
31
+ // Ignore on platforms where chmod permissions are not meaningful.
32
+ }
33
+ }
34
+
35
+ async function saveApiKey(apiKey) {
36
+ const config = await readConfig();
37
+ config.apiKey = apiKey;
38
+ await writeConfig(config);
39
+ }
40
+
41
+ async function clearApiKey() {
42
+ const config = await readConfig();
43
+ delete config.apiKey;
44
+ await writeConfig(config);
45
+ }
46
+
47
+ function maskToken(token) {
48
+ if (!token || token.length < 8) {
49
+ return "(set)";
50
+ }
51
+
52
+ return `${token.slice(0, 4)}...${token.slice(-4)}`;
53
+ }
54
+
55
+ async function resolveApiKey(runtimeApiKey) {
56
+ if (runtimeApiKey) {
57
+ return runtimeApiKey;
58
+ }
59
+
60
+ if (process.env.NUELINK_API_KEY) {
61
+ return process.env.NUELINK_API_KEY;
62
+ }
63
+
64
+ const config = await readConfig();
65
+ return config.apiKey;
66
+ }
67
+
68
+ function extractAuthArg(args) {
69
+ const sanitizedArgs = [];
70
+ let apiKey;
71
+
72
+ for (let index = 0; index < args.length; index += 1) {
73
+ const arg = args[index];
74
+
75
+ if (arg === "--auth" || arg === "-a") {
76
+ const next = args[index + 1];
77
+ if (next && !next.startsWith("-")) {
78
+ apiKey = next;
79
+ index += 1;
80
+ continue;
81
+ }
82
+ }
83
+
84
+ if (arg.startsWith("--auth=")) {
85
+ apiKey = arg.slice("--auth=".length);
86
+ continue;
87
+ }
88
+
89
+ sanitizedArgs.push(arg);
90
+ }
91
+
92
+ return { apiKey, sanitizedArgs };
93
+ }
94
+
95
+ function parseCsv(value) {
96
+ if (!value) {
97
+ return [];
98
+ }
99
+
100
+ return value
101
+ .split(",")
102
+ .map((item) => item.trim())
103
+ .filter(Boolean);
104
+ }
105
+
106
+ function parseBoolean(value) {
107
+ if (value === undefined || value === null || value === "") {
108
+ return undefined;
109
+ }
110
+
111
+ const normalized = String(value).trim().toLowerCase();
112
+
113
+ if (["true", "1", "yes", "y"].includes(normalized)) {
114
+ return true;
115
+ }
116
+
117
+ if (["false", "0", "no", "n"].includes(normalized)) {
118
+ return false;
119
+ }
120
+
121
+ return undefined;
122
+ }
123
+
124
+ function parseNumber(value) {
125
+ if (value === undefined || value === null || value === "") {
126
+ return undefined;
127
+ }
128
+
129
+ const parsed = Number(value);
130
+ return Number.isNaN(parsed) ? undefined : parsed;
131
+ }
132
+
133
+ function mergeMedia(idsCsv, urlsCsv) {
134
+ const idMedia = parseCsv(idsCsv).map((id) => ({ id }));
135
+ const urlMedia = parseCsv(urlsCsv).map((url) => ({ url }));
136
+ return [...idMedia, ...urlMedia];
137
+ }
138
+
139
+ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart }) {
140
+ if (!apiKey) {
141
+ console.error(chalk.red("Missing API key. Use --auth <api_key> to set it."));
142
+ process.exitCode = 1;
143
+ return null;
144
+ }
145
+
146
+ const url = new URL(`${API_BASE_URL}${endpoint}`);
147
+
148
+ if (query) {
149
+ Object.entries(query).forEach(([key, value]) => {
150
+ if (value !== undefined && value !== null && value !== "") {
151
+ url.searchParams.set(key, String(value));
152
+ }
153
+ });
154
+ }
155
+
156
+ const headers = {
157
+ Authorization: `Bearer ${apiKey}`,
158
+ Accept: "application/json",
159
+ "User-Agent": "nuelink-cli/1.0.0",
160
+ };
161
+
162
+ const init = {
163
+ method,
164
+ headers,
165
+ };
166
+
167
+ if (multipart) {
168
+ init.body = multipart;
169
+ } else if (body !== undefined) {
170
+ headers["Content-Type"] = "application/json";
171
+ init.body = JSON.stringify(body);
172
+ }
173
+
174
+ try {
175
+ const response = await fetch(url, {
176
+ ...init,
177
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
178
+ });
179
+ const text = await response.text();
180
+ let data = {};
181
+
182
+ if (text) {
183
+ try {
184
+ data = JSON.parse(text);
185
+ } catch {
186
+ data = { raw: text };
187
+ }
188
+ }
189
+
190
+ if (!response.ok) {
191
+ console.error(chalk.red(`Request failed (${response.status} ${response.statusText})`));
192
+ console.error(chalk.red(JSON.stringify(data, null, 2)));
193
+ process.exitCode = 1;
194
+ return null;
195
+ }
196
+
197
+ console.log(chalk.green(`OK ${method} ${url.pathname}`));
198
+ console.log(JSON.stringify(data, null, 2));
199
+ return data;
200
+ } catch (error) {
201
+ if (error?.name === "TimeoutError") {
202
+ console.error(chalk.red(`Request timed out after ${REQUEST_TIMEOUT_MS}ms.`));
203
+ process.exitCode = 1;
204
+ return null;
205
+ }
206
+
207
+ console.error(chalk.red("Request error:"), error.message);
208
+ process.exitCode = 1;
209
+ return null;
210
+ }
211
+ }
212
+
213
+ const parsedAuth = extractAuthArg(process.argv.slice(2));
214
+ const runtimeApiKey = parsedAuth.apiKey;
215
+ const parseArgv = [process.argv[0], process.argv[1], ...parsedAuth.sanitizedArgs];
216
+
217
+ if (runtimeApiKey) {
218
+ await saveApiKey(runtimeApiKey);
219
+ }
220
+
221
+ program
222
+ .name("nuelink-cli")
223
+ .version("1.0.0")
224
+ .description("Nuelink CLI for the Public API")
225
+ .option("-a, --auth <apiKey>", "Set and use API key");
226
+
227
+ program
228
+ .command("auth:clear")
229
+ .description("Remove the saved API key")
230
+ .action(async () => {
231
+ await clearApiKey();
232
+ console.log(chalk.yellow("Saved API key removed."));
233
+ });
234
+
235
+ program
236
+ .command("auth:status")
237
+ .description("Show where auth is currently resolved from")
238
+ .action(async () => {
239
+ if (runtimeApiKey) {
240
+ console.log(chalk.green(`Auth source: CLI flag (${maskToken(runtimeApiKey)})`));
241
+ return;
242
+ }
243
+
244
+ if (process.env.NUELINK_API_KEY) {
245
+ console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
246
+ return;
247
+ }
248
+
249
+ const config = await readConfig();
250
+ if (config.apiKey) {
251
+ console.log(chalk.green(`Auth source: saved config (${maskToken(config.apiKey)})`));
252
+
253
+ try {
254
+ const fileStat = await stat(CONFIG_FILE);
255
+ console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
256
+ console.log(chalk.blue(`Last updated: ${fileStat.mtime.toISOString()}`));
257
+ } catch {
258
+ // Ignore non-critical stat failure.
259
+ }
260
+
261
+ return;
262
+ }
263
+
264
+ console.log(chalk.yellow("No API key configured. Set one with --auth <api_key>."));
265
+ });
266
+
267
+ program
268
+ .command("me")
269
+ .description("Get current profile")
270
+ .action(async () => {
271
+ const apiKey = await resolveApiKey(runtimeApiKey);
272
+ await nuelinkRequest({ apiKey, endpoint: "/me" });
273
+ });
274
+
275
+ program
276
+ .command("brands")
277
+ .description("List brands")
278
+ .option("--per-page <number>", "Items per page", "25")
279
+ .option("--page <number>", "Page number", "1")
280
+ .action(async (options) => {
281
+ const apiKey = await resolveApiKey(runtimeApiKey);
282
+ await nuelinkRequest({
283
+ apiKey,
284
+ endpoint: "/brands",
285
+ query: {
286
+ per_page: options.perPage,
287
+ page: options.page,
288
+ },
289
+ });
290
+ });
291
+
292
+ program
293
+ .command("collections")
294
+ .description("List collections for a brand")
295
+ .requiredOption("--brand-id <id>", "Brand ID")
296
+ .option("--per-page <number>", "Items per page", "25")
297
+ .option("--page <number>", "Page number", "1")
298
+ .action(async (options) => {
299
+ const apiKey = await resolveApiKey(runtimeApiKey);
300
+ await nuelinkRequest({
301
+ apiKey,
302
+ endpoint: `/brands/${options.brandId}/collections`,
303
+ query: {
304
+ per_page: options.perPage,
305
+ page: options.page,
306
+ },
307
+ });
308
+ });
309
+
310
+ program
311
+ .command("collections:create")
312
+ .description("Create a collection")
313
+ .requiredOption("--brand-id <id>", "Brand ID")
314
+ .requiredOption("--title <title>", "Collection title")
315
+ .option("--description <text>", "Collection description", "")
316
+ .option("--max-republish <number>", "Max republish")
317
+ .option("--channels <ids>", "Comma-separated channel IDs")
318
+ .option("--queues <slots>", "Comma-separated queue slots (e.g. Mon 10:10,Mon 12:12)")
319
+ .action(async (options) => {
320
+ const apiKey = await resolveApiKey(runtimeApiKey);
321
+ await nuelinkRequest({
322
+ apiKey,
323
+ method: "POST",
324
+ endpoint: `/brands/${options.brandId}/collections`,
325
+ body: {
326
+ title: options.title,
327
+ description: options.description,
328
+ maxRepublish: options.maxRepublish ? Number(options.maxRepublish) : undefined,
329
+ channels: parseCsv(options.channels).map((id) => Number(id)),
330
+ queues: parseCsv(options.queues),
331
+ },
332
+ });
333
+ });
334
+
335
+ program
336
+ .command("automations")
337
+ .description("List automations for a brand")
338
+ .requiredOption("--brand-id <id>", "Brand ID")
339
+ .action(async (options) => {
340
+ const apiKey = await resolveApiKey(runtimeApiKey);
341
+ await nuelinkRequest({
342
+ apiKey,
343
+ endpoint: `/brands/${options.brandId}/automations`,
344
+ });
345
+ });
346
+
347
+ program
348
+ .command("automations:create")
349
+ .description("Create an automation")
350
+ .requiredOption("--brand-id <id>", "Brand ID")
351
+ .requiredOption("--collection-id <id>", "Collection ID")
352
+ .requiredOption("--feed-url <url>", "Feed URL")
353
+ .requiredOption("--import-as-type <type>", "Import type, e.g. IMAGE")
354
+ .requiredOption("--sub-type <type>", "Sub type, e.g. RSS")
355
+ .requiredOption("--title <title>", "Automation title")
356
+ .option("--type <type>", "Automation type", "FEED")
357
+ .option("--dynamic-title <text>", "Dynamic title", "{{title}}")
358
+ .option("--dynamic-body <text>", "Dynamic body", "{title} {link}")
359
+ .option("--description <text>", "Automation description")
360
+ .action(async (options) => {
361
+ const apiKey = await resolveApiKey(runtimeApiKey);
362
+ await nuelinkRequest({
363
+ apiKey,
364
+ method: "POST",
365
+ endpoint: `/brands/${options.brandId}/automations`,
366
+ body: {
367
+ collectionId: Number(options.collectionId),
368
+ feedUrl: options.feedUrl,
369
+ importAsType: options.importAsType,
370
+ subType: options.subType,
371
+ title: options.title,
372
+ type: options.type,
373
+ dynamicTitle: options.dynamicTitle,
374
+ dynamicBody: options.dynamicBody,
375
+ description: options.description,
376
+ },
377
+ });
378
+ });
379
+
380
+ program
381
+ .command("channels")
382
+ .description("List channels for a brand")
383
+ .requiredOption("--brand-id <id>", "Brand ID")
384
+ .option("--per-page <number>", "Items per page", "25")
385
+ .option("--page <number>", "Page number", "1")
386
+ .action(async (options) => {
387
+ const apiKey = await resolveApiKey(runtimeApiKey);
388
+ await nuelinkRequest({
389
+ apiKey,
390
+ endpoint: `/brands/${options.brandId}/channels`,
391
+ query: {
392
+ per_page: options.perPage,
393
+ page: options.page,
394
+ },
395
+ });
396
+ });
397
+
398
+ program
399
+ .command("media")
400
+ .description("List media for a brand")
401
+ .requiredOption("--brand-id <id>", "Brand ID")
402
+ .action(async (options) => {
403
+ const apiKey = await resolveApiKey(runtimeApiKey);
404
+ await nuelinkRequest({
405
+ apiKey,
406
+ endpoint: `/brands/${options.brandId}/media`,
407
+ });
408
+ });
409
+
410
+ program
411
+ .command("media:upload")
412
+ .description("Upload a media file")
413
+ .requiredOption("--brand-id <id>", "Brand ID")
414
+ .requiredOption("--file <path>", "Path to local file")
415
+ .action(async (options) => {
416
+ const apiKey = await resolveApiKey(runtimeApiKey);
417
+
418
+ const fileBuffer = await readFile(options.file);
419
+ const formData = new FormData();
420
+ formData.append("media", new Blob([fileBuffer]), path.basename(options.file));
421
+
422
+ await nuelinkRequest({
423
+ apiKey,
424
+ method: "POST",
425
+ endpoint: `/brands/${options.brandId}/media`,
426
+ multipart: formData,
427
+ });
428
+ });
429
+
430
+ program
431
+ .command("posts")
432
+ .description("List posts in a collection")
433
+ .requiredOption("--brand-id <id>", "Brand ID")
434
+ .requiredOption("--collection-id <id>", "Collection ID")
435
+ .action(async (options) => {
436
+ const apiKey = await resolveApiKey(runtimeApiKey);
437
+ await nuelinkRequest({
438
+ apiKey,
439
+ endpoint: `/brands/${options.brandId}/collections/${options.collectionId}/posts`,
440
+ });
441
+ });
442
+
443
+ program
444
+ .command("posts:add-json")
445
+ .description("Create a post using a JSON payload file")
446
+ .requiredOption("--brand-id <id>", "Brand ID")
447
+ .requiredOption("--collection-id <id>", "Collection ID")
448
+ .requiredOption("--payload <file>", "Path to JSON payload file")
449
+ .action(async (options) => {
450
+ const apiKey = await resolveApiKey(runtimeApiKey);
451
+ const payloadText = await readFile(options.payload, "utf8");
452
+ const payload = JSON.parse(payloadText);
453
+
454
+ await nuelinkRequest({
455
+ apiKey,
456
+ method: "POST",
457
+ endpoint: `/brands/${options.brandId}/collections/${options.collectionId}/posts`,
458
+ body: payload,
459
+ });
460
+ });
461
+
462
+ program
463
+ .command("posts:create")
464
+ .description("Create a post using CLI options")
465
+ .requiredOption("--brand-id <id>", "Brand ID")
466
+ .requiredOption("--collection-id <id>", "Collection ID")
467
+ .option("--title <text>", "Post title")
468
+ .option("--caption <text>", "Post caption/body")
469
+ .option("--alt <text>", "Alt text")
470
+ .option("--link <url>", "Post link")
471
+ .option("--publish-mode <mode>", "Publish mode (e.g. DRAFT, NOW, SCHEDULE)", "DRAFT")
472
+ .option("--publish-at <value>", "Publish datetime (YYYY-MM-DD HH:mm:ss or ISO) or null")
473
+ .option("--post-as-story <boolean>", "Post as story: true/false")
474
+ .option("--post-type <type>", "Post type override")
475
+ .option("--comment <text>", "First comment")
476
+ .option("--comment-delay <seconds>", "First comment delay seconds")
477
+ .option("--media-ids <ids>", "Comma-separated media IDs")
478
+ .option("--media-urls <urls>", "Comma-separated media URLs")
479
+ .option("--poll-question <text>", "Poll question")
480
+ .option("--poll-options <items>", "Comma-separated poll options")
481
+ .option("--poll-period <value>", "Poll period (e.g. 3d)")
482
+ .option("--poll-correct-option-index <number>", "Poll correct option index")
483
+ .option("--poll-explanation <text>", "Poll explanation")
484
+ .option("--instagram-collab <username>", "Instagram collab username")
485
+ .option("--instagram-location-id <id>", "Instagram location ID")
486
+ .option("--instagram-location-name <name>", "Instagram location name")
487
+ .option("--instagram-trial-reel <mode>", "Instagram trial reel mode")
488
+ .option("--instagram-share-to-feed <boolean>", "Instagram share to feed true/false")
489
+ .option("--facebook-collab <username>", "Facebook collab username")
490
+ .option("--facebook-location-id <id>", "Facebook location ID")
491
+ .option("--facebook-location-name <name>", "Facebook location name")
492
+ .option("--tiktok-send-to-inbox <boolean>", "TikTok send to inbox true/false")
493
+ .option("--youtube-tags <tags>", "Comma-separated YouTube tags")
494
+ .option("--youtube-playlists <json>", "YouTube playlists JSON string")
495
+ .action(async (options) => {
496
+ const apiKey = await resolveApiKey(runtimeApiKey);
497
+
498
+ const media = mergeMedia(options.mediaIds, options.mediaUrls);
499
+
500
+ const poll = {
501
+ ...(options.pollQuestion ? { question: options.pollQuestion } : {}),
502
+ ...(options.pollOptions ? { options: parseCsv(options.pollOptions) } : {}),
503
+ ...(options.pollPeriod ? { period: options.pollPeriod } : {}),
504
+ ...(parseNumber(options.pollCorrectOptionIndex) !== undefined
505
+ ? { correctOptionIndex: parseNumber(options.pollCorrectOptionIndex) }
506
+ : {}),
507
+ ...(options.pollExplanation ? { explanation: options.pollExplanation } : {}),
508
+ };
509
+
510
+ const instagram = {
511
+ ...(options.instagramCollab ? { collab: options.instagramCollab } : {}),
512
+ ...(options.instagramLocationId || options.instagramLocationName
513
+ ? {
514
+ location: {
515
+ ...(options.instagramLocationId ? { id: options.instagramLocationId } : {}),
516
+ ...(options.instagramLocationName ? { name: options.instagramLocationName } : {}),
517
+ },
518
+ }
519
+ : {}),
520
+ ...(options.instagramTrialReel ? { trialReel: options.instagramTrialReel } : {}),
521
+ ...(parseBoolean(options.instagramShareToFeed) !== undefined
522
+ ? { shareToFeed: parseBoolean(options.instagramShareToFeed) }
523
+ : {}),
524
+ };
525
+
526
+ const facebook = {
527
+ ...(options.facebookCollab ? { collab: options.facebookCollab } : {}),
528
+ ...(options.facebookLocationId || options.facebookLocationName
529
+ ? {
530
+ location: {
531
+ ...(options.facebookLocationId ? { id: options.facebookLocationId } : {}),
532
+ ...(options.facebookLocationName ? { name: options.facebookLocationName } : {}),
533
+ },
534
+ }
535
+ : {}),
536
+ };
537
+
538
+
539
+ const tiktok = {
540
+ ...(parseBoolean(options.tiktokSendToInbox) !== undefined
541
+ ? { sendToInbox: parseBoolean(options.tiktokSendToInbox) }
542
+ : {}),
543
+ };
544
+
545
+ let youtubePlaylists;
546
+ if (options.youtubePlaylists) {
547
+ try {
548
+ youtubePlaylists = JSON.parse(options.youtubePlaylists);
549
+ } catch {
550
+ console.error(chalk.red("Invalid --youtube-playlists JSON."));
551
+ process.exitCode = 1;
552
+ return;
553
+ }
554
+ }
555
+
556
+ const youtube = {
557
+ ...(options.youtubeTags ? { tags: parseCsv(options.youtubeTags) } : {}),
558
+ ...(youtubePlaylists ? { playlists: youtubePlaylists } : {}),
559
+ };
560
+
561
+ const payload = {
562
+ ...(options.title ? { title: options.title } : {}),
563
+ ...(options.caption ? { caption: options.caption } : {}),
564
+ ...(options.alt ? { alt: options.alt } : {}),
565
+ ...(options.link ? { link: options.link } : {}),
566
+ ...(options.postType ? { postType: options.postType } : {}),
567
+ publishMode: options.publishMode,
568
+ ...(options.publishAt && options.publishAt !== "null" ? { publishAt: options.publishAt } : { publishAt: null }),
569
+ ...(parseBoolean(options.postAsStory) !== undefined
570
+ ? { postAsStory: parseBoolean(options.postAsStory) }
571
+ : {}),
572
+ ...(options.comment
573
+ ? {
574
+ comment: {
575
+ comment: options.comment,
576
+ ...(parseNumber(options.commentDelay) !== undefined
577
+ ? { delay: parseNumber(options.commentDelay) }
578
+ : {}),
579
+ },
580
+ }
581
+ : {}),
582
+ ...(media.length > 0 ? { media } : {}),
583
+ ...(Object.keys(poll).length > 0 ? { poll } : {}),
584
+ ...(Object.keys(instagram).length > 0 || Object.keys(facebook).length > 0 || Object.keys(tiktok).length > 0 || Object.keys(youtube).length > 0
585
+ ? {
586
+ platforms: {
587
+ ...(Object.keys(instagram).length > 0 ? { instagram } : {}),
588
+ ...(Object.keys(facebook).length > 0 ? { facebook } : {}),
589
+ ...(Object.keys(tiktok).length > 0 ? { tiktok } : {}),
590
+ ...(Object.keys(youtube).length > 0 ? { youtube } : {}),
591
+ },
592
+ }
593
+ : {}),
594
+ };
595
+
596
+ await nuelinkRequest({
597
+ apiKey,
598
+ method: "POST",
599
+ endpoint: `/brands/${options.brandId}/collections/${options.collectionId}/posts`,
600
+ body: payload,
601
+ });
602
+ });
603
+
604
+ const argvHasCommand = parsedAuth.sanitizedArgs.some((arg) => !arg.startsWith("-"));
605
+ const hasHelpFlag = parsedAuth.sanitizedArgs.includes("--help") || parsedAuth.sanitizedArgs.includes("-h");
606
+
607
+ if (!argvHasCommand && runtimeApiKey && !hasHelpFlag) {
608
+ console.log(chalk.green("API key saved and ready to use."));
609
+ process.exit(0);
610
+ }
611
+
612
+ if (!argvHasCommand && !runtimeApiKey && !hasHelpFlag) {
613
+ program.outputHelp();
614
+ process.exit(0);
615
+ }
616
+
617
+ await program.parseAsync(parseArgv);