juxscript 1.1.239 → 1.1.243

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 (297) hide show
  1. package/index.js +7 -137
  2. package/lib/components/dataframe.ts +0 -569
  3. package/lib/components/tag.ts +68 -0
  4. package/lib/styles/shadcn.css +20 -7
  5. package/lib/utils/idgen.ts +6 -0
  6. package/package.json +5 -6
  7. package/index.d.ts +0 -239
  8. package/index.d.ts.map +0 -1
  9. package/lib/components/alert.d.ts +0 -36
  10. package/lib/components/alert.d.ts.map +0 -1
  11. package/lib/components/alert.js +0 -172
  12. package/lib/components/alert.ts +0 -219
  13. package/lib/components/app.d.ts +0 -89
  14. package/lib/components/app.d.ts.map +0 -1
  15. package/lib/components/app.js +0 -175
  16. package/lib/components/app.ts +0 -247
  17. package/lib/components/badge.d.ts +0 -26
  18. package/lib/components/badge.d.ts.map +0 -1
  19. package/lib/components/badge.js +0 -91
  20. package/lib/components/badge.ts +0 -118
  21. package/lib/components/base/Animations.d.ts +0 -36
  22. package/lib/components/base/Animations.d.ts.map +0 -1
  23. package/lib/components/base/Animations.js +0 -70
  24. package/lib/components/base/Animations.ts +0 -112
  25. package/lib/components/base/BaseComponent.d.ts +0 -294
  26. package/lib/components/base/BaseComponent.d.ts.map +0 -1
  27. package/lib/components/base/BaseComponent.js +0 -735
  28. package/lib/components/base/BaseComponent.ts +0 -884
  29. package/lib/components/base/FormInput.d.ts +0 -77
  30. package/lib/components/base/FormInput.d.ts.map +0 -1
  31. package/lib/components/base/FormInput.js +0 -171
  32. package/lib/components/base/FormInput.ts +0 -237
  33. package/lib/components/blueprint.d.ts +0 -40
  34. package/lib/components/blueprint.d.ts.map +0 -1
  35. package/lib/components/blueprint.js +0 -327
  36. package/lib/components/button.d.ts +0 -70
  37. package/lib/components/button.d.ts.map +0 -1
  38. package/lib/components/button.js +0 -177
  39. package/lib/components/button.ts +0 -237
  40. package/lib/components/card.d.ts +0 -35
  41. package/lib/components/card.d.ts.map +0 -1
  42. package/lib/components/card.js +0 -130
  43. package/lib/components/card.ts +0 -177
  44. package/lib/components/chart.d.ts +0 -49
  45. package/lib/components/chart.d.ts.map +0 -1
  46. package/lib/components/chart.js +0 -205
  47. package/lib/components/chart.ts +0 -254
  48. package/lib/components/checkbox.d.ts +0 -33
  49. package/lib/components/checkbox.d.ts.map +0 -1
  50. package/lib/components/checkbox.js +0 -202
  51. package/lib/components/checkbox.ts +0 -260
  52. package/lib/components/code.d.ts +0 -52
  53. package/lib/components/code.d.ts.map +0 -1
  54. package/lib/components/code.js +0 -201
  55. package/lib/components/code.ts +0 -260
  56. package/lib/components/container.d.ts +0 -60
  57. package/lib/components/container.d.ts.map +0 -1
  58. package/lib/components/container.js +0 -195
  59. package/lib/components/container.ts +0 -259
  60. package/lib/components/data.d.ts +0 -36
  61. package/lib/components/data.d.ts.map +0 -1
  62. package/lib/components/data.js +0 -110
  63. package/lib/components/data.ts +0 -135
  64. package/lib/components/dataframe/DataFrameSource.d.ts +0 -118
  65. package/lib/components/dataframe/DataFrameSource.d.ts.map +0 -1
  66. package/lib/components/dataframe/DataFrameSource.js +0 -421
  67. package/lib/components/dataframe/DataFrameSource.ts +0 -532
  68. package/lib/components/dataframe/ImportSettingsModal.d.ts +0 -60
  69. package/lib/components/dataframe/ImportSettingsModal.d.ts.map +0 -1
  70. package/lib/components/dataframe/ImportSettingsModal.js +0 -442
  71. package/lib/components/dataframe/ImportSettingsModal.ts +0 -531
  72. package/lib/components/dataframe.d.ts +0 -110
  73. package/lib/components/dataframe.d.ts.map +0 -1
  74. package/lib/components/dataframe.js +0 -470
  75. package/lib/components/datepicker.d.ts +0 -40
  76. package/lib/components/datepicker.d.ts.map +0 -1
  77. package/lib/components/datepicker.js +0 -193
  78. package/lib/components/datepicker.ts +0 -251
  79. package/lib/components/dialog.d.ts +0 -39
  80. package/lib/components/dialog.d.ts.map +0 -1
  81. package/lib/components/dialog.js +0 -131
  82. package/lib/components/dialog.ts +0 -178
  83. package/lib/components/divider.d.ts +0 -31
  84. package/lib/components/divider.d.ts.map +0 -1
  85. package/lib/components/divider.js +0 -72
  86. package/lib/components/divider.ts +0 -104
  87. package/lib/components/dropdown-menu.d.ts +0 -42
  88. package/lib/components/dropdown-menu.d.ts.map +0 -1
  89. package/lib/components/dropdown-menu.js +0 -177
  90. package/lib/components/dropdown-menu.ts +0 -214
  91. package/lib/components/dropdown.d.ts +0 -41
  92. package/lib/components/dropdown.d.ts.map +0 -1
  93. package/lib/components/dropdown.js +0 -136
  94. package/lib/components/dropdown.ts +0 -188
  95. package/lib/components/element.d.ts +0 -51
  96. package/lib/components/element.d.ts.map +0 -1
  97. package/lib/components/element.js +0 -209
  98. package/lib/components/element.ts +0 -271
  99. package/lib/components/event-chain.d.ts +0 -9
  100. package/lib/components/event-chain.d.ts.map +0 -1
  101. package/lib/components/event-chain.js +0 -33
  102. package/lib/components/fileupload.d.ts +0 -98
  103. package/lib/components/fileupload.d.ts.map +0 -1
  104. package/lib/components/fileupload.js +0 -351
  105. package/lib/components/fileupload.ts +0 -449
  106. package/lib/components/grid.d.ts +0 -88
  107. package/lib/components/grid.d.ts.map +0 -1
  108. package/lib/components/grid.js +0 -208
  109. package/lib/components/grid.ts +0 -295
  110. package/lib/components/heading.d.ts +0 -25
  111. package/lib/components/heading.d.ts.map +0 -1
  112. package/lib/components/heading.js +0 -83
  113. package/lib/components/heading.ts +0 -113
  114. package/lib/components/helpers.d.ts +0 -9
  115. package/lib/components/helpers.d.ts.map +0 -1
  116. package/lib/components/helpers.js +0 -30
  117. package/lib/components/helpers.ts +0 -41
  118. package/lib/components/hero.d.ts +0 -60
  119. package/lib/components/hero.d.ts.map +0 -1
  120. package/lib/components/hero.js +0 -239
  121. package/lib/components/hero.ts +0 -302
  122. package/lib/components/history/StateHistory.d.ts +0 -91
  123. package/lib/components/history/StateHistory.d.ts.map +0 -1
  124. package/lib/components/history/StateHistory.js +0 -154
  125. package/lib/components/history/StateHistory.ts +0 -200
  126. package/lib/components/icon.d.ts +0 -36
  127. package/lib/components/icon.d.ts.map +0 -1
  128. package/lib/components/icon.js +0 -135
  129. package/lib/components/icon.ts +0 -182
  130. package/lib/components/icons.d.ts +0 -25
  131. package/lib/components/icons.d.ts.map +0 -1
  132. package/lib/components/icons.js +0 -440
  133. package/lib/components/icons.ts +0 -464
  134. package/lib/components/image.d.ts +0 -42
  135. package/lib/components/image.d.ts.map +0 -1
  136. package/lib/components/image.js +0 -204
  137. package/lib/components/image.ts +0 -260
  138. package/lib/components/include.d.ts +0 -86
  139. package/lib/components/include.d.ts.map +0 -1
  140. package/lib/components/include.js +0 -238
  141. package/lib/components/include.ts +0 -281
  142. package/lib/components/input.d.ts +0 -85
  143. package/lib/components/input.d.ts.map +0 -1
  144. package/lib/components/input.js +0 -362
  145. package/lib/components/input.ts +0 -473
  146. package/lib/components/layer.d.ts +0 -72
  147. package/lib/components/layer.d.ts.map +0 -1
  148. package/lib/components/layer.js +0 -219
  149. package/lib/components/layer.ts +0 -304
  150. package/lib/components/link.d.ts +0 -41
  151. package/lib/components/link.d.ts.map +0 -1
  152. package/lib/components/link.js +0 -216
  153. package/lib/components/link.ts +0 -268
  154. package/lib/components/list.d.ts +0 -83
  155. package/lib/components/list.d.ts.map +0 -1
  156. package/lib/components/list.js +0 -314
  157. package/lib/components/list.ts +0 -423
  158. package/lib/components/loading.d.ts +0 -25
  159. package/lib/components/loading.d.ts.map +0 -1
  160. package/lib/components/loading.js +0 -76
  161. package/lib/components/loading.ts +0 -104
  162. package/lib/components/menu.d.ts +0 -38
  163. package/lib/components/menu.d.ts.map +0 -1
  164. package/lib/components/menu.js +0 -205
  165. package/lib/components/menu.ts +0 -279
  166. package/lib/components/modal.d.ts +0 -97
  167. package/lib/components/modal.d.ts.map +0 -1
  168. package/lib/components/modal.js +0 -463
  169. package/lib/components/modal.ts +0 -576
  170. package/lib/components/nav.d.ts +0 -46
  171. package/lib/components/nav.d.ts.map +0 -1
  172. package/lib/components/nav.js +0 -193
  173. package/lib/components/nav.ts +0 -261
  174. package/lib/components/paragraph.d.ts +0 -30
  175. package/lib/components/paragraph.d.ts.map +0 -1
  176. package/lib/components/paragraph.js +0 -93
  177. package/lib/components/paragraph.ts +0 -123
  178. package/lib/components/pen.d.ts +0 -125
  179. package/lib/components/pen.d.ts.map +0 -1
  180. package/lib/components/pen.js +0 -443
  181. package/lib/components/pen.ts +0 -567
  182. package/lib/components/progress.d.ts +0 -40
  183. package/lib/components/progress.d.ts.map +0 -1
  184. package/lib/components/progress.js +0 -116
  185. package/lib/components/progress.ts +0 -163
  186. package/lib/components/radio.d.ts +0 -43
  187. package/lib/components/radio.d.ts.map +0 -1
  188. package/lib/components/radio.js +0 -226
  189. package/lib/components/radio.ts +0 -303
  190. package/lib/components/registry.d.ts +0 -34
  191. package/lib/components/registry.d.ts.map +0 -1
  192. package/lib/components/registry.js +0 -163
  193. package/lib/components/registry.ts +0 -193
  194. package/lib/components/req.d.ts +0 -155
  195. package/lib/components/req.d.ts.map +0 -1
  196. package/lib/components/req.js +0 -253
  197. package/lib/components/req.ts +0 -303
  198. package/lib/components/script.d.ts +0 -14
  199. package/lib/components/script.d.ts.map +0 -1
  200. package/lib/components/script.js +0 -33
  201. package/lib/components/script.ts +0 -41
  202. package/lib/components/select.d.ts +0 -42
  203. package/lib/components/select.d.ts.map +0 -1
  204. package/lib/components/select.js +0 -209
  205. package/lib/components/select.ts +0 -281
  206. package/lib/components/sidebar.d.ts +0 -59
  207. package/lib/components/sidebar.d.ts.map +0 -1
  208. package/lib/components/sidebar.js +0 -298
  209. package/lib/components/sidebar.ts +0 -395
  210. package/lib/components/stack/BaseStack.d.ts +0 -65
  211. package/lib/components/stack/BaseStack.d.ts.map +0 -1
  212. package/lib/components/stack/BaseStack.js +0 -274
  213. package/lib/components/stack/BaseStack.ts +0 -328
  214. package/lib/components/stack/HStack.d.ts +0 -18
  215. package/lib/components/stack/HStack.d.ts.map +0 -1
  216. package/lib/components/stack/HStack.js +0 -22
  217. package/lib/components/stack/HStack.ts +0 -25
  218. package/lib/components/stack/VStack.d.ts +0 -19
  219. package/lib/components/stack/VStack.d.ts.map +0 -1
  220. package/lib/components/stack/VStack.js +0 -23
  221. package/lib/components/stack/VStack.ts +0 -26
  222. package/lib/components/stack/ZStack.d.ts +0 -18
  223. package/lib/components/stack/ZStack.d.ts.map +0 -1
  224. package/lib/components/stack/ZStack.js +0 -22
  225. package/lib/components/stack/ZStack.ts +0 -25
  226. package/lib/components/style.d.ts +0 -14
  227. package/lib/components/style.d.ts.map +0 -1
  228. package/lib/components/style.js +0 -33
  229. package/lib/components/style.ts +0 -41
  230. package/lib/components/switch.d.ts +0 -34
  231. package/lib/components/switch.d.ts.map +0 -1
  232. package/lib/components/switch.js +0 -209
  233. package/lib/components/switch.ts +0 -272
  234. package/lib/components/table.d.ts +0 -137
  235. package/lib/components/table.d.ts.map +0 -1
  236. package/lib/components/table.js +0 -1019
  237. package/lib/components/table.ts +0 -1225
  238. package/lib/components/tabs.d.ts +0 -53
  239. package/lib/components/tabs.d.ts.map +0 -1
  240. package/lib/components/tabs.js +0 -275
  241. package/lib/components/tabs.ts +0 -349
  242. package/lib/components/theme-toggle.d.ts +0 -45
  243. package/lib/components/theme-toggle.d.ts.map +0 -1
  244. package/lib/components/theme-toggle.js +0 -218
  245. package/lib/components/theme-toggle.ts +0 -297
  246. package/lib/components/tooltip.d.ts +0 -31
  247. package/lib/components/tooltip.d.ts.map +0 -1
  248. package/lib/components/tooltip.js +0 -112
  249. package/lib/components/tooltip.ts +0 -148
  250. package/lib/components/watcher.d.ts +0 -195
  251. package/lib/components/watcher.d.ts.map +0 -1
  252. package/lib/components/watcher.js +0 -241
  253. package/lib/components/watcher.ts +0 -261
  254. package/lib/components/write.d.ts +0 -107
  255. package/lib/components/write.d.ts.map +0 -1
  256. package/lib/components/write.js +0 -222
  257. package/lib/components/write.ts +0 -272
  258. package/lib/data/DataPipeline.d.ts +0 -113
  259. package/lib/data/DataPipeline.d.ts.map +0 -1
  260. package/lib/data/DataPipeline.js +0 -359
  261. package/lib/data/DataPipeline.ts +0 -452
  262. package/lib/facades/dataframe.jux +0 -0
  263. package/lib/globals.d.ts +0 -21
  264. package/lib/reactivity/state.d.ts +0 -36
  265. package/lib/reactivity/state.d.ts.map +0 -1
  266. package/lib/reactivity/state.js +0 -67
  267. package/lib/reactivity/state.ts +0 -78
  268. package/lib/storage/DataFrame.d.ts +0 -284
  269. package/lib/storage/DataFrame.d.ts.map +0 -1
  270. package/lib/storage/DataFrame.js +0 -1022
  271. package/lib/storage/DataFrame.ts +0 -1195
  272. package/lib/storage/DataFrameSource.d.ts +0 -158
  273. package/lib/storage/DataFrameSource.d.ts.map +0 -1
  274. package/lib/storage/DataFrameSource.js +0 -409
  275. package/lib/storage/DataFrameSource.ts +0 -556
  276. package/lib/storage/FileStorage.d.ts +0 -53
  277. package/lib/storage/FileStorage.d.ts.map +0 -1
  278. package/lib/storage/FileStorage.js +0 -80
  279. package/lib/storage/FileStorage.ts +0 -95
  280. package/lib/storage/IndexedDBDriver.d.ts +0 -75
  281. package/lib/storage/IndexedDBDriver.d.ts.map +0 -1
  282. package/lib/storage/IndexedDBDriver.js +0 -177
  283. package/lib/storage/IndexedDBDriver.ts +0 -226
  284. package/lib/storage/TabularDriver.d.ts +0 -118
  285. package/lib/storage/TabularDriver.d.ts.map +0 -1
  286. package/lib/storage/TabularDriver.js +0 -731
  287. package/lib/storage/TabularDriver.ts +0 -874
  288. package/lib/utils/codeparser.d.ts +0 -29
  289. package/lib/utils/codeparser.d.ts.map +0 -1
  290. package/lib/utils/codeparser.js +0 -409
  291. package/lib/utils/fetch.d.ts +0 -176
  292. package/lib/utils/fetch.d.ts.map +0 -1
  293. package/lib/utils/fetch.js +0 -427
  294. package/lib/utils/formatId.d.ts +0 -16
  295. package/lib/utils/formatId.d.ts.map +0 -1
  296. package/lib/utils/formatId.js +0 -27
  297. package/lib/utils/path-resolver.js +0 -23
@@ -1,874 +0,0 @@
1
- import { DataFrame } from './DataFrame.js';
2
-
3
- export interface StoredTable {
4
- id: string;
5
- name: string;
6
- columns: string[];
7
- rows: any[][];
8
- rowCount: number;
9
- delimiter: string;
10
- timestamp: number;
11
- metadata?: Record<string, any>;
12
- }
13
-
14
- export interface ParseOptions {
15
- delimiter?: string;
16
- hasHeader?: boolean;
17
- chunkSize?: number;
18
- onProgress?: (parsed: number, total: number | null) => void;
19
- maxRows?: number;
20
- skipRows?: number;
21
- columns?: string[];
22
- sheet?: string | number;
23
- maxSheetSize?: number; // ✅ NEW: Max rows per sheet to prevent memory issues
24
- sheetChunkSize?: number; // ✅ NEW: Process Excel in chunks
25
- headerRow?: number; // ✅ NEW: Which row contains headers (default: 0)
26
- autoDetectDelimiter?: boolean; // ✅ NEW: Auto-detect delimiter from first lines
27
- }
28
-
29
- export class TabularDriver {
30
- private _dbName: string;
31
- private _storeName: string;
32
- private _db: IDBDatabase | null = null;
33
-
34
- constructor(dbName: string = 'jux-tabular', storeName: string = 'tables') {
35
- this._dbName = dbName;
36
- this._storeName = storeName;
37
- }
38
-
39
- async open(): Promise<IDBDatabase> {
40
- if (this._db) return this._db;
41
-
42
- return new Promise((resolve, reject) => {
43
- const request = indexedDB.open(this._dbName, 1);
44
-
45
- request.onupgradeneeded = (e) => {
46
- const db = (e.target as IDBOpenDBRequest).result;
47
- if (!db.objectStoreNames.contains(this._storeName)) {
48
- const store = db.createObjectStore(this._storeName, { keyPath: 'id' });
49
- store.createIndex('name', 'name', { unique: false });
50
- store.createIndex('timestamp', 'timestamp', { unique: false });
51
- }
52
- };
53
-
54
- request.onsuccess = (e) => {
55
- this._db = (e.target as IDBOpenDBRequest).result;
56
- resolve(this._db);
57
- };
58
-
59
- request.onerror = () => reject(request.error);
60
- });
61
- }
62
-
63
- /* ═══════════════════════════════════════════════════
64
- * CSV / TSV PARSING
65
- * ═══════════════════════════════════════════════════ */
66
-
67
- /**
68
- * ✅ NEW: Auto-detect delimiter from first N lines of CSV
69
- * Checks for: , | \t ;
70
- */
71
- private _detectDelimiter(text: string, sampleLines: number = 5): string {
72
- const lines = this._splitLines(text).slice(0, sampleLines).filter(l => l.trim());
73
- if (lines.length === 0) return ',';
74
-
75
- const delimiters = [',', '|', '\t', ';'];
76
- const scores: Record<string, number> = {};
77
-
78
- delimiters.forEach(delim => {
79
- const counts = lines.map(line => {
80
- // Count occurrences of delimiter NOT inside quotes
81
- let count = 0;
82
- let inQuotes = false;
83
- for (let i = 0; i < line.length; i++) {
84
- if (line[i] === '"') inQuotes = !inQuotes;
85
- if (!inQuotes && line[i] === delim) count++;
86
- }
87
- return count;
88
- });
89
-
90
- // Delimiter should have consistent count across lines
91
- const avg = counts.reduce((sum, c) => sum + c, 0) / counts.length;
92
- const variance = counts.reduce((sum, c) => sum + Math.pow(c - avg, 2), 0) / counts.length;
93
-
94
- // Score: high count, low variance
95
- scores[delim] = avg > 0 ? avg / (1 + variance) : 0;
96
- });
97
-
98
- // Return delimiter with highest score
99
- const best = Object.entries(scores).sort((a, b) => b[1] - a[1])[0];
100
- return best[0];
101
- }
102
-
103
- /**
104
- * ✅ NEW: Detect which row contains the header
105
- * Looks for first row with mostly string values
106
- */
107
- private _detectHeaderRow(text: string, delimiter: string, maxCheck: number = 10): number {
108
- const lines = this._splitLines(text).slice(0, maxCheck).filter(l => l.trim());
109
-
110
- for (let i = 0; i < lines.length; i++) {
111
- const values = this._parseLine(lines[i], delimiter);
112
-
113
- // Skip if mostly empty
114
- const nonEmpty = values.filter(v => v.trim()).length;
115
- if (nonEmpty < values.length * 0.5) continue;
116
-
117
- // Check if mostly non-numeric (likely headers)
118
- const nonNumeric = values.filter(v => {
119
- const trimmed = v.trim();
120
- return isNaN(Number(trimmed)) && trimmed !== '';
121
- }).length;
122
-
123
- if (nonNumeric >= values.length * 0.7) {
124
- return i;
125
- }
126
- }
127
-
128
- return 0; // Fallback to first row
129
- }
130
-
131
- /**
132
- * Parse a CSV/TSV string into a DataFrame
133
- */
134
- parseCSV(text: string, options: ParseOptions = {}): DataFrame {
135
- const {
136
- delimiter: userDelimiter,
137
- hasHeader = true,
138
- maxRows,
139
- skipRows: userSkipRows = 0,
140
- columns: selectCols,
141
- headerRow: userHeaderRow,
142
- autoDetectDelimiter = true
143
- } = options;
144
-
145
- // ✅ Auto-detect delimiter if not provided
146
- const delimiter = userDelimiter || (autoDetectDelimiter ? this._detectDelimiter(text) : ',');
147
-
148
- // ✅ Auto-detect header row if not provided
149
- const headerRow = userHeaderRow !== undefined ? userHeaderRow : (hasHeader ? this._detectHeaderRow(text, delimiter) : -1);
150
-
151
- const lines = this._splitLines(text);
152
- let headers: string[];
153
-
154
- // Skip rows before header
155
- let startIdx = userSkipRows;
156
-
157
- if (hasHeader && headerRow >= 0) {
158
- const headerLine = lines[headerRow + userSkipRows];
159
- if (headerLine) {
160
- headers = this._parseLine(headerLine, delimiter);
161
- startIdx = headerRow + userSkipRows + 1;
162
- } else {
163
- const firstLine = this._parseLine(lines[startIdx] || '', delimiter);
164
- headers = firstLine.map((_, i) => `col_${i}`);
165
- }
166
- } else {
167
- const firstLine = this._parseLine(lines[startIdx] || '', delimiter);
168
- headers = firstLine.map((_, i) => `col_${i}`);
169
- }
170
-
171
- const rows: Record<string, any>[] = [];
172
- const end = maxRows ? Math.min(startIdx + maxRows, lines.length) : lines.length;
173
-
174
- for (let i = startIdx; i < end; i++) {
175
- if (!lines[i].trim()) continue;
176
- const values = this._parseLine(lines[i], delimiter);
177
- const row: Record<string, any> = {};
178
-
179
- headers.forEach((h, j) => {
180
- row[h] = this._autoType(values[j]);
181
- });
182
-
183
- rows.push(row);
184
- }
185
-
186
- let df = new DataFrame(rows);
187
-
188
- if (selectCols) {
189
- df = df.select(...selectCols);
190
- }
191
-
192
- return df;
193
- }
194
-
195
- /**
196
- * Stream-parse a File into a DataFrame, with progress callback.
197
- * Auto-detects XLSX/XLS and routes accordingly.
198
- */
199
- async streamFile(file: File, options: ParseOptions = {}): Promise<DataFrame> {
200
- const ext = file.name.split('.').pop()?.toLowerCase();
201
-
202
- if (ext === 'xlsx' || ext === 'xls') {
203
- return this._parseXLSX(file, options);
204
- }
205
-
206
- const {
207
- delimiter = file.name.endsWith('.tsv') ? '\t' : ',',
208
- hasHeader = true,
209
- chunkSize = 64 * 1024,
210
- onProgress,
211
- maxRows,
212
- skipRows = 0,
213
- columns: selectCols
214
- } = options;
215
-
216
- const totalSize = file.size;
217
- let bytesRead = 0;
218
- let headers: string[] | null = null;
219
- let lineBuffer = '';
220
- let rowCount = 0;
221
- let skipped = 0;
222
- const rows: Record<string, any>[] = [];
223
-
224
- const reader = file.stream().getReader();
225
- const decoder = new TextDecoder();
226
-
227
- while (true) {
228
- const { done, value } = await reader.read();
229
- if (done) break;
230
-
231
- bytesRead += value.byteLength;
232
- lineBuffer += decoder.decode(value, { stream: !done });
233
-
234
- const lines = lineBuffer.split('\n');
235
- lineBuffer = lines.pop() || '';
236
-
237
- for (const line of lines) {
238
- if (!line.trim()) continue;
239
-
240
- if (!headers && hasHeader) {
241
- headers = this._parseLine(line, delimiter);
242
- continue;
243
- }
244
-
245
- if (!headers) {
246
- const vals = this._parseLine(line, delimiter);
247
- headers = vals.map((_, i) => `col_${i}`);
248
- }
249
-
250
- if (skipped < skipRows) {
251
- skipped++;
252
- continue;
253
- }
254
-
255
- if (maxRows && rowCount >= maxRows) break;
256
-
257
- const values = this._parseLine(line, delimiter);
258
- const row: Record<string, any> = {};
259
- headers.forEach((h, j) => {
260
- row[h] = this._autoType(values[j]);
261
- });
262
- rows.push(row);
263
- rowCount++;
264
- }
265
-
266
- if (onProgress) {
267
- onProgress(bytesRead, totalSize);
268
- }
269
-
270
- if (maxRows && rowCount >= maxRows) break;
271
- }
272
-
273
- // Handle remaining buffer
274
- if (lineBuffer.trim() && (!maxRows || rowCount < maxRows)) {
275
- if (!headers) {
276
- headers = this._parseLine(lineBuffer, delimiter).map((_, i) => `col_${i}`);
277
- } else {
278
- const values = this._parseLine(lineBuffer, delimiter);
279
- const row: Record<string, any> = {};
280
- headers.forEach((h, j) => {
281
- row[h] = this._autoType(values[j]);
282
- });
283
- rows.push(row);
284
- }
285
- }
286
-
287
- if (onProgress) onProgress(totalSize, totalSize);
288
-
289
- let df = new DataFrame(rows);
290
- if (selectCols) df = df.select(...selectCols);
291
-
292
- return df;
293
- }
294
-
295
- /* ═══════════════════════════════════════════════════
296
- * XLSX / XLS PARSING (ExcelJS)
297
- * ═══════════════════════════════════════════════════ */
298
-
299
- /**
300
- * Parse an XLSX/XLS file into a DataFrame using ExcelJS
301
- */
302
- private async _parseXLSX(file: File, options: ParseOptions = {}): Promise<DataFrame> {
303
- const { maxRows, skipRows = 0, columns: selectCols, sheet, onProgress, hasHeader = true } = options;
304
-
305
- let ExcelJS: any;
306
- try {
307
- ExcelJS = await import('exceljs');
308
- } catch {
309
- throw new Error(
310
- 'XLSX support requires the "exceljs" package. Install it with: npm install exceljs'
311
- );
312
- }
313
-
314
- if (onProgress) onProgress(0, file.size);
315
-
316
- const buffer = await file.arrayBuffer();
317
-
318
- if (onProgress) onProgress(file.size * 0.5, file.size);
319
-
320
- const workbook = new ExcelJS.Workbook();
321
- await workbook.xlsx.load(buffer);
322
-
323
- // Select sheet
324
- let worksheet: any;
325
- if (typeof sheet === 'number') {
326
- worksheet = workbook.worksheets[sheet] || workbook.worksheets[0];
327
- } else if (typeof sheet === 'string') {
328
- worksheet = workbook.getWorksheet(sheet) || workbook.worksheets[0];
329
- } else {
330
- worksheet = workbook.worksheets[0];
331
- }
332
-
333
- if (!worksheet) {
334
- const names = workbook.worksheets.map((ws: any) => ws.name).join(', ');
335
- throw new Error(`No worksheet found. Available: ${names}`);
336
- }
337
-
338
- if (onProgress) onProgress(file.size * 0.7, file.size);
339
-
340
- // Read all rows
341
- const allRows: Record<string, any>[] = [];
342
- let headers: string[] | null = null;
343
-
344
- worksheet.eachRow({ includeEmpty: false }, (row: any, rowNumber: number) => {
345
- const values = this._excelRowToArray(row, worksheet.columnCount);
346
-
347
- if (!headers && hasHeader) {
348
- headers = values.map((v: any, i: number) => {
349
- if (v === null || v === undefined || String(v).trim() === '') return `col_${i}`;
350
- return String(v).trim();
351
- });
352
- return;
353
- }
354
-
355
- if (!headers) {
356
- headers = values.map((_: any, i: number) => `col_${i}`);
357
- }
358
-
359
- const rowObj: Record<string, any> = {};
360
- headers.forEach((h, j) => {
361
- rowObj[h] = this._autoType(values[j] === null || values[j] === undefined ? '' : String(values[j]));
362
- });
363
- allRows.push(rowObj);
364
- });
365
-
366
- if (onProgress) onProgress(file.size * 0.9, file.size);
367
-
368
- let rows = allRows;
369
- if (skipRows > 0) rows = rows.slice(skipRows);
370
- if (maxRows !== undefined) rows = rows.slice(0, maxRows);
371
-
372
- if (onProgress) onProgress(file.size, file.size);
373
-
374
- let df = new DataFrame(rows);
375
- if (selectCols) df = df.select(...selectCols);
376
- return df;
377
- }
378
-
379
- /**
380
- * Get sheet names from an XLSX file
381
- */
382
- async getSheetNames(file: File): Promise<string[]> {
383
- let ExcelJS: any;
384
- try {
385
- ExcelJS = await import('exceljs');
386
- } catch {
387
- throw new Error('XLSX support requires the "exceljs" package. Install it with: npm install exceljs');
388
- }
389
-
390
- const buffer = await file.arrayBuffer();
391
- const workbook = new ExcelJS.Workbook();
392
- await workbook.xlsx.load(buffer);
393
- return workbook.worksheets.map((ws: any) => ws.name);
394
- }
395
-
396
- /* ═══════════════════════════════════════════════════
397
- * INDEXEDDB PERSISTENCE
398
- * ═══════════════════════════════════════════════════ */
399
-
400
- /**
401
- * Store a DataFrame to IndexedDB
402
- */
403
- async store(name: string, df: DataFrame, metadata?: Record<string, any>): Promise<string> {
404
- const db = await this.open();
405
-
406
- const table: StoredTable = {
407
- id: `${name}-${Date.now()}`,
408
- name,
409
- columns: df.columns,
410
- rows: df.toRows().map(row => df.columns.map(c => row[c])),
411
- rowCount: df.height,
412
- delimiter: ',',
413
- timestamp: Date.now(),
414
- metadata
415
- };
416
-
417
- return new Promise((resolve, reject) => {
418
- const tx = db.transaction(this._storeName, 'readwrite');
419
- const store = tx.objectStore(this._storeName);
420
- const request = store.put(table);
421
- request.onsuccess = () => resolve(table.id);
422
- request.onerror = () => reject(request.error);
423
- });
424
- }
425
-
426
- /**
427
- * Load a DataFrame from IndexedDB by ID
428
- */
429
- async load(id: string): Promise<DataFrame | null> {
430
- const db = await this.open();
431
-
432
- return new Promise((resolve, reject) => {
433
- const tx = db.transaction(this._storeName, 'readonly');
434
- const store = tx.objectStore(this._storeName);
435
- const request = store.get(id);
436
-
437
- request.onsuccess = () => {
438
- const table: StoredTable = request.result;
439
- if (!table) return resolve(null);
440
-
441
- const rows = table.rows.map(row => {
442
- const obj: Record<string, any> = {};
443
- table.columns.forEach((col, i) => { obj[col] = row[i]; });
444
- return obj;
445
- });
446
-
447
- resolve(new DataFrame(rows));
448
- };
449
- request.onerror = () => reject(request.error);
450
- });
451
- }
452
-
453
- /**
454
- * Load the most recent table by name
455
- */
456
- async loadByName(name: string): Promise<DataFrame | null> {
457
- const db = await this.open();
458
-
459
- return new Promise((resolve, reject) => {
460
- const tx = db.transaction(this._storeName, 'readonly');
461
- const store = tx.objectStore(this._storeName);
462
- const index = store.index('name');
463
- const request = index.getAll(name);
464
-
465
- request.onsuccess = () => {
466
- const tables: StoredTable[] = request.result || [];
467
- if (tables.length === 0) return resolve(null);
468
-
469
- tables.sort((a, b) => b.timestamp - a.timestamp);
470
- const table = tables[0];
471
-
472
- const rows = table.rows.map(row => {
473
- const obj: Record<string, any> = {};
474
- table.columns.forEach((col, i) => { obj[col] = row[i]; });
475
- return obj;
476
- });
477
-
478
- resolve(new DataFrame(rows));
479
- };
480
- request.onerror = () => reject(request.error);
481
- });
482
- }
483
-
484
- /**
485
- * List all stored tables (metadata only)
486
- */
487
- async list(): Promise<Array<{ id: string; name: string; columns: string[]; rowCount: number; timestamp: number }>> {
488
- const db = await this.open();
489
-
490
- return new Promise((resolve, reject) => {
491
- const tx = db.transaction(this._storeName, 'readonly');
492
- const store = tx.objectStore(this._storeName);
493
- const request = store.getAll();
494
-
495
- request.onsuccess = () => {
496
- resolve((request.result || []).map((t: StoredTable) => ({
497
- id: t.id,
498
- name: t.name,
499
- columns: t.columns,
500
- rowCount: t.rowCount,
501
- timestamp: t.timestamp
502
- })));
503
- };
504
- request.onerror = () => reject(request.error);
505
- });
506
- }
507
-
508
- /**
509
- * Delete a stored table
510
- */
511
- async delete(id: string): Promise<void> {
512
- const db = await this.open();
513
-
514
- return new Promise((resolve, reject) => {
515
- const tx = db.transaction(this._storeName, 'readwrite');
516
- const store = tx.objectStore(this._storeName);
517
- const request = store.delete(id);
518
- request.onsuccess = () => resolve();
519
- request.onerror = () => reject(request.error);
520
- });
521
- }
522
-
523
- async clear(): Promise<void> {
524
- const db = await this.open();
525
-
526
- return new Promise((resolve, reject) => {
527
- const tx = db.transaction(this._storeName, 'readwrite');
528
- const store = tx.objectStore(this._storeName);
529
- const request = store.clear();
530
- request.onsuccess = () => resolve();
531
- request.onerror = () => reject(request.error);
532
- });
533
- }
534
-
535
- /* ═══════════════════════════════════════════════════
536
- * STREAM FROM URL
537
- * ═══════════════════════════════════════════════════ */
538
-
539
- /**
540
- * Fetch and stream-parse a remote CSV/TSV file
541
- */
542
- async fetch(url: string, options: ParseOptions = {}): Promise<DataFrame> {
543
- const response = await globalThis.fetch(url);
544
- if (!response.ok) throw new Error(`Failed to fetch: ${response.status}`);
545
- if (!response.body) throw new Error('No response body');
546
-
547
- const contentLength = Number(response.headers.get('content-length')) || null;
548
- const ext = url.split('.').pop()?.toLowerCase();
549
- const delimiter = options.delimiter ?? (ext === 'tsv' ? '\t' : ',');
550
-
551
- const { hasHeader = true, chunkSize, onProgress, maxRows, skipRows = 0, columns: selectCols } = options;
552
-
553
- const reader = response.body.getReader();
554
- const decoder = new TextDecoder();
555
-
556
- let headers: string[] | null = null;
557
- let lineBuffer = '';
558
- let rowCount = 0;
559
- let skipped = 0;
560
- let bytesRead = 0;
561
- const rows: Record<string, any>[] = [];
562
-
563
- while (true) {
564
- const { done, value } = await reader.read();
565
- if (done) break;
566
-
567
- bytesRead += value.byteLength;
568
- lineBuffer += decoder.decode(value, { stream: true });
569
-
570
- const lines = lineBuffer.split('\n');
571
- lineBuffer = lines.pop() || '';
572
-
573
- for (const line of lines) {
574
- if (!line.trim()) continue;
575
-
576
- if (!headers && hasHeader) {
577
- headers = this._parseLine(line, delimiter);
578
- continue;
579
- }
580
-
581
- if (!headers) {
582
- const vals = this._parseLine(line, delimiter);
583
- headers = vals.map((_, i) => `col_${i}`);
584
- }
585
-
586
- if (skipped < skipRows) { skipped++; continue; }
587
- if (maxRows && rowCount >= maxRows) break;
588
-
589
- const values = this._parseLine(line, delimiter);
590
- const row: Record<string, any> = {};
591
- headers.forEach((h, j) => { row[h] = this._autoType(values[j]); });
592
- rows.push(row);
593
- rowCount++;
594
- }
595
-
596
- if (onProgress) onProgress(bytesRead, contentLength);
597
- if (maxRows && rowCount >= maxRows) break;
598
- }
599
-
600
- if (lineBuffer.trim() && (!maxRows || rowCount < maxRows)) {
601
- if (headers) {
602
- const values = this._parseLine(lineBuffer, delimiter);
603
- const row: Record<string, any> = {};
604
- headers.forEach((h, j) => { row[h] = this._autoType(values[j]); });
605
- rows.push(row);
606
- }
607
- }
608
-
609
- if (onProgress) onProgress(bytesRead, bytesRead);
610
-
611
- let df = new DataFrame(rows);
612
- if (selectCols) df = df.select(...selectCols);
613
- return df;
614
- }
615
-
616
- /**
617
- * Read raw cell values from first sheet of an Excel file.
618
- * Returns rows with their 0-based row indices.
619
- * Used by both the preview UI and the parser to ensure consistency.
620
- */
621
- async readRawExcelRows(file: File, maxRows: number = 15): Promise<{ sheetRow: number; values: any[] }[]> {
622
- let ExcelJS: any;
623
- try {
624
- ExcelJS = await import('exceljs');
625
- } catch {
626
- throw new Error('XLSX support requires the "exceljs" package.');
627
- }
628
-
629
- const buffer = await file.arrayBuffer();
630
- const workbook = new ExcelJS.Workbook();
631
- await workbook.xlsx.load(buffer);
632
-
633
- const worksheet = workbook.worksheets[0];
634
- if (!worksheet) return [];
635
-
636
- const colCount = worksheet.columnCount;
637
- const rows: { sheetRow: number; values: any[] }[] = [];
638
- let count = 0;
639
-
640
- // ExcelJS eachRow gives 1-based rowNumber; we expose 0-based to the UI
641
- // But we need to also show truly empty rows, so iterate by index
642
- const totalRows = Math.min(worksheet.rowCount, maxRows);
643
-
644
- for (let r = 1; r <= totalRows; r++) {
645
- const row = worksheet.getRow(r);
646
- const values = this._excelRowToArray(row, colCount);
647
- // sheetRow is 0-based (r-1) to match what we pass back to streamFileMultiSheet
648
- rows.push({ sheetRow: r - 1, values });
649
- count++;
650
- if (count >= maxRows) break;
651
- }
652
-
653
- console.log(`[readRawExcelRows] ${rows.length} rows, colCount=${colCount}`);
654
- rows.forEach(r => console.log(` sheetRow ${r.sheetRow}:`, r.values.slice(0, 5)));
655
-
656
- return rows;
657
- }
658
-
659
- /**
660
- * Stream Excel file with optional headerRow override.
661
- * headerRow is 0-based (same as sheetRow from readRawExcelRows).
662
- */
663
- async streamFileMultiSheet(file: File, options: ParseOptions = {}): Promise<Record<string, DataFrame>> {
664
- const { maxSheetSize = 100000, onProgress, headerRow = 0 } = options;
665
-
666
- let ExcelJS: any;
667
- try {
668
- ExcelJS = await import('exceljs');
669
- } catch {
670
- throw new Error('XLSX support requires the "exceljs" package. Install it with: npm install exceljs');
671
- }
672
-
673
- if (onProgress) onProgress(0, file.size);
674
-
675
- const buffer = await file.arrayBuffer();
676
-
677
- if (onProgress) onProgress(file.size * 0.3, file.size);
678
-
679
- const workbook = new ExcelJS.Workbook();
680
- await workbook.xlsx.load(buffer);
681
-
682
- const sheets: Record<string, DataFrame> = {};
683
- const totalSheets = workbook.worksheets.length;
684
- let processedSheets = 0;
685
-
686
- for (const worksheet of workbook.worksheets) {
687
- const sheetName = worksheet.name;
688
- const colCount = worksheet.columnCount;
689
- const rowCount = worksheet.rowCount;
690
-
691
- if (rowCount === 0 || colCount === 0) {
692
- processedSheets++;
693
- continue;
694
- }
695
-
696
- // headerRow is 0-based; ExcelJS rows are 1-based
697
- const headerExcelRow = headerRow + 1;
698
-
699
- console.log(`[TabularDriver] Sheet "${sheetName}": rowCount=${rowCount}, colCount=${colCount}`);
700
- console.log(`[TabularDriver] headerRow=${headerRow} (0-based), excelRow=${headerExcelRow} (1-based)`);
701
-
702
- if (headerExcelRow > rowCount) {
703
- console.warn(`[TabularDriver] headerRow ${headerRow} exceeds rowCount ${rowCount}`);
704
- processedSheets++;
705
- continue;
706
- }
707
-
708
- // Read header row
709
- const headerRowObj = worksheet.getRow(headerExcelRow);
710
- const headerValues = this._excelRowToArray(headerRowObj, colCount);
711
- console.log(`[TabularDriver] Raw header values at row ${headerRow}:`, headerValues);
712
-
713
- const headers: string[] = headerValues.map((h: any, i: number) => {
714
- if (h === null || h === undefined || String(h).trim() === '') {
715
- return `__EMPTY${i > 0 ? '_' + i : ''}`;
716
- }
717
- return String(h).trim();
718
- });
719
-
720
- const validHeaders = headers.filter(h => !h.startsWith('__EMPTY'));
721
- console.log(`[TabularDriver] Headers (${validHeaders.length} valid / ${headers.length} total):`, headers);
722
-
723
- if (validHeaders.length === 0) {
724
- console.warn(`[TabularDriver] No valid headers found at row ${headerRow} in sheet "${sheetName}"`);
725
- // Debug surrounding rows
726
- for (let debugR = Math.max(1, headerExcelRow - 2); debugR <= Math.min(rowCount, headerExcelRow + 2); debugR++) {
727
- const debugRow = worksheet.getRow(debugR);
728
- console.log(`[TabularDriver] row ${debugR - 1}:`, this._excelRowToArray(debugRow, colCount));
729
- }
730
- processedSheets++;
731
- continue;
732
- }
733
-
734
- // Build data rows: everything after the header row
735
- const rows: Record<string, any>[] = [];
736
- const maxDataRow = Math.min(rowCount, headerExcelRow + maxSheetSize);
737
-
738
- for (let r = headerExcelRow + 1; r <= maxDataRow; r++) {
739
- const row = worksheet.getRow(r);
740
- const rowData = this._excelRowToArray(row, colCount);
741
-
742
- // Skip completely empty rows
743
- const hasContent = rowData.some((cell: any) =>
744
- cell !== null && cell !== undefined && String(cell).trim() !== ''
745
- );
746
- if (!hasContent) continue;
747
-
748
- const rowObj: Record<string, any> = {};
749
- for (let j = 0; j < headers.length; j++) {
750
- rowObj[headers[j]] = rowData[j];
751
- }
752
- rows.push(rowObj);
753
- }
754
-
755
- console.log(`[TabularDriver] Built ${rows.length} data rows for sheet "${sheetName}"`);
756
- if (rows.length > 0) {
757
- console.log(`[TabularDriver] First row:`, rows[0]);
758
- }
759
-
760
- if (rows.length > 0) {
761
- sheets[sheetName] = new DataFrame(rows);
762
- }
763
-
764
- processedSheets++;
765
- if (onProgress) {
766
- const progress = 0.3 + (0.6 * (processedSheets / totalSheets));
767
- onProgress(file.size * progress, file.size);
768
- }
769
- }
770
-
771
- if (onProgress) onProgress(file.size, file.size);
772
-
773
- return sheets;
774
- }
775
-
776
- /**
777
- * Extract cell values from an ExcelJS row into a plain array.
778
- * ExcelJS row.values is 1-based (index 0 is undefined), so we normalize.
779
- */
780
- private _excelRowToArray(row: any, colCount: number): any[] {
781
- const values: any[] = [];
782
- for (let c = 1; c <= colCount; c++) {
783
- const cell = row.getCell(c);
784
- if (!cell || cell.value === null || cell.value === undefined) {
785
- values.push(null);
786
- } else if (cell.type === 8 /* FormulaType */ && cell.result !== undefined) {
787
- values.push(cell.result);
788
- } else if (typeof cell.value === 'object' && cell.value !== null) {
789
- // Handle rich text, hyperlinks, etc.
790
- if (cell.value.richText) {
791
- values.push(cell.value.richText.map((rt: any) => rt.text).join(''));
792
- } else if (cell.value.text) {
793
- values.push(cell.value.text);
794
- } else if (cell.value.hyperlink) {
795
- values.push(cell.value.text || cell.value.hyperlink);
796
- } else {
797
- values.push(String(cell.value));
798
- }
799
- } else {
800
- values.push(cell.value);
801
- }
802
- }
803
- return values;
804
- }
805
-
806
- /* ═══════════════════════════════════════════════════
807
- * INTERNAL PARSING HELPERS
808
- * ═══════════════════════════════════════════════════ */
809
-
810
- private _splitLines(text: string): string[] {
811
- return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
812
- }
813
-
814
- private _parseLine(line: string, delimiter: string): string[] {
815
- const result: string[] = [];
816
- let current = '';
817
- let inQuotes = false;
818
-
819
- for (let i = 0; i < line.length; i++) {
820
- const ch = line[i];
821
-
822
- if (inQuotes) {
823
- if (ch === '"') {
824
- if (i + 1 < line.length && line[i + 1] === '"') {
825
- current += '"';
826
- i++;
827
- } else {
828
- inQuotes = false;
829
- }
830
- } else {
831
- current += ch;
832
- }
833
- } else {
834
- if (ch === '"') {
835
- inQuotes = true;
836
- } else if (ch === delimiter) {
837
- result.push(current.trim());
838
- current = '';
839
- } else {
840
- current += ch;
841
- }
842
- }
843
- }
844
-
845
- result.push(current.trim());
846
- return result;
847
- }
848
-
849
- private _autoType(value: string | undefined): any {
850
- if (value === undefined || value === '' || value === null) return null;
851
-
852
- if (value === 'true') return true;
853
- if (value === 'false') return false;
854
-
855
- const num = Number(value);
856
- if (!isNaN(num) && value.trim() !== '') return num;
857
-
858
- return value;
859
- }
860
-
861
- close(): void {
862
- if (this._db) {
863
- this._db.close();
864
- this._db = null;
865
- }
866
- }
867
- }
868
-
869
- /**
870
- * Factory
871
- */
872
- export function tabularDriver(dbName?: string, storeName?: string): TabularDriver {
873
- return new TabularDriver(dbName, storeName);
874
- }