|
| 1 | +import type {OutputItem} from 'vscode-notebook-renderer'; |
| 2 | +import {csvParse} from 'd3-dsv'; |
| 3 | +const xmlParser = require('fast-xml-parser'); |
| 4 | + |
| 5 | +/** |
| 6 | + * OutputLoaders loads data from notebook cell output items. |
| 7 | + */ |
| 8 | +export class OutputLoader { |
| 9 | + |
| 10 | + /** |
| 11 | + * Creates new OutputLoader instance. |
| 12 | + * @param outputData Notebook cell output item. |
| 13 | + * @param mimeType Notebook cell output mime type. |
| 14 | + */ |
| 15 | + constructor (private outputData: OutputItem, private mimeType: string) { |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Gets data output. |
| 20 | + */ |
| 21 | + getData(): any { |
| 22 | + // try getting JSON data first |
| 23 | + const objectData = this.getJsonData(this.outputData); |
| 24 | + if (objectData !== undefined) { |
| 25 | + return objectData; |
| 26 | + } |
| 27 | + |
| 28 | + // try parsing text data |
| 29 | + let textData: string = this.outputData.text(); |
| 30 | + if (textData.length > 0) { |
| 31 | + if (textData.startsWith("'") && textData.endsWith("'")) { |
| 32 | + // strip out start/end single quotes from notebook cell output |
| 33 | + textData = textData.substr(1, textData.length-2); |
| 34 | + } |
| 35 | + console.log('leaflet.map:data:text:', textData.substring(0, Math.min(300, textData.length)), '...'); |
| 36 | + |
| 37 | + // see if text data is in json data format |
| 38 | + const jsonData = this.getJsonData(textData); |
| 39 | + if (jsonData !== undefined) { |
| 40 | + return jsonData; |
| 41 | + } |
| 42 | + else if (textData.startsWith('<?xml version="1.0"')) { |
| 43 | + // parse XML data |
| 44 | + return this.xmlParse(textData); |
| 45 | + } |
| 46 | + else if (this.isCsv(textData)) { |
| 47 | + // parse CSV data |
| 48 | + return csvParse(textData); |
| 49 | + } |
| 50 | + else if (textData !== '{}' && !textData.startsWith('<Buffer ')) { // empty object or binary data |
| 51 | + return textData; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // TODO: try loading binary Apache Arrow data |
| 56 | + // console.log('leaflet.map:data:output', this.outputData); |
| 57 | + const dataArray: Uint8Array = this.outputData.data(); |
| 58 | + console.log(dataArray); |
| 59 | + if (dataArray.length > 0 ) { |
| 60 | + console.log(`leaflet.map:dataType: ${dataArray.constructor}`); |
| 61 | + // return aq.fromArrow(dataArray); |
| 62 | + } |
| 63 | + |
| 64 | + return this.outputData; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Gets JSON object or data array, |
| 69 | + * CSV rows data array, or undefined |
| 70 | + * for plain text and binary data types. |
| 71 | + * @param data Notebook cell output data value. |
| 72 | + */ |
| 73 | + getJsonData(data: any): any { |
| 74 | + // console.log('leaflet.map:data:json:', data); |
| 75 | + try { |
| 76 | + if (typeof data === 'string') { |
| 77 | + // try parsing JSON string |
| 78 | + const textData: string = this.patchJson(data); |
| 79 | + const objectData: any = JSON.parse(textData); |
| 80 | + if (Array.isArray(objectData)) { |
| 81 | + console.log('leaflet.map:data:format: JSON array'); |
| 82 | + return objectData; |
| 83 | + } |
| 84 | + else { |
| 85 | + console.log('leaflet.map:data:format: JSON'); |
| 86 | + return objectData; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + // try getting json data object |
| 91 | + // console.log('leaflet.map:data:json:', data); |
| 92 | + let jsonData: any = data.json(); |
| 93 | + if (jsonData.data) { |
| 94 | + // use data object from REST response |
| 95 | + jsonData = jsonData.data; |
| 96 | + } |
| 97 | + |
| 98 | + if (jsonData.features) { |
| 99 | + console.log('leaflet.map:data:format: GeoJSON'); |
| 100 | + return jsonData; |
| 101 | + } |
| 102 | + |
| 103 | + if (Array.isArray(jsonData)) { |
| 104 | + console.log('leaflet.map:data:format: JSON array'); |
| 105 | + return jsonData; |
| 106 | + } |
| 107 | + |
| 108 | + if (typeof jsonData === 'string') { |
| 109 | + if (this.isCsv(jsonData)) { |
| 110 | + // parse CSV data for JSON response from REST Book |
| 111 | + // see: https://github.com/tanhakabir/rest-book/issues/114 |
| 112 | + return csvParse(jsonData); |
| 113 | + } |
| 114 | + else if (jsonData.startsWith('<?xml version="1.0"')) { |
| 115 | + // try to parse XML data as the last resort |
| 116 | + return this.xmlParse(jsonData); |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + catch (error: any) { |
| 121 | + console.log('leaflet.map:data: JSON.parse error:\n', error.message); |
| 122 | + } |
| 123 | + return undefined; |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Patches garbled JSON string. |
| 128 | + * @param data JSON data string. |
| 129 | + * @returns Patched up JSON string. |
| 130 | + */ |
| 131 | + patchJson(data: string): string { |
| 132 | + // patch garbled json string |
| 133 | + const escapedQuoteRegEx = /\\\\"/g; |
| 134 | + const objectStartRegEx = /"{/g; |
| 135 | + const objectEndRegEx = /}"/g; |
| 136 | + const xRegEx = /\\xa0/g; |
| 137 | + const newLineRegEx = /\\n/g; |
| 138 | + let textData: string = data.replace(escapedQuoteRegEx, '"'); |
| 139 | + textData = textData.replace(objectStartRegEx, '{'); |
| 140 | + textData = textData.replace(objectEndRegEx, '}'); |
| 141 | + textData = textData.replace(xRegEx, ' '); |
| 142 | + textData = textData.replace(newLineRegEx, ''); |
| 143 | + // console.log('leaflet.map:data:text:', textData.substring(0, Math.min(300, textData.length)), '...'); |
| 144 | + return textData; |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * Checks if text content is in CSV format. |
| 149 | + * @param text Text content to check. |
| 150 | + */ |
| 151 | + isCsv(text: string): boolean { |
| 152 | + if (text === undefined || text.length === 0) { |
| 153 | + return false; |
| 154 | + } |
| 155 | + |
| 156 | + // get text lines |
| 157 | + const maxLines: number = 10; |
| 158 | + const lines: string[] = text.trimEnd().split('\n', maxLines); |
| 159 | + const minRows: number = Math.min(lines.length, maxLines); |
| 160 | + |
| 161 | + if (lines.length > 0) { |
| 162 | + console.log('leaflet.map:data:lines:', lines); |
| 163 | + const columns: string[] = lines[0].split(','); |
| 164 | + const columnCount = columns.length; |
| 165 | + |
| 166 | + if (columnCount > 1) { |
| 167 | + console.log('leaflet.map:data:columns:', columns); |
| 168 | + // check columns for garbled json |
| 169 | + for (let k =0; k < columnCount; k++) { |
| 170 | + let columnName: string = columns[k]; |
| 171 | + if (columnName.startsWith('[') || columnName.startsWith('{')) { |
| 172 | + return false; |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + // do naive check for some commas in the first 9 rows |
| 177 | + for (let i = 1; i < minRows; i++) { |
| 178 | + const columnValues: string[] = lines[i].split(','); |
| 179 | + // console.log(`data.table:row[${i}]`, columnValues); |
| 180 | + if (columnValues.length < columnCount) { |
| 181 | + return false; |
| 182 | + } |
| 183 | + } |
| 184 | + console.log('leaflet.map:data:format: CSV'); |
| 185 | + return true; |
| 186 | + } |
| 187 | + } |
| 188 | + return false; |
| 189 | + } |
| 190 | + |
| 191 | + /** |
| 192 | + * Parses xml data. |
| 193 | + * @param xml Xml data string. |
| 194 | + */ |
| 195 | + xmlParse(xml: string): any { |
| 196 | + let jsonData = {}; |
| 197 | + const xmlParserOptions = { |
| 198 | + attributeNamePrefix : '', |
| 199 | + textNodeName : 'value', |
| 200 | + ignoreAttributes : false, |
| 201 | + ignoreNameSpace : true, |
| 202 | + allowBooleanAttributes : true, |
| 203 | + parseNodeValue : true, |
| 204 | + parseAttributeValue : true, |
| 205 | + trimValues: true, |
| 206 | + // parseTrueNumberOnly: false, |
| 207 | + // arrayMode: false, //"strict" |
| 208 | + }; |
| 209 | + try { |
| 210 | + jsonData = xmlParser.parse(xml, xmlParserOptions); // , true); // validate xml |
| 211 | + console.log('leaflet.map:data:format: XML'); |
| 212 | + // console.log(JSON.stringify(jsonData, null, 2)); |
| 213 | + } |
| 214 | + catch(error: any) { |
| 215 | + console.log('leaflet.map:data: XML parse error:\n', error.message); |
| 216 | + } |
| 217 | + return jsonData; |
| 218 | + } |
| 219 | +} |
0 commit comments