util.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. /**
  8. * This is a helper function for getting values from parameter/options
  9. * objects.
  10. *
  11. * @param args The object we are extracting values from
  12. * @param name The name of the property we are getting.
  13. * @param defaultValue An optional value to return if the property is missing
  14. * from the object. If this is not specified and the property is missing, an
  15. * error will be thrown.
  16. */
  17. function getArg(aArgs, aName, aDefaultValue) {
  18. if (aName in aArgs) {
  19. return aArgs[aName]
  20. } else if (arguments.length === 3) {
  21. return aDefaultValue
  22. }
  23. throw new Error('"' + aName + '" is a required argument.')
  24. }
  25. exports.getArg = getArg
  26. const urlRegexp =
  27. /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/
  28. const dataUrlRegexp = /^data:.+\,.+$/
  29. function urlParse(aUrl) {
  30. const match = aUrl.match(urlRegexp)
  31. if (!match) {
  32. return null
  33. }
  34. return {
  35. scheme: match[1],
  36. auth: match[2],
  37. host: match[3],
  38. port: match[4],
  39. path: match[5],
  40. }
  41. }
  42. exports.urlParse = urlParse
  43. function urlGenerate(aParsedUrl) {
  44. let url = ''
  45. if (aParsedUrl.scheme) {
  46. url += aParsedUrl.scheme + ':'
  47. }
  48. url += '//'
  49. if (aParsedUrl.auth) {
  50. url += aParsedUrl.auth + '@'
  51. }
  52. if (aParsedUrl.host) {
  53. url += aParsedUrl.host
  54. }
  55. if (aParsedUrl.port) {
  56. url += ':' + aParsedUrl.port
  57. }
  58. if (aParsedUrl.path) {
  59. url += aParsedUrl.path
  60. }
  61. return url
  62. }
  63. exports.urlGenerate = urlGenerate
  64. const MAX_CACHED_INPUTS = 32
  65. /**
  66. * Takes some function `f(input) -> result` and returns a memoized version of
  67. * `f`.
  68. *
  69. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  70. * memoization is a dumb-simple, linear least-recently-used cache.
  71. */
  72. function lruMemoize(f) {
  73. const cache = []
  74. return function (input) {
  75. for (let i = 0; i < cache.length; i++) {
  76. if (cache[i].input === input) {
  77. const temp = cache[0]
  78. cache[0] = cache[i]
  79. cache[i] = temp
  80. return cache[0].result
  81. }
  82. }
  83. const result = f(input)
  84. cache.unshift({
  85. input,
  86. result,
  87. })
  88. if (cache.length > MAX_CACHED_INPUTS) {
  89. cache.pop()
  90. }
  91. return result
  92. }
  93. }
  94. /**
  95. * Normalizes a path, or the path portion of a URL:
  96. *
  97. * - Replaces consecutive slashes with one slash.
  98. * - Removes unnecessary '.' parts.
  99. * - Removes unnecessary '<dir>/..' parts.
  100. *
  101. * Based on code in the Node.js 'path' core module.
  102. *
  103. * @param aPath The path or url to normalize.
  104. */
  105. const normalize = lruMemoize(function normalize(aPath) {
  106. let path = aPath
  107. const url = urlParse(aPath)
  108. if (url) {
  109. if (!url.path) {
  110. return aPath
  111. }
  112. path = url.path
  113. }
  114. const isAbsolute = exports.isAbsolute(path)
  115. // Split the path into parts between `/` characters. This is much faster than
  116. // using `.split(/\/+/g)`.
  117. const parts = []
  118. let start = 0
  119. let i = 0
  120. while (true) {
  121. start = i
  122. i = path.indexOf('/', start)
  123. if (i === -1) {
  124. parts.push(path.slice(start))
  125. break
  126. } else {
  127. parts.push(path.slice(start, i))
  128. while (i < path.length && path[i] === '/') {
  129. i++
  130. }
  131. }
  132. }
  133. let up = 0
  134. for (i = parts.length - 1; i >= 0; i--) {
  135. const part = parts[i]
  136. if (part === '.') {
  137. parts.splice(i, 1)
  138. } else if (part === '..') {
  139. up++
  140. } else if (up > 0) {
  141. if (part === '') {
  142. // The first part is blank if the path is absolute. Trying to go
  143. // above the root is a no-op. Therefore we can remove all '..' parts
  144. // directly after the root.
  145. parts.splice(i + 1, up)
  146. up = 0
  147. } else {
  148. parts.splice(i, 2)
  149. up--
  150. }
  151. }
  152. }
  153. path = parts.join('/')
  154. if (path === '') {
  155. path = isAbsolute ? '/' : '.'
  156. }
  157. if (url) {
  158. url.path = path
  159. return urlGenerate(url)
  160. }
  161. return path
  162. })
  163. exports.normalize = normalize
  164. /**
  165. * Joins two paths/URLs.
  166. *
  167. * @param aRoot The root path or URL.
  168. * @param aPath The path or URL to be joined with the root.
  169. *
  170. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  171. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  172. * first.
  173. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  174. * is updated with the result and aRoot is returned. Otherwise the result
  175. * is returned.
  176. * - If aPath is absolute, the result is aPath.
  177. * - Otherwise the two paths are joined with a slash.
  178. * - Joining for example 'http://' and 'www.example.com' is also supported.
  179. */
  180. function join(aRoot, aPath) {
  181. if (aRoot === '') {
  182. aRoot = '.'
  183. }
  184. if (aPath === '') {
  185. aPath = '.'
  186. }
  187. const aPathUrl = urlParse(aPath)
  188. const aRootUrl = urlParse(aRoot)
  189. if (aRootUrl) {
  190. aRoot = aRootUrl.path || '/'
  191. }
  192. // `join(foo, '//www.example.org')`
  193. if (aPathUrl && !aPathUrl.scheme) {
  194. if (aRootUrl) {
  195. aPathUrl.scheme = aRootUrl.scheme
  196. }
  197. return urlGenerate(aPathUrl)
  198. }
  199. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  200. return aPath
  201. }
  202. // `join('http://', 'www.example.com')`
  203. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  204. aRootUrl.host = aPath
  205. return urlGenerate(aRootUrl)
  206. }
  207. const joined =
  208. aPath.charAt(0) === '/'
  209. ? aPath
  210. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath)
  211. if (aRootUrl) {
  212. aRootUrl.path = joined
  213. return urlGenerate(aRootUrl)
  214. }
  215. return joined
  216. }
  217. exports.join = join
  218. exports.isAbsolute = function (aPath) {
  219. return aPath.charAt(0) === '/' || urlRegexp.test(aPath)
  220. }
  221. /**
  222. * Make a path relative to a URL or another path.
  223. *
  224. * @param aRoot The root path or URL.
  225. * @param aPath The path or URL to be made relative to aRoot.
  226. */
  227. function relative(aRoot, aPath) {
  228. if (aRoot === '') {
  229. aRoot = '.'
  230. }
  231. aRoot = aRoot.replace(/\/$/, '')
  232. // It is possible for the path to be above the root. In this case, simply
  233. // checking whether the root is a prefix of the path won't work. Instead, we
  234. // need to remove components from the root one by one, until either we find
  235. // a prefix that fits, or we run out of components to remove.
  236. let level = 0
  237. while (aPath.indexOf(aRoot + '/') !== 0) {
  238. const index = aRoot.lastIndexOf('/')
  239. if (index < 0) {
  240. return aPath
  241. }
  242. // If the only part of the root that is left is the scheme (i.e. http://,
  243. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  244. // have exhausted all components, so the path is not relative to the root.
  245. aRoot = aRoot.slice(0, index)
  246. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  247. return aPath
  248. }
  249. ++level
  250. }
  251. // Make sure we add a "../" for each component we removed from the root.
  252. return Array(level + 1).join('../') + aPath.substr(aRoot.length + 1)
  253. }
  254. exports.relative = relative
  255. const supportsNullProto = (function () {
  256. const obj = Object.create(null)
  257. return !('__proto__' in obj)
  258. })()
  259. function identity(s) {
  260. return s
  261. }
  262. /**
  263. * Because behavior goes wacky when you set `__proto__` on objects, we
  264. * have to prefix all the strings in our set with an arbitrary character.
  265. *
  266. * See https://github.com/mozilla/source-map/pull/31 and
  267. * https://github.com/mozilla/source-map/issues/30
  268. *
  269. * @param String aStr
  270. */
  271. function toSetString(aStr) {
  272. if (isProtoString(aStr)) {
  273. return '$' + aStr
  274. }
  275. return aStr
  276. }
  277. exports.toSetString = supportsNullProto ? identity : toSetString
  278. function fromSetString(aStr) {
  279. if (isProtoString(aStr)) {
  280. return aStr.slice(1)
  281. }
  282. return aStr
  283. }
  284. exports.fromSetString = supportsNullProto ? identity : fromSetString
  285. function isProtoString(s) {
  286. if (!s) {
  287. return false
  288. }
  289. const length = s.length
  290. if (length < 9 /* "__proto__".length */) {
  291. return false
  292. }
  293. /* eslint-disable no-multi-spaces */
  294. if (
  295. s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  296. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  297. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  298. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  299. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  300. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  301. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  302. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  303. s.charCodeAt(length - 9) !== 95 /* '_' */
  304. ) {
  305. return false
  306. }
  307. /* eslint-enable no-multi-spaces */
  308. for (let i = length - 10; i >= 0; i--) {
  309. if (s.charCodeAt(i) !== 36 /* '$' */) {
  310. return false
  311. }
  312. }
  313. return true
  314. }
  315. /**
  316. * Comparator between two mappings where the original positions are compared.
  317. *
  318. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  319. * mappings with the same original source/line/column, but different generated
  320. * line and column the same. Useful when searching for a mapping with a
  321. * stubbed out mapping.
  322. */
  323. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  324. let cmp = strcmp(mappingA.source, mappingB.source)
  325. if (cmp !== 0) {
  326. return cmp
  327. }
  328. cmp = mappingA.originalLine - mappingB.originalLine
  329. if (cmp !== 0) {
  330. return cmp
  331. }
  332. cmp = mappingA.originalColumn - mappingB.originalColumn
  333. if (cmp !== 0 || onlyCompareOriginal) {
  334. return cmp
  335. }
  336. cmp = mappingA.generatedColumn - mappingB.generatedColumn
  337. if (cmp !== 0) {
  338. return cmp
  339. }
  340. cmp = mappingA.generatedLine - mappingB.generatedLine
  341. if (cmp !== 0) {
  342. return cmp
  343. }
  344. return strcmp(mappingA.name, mappingB.name)
  345. }
  346. exports.compareByOriginalPositions = compareByOriginalPositions
  347. /**
  348. * Comparator between two mappings with deflated source and name indices where
  349. * the generated positions are compared.
  350. *
  351. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  352. * mappings with the same generated line and column, but different
  353. * source/name/original line and column the same. Useful when searching for a
  354. * mapping with a stubbed out mapping.
  355. */
  356. function compareByGeneratedPositionsDeflated(
  357. mappingA,
  358. mappingB,
  359. onlyCompareGenerated
  360. ) {
  361. let cmp = mappingA.generatedLine - mappingB.generatedLine
  362. if (cmp !== 0) {
  363. return cmp
  364. }
  365. cmp = mappingA.generatedColumn - mappingB.generatedColumn
  366. if (cmp !== 0 || onlyCompareGenerated) {
  367. return cmp
  368. }
  369. cmp = strcmp(mappingA.source, mappingB.source)
  370. if (cmp !== 0) {
  371. return cmp
  372. }
  373. cmp = mappingA.originalLine - mappingB.originalLine
  374. if (cmp !== 0) {
  375. return cmp
  376. }
  377. cmp = mappingA.originalColumn - mappingB.originalColumn
  378. if (cmp !== 0) {
  379. return cmp
  380. }
  381. return strcmp(mappingA.name, mappingB.name)
  382. }
  383. exports.compareByGeneratedPositionsDeflated =
  384. compareByGeneratedPositionsDeflated
  385. function strcmp(aStr1, aStr2) {
  386. if (aStr1 === aStr2) {
  387. return 0
  388. }
  389. if (aStr1 === null) {
  390. return 1 // aStr2 !== null
  391. }
  392. if (aStr2 === null) {
  393. return -1 // aStr1 !== null
  394. }
  395. if (aStr1 > aStr2) {
  396. return 1
  397. }
  398. return -1
  399. }
  400. /**
  401. * Comparator between two mappings with inflated source and name strings where
  402. * the generated positions are compared.
  403. */
  404. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  405. let cmp = mappingA.generatedLine - mappingB.generatedLine
  406. if (cmp !== 0) {
  407. return cmp
  408. }
  409. cmp = mappingA.generatedColumn - mappingB.generatedColumn
  410. if (cmp !== 0) {
  411. return cmp
  412. }
  413. cmp = strcmp(mappingA.source, mappingB.source)
  414. if (cmp !== 0) {
  415. return cmp
  416. }
  417. cmp = mappingA.originalLine - mappingB.originalLine
  418. if (cmp !== 0) {
  419. return cmp
  420. }
  421. cmp = mappingA.originalColumn - mappingB.originalColumn
  422. if (cmp !== 0) {
  423. return cmp
  424. }
  425. return strcmp(mappingA.name, mappingB.name)
  426. }
  427. exports.compareByGeneratedPositionsInflated =
  428. compareByGeneratedPositionsInflated
  429. /**
  430. * Strip any JSON XSSI avoidance prefix from the string (as documented
  431. * in the source maps specification), and then parse the string as
  432. * JSON.
  433. */
  434. function parseSourceMapInput(str) {
  435. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''))
  436. }
  437. exports.parseSourceMapInput = parseSourceMapInput
  438. /**
  439. * Compute the URL of a source given the the source root, the source's
  440. * URL, and the source map's URL.
  441. */
  442. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  443. sourceURL = sourceURL || ''
  444. if (sourceRoot) {
  445. // This follows what Chrome does.
  446. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  447. sourceRoot += '/'
  448. }
  449. // The spec says:
  450. // Line 4: An optional source root, useful for relocating source
  451. // files on a server or removing repeated values in the
  452. // “sources” entry. This value is prepended to the individual
  453. // entries in the “source” field.
  454. sourceURL = sourceRoot + sourceURL
  455. }
  456. // Historically, SourceMapConsumer did not take the sourceMapURL as
  457. // a parameter. This mode is still somewhat supported, which is why
  458. // this code block is conditional. However, it's preferable to pass
  459. // the source map URL to SourceMapConsumer, so that this function
  460. // can implement the source URL resolution algorithm as outlined in
  461. // the spec. This block is basically the equivalent of:
  462. // new URL(sourceURL, sourceMapURL).toString()
  463. // ... except it avoids using URL, which wasn't available in the
  464. // older releases of node still supported by this library.
  465. //
  466. // The spec says:
  467. // If the sources are not absolute URLs after prepending of the
  468. // “sourceRoot”, the sources are resolved relative to the
  469. // SourceMap (like resolving script src in a html document).
  470. if (sourceMapURL) {
  471. const parsed = urlParse(sourceMapURL)
  472. if (!parsed) {
  473. throw new Error('sourceMapURL could not be parsed')
  474. }
  475. if (parsed.path) {
  476. // Strip the last path component, but keep the "/".
  477. const index = parsed.path.lastIndexOf('/')
  478. if (index >= 0) {
  479. parsed.path = parsed.path.substring(0, index + 1)
  480. }
  481. }
  482. sourceURL = join(urlGenerate(parsed), sourceURL)
  483. }
  484. return normalize(sourceURL)
  485. }
  486. exports.computeSourceURL = computeSourceURL