slack-copy 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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -0
  3. package/dist/index.js +345 -0
  4. package/package.json +44 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Finn Janssens
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # slack-copy
2
+
3
+ Markdown on the clipboard, ready to paste into Slack.
4
+
5
+ ## Requirements
6
+
7
+ - macOS (the clipboard write goes through `osascript`; with `--no-copy` the
8
+ converter prints on any platform)
9
+ - Node.js 18+
10
+
11
+ ## Install
12
+
13
+ From npm:
14
+
15
+ ```bash
16
+ npx slack-copy message.md
17
+ # or
18
+ npm install -g slack-copy
19
+ ```
20
+
21
+ Pre-publish, run it straight from GitHub:
22
+
23
+ ```bash
24
+ npx github:finnjanssens/slack-copy message.md
25
+ ```
26
+
27
+ Or as an [Agent Skill](https://agentskills.io) for Claude Code, Cursor, Codex,
28
+ opencode, or any other agent the [skills CLI](https://github.com/vercel-labs/skills)
29
+ supports:
30
+
31
+ ```bash
32
+ npx skills add finnjanssens/slack-copy -g # every detected agent
33
+ npx skills add finnjanssens/slack-copy -g -a claude-code # one agent
34
+ ```
35
+
36
+ Or manually:
37
+
38
+ ```bash
39
+ git clone https://github.com/finnjanssens/slack-copy.git
40
+ ln -s "$(pwd)/slack-copy" ~/.claude/skills/slack-copy
41
+ ```
42
+
43
+ See [SKILL.md](SKILL.md) for the skill instructions.
44
+
45
+ Slack's default composer is rich text: the one with the **B** *I* U toolbar. It
46
+ does not interpret mrkdwn, so pasting `*bold*` or `<url|label>` into it leaves
47
+ the asterisks, pipes and brackets sitting there literally. mrkdwn is only
48
+ interpreted for messages sent through the API, or when you turn on the "format
49
+ messages with markup" preference, which replaces the rich composer entirely.
50
+
51
+ So this puts two clipboard flavours down at once:
52
+
53
+ - **`text/html`** — what the rich composer actually reads. Pasting produces real
54
+ bold, lists, code and links, with no Slack setting involved.
55
+ - **plain text** — mrkdwn, as a fallback for markup mode and for API posting.
56
+
57
+ ## Usage
58
+
59
+ ```bash
60
+ npx slack-copy message.md # convert and copy
61
+ npx github:finnjanssens/slack-copy message.md # pre-publish, from GitHub
62
+ cat message.md | npx slack-copy
63
+ npx slack-copy --no-copy msg.md # print only
64
+ npx slack-copy --html msg.md # print the HTML it copies
65
+ ```
66
+
67
+ Reads a file argument or stdin. Prints the mrkdwn on stdout, since it is the
68
+ readable one to eyeball. macOS only: the clipboard write goes through
69
+ `osascript`, because `pbcopy` can only carry plain text.
70
+
71
+ ## Conversions
72
+
73
+ See [references/conversions.md](references/conversions.md) for the full
74
+ Markdown → mrkdwn/HTML table.
75
+
76
+ ## Test
77
+
78
+ ```bash
79
+ npm test # unit suite + eval rows
80
+ node evals/check.js # evals only
81
+ ```
82
+
83
+ `test.ts` is the unit suite; `evals/` holds the data-driven evals: one row in
84
+ `evals/cases.json` pins one behaviour, and `evals/check.js` reports by row ID.
85
+ A new behaviour is a new row, and CI runs both on every PR.
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ #!/usr/bin/env node
2
+ // slack-copy: Markdown -> Slack, on the clipboard.
3
+ //
4
+ // Slack's default composer is rich text (the B/I/U toolbar). It does not
5
+ // interpret mrkdwn at all: pasted *bold* stays literally *bold* and <url|label>
6
+ // shows its pipe and brackets. mrkdwn is only interpreted for messages sent
7
+ // through the API, or when the "format messages with markup" preference is on.
8
+ //
9
+ // So the clipboard gets two flavours:
10
+ //
11
+ // text/html what the rich composer actually reads. Pasting it produces real
12
+ // bold, lists and links with no Slack setting involved.
13
+ // plain text mrkdwn, as a fallback for markup mode and for API posting.
14
+ //
15
+ // Hand-rolled rather than parsed: neither target needs more than a block pass
16
+ // plus an inline pass.
17
+ import { readFileSync, realpathSync } from "node:fs";
18
+ import { execFileSync } from "node:child_process";
19
+ const BOLD = "\x00";
20
+ const ITALIC = "\x01";
21
+ // Slack requires these three escaped everywhere, including inside code spans and
22
+ // fences. It unescapes them when rendering.
23
+ const escapeEntities = (s) => s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
24
+ const isTableSeparator = (line) => /^\s*\|?[\s:|-]*-[\s:|-]*\|[\s:|-]*$/.test(line ?? "");
25
+ const isTableRow = (line) => /^\s*\|/.test(line);
26
+ // Inline formatting for one run of non-code text.
27
+ function formatRun(text) {
28
+ let out = escapeEntities(text);
29
+ // Autolinks were written as <url>, so undo the escaping we just applied.
30
+ out = out.replace(/&lt;((?:https?|mailto):[^\s|>]+)&gt;/g, "<$1>");
31
+ // Links before emphasis, so emphasis inside the link label still converts.
32
+ // Titles are dropped, mrkdwn has nowhere to put them.
33
+ const link = (_, label, url) => (label ? `<${url}|${label}>` : `<${url}>`);
34
+ out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, link);
35
+ out = out.replace(/\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, link);
36
+ // Emphasis markers are emitted as sentinels and swapped for real ones at the
37
+ // end. Writing "*" directly would let the *italic* rule re-match the "*bold*"
38
+ // the ** rule just produced and turn it into _bold_.
39
+ // Longest marker first: *** would otherwise be eaten by the ** rule.
40
+ out = out.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, `${BOLD}${ITALIC}$2${ITALIC}${BOLD}`);
41
+ out = out.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, `${BOLD}$2${BOLD}`);
42
+ // *italic* -> _italic_. Word-boundary guards keep a*b and 2*3 alone; single
43
+ // _italic_ needs no rule, mrkdwn already spells it that way.
44
+ out = out.replace(/(?<![\w*])\*(?=\S)([^*\n]*\S)\*(?![\w*])/g, `${ITALIC}$1${ITALIC}`);
45
+ out = out.replace(/~~(?=\S)([\s\S]*?\S)~~/g, "~$1~");
46
+ return out.replaceAll(BOLD, "*").replaceAll(ITALIC, "_");
47
+ }
48
+ // Split code spans out so their contents are escaped but never reformatted.
49
+ const formatInline = (text) => text
50
+ .split(/(`+[^`\n]+`+)/g)
51
+ .map((part, i) => (i % 2 ? escapeEntities(part) : formatRun(part)))
52
+ .join("");
53
+ export function toSlack(markdown) {
54
+ const lines = markdown
55
+ .replace(/\r\n?/g, "\n")
56
+ .replace(/<!--[\s\S]*?-->/g, "")
57
+ .split("\n");
58
+ const out = [];
59
+ let inFence = false;
60
+ for (let i = 0; i < lines.length; i++) {
61
+ const line = lines[i];
62
+ if (/^\s*(```|~~~)/.test(line)) {
63
+ inFence = !inFence;
64
+ // mrkdwn fences take no language.
65
+ out.push("```");
66
+ continue;
67
+ }
68
+ if (inFence) {
69
+ out.push(escapeEntities(line));
70
+ continue;
71
+ }
72
+ // Tables have no mrkdwn equivalent; a fence at least keeps them aligned.
73
+ if (isTableRow(line) && isTableSeparator(lines[i + 1])) {
74
+ const rows = [];
75
+ while (i < lines.length && isTableRow(lines[i])) {
76
+ if (!isTableSeparator(lines[i]))
77
+ rows.push(escapeEntities(lines[i]));
78
+ i++;
79
+ }
80
+ i--;
81
+ out.push("```", ...rows, "```");
82
+ continue;
83
+ }
84
+ const heading = line.match(/^#{1,6}\s+(.*?)\s*#*$/);
85
+ if (heading) {
86
+ // The whole heading is already bold, so bold inside it would only add
87
+ // stray asterisks.
88
+ out.push(`*${formatInline(heading[1].replace(/\*\*|__/g, ""))}*`);
89
+ continue;
90
+ }
91
+ // Horizontal rule: --- / *** / ___
92
+ if (/^\s*([-*_])(?:\s*\1){2,}\s*$/.test(line)) {
93
+ out.push("────────");
94
+ continue;
95
+ }
96
+ const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
97
+ if (bullet) {
98
+ out.push(`${bullet[1]}• ${formatInline(bullet[2])}`);
99
+ continue;
100
+ }
101
+ // Slack does not renumber, so the author's numbers are kept verbatim.
102
+ const ordered = line.match(/^(\s*)(\d+)[.)]\s+(.*)$/);
103
+ if (ordered) {
104
+ out.push(`${ordered[1]}${ordered[2]}. ${formatInline(ordered[3])}`);
105
+ continue;
106
+ }
107
+ const quote = line.match(/^\s*>\s?(.*)$/);
108
+ if (quote) {
109
+ out.push(`> ${formatInline(quote[1])}`);
110
+ continue;
111
+ }
112
+ out.push(formatInline(line));
113
+ }
114
+ // Trim both ends: a multi-line comment at the top would otherwise leave a
115
+ // blank first line in the pasted message.
116
+ return out.join("\n").trim() + "\n";
117
+ }
118
+ // ---------------------------------------------------------------- HTML output
119
+ const escapeHtml = (s) => s
120
+ .replaceAll("&", "&amp;")
121
+ .replaceAll("<", "&lt;")
122
+ .replaceAll(">", "&gt;")
123
+ .replaceAll('"', "&quot;");
124
+ function inlineHtmlRun(text) {
125
+ let out = escapeHtml(text);
126
+ // Bare autolinks were written as <url>.
127
+ out = out.replace(/&lt;((?:https?|mailto):[^\s|>]+)&gt;/g, '<a href="$1">$1</a>');
128
+ const link = (_, label, url) => `<a href="${url}">${label || url}</a>`;
129
+ out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, link);
130
+ out = out.replace(/\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, link);
131
+ out = out.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, "<b><i>$2</i></b>");
132
+ out = out.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, "<b>$2</b>");
133
+ out = out.replace(/(?<![\w*])\*(?=\S)([^*\n]*\S)\*(?![\w*])/g, "<i>$1</i>");
134
+ out = out.replace(/(?<![\w_])_(?=\S)([^_\n]*\S)_(?![\w_])/g, "<i>$1</i>");
135
+ out = out.replace(/~~(?=\S)([\s\S]*?\S)~~/g, "<s>$1</s>");
136
+ return out;
137
+ }
138
+ const inlineHtml = (text) => text
139
+ .split(/(`+[^`\n]+`+)/g)
140
+ .map((part, i) => i % 2 ? `<code>${escapeHtml(part.replace(/^`+|`+$/g, ""))}</code>` : inlineHtmlRun(part))
141
+ .join("");
142
+ // Items are pre-collected as {indent, ordered, text}; nesting comes from indent,
143
+ // and a deeper list is emitted inside the <li> that precedes it so Slack shows it
144
+ // as a sub-bullet rather than a new list.
145
+ function listHtml(items, cursor, indent) {
146
+ const ordered = items[cursor.i].ordered;
147
+ let html = ordered ? "<ol>" : "<ul>";
148
+ while (cursor.i < items.length) {
149
+ const item = items[cursor.i];
150
+ if (item.indent < indent || (item.indent === indent && item.ordered !== ordered))
151
+ break;
152
+ cursor.i++;
153
+ html += `<li>${inlineHtml(item.text)}`;
154
+ const next = items[cursor.i];
155
+ if (next && next.indent > indent)
156
+ html += listHtml(items, cursor, next.indent);
157
+ html += "</li>";
158
+ }
159
+ return html + (ordered ? "</ol>" : "</ul>");
160
+ }
161
+ export function toHtml(markdown) {
162
+ const lines = markdown
163
+ .replace(/\r\n?/g, "\n")
164
+ .replace(/<!--[\s\S]*?-->/g, "")
165
+ .split("\n");
166
+ const out = [];
167
+ let paragraph = [];
168
+ const flush = () => {
169
+ if (paragraph.length)
170
+ out.push(`<p>${paragraph.map(inlineHtml).join("<br>")}</p>`);
171
+ paragraph = [];
172
+ };
173
+ for (let i = 0; i < lines.length; i++) {
174
+ const line = lines[i];
175
+ if (!line.trim()) {
176
+ flush();
177
+ continue;
178
+ }
179
+ if (/^\s*(```|~~~)/.test(line)) {
180
+ flush();
181
+ const code = [];
182
+ i++;
183
+ while (i < lines.length && !/^\s*(```|~~~)/.test(lines[i]))
184
+ code.push(lines[i++]);
185
+ out.push(`<pre><code>${escapeHtml(code.join("\n"))}</code></pre>`);
186
+ continue;
187
+ }
188
+ if (isTableRow(line) && isTableSeparator(lines[i + 1])) {
189
+ flush();
190
+ const rows = [];
191
+ while (i < lines.length && isTableRow(lines[i])) {
192
+ if (!isTableSeparator(lines[i]))
193
+ rows.push(lines[i]);
194
+ i++;
195
+ }
196
+ i--;
197
+ // Slack's composer has no table, but a code block keeps the columns lined up.
198
+ out.push(`<pre><code>${escapeHtml(rows.join("\n"))}</code></pre>`);
199
+ continue;
200
+ }
201
+ const heading = line.match(/^#{1,6}\s+(.*?)\s*#*$/);
202
+ if (heading) {
203
+ flush();
204
+ // Slack has no headings, so a bold paragraph is as close as it gets.
205
+ out.push(`<p><b>${inlineHtml(heading[1].replace(/\*\*|__/g, ""))}</b></p>`);
206
+ continue;
207
+ }
208
+ if (/^\s*([-*_])(?:\s*\1){2,}\s*$/.test(line)) {
209
+ flush();
210
+ out.push("<p>────────</p>");
211
+ continue;
212
+ }
213
+ if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) {
214
+ flush();
215
+ const start = i;
216
+ const items = [];
217
+ while (i < lines.length) {
218
+ const item = lines[i].match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);
219
+ if (!item)
220
+ break;
221
+ items.push({
222
+ indent: item[1].length,
223
+ ordered: /\d/.test(item[2]),
224
+ text: item[3],
225
+ });
226
+ i++;
227
+ }
228
+ // listHtml may stop before the end: a type change at the same indent
229
+ // starts a new list, so the unconsumed lines must be re-examined
230
+ // instead of being skipped by a plain i--. cursor.i is relative to the
231
+ // line the list started on, hence the offset from `start`.
232
+ const cursor = { i: 0 };
233
+ out.push(listHtml(items, cursor, items[0].indent));
234
+ i = start + cursor.i - 1;
235
+ continue;
236
+ }
237
+ const quote = line.match(/^\s*>\s?(.*)$/);
238
+ if (quote) {
239
+ flush();
240
+ const quoted = [quote[1]];
241
+ while (i + 1 < lines.length && /^\s*>/.test(lines[i + 1])) {
242
+ quoted.push(lines[++i].replace(/^\s*>\s?/, ""));
243
+ }
244
+ out.push(`<blockquote>${quoted.map(inlineHtml).join("<br>")}</blockquote>`);
245
+ continue;
246
+ }
247
+ paragraph.push(line);
248
+ }
249
+ flush();
250
+ return out.join("");
251
+ }
252
+ export function copyPlan(platform, html, plain) {
253
+ if (platform === "darwin") {
254
+ // pbcopy is plain text only, so this goes through AppleScript; both
255
+ // payloads are hex so nothing needs escaping for AppleScript's syntax.
256
+ const hex = (s) => Buffer.from(s, "utf8").toString("hex");
257
+ return [
258
+ {
259
+ cmd: "osascript",
260
+ args: [
261
+ "-e",
262
+ `set the clipboard to {«class HTML»:«data HTML${hex(html)}», ` +
263
+ `«class utf8»:«data utf8${hex(plain)}»}`,
264
+ ],
265
+ input: "",
266
+ },
267
+ ];
268
+ }
269
+ if (platform === "linux") {
270
+ // wl-copy and xclip offer a single flavour per invocation, so it has to be
271
+ // text/html: that is what Slack's rich composer reads, and pasting plain
272
+ // mrkdwn into it is exactly what this tool exists to avoid.
273
+ return [
274
+ { cmd: "wl-copy", args: ["--type", "text/html"], input: html },
275
+ { cmd: "xclip", args: ["-selection", "clipboard", "-t", "text/html"], input: html },
276
+ ];
277
+ }
278
+ if (platform === "win32") {
279
+ // Set-Clipboard is plain text only; CF_HTML is the upgrade path.
280
+ return [
281
+ { cmd: "powershell", args: ["-NoProfile", "-Command", "$input | Set-Clipboard"], input: plain },
282
+ ];
283
+ }
284
+ return [];
285
+ }
286
+ export function copyWith(plan, run) {
287
+ let last;
288
+ for (const { cmd, args, input } of plan) {
289
+ try {
290
+ run(cmd, args, input);
291
+ return;
292
+ }
293
+ catch (err) {
294
+ last = err;
295
+ }
296
+ }
297
+ throw last instanceof Error ? last : new Error("clipboard copy failed");
298
+ }
299
+ function copyRich(html, plain) {
300
+ try {
301
+ copyWith(copyPlan(process.platform, html, plain), (cmd, args, input) =>
302
+ // stdout/stderr ignored: xclip and wl-copy fork a daemon that owns the
303
+ // selection, and it would hold inherited output pipes open forever.
304
+ execFileSync(cmd, args, { input, stdio: ["pipe", "ignore", "ignore"] }));
305
+ }
306
+ catch {
307
+ process.stderr.write("slack-copy: could not set the clipboard (install wl-clipboard or xclip on linux)\n");
308
+ process.exit(1);
309
+ }
310
+ if (process.platform === "win32") {
311
+ process.stderr.write("slack-copy: rich text not supported on this platform, copied plain mrkdwn only\n");
312
+ }
313
+ }
314
+ function main(argv) {
315
+ const args = argv.slice(2);
316
+ const noCopy = args.includes("--no-copy");
317
+ const rest = args.filter((a) => !a.startsWith("--"));
318
+ if (rest.includes("-h") || rest.includes("--help")) {
319
+ process.stdout.write("usage: slack-copy [--no-copy|--html] [file]\n\n" +
320
+ "Reads Markdown from <file> or stdin and copies it to the clipboard as\n" +
321
+ "rich text, ready to paste into Slack's composer. Prints the mrkdwn\n" +
322
+ "equivalent on stdout.\n\n" +
323
+ " --no-copy print only, leave the clipboard alone\n" +
324
+ " --html print the HTML that goes on the clipboard\n");
325
+ return 0;
326
+ }
327
+ const file = rest[0];
328
+ if (!file && process.stdin.isTTY) {
329
+ process.stderr.write("slack-copy: no input (pass a file or pipe stdin)\n");
330
+ return 2;
331
+ }
332
+ const markdown = readFileSync(file && file !== "-" ? file : 0, "utf8");
333
+ const slack = toSlack(markdown);
334
+ // Copy before printing: if the copy fails we exit non-zero without having
335
+ // claimed success on stdout.
336
+ if (!noCopy)
337
+ copyRich(toHtml(markdown), slack);
338
+ process.stdout.write(args.includes("--html") ? toHtml(markdown) + "\n" : slack);
339
+ return 0;
340
+ }
341
+ // realpath both sides: npx runs the bin through a node_modules/.bin symlink, so
342
+ // a plain argv[1] comparison never matches and the CLI silently does nothing.
343
+ if (process.argv[1] && realpathSync(process.argv[1]) === import.meta.filename) {
344
+ process.exit(main(process.argv));
345
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "slack-copy",
3
+ "version": "1.0.0",
4
+ "description": "Convert Markdown to Slack mrkdwn and put it on the clipboard",
5
+ "type": "module",
6
+ "author": {
7
+ "name": "Finn Janssens",
8
+ "url": "https://github.com/finnjanssens"
9
+ },
10
+ "homepage": "https://github.com/finnjanssens/slack-copy#readme",
11
+ "bugs": "https://github.com/finnjanssens/slack-copy/issues",
12
+ "bin": {
13
+ "slack-copy": "dist/index.js"
14
+ },
15
+ "files": [
16
+ "dist/index.js"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.build.json",
20
+ "prepublishOnly": "npm run build",
21
+ "test": "node test.ts && node clipboard.test.ts && node evals/check.ts",
22
+ "typecheck": "tsc --noEmit",
23
+ "evals": "node evals/check.ts"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^26",
27
+ "typescript": "^5"
28
+ },
29
+ "engines": {
30
+ "node": ">=26"
31
+ },
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/finnjanssens/slack-copy.git"
36
+ },
37
+ "keywords": [
38
+ "slack",
39
+ "markdown",
40
+ "mrkdwn",
41
+ "clipboard",
42
+ "cli"
43
+ ]
44
+ }