Skip to content

Instantly share code, notes, and snippets.

@rarecoil
Created June 12, 2019 00:49
Show Gist options
  • Save rarecoil/654142796505034d0c5af26e7a2c9b9e to your computer and use it in GitHub Desktop.
Save rarecoil/654142796505034d0c5af26e7a2c9b9e to your computer and use it in GitHub Desktop.
Reconstruct source files from a webpack-made sourceMap
#!/usr/bin/env python3
import json
import os
import sys
def main():
if len(sys.argv) != 2:
print("Usage: webpack_source_reconstruct.py /path/to/source.map")
sys.exit(1)
sourcemap = os.path.abspath(sys.argv[1])
if not os.path.isfile(sourcemap):
print("Sourcemap is not file")
sys.exit(1)
try:
with open(sourcemap, 'r') as f:
sourcemap = json.load(f)
if 'sourcesContent' not in sourcemap or len(sourcemap['sourcesContent']) == 0:
print("Sourcemap does not contain content.")
sys.exit(2)
idx = 0
if 'sources' in sourcemap:
lsources = len(sourcemap['sources'])
lcontent = len(sourcemap['sourcesContent'])
if lsources != lcontent:
print("Warning: sources and sourcesContent do not agree, filenames may be wrong")
for source in sourcemap['sources']:
filename = source.replace("webpack://", "")
filename = filename.replace("/", "-").replace("\\", "-")
if filename[0] == '.':
filename = filename[1:]
if not os.path.isdir("output/"):
os.mkdir("output/", 0o755)
try:
content = sourcemap['sourcesContent'][idx]
idx += 1
print("Writing %s" % filename)
with open("output/"+filename, 'w') as sf:
sf.write(content)
except IndexError:
print("Reached end of sourcesContent, finishing incompletely")
sys.exit(1)
except:
raise
print("Sourcemap failed to parse.")
sys.exit(2)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment