All files / lib/internal/modules/esm get_source.js

91.18% Statements 31/34
77.78% Branches 7/9
100% Functions 1/1
91.18% Lines 31/34

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 35142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 251x 251x 251x 239x 239x 237x 251x 12x 12x     12x 12x 12x 12x 12x   251x 142x  
'use strict';
 
const { Buffer } = require('buffer');
 
const fs = require('fs');
const { URL } = require('url');
const { promisify } = require('internal/util');
const {
  ERR_INVALID_URL,
  ERR_INVALID_URL_SCHEME,
} = require('internal/errors').codes;
const readFileAsync = promisify(fs.readFile);
 
const DATA_URL_PATTERN = /^[^/]+\/[^,;]+(?:[^,]*?)(;base64)?,([\s\S]*)$/;
 
async function defaultGetSource(url, { format } = {}, defaultGetSource) {
  const parsed = new URL(url);
  if (parsed.protocol === 'file:') {
    return {
      source: await readFileAsync(parsed)
    };
  } else if (parsed.protocol === 'data:') {
    const match = DATA_URL_PATTERN.exec(parsed.pathname);
    if (!match) {
      throw new ERR_INVALID_URL(url);
    }
    const [ , base64, body ] = match;
    return {
      source: Buffer.from(body, base64 ? 'base64' : 'utf8')
    };
  }
  throw new ERR_INVALID_URL_SCHEME(['file', 'data']);
}
exports.defaultGetSource = defaultGetSource;