All files / lib/internal/source_map source_map_cache.js

96.33% Statements 236/245
86.79% Branches 46/53
100% Functions 12/12
96.33% Lines 236/245

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 246144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 111x 111x 111x 111x 144x 144x 144x 144x 545x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 144x 63692x 63692x 4886x 4886x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 4886x 63692x 63692x 144x 30221x 30221x 30221x 30221x 30221x 30221x 513x 513x 513x 513x 513x 29708x 29708x 29708x 29708x 30221x 80x 80x 80x 76x 76x 76x 76x 76x 76x 80x 4x 4x 4x 4x 4x 4x 4x 4x 80x 30221x 144x 80x 80x 80x 80x 80x 13x 80x 6x 6x 80x 80x 61x 61x 61x 61x 61x 80x 144x 144x 144x 144x 80x 80x 80x 80x 80x 56894x 80x 80x 144x 61x 61x 61x 61x 61x 61x 51x 51x 51x 61x 144x 144x 144x 13x 13x 13x 13x 13x 13x 12x 12x 12x 12x 12x 12x 1x 1x 1x 13x 1x 1x 1x 13x 144x 144x 144x 144x 21x 21x 22x 22x 21x 21x 21x 21x 21x 21x 144x 144x 15x 15x 15x 10x 10x 15x 144x 144x 144x 144x 144x 144x 144x 144x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x   2x 144x 2x 2x             2x 144x 108x 108x 107x 107x 108x 14x 14x 105x 105x 104x 87x 87x 24x 24x 24x 24x 87x 104x 108x 16x 16x 89x 108x 144x 144x 144x 144x 144x 144x 144x 144x  
'use strict';
 
const {
  ArrayPrototypeMap,
  JSONParse,
  ObjectCreate,
  ObjectKeys,
  ObjectGetOwnPropertyDescriptor,
  ObjectPrototypeHasOwnProperty,
  RegExpPrototypeTest,
  SafeMap,
  StringPrototypeMatch,
  StringPrototypeSplit,
} = primordials;
 
function ObjectGetValueSafe(obj, key) {
  const desc = ObjectGetOwnPropertyDescriptor(obj, key);
  return ObjectPrototypeHasOwnProperty(desc, 'value') ? desc.value : undefined;
}
 
// See https://sourcemaps.info/spec.html for SourceMap V3 specification.
const { Buffer } = require('buffer');
let debug = require('internal/util/debuglog').debuglog('source_map', (fn) => {
  debug = fn;
});
const fs = require('fs');
const { getOptionValue } = require('internal/options');
const { IterableWeakMap } = require('internal/util/iterable_weak_map');
const {
  normalizeReferrerURL,
} = require('internal/modules/cjs/helpers');
// Since the CJS module cache is mutable, which leads to memory leaks when
// modules are deleted, we use a WeakMap so that the source map cache will
// be purged automatically:
const cjsSourceMapCache = new IterableWeakMap();
// The esm cache is not mutable, so we can use a Map without memory concerns:
const esmSourceMapCache = new SafeMap();
const { fileURLToPath, pathToFileURL, URL } = require('internal/url');
let SourceMap;
 
let sourceMapsEnabled;
function getSourceMapsEnabled() {
  if (sourceMapsEnabled === undefined) {
    sourceMapsEnabled = getOptionValue('--enable-source-maps');
    if (sourceMapsEnabled) {
      const {
        enableSourceMaps,
        setPrepareStackTraceCallback
      } = internalBinding('errors');
      const {
        prepareStackTrace
      } = require('internal/source_map/prepare_stack_trace');
      setPrepareStackTraceCallback(prepareStackTrace);
      enableSourceMaps();
    }
  }
  return sourceMapsEnabled;
}
 
function maybeCacheSourceMap(filename, content, cjsModuleInstance) {
  const sourceMapsEnabled = getSourceMapsEnabled();
  if (!(process.env.NODE_V8_COVERAGE || sourceMapsEnabled)) return;
  try {
    filename = normalizeReferrerURL(filename);
  } catch (err) {
    // This is most likely an [eval]-wrapper, which is currently not
    // supported.
    debug(err.stack);
    return;
  }
  const match = StringPrototypeMatch(
    content,
    /\/[*/]#\s+sourceMappingURL=(?<sourceMappingURL>[^\s]+)/
  );
  if (match) {
    const data = dataFromUrl(filename, match.groups.sourceMappingURL);
    const url = data ? null : match.groups.sourceMappingURL;
    if (cjsModuleInstance) {
      cjsSourceMapCache.set(cjsModuleInstance, {
        filename,
        lineLengths: lineLengths(content),
        data,
        url
      });
    } else {
      // If there is no cjsModuleInstance assume we are in a
      // "modules/esm" context.
      esmSourceMapCache.set(filename, {
        lineLengths: lineLengths(content),
        data,
        url
      });
    }
  }
}
 
function dataFromUrl(sourceURL, sourceMappingURL) {
  try {
    const url = new URL(sourceMappingURL);
    switch (url.protocol) {
      case 'data:':
        return sourceMapFromDataUrl(sourceURL, url.pathname);
      default:
        debug(`unknown protocol ${url.protocol}`);
        return null;
    }
  } catch (err) {
    debug(err.stack);
    // If no scheme is present, we assume we are dealing with a file path.
    const mapURL = new URL(sourceMappingURL, sourceURL).href;
    return sourceMapFromFile(mapURL);
  }
}
 
// Cache the length of each line in the file that a source map was extracted
// from. This allows translation from byte offset V8 coverage reports,
// to line/column offset Source Map V3.
function lineLengths(content) {
  // We purposefully keep \r as part of the line-length calculation, in
  // cases where there is a \r\n separator, so that this can be taken into
  // account in coverage calculations.
  return ArrayPrototypeMap(StringPrototypeSplit(content, /\n|\u2028|\u2029/), (line) => {
    return line.length;
  });
}
 
function sourceMapFromFile(mapURL) {
  try {
    const content = fs.readFileSync(fileURLToPath(mapURL), 'utf8');
    const data = JSONParse(content);
    return sourcesToAbsolute(mapURL, data);
  } catch (err) {
    debug(err.stack);
    return null;
  }
}
 
// data:[<mediatype>][;base64],<data> see:
// https://tools.ietf.org/html/rfc2397#section-2
function sourceMapFromDataUrl(sourceURL, url) {
  const [format, data] = StringPrototypeSplit(url, ',');
  const splitFormat = StringPrototypeSplit(format, ';');
  const contentType = splitFormat[0];
  const base64 = splitFormat[splitFormat.length - 1] === 'base64';
  if (contentType === 'application/json') {
    const decodedData = base64 ?
      Buffer.from(data, 'base64').toString('utf8') : data;
    try {
      const parsedData = JSONParse(decodedData);
      return sourcesToAbsolute(sourceURL, parsedData);
    } catch (err) {
      debug(err.stack);
      return null;
    }
  } else {
    debug(`unknown content-type ${contentType}`);
    return null;
  }
}
 
// If the sources are not absolute URLs after prepending of the "sourceRoot",
// the sources are resolved relative to the SourceMap (like resolving script
// src in a html document).
function sourcesToAbsolute(baseURL, data) {
  data.sources = data.sources.map((source) => {
    source = (data.sourceRoot || '') + source;
    return new URL(source, baseURL).href;
  });
  // The sources array is now resolved to absolute URLs, sourceRoot should
  // be updated to noop.
  data.sourceRoot = '';
  return data;
}
 
// Move source map from garbage collected module to alternate key.
function rekeySourceMap(cjsModuleInstance, newInstance) {
  const sourceMap = cjsSourceMapCache.get(cjsModuleInstance);
  if (sourceMap) {
    cjsSourceMapCache.set(newInstance, sourceMap);
  }
}
 
// WARNING: The `sourceMapCacheToObject` and `appendCJSCache` run during
// shutdown. In particular, they also run when Workers are terminated, making
// it important that they do not call out to any user-provided code, including
// built-in prototypes that might have been tampered with.
 
// Get serialized representation of source-map cache, this is used
// to persist a cache of source-maps to disk when NODE_V8_COVERAGE is enabled.
function sourceMapCacheToObject() {
  const obj = ObjectCreate(null);
 
  for (const { 0: k, 1: v } of esmSourceMapCache) {
    obj[k] = v;
  }
 
  appendCJSCache(obj);
 
  if (ObjectKeys(obj).length === 0) {
    return undefined;
  }
  return obj;
}
 
function appendCJSCache(obj) {
  for (const value of cjsSourceMapCache) {
    obj[ObjectGetValueSafe(value, 'filename')] = {
      lineLengths: ObjectGetValueSafe(value, 'lineLengths'),
      data: ObjectGetValueSafe(value, 'data'),
      url: ObjectGetValueSafe(value, 'url')
    };
  }
}
 
function findSourceMap(sourceURL) {
  if (!RegExpPrototypeTest(/^\w+:\/\//, sourceURL)) {
    sourceURL = pathToFileURL(sourceURL).href;
  }
  if (!SourceMap) {
    SourceMap = require('internal/source_map/source_map').SourceMap;
  }
  let sourceMap = esmSourceMapCache.get(sourceURL);
  if (sourceMap === undefined) {
    for (const value of cjsSourceMapCache) {
      const filename = ObjectGetValueSafe(value, 'filename');
      if (sourceURL === filename) {
        sourceMap = {
          data: ObjectGetValueSafe(value, 'data')
        };
      }
    }
  }
  if (sourceMap && sourceMap.data) {
    return new SourceMap(sourceMap.data);
  }
  return undefined;
}
 
module.exports = {
  findSourceMap,
  getSourceMapsEnabled,
  maybeCacheSourceMap,
  rekeySourceMap,
  sourceMapCacheToObject,
};