@tooee/renderers 0.2.4 → 0.3.1

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 (116) hide show
  1. package/dist/code-blocks.d.ts +6 -6
  2. package/dist/code-blocks.d.ts.map +1 -1
  3. package/dist/code-blocks.js +52 -42
  4. package/dist/code-blocks.js.map +1 -1
  5. package/dist/{CodeView.d.ts → code-view.d.ts} +3 -3
  6. package/dist/code-view.d.ts.map +1 -0
  7. package/dist/{CodeView.js → code-view.js} +5 -5
  8. package/dist/code-view.js.map +1 -0
  9. package/dist/{CommandPalette.d.ts → command-palette.d.ts} +2 -2
  10. package/dist/command-palette.d.ts.map +1 -0
  11. package/dist/{CommandPalette.js → command-palette.js} +27 -24
  12. package/dist/command-palette.js.map +1 -0
  13. package/dist/{ContextMenu.d.ts → context-menu.d.ts} +2 -2
  14. package/dist/context-menu.d.ts.map +1 -0
  15. package/dist/{ContextMenu.js → context-menu.js} +24 -14
  16. package/dist/context-menu.js.map +1 -0
  17. package/dist/{DecorationLayer.d.ts → decoration-layer.d.ts} +2 -2
  18. package/dist/decoration-layer.d.ts.map +1 -0
  19. package/dist/decoration-layer.js +2 -0
  20. package/dist/decoration-layer.js.map +1 -0
  21. package/dist/{DocumentBindings.d.ts → document-bindings.d.ts} +4 -4
  22. package/dist/document-bindings.d.ts.map +1 -0
  23. package/dist/document-bindings.js +2 -0
  24. package/dist/document-bindings.js.map +1 -0
  25. package/dist/index.d.ts +16 -15
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +9 -9
  28. package/dist/index.js.map +1 -1
  29. package/dist/markdown-blocks.d.ts +9 -13
  30. package/dist/markdown-blocks.d.ts.map +1 -1
  31. package/dist/markdown-blocks.js +98 -79
  32. package/dist/markdown-blocks.js.map +1 -1
  33. package/dist/{MarkdownView.d.ts → markdown-view.d.ts} +13 -13
  34. package/dist/markdown-view.d.ts.map +1 -0
  35. package/dist/markdown-view.js +455 -0
  36. package/dist/markdown-view.js.map +1 -0
  37. package/dist/mermaid.d.ts +6 -6
  38. package/dist/mermaid.d.ts.map +1 -1
  39. package/dist/mermaid.js +56 -26
  40. package/dist/mermaid.js.map +1 -1
  41. package/dist/parsers.d.ts +5 -5
  42. package/dist/parsers.d.ts.map +1 -1
  43. package/dist/parsers.js +64 -44
  44. package/dist/parsers.js.map +1 -1
  45. package/dist/{RowDocumentRenderable.d.ts → row-document-renderable.d.ts} +15 -11
  46. package/dist/row-document-renderable.d.ts.map +1 -0
  47. package/dist/{RowDocumentRenderable.js → row-document-renderable.js} +110 -62
  48. package/dist/row-document-renderable.js.map +1 -0
  49. package/dist/row-document.d.ts +1 -1
  50. package/dist/row-document.d.ts.map +1 -1
  51. package/dist/row-document.js +1 -1
  52. package/dist/row-document.js.map +1 -1
  53. package/dist/source.d.ts +6 -6
  54. package/dist/source.d.ts.map +1 -1
  55. package/dist/source.js +35 -26
  56. package/dist/source.js.map +1 -1
  57. package/dist/table-types.d.ts.map +1 -1
  58. package/dist/{Table.d.ts → table.d.ts} +6 -6
  59. package/dist/table.d.ts.map +1 -0
  60. package/dist/{Table.js → table.js} +65 -35
  61. package/dist/table.js.map +1 -0
  62. package/dist/text-table.d.ts.map +1 -1
  63. package/dist/text-table.js.map +1 -1
  64. package/dist/use-gutter-palette.d.ts +3 -0
  65. package/dist/use-gutter-palette.d.ts.map +1 -0
  66. package/dist/{useGutterPalette.js → use-gutter-palette.js} +4 -4
  67. package/dist/use-gutter-palette.js.map +1 -0
  68. package/package.json +5 -5
  69. package/src/code-blocks.tsx +122 -106
  70. package/src/{CodeView.tsx → code-view.tsx} +19 -14
  71. package/src/command-palette.tsx +163 -0
  72. package/src/context-menu.tsx +157 -0
  73. package/src/decoration-layer.ts +11 -0
  74. package/src/document-bindings.ts +16 -0
  75. package/src/index.ts +24 -23
  76. package/src/markdown-blocks.ts +178 -138
  77. package/src/markdown-view.tsx +853 -0
  78. package/src/mermaid.ts +122 -70
  79. package/src/parsers.ts +141 -103
  80. package/src/row-document-renderable.ts +672 -0
  81. package/src/row-document.ts +4 -4
  82. package/src/source.ts +92 -72
  83. package/src/table-types.ts +4 -4
  84. package/src/table.tsx +346 -0
  85. package/src/text-table.ts +4 -4
  86. package/src/use-gutter-palette.ts +15 -0
  87. package/dist/CodeView.d.ts.map +0 -1
  88. package/dist/CodeView.js.map +0 -1
  89. package/dist/CommandPalette.d.ts.map +0 -1
  90. package/dist/CommandPalette.js.map +0 -1
  91. package/dist/ContextMenu.d.ts.map +0 -1
  92. package/dist/ContextMenu.js.map +0 -1
  93. package/dist/DecorationLayer.d.ts.map +0 -1
  94. package/dist/DecorationLayer.js +0 -2
  95. package/dist/DecorationLayer.js.map +0 -1
  96. package/dist/DocumentBindings.d.ts.map +0 -1
  97. package/dist/DocumentBindings.js +0 -2
  98. package/dist/DocumentBindings.js.map +0 -1
  99. package/dist/MarkdownView.d.ts.map +0 -1
  100. package/dist/MarkdownView.js +0 -360
  101. package/dist/MarkdownView.js.map +0 -1
  102. package/dist/RowDocumentRenderable.d.ts.map +0 -1
  103. package/dist/RowDocumentRenderable.js.map +0 -1
  104. package/dist/Table.d.ts.map +0 -1
  105. package/dist/Table.js.map +0 -1
  106. package/dist/useGutterPalette.d.ts +0 -3
  107. package/dist/useGutterPalette.d.ts.map +0 -1
  108. package/dist/useGutterPalette.js.map +0 -1
  109. package/src/CommandPalette.tsx +0 -147
  110. package/src/ContextMenu.tsx +0 -132
  111. package/src/DecorationLayer.ts +0 -11
  112. package/src/DocumentBindings.ts +0 -16
  113. package/src/MarkdownView.tsx +0 -738
  114. package/src/RowDocumentRenderable.ts +0 -593
  115. package/src/Table.tsx +0 -300
  116. package/src/useGutterPalette.ts +0 -15
package/src/mermaid.ts CHANGED
@@ -1,136 +1,188 @@
1
- import { renderMermaidASCII } from "beautiful-mermaid"
2
- import { parseColor, StyledText, type TextChunk } from "@opentui/core"
3
-
4
- type BeautifulMermaidAsciiTheme = {
5
- fg?: string
6
- border?: string
7
- line?: string
8
- arrow?: string
9
- accent?: string
10
- bg?: string
11
- corner?: string
12
- junction?: string
1
+ import { parseMermaid, renderMermaidASCII } from "beautiful-mermaid";
2
+ import { parseColor, StyledText } from "@opentui/core";
3
+ import type { TextChunk } from "@opentui/core";
4
+
5
+ interface BeautifulMermaidAsciiTheme {
6
+ fg?: string;
7
+ border?: string;
8
+ line?: string;
9
+ arrow?: string;
10
+ accent?: string;
11
+ bg?: string;
12
+ corner?: string;
13
+ junction?: string;
13
14
  }
14
15
 
15
- export type MermaidRenderMode = "plain" | "ansi"
16
+ export type MermaidRenderMode = "plain" | "ansi";
16
17
 
17
18
  export type MermaidRenderResult =
18
19
  | { ok: true; text: string; content: StyledText }
19
- | { ok: false; reason: "empty" | "render-error"; message: string }
20
+ | { ok: false; reason: "complexity-limit" | "empty" | "render-error"; message: string };
20
21
 
21
22
  export interface MermaidRenderOptions {
22
- mode?: MermaidRenderMode
23
- theme?: BeautifulMermaidAsciiTheme
23
+ mode?: MermaidRenderMode;
24
+ theme?: BeautifulMermaidAsciiTheme;
24
25
  }
25
26
 
26
- const SGR_SEQUENCE = new RegExp(String.raw`\u001B\[([0-9;]*)m`, "g")
27
+ // beautiful-mermaid's flowchart renderer uses unbounded synchronous A* pathfinding.
28
+ // Dense graphs can therefore block the UI thread and exhaust the process heap when
29
+ // an edge cannot be routed. Keep synchronous work within a conservative budget;
30
+ // MarkdownView will visibly fall back to the original Mermaid source instead.
31
+ const MAX_SOURCE_LENGTH = 20_000;
32
+ const MAX_SOURCE_LINES = 300;
33
+ const MAX_FLOWCHART_EDGES = 32;
34
+
35
+ // oxlint-disable-next-line no-control-regex -- ANSI SGR sequences start with the ESC control character
36
+ const SGR_SEQUENCE = /\u001B\[(?<params>[0-9;]*)m/gu;
27
37
 
28
38
  /**
29
39
  * Marked may include extra info-string content after the language. Treat only
30
40
  * the first word as the fence language, matching common Markdown behavior.
31
41
  */
32
- export function isMermaidFence(lang?: string): boolean {
33
- return (lang ?? "").trim().split(/\s+/)[0]?.toLowerCase() === "mermaid"
34
- }
42
+ export const isMermaidFence = function isMermaidFence(lang?: string): boolean {
43
+ return (lang ?? "").trim().split(/\s+/u)[0]?.toLowerCase() === "mermaid";
44
+ };
45
+
46
+ const exceedsSynchronousRenderBudget = function exceedsSynchronousRenderBudget(
47
+ source: string,
48
+ ): boolean {
49
+ if (source.length > MAX_SOURCE_LENGTH || source.split("\n").length > MAX_SOURCE_LINES) {
50
+ return true;
51
+ }
35
52
 
36
- function appendStyledChunk(chunks: TextChunk[], text: string, fg?: string) {
37
- if (text.length === 0) return
53
+ const firstLine = source.trimStart().split(/[;\n]/u)[0]?.trim().toLowerCase() ?? "";
54
+ const isFlowchart = /^(?:flowchart|graph|statediagram(?:-v2)?)\b/u.test(firstLine);
55
+
56
+ return isFlowchart && parseMermaid(source).edges.length > MAX_FLOWCHART_EDGES;
57
+ };
58
+
59
+ const appendStyledChunk = function appendStyledChunk(
60
+ chunks: TextChunk[],
61
+ text: string,
62
+ fg?: string,
63
+ ) {
64
+ if (text.length === 0) {
65
+ return;
66
+ }
38
67
 
39
68
  chunks.push({
40
69
  __isChunk: true,
41
70
  text,
42
- ...(fg ? { fg: parseColor(fg) } : {}),
43
- })
44
- }
71
+ ...(fg !== undefined && fg !== "" ? { fg: parseColor(fg) } : {}),
72
+ });
73
+ };
45
74
 
46
- function sgrParams(rawParams: string): number[] {
47
- if (rawParams === "") return [0]
48
- return rawParams.split(";").map((param) => (param === "" ? 0 : Number(param)))
49
- }
75
+ const sgrParams = function sgrParams(rawParams: string): number[] {
76
+ if (rawParams === "") {
77
+ return [0];
78
+ }
79
+ return rawParams.split(";").map((param) => (param === "" ? 0 : Number(param)));
80
+ };
50
81
 
51
- function updateAnsiForeground(params: number[], currentFg: string | undefined): string | undefined {
52
- let fg = currentFg
82
+ const updateAnsiForeground = function updateAnsiForeground(
83
+ params: number[],
84
+ currentFg: string | undefined,
85
+ ): string | undefined {
86
+ let fg = currentFg;
53
87
 
54
- for (let i = 0; i < params.length; i++) {
55
- const param = params[i]
88
+ for (let i = 0; i < params.length; i += 1) {
89
+ const param = params[i];
56
90
 
57
91
  if (param === 0 || param === 39) {
58
- fg = undefined
59
- continue
92
+ fg = undefined;
93
+ continue;
60
94
  }
61
95
 
62
96
  if (param === 38 && params[i + 1] === 2) {
63
- const r = params[i + 2]
64
- const g = params[i + 3]
65
- const b = params[i + 4]
66
-
67
- if (r != null && g != null && b != null) {
97
+ const r = params[i + 2];
98
+ const g = params[i + 3];
99
+ const b = params[i + 4];
100
+
101
+ if (
102
+ r !== null &&
103
+ r !== undefined &&
104
+ g !== null &&
105
+ g !== undefined &&
106
+ b !== null &&
107
+ b !== undefined
108
+ ) {
68
109
  fg = `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b
69
110
  .toString(16)
70
- .padStart(2, "0")}`
71
- i += 4
111
+ .padStart(2, "0")}`;
112
+ i += 4;
72
113
  }
73
114
  }
74
115
  }
75
116
 
76
- return fg
77
- }
117
+ return fg;
118
+ };
78
119
 
79
120
  /** Convert beautiful-mermaid truecolor ANSI output into OpenTUI StyledText. */
80
- export function ansiToStyledText(input: string): { text: string; content: StyledText } {
81
- const chunks: TextChunk[] = []
82
- let plainText = ""
83
- let cursor = 0
84
- let currentFg: string | undefined
121
+ export const ansiToStyledText = function ansiToStyledText(input: string): {
122
+ text: string;
123
+ content: StyledText;
124
+ } {
125
+ const chunks: TextChunk[] = [];
126
+ let plainText = "";
127
+ let cursor = 0;
128
+ let currentFg: string | undefined;
85
129
 
86
130
  for (const match of input.matchAll(SGR_SEQUENCE)) {
87
- const index = match.index ?? 0
88
- const literal = input.slice(cursor, index)
89
- appendStyledChunk(chunks, literal, currentFg)
90
- plainText += literal
131
+ const index = match.index ?? 0;
132
+ const literal = input.slice(cursor, index);
133
+ appendStyledChunk(chunks, literal, currentFg);
134
+ plainText += literal;
91
135
 
92
- currentFg = updateAnsiForeground(sgrParams(match[1] ?? ""), currentFg)
93
- cursor = index + match[0].length
136
+ currentFg = updateAnsiForeground(sgrParams(match.groups?.params ?? ""), currentFg);
137
+ cursor = index + match[0].length;
94
138
  }
95
139
 
96
- const tail = input.slice(cursor)
97
- appendStyledChunk(chunks, tail, currentFg)
98
- plainText += tail
140
+ const tail = input.slice(cursor);
141
+ appendStyledChunk(chunks, tail, currentFg);
142
+ plainText += tail;
99
143
 
100
- return { text: plainText, content: new StyledText(chunks) }
101
- }
144
+ return { content: new StyledText(chunks), text: plainText };
145
+ };
102
146
 
103
147
  /**
104
148
  * Render Mermaid source for terminal display. This wrapper keeps third-party
105
149
  * parser/layout failures out of React render paths so MarkdownView can fall
106
150
  * back to the original source block.
107
151
  */
108
- export function renderMermaidForTerminal(
152
+ export const renderMermaidForTerminal = function renderMermaidForTerminal(
109
153
  source: string,
110
154
  options: MermaidRenderOptions = {},
111
155
  ): MermaidRenderResult {
112
156
  if (source.trim().length === 0) {
113
- return { ok: false, reason: "empty", message: "Mermaid block is empty" }
157
+ return { message: "Mermaid block is empty", ok: false, reason: "empty" };
114
158
  }
115
159
 
116
160
  try {
117
- const mode = options.mode ?? "plain"
161
+ if (exceedsSynchronousRenderBudget(source)) {
162
+ return {
163
+ message: "Mermaid diagram exceeds the synchronous rendering complexity limit",
164
+ ok: false,
165
+ reason: "complexity-limit",
166
+ };
167
+ }
168
+
169
+ const mode = options.mode ?? "plain";
118
170
  const rendered = renderMermaidASCII(source, {
119
171
  colorMode: mode === "ansi" ? "truecolor" : "none",
120
172
  theme: options.theme,
121
- }).trimEnd()
122
- const { text, content } = ansiToStyledText(rendered)
173
+ }).trimEnd();
174
+ const { text, content } = ansiToStyledText(rendered);
123
175
 
124
176
  if (text.trim().length === 0) {
125
- return { ok: false, reason: "empty", message: "Mermaid renderer returned no output" }
177
+ return { message: "Mermaid renderer returned no output", ok: false, reason: "empty" };
126
178
  }
127
179
 
128
- return { ok: true, text, content }
180
+ return { content, ok: true, text };
129
181
  } catch (error) {
130
182
  return {
183
+ message: error instanceof Error ? error.message : String(error),
131
184
  ok: false,
132
185
  reason: "render-error",
133
- message: error instanceof Error ? error.message : String(error),
134
- }
186
+ };
135
187
  }
136
- }
188
+ };
package/src/parsers.ts CHANGED
@@ -1,149 +1,187 @@
1
- import type { ColumnDef, TableRow } from "./table-types.js"
1
+ import type { ColumnDef, TableRow } from "./table-types.js";
2
2
 
3
3
  export interface ParsedTable {
4
- columns: ColumnDef[]
5
- rows: TableRow[]
6
- format: Format
4
+ columns: ColumnDef[];
5
+ rows: TableRow[];
6
+ format: Format;
7
7
  }
8
8
 
9
- export function parseCSV(input: string): { columns: ColumnDef[]; rows: TableRow[] } {
10
- const lines = splitLines(input)
11
- if (lines.length === 0) return { columns: [], rows: [] }
12
- const columns = createColumnDefs(parseCSVLine(lines[0]))
13
- const rows = buildRows(columns, lines.slice(1).map(parseCSVLine))
14
- return { columns, rows }
15
- }
9
+ export const parseCSV = function parseCSV(input: string): {
10
+ columns: ColumnDef[];
11
+ rows: TableRow[];
12
+ } {
13
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): parser helpers are kept below the public entry points
14
+ const lines = splitLines(input);
15
+ if (lines.length === 0) {
16
+ return { columns: [], rows: [] };
17
+ }
18
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): parser helpers are kept below the public entry points
19
+ const columns = createColumnDefs(parseCSVLine(lines[0]));
20
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): parser helpers are kept below the public entry points
21
+ const rows = buildRows(columns, lines.slice(1).map(parseCSVLine));
22
+ return { columns, rows };
23
+ };
16
24
 
17
- function parseCSVLine(line: string): string[] {
18
- const fields: string[] = []
19
- let i = 0
25
+ const parseCSVLine = function parseCSVLine(line: string): string[] {
26
+ const fields: string[] = [];
27
+ let i = 0;
20
28
  while (i < line.length) {
21
29
  if (line[i] === '"') {
22
30
  // Quoted field
23
- i++
24
- let field = ""
31
+ i += 1;
32
+ let field = "";
25
33
  while (i < line.length) {
26
34
  if (line[i] === '"') {
27
35
  if (i + 1 < line.length && line[i + 1] === '"') {
28
- field += '"'
29
- i += 2
36
+ field += '"';
37
+ i += 2;
30
38
  } else {
31
- i++ // closing quote
32
- break
39
+ i += 1;
40
+ break;
33
41
  }
34
42
  } else {
35
- field += line[i]
36
- i++
43
+ field += line[i];
44
+ i += 1;
37
45
  }
38
46
  }
39
- fields.push(field)
40
- if (i < line.length && line[i] === ",") i++ // skip comma
47
+ fields.push(field);
48
+ // Skip the comma after a quoted field.
49
+ if (i < line.length && line[i] === ",") {
50
+ i += 1;
51
+ }
41
52
  } else {
42
- const nextComma = line.indexOf(",", i)
53
+ const nextComma = line.indexOf(",", i);
43
54
  if (nextComma === -1) {
44
- fields.push(line.slice(i))
45
- break
55
+ fields.push(line.slice(i));
56
+ break;
46
57
  } else {
47
- fields.push(line.slice(i, nextComma))
48
- i = nextComma + 1
58
+ fields.push(line.slice(i, nextComma));
59
+ i = nextComma + 1;
49
60
  }
50
61
  }
51
62
  }
52
- return fields
53
- }
63
+ return fields;
64
+ };
54
65
 
55
- export function parseTSV(input: string): { columns: ColumnDef[]; rows: TableRow[] } {
56
- const lines = splitLines(input)
57
- if (lines.length === 0) return { columns: [], rows: [] }
58
- const columns = createColumnDefs(lines[0].split("\t"))
66
+ export const parseTSV = function parseTSV(input: string): {
67
+ columns: ColumnDef[];
68
+ rows: TableRow[];
69
+ } {
70
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): parser helpers are kept below the public entry points
71
+ const lines = splitLines(input);
72
+ if (lines.length === 0) {
73
+ return { columns: [], rows: [] };
74
+ }
75
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): parser helpers are kept below the public entry points
76
+ const columns = createColumnDefs(lines[0].split("\t"));
77
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): parser helpers are kept below the public entry points
59
78
  const rows = buildRows(
60
79
  columns,
61
80
  lines.slice(1).map((line) => line.split("\t")),
62
- )
63
- return { columns, rows }
64
- }
81
+ );
82
+ return { columns, rows };
83
+ };
65
84
 
66
- export function parseJSON(input: string): { columns: ColumnDef[]; rows: TableRow[] } {
67
- const data = JSON.parse(input)
68
- if (!Array.isArray(data) || data.length === 0) return { columns: [], rows: [] }
69
- const keys = Array.from(
70
- new Set(data.flatMap((item: Record<string, unknown>) => Object.keys(item))),
71
- )
72
- const columns: ColumnDef[] = keys.map((key) => ({ key, header: key }))
85
+ export const parseJSON = function parseJSON(input: string): {
86
+ columns: ColumnDef[];
87
+ rows: TableRow[];
88
+ } {
89
+ const data: unknown = JSON.parse(input);
90
+ if (!Array.isArray(data) || data.length === 0) {
91
+ return { columns: [], rows: [] };
92
+ }
93
+ const keys = [...new Set(data.flatMap((item: Record<string, unknown>) => Object.keys(item)))];
94
+ const columns: ColumnDef[] = keys.map((key) => ({ header: key, key }));
73
95
  const rows = data.map((item: Record<string, unknown>) => {
74
- const row: TableRow = {}
96
+ const row: TableRow = {};
75
97
  for (const column of columns) {
76
- row[column.key] = item[column.key] ?? ""
98
+ row[column.key] = item[column.key] ?? "";
77
99
  }
78
- return row
79
- })
80
- return { columns, rows }
81
- }
100
+ return row;
101
+ });
102
+ return { columns, rows };
103
+ };
82
104
 
83
- export type Format = "csv" | "tsv" | "json" | "unknown"
105
+ export type Format = "csv" | "tsv" | "json" | "unknown";
84
106
 
85
- export function detectFormat(input: string): Format {
86
- const trimmed = input.trimStart()
107
+ export const detectFormat = function detectFormat(input: string): Format {
108
+ const trimmed = input.trimStart();
87
109
  if (trimmed.startsWith("[")) {
88
110
  try {
89
- const parsed = JSON.parse(trimmed)
90
- if (Array.isArray(parsed)) return "json"
91
- } catch {}
111
+ const parsed: unknown = JSON.parse(trimmed);
112
+ if (Array.isArray(parsed)) {
113
+ return "json";
114
+ }
115
+ } catch {
116
+ // Not valid JSON — fall through to the delimiter sniffing below.
117
+ }
92
118
  }
93
- const firstLine = input.split("\n")[0] ?? ""
94
- if (firstLine.includes("\t")) return "tsv"
95
- if (firstLine.includes(",")) return "csv"
96
- return "unknown"
97
- }
119
+ const firstLine = input.split("\n")[0] ?? "";
120
+ if (firstLine.includes("\t")) {
121
+ return "tsv";
122
+ }
123
+ if (firstLine.includes(",")) {
124
+ return "csv";
125
+ }
126
+ return "unknown";
127
+ };
98
128
 
99
- export function parseAuto(input: string): ParsedTable {
100
- const format = detectFormat(input)
101
- let columns: ColumnDef[]
102
- let rows: TableRow[]
129
+ export const parseAuto = function parseAuto(input: string): ParsedTable {
130
+ const format = detectFormat(input);
131
+ let columns: ColumnDef[];
132
+ let rows: TableRow[];
103
133
  switch (format) {
104
- case "csv":
105
- ;({ columns, rows } = parseCSV(input))
106
- break
107
- case "tsv":
108
- ;({ columns, rows } = parseTSV(input))
109
- break
110
- case "json":
111
- ;({ columns, rows } = parseJSON(input))
112
- break
113
- default:
134
+ case "csv": {
135
+ ({ columns, rows } = parseCSV(input));
136
+ break;
137
+ }
138
+ case "tsv": {
139
+ ({ columns, rows } = parseTSV(input));
140
+ break;
141
+ }
142
+ case "json": {
143
+ ({ columns, rows } = parseJSON(input));
144
+ break;
145
+ }
146
+ case "unknown": {
114
147
  // Fall back to CSV
115
- ;({ columns, rows } = parseCSV(input))
116
- break
148
+ ({ columns, rows } = parseCSV(input));
149
+ break;
150
+ }
151
+ default: {
152
+ ({ columns, rows } = parseCSV(input));
153
+ break;
154
+ }
117
155
  }
118
- return { columns, rows, format }
119
- }
156
+ return { columns, format, rows };
157
+ };
120
158
 
121
- function splitLines(input: string): string[] {
122
- return input.split("\n").filter((line) => line.trim().length > 0)
123
- }
159
+ const splitLines = function splitLines(input: string): string[] {
160
+ return input.split("\n").filter((line) => line.trim().length > 0);
161
+ };
124
162
 
125
- function createColumnDefs(rawHeaders: string[]): ColumnDef[] {
126
- const seen = new Map<string, number>()
163
+ const createColumnDefs = function createColumnDefs(rawHeaders: string[]): ColumnDef[] {
164
+ const seen = new Map<string, number>();
127
165
  return rawHeaders.map((header, index) => {
128
- const trimmed = header.trim()
129
- const fallback = `column_${index + 1}`
130
- const base = trimmed === "" ? fallback : trimmed
131
- const count = seen.get(base) ?? 0
132
- seen.set(base, count + 1)
133
- const key = count === 0 ? base : `${base}_${count + 1}`
166
+ const trimmed = header.trim();
167
+ const fallback = `column_${index + 1}`;
168
+ const base = trimmed === "" ? fallback : trimmed;
169
+ const count = seen.get(base) ?? 0;
170
+ seen.set(base, count + 1);
171
+ const key = count === 0 ? base : `${base}_${count + 1}`;
134
172
  return {
135
- key,
136
173
  header: trimmed || undefined,
137
- }
138
- })
139
- }
174
+ key,
175
+ };
176
+ });
177
+ };
140
178
 
141
- function buildRows(columns: ColumnDef[], rawRows: string[][]): TableRow[] {
179
+ const buildRows = function buildRows(columns: ColumnDef[], rawRows: string[][]): TableRow[] {
142
180
  return rawRows.map((row) => {
143
- const record: TableRow = {}
144
- columns.forEach((column, index) => {
145
- record[column.key] = row[index] ?? ""
146
- })
147
- return record
148
- })
149
- }
181
+ const record: TableRow = {};
182
+ for (const [index, column] of columns.entries()) {
183
+ record[column.key] = row[index] ?? "";
184
+ }
185
+ return record;
186
+ });
187
+ };