@leitwerk-dev/jira 0.0.0-stage → 0.4.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.
@@ -0,0 +1,327 @@
1
+ import MarkdownIt from "markdown-it";
2
+ import type Token from "markdown-it/lib/token.mjs";
3
+
4
+ const markdownParser = new MarkdownIt({ html: false, linkify: false });
5
+ const normalizeNewlines = (value: string) => value.replace(/\r\n?/g, "\n");
6
+ const escapeMarkdown = (value: string) => value.replace(/[\\`*_[\]<>|~]/g, "\\$&");
7
+ const escapeJira = (value: string) =>
8
+ value.replace(/[\\*_{}[\]|!+^~]/g, "\\$&").replace(/(?<!\w)-(?=\S)|(?<=\S)-(?!\w)/g, "\\-");
9
+
10
+ function closingToken(tokens: Token[], start: number): number {
11
+ let depth = 0;
12
+ for (let index = start; index < tokens.length; index++) {
13
+ depth += tokens[index]?.nesting ?? 0;
14
+ if (depth === 0) return index;
15
+ }
16
+ return tokens.length;
17
+ }
18
+
19
+ function markdownInlineToJira(tokens: Token[]): string {
20
+ const output: string[] = [];
21
+ for (let index = 0; index < tokens.length; index++) {
22
+ const token = tokens[index];
23
+ if (!token) continue;
24
+ if (token.type === "link_open") {
25
+ const end = closingToken(tokens, index);
26
+ output.push(
27
+ `[${markdownInlineToJira(tokens.slice(index + 1, end))}|${token.attrGet("href") ?? ""}]`,
28
+ );
29
+ index = end;
30
+ } else if (token.type === "code_inline") output.push(`{{${token.content}}}`);
31
+ else if (token.type.startsWith("strong_")) output.push("*");
32
+ else if (token.type.startsWith("em_")) output.push("_");
33
+ else if (token.type.startsWith("s_")) output.push("-");
34
+ else if (token.type === "softbreak") output.push("\n");
35
+ else if (token.type === "hardbreak") output.push("\\\\\n");
36
+ else if (token.type === "image")
37
+ output.push(`[${escapeJira(token.content)}|${token.attrGet("src") ?? ""}]`);
38
+ else
39
+ output.push(
40
+ token.children ? markdownInlineToJira(token.children) : escapeJira(token.content),
41
+ );
42
+ }
43
+ return output.join("");
44
+ }
45
+
46
+ function markdownTableToJira(tokens: Token[]): string {
47
+ const rows: string[] = [];
48
+ for (let index = 0; index < tokens.length; index++) {
49
+ if (tokens[index]?.type !== "tr_open") continue;
50
+ const end = closingToken(tokens, index);
51
+ const row = tokens.slice(index + 1, end);
52
+ const separator = row.some((token) => token.type === "th_open") ? "||" : "|";
53
+ const cells = row
54
+ .filter((token) => token.type === "inline")
55
+ .map((token) => markdownInlineToJira(token.children ?? []));
56
+ rows.push(`${separator}${cells.join(separator)}${separator}`);
57
+ index = end;
58
+ }
59
+ return rows.join("\n");
60
+ }
61
+
62
+ function markdownBlocksToJira(tokens: Token[], listMarkers = ""): string[] {
63
+ const output: string[] = [];
64
+ for (let index = 0; index < tokens.length; index++) {
65
+ const token = tokens[index];
66
+ if (!token) continue;
67
+ if (token.type === "fence" || token.type === "code_block") {
68
+ const language = /^[\w+-]+/.exec(token.info.trim())?.[0] ?? "";
69
+ output.push(
70
+ `{code${language ? `:${language}` : ""}}\n${token.content.replace(/\n$/, "")}\n{code}`,
71
+ );
72
+ } else if (token.type === "hr") output.push("----");
73
+ else if (token.nesting === 1) {
74
+ const end = closingToken(tokens, index);
75
+ const inner = tokens.slice(index + 1, end);
76
+ if (token.type === "bullet_list_open" || token.type === "ordered_list_open") {
77
+ const markers = listMarkers + (token.type === "bullet_list_open" ? "*" : "#");
78
+ const items: string[] = [];
79
+ for (let item = 0; item < inner.length; item++) {
80
+ if (inner[item]?.type !== "list_item_open") continue;
81
+ const itemEnd = closingToken(inner, item);
82
+ const blocks = markdownBlocksToJira(inner.slice(item + 1, itemEnd), markers);
83
+ items.push(`${markers} ${blocks.join("\n")}`);
84
+ item = itemEnd;
85
+ }
86
+ output.push(items.join("\n"));
87
+ } else if (token.type === "blockquote_open")
88
+ output.push(`{quote}\n${markdownBlocksToJira(inner, listMarkers).join("\n\n")}\n{quote}`);
89
+ else if (token.type === "table_open") output.push(markdownTableToJira(inner));
90
+ else {
91
+ const text = markdownBlocksToJira(inner, listMarkers).join("\n\n");
92
+ output.push(token.type === "heading_open" ? `${token.tag}. ${text}` : text);
93
+ }
94
+ index = end;
95
+ } else if (token.type === "inline") output.push(markdownInlineToJira(token.children ?? []));
96
+ else if (token.content) output.push(escapeJira(token.content));
97
+ }
98
+ return output;
99
+ }
100
+
101
+ /** Converts ticket Markdown to Jira Server/Data Center wiki markup. @internal */
102
+ export function markdownToJira(markdown: string): string {
103
+ return markdownBlocksToJira(markdownParser.parse(normalizeNewlines(markdown ?? ""), {})).join(
104
+ "\n\n",
105
+ );
106
+ }
107
+
108
+ function backtickDelimiter(value: string, minimum: number): string {
109
+ const lengths = [...value.matchAll(/`+/g)].map((match) => match[0].length + 1);
110
+ return "`".repeat(Math.max(minimum, ...lengths));
111
+ }
112
+
113
+ function markdownCodeSpan(value: string): string {
114
+ const delimiter = backtickDelimiter(value, 1);
115
+ const pad = /^`|`$|^ .* $/s.test(value) ? " " : "";
116
+ return `${delimiter}${pad}${value}${pad}${delimiter}`;
117
+ }
118
+
119
+ function literalEnd(value: string, start: number): number | null {
120
+ if (value.startsWith("{{", start)) {
121
+ const closing = /}{2,}/.exec(value.slice(start + 2));
122
+ return closing ? start + 2 + closing.index + closing[0].length : null;
123
+ }
124
+ if (value[start] === "[" || value[start] === "{") {
125
+ const close = value[start] === "[" ? "]" : "}";
126
+ for (let index = start + 1; index < value.length; index++) {
127
+ if (value[index] === "\\") index++;
128
+ else if (value[index] === close) return index + 1;
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+
134
+ function jiraEmphasisEnd(value: string, start: number, delimiter: string): number | null {
135
+ for (let index = start + 1; index < value.length; index++) {
136
+ if (value[index] === "\\") {
137
+ index++;
138
+ continue;
139
+ }
140
+ const protectedEnd = literalEnd(value, index);
141
+ if (protectedEnd !== null) {
142
+ index = protectedEnd - 1;
143
+ continue;
144
+ }
145
+ if (
146
+ value[index] === delimiter &&
147
+ index > start + 1 &&
148
+ !/\s/.test(value[index - 1] ?? "") &&
149
+ !/[\w]/.test(value[index + 1] ?? "")
150
+ )
151
+ return index;
152
+ }
153
+ return null;
154
+ }
155
+
156
+ function jiraInlineToMarkdown(value: string): string {
157
+ const output: string[] = [];
158
+ for (let index = 0; index < value.length; index++) {
159
+ const char = value[index] ?? "";
160
+ if (value.startsWith("\\\\", index)) {
161
+ output.push(" \n");
162
+ index++;
163
+ continue;
164
+ }
165
+ if (char === "\\" && /[\\*_{}[\]|!+\-^~]/.test(value[index + 1] ?? "")) {
166
+ output.push(escapeMarkdown(value[++index] ?? ""));
167
+ continue;
168
+ }
169
+ const end = literalEnd(value, index);
170
+ if (end !== null && value.startsWith("{{", index)) {
171
+ output.push(markdownCodeSpan(value.slice(index + 2, end - 2)));
172
+ index = end - 1;
173
+ continue;
174
+ }
175
+ if (end !== null && char === "[") {
176
+ const link = value.slice(index + 1, end - 1);
177
+ const separator = link.search(/(?<!\\)\|/);
178
+ const target = (separator < 0 ? link : link.slice(separator + 1)).trim();
179
+ if (/^(https?:\/\/|mailto:)/i.test(target)) {
180
+ const label =
181
+ separator < 0 ? escapeMarkdown(link) : jiraInlineToMarkdown(link.slice(0, separator));
182
+ const url = target.replace(/[<>\s\\]/g, (c) => encodeURIComponent(c));
183
+ output.push(`[${label}](${/[()]/.test(url) ? `<${url}>` : url})`);
184
+ } else output.push(escapeMarkdown(value.slice(index, end)));
185
+ index = end - 1;
186
+ continue;
187
+ }
188
+ if (end !== null && char === "{") {
189
+ output.push(escapeMarkdown(value.slice(index, end)));
190
+ index = end - 1;
191
+ continue;
192
+ }
193
+ const delimiter = char === "*" ? "**" : char === "_" ? "*" : char === "-" ? "~~" : null;
194
+ if (
195
+ delimiter &&
196
+ !/[\w]/.test(value[index - 1] ?? "") &&
197
+ !/[\s]/.test(value[index + 1] ?? "") &&
198
+ value[index + 1] !== char
199
+ ) {
200
+ const close = jiraEmphasisEnd(value, index, char);
201
+ if (close !== null) {
202
+ output.push(
203
+ `${delimiter}${jiraInlineToMarkdown(value.slice(index + 1, close))}${delimiter}`,
204
+ );
205
+ index = close;
206
+ continue;
207
+ }
208
+ }
209
+ output.push(escapeMarkdown(char));
210
+ }
211
+ return output.join("");
212
+ }
213
+
214
+ function jiraTableRow(line: string): { cells: string[]; header: boolean } | null {
215
+ const row = line.trim();
216
+ if (!row.startsWith("|") || !row.endsWith("|")) return null;
217
+ const cells: string[] = [];
218
+ let cell = "";
219
+ const start = row.startsWith("||") ? 2 : 1;
220
+ const end = row.length - (row.endsWith("||") ? 2 : 1);
221
+ for (let index = start; index < end; index++) {
222
+ if (row[index] === "\\" && index + 1 < end) cell += row[index] + row[++index];
223
+ else {
224
+ const protectedEnd = literalEnd(row, index);
225
+ if (protectedEnd !== null) {
226
+ cell += row.slice(index, protectedEnd);
227
+ index = protectedEnd - 1;
228
+ } else if (row[index] === "|") {
229
+ cells.push(cell.trim());
230
+ cell = "";
231
+ if (row[index + 1] === "|") index++;
232
+ } else cell += row[index];
233
+ }
234
+ }
235
+ cells.push(cell.trim());
236
+ return { cells, header: start === 2 };
237
+ }
238
+
239
+ function jiraTextToMarkdown(value: string): string {
240
+ const lines = value.split("\n");
241
+ const output: string[] = [];
242
+ for (let index = 0; index < lines.length; index++) {
243
+ const line = lines[index] ?? "";
244
+ const table = jiraTableRow(line);
245
+ if (table) {
246
+ const rows = [table];
247
+ while (index + 1 < lines.length) {
248
+ const next = jiraTableRow(lines[index + 1] ?? "");
249
+ if (!next) break;
250
+ rows.push(next);
251
+ index++;
252
+ }
253
+ const width = Math.max(...rows.map((row) => row.cells.length));
254
+ const renderRow = (cells: string[]) =>
255
+ `| ${Array.from({ length: width }, (_, column) =>
256
+ jiraInlineToMarkdown(cells[column] ?? "").replace(/(?<!\\)\|/g, "\\|"),
257
+ ).join(" | ")} |`;
258
+ const header = table.header ? (rows.shift()?.cells ?? []) : [];
259
+ output.push(
260
+ renderRow(header),
261
+ `| ${Array(width).fill("---").join(" | ")} |`,
262
+ ...rows.map((row) => renderRow(row.cells)),
263
+ );
264
+ continue;
265
+ }
266
+ const heading = /^h([1-6])\.\s+(.*)$/.exec(line);
267
+ const list = /^\s*([*#]+)\s+(.*)$/.exec(line);
268
+ if (heading)
269
+ output.push(`${"#".repeat(Number(heading[1]))} ${jiraInlineToMarkdown(heading[2] ?? "")}`);
270
+ else if (list) {
271
+ const markers = list[1] ?? "*";
272
+ output.push(
273
+ `${" ".repeat(markers.length - 1)}${markers.endsWith("#") ? "1." : "-"} ${jiraInlineToMarkdown(list[2] ?? "")}`,
274
+ );
275
+ } else if (/^bq\.\s?/.test(line))
276
+ output.push(`> ${jiraInlineToMarkdown(line.replace(/^bq\.\s?/, ""))}`);
277
+ else if (/^-{4,}\s*$/.test(line)) output.push("---");
278
+ else output.push(jiraInlineToMarkdown(line));
279
+ }
280
+ return output.join("\n");
281
+ }
282
+
283
+ /** Converts Jira wiki markup to Markdown while retaining unsupported macros as text. @internal */
284
+ export function jiraToMarkdown(markup: string | null | undefined): string {
285
+ const value = normalizeNewlines(markup ?? "");
286
+ const output: string[] = [];
287
+ let cursor = 0;
288
+ for (let index = 0; index < value.length; index++) {
289
+ if (value[index] === "\\") {
290
+ index++;
291
+ continue;
292
+ }
293
+ const match = /^\{(code|noformat|quote)(?::([^}\n]*))?}/.exec(value.slice(index));
294
+ if (!match || value.startsWith("{{", index)) {
295
+ const protectedEnd = literalEnd(value, index);
296
+ if (protectedEnd !== null) index = protectedEnd - 1;
297
+ continue;
298
+ }
299
+ const start = index + match[0].length;
300
+ const end = value.indexOf(`{${match[1]}}`, start);
301
+ if (end < 0) continue;
302
+ const before = jiraTextToMarkdown(value.slice(cursor, index)).replace(/^\n+|\n+$/g, "");
303
+ if (before) output.push(before);
304
+ const content = value.slice(start, end).replace(/^\n|\n$/g, "");
305
+ if (match[1] === "quote")
306
+ output.push(
307
+ jiraToMarkdown(content)
308
+ .split("\n")
309
+ .map((line) => `> ${line}`)
310
+ .join("\n"),
311
+ );
312
+ else {
313
+ const params = match[2] ?? "";
314
+ const language =
315
+ /(?:^|\|)language=([\w+-]+)/.exec(params)?.[1] ??
316
+ /^([\w+-]+)(?:\||$)/.exec(params)?.[1] ??
317
+ "";
318
+ const fence = backtickDelimiter(content, 3);
319
+ output.push(`${fence}${language}\n${content}\n${fence}`);
320
+ }
321
+ cursor = end + `{${match[1]}}`.length;
322
+ index = cursor - 1;
323
+ }
324
+ const after = jiraTextToMarkdown(value.slice(cursor)).replace(/^\n+|\n+$/g, "");
325
+ if (after) output.push(after);
326
+ return output.join("\n\n");
327
+ }