activitysmith-cli 0.1.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 +85 -0
  2. package/package.json +46 -0
  3. package/src/cli.js +458 -0
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # ActivitySmith CLI
2
+
3
+ CLI wrapper for the ActivitySmith API using the official Node SDK.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g activitysmith-cli
9
+ ```
10
+
11
+ ## Auth
12
+
13
+ Set `ACTIVITYSMITH_API_KEY` or pass `--api-key`.
14
+
15
+ ## Usage
16
+
17
+ ```bash
18
+ activitysmith --help
19
+ ```
20
+
21
+ ### Send Push
22
+
23
+ ```bash
24
+ activitysmith push \
25
+ --title "Build Failed" \
26
+ --message "CI pipeline failed on main branch"
27
+ ```
28
+
29
+ ### Start Live Activity
30
+
31
+ ```bash
32
+ activitysmith activity start \
33
+ --content-state '{"title":"Deploy","subtitle":"start","numberOfSteps":4,"currentStep":1,"type":"segmented_progress","color":"yellow"}'
34
+ ```
35
+
36
+ ### Update Live Activity
37
+
38
+ ```bash
39
+ activitysmith activity update \
40
+ --activity-id "<activityId>" \
41
+ --content-state '{"title":"Deploy","subtitle":"step 2","currentStep":2}'
42
+ ```
43
+
44
+ ### End Live Activity
45
+
46
+ ```bash
47
+ activitysmith activity end \
48
+ --activity-id "<activityId>" \
49
+ --content-state '{"title":"Deploy","subtitle":"done","currentStep":4,"autoDismissMinutes":3}'
50
+ ```
51
+
52
+ ### JSON Output
53
+
54
+ ```bash
55
+ activitysmith push --title "Hello" --json
56
+ ```
57
+
58
+ ## Aliases
59
+
60
+ The CLI installs two bin names:
61
+
62
+ - `activitysmith` (recommended)
63
+ - `activitysmith-cli` (alias)
64
+
65
+ ## Content State Options
66
+
67
+ For `activity start|update|end`, you can pass content state via JSON:
68
+
69
+ - `--content-state <json>`
70
+ - `--content-state-file <path>`
71
+
72
+ Or use flags to build the payload:
73
+
74
+ - `--title <title>`
75
+ - `--subtitle <subtitle>`
76
+ - `--type <type>`
77
+ - `--number-of-steps <number>`
78
+ - `--current-step <number>`
79
+ - `--color <color>`
80
+ - `--step-color <color>`
81
+ - `--auto-dismiss-minutes <number>`
82
+
83
+ ## Output
84
+
85
+ Use `--json` for machine-readable output.
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "activitysmith-cli",
3
+ "version": "0.1.0",
4
+ "description": "Command-line interface for ActivitySmith. Send push notifications, start, update and end live activities directly from your terminal.",
5
+ "keywords": [
6
+ "activitysmith",
7
+ "live-activities",
8
+ "push-notifications",
9
+ "api",
10
+ "cli",
11
+ "deployment",
12
+ "publishing",
13
+ "monitoring",
14
+ "observability",
15
+ "logging",
16
+ "logs",
17
+ "automation",
18
+ "tracking",
19
+ "reporting"
20
+ ],
21
+ "author": "ActivitySmith",
22
+ "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/ActivitySmithHQ/activitysmith-cli.git"
26
+ },
27
+ "homepage": "https://activitysmith.com/docs/sdks/cli",
28
+ "type": "module",
29
+ "bin": {
30
+ "activitysmith": "src/cli.js",
31
+ "activitysmith-cli": "src/cli.js"
32
+ },
33
+ "files": [
34
+ "src"
35
+ ],
36
+ "engines": {
37
+ "node": ">=18"
38
+ },
39
+ "scripts": {
40
+ "lint": "node --check src/cli.js"
41
+ },
42
+ "dependencies": {
43
+ "activitysmith": "0.1.1",
44
+ "commander": "^12.1.0"
45
+ }
46
+ }
package/src/cli.js ADDED
@@ -0,0 +1,458 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command, InvalidArgumentError } from "commander";
4
+ import ActivitySmith from "activitysmith";
5
+ import { readFile } from "fs/promises";
6
+ import { resolve } from "path";
7
+
8
+ const program = new Command();
9
+
10
+ program
11
+ .name("activitysmith-cli")
12
+ .description("CLI for ActivitySmith API")
13
+ .version("0.1.0")
14
+ .option(
15
+ "--api-key <key>",
16
+ "ActivitySmith API key (defaults to ACTIVITYSMITH_API_KEY)"
17
+ )
18
+ .option("--json", "Output JSON");
19
+
20
+ const parseIntegerOption = (label) => (value) => {
21
+ const parsed = Number(value);
22
+ if (!Number.isInteger(parsed)) {
23
+ throw new InvalidArgumentError(`${label} must be an integer`);
24
+ }
25
+ return parsed;
26
+ };
27
+
28
+ const addContentStateOptions = (command, { includeAutoDismiss } = {}) => {
29
+ command
30
+ .option("--content-state <json>", "Content state as JSON string")
31
+ .option("--content-state-file <path>", "Content state JSON file path")
32
+ .option("--title <title>", "Content state title")
33
+ .option("--subtitle <subtitle>", "Content state subtitle")
34
+ .option("--type <type>", "Content state type")
35
+ .option(
36
+ "--number-of-steps <number>",
37
+ "Content state number of steps",
38
+ parseIntegerOption("number-of-steps")
39
+ )
40
+ .option(
41
+ "--current-step <number>",
42
+ "Content state current step",
43
+ parseIntegerOption("current-step")
44
+ )
45
+ .option("--color <color>", "Content state color")
46
+ .option("--step-color <color>", "Content state step color");
47
+
48
+ if (includeAutoDismiss) {
49
+ command.option(
50
+ "--auto-dismiss-minutes <number>",
51
+ "Auto dismiss minutes for ended activity",
52
+ parseIntegerOption("auto-dismiss-minutes")
53
+ );
54
+ }
55
+
56
+ return command;
57
+ };
58
+
59
+ const getApiKey = (options) =>
60
+ options.apiKey || process.env.ACTIVITYSMITH_API_KEY;
61
+
62
+ const createClient = (apiKey) => new ActivitySmith({ apiKey });
63
+
64
+ const assertPlainObject = (value, label) => {
65
+ const isPlainObject =
66
+ value !== null &&
67
+ typeof value === "object" &&
68
+ !Array.isArray(value) &&
69
+ Object.prototype.toString.call(value) === "[object Object]";
70
+
71
+ if (!isPlainObject) {
72
+ throw new Error(`${label} must be a JSON object`);
73
+ }
74
+ };
75
+
76
+ const parseJsonString = (value, label) => {
77
+ try {
78
+ const parsed = JSON.parse(value);
79
+ assertPlainObject(parsed, label);
80
+ return parsed;
81
+ } catch (error) {
82
+ if (error instanceof SyntaxError) {
83
+ throw new Error(`${label} must be valid JSON`);
84
+ }
85
+ throw error;
86
+ }
87
+ };
88
+
89
+ const readJsonFile = async (filePath, label) => {
90
+ const resolvedPath = resolve(process.cwd(), filePath);
91
+ let text = "";
92
+
93
+ try {
94
+ text = await readFile(resolvedPath, "utf8");
95
+ } catch (error) {
96
+ throw new Error(`${label} could not be read at ${resolvedPath}`);
97
+ }
98
+
99
+ try {
100
+ const parsed = JSON.parse(text);
101
+ assertPlainObject(parsed, label);
102
+ return parsed;
103
+ } catch (error) {
104
+ if (error instanceof SyntaxError) {
105
+ throw new Error(`${label} must contain valid JSON`);
106
+ }
107
+ throw error;
108
+ }
109
+ };
110
+
111
+ const buildContentStateFromOptions = (options) => {
112
+ const contentState = {};
113
+
114
+ if (options.title !== undefined) {
115
+ contentState.title = options.title;
116
+ }
117
+
118
+ if (options.subtitle !== undefined) {
119
+ contentState.subtitle = options.subtitle;
120
+ }
121
+
122
+ if (options.type !== undefined) {
123
+ contentState.type = options.type;
124
+ }
125
+
126
+ if (options.numberOfSteps !== undefined) {
127
+ contentState.numberOfSteps = options.numberOfSteps;
128
+ }
129
+
130
+ if (options.currentStep !== undefined) {
131
+ contentState.currentStep = options.currentStep;
132
+ }
133
+
134
+ if (options.color !== undefined) {
135
+ contentState.color = options.color;
136
+ }
137
+
138
+ if (options.stepColor !== undefined) {
139
+ contentState.stepColor = options.stepColor;
140
+ }
141
+
142
+ if (options.autoDismissMinutes !== undefined) {
143
+ contentState.autoDismissMinutes = options.autoDismissMinutes;
144
+ }
145
+
146
+ return contentState;
147
+ };
148
+
149
+ const toApiContentState = (contentState) => {
150
+ const keyMap = {
151
+ numberOfSteps: "number_of_steps",
152
+ currentStep: "current_step",
153
+ stepColor: "step_color",
154
+ autoDismissMinutes: "auto_dismiss_minutes",
155
+ };
156
+
157
+ const mapped = {};
158
+ for (const [key, value] of Object.entries(contentState)) {
159
+ if (value === undefined) {
160
+ continue;
161
+ }
162
+ if (keyMap[key]) {
163
+ mapped[keyMap[key]] = value;
164
+ } else {
165
+ mapped[key] = value;
166
+ }
167
+ }
168
+ return mapped;
169
+ };
170
+
171
+ const toApiLiveActivityStartRequest = (contentState) => ({
172
+ content_state: toApiContentState(contentState),
173
+ });
174
+
175
+ const toApiLiveActivityUpdateRequest = (activityId, contentState) => ({
176
+ activity_id: activityId,
177
+ content_state: toApiContentState(contentState),
178
+ });
179
+
180
+ const toApiLiveActivityEndRequest = (activityId, contentState) => ({
181
+ activity_id: activityId,
182
+ content_state: toApiContentState(contentState),
183
+ });
184
+
185
+ const loadContentState = async (options) => {
186
+ let contentState = {};
187
+
188
+ if (options.contentStateFile) {
189
+ const fromFile = await readJsonFile(
190
+ options.contentStateFile,
191
+ "content-state-file"
192
+ );
193
+ contentState = { ...contentState, ...fromFile };
194
+ }
195
+
196
+ if (options.contentState) {
197
+ const fromString = parseJsonString(
198
+ options.contentState,
199
+ "content-state"
200
+ );
201
+ contentState = { ...contentState, ...fromString };
202
+ }
203
+
204
+ const fromFlags = buildContentStateFromOptions(options);
205
+ contentState = { ...contentState, ...fromFlags };
206
+
207
+ if (Object.keys(contentState).length === 0) {
208
+ throw new Error(
209
+ "contentState is required. Provide --content-state, --content-state-file, or field flags."
210
+ );
211
+ }
212
+
213
+ return contentState;
214
+ };
215
+
216
+ const formatError = (error) => {
217
+ if (!error) {
218
+ return "Unknown error";
219
+ }
220
+
221
+ if (typeof error === "string") {
222
+ return error;
223
+ }
224
+
225
+ if (error instanceof Error) {
226
+ return error.message || "Unknown error";
227
+ }
228
+
229
+ return "Unknown error";
230
+ };
231
+
232
+ const tryParseJson = (value) => {
233
+ try {
234
+ return JSON.parse(value);
235
+ } catch {
236
+ return null;
237
+ }
238
+ };
239
+
240
+ const readErrorResponse = async (response) => {
241
+ if (!response || typeof response.text !== "function") {
242
+ return null;
243
+ }
244
+
245
+ try {
246
+ const target = typeof response.clone === "function" ? response.clone() : response;
247
+ const text = await target.text();
248
+ return text || null;
249
+ } catch {
250
+ return null;
251
+ }
252
+ };
253
+
254
+ const buildErrorDetails = async (error) => {
255
+ const details = {
256
+ message: formatError(error),
257
+ };
258
+
259
+ if (error?.response) {
260
+ details.status = error.response.status;
261
+ details.statusText = error.response.statusText;
262
+ details.url = error.response.url;
263
+
264
+ const responseText = await readErrorResponse(error.response);
265
+ if (responseText) {
266
+ details.responseBody = tryParseJson(responseText) ?? responseText;
267
+ }
268
+ }
269
+
270
+ if (error?.cause instanceof Error) {
271
+ details.cause = error.cause.message || String(error.cause);
272
+ }
273
+
274
+ return details;
275
+ };
276
+
277
+ const handleError = async (error, options) => {
278
+ const details = await buildErrorDetails(error);
279
+
280
+ if (options?.json) {
281
+ console.log(JSON.stringify({ error: details }, null, 2));
282
+ } else {
283
+ console.error(details.message);
284
+ if (details.status) {
285
+ console.error(`Status: ${details.status} ${details.statusText || ""}`.trim());
286
+ }
287
+ if (details.url) {
288
+ console.error(`URL: ${details.url}`);
289
+ }
290
+ if (details.responseBody) {
291
+ const responseText =
292
+ typeof details.responseBody === "string"
293
+ ? details.responseBody
294
+ : JSON.stringify(details.responseBody, null, 2);
295
+ const maxLength = 2000;
296
+ const trimmed =
297
+ responseText.length > maxLength
298
+ ? `${responseText.slice(0, maxLength)}... (truncated)`
299
+ : responseText;
300
+ console.error(`Response: ${trimmed}`);
301
+ }
302
+ if (details.cause) {
303
+ console.error(`Cause: ${details.cause}`);
304
+ }
305
+ }
306
+
307
+ process.exit(1);
308
+ };
309
+
310
+ const requireApiKey = (options) => {
311
+ const apiKey = getApiKey(options);
312
+ if (!apiKey) {
313
+ throw new Error(
314
+ "Missing API key. Provide --api-key or set ACTIVITYSMITH_API_KEY."
315
+ );
316
+ }
317
+ return apiKey;
318
+ };
319
+
320
+ const outputResult = (payload, options, lines) => {
321
+ if (options.json) {
322
+ console.log(JSON.stringify(payload, null, 2));
323
+ return;
324
+ }
325
+
326
+ lines.filter(Boolean).forEach((line) => console.log(line));
327
+ };
328
+
329
+ program
330
+ .command("push")
331
+ .description("Send a push notification")
332
+ .requiredOption("--title <title>", "Push title")
333
+ .option("--message <message>", "Push message")
334
+ .option("--subtitle <subtitle>", "Push subtitle")
335
+ .action(async (options) => {
336
+ const globalOptions = program.opts();
337
+
338
+ try {
339
+ const apiKey = requireApiKey(globalOptions);
340
+ const client = createClient(apiKey);
341
+
342
+ const response = await client.notifications.sendPushNotification({
343
+ pushNotificationRequest: {
344
+ title: options.title,
345
+ message: options.message,
346
+ subtitle: options.subtitle,
347
+ },
348
+ });
349
+
350
+ outputResult(response, globalOptions, [
351
+ "Push sent.",
352
+ response?.success !== undefined
353
+ ? `Success: ${response.success}`
354
+ : null,
355
+ response?.devicesNotified !== undefined
356
+ ? `Devices notified: ${response.devicesNotified}`
357
+ : null,
358
+ response?.timestamp ? `Timestamp: ${response.timestamp}` : null,
359
+ ]);
360
+ } catch (error) {
361
+ await handleError(error, globalOptions);
362
+ }
363
+ });
364
+
365
+ const activityCommand = program
366
+ .command("activity")
367
+ .description("Manage Live Activities");
368
+
369
+ addContentStateOptions(
370
+ activityCommand
371
+ .command("start")
372
+ .description("Start a Live Activity")
373
+ .action(async (options) => {
374
+ const globalOptions = program.opts();
375
+
376
+ try {
377
+ const apiKey = requireApiKey(globalOptions);
378
+ const client = createClient(apiKey);
379
+ const contentState = await loadContentState(options);
380
+
381
+ const response = await client.liveActivities.startLiveActivity({
382
+ liveActivityStartRequest: toApiLiveActivityStartRequest(contentState),
383
+ });
384
+
385
+ const activityId = response?.activityId ?? response?.activity_id;
386
+ outputResult(response, globalOptions, [
387
+ "Live Activity started.",
388
+ activityId ? `Activity ID: ${activityId}` : null,
389
+ ]);
390
+ } catch (error) {
391
+ await handleError(error, globalOptions);
392
+ }
393
+ })
394
+ );
395
+
396
+ addContentStateOptions(
397
+ activityCommand
398
+ .command("update")
399
+ .description("Update a Live Activity")
400
+ .requiredOption("--activity-id <id>", "Live Activity ID")
401
+ .action(async (options) => {
402
+ const globalOptions = program.opts();
403
+
404
+ try {
405
+ const apiKey = requireApiKey(globalOptions);
406
+ const client = createClient(apiKey);
407
+ const contentState = await loadContentState(options);
408
+
409
+ const response = await client.liveActivities.updateLiveActivity({
410
+ liveActivityUpdateRequest: toApiLiveActivityUpdateRequest(
411
+ options.activityId,
412
+ contentState
413
+ ),
414
+ });
415
+
416
+ outputResult(response, globalOptions, [
417
+ "Live Activity updated.",
418
+ options.activityId ? `Activity ID: ${options.activityId}` : null,
419
+ ]);
420
+ } catch (error) {
421
+ await handleError(error, globalOptions);
422
+ }
423
+ })
424
+ );
425
+
426
+ addContentStateOptions(
427
+ activityCommand
428
+ .command("end")
429
+ .description("End a Live Activity")
430
+ .requiredOption("--activity-id <id>", "Live Activity ID")
431
+ .action(async (options) => {
432
+ const globalOptions = program.opts();
433
+
434
+ try {
435
+ const apiKey = requireApiKey(globalOptions);
436
+ const client = createClient(apiKey);
437
+ const contentState = await loadContentState(options);
438
+
439
+ const response = await client.liveActivities.endLiveActivity({
440
+ liveActivityEndRequest: toApiLiveActivityEndRequest(
441
+ options.activityId,
442
+ contentState
443
+ ),
444
+ });
445
+
446
+ outputResult(response, globalOptions, [
447
+ "Live Activity ended.",
448
+ options.activityId ? `Activity ID: ${options.activityId}` : null,
449
+ ]);
450
+ } catch (error) {
451
+ await handleError(error, globalOptions);
452
+ }
453
+ }),
454
+ { includeAutoDismiss: true }
455
+ );
456
+
457
+ program.showHelpAfterError(true);
458
+ program.parseAsync(process.argv);