This commit is contained in:
chrosey
2017-09-13 07:52:34 +02:00
parent a1f16c37f4
commit 2340b0226b
24621 changed files with 2912161 additions and 149 deletions
+20
View File
@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+213
View File
@@ -0,0 +1,213 @@
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<h1>webpack Dev Middleware</h1>
</div>
It's a simple wrapper middleware for webpack. It serves the files emitted from webpack over a connect server. This should be used for **development only**.
It has a few advantages over bundling it as files:
* No files are written to disk, it handle the files in memory
* If files changed in watch mode, the middleware no longer serves the old bundle, but delays requests until the compiling has finished. You don't have to wait before refreshing the page after a file modification.
* I may add some specific optimization in future releases.
<h2 align="center">Install</h2>
```
npm install webpack-dev-middleware --save-dev
```
<h2 align="center">Usage</h2>
``` javascript
var webpackMiddleware = require("webpack-dev-middleware");
app.use(webpackMiddleware(...));
```
Example usage:
``` javascript
app.use(webpackMiddleware(webpack({
// webpack options
// webpackMiddleware takes a Compiler object as first parameter
// which is returned by webpack(...) without callback.
entry: "...",
output: {
path: "/"
// no real path is required, just pass "/"
// but it will work with other paths too.
}
}), {
// publicPath is required, whereas all other options are optional
noInfo: false,
// display no info to console (only warnings and errors)
quiet: false,
// display nothing to the console
lazy: true,
// switch into lazy mode
// that means no watching, but recompilation on every request
watchOptions: {
aggregateTimeout: 300,
poll: true
},
// watch options (only lazy: false)
publicPath: "/assets/",
// public path to bind the middleware to
// use the same as in webpack
index: "index.html",
// the index path for web server
headers: { "X-Custom-Header": "yes" },
// custom headers
stats: {
colors: true
},
// options for formating the statistics
reporter: null,
// Provide a custom reporter to change the way how logs are shown.
serverSideRender: false,
// Turn off the server-side rendering mode. See Server-Side Rendering part for more info.
}));
```
## Advanced API
This part shows how you might interact with the middleware during runtime:
* `close(callback)` - stop watching for file changes
```js
var webpackDevMiddlewareInstance = webpackMiddleware(/* see example usage */);
app.use(webpackDevMiddlewareInstance);
// After 10 seconds stop watching for file changes:
setTimeout(function(){
webpackDevMiddlewareInstance.close();
}, 10000);
```
* `invalidate()` - recompile the bundle - e.g. after you changed the configuration
```js
var compiler = webpack(/* see example usage */);
var webpackDevMiddlewareInstance = webpackMiddleware(compiler);
app.use(webpackDevMiddlewareInstance);
setTimeout(function(){
// After a short delay the configuration is changed
// in this example we will just add a banner plugin:
compiler.apply(new webpack.BannerPlugin('A new banner'));
// Recompile the bundle with the banner plugin:
webpackDevMiddlewareInstance.invalidate();
}, 1000);
```
* `waitUntilValid(callback)` - executes the `callback` if the bundle is valid or after it is valid again:
```js
var webpackDevMiddlewareInstance = webpackMiddleware(/* see example usage */);
app.use(webpackDevMiddlewareInstance);
webpackDevMiddlewareInstance.waitUntilValid(function(){
console.log('Package is in a valid state');
});
```
## Server-Side Rendering
**Note: this feature is experimental and may be removed or changed completely in the future.**
In order to develop a server-side rendering application, we need access to the [`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is generated with the latest build.
In the server-side rendering mode, __webpack-dev-middleware__ would sets the `stat` to `res.locals.webpackStats` before invoking the next middleware, where we can render pages and response to clients.
Notice that requests for bundle files would still be responded by __webpack-dev-middleware__ and all requests will be pending until the building process is finished in the server-side rendering mode.
```javascript
app.use(webpackMiddleware(compiler, { serverSideRender: true })
// The following middleware would not be invoked until the latest build is finished.
app.use((req, res) => {
const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName
// then use `assetsByChunkName` for server-sider rendering
// For example, if you have only one main chunk:
res.send(`
<html>
<head>
<title>My App</title>
${
assetsByChunkName.main
.filter(path => path.endsWith('.css'))
.map(path => `<link rel="stylesheet" href="${path}" />`)
}
</head>
<body>
<div id="root"></div>
${
assetsByChunkName.main
.filter(path => path.endsWith('.js'))
.map(path => `<script src="${path}" />`)
}
</body>
</html>
`)
})
```
<h2 align="center">Contributing</h2>
Don't hesitate to create a pull request. Every contribution is appreciated. In development you can start the tests by calling `npm test`.
<h2 align="center">Maintainers</h2>
<table>
<tbody>
<tr>
<td align="center">
<img width="150 height="150"
src="https://avatars.githubusercontent.com/SpaceK33z?v=3">
<br />
<a href="https://github.com/SpaceK33z">Kees Kluskens</a>
</td>
<tr>
<tbody>
</table>
<h2 align="center">LICENSE</h2>
#### [MIT](./LICENSE)
[npm]: https://img.shields.io/npm/v/webpack-dev-middleware.svg
[npm-url]: https://npmjs.com/package/webpack-dev-middleware
[node]: https://img.shields.io/node/v/webpack-dev-middleware.svg
[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack/webpack-dev-middleware.svg
[deps-url]: https://david-dm.org/webpack/webpack-dev-middleware
[tests]: http://img.shields.io/travis/webpack/webpack-dev-middleware.svg
[tests-url]: https://travis-ci.org/webpack/webpack-dev-middleware
[cover]: https://codecov.io/gh/webpack/webpack-dev-middleware/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack/webpack-dev-middleware
[chat]: https://badges.gitter.im/webpack/webpack.svg
[chat-url]: https://gitter.im/webpack/webpack
+36
View File
@@ -0,0 +1,36 @@
var pathJoin = require("./PathJoin");
var urlParse = require("url").parse;
function getFilenameFromUrl(publicPath, outputPath, url) {
var filename;
// localPrefix is the folder our bundle should be in
var localPrefix = urlParse(publicPath || "/", false, true);
var urlObject = urlParse(url);
// publicPath has the hostname that is not the same as request url's, should fail
if(localPrefix.hostname !== null && urlObject.hostname !== null &&
localPrefix.hostname !== urlObject.hostname) {
return false;
}
// publicPath is not in url, so it should fail
if(publicPath && localPrefix.hostname === urlObject.hostname && url.indexOf(publicPath) !== 0) {
return false;
}
// strip localPrefix from the start of url
if(urlObject.pathname.indexOf(localPrefix.pathname) === 0) {
filename = urlObject.pathname.substr(localPrefix.pathname.length);
}
if(!urlObject.hostname && localPrefix.hostname &&
url.indexOf(localPrefix.path) !== 0) {
return false;
}
// and if not match, use outputPath as filename
return decodeURIComponent(filename ? pathJoin(outputPath, filename) : outputPath);
}
module.exports = getFilenameFromUrl;
+5
View File
@@ -0,0 +1,5 @@
function pathJoin(a, b) {
return a == "/" ? "/" + b : (a || "") + "/" + b;
}
module.exports = pathJoin;
+223
View File
@@ -0,0 +1,223 @@
var parseRange = require("range-parser");
var pathIsAbsolute = require("path-is-absolute");
var MemoryFileSystem = require("memory-fs");
var HASH_REGEXP = /[0-9a-f]{10,}/;
module.exports = function Shared(context) {
var share = {
setOptions: function(options) {
if(!options) options = {};
if(typeof options.watchOptions === "undefined") options.watchOptions = {};
if(typeof options.reporter !== "function") options.reporter = share.defaultReporter;
if(typeof options.log !== "function") options.log = console.log.bind(console);
if(typeof options.warn !== "function") options.warn = console.warn.bind(console);
if(typeof options.error !== "function") options.error = console.error.bind(console);
if(typeof options.watchDelay !== "undefined") {
// TODO remove this in next major version
options.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
options.watchOptions.aggregateTimeout = options.watchDelay;
}
if(typeof options.watchOptions.aggregateTimeout === "undefined") options.watchOptions.aggregateTimeout = 200;
if(typeof options.stats === "undefined") options.stats = {};
if(!options.stats.context) options.stats.context = process.cwd();
if(options.lazy) {
if(typeof options.filename === "string") {
var str = options.filename
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
.replace(/\\\[[a-z]+\\\]/ig, ".+");
options.filename = new RegExp("^[\/]{0,1}" + str + "$");
}
}
context.options = options;
},
defaultReporter: function(reporterOptions) {
var state = reporterOptions.state;
var stats = reporterOptions.stats;
var options = reporterOptions.options;
if(state) {
var displayStats = (!options.quiet && options.stats !== false);
if(displayStats && !(stats.hasErrors() || stats.hasWarnings()) &&
options.noInfo)
displayStats = false;
if(displayStats) {
options.log(stats.toString(options.stats));
}
if(!options.noInfo && !options.quiet) {
var msg = "Compiled successfully.";
if(stats.hasErrors()) {
msg = "Failed to compile.";
} else if(stats.hasWarnings()) {
msg = "Compiled with warnings.";
}
options.log("webpack: " + msg);
}
} else {
options.log("webpack: Compiling...");
}
},
handleRangeHeaders: function handleRangeHeaders(content, req, res) {
//assumes express API. For other servers, need to add logic to access alternative header APIs
res.setHeader("Accept-Ranges", "bytes");
if(req.headers.range) {
var ranges = parseRange(content.length, req.headers.range);
// unsatisfiable
if(-1 == ranges) {
res.setHeader("Content-Range", "bytes */" + content.length);
res.statusCode = 416;
}
// valid (syntactically invalid/multiple ranges are treated as a regular response)
if(-2 != ranges && ranges.length === 1) {
// Content-Range
res.statusCode = 206;
var length = content.length;
res.setHeader(
"Content-Range",
"bytes " + ranges[0].start + "-" + ranges[0].end + "/" + length
);
content = content.slice(ranges[0].start, ranges[0].end + 1);
}
}
return content;
},
setFs: function(compiler) {
if(typeof compiler.outputPath === "string" && !pathIsAbsolute.posix(compiler.outputPath) && !pathIsAbsolute.win32(compiler.outputPath)) {
throw new Error("`output.path` needs to be an absolute path or `/`.");
}
// store our files in memory
var fs;
var isMemoryFs = !compiler.compilers && compiler.outputFileSystem instanceof MemoryFileSystem;
if(isMemoryFs) {
fs = compiler.outputFileSystem;
} else {
fs = compiler.outputFileSystem = new MemoryFileSystem();
}
context.fs = fs;
},
compilerDone: function(stats) {
// We are now on valid state
context.state = true;
context.webpackStats = stats;
// Do the stuff in nextTick, because bundle may be invalidated
// if a change happened while compiling
process.nextTick(function() {
// check if still in valid state
if(!context.state) return;
// print webpack output
context.options.reporter({
state: true,
stats: stats,
options: context.options
});
// execute callback that are delayed
var cbs = context.callbacks;
context.callbacks = [];
cbs.forEach(function continueBecauseBundleAvailable(cb) {
cb(stats);
});
});
// In lazy mode, we may issue another rebuild
if(context.forceRebuild) {
context.forceRebuild = false;
share.rebuild();
}
},
compilerInvalid: function() {
if(context.state && (!context.options.noInfo && !context.options.quiet))
context.options.reporter({
state: false,
options: context.options
});
// We are now in invalid state
context.state = false;
//resolve async
if(arguments.length === 2 && typeof arguments[1] === "function") {
var callback = arguments[1];
callback();
}
},
ready: function ready(fn, req) {
var options = context.options;
if(context.state) return fn(context.webpackStats);
if(!options.noInfo && !options.quiet)
options.log("webpack: wait until bundle finished: " + (req.url || fn.name));
context.callbacks.push(fn);
},
startWatch: function() {
var options = context.options;
var compiler = context.compiler;
// start watching
if(!options.lazy) {
var watching = compiler.watch(options.watchOptions, share.handleCompilerCallback);
context.watching = watching;
} else {
context.state = true;
}
},
rebuild: function rebuild() {
if(context.state) {
context.state = false;
context.compiler.run(share.handleCompilerCallback);
} else {
context.forceRebuild = true;
}
},
handleCompilerCallback: function(err) {
if(err) {
context.options.error(err.stack || err);
if(err.details) context.options.error(err.details);
}
},
handleRequest: function(filename, processRequest, req) {
// in lazy mode, rebuild on bundle request
if(context.options.lazy && (!context.options.filename || context.options.filename.test(filename)))
share.rebuild();
if(HASH_REGEXP.test(filename)) {
try {
if(context.fs.statSync(filename).isFile()) {
processRequest();
return;
}
} catch(e) {
}
}
share.ready(processRequest, req);
},
waitUntilValid: function(callback) {
callback = callback || function() {};
share.ready(callback, {});
},
invalidate: function(callback) {
callback = callback || function() {};
if(context.watching) {
share.ready(callback, {});
context.watching.invalidate();
} else {
callback();
}
},
close: function(callback) {
callback = callback || function() {};
if(context.watching) context.watching.close(callback);
else callback();
}
};
share.setOptions(context.options);
share.setFs(context.compiler);
context.compiler.plugin("done", share.compilerDone);
context.compiler.plugin("invalid", share.compilerInvalid);
context.compiler.plugin("watch-run", share.compilerInvalid);
context.compiler.plugin("run", share.compilerInvalid);
share.startWatch();
return share;
};
+83
View File
@@ -0,0 +1,83 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var mime = require("mime");
var getFilenameFromUrl = require("./lib/GetFilenameFromUrl");
var Shared = require("./lib/Shared");
var pathJoin = require("./lib/PathJoin");
// constructor for the middleware
module.exports = function(compiler, options) {
var context = {
state: false,
webpackStats: undefined,
callbacks: [],
options: options,
compiler: compiler,
watching: undefined,
forceRebuild: false
};
var shared = Shared(context);
// The middleware function
function webpackDevMiddleware(req, res, next) {
function goNext() {
if(!context.options.serverSideRender) return next();
shared.ready(function() {
res.locals.webpackStats = context.webpackStats;
next();
}, req);
}
if(req.method !== "GET") {
return goNext();
}
var filename = getFilenameFromUrl(context.options.publicPath, context.compiler.outputPath, req.url);
if(filename === false) return goNext();
shared.handleRequest(filename, processRequest, req);
function processRequest() {
try {
var stat = context.fs.statSync(filename);
if(!stat.isFile()) {
if(stat.isDirectory()) {
filename = pathJoin(filename, context.options.index || "index.html");
stat = context.fs.statSync(filename);
if(!stat.isFile()) throw "next";
} else {
throw "next";
}
}
} catch(e) {
return goNext();
}
// server content
var content = context.fs.readFileSync(filename);
content = shared.handleRangeHeaders(content, req, res);
res.setHeader("Content-Type", mime.lookup(filename) + "; charset=UTF-8");
res.setHeader("Content-Length", content.length);
if(context.options.headers) {
for(var name in context.options.headers) {
res.setHeader(name, context.options.headers[name]);
}
}
if(res.send) res.send(content);
else res.end(content);
}
}
webpackDevMiddleware.getFilenameFromUrl = getFilenameFromUrl.bind(this, context.options.publicPath, context.compiler.outputPath);
webpackDevMiddleware.waitUntilValid = shared.waitUntilValid;
webpackDevMiddleware.invalidate = shared.invalidate;
webpackDevMiddleware.close = shared.close;
webpackDevMiddleware.fileSystem = context.fs;
return webpackDevMiddleware;
};
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../mime/cli.js" "$@"
ret=$?
else
node "$basedir/../mime/cli.js" "$@"
ret=$?
fi
exit $ret
+7
View File
@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\mime\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\mime\cli.js" %*
)
View File
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2010 Benjamin Thomas, Robert Kieffer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+90
View File
@@ -0,0 +1,90 @@
# mime
Comprehensive MIME type mapping API based on mime-db module.
## Install
Install with [npm](http://github.com/isaacs/npm):
npm install mime
## Contributing / Testing
npm run test
## Command Line
mime [path_string]
E.g.
> mime scripts/jquery.js
application/javascript
## API - Queries
### mime.lookup(path)
Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.
```js
var mime = require('mime');
mime.lookup('/path/to/file.txt'); // => 'text/plain'
mime.lookup('file.txt'); // => 'text/plain'
mime.lookup('.TXT'); // => 'text/plain'
mime.lookup('htm'); // => 'text/html'
```
### mime.default_type
Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)
### mime.extension(type)
Get the default extension for `type`
```js
mime.extension('text/html'); // => 'html'
mime.extension('application/octet-stream'); // => 'bin'
```
### mime.charsets.lookup()
Map mime-type to charset
```js
mime.charsets.lookup('text/plain'); // => 'UTF-8'
```
(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)
## API - Defining Custom Types
Custom type mappings can be added on a per-project basis via the following APIs.
### mime.define()
Add custom mime/extension mappings
```js
mime.define({
'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],
'application/x-my-type': ['x-mt', 'x-mtt'],
// etc ...
});
mime.lookup('x-sft'); // => 'text/x-some-format'
```
The first entry in the extensions array is returned by `mime.extension()`. E.g.
```js
mime.extension('text/x-some-format'); // => 'x-sf'
```
### mime.load(filepath)
Load mappings from an Apache ".types" format file
```js
mime.load('./my_project.types');
```
The .types file format is simple - See the `types` dir for examples.
+11
View File
@@ -0,0 +1,11 @@
var db = require('mime-db');
var mapByType = {};
Object.keys(db).forEach(function(key) {
var extensions = db[key].extensions;
if (extensions) {
mapByType[key] = extensions;
}
});
console.log(JSON.stringify(mapByType));
+60
View File
@@ -0,0 +1,60 @@
/**
* Usage: node test.js
*/
var mime = require('../mime');
var assert = require('assert');
var path = require('path');
//
// Test mime lookups
//
assert.equal('text/plain', mime.lookup('text.txt')); // normal file
assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase
assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file
assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file
assert.equal('text/plain', mime.lookup('.txt')); // nameless
assert.equal('text/plain', mime.lookup('txt')); // extension-only
assert.equal('text/plain', mime.lookup('/txt')); // extension-less ()
assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less
assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized
assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default
//
// Test extensions
//
assert.equal('txt', mime.extension(mime.types.text));
assert.equal('html', mime.extension(mime.types.htm));
assert.equal('bin', mime.extension('application/octet-stream'));
assert.equal('bin', mime.extension('application/octet-stream '));
assert.equal('html', mime.extension(' text/html; charset=UTF-8'));
assert.equal('html', mime.extension('text/html; charset=UTF-8 '));
assert.equal('html', mime.extension('text/html; charset=UTF-8'));
assert.equal('html', mime.extension('text/html ; charset=UTF-8'));
assert.equal('html', mime.extension('text/html;charset=UTF-8'));
assert.equal('html', mime.extension('text/Html;charset=UTF-8'));
assert.equal(undefined, mime.extension('unrecognized'));
//
// Test node.types lookups
//
assert.equal('application/font-woff', mime.lookup('file.woff'));
assert.equal('application/octet-stream', mime.lookup('file.buffer'));
// TODO: Uncomment once #157 is resolved
// assert.equal('audio/mp4', mime.lookup('file.m4a'));
assert.equal('font/opentype', mime.lookup('file.otf'));
//
// Test charsets
//
assert.equal('UTF-8', mime.charsets.lookup('text/plain'));
assert.equal('UTF-8', mime.charsets.lookup(mime.types.js));
assert.equal('UTF-8', mime.charsets.lookup(mime.types.json));
assert.equal(undefined, mime.charsets.lookup(mime.types.bin));
assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback'));
console.log('\nAll tests passed');
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env node
var mime = require('./mime.js');
var file = process.argv[2];
var type = mime.lookup(file);
process.stdout.write(type + '\n');
+108
View File
@@ -0,0 +1,108 @@
var path = require('path');
var fs = require('fs');
function Mime() {
// Map of extension -> mime type
this.types = Object.create(null);
// Map of mime type -> extension
this.extensions = Object.create(null);
}
/**
* Define mimetype -> extension mappings. Each key is a mime-type that maps
* to an array of extensions associated with the type. The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* @param map (Object) type definitions
*/
Mime.prototype.define = function (map) {
for (var type in map) {
var exts = map[type];
for (var i = 0; i < exts.length; i++) {
if (process.env.DEBUG_MIME && this.types[exts[i]]) {
console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
this.types[exts[i]] + ' to ' + type);
}
this.types[exts[i]] = type;
}
// Default extension is the first one we encounter
if (!this.extensions[type]) {
this.extensions[type] = exts[0];
}
}
};
/**
* Load an Apache2-style ".types" file
*
* This may be called multiple times (it's expected). Where files declare
* overlapping types/extensions, the last file wins.
*
* @param file (String) path of file to load.
*/
Mime.prototype.load = function(file) {
this._loading = file;
// Read file and split into lines
var map = {},
content = fs.readFileSync(file, 'ascii'),
lines = content.split(/[\r\n]+/);
lines.forEach(function(line) {
// Clean up whitespace/comments, and split into fields
var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
map[fields.shift()] = fields;
});
this.define(map);
this._loading = null;
};
/**
* Lookup a mime type based on extension
*/
Mime.prototype.lookup = function(path, fallback) {
var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase();
return this.types[ext] || fallback || this.default_type;
};
/**
* Return file extension associated with a mime type
*/
Mime.prototype.extension = function(mimeType) {
var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
return this.extensions[type];
};
// Default instance
var mime = new Mime();
// Define built-in types
mime.define(require('./types.json'));
// Default type
mime.default_type = mime.lookup('bin');
//
// Additional API specific to the default instance
//
mime.Mime = Mime;
/**
* Lookup a charset based on mime type.
*/
mime.charsets = {
lookup: function(mimeType, fallback) {
// Assume text types are utf8
return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback;
}
};
module.exports = mime;
+106
View File
@@ -0,0 +1,106 @@
{
"_args": [
[
{
"raw": "mime@^1.3.4",
"scope": null,
"escapedName": "mime",
"name": "mime",
"rawSpec": "^1.3.4",
"spec": ">=1.3.4 <2.0.0",
"type": "range"
},
"c:\\xampp\\htdocs\\laravel\\node_modules\\webpack-dev-middleware"
]
],
"_from": "mime@>=1.3.4 <2.0.0",
"_id": "mime@1.3.6",
"_inCache": true,
"_location": "/webpack-dev-middleware/mime",
"_nodeVersion": "6.9.2",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/mime-1.3.6.tgz_1494565179088_0.4127067362423986"
},
"_npmUser": {
"name": "broofa",
"email": "robert@broofa.com"
},
"_npmVersion": "4.3.0",
"_phantomChildren": {},
"_requested": {
"raw": "mime@^1.3.4",
"scope": null,
"escapedName": "mime",
"name": "mime",
"rawSpec": "^1.3.4",
"spec": ">=1.3.4 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/webpack-dev-middleware"
],
"_resolved": "https://registry.npmjs.org/mime/-/mime-1.3.6.tgz",
"_shasum": "591d84d3653a6b0b4a3b9df8de5aa8108e72e5e0",
"_shrinkwrap": null,
"_spec": "mime@^1.3.4",
"_where": "c:\\xampp\\htdocs\\laravel\\node_modules\\webpack-dev-middleware",
"author": {
"name": "Robert Kieffer",
"email": "robert@broofa.com",
"url": "http://github.com/broofa"
},
"bin": {
"mime": "cli.js"
},
"bugs": {
"url": "https://github.com/broofa/node-mime/issues"
},
"contributors": [
{
"name": "Benjamin Thomas",
"email": "benjamin@benjaminthomas.org",
"url": "http://github.com/bentomas"
}
],
"dependencies": {},
"description": "A comprehensive library for mime-type mapping",
"devDependencies": {
"mime-db": "^1.22.0"
},
"directories": {},
"dist": {
"shasum": "591d84d3653a6b0b4a3b9df8de5aa8108e72e5e0",
"tarball": "https://registry.npmjs.org/mime/-/mime-1.3.6.tgz"
},
"gitHead": "78aa9df74925ee629b9f2c35ec16b099189e9cef",
"homepage": "https://github.com/broofa/node-mime#readme",
"keywords": [
"util",
"mime"
],
"license": "MIT",
"main": "mime.js",
"maintainers": [
{
"name": "broofa",
"email": "robert@broofa.com"
},
{
"name": "bentomas",
"email": "benjamin@benjaminthomas.org"
}
],
"name": "mime",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"url": "git+https://github.com/broofa/node-mime.git",
"type": "git"
},
"scripts": {
"prepublish": "node build/build.js > types.json",
"test": "node build/test.js"
},
"version": "1.3.6"
}
File diff suppressed because one or more lines are too long
+127
View File
@@ -0,0 +1,127 @@
{
"_args": [
[
{
"raw": "webpack-dev-middleware@^1.10.2",
"scope": null,
"escapedName": "webpack-dev-middleware",
"name": "webpack-dev-middleware",
"rawSpec": "^1.10.2",
"spec": ">=1.10.2 <2.0.0",
"type": "range"
},
"c:\\xampp\\htdocs\\laravel\\node_modules\\webpack-dev-server"
]
],
"_from": "webpack-dev-middleware@>=1.10.2 <2.0.0",
"_id": "webpack-dev-middleware@1.10.2",
"_inCache": true,
"_location": "/webpack-dev-middleware",
"_nodeVersion": "7.4.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/webpack-dev-middleware-1.10.2.tgz_1492855208221_0.35484315757639706"
},
"_npmUser": {
"name": "sokra",
"email": "tobias.koppers@googlemail.com"
},
"_npmVersion": "4.0.5",
"_phantomChildren": {},
"_requested": {
"raw": "webpack-dev-middleware@^1.10.2",
"scope": null,
"escapedName": "webpack-dev-middleware",
"name": "webpack-dev-middleware",
"rawSpec": "^1.10.2",
"spec": ">=1.10.2 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/webpack-dev-server"
],
"_resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.10.2.tgz",
"_shasum": "2e252ce1dfb020dbda1ccb37df26f30ab014dbd1",
"_shrinkwrap": null,
"_spec": "webpack-dev-middleware@^1.10.2",
"_where": "c:\\xampp\\htdocs\\laravel\\node_modules\\webpack-dev-server",
"author": {
"name": "Tobias Koppers @sokra"
},
"bugs": {
"url": "https://github.com/webpack/webpack-dev-middleware/issues"
},
"dependencies": {
"memory-fs": "~0.4.1",
"mime": "^1.3.4",
"path-is-absolute": "^1.0.0",
"range-parser": "^1.0.3"
},
"description": "Offers a dev middleware for webpack, which arguments a live bundle to a directory",
"devDependencies": {
"codecov.io": "^0.1.6",
"eslint": "^3.4.0",
"express": "^4.14.0",
"file-loader": "^0.9.0",
"istanbul": "^0.4.5",
"mocha": "^3.0.2",
"mocha-sinon": "^1.1.6",
"should": "^11.1.0",
"sinon": "^1.17.5",
"supertest": "^2.0.0",
"webpack": "^2.2.0"
},
"directories": {},
"dist": {
"shasum": "2e252ce1dfb020dbda1ccb37df26f30ab014dbd1",
"tarball": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.10.2.tgz"
},
"engines": {
"node": ">=0.6"
},
"files": [
"middleware.js",
"lib/"
],
"gitHead": "9b03d791c6641ad7e8eaba2255b95777e30630ed",
"homepage": "http://github.com/webpack/webpack-dev-middleware",
"license": "MIT",
"main": "middleware.js",
"maintainers": [
{
"name": "jhnns",
"email": "mail@johannesewald.de"
},
{
"name": "peerigon",
"email": "developers@peerigon.com"
},
{
"name": "sokra",
"email": "tobias.koppers@googlemail.com"
},
{
"name": "spacek33z",
"email": "kees@webduck.nl"
}
],
"name": "webpack-dev-middleware",
"optionalDependencies": {},
"peerDependencies": {
"webpack": "1 || ^2.1.0-beta || ^2.2.0-rc.0"
},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/webpack/webpack-dev-middleware.git"
},
"scripts": {
"beautify": "npm run lint -- --fix",
"cover": "istanbul cover node_modules/mocha/bin/_mocha",
"lint": "eslint *.js lib test",
"posttest": "npm run -s lint",
"test": "mocha --full-trace --check-leaks",
"travis": "npm run cover -- --report lcovonly && npm run lint"
},
"version": "1.10.2"
}