-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathxlsx-to-csv.ts
More file actions
69 lines (58 loc) · 1.76 KB
/
Copy pathxlsx-to-csv.ts
File metadata and controls
69 lines (58 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { existsSync } from 'node:fs';
import path from 'node:path';
type ContentFile = {
type?: string;
media_type?: string;
path?: string;
};
const XLSX_MEDIA_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
function findSpreadsheet(output: unknown): ContentFile | undefined {
if (!Array.isArray(output)) {
return undefined;
}
return output.find((block): block is ContentFile => {
if (!block || typeof block !== 'object') {
return false;
}
const file = block as ContentFile;
return (
file.type === 'file' &&
typeof file.path === 'string' &&
(file.path.endsWith('.xlsx') || file.media_type === XLSX_MEDIA_TYPE)
);
});
}
function spreadsheetPath(file: ContentFile): string {
if (!file.path) {
throw new Error('missing spreadsheet path');
}
if (path.isAbsolute(file.path)) {
return file.path;
}
return path.resolve(import.meta.dir, '..', '..', file.path);
}
export default function transform(output: unknown): string {
const file = findSpreadsheet(output);
if (!file) {
throw new Error('expected a .xlsx ContentFile output');
}
const absolutePath = spreadsheetPath(file);
if (!existsSync(absolutePath)) {
throw new Error(`spreadsheet not found: ${file.path}`);
}
// Example-only placeholder conversion. Replace this with a real XLSX parser
// such as SheetJS or your project's existing spreadsheet extractor.
return ['spreadsheet: revenue,total', 'Q1,42'].join('\n');
}
if (import.meta.main) {
const filePath = process.argv[2];
if (!filePath) {
throw new Error('missing file path');
}
const payload: ContentFile = {
type: 'file',
media_type: XLSX_MEDIA_TYPE,
path: filePath,
};
process.stdout.write(`${transform([payload])}\n`);
}