[
  {
    "path": ".babelrc",
    "content": "{\n  \"presets\": [\"@babel/preset-env\"],\n  \"plugins\": [\"@babel/plugin-transform-runtime\"]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "### Intellij ###\n# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm\n# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839\n\n# User-specific stuff\n.idea/**/workspace.xml\n.idea/**/tasks.xml\n.idea/**/usage.statistics.xml\n.idea/**/dictionaries\n.idea/**/shelf\n\n# Generated files\n.idea/**/contentModel.xml\n\n# Sensitive or high-churn files\n.idea/**/dataSources/\n.idea/**/dataSources.ids\n.idea/**/dataSources.local.xml\n.idea/**/sqlDataSources.xml\n.idea/**/dynamic.xml\n.idea/**/uiDesigner.xml\n.idea/**/dbnavigator.xml\n\n# Gradle\n.idea/**/gradle.xml\n.idea/**/libraries\n\n# Gradle and Maven with auto-import\n# When using Gradle or Maven with auto-import, you should exclude module files,\n# since they will be recreated, and may cause churn.  Uncomment if using\n# auto-import.\n# .idea/modules.xml\n# .idea/*.iml\n# .idea/modules\n\n# CMake\ncmake-build-*/\n\n# Mongo Explorer plugin\n.idea/**/mongoSettings.xml\n\n# File-based project format\n*.iws\n\n# IntelliJ\nout/\n\n# mpeltonen/sbt-idea plugin\n.idea_modules/\n\n# JIRA plugin\natlassian-ide-plugin.xml\n\n# Cursive Clojure plugin\n.idea/replstate.xml\n\n# Crashlytics plugin (for Android Studio and IntelliJ)\ncom_crashlytics_export_strings.xml\ncrashlytics.properties\ncrashlytics-build.properties\nfabric.properties\n\n# Editor-based Rest Client\n.idea/httpRequests\n\n# Android studio 3.1+ serialized cache file\n.idea/caches/build_file_checksums.ser\n\n### Intellij Patch ###\n# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721\n\n# *.iml\n# modules.xml\n# .idea/misc.xml\n# *.ipr\n\n# Sonarlint plugin\n.idea/sonarlint\n\n### macOS ###\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n### Node ###\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\ntypings/\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n\n# next.js build output\n.next\n\n# nuxt.js build output\n.nuxt\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n#DynamoDB Local files\n.dynamodb/\n\n### Project ###\n# build folder\nbuild/\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"semi\": false,\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": "LICENCE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2016 Listen 1\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n\t<br>\n\t<br>\n\t<img width=\"126\" src=\"media/header.png\" alt=\"Save Page State\">\n  <h3>Save Page State</h3>\n\t<br>\n\t<br>\n</div>\n\n> A browser extension to save the state of a page for further analysis\n\n[![Chrome Web Store](https://img.shields.io/chrome-web-store/v/aokllhajmkihfihciggkmpgdhgecgaic.svg)](https://chrome.google.com/webstore/detail/save-page-state/aokllhajmkihfihciggkmpgdhgecgaic) ![](https://img.shields.io/david/vrtdev/save-page-state.svg) ![](https://img.shields.io/david/dev/vrtdev/save-page-state.svg)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE)\n\n## Highlights\n\n- [DOM Snapshot](#dom-snapshot)\n- [MHTML file](#mhtml-file)\n- [Screenshot](#screenshot)\n- [Metadata](#metadata)\n\n## Install\n\nInstall the extension from the [chrome web store](https://chrome.google.com/webstore/detail/save-page-state/aokllhajmkihfihciggkmpgdhgecgaic) or [firefox add-ons](https://addons.mozilla.org/nl/firefox/addon/save-page-state/).\n\nOr create a custom extension with this repo with limited access permission\n\n## Customize\n\n### Restrict Access Permission\n\nIn manifest.json (`/src/manifest.json`), replace `<all_urls>` with your own project URL pattern you wish to save the page states from.\n\n```javascript\n{\n\t...\n\t\"content_scripts\": [\n\t\t{\n\t\t\t\"matches\": [\"<all_urls>\"], // <- change this to your url pattern\n\t\t\t\"js\": [\"js/content.js\"]\n\t\t}\n\t],\n\t\"permissions\": [\"activeTab\", \"pageCapture\", \"<all_urls>\"]  // <- change this to your url pattern\n\t...\n}\n```\n\n### Install dependencies\n\n```\nnpm i\n```\n\n### Build\n\n```\nnpm run build\n```\n\nBuilds to `/build/prod`\n\n### Publish\n\n#### Chrome\n\nCreate a zip file from `/build/prod/chrome`\n[upload it to the chrome web store](https://developer.chrome.com/webstore/publish#upload-your-app).\n\n#### Firefox\n\nCreate a zip file from `/build/prod/firefox`\n[upload it to the firefox developer hub](https://addons.mozilla.org/nl/developers/).\n\n### Development\n\n```\nnpm run dev:chrome // builds to /build/dev/chrome\nnpm run dev:firefox // builds to /build/dev/firefox\n```\n\n## Features\n\n### DOM Snapshot\n\nAn HTML file containing the state of the DOM.\n\n### MHTML file (chrome only for now)\n\n> **Note** Firefox doesn't support saving an MHTML file natively yet.\n\nAn MHTML page with encapsulated resources, so you could immediately check the layout by opening the MHTML file in Chrome.\n\n### Screenshot\n\nA PNG image of the viewport.\n\n### Metadata\n\nText file with extra metadata useful for debugging with the exact same state.\n\n- **height**: viewport height\n- **width**: viewport width\n- **incognito**: is page loaded in incognito mode\n- **status**: page loading status\n- **title**: page title\n- **url**: page URL\n- **browser**: browser\n- **browserVersion**: browser version\n- **os**: operating system\n\n## Maintainer\n\n[![Wing Leung](https://github.com/wingleung.png?size=100)](https://github.com/wingleung)\n"
  },
  {
    "path": "config/config.js",
    "content": "const path = require('path')\n\nmodule.exports = {\n  entry: {\n    background: './src/js/background',\n    content: './src/js/content'\n  },\n  output: {\n    filename: './js/[name].js'\n  },\n  resolve: {\n    modules: [path.join(__dirname, 'src'), 'node_modules']\n  },\n  module: {\n    rules: [\n      {\n        test: /\\.js$/,\n        loaders: ['babel-loader'],\n        include: path.resolve(__dirname, '../src/js')\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "config/webpack.config.dev.js",
    "content": "const _ = require('lodash')\nconst path = require('path')\nconst CopyWebpackPlugin = require('copy-webpack-plugin')\nconst VersionFilePlugin = require('webpack-version-file-plugin')\n\nconst config = require('./config.js')\n\nmodule.exports = (env = { vendor: 'chrome' }) => _.merge({}, config, {\n  mode: 'development',\n\n  output: {\n    path: path.resolve(__dirname, `../build/dev/${env.vendor}`)\n  },\n\n  devtool: 'source-map',\n\n  plugins: [\n    new CopyWebpackPlugin([{ from: './src' }], {\n      ignore: ['js/**/*', 'manifest*.json', '.DS_Store'],\n      copyUnmodified: false\n    }),\n    new VersionFilePlugin({\n      packageFile: path.resolve(__dirname, '../package.json'),\n      template: path.resolve(__dirname, `../src/manifest.${env.vendor}.json`),\n      outputFile: path.resolve(__dirname, `../build/dev/${env.vendor}/manifest.json`)\n    })\n  ],\n\n  watch: true\n})\n"
  },
  {
    "path": "config/webpack.config.prod.js",
    "content": "const _ = require('lodash')\nconst path = require('path')\nconst webpack = require('webpack')\nconst CopyWebpackPlugin = require('copy-webpack-plugin')\nconst VersionFilePlugin = require('webpack-version-file-plugin')\nconst UglifyJsPlugin = require('uglifyjs-webpack-plugin')\n\nconst config = require('./config.js')\n\nmodule.exports = (env = { vendor: 'chrome' }) => _.merge({}, config, {\n  mode: 'production',\n\n  output: {\n    path: path.resolve(__dirname, `../build/prod/${env.vendor}`)\n  },\n\n  optimization: {\n    minimizer: [new UglifyJsPlugin()]\n  },\n\n  plugins: [\n    new CopyWebpackPlugin([{ from: './src' }], {\n      ignore: ['js/**/*', 'manifest*.json', '.DS_Store'],\n      copyUnmodified: true\n    }),\n    new VersionFilePlugin({\n      packageFile: path.resolve(__dirname, '../package.json'),\n      template: path.resolve(__dirname, `../src/manifest.${env.vendor}.json`),\n      outputFile: path.resolve(__dirname, `../build/prod/${env.vendor}/manifest.json`)\n    }),\n    new webpack.DefinePlugin({ 'process.env.NODE_ENV': '\"production\"' })\n  ]\n})\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"save-page-state\",\n  \"version\": \"1.1.1\",\n  \"description\": \"Extension to save a state of a page for remote analysis\",\n  \"scripts\": {\n    \"build\": \"npm run build:chrome && npm run build:firefox\",\n    \"build:chrome\": \"mkdir -p ./build/prod && mkdir -p ./build/prod/chrome && npx webpack --env.vendor=chrome --config ./config/webpack.config.prod.js\",\n    \"build:firefox\": \"mkdir -p ./build/prod && mkdir -p ./build/prod/firefox && npx webpack --env.vendor=firefox --config ./config/webpack.config.prod.js\",\n    \"dev:chrome\": \"mkdir -p ./build/dev && mkdir -p ./build/dev/chrome && npx webpack --env.vendor=chrome --config ./config/webpack.config.dev.js\",\n    \"dev:firefox\": \"mkdir -p ./build/dev && mkdir -p ./build/dev/firefox  && npx webpack --env.vendor=firefox --config ./config/webpack.config.dev.js\",\n    \"precommit\": \"lint-staged\"\n  },\n  \"lint-staged\": {\n    \"*.{js,json,md}\": [\n      \"prettier --write\",\n      \"git add\"\n    ]\n  },\n  \"author\": \"Wing Leung\",\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.4.4\",\n    \"@babel/plugin-transform-runtime\": \"^7.4.4\",\n    \"@babel/preset-env\": \"^7.4.4\",\n    \"@babel/runtime\": \"^7.4.4\",\n    \"babel-loader\": \"^8.0.4\",\n    \"copy-webpack-plugin\": \"^4.6.0\",\n    \"husky\": \"^1.2.0\",\n    \"lint-staged\": \"^8.1.0\",\n    \"lodash\": \"^4.17.11\",\n    \"prettier\": \"^1.15.3\",\n    \"uglifyjs-webpack-plugin\": \"^2.0.1\",\n    \"webpack\": \"^4.27.1\",\n    \"webpack-cli\": \"^3.1.2\",\n    \"webpack-version-file-plugin\": \"github:mvanede/webpack-version-file-plugin\"\n  },\n  \"dependencies\": {\n    \"detect-browser\": \"^4.5.0\",\n    \"file-saver\": \"^2.0.2\",\n    \"jszip\": \"^3.2.1\"\n  }\n}\n"
  },
  {
    "path": "src/js/background.js",
    "content": "import JSZip from 'jszip'\nimport saveAs from 'file-saver'\n\nimport {\n  getTimestamp,\n  getBrowserData,\n  formatJSONtoPlain,\n  base64toBlob\n} from './helpers'\n\nwindow.browser = window.browser || window.chrome\n\nlet browserData = null\nlet pageTitle = null\nlet currentTab = null\nlet metaData = null\n\nconst getFileName = () =>\n  `snapshot_${getTimestamp()}_${pageTitle.replace(\n    /[<>:\"\\/\\\\|?*\\x00-\\x1F ]/g,\n    '_'\n  )}`\n\nconst getImageBlob = image =>\n  base64toBlob(image.replace(/^data:image\\/\\w+;base64,/, ''), 'image/jpeg')\n\nconst captureVisibleTab = () =>\n  browserData.isChrome\n    ? new Promise(resolve => {\n        browser.tabs.captureVisibleTab(null, {}, image => resolve(image))\n      })\n    : browser.tabs.captureVisibleTab()\n\nconst generateMHTML = () =>\n  new Promise(resolve => {\n    chrome.pageCapture.saveAsMHTML({ tabId: currentTab }, htmlData => {\n      resolve(htmlData)\n    })\n  })\n\nconst downloadFile = (blob, fileName) => {\n  if (browserData.isChrome) {\n    saveAs(blob, fileName)\n  } else {\n    browser.tabs.sendMessage(currentTab, {\n      action: 'saveFile',\n      file: {\n        content: blob,\n        name: fileName\n      }\n    })\n  }\n}\n\nconst generatePageStateZip = async dom => {\n  const file = new Blob([dom], { type: 'text/html' })\n  const fileName = getFileName()\n\n  const zipArchive = new JSZip()\n  const zipRoot = zipArchive.folder(fileName)\n\n  zipRoot.file('dom/snapshot.html', file)\n  zipRoot.file('metadata.txt', formatJSONtoPlain(metaData))\n\n  const image = await captureVisibleTab()\n  zipRoot.file('screenshot.png', getImageBlob(image))\n\n  if (browserData.isChrome) {\n    const htmlData = await generateMHTML()\n    zipRoot.file('layout/snapshot.mhtml', htmlData)\n  }\n\n  const blob = await zipArchive.generateAsync({ type: 'blob' })\n  downloadFile(blob, `${fileName}.zip`)\n}\n\nconst savePageState = tab => {\n  browserData = getBrowserData()\n  pageTitle = tab.title\n  currentTab = tab.id\n  metaData = {\n    height: tab.height,\n    width: tab.width,\n    incognito: tab.incognito,\n    status: tab.status,\n    title: tab.title,\n    url: tab.url,\n    browser: browserData.name,\n    browserVersion: browserData.version,\n    os: browserData.os\n  }\n\n  browser.tabs.sendMessage(tab.id, { action: 'captureDOM' })\n}\n\nconst handleBackgroundAction = ({ action, dom }) => {\n  switch (action) {\n    case 'captureDOM':\n      generatePageStateZip(dom).then(() => console.log('downloaded page state'))\n      break\n    default:\n      break\n  }\n}\n\nbrowser.browserAction.onClicked.addListener(savePageState)\n\nbrowser.runtime.onMessage.addListener(handleBackgroundAction)\n"
  },
  {
    "path": "src/js/content.js",
    "content": "import { DOMtoString } from './helpers'\n\nwindow.browser = window.browser || window.chrome\n\nconst click = node => {\n  try {\n    node.dispatchEvent(new MouseEvent('click'))\n  } catch (e) {\n    var evt = document.createEvent('MouseEvents')\n    evt.initMouseEvent(\n      'click',\n      true,\n      true,\n      window,\n      0,\n      0,\n      0,\n      80,\n      20,\n      false,\n      false,\n      false,\n      false,\n      0,\n      null\n    )\n    node.dispatchEvent(evt)\n  }\n}\n\nconst saveAs = (blob, name, opts) => {\n  var URL = window.URL || window.webkitURL\n  var a = document.createElement('a')\n  name = name || blob.name || 'download'\n\n  a.download = name\n  a.rel = 'noopener' // tabnabbing\n\n  // Support blobs\n  a.href = URL.createObjectURL(blob)\n  setTimeout(function() {\n    URL.revokeObjectURL(a.href)\n  }, 4e4) // 40s\n  setTimeout(function() {\n    click(a)\n  }, 0)\n}\n\nconst handlePageAction = req => {\n  switch (req.action) {\n    case 'captureDOM':\n      browser.runtime.sendMessage({\n        action: 'captureDOM',\n        dom: DOMtoString(document)\n      })\n      break\n    case 'saveFile':\n      console.log('saving file...', req)\n      saveAs(req.file.content, req.file.name)\n      break\n    default:\n      break\n  }\n}\n\nbrowser.runtime.onMessage.addListener(handlePageAction)\n"
  },
  {
    "path": "src/js/helpers/index.js",
    "content": "const { detect } = require('detect-browser')\n\nconst getTimestamp = () => {\n  const time = new Date()\n  const months = [\n    'jan',\n    'feb',\n    'mar',\n    'apr',\n    'may',\n    'jun',\n    'jul',\n    'aug',\n    'sep',\n    'oct',\n    'nov',\n    'dec'\n  ]\n  const month = months[time.getMonth()]\n  const date = time.getDate()\n  let hour = time.getHours()\n  hour = hour < 10 ? `0${hour}` : hour\n  let min = time.getMinutes()\n  min = min < 10 ? `0${min}` : min\n  let sec = time.getSeconds()\n  sec = sec < 10 ? `0${sec}` : sec\n\n  return `${date + month}_${hour}${min}${sec}`\n}\n\nconst getBrowserData = () => {\n  const browserData = detect() || {}\n\n  return {\n    ...browserData,\n    isChrome: browserData.name === 'chrome'\n  }\n}\n\nconst formatJSONtoPlain = jsonData => {\n  let plainTxt = ''\n\n  for (const name in jsonData) {\n    plainTxt = `${plainTxt + name}: ${jsonData[name]}\\n`\n  }\n\n  return plainTxt\n}\n\nconst base64toBlob = (b64Data, contentType = '', sliceSize = 512) => {\n  const byteCharacters = atob(b64Data)\n  const byteArrays = []\n\n  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {\n    const slice = byteCharacters.slice(offset, offset + sliceSize)\n\n    const byteNumbers = new Array(slice.length)\n    for (let i = 0; i < slice.length; i++) {\n      byteNumbers[i] = slice.charCodeAt(i)\n    }\n\n    const byteArray = new Uint8Array(byteNumbers)\n\n    byteArrays.push(byteArray)\n  }\n  const blob = new Blob(byteArrays, { type: contentType })\n  return blob\n}\n\nconst DOMtoString = document_root => {\n  var html = '',\n    node = document_root.firstChild\n  while (node) {\n    switch (node.nodeType) {\n      case Node.ELEMENT_NODE:\n        html += node.outerHTML\n        break\n      case Node.TEXT_NODE:\n        html += node.nodeValue\n        break\n      case Node.CDATA_SECTION_NODE:\n        html += '<![CDATA[' + node.nodeValue + ']]>'\n        break\n      case Node.COMMENT_NODE:\n        html += '<!--' + node.nodeValue + '-->'\n        break\n      case Node.DOCUMENT_TYPE_NODE:\n        // (X)HTML documents are identified by public identifiers\n        html +=\n          '<!DOCTYPE ' +\n          node.name +\n          (node.publicId ? ' PUBLIC \"' + node.publicId + '\"' : '') +\n          (!node.publicId && node.systemId ? ' SYSTEM' : '') +\n          (node.systemId ? ' \"' + node.systemId + '\"' : '') +\n          '>\\n'\n        break\n    }\n    node = node.nextSibling\n  }\n  return html\n}\n\nexport {\n  getTimestamp,\n  getBrowserData,\n  formatJSONtoPlain,\n  base64toBlob,\n  DOMtoString\n}\n"
  },
  {
    "path": "src/manifest.chrome.json",
    "content": "{\n  \"name\": \"Save Page State\",\n  \"version\": \"<%= package.version %>\",\n  \"description\": \"<%= package.description %>\",\n  \"manifest_version\": 2,\n  \"icons\": { \"128\": \"images/icon.png\" },\n  \"browser_action\": {\n    \"default_icon\": \"images/icon.png\"\n  },\n  \"background\": { \"scripts\": [\"js/background.js\"] },\n  \"content_scripts\": [\n    {\n      \"matches\": [\"<all_urls>\"],\n      \"js\": [\"js/content.js\"]\n    }\n  ],\n  \"permissions\": [\"<all_urls>\", \"activeTab\", \"pageCapture\"]\n}\n"
  },
  {
    "path": "src/manifest.firefox.json",
    "content": "{\n  \"name\": \"Save Page State\",\n  \"version\": \"<%= package.version %>\",\n  \"description\": \"<%= package.description %>\",\n  \"manifest_version\": 2,\n  \"icons\": { \"128\": \"images/icon.png\" },\n  \"browser_action\": {\n    \"default_icon\": \"images/icon.png\"\n  },\n  \"background\": { \"scripts\": [\"js/background.js\"] },\n  \"content_scripts\": [\n    {\n      \"matches\": [\"<all_urls>\"],\n      \"js\": [\"js/content.js\"]\n    }\n  ],\n  \"permissions\": [\"<all_urls>\", \"activeTab\"]\n}\n"
  }
]