@postshiba/cli 0.0.0-stage → 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.
package/src/prompts.js ADDED
@@ -0,0 +1,118 @@
1
+ // @ts-check
2
+
3
+ import * as clack from "@clack/prompts";
4
+ import { CancelError } from "./errors.js";
5
+
6
+ /**
7
+ * @typedef {object} Prompts
8
+ * @property {(opts: { message: string, placeholder?: string, defaultValue?: string }) => Promise<string>} text
9
+ * @property {(opts: { message: string }) => Promise<string>} password
10
+ * @property {(opts: { message: string, options: { value: string, label: string, hint?: string }[] }) => Promise<string>} select
11
+ * @property {(opts: { message: string }) => Promise<boolean>} confirm
12
+ * @property {(message: string) => void} intro
13
+ * @property {(message: string) => void} outro
14
+ * @property {(message: string, title?: string) => void} note
15
+ * @property {() => { start: (message?: string) => void, stop: (message?: string) => void, error: (message?: string) => void }} spinner
16
+ * @property {(message: string) => void} [cancel]
17
+ * @property {{ success: (message: string) => void, error: (message: string) => void, info: (message: string) => void }} [log]
18
+ */
19
+
20
+ /**
21
+ * @param {unknown} value
22
+ */
23
+ function unwrap(value) {
24
+ if (clack.isCancel(value)) throw new CancelError();
25
+ return value;
26
+ }
27
+
28
+ /**
29
+ * @template T
30
+ * @param {Prompts | null | undefined} prompts
31
+ * @param {string} label
32
+ * @param {() => Promise<T>} work
33
+ * @param {(result: T) => string} done
34
+ * @returns {Promise<T>}
35
+ */
36
+ export async function spinning(prompts, label, work, done) {
37
+ if (!prompts) return work();
38
+ const spin = prompts.spinner();
39
+ spin.start(label);
40
+ try {
41
+ const result = await work();
42
+ spin.stop(done(result));
43
+ return result;
44
+ } catch (err) {
45
+ spin.error(`${label} failed`);
46
+ throw err;
47
+ }
48
+ }
49
+
50
+ /** @returns {Prompts} */
51
+ export function createClackPrompts() {
52
+ return {
53
+ async text(opts) {
54
+ return String(
55
+ unwrap(
56
+ await clack.text({
57
+ message: opts.message,
58
+ placeholder: opts.placeholder,
59
+ defaultValue: opts.defaultValue,
60
+ }),
61
+ ),
62
+ );
63
+ },
64
+ async password(opts) {
65
+ return String(unwrap(await clack.password({ message: opts.message })));
66
+ },
67
+ async select(opts) {
68
+ return String(
69
+ unwrap(
70
+ await clack.select({
71
+ message: opts.message,
72
+ options: opts.options,
73
+ }),
74
+ ),
75
+ );
76
+ },
77
+ async confirm(opts) {
78
+ return Boolean(unwrap(await clack.confirm({ message: opts.message })));
79
+ },
80
+ intro(message) {
81
+ clack.intro(message);
82
+ },
83
+ outro(message) {
84
+ clack.outro(message);
85
+ },
86
+ note(message, title) {
87
+ clack.note(message, title);
88
+ },
89
+ spinner() {
90
+ const spin = clack.spinner();
91
+ return {
92
+ start(message) {
93
+ spin.start(message);
94
+ },
95
+ stop(message) {
96
+ spin.stop(message);
97
+ },
98
+ error(message) {
99
+ spin.error(message);
100
+ },
101
+ };
102
+ },
103
+ cancel(message) {
104
+ clack.cancel(message);
105
+ },
106
+ log: {
107
+ success(message) {
108
+ clack.log.success(message);
109
+ },
110
+ error(message) {
111
+ clack.log.error(message);
112
+ },
113
+ info(message) {
114
+ clack.log.info(message);
115
+ },
116
+ },
117
+ };
118
+ }
package/src/render.js ADDED
@@ -0,0 +1,177 @@
1
+ // @ts-check
2
+
3
+ import { createColors } from "picocolors";
4
+
5
+ /** @typedef {ReturnType<typeof createColors>} Palette */
6
+
7
+ const SECRET_KEYS = new Set(["dkim_private_key", "provider_resources"]);
8
+ const STATUS_KEYS = new Set([
9
+ "status",
10
+ "desired_status",
11
+ "dkim_status",
12
+ "return_path_status",
13
+ "dmarc_status",
14
+ "mx_status",
15
+ "drain_status",
16
+ ]);
17
+
18
+ /**
19
+ * @param {{ env?: NodeJS.ProcessEnv, stdout?: { isTTY?: boolean, write?: (chunk: string) => unknown }, isTTY?: boolean, interactive?: boolean }} io
20
+ */
21
+ export function colorsFor(io) {
22
+ const env = io.env ?? {};
23
+ if (env.FORCE_COLOR) return createColors(true);
24
+ if (env.NO_COLOR) return createColors(false);
25
+ return createColors(Boolean(io.interactive || io.isTTY || (io.stdout && io.stdout.isTTY)));
26
+ }
27
+
28
+ /**
29
+ * @param {unknown} value
30
+ * @returns {unknown}
31
+ */
32
+ export function redact(value) {
33
+ if (Array.isArray(value)) return value.map(redact);
34
+ if (value && typeof value === "object") {
35
+ /** @type {Record<string, unknown>} */
36
+ const out = {};
37
+ for (const [key, item] of Object.entries(value)) {
38
+ if (SECRET_KEYS.has(key)) continue;
39
+ out[key] = redact(item);
40
+ }
41
+ return out;
42
+ }
43
+ return value;
44
+ }
45
+
46
+ /**
47
+ * @param {{ write: (chunk: string) => unknown }} stdout
48
+ * @param {unknown} value
49
+ */
50
+ export function writeJson(stdout, value) {
51
+ stdout.write(`${JSON.stringify(redact(value), null, 2)}\n`);
52
+ }
53
+
54
+ /**
55
+ * @param {Palette} c
56
+ */
57
+ export function wordmark(c) {
58
+ const letters = ["p", "o", "s", "t", "s", "h", "i", "b", "a"];
59
+ const paints = [c.cyan, c.magenta, c.yellow, c.green, c.blue, c.cyan, c.magenta, c.yellow, c.green];
60
+ const title = letters.map((ch, i) => paints[i % paints.length](c.bold(ch))).join(" ");
61
+ const line = c.dim("─".repeat(21));
62
+ return [` ${c.dim("╭")} ${title} ${c.dim("╮")}`, ` ${line}`, ` ${c.dim("mail from the terminal")}`].join("\n");
63
+ }
64
+
65
+ /**
66
+ * @param {unknown} value
67
+ * @param {string} key
68
+ * @param {Palette} c
69
+ */
70
+ export function paintStatus(value, key, c) {
71
+ const text = value === null || value === undefined ? "" : String(value);
72
+ if (key === "sending_ready") return value ? c.green("ready") : c.red("not ready");
73
+ if (key === "enabled" || key === "published" || key === "primary") {
74
+ if (value === true) return c.green(text);
75
+ if (value === false) return c.dim(text);
76
+ }
77
+ if (key === "suspended") return value ? c.red("suspended") : c.green("active");
78
+ const lower = text.toLowerCase();
79
+ if (["ready", "verified", "active", "delivered", "pass"].includes(lower)) return c.green(text);
80
+ if (["pending", "not_required"].includes(lower)) return c.yellow(text);
81
+ if (["failed", "suspended", "bounce", "dropped"].includes(lower)) return c.red(text);
82
+ if (STATUS_KEYS.has(key)) return c.yellow(text);
83
+ return text;
84
+ }
85
+
86
+ /**
87
+ * @param {unknown} value
88
+ */
89
+ function cell(value) {
90
+ if (value === null || value === undefined) return "";
91
+ if (typeof value === "boolean") return value ? "true" : "false";
92
+ return String(value);
93
+ }
94
+
95
+ /**
96
+ * @param {Record<string, unknown>[]} rows
97
+ * @param {string[]} columns
98
+ * @param {Palette} c
99
+ */
100
+ export function formatTable(rows, columns, c) {
101
+ const widths = columns.map((col) =>
102
+ Math.max(col.length, ...rows.map((item) => cell(item[col]).length)),
103
+ );
104
+ const header = columns.map((col, i) => c.dim(col.toUpperCase().padEnd(widths[i] ?? 0))).join(" ");
105
+ const lines = [header];
106
+ for (const item of rows) {
107
+ lines.push(
108
+ columns
109
+ .map((col, i) => {
110
+ const raw = cell(item[col]);
111
+ const painted = paintStatus(item[col], col, c);
112
+ const pad = (widths[i] ?? 0) - raw.length;
113
+ return painted + " ".repeat(Math.max(0, pad));
114
+ })
115
+ .join(" "),
116
+ );
117
+ }
118
+ return lines.join("\n");
119
+ }
120
+
121
+ /**
122
+ * @param {Record<string, unknown>} value
123
+ * @param {Palette} c
124
+ */
125
+ export function formatSummary(value, c) {
126
+ const cleaned = /** @type {Record<string, unknown>} */ (redact(value));
127
+ const keys = Object.keys(cleaned);
128
+ const width = Math.max(0, ...keys.map((key) => key.length));
129
+ return keys
130
+ .map((key) => {
131
+ const raw = cleaned[key];
132
+ const display =
133
+ raw && typeof raw === "object" ? JSON.stringify(raw) : paintStatus(raw, key, c);
134
+ return ` ${c.dim(key.padEnd(width))} ${display}`;
135
+ })
136
+ .join("\n");
137
+ }
138
+
139
+ /**
140
+ * @param {unknown} value
141
+ */
142
+ export function asRecords(value) {
143
+ if (Array.isArray(value)) return value.filter((item) => item && typeof item === "object");
144
+ return [];
145
+ }
146
+
147
+ /**
148
+ * @param {unknown} domain
149
+ */
150
+ export function domainDnsRows(domain) {
151
+ if (!domain || typeof domain !== "object") return [];
152
+ const d = /** @type {Record<string, unknown>} */ (domain);
153
+ /** @type {{ type: string, name: string, value: string }[]} */
154
+ const rows = [];
155
+ if (d.dkim_cname_host && d.dkim_cname_target) {
156
+ rows.push({ type: "CNAME", name: String(d.dkim_cname_host), value: String(d.dkim_cname_target) });
157
+ }
158
+ if (d.dkim_manual && d.dkim_txt && d.dkim_cname_host) {
159
+ rows.push({ type: "TXT", name: String(d.dkim_cname_host), value: String(d.dkim_txt) });
160
+ }
161
+ if (d.return_path_host && d.return_path_target) {
162
+ rows.push({ type: "CNAME", name: String(d.return_path_host), value: String(d.return_path_target) });
163
+ }
164
+ if (d.dmarc_host && d.dmarc_record) {
165
+ rows.push({ type: "TXT", name: String(d.dmarc_host), value: String(d.dmarc_record) });
166
+ }
167
+ return rows;
168
+ }
169
+
170
+ /**
171
+ * @param {unknown} domain
172
+ */
173
+ export function domainVerified(domain) {
174
+ if (!domain || typeof domain !== "object") return false;
175
+ const d = /** @type {Record<string, unknown>} */ (domain);
176
+ return d.dkim_status === "verified" && d.return_path_status === "verified";
177
+ }
package/src/send.js ADDED
@@ -0,0 +1,283 @@
1
+ // @ts-check
2
+
3
+ import { readFile } from "node:fs/promises";
4
+ import { basename, extname } from "node:path";
5
+ import { UsageError } from "./errors.js";
6
+ import { domainVerified } from "./render.js";
7
+
8
+ const MIME = {
9
+ ".png": "image/png",
10
+ ".jpg": "image/jpeg",
11
+ ".jpeg": "image/jpeg",
12
+ ".gif": "image/gif",
13
+ ".webp": "image/webp",
14
+ ".pdf": "application/pdf",
15
+ ".txt": "text/plain",
16
+ ".html": "text/html",
17
+ ".htm": "text/html",
18
+ ".json": "application/json",
19
+ ".csv": "text/csv",
20
+ };
21
+
22
+ /**
23
+ * @param {AsyncIterable<string | Uint8Array>} stdin
24
+ */
25
+ export async function readStream(stdin) {
26
+ const chunks = [];
27
+ for await (const chunk of stdin) {
28
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
29
+ }
30
+ return chunks.join("");
31
+ }
32
+
33
+ /**
34
+ * @param {string} raw
35
+ * @param {AsyncIterable<string | Uint8Array>} stdin
36
+ */
37
+ export async function loadData(raw, stdin) {
38
+ let text;
39
+ if (raw === "-") text = await readStream(stdin);
40
+ else if (raw.startsWith("@")) text = await readFile(raw.slice(1), "utf8");
41
+ else text = raw;
42
+ try {
43
+ return JSON.parse(text);
44
+ } catch {
45
+ throw new UsageError("Invalid JSON for --data");
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {Record<string, any>} values
51
+ * @param {AsyncIterable<string | Uint8Array>} stdin
52
+ */
53
+ export async function buildSendBody(values, stdin) {
54
+ const body = values.data !== undefined ? await loadData(values.data, stdin) : {};
55
+ if (values.from) body.from = values.from;
56
+ if (values.to) body.to = values.to;
57
+ if (values.cc) body.cc = values.cc;
58
+ if (values.bcc) body.bcc = values.bcc;
59
+ if (values["reply-to"]) body.reply_to = values["reply-to"];
60
+ if (values.subject) body.subject = values.subject;
61
+ if (values.text !== undefined) body.text = values.text;
62
+ if (values["text-file"]) body.text = await readFile(values["text-file"], "utf8");
63
+ if (values.html !== undefined) body.html = values.html;
64
+ if (values["html-file"]) body.html = await readFile(values["html-file"], "utf8");
65
+
66
+ const usingTemplate = Boolean(values.template || body.template);
67
+ if (values.template) {
68
+ body.template = {
69
+ id: values.template,
70
+ variables: { ...(body.template && body.template.variables), ...pairs(values.var) },
71
+ };
72
+ delete body.html;
73
+ delete body.text;
74
+ } else if (values.var) {
75
+ body.template = {
76
+ ...(body.template ?? {}),
77
+ variables: { ...(body.template && body.template.variables), ...pairs(values.var) },
78
+ };
79
+ }
80
+
81
+ if (values.header) body.headers = { ...body.headers, ...headers(values.header) };
82
+ if (values.arg) body.unique_args = { ...body.unique_args, ...pairs(values.arg) };
83
+ if (values.attach) {
84
+ body.attachments = [];
85
+ for (const file of values.attach) {
86
+ const buf = await readFile(file);
87
+ body.attachments.push({
88
+ filename: basename(file),
89
+ content_type: MIME[/** @type {keyof typeof MIME} */ (extname(file).toLowerCase())] || "application/octet-stream",
90
+ content: buf.toString("base64"),
91
+ });
92
+ }
93
+ }
94
+ if (values.tenant) body.tenant = values.tenant;
95
+
96
+ if (!usingTemplate) {
97
+ if (body.cc === undefined) body.cc = [];
98
+ if (body.bcc === undefined) body.bcc = [];
99
+ }
100
+
101
+ if (!body.from || !hasRecipients(body.to)) {
102
+ throw new UsageError("send requires --from and at least one --to", { helpResource: "send" });
103
+ }
104
+ return body;
105
+ }
106
+
107
+ /**
108
+ * @param {Record<string, any>} values
109
+ * @param {string} [clusterId]
110
+ */
111
+ export function sendRoute(values, clusterId) {
112
+ const sandbox = Boolean(values.sandbox);
113
+ const idempotencyKey = values["idempotency-key"];
114
+ const id = values.cluster ?? clusterId;
115
+ // Cluster-path send is for sandbox or idempotent replay; --cluster alone stays on /emails.
116
+ if (sandbox || idempotencyKey) {
117
+ if (!id) {
118
+ throw new UsageError(
119
+ sandbox
120
+ ? "Missing --cluster. --sandbox requires --cluster."
121
+ : "Missing --cluster. --idempotency-key requires --cluster.",
122
+ { helpResource: "send" },
123
+ );
124
+ }
125
+ return {
126
+ path: "/api/v1/teams/:teamId/clusters/:clusterId/sends",
127
+ team: true,
128
+ clusterId: id,
129
+ sandbox,
130
+ idempotencyKey,
131
+ };
132
+ }
133
+ return {
134
+ path: "/api/v1/emails",
135
+ team: false,
136
+ clusterId: id,
137
+ sandbox: false,
138
+ idempotencyKey: undefined,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * @param {Record<string, any>} values
144
+ * @param {object} ctx
145
+ * @param {import("./prompts.js").Prompts} ctx.prompts
146
+ * @param {(method: string, path: string) => Promise<unknown>} ctx.api
147
+ * @param {{ clusterId?: string, teamId?: string }} creds
148
+ */
149
+ export async function completeSendFlags(values, ctx, creds) {
150
+ const next = { ...values };
151
+ if (!next.from) {
152
+ const domains = asList(await ctx.api("GET", `/api/v1/teams/${creds.teamId}/sending_domains`)).filter(domainVerified);
153
+ const suggestion = domains[0] && typeof domains[0].name === "string" ? `hello@${domains[0].name}` : undefined;
154
+ next.from = await ctx.prompts.text({
155
+ message: "From",
156
+ placeholder: "hello@mail.example.com",
157
+ defaultValue: suggestion,
158
+ });
159
+ }
160
+ if (!next.to) {
161
+ const raw = await ctx.prompts.text({ message: "To (comma separated)", placeholder: "you@example.com" });
162
+ next.to = raw
163
+ .split(",")
164
+ .map((item) => item.trim())
165
+ .filter(Boolean);
166
+ }
167
+ if (!next.subject && !next.template && !next.data) {
168
+ next.subject = await ctx.prompts.text({ message: "Subject" });
169
+ }
170
+ if (!next.text && !next.html && !next.template && !next["html-file"] && !next["text-file"] && !next.data) {
171
+ const kind = await ctx.prompts.select({
172
+ message: "Body",
173
+ options: [
174
+ { value: "text", label: "Plain text" },
175
+ { value: "html", label: "HTML file" },
176
+ { value: "template", label: "Published template" },
177
+ ],
178
+ });
179
+ if (kind === "text") next.text = await ctx.prompts.text({ message: "Text" });
180
+ if (kind === "html") next["html-file"] = await ctx.prompts.text({ message: "HTML file path" });
181
+ if (kind === "template") {
182
+ const templates = asList(await ctx.api("GET", `/api/v1/teams/${creds.teamId}/templates`)).filter(
183
+ (item) => item.published,
184
+ );
185
+ if (templates.length === 0) throw new UsageError("No published templates.", { helpResource: "send" });
186
+ next.template = await ctx.prompts.select({
187
+ message: "Template",
188
+ options: templates.map((item) => ({
189
+ value: String(item.alias ?? item.id),
190
+ label: String(item.name ?? item.alias ?? item.id),
191
+ })),
192
+ });
193
+ /** @type {string[]} */
194
+ const vars = [];
195
+ while (true) {
196
+ const pair = await ctx.prompts.text({
197
+ message: "Variable KEY=VALUE (blank to finish)",
198
+ placeholder: "name=Ada",
199
+ });
200
+ if (!String(pair).trim()) break;
201
+ vars.push(String(pair).trim());
202
+ }
203
+ if (vars.length) next.var = vars;
204
+ }
205
+ }
206
+ if (!next.cluster) {
207
+ if (creds.clusterId) next.cluster = creds.clusterId;
208
+ else if (creds.teamId) {
209
+ const clusters = asList(await ctx.api("GET", `/api/v1/teams/${creds.teamId}/clusters`));
210
+ if (clusters.length === 1) next.cluster = String(clusters[0].id);
211
+ else if (clusters.length > 1) {
212
+ next.cluster = await ctx.prompts.select({
213
+ message: "Cluster",
214
+ options: clusters.map((item) => ({
215
+ value: String(item.id),
216
+ label: String(item.name ?? item.id),
217
+ })),
218
+ });
219
+ }
220
+ }
221
+ }
222
+ return next;
223
+ }
224
+
225
+ /**
226
+ * @param {Record<string, unknown>} body
227
+ * @param {{ sandbox?: boolean, clusterId?: string }} route
228
+ */
229
+ export function sendPreview(body, route) {
230
+ const to = Array.isArray(body.to) ? body.to.join(", ") : String(body.to ?? "");
231
+ const lines = [
232
+ `From ${body.from ?? ""}`,
233
+ `To ${to}`,
234
+ `Subject ${body.subject ?? (body.template ? `(template ${/** @type {{ id?: string }} */ (body.template).id})` : "")}`,
235
+ ];
236
+ if (route.clusterId) lines.push(`Cluster ${route.clusterId}`);
237
+ if (route.sandbox) lines.push("Sandbox yes");
238
+ return lines.join("\n");
239
+ }
240
+
241
+ /**
242
+ * @param {unknown} value
243
+ * @returns {Record<string, any>[]}
244
+ */
245
+ function asList(value) {
246
+ return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
247
+ }
248
+
249
+ /**
250
+ * @param {unknown} to
251
+ */
252
+ function hasRecipients(to) {
253
+ if (Array.isArray(to)) return to.length > 0;
254
+ return Boolean(to);
255
+ }
256
+
257
+ /**
258
+ * @param {string[] | undefined} items
259
+ */
260
+ function pairs(items) {
261
+ /** @type {Record<string, string>} */
262
+ const out = {};
263
+ for (const item of items ?? []) {
264
+ const at = item.indexOf("=");
265
+ if (at === -1) throw new UsageError(`Expected KEY=VALUE, got ${item}`);
266
+ out[item.slice(0, at)] = item.slice(at + 1);
267
+ }
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * @param {string[] | undefined} items
273
+ */
274
+ function headers(items) {
275
+ /** @type {Record<string, string>} */
276
+ const out = {};
277
+ for (const item of items ?? []) {
278
+ const at = item.indexOf(":");
279
+ if (at === -1) throw new UsageError(`Expected "Name: value", got ${item}`, { helpResource: "send" });
280
+ out[item.slice(0, at).trim()] = item.slice(at + 1).trim();
281
+ }
282
+ return out;
283
+ }
package/src/skills.js ADDED
@@ -0,0 +1,40 @@
1
+ // @ts-check
2
+
3
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { UsageError } from "./errors.js";
6
+ import { SKILL_FILE } from "./pkg.js";
7
+
8
+ const TARGETS = {
9
+ cursor: ".cursor/skills/postshiba-cli/SKILL.md",
10
+ claude: ".claude/skills/postshiba-cli/SKILL.md",
11
+ agents: ".agents/skills/postshiba-cli/SKILL.md",
12
+ };
13
+
14
+ /**
15
+ * @param {Record<string, any>} values
16
+ * @param {object} ctx
17
+ * @param {NodeJS.ProcessEnv} ctx.env
18
+ * @param {string} [ctx.cwd]
19
+ * @param {string} [ctx.home]
20
+ * @param {{ write: (chunk: string) => unknown }} ctx.stdout
21
+ */
22
+ export async function installSkill(values, ctx) {
23
+ const targetName = values.target ?? "cursor";
24
+ const rel = TARGETS[/** @type {keyof typeof TARGETS} */ (targetName)];
25
+ if (!rel) {
26
+ throw new UsageError("Unknown --target. Use cursor, claude, or agents.", { helpResource: "skills" });
27
+ }
28
+ const root = values.global
29
+ ? (ctx.home ?? ctx.env.HOME ?? ctx.env.USERPROFILE)
30
+ : (ctx.cwd ?? process.cwd());
31
+ if (!root) throw new UsageError("Missing home directory for --global.");
32
+ const dest = join(root, rel);
33
+ await mkdir(dirname(dest), { recursive: true });
34
+ const body = await readFile(SKILL_FILE);
35
+ await writeFile(dest, body);
36
+ ctx.stdout.write(`${dest}\n`);
37
+ return 0;
38
+ }
39
+
40
+ export { TARGETS };