webpack/lib/RequestShortener.js

70 lines
2.4 KiB
JavaScript
Raw Normal View History

2013-01-31 01:49:25 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g;
const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g;
const SEPARATOR_REGEXP = /[/\\]$/;
const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g;
2017-07-02 07:18:29 +08:00
const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g;
const normalizeBackSlashDirection = (request) => {
return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/");
};
const createRegExpForPath = (path) => {
const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&");
return new RegExp(`(^|!)${regexpTypePartial}`, "g");
2017-07-01 04:07:02 +08:00
};
class RequestShortener {
constructor(directory) {
directory = normalizeBackSlashDirection(directory);
if(SEPARATOR_REGEXP.test(directory)) directory = directory.substr(0, directory.length - 1);
if(directory) {
this.currentDirectoryRegExp = createRegExpForPath(directory);
}
2017-02-05 08:02:48 +08:00
const dirname = path.dirname(directory);
const endsWithSeperator = SEPARATOR_REGEXP.test(dirname);
2017-02-05 08:02:48 +08:00
const parentDirectory = endsWithSeperator ? dirname.substr(0, dirname.length - 1) : dirname;
if(parentDirectory && parentDirectory !== directory) {
this.parentDirectoryRegExp = createRegExpForPath(parentDirectory);
}
if(__dirname.length >= 2) {
const buildins = normalizeBackSlashDirection(path.join(__dirname, ".."));
2017-02-05 08:02:48 +08:00
const buildinsAsModule = this.currentDirectoryRegExp && this.currentDirectoryRegExp.test(buildins);
this.buildinsAsModule = buildinsAsModule;
this.buildinsRegExp = createRegExpForPath(buildins);
}
2017-11-24 20:11:31 +08:00
this.cache = new Map();
2013-07-11 05:20:07 +08:00
}
shorten(request) {
if(!request) return request;
2017-11-24 20:11:31 +08:00
const cacheEntry = this.cache.get(request);
if(cacheEntry !== undefined) return cacheEntry;
let result = normalizeBackSlashDirection(request);
if(this.buildinsAsModule && this.buildinsRegExp)
2017-11-24 20:11:31 +08:00
result = result.replace(this.buildinsRegExp, "!(webpack)");
if(this.currentDirectoryRegExp)
2017-11-24 20:11:31 +08:00
result = result.replace(this.currentDirectoryRegExp, "!.");
if(this.parentDirectoryRegExp)
2017-11-24 20:11:31 +08:00
result = result.replace(this.parentDirectoryRegExp, "!..");
if(!this.buildinsAsModule && this.buildinsRegExp)
2017-11-24 20:11:31 +08:00
result = result.replace(this.buildinsRegExp, "!(webpack)");
result = result.replace(INDEX_JS_REGEXP, "$1");
result = result.replace(FRONT_OR_BACK_BANG_REGEXP, "");
this.cache.set(request, result);
return result;
2013-07-11 05:20:07 +08:00
}
2013-01-31 01:49:25 +08:00
}
module.exports = RequestShortener;