-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgetCodeAndMap.ts
More file actions
82 lines (74 loc) · 2.4 KB
/
Copy pathgetCodeAndMap.ts
File metadata and controls
82 lines (74 loc) · 2.4 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
import * as vscode from 'vscode'
import { getSourceMapUrl } from './getSourceMapUrl'
export async function getCodeAndMap(): Promise<{ code: string; map: string } | undefined> {
const editor = vscode.window.activeTextEditor
if (!editor)
return
const document = editor.document
const code = editor.selection.isEmpty ? document.getText() : editor.selections.map(document.getText).join('\n')
if (!code)
return
const file = document.uri.path
const dir = file.replace(/\/[^\/]+$/, '')
const readTextFile = async (relativePath: string) => {
try {
const uri = vscode.Uri.file(`${dir}/${relativePath}`)
const buf = await vscode.workspace.fs.readFile(uri)
return new TextDecoder('utf-8').decode(buf)
}
catch (err) {
console.warn('Error reading file', err)
}
}
const addMissingSourceContent = async (map: string) => {
const json = JSON.parse(map)
const { sources, sourcesContent } = json
let addedSourceContent = false
for (let i = 0; i < sources.length; i++) {
if (!sourcesContent[i] && sources[i]) {
addedSourceContent = true
sourcesContent[i] = await readTextFile(sources[i])
}
}
if (addedSourceContent)
map = JSON.stringify(json)
return map
}
const mapUrl = getSourceMapUrl(code)
if (mapUrl) {
if (mapUrl.startsWith('data:')) {
const [type, data] = mapUrl.split(',')
const map = new TextDecoder('utf-8').decode(Buffer.from(data, type.includes('base64') ? 'base64' : 'utf-8'))
if (map)
return { code, map }
}
else if (/^https?:/.test(mapUrl)) {
// TODO: fetch map from url
}
else if (mapUrl.startsWith('/')) {
// TODO: read map from absolute path?
}
else if (!document.isUntitled) {
const map = await readTextFile(mapUrl)
if (map)
return { code, map }
}
}
if (document.isUntitled)
return
const fileName = file.split('/').pop()
if (fileName) {
const filelist = await vscode.workspace.fs.readDirectory(vscode.Uri.file(dir))
const mapFiles = filelist.map(([name]) => name).filter(f => f.endsWith('.map'))
const mapFile
= mapFiles.find(f => f === `${fileName}.map`)
|| mapFiles.find(f => fileName.startsWith(f.split('.')[0]))
if (mapFile) {
let map = await readTextFile(mapFile)
if (map) {
map = await addMissingSourceContent(map)
return { code, map }
}
}
}
}