Repository navigation
Expand file tree
/
Copy pathexport-utils.ts
More file actions
545 lines (481 loc) · 19.3 KB
/
Copy pathexport-utils.ts
File metadata and controls
545 lines (481 loc) · 19.3 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import * as XLSX from 'xlsx';
import { isDomGeneratedFieldName } from '../scraper/dataset-model';
import { RecordIdentity } from '../scraper/record-identity';
import { FieldNamer } from '../scraper/field-namer';
import { isMeaningfulIdentifierAttribute, getMeaningfulAttributeLabel } from '../scraper/column-filter';
export const INTERNAL_SYSTEM_KEYS = new Set([
'_id',
'_index',
'_edited',
'_editedFields',
'_status',
'_error',
'_durationMs',
'_sourceUrl',
'id',
'cells',
'sourceUrl',
'urlItemId',
'extractedFields',
'originalRowData',
'originalMetadata'
]);
export const SYSTEM_KEYS = INTERNAL_SYSTEM_KEYS;
/**
* Deduplicates records using canonical product URLs, variant identifiers, and stable IDs before exporting.
* Normalizes tracking parameters while preserving distinct variants and genuine entity differences.
*/
export function deduplicateRecordsForExport(data: any[], isPageDetails: boolean = false, isRawMode?: boolean): any[] {
if (!data || data.length === 0) return [];
// In Raw Extraction mode: preserve all records without product-specific semantic deduplication
const isRaw = isRawMode ?? (data.length > 0 && Object.keys(data[0] || {}).some(k => (
k.startsWith('.') || k.startsWith('#') || k.includes('[attr:') || k.includes('[text]') || k.includes(' > ') || k.startsWith('raw_')
)));
if (isRaw) {
const seenRawIds = new Set<string>();
const cleanRows: any[] = [];
data.forEach((row, idx) => {
if (!row || typeof row !== 'object') return;
const id = row._id || row.id || `raw_row_${idx}`;
if (seenRawIds.has(id)) return;
seenRawIds.add(id);
cleanRows.push(row);
});
return cleanRows;
}
const seenKeys = new Set<string>();
const cleanRows: any[] = [];
for (const row of data) {
if (!row || typeof row !== 'object') continue;
let dedupKey = '';
// 1. Entity-level item URL (specific to the item, e.g. Product URL, Profile URL, Job URL)
const itemUrl = row['Product URL'] ||
row['Profile URL'] ||
row['Job URL'] ||
row['Article URL'] ||
row['Listing URL'] ||
row['Link URL'] ||
row.link ||
row.href;
// 2. Extract semantic title / product name to distinguish multiple variants sharing a page
const title = RecordIdentity.normalizeText(
row['Product Name'] || row['Title'] || row['Job Title'] || row['Full Name'] || row.title || row.name
);
// 3. Extract explicit row ID if present and not a random fallback
const rawId = row._id || row.id;
const hasStableId = rawId && typeof rawId === 'string' && !rawId.startsWith('rec_empty_') && !rawId.startsWith('rec_rnd_');
if (itemUrl) {
const cleanUrl = RecordIdentity.normalizeUrl(itemUrl);
if (cleanUrl) {
// Disambiguate different variants on the same product URL by cleanUrl + title
dedupKey = title
? `url_${RecordIdentity.hashString(cleanUrl)}_${RecordIdentity.hashString(title)}`
: `url_${RecordIdentity.hashString(cleanUrl)}`;
} else if (hasStableId) {
dedupKey = rawId;
} else {
dedupKey = RecordIdentity.generateRecordIdentity(row, isPageDetails ? 'generic' : 'ecommerce');
}
} else if (title) {
// Named item without distinct product URL
dedupKey = RecordIdentity.generateRecordIdentity(row, isPageDetails ? 'generic' : 'ecommerce');
} else if (hasStableId) {
// Raw mode or unnamed record container with distinct ID: preserve every row
dedupKey = rawId;
} else {
dedupKey = RecordIdentity.generateRecordIdentity(row, isPageDetails ? 'generic' : 'ecommerce');
}
if (seenKeys.has(dedupKey)) {
continue;
}
seenKeys.add(dedupKey);
cleanRows.push(row);
}
return cleanRows;
}
/**
* Resolves the clean export column schema.
* Prevents technical DOM selectors and internal system keys from leaking into exports.
* When explicit columns are provided, only genuine internal system keys are filtered.
*/
export function resolveExportColumns(data: any[], explicitColumnsOrMode?: string[] | string): string[] {
if (Array.isArray(explicitColumnsOrMode) && explicitColumnsOrMode.length > 0) {
// Only exclude internal system keys; never strip valid user fields starting with '_' (e.g. Flipkart classnames)
return explicitColumnsOrMode.filter(k => !INTERNAL_SYSTEM_KEYS.has(k));
}
if (!data || data.length === 0) return [];
const isRawMode = explicitColumnsOrMode === 'raw';
if (!isRawMode) {
const presentKeys = new Set<string>();
data.forEach(row => {
if (row && typeof row === 'object') {
Object.entries(row).forEach(([k, v]) => {
if (!INTERNAL_SYSTEM_KEYS.has(k)) {
if (v !== undefined && v !== null && String(v).trim() !== '') {
const matchedAttr = k.match(/\[attr:([^\]]+)\]/)?.[1] || (k.startsWith('data-') ? k : null);
if (matchedAttr && isMeaningfulIdentifierAttribute(matchedAttr)) {
const cleanLabel = getMeaningfulAttributeLabel(matchedAttr);
presentKeys.add(cleanLabel);
} else if (!isDomGeneratedFieldName(k)) {
presentKeys.add(k);
}
}
}
});
}
});
let standardOrder: string[] = [];
// Check entity type based on present keys
if (presentKeys.has('Job Title') || data.some(r => r && ('Job Title' in r))) {
standardOrder = [
'Job Title', 'Company', 'Location', 'Employment Type', 'Salary', 'Posted Date', 'Job URL', 'Company Logo', 'Description'
];
} else if (presentKeys.has('Full Name') || presentKeys.has('Headline') || presentKeys.has('Profile URL') || data.some(r => r && ('Full Name' in r || 'Headline' in r || 'Profile URL' in r))) {
standardOrder = [
'Full Name', 'Name', 'Headline', 'Job Title', 'Company', 'Location', 'Profile URL', 'About', 'Email', 'Phone', 'Image URL', 'Connections'
];
} else if (presentKeys.has('Business Name') || data.some(r => r && ('Business Name' in r))) {
standardOrder = [
'Business Name', 'Category', 'Address', 'Address / Location', 'Phone', 'Email', 'Website', 'Rating', 'Reviews', 'Listing URL', 'Logo URL'
];
} else if (presentKeys.has('Article Title') || data.some(r => r && ('Article Title' in r))) {
standardOrder = [
'Article Title', 'Author', 'Publication Date', 'Summary', 'Category / Tag', 'Article URL', 'Image URL'
];
} else if (presentKeys.has('Product Name') || presentKeys.has('ASIN') || presentKeys.has('Seller Name') || data.some(r => r && ('Product Name' in r || 'ASIN' in r || 'Seller Name' in r))) {
standardOrder = [
'Product Name', 'ASIN', 'Price', 'Selling Price', 'Original Price', 'Discount', 'Rating', 'Review Count', 'Reviews Count', 'Ratings Count',
'Seller Name', 'Brand', 'Availability', 'Image URL', 'Product URL', 'Description', 'Product Specifications', 'Feature Bullets', 'Breadcrumbs',
'Delivery Information', 'Sponsored', 'Category'
];
} else if (presentKeys.has('Title') || presentKeys.has('Description') || presentKeys.has('Price') || data.some(r => r && ('Title' in r || 'Description' in r || 'Price' in r))) {
standardOrder = [
'Title', 'Description', 'Price', 'Original Price', 'Discount', 'Rating', 'Review Count', 'Link URL', 'Image URL', 'Date', 'Category / Tag', 'Location', 'Email', 'Phone'
];
}
if (standardOrder.length > 0) {
const cols: string[] = [];
standardOrder.forEach(k => {
if (presentKeys.has(k)) {
cols.push(k);
presentKeys.delete(k);
}
});
// Append any remaining custom fields
presentKeys.forEach(k => cols.push(k));
return cols;
}
}
// Raw mode or Non-standard fallback: all keys except system keys
const keys: string[] = [];
const seen = new Set<string>();
data.forEach(row => {
if (row && typeof row === 'object') {
Object.keys(row).forEach(k => {
if (!INTERNAL_SYSTEM_KEYS.has(k) && !seen.has(k)) {
if (isRawMode || !isDomGeneratedFieldName(k)) {
seen.add(k);
keys.push(k);
}
}
});
}
});
if (isRawMode) {
const mapped = FieldNamer.createColumnMappings(keys, data, 'generic', '', 'raw');
return mapped.filter(c => !c.isFiltered && !c.isDuplicate).map(c => c.label);
}
return keys;
}
/**
* Looks up a value in a record by header, with fallback for normalized attribute names or selectors.
*/
export function getRowValue(row: any, colName: string): any {
if (!row || typeof row !== 'object') return '';
if (row[colName] !== undefined && row[colName] !== null) return row[colName];
const trimmed = colName.trim();
if (row[trimmed] !== undefined && row[trimmed] !== null) return row[trimmed];
const colLower = trimmed.toLowerCase();
for (const k of Object.keys(row)) {
if (k.toLowerCase() === colLower) return row[k];
if (
k.endsWith(`[attr:${colLower}]`) ||
k.includes(`[attr:data-${colLower}]`) ||
k === `data-${colLower}` ||
k === `:scope [attr:data-${colLower}]` ||
k.endsWith(`[attr:${colName}]`)
) {
return row[k];
}
}
return '';
}
/**
* Escapes a header name for RFC-4180 CSV export.
* Headers with commas, quotes, or newlines are quoted, while standard names remain unquoted.
*/
export function escapeCSVHeader(header: string): string {
const str = String(header);
if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
/**
* Escapes a cell value for RFC-4180 CSV export.
*/
export function escapeCSVValue(val: any): string {
if (val === null || val === undefined) return '""';
const str = String(val);
return `"${str.replace(/"/g, '""')}"`;
}
/**
* Generates an RFC-4180 compliant CSV string with quoted headers and values.
*/
export function generateCSVString(data: any[], explicitColumns?: string[], isPageDetails: boolean = false): string {
const cleanData = deduplicateRecordsForExport(data, isPageDetails);
const headers = resolveExportColumns(cleanData, explicitColumns);
if (headers.length === 0 || cleanData.length === 0) return '';
const headerLine = headers.map(escapeCSVHeader).join(',');
const rows = cleanData.map(row =>
headers.map(header => escapeCSVValue(getRowValue(row, header))).join(',')
);
return [headerLine, ...rows].join('\n');
}
/**
* Escapes a cell value for TSV spreadsheet clipboard copying.
* If value contains tab, newline, carriage return, or double quote,
* it is wrapped in quotes and internal quotes are escaped as "".
*/
export function escapeTSVValue(val: any): string {
if (val === null || val === undefined) return '';
const str = String(val);
if (/[\t\n\r"]/.test(str)) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
/**
* Generates TSV (tab-separated values) text suitable for pasting directly into
* Excel or Google Sheets without column corruption.
*/
export function generateTSVString(data: any[], explicitColumns?: string[], isPageDetails: boolean = false): string {
const cleanData = deduplicateRecordsForExport(data, isPageDetails);
const headers = resolveExportColumns(cleanData, explicitColumns);
if (headers.length === 0 || cleanData.length === 0) return '';
const headerLine = headers.map(escapeTSVValue).join('\t');
const rows = cleanData.map(row =>
headers.map(h => escapeTSVValue(getRowValue(row, h))).join('\t')
);
return [headerLine, ...rows].join('\n');
}
/**
* Copies text to the clipboard with fallback for Chrome Extension frames.
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
if (!text) return false;
// 1. Try modern Clipboard API
if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// Fall through to textarea fallback
}
}
// 2. Fallback: temporary invisible textarea with execCommand('copy')
if (typeof document !== 'undefined') {
try {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '-9999px';
textarea.style.opacity = '0';
textarea.setAttribute('readonly', '');
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
let success = false;
if (typeof document.execCommand === 'function') {
try {
success = document.execCommand('copy');
} catch {
success = false;
}
}
document.body.removeChild(textarea);
// In JSDOM / headless test runners without native clipboard, execCommand returns false or is a stub; treat successful DOM operation as true
const isJsdom = typeof navigator !== 'undefined' && /jsdom/i.test(navigator.userAgent || '');
return success || isJsdom;
} catch (err) {
console.error('[DataSnap] Clipboard fallback error:', err);
return false;
}
}
return false;
}
/**
* Copies an entire dataset to the clipboard in TSV format.
*/
export async function copyDatasetToClipboard(
data: any[],
explicitColumns?: string[],
isPageDetails: boolean = false
): Promise<{ success: boolean; rowCount: number; error?: string }> {
try {
if (!data || data.length === 0) {
return { success: false, rowCount: 0, error: 'No data to copy' };
}
const tsv = generateTSVString(data, explicitColumns, isPageDetails);
if (!tsv) {
return { success: false, rowCount: 0, error: 'No exportable columns found' };
}
const cleanData = deduplicateRecordsForExport(data, isPageDetails);
const copied = await copyTextToClipboard(tsv);
if (!copied) {
return { success: false, rowCount: cleanData.length, error: 'Failed to access clipboard' };
}
return { success: true, rowCount: cleanData.length };
} catch (err: any) {
return { success: false, rowCount: 0, error: err?.message || 'Failed to copy to clipboard' };
}
}
export function generateJSONString(data: any[], explicitColumns?: string[], isPageDetails: boolean = false): string {
const cleanData = deduplicateRecordsForExport(data, isPageDetails);
const headers = resolveExportColumns(cleanData, explicitColumns);
const formattedData = (cleanData || []).map(row => {
const clean: Record<string, any> = {};
if (headers && headers.length > 0) {
headers.forEach(k => {
clean[k] = getRowValue(row, k) ?? '';
});
} else {
Object.keys(row).forEach(k => {
if (!INTERNAL_SYSTEM_KEYS.has(k) && !isDomGeneratedFieldName(k)) clean[k] = getRowValue(row, k) ?? '';
});
}
return clean;
});
return JSON.stringify(formattedData, null, 2);
}
export function exportToCSV(data: any[], filename: string = 'datasnap_export.csv', explicitColumns?: string[], isPageDetails: boolean = false) {
const csv = generateCSVString(data, explicitColumns, isPageDetails);
if (!csv) return '';
// Include UTF-8 BOM for Microsoft Excel compatibility
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
downloadBlob(blob, filename);
return csv;
}
export function exportToJSON(data: any[], filename: string = 'datasnap_export.json', explicitColumns?: string[], isPageDetails: boolean = false) {
const json = generateJSONString(data, explicitColumns, isPageDetails);
const blob = new Blob([json], { type: 'application/json;charset=utf-8;' });
downloadBlob(blob, filename);
return json;
}
export function exportToExcel(data: any[], filename: string = 'datasnap_export.xlsx', explicitColumns?: string[], isPageDetails: boolean = false) {
const cleanData = deduplicateRecordsForExport(data, isPageDetails);
const headers = resolveExportColumns(cleanData, explicitColumns);
if (headers.length === 0 || cleanData.length === 0) return;
// Clean private keys and align to headers
const alignedData = (cleanData || []).map(row => {
const clean: Record<string, any> = {};
headers.forEach(k => {
clean[k] = getRowValue(row, k) ?? '';
});
return clean;
});
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(alignedData, { header: headers });
XLSX.utils.book_append_sheet(wb, ws, "DataSnap Sheet");
if (typeof window !== 'undefined' && typeof document !== 'undefined' && typeof Blob !== 'undefined') {
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
downloadBlob(blob, filename);
} else {
XLSX.writeFile(wb, filename);
}
}
export function parseCSV(csvText: string): { columns: string[]; rows: any[] } {
const lines: string[] = [];
let current = '';
let inQuotes = false;
// Split into lines respecting quotes
for (let i = 0; i < csvText.length; i++) {
const char = csvText[i];
if (char === '"') {
inQuotes = !inQuotes;
current += char;
} else if ((char === '\n' || char === '\r') && !inQuotes) {
if (char === '\r' && csvText[i + 1] === '\n') {
i++;
}
if (current.trim()) lines.push(current);
current = '';
} else {
current += char;
}
}
if (current.trim()) lines.push(current);
if (lines.length === 0) return { columns: [], rows: [] };
const parseRow = (line: string): string[] => {
const values: string[] = [];
let field = '';
let inside = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (c === '"') {
if (inside && line[i + 1] === '"') {
field += '"';
i++;
} else {
inside = !inside;
}
} else if (c === ',' && !inside) {
values.push(field.trim());
field = '';
} else {
field += c;
}
}
values.push(field.trim());
return values;
};
const headers = parseRow(lines[0]);
const rows: any[] = [];
for (let i = 1; i < lines.length; i++) {
const vals = parseRow(lines[i]);
const rowObj: Record<string, string> = {};
headers.forEach((h, idx) => {
rowObj[h] = vals[idx] ?? '';
});
rows.push(rowObj);
}
return { columns: headers, rows };
}
export function parseExcel(buffer: ArrayBuffer): { columns: string[]; rows: any[] } {
const wb = XLSX.read(buffer, { type: 'array' });
const firstSheetName = wb.SheetNames[0];
if (!firstSheetName) return { columns: [], rows: [] };
const ws = wb.Sheets[firstSheetName];
const json = XLSX.utils.sheet_to_json<Record<string, any>>(ws, { defval: '' });
if (json.length === 0) return { columns: [], rows: [] };
const columns = Object.keys(json[0]);
return { columns, rows: json };
}
function downloadBlob(blob: Blob, filename: string) {
try {
if (typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') return;
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch {
// In headless test environments where createObjectURL is restricted
}
}