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