-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
771 lines (661 loc) · 21.3 KB
/
index.js
File metadata and controls
771 lines (661 loc) · 21.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
const path = require('path')
const fs = require('fs').promises
const https = require('https')
const http = require('http')
const {URL} = require('url')
const {readdir, stat} = require('fs').promises
const os = require('os')
const isWindows = os.platform() === 'win32'
const MAX_FILENAME_LENGTH = 255
const INVALID_CHARS_WIN = /[<>:"|?*\x00-\x1f]/g
const INVALID_CHARS_UNIX = /[\x00\/]/g
const INVALID_CHARS_COMMON = /[<>:"|?*\\]/g
const RESERVED_NAMES_WIN = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i
function sanitizeFilename(filename, options = {}) {
if (!filename || typeof filename !== 'string') {
return 'unnamed'
}
let sanitized = filename.trim()
if (isWindows) {
sanitized = sanitized.replace(INVALID_CHARS_WIN, '_')
const match = sanitized.match(RESERVED_NAMES_WIN)
if (match) {
const name = match[1]
const ending = match[2] || ''
sanitized = sanitized.replace(RESERVED_NAMES_WIN, name + '_' + ending)
}
sanitized = sanitized.replace(/\.+$/, '')
if (sanitized.endsWith(' ')) {
sanitized = sanitized.replace(/ +$/, '')
}
} else {
sanitized = sanitized.replace(INVALID_CHARS_UNIX, '_')
sanitized = sanitized.replace(INVALID_CHARS_COMMON, '_')
}
sanitized = sanitized.replace(/[\x80-\x9f]/g, '_')
if (sanitized.length === 0) {
sanitized = 'unnamed'
}
if (sanitized.length > MAX_FILENAME_LENGTH) {
const ext = path.extname(sanitized)
const nameWithoutExt = path.basename(sanitized, ext)
const maxNameLength = MAX_FILENAME_LENGTH - ext.length
sanitized = nameWithoutExt.substring(0, maxNameLength) + ext
}
return path.normalize(sanitized)
}
function extractInlineSourceMapUrl(sourceCode) {
const regex = /\/\/[#@]\s*sourceMappingURL=(.+)/i
const match = sourceCode.match(regex)
return match ? match[1].trim() : null
}
function decodeBase64SourceMap(dataUri) {
const base64Match = dataUri.match(/^data:application\/json(?:;charset=[^;]+)?;base64,(.+)$/i)
if (base64Match) {
try {
const base64Data = base64Match[1]
const jsonString = Buffer.from(base64Data, 'base64').toString('utf8')
return JSON.parse(jsonString)
} catch (error) {
throw new Error(`Failed to decode base64 source map: ${error.message}`)
}
}
if (dataUri.startsWith('{')) {
try {
return JSON.parse(dataUri)
} catch (error) {
}
}
return null
}
function downloadFromUrl(urlString) {
return new Promise((resolve, reject) => {
let url
try {
url = new URL(urlString)
} catch (error) {
reject(new Error(`Invalid URL: ${urlString}`))
return
}
const protocol = url.protocol === 'https:' ? https : http
const options = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:144.0) Gecko/20100101 Firefox/144.0',
'Accept': '*/*',
'X-Tool': 'unmapx/incogbyte',
},
}
const req = protocol.request(options, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
return resolve(downloadFromUrl(res.headers.location))
}
if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}: Failed to download ${urlString}`))
return
}
const chunks = []
res.on('data', (chunk) => chunks.push(chunk))
res.on('end', () => {
const data = Buffer.concat(chunks).toString('utf8')
resolve(data)
})
})
req.setTimeout(30000, () => {
req.destroy()
reject(new Error(`Timeout downloading ${urlString}`))
})
req.on('error', (error) => {
reject(new Error(`Failed to download ${urlString}: ${error.message}`))
})
req.end()
})
}
async function readSourceMapFromUrl(urlString) {
try {
const data = await downloadFromUrl(urlString)
try {
return JSON.parse(data)
} catch (jsonError) {
const inlineUrl = extractInlineSourceMapUrl(data)
if (inlineUrl) {
const decoded = decodeBase64SourceMap(inlineUrl)
if (decoded) {
return decoded
}
if (inlineUrl.startsWith('http://') || inlineUrl.startsWith('https://')) {
return readSourceMapFromUrl(inlineUrl)
} else {
const baseUrl = new URL(urlString)
const resolvedUrl = new URL(inlineUrl, baseUrl).toString()
return readSourceMapFromUrl(resolvedUrl)
}
}
const decoded = decodeBase64SourceMap(data.trim())
if (decoded) {
return decoded
}
throw new Error(`URL does not contain a valid source map: ${urlString}`)
}
} catch (error) {
if (error.message.includes('Invalid URL') || error.message.includes('Failed to download')) {
throw error
}
throw new Error(`Failed to read source map from URL ${urlString}: ${error.message}`)
}
}
function normalizeSourceMap(sourceMap) {
if (!sourceMap || typeof sourceMap !== 'object') {
throw new Error('Invalid source map: must be an object')
}
if (sourceMap.sections) {
return normalizeIndexedSourceMap(sourceMap)
}
if (Array.isArray(sourceMap.sources) && (!sourceMap.sourcesContent || sourceMap.sourcesContent.length === 0)) {
if (sourceMap.x_google_ignoreList) {
sourceMap.sourcesContent = sourceMap.sources.map(() => null)
}
}
if (Array.isArray(sourceMap.sources)) {
if (!Array.isArray(sourceMap.sourcesContent)) {
sourceMap.sourcesContent = []
}
while (sourceMap.sourcesContent.length < sourceMap.sources.length) {
sourceMap.sourcesContent.push(null)
}
if (sourceMap.sourcesContent.length > sourceMap.sources.length) {
sourceMap.sourcesContent = sourceMap.sourcesContent.slice(0, sourceMap.sources.length)
}
}
if (!sourceMap.sourceRoot && sourceMap.sourceRoot !== '') {
sourceMap.sourceRoot = sourceMap.sourceRoot || ''
}
return sourceMap
}
function normalizeIndexedSourceMap(indexedMap) {
if (!indexedMap.sections || !Array.isArray(indexedMap.sections)) {
throw new Error('Invalid indexed source map: missing sections array')
}
const mergedSources = []
const mergedSourcesContent = []
const mergedMappings = []
let mergedNames = indexedMap.names || []
let mergedFile = indexedMap.file || ''
let mergedSourceRoot = indexedMap.sourceRoot || ''
for (const section of indexedMap.sections) {
if (!section.offset || !section.map) {
continue
}
const offset = section.offset
const map = section.map
if (map.sources) {
mergedSources.push(...map.sources)
}
if (map.sourcesContent) {
mergedSourcesContent.push(...map.sourcesContent)
} else if (map.sources) {
mergedSourcesContent.push(...map.sources.map(() => null))
}
if (map.names) {
const existingNamesCount = mergedNames.length
mergedNames.push(...map.names)
}
if (map.mappings) {
mergedMappings.push({
offset: offset,
mappings: map.mappings
})
}
}
return {
version: indexedMap.version || 3,
file: mergedFile,
sourceRoot: mergedSourceRoot,
sources: mergedSources,
sourcesContent: mergedSourcesContent,
names: mergedNames,
mappings: mergedMappings,
_indexed: true
}
}
async function readSourceMapFromFile(filepath) {
try {
const data = await fs.readFile(filepath, 'utf8')
try {
return JSON.parse(data)
} catch (jsonError) {
const inlineUrl = extractInlineSourceMapUrl(data)
if (inlineUrl) {
const decoded = decodeBase64SourceMap(inlineUrl)
if (decoded) {
return decoded
}
const sourceMapPath = path.resolve(path.dirname(filepath), inlineUrl)
try {
const sourceMapData = await fs.readFile(sourceMapPath, 'utf8')
return JSON.parse(sourceMapData)
} catch (error) {
throw new Error(`Failed to read source map from ${sourceMapPath}: ${error.message}`)
}
}
throw new Error(`File does not contain a valid source map: ${filepath}`)
}
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`Source map file not found: ${filepath}`)
}
throw error
}
}
async function readInlineSourceMap(jsFilePath) {
const sourceCode = await fs.readFile(jsFilePath, 'utf8')
const sourceMapUrl = extractInlineSourceMapUrl(sourceCode)
if (!sourceMapUrl) {
throw new Error(`No inline source map found in ${jsFilePath}`)
}
const decoded = decodeBase64SourceMap(sourceMapUrl)
if (decoded) {
return decoded
}
const sourceMapPath = path.resolve(path.dirname(jsFilePath), sourceMapUrl)
return readSourceMapFromFile(sourceMapPath)
}
async function spit(filepath, data) {
const dirpath = path.dirname(filepath)
await fs.mkdir(dirpath, {recursive: true})
return fs.writeFile(filepath, data)
}
async function dumpSource(source, sourceContent, sourceRoot, dirpath, options = {}) {
if (sourceContent === null || sourceContent === undefined) {
if (options.skipMissing) {
return null
}
if (options.createPlaceholders) {
sourceContent = `// Source content not available for: ${source}\n`
} else {
throw new Error(`Missing source content for: ${source}`)
}
}
// Normalize the source path to handle relative paths like ../node_modules/...
// Split by path separator, sanitize each component, then rejoin
const pathParts = source.split(/[/\\]/).filter(part => part && part !== '.')
const sanitizedParts = pathParts.map(part => {
if (part === '..') {
return '__parent__' // Replace .. with safe directory name
}
return sanitizeFilename(part, options)
})
const sourcePath = path.join(...sanitizedParts)
const sourceFilepath = path.join(dirpath, sourceRoot || '', sourcePath)
if (options.verbose) {
options.logger?.info(`Extracting: ${source} -> ${sourceFilepath}`)
}
if (options.dryRun) {
return sourceFilepath
}
await spit(sourceFilepath, sourceContent)
return sourceFilepath
}
function dumpSourceMap(sourceMapData, dirpath, options = {}) {
const sourceMap = normalizeSourceMap(sourceMapData)
const {sources, sourcesContent, sourceRoot} = sourceMap
if (!Array.isArray(sources)) {
throw new Error('Invalid source map: sources must be an array')
}
if (options.verbose) {
options.logger?.info(`Processing source map with ${sources.length} source(s)`)
if (sourceMap._indexed) {
options.logger?.info('Detected indexed source map format')
}
}
const sourcePromises = sources.map((source, i) => {
const sourceContent = sourcesContent[i]
if ((sourceContent === null || sourceContent === undefined) && options.skipMissing) {
return Promise.resolve(null)
}
return dumpSource(source, sourceContent, sourceRoot || '', dirpath, options)
})
return Promise.all(sourcePromises).then(results =>
results.filter(result => result !== null)
)
}
async function dumpFile(filepath, dirpath, sourceRoot, options = {}) {
let sourceMap
if (filepath.startsWith('http://') || filepath.startsWith('https://')) {
if (options.isJsFile) {
const jsContent = await downloadFromUrl(filepath)
const inlineUrl = extractInlineSourceMapUrl(jsContent)
if (inlineUrl) {
const decoded = decodeBase64SourceMap(inlineUrl)
if (decoded) {
sourceMap = decoded
} else if (inlineUrl.startsWith('http://') || inlineUrl.startsWith('https://')) {
sourceMap = await readSourceMapFromUrl(inlineUrl)
} else {
const baseUrl = new URL(filepath)
const resolvedUrl = new URL(inlineUrl, baseUrl).toString()
sourceMap = await readSourceMapFromUrl(resolvedUrl)
}
} else {
throw new Error(`No inline source map found in JavaScript file: ${filepath}`)
}
} else {
sourceMap = await readSourceMapFromUrl(filepath)
}
}
else if (filepath === '/dev/stdin' || filepath === '-') {
const chunks = []
for await (const chunk of process.stdin) {
chunks.push(chunk)
}
const inputData = Buffer.concat(chunks).toString('utf8')
try {
sourceMap = JSON.parse(inputData)
} catch (error) {
const inlineUrl = extractInlineSourceMapUrl(inputData)
if (inlineUrl) {
const decoded = decodeBase64SourceMap(inlineUrl)
if (decoded) {
sourceMap = decoded
} else {
throw new Error(`Failed to parse source map from stdin: ${error.message}`)
}
} else {
throw new Error(`Failed to parse source map from stdin: ${error.message}`)
}
}
} else {
const isJsFile = filepath.endsWith('.js') || filepath.endsWith('.mjs') || filepath.endsWith('.cjs')
if (isJsFile && !filepath.endsWith('.map')) {
try {
sourceMap = await readInlineSourceMap(filepath)
} catch (error) {
const mapFilePath = filepath + '.map'
try {
sourceMap = await readSourceMapFromFile(mapFilePath)
} catch (mapError) {
throw new Error(`No source map found for ${filepath}. Tried inline and ${mapFilePath}`)
}
}
} else {
sourceMap = await readSourceMapFromFile(filepath)
}
}
if (sourceRoot !== undefined && sourceRoot !== null) {
sourceMap.sourceRoot = sourceRoot
}
return dumpSourceMap(sourceMap, dirpath, options)
}
async function dumpMultipleFiles(filepaths, baseDirpath, sourceRoot, options = {}) {
const results = {}
for (const filepath of filepaths) {
const outputDir = options.separateDirs
? path.join(baseDirpath, path.basename(filepath, path.extname(filepath)))
: baseDirpath
try {
const writtenFiles = await dumpFile(filepath, outputDir, sourceRoot, options)
results[filepath] = writtenFiles
} catch (error) {
if (options.continueOnError) {
results[filepath] = { error: error.message }
} else {
throw error
}
}
}
return results
}
async function getAllFiles(dirPath, fileList = []) {
try {
const files = await readdir(dirPath)
for (const file of files) {
const filePath = path.join(dirPath, file)
const fileStat = await stat(filePath)
if (fileStat.isDirectory()) {
await getAllFiles(filePath, fileList)
} else {
fileList.push(filePath)
}
}
return fileList
} catch (error) {
return fileList
}
}
function extractUrlsFromText(text) {
const urlRegex = /(https?:\/\/[^\s"'<>{}|\\^`\[\]]+)/gi
const urls = new Set()
const matches = text.matchAll(urlRegex)
for (const match of matches) {
try {
const url = new URL(match[1])
urls.add(url.toString())
} catch (error) {
}
}
return Array.from(urls)
}
async function extractLinksFromDirectory(dirPath) {
const allUrls = new Set()
try {
const files = await getAllFiles(dirPath)
for (const filePath of files) {
try {
const content = await fs.readFile(filePath, 'utf8')
const urls = extractUrlsFromText(content)
urls.forEach(url => allUrls.add(url))
} catch (error) {
}
}
} catch (error) {
throw new Error(`Failed to extract links from directory: ${error.message}`)
}
return Array.from(allUrls).sort()
}
function createLogger(verbose = false, quiet = false) {
return {
debug: (msg) => {
if (verbose && !quiet) {
console.error(`[DEBUG] ${msg}`)
}
},
info: (msg) => {
if (!quiet) {
console.error(msg)
}
},
error: (msg) => {
if (!quiet) {
console.error(msg)
}
},
warn: (msg) => {
if (!quiet) {
console.error(`[WARN] ${msg}`)
}
}
}
}
async function verifySourceMap(urlString) {
try {
const url = new URL(urlString)
const protocol = url.protocol === 'https:' ? https : http
const options = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:144.0) Gecko/20100101 Firefox/144.0',
'Accept': '*/*',
'X-Tool': 'unmapx/incogbyte',
},
}
return new Promise((resolve) => {
const req = protocol.request(options, (res) => {
// Check for X-SourceMap header first (faster check)
if (res.headers['x-sourcemap'] || res.headers['sourcemap']) {
req.destroy()
resolve(true)
return
}
// If redirect, follow it
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
req.destroy()
return resolve(verifySourceMap(res.headers.location))
}
if (res.statusCode !== 200) {
req.destroy()
resolve(false)
return
}
// Download content to check for inline sourcemap
// Sourcemap comment is usually at the end, so we'll read the last portion
// For efficiency, we'll read chunks and keep only the last 128KB
const chunks = []
let totalLength = 0
const maxKeepLength = 131072 // 128KB - enough for sourcemap at end
res.on('data', (chunk) => {
chunks.push(chunk)
totalLength += chunk.length
// If we exceed the limit, remove old chunks but keep recent ones
if (totalLength > maxKeepLength) {
let removeLength = 0
while (chunks.length > 1 && totalLength - removeLength > maxKeepLength) {
const firstChunk = chunks.shift()
removeLength += firstChunk.length
}
totalLength -= removeLength
}
})
res.on('end', () => {
try {
const content = Buffer.concat(chunks).toString('utf8')
const inlineUrl = extractInlineSourceMapUrl(content)
resolve(!!inlineUrl)
} catch (error) {
resolve(false)
}
})
})
req.setTimeout(10000, () => {
req.destroy()
resolve(false)
})
req.on('error', () => {
resolve(false)
})
req.end()
})
} catch (error) {
return false
}
}
async function verifyMultipleUrls(urls) {
const results = await Promise.allSettled(
urls.map(async (url) => {
const hasSourceMap = await verifySourceMap(url.trim())
return { url: url.trim(), hasSourceMap }
})
)
return results.map((result, index) => {
if (result.status === 'fulfilled') {
return result.value
} else {
return { url: urls[index].trim(), hasSourceMap: false, error: result.reason }
}
})
}
function extractDomainFromUrl(urlString) {
try {
const url = new URL(urlString)
// Remove port if present
return url.hostname
} catch (error) {
// Fallback: try to extract domain manually
const match = urlString.match(/https?:\/\/([^\/:]+)/)
return match ? match[1] : 'unknown'
}
}
async function downloadAllSourceMaps(urls, baseOutputDir, options = {}) {
const logger = options.logger || createLogger()
const results = []
// URLs are already verified, so we can use them directly
const urlsToDownload = urls.filter(url => {
const trimmed = url.trim()
return trimmed && (trimmed.startsWith('http://') || trimmed.startsWith('https://'))
})
if (urlsToDownload.length === 0) {
logger.info('No URLs with source maps found to download')
return results
}
if (options.verbose) {
logger.info(`Found ${urlsToDownload.length} URL(s) with source maps. Starting download...`)
}
// Download and extract sourcemaps for each URL
const downloadPromises = urlsToDownload.map(async (url) => {
try {
const domain = extractDomainFromUrl(url)
const domainDir = path.join(baseOutputDir, domain)
if (options.verbose) {
logger.info(`Downloading source map from: ${url}`)
}
const fileOptions = {
...options,
isJsFile: true,
continueOnError: true,
}
const writtenFiles = await dumpFile(url, domainDir, undefined, fileOptions)
return {
url,
domain,
success: true,
files: writtenFiles,
}
} catch (error) {
return {
url,
domain: extractDomainFromUrl(url),
success: false,
error: error.message,
}
}
})
const downloadResults = await Promise.allSettled(downloadPromises)
return downloadResults.map((result, index) => {
if (result.status === 'fulfilled') {
return result.value
} else {
return {
url: urlsToDownload[index],
domain: extractDomainFromUrl(urlsToDownload[index]),
success: false,
error: result.reason?.message || 'Unknown error',
}
}
})
}
module.exports = {
dumpSource,
dumpSourceMap,
dumpFile,
dumpMultipleFiles,
readInlineSourceMap,
readSourceMapFromFile,
readSourceMapFromUrl,
downloadFromUrl,
extractInlineSourceMapUrl,
decodeBase64SourceMap,
normalizeSourceMap,
normalizeIndexedSourceMap,
extractLinksFromDirectory,
sanitizeFilename,
createLogger,
verifySourceMap,
verifyMultipleUrls,
extractDomainFromUrl,
downloadAllSourceMaps,
}