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