1 | 'use strict';
|
---|
2 |
|
---|
3 | var path = require('path'),
|
---|
4 | fs = require('fs');
|
---|
5 |
|
---|
6 | /**
|
---|
7 | * Codec for relative paths with respect to the source directory.
|
---|
8 | * @type {{name:string, decode: function, encode: function, root: function}}
|
---|
9 | */
|
---|
10 | module.exports = {
|
---|
11 | name : 'sourceRelative',
|
---|
12 | decode: decode,
|
---|
13 | encode: encode,
|
---|
14 | root : root
|
---|
15 | };
|
---|
16 |
|
---|
17 | /**
|
---|
18 | * Decode the given uri.
|
---|
19 | * Any path without leading slash is tested against source directory.
|
---|
20 | * @this {{options: object}} A loader or compilation
|
---|
21 | * @param {string} uri A source uri to decode
|
---|
22 | * @returns {boolean|string} False where unmatched else the decoded path
|
---|
23 | */
|
---|
24 | function decode(uri) {
|
---|
25 | /* jshint validthis:true */
|
---|
26 | var base = !uri.startsWith('/') && this.context,
|
---|
27 | absFile = !!base && path.normalize(path.join(base, uri)),
|
---|
28 | isValid = !!absFile && fs.existsSync(absFile) && fs.statSync(absFile).isFile();
|
---|
29 | return isValid && absFile;
|
---|
30 | }
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * Encode the given file path.
|
---|
34 | * @this {{options: object}} A loader or compilation
|
---|
35 | * @param {string} absolute An absolute file path to encode
|
---|
36 | * @returns {string} A uri without leading slash
|
---|
37 | */
|
---|
38 | function encode(absolute) {
|
---|
39 | /* jshint validthis:true */
|
---|
40 | return path.relative(this.context, absolute);
|
---|
41 | }
|
---|
42 |
|
---|
43 | /**
|
---|
44 | * The source-map root where relevant.
|
---|
45 | * @this {{options: object}} A loader or compilation
|
---|
46 | * @returns {string|undefined} The source-map root applicable to any encoded uri
|
---|
47 | */
|
---|
48 | function root() {
|
---|
49 | /* jshint validthis:true */
|
---|
50 | return this.context;
|
---|
51 | }
|
---|