Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proxy integrated #99

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

All notable changes to `rollup-plugin-serve` will be documented in this file.

## [2.0.3] - 2023-07-20
### Added
- Proxy

## [1.1.0] - 2020-11-01
### Added
- Add `onListening` hook #69 @filoxo
Expand Down
20 changes: 10 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "rollup-plugin-serve",
"version": "2.0.2",
"version": "2.0.3",
"description": "Serve your rolled up bundle",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
Expand All @@ -12,9 +12,10 @@
"scripts": {
"build": "rollup -c",
"dev": "rollup -cw",
"lint": "standard --fix rollup.config.js src/**",
"prepare": "yarn lint && yarn build",
"test": "cd test && rollup -cw || cd .."
"lint-check": "standard *.mjs src/**/*.js test/**/*.js",
"lint": "standard --fix *.mjs src/**/*.js test/**/*.js",
"prepare": "npm run lint && npm run build",
"test": "rollup -c && rollup -c test.rollup.config.mjs -w"
},
"keywords": [
"rollup",
Expand All @@ -38,13 +39,12 @@
"index.d.ts"
],
"dependencies": {
"mime": ">=2.4.6",
"opener": "1"
"mime": "^3.0.0",
"opener": "^1.5.2"
},
"devDependencies": {
"@rollup/plugin-buble": "0.21.3",
"@types/node": "^18.7.15",
"rollup": "2",
"standard": "17"
"@rollup/plugin-buble": "^1.0.2",
"rollup": "^3.26.3",
"standard": "*"
}
}
4 changes: 2 additions & 2 deletions rollup.config.js → rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import buble from '@rollup/plugin-buble'
export default {
input: 'src/index.js',
output: [
{ file: 'dist/index.cjs', format: 'cjs', exports: 'default' },
{ file: 'dist/index.mjs', format: 'esm' }
{ file: 'dist/index.cjs.js', format: 'cjs', exports: 'default' },
{ file: 'dist/index.es.js', format: 'es' }
],
plugins: [buble()],
external: ['fs', 'https', 'http', 'path', 'mime', 'opener']
Expand Down
82 changes: 66 additions & 16 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readFile } from 'fs'
import { createServer as createHttpsServer } from 'https'
import { createServer } from 'http'
import https from 'https'
import http from 'http'
import { resolve, posix } from 'path'

import mime from 'mime'
Expand All @@ -17,29 +17,72 @@ function serve (options = { contentBase: '' }) {
options = { contentBase: options }
}
options.contentBase = Array.isArray(options.contentBase) ? options.contentBase : [options.contentBase || '']
options.host = options.host || 'localhost'
options.port = options.port || 10001
options.headers = options.headers || {}
options.https = options.https || false
options.openPage = options.openPage || ''
options.onListening = options.onListening || function noop () { }
options.proxy = options.proxy || {}
options.onListening = options.onListening || function noop () {}
mime.default_type = 'text/plain'

if (options.mimeTypes) {
mime.define(options.mimeTypes, true)
}

const proxies = Object.keys(options.proxy).map(proxy => {
return {
destination: options.proxy[proxy],
test: new RegExp('/' + proxy)
}
})

const requestListener = (request, response) => {
// Remove querystring
const unsafePath = decodeURI(request.url.split('?')[0])

// Don't allow path traversal
const urlPath = posix.normalize(unsafePath)

Object.keys(options.headers).forEach((key) => {
response.setHeader(key, options.headers[key])
})
setHeaders(response, options.headers)

// Find the appropriate proxy for the request if one exists
const proxy = proxies.find(ref => urlPath.match(ref.test))

// If a proxy exists, forward the request to the appropriate server
if (proxy && proxy.destination) {
const destination = '' + proxy.destination + request.url
const opts = { headers: request.headers, method: request.method }

// Get the request contents
let body = ''
request.on('data', chunk => {
body += chunk
})

// Forward the request
request.on('end', () => {
const proxyRequest = (options.https ? https : http)
.request(destination, opts, proxyResponse => {
let data = ''
proxyResponse.on('data', chunk => {
data += chunk
})
proxyResponse.on('end', () => {
setHeaders(response, proxyResponse.headers)
foundProxy(response, proxyResponse.statusCode, data)
})
})
.end(body, 'utf-8')

readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
proxyRequest.on('error', err => {
console.error('There was a problem with the request for ' + request.url + ': ' + err)
})
proxyRequest.end()
})
return
}
readFileFromContentBase(options.contentBase, urlPath, (error, content, filePath) => {
if (!error) {
return found(response, filePath, content)
}
Expand All @@ -53,7 +96,7 @@ function serve (options = { contentBase: '' }) {
}
if (options.historyApiFallback) {
const fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'
readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {
readFileFromContentBase(options.contentBase, fallbackPath, (error, content, filePath) => {
if (error) {
notFound(response, filePath)
} else {
Expand All @@ -75,12 +118,12 @@ function serve (options = { contentBase: '' }) {

// If HTTPS options are available, create an HTTPS server
server = options.https
? createHttpsServer(options.https, requestListener)
: createServer(requestListener)
? https.createServer(options.https, requestListener)
: http.createServer(requestListener)
server.listen(options.port, options.host, () => options.onListening(server))

// Assemble url for error and info messages
const url = (options.https ? 'https' : 'http') + '://' + (options.host || 'localhost') + ':' + options.port
const url = (options.https ? 'https' : 'http') + '://' + options.host + ':' + options.port

// Handle common server errors
server.on('error', e => {
Expand Down Expand Up @@ -109,11 +152,7 @@ function serve (options = { contentBase: '' }) {

// Open browser
if (options.open) {
if (/https?:\/\/.+/.test(options.openPage)) {
opener(options.openPage)
} else {
opener(url + options.openPage)
}
opener(url + options.openPage)
}
}
}
Expand Down Expand Up @@ -151,6 +190,17 @@ function found (response, filePath, content) {
response.end(content, 'utf-8')
}

function foundProxy (response, status, content) {
response.writeHead(status)
response.end(content, 'utf-8')
}

function setHeaders (response, headers) {
Object.keys(headers).forEach(key => {
response.setHeader(key, headers[key])
})
}

function green (text) {
return '\u001b[1m\u001b[32m' + text + '\u001b[39m\u001b[22m'
}
Expand Down
14 changes: 7 additions & 7 deletions test/rollup.config.js → test.rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import serve from '../src/index.js'
import serve from './dist/index.cjs.js'

const testOnListening = () => {
const timeout = 3
Expand All @@ -7,28 +7,28 @@ const testOnListening = () => {
console.error(msg)
throw new Error(msg)
}, timeout * 1000)
return (server) => {
return server => {
clearTimeout(timer)
console.log('onListening works', server.address())
}
}

export default {
input: 'entry.js',
input: 'test/entry.js',
output: {
file: 'dest.js',
file: 'test/dest.js',
format: 'cjs'
},
watch: {
clearScreen: false,
clearScreen: false
},
plugins: [
serve({
open: true,
openPage: '/frames.html',
historyApiFallback: '/fallback.html',
contentBase: ['.', 'base1', 'base2'],
onListening: testOnListening(),
contentBase: ['test', 'test/base1', 'test/base2'],
onListening: testOnListening()
})
]
}
2 changes: 1 addition & 1 deletion test/base1/index.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<!doctype html>
<!DOCTYPE html>
File: /base1/index.html
<script src="dest.js"></script>
2 changes: 1 addition & 1 deletion test/base1/test1.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<!doctype html>
<!DOCTYPE html>
File: /base1/test1.html
<script src="dest.js"></script>
2 changes: 1 addition & 1 deletion test/base2/index.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<!doctype html>
<!DOCTYPE html>
File: /base2/index.html
<script src="dest.js"></script>
2 changes: 1 addition & 1 deletion test/base2/test2.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<!doctype html>
<!DOCTYPE html>
File: /base2/test2.html
<script src="dest.js"></script>
6 changes: 4 additions & 2 deletions test/entry.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import lib from './lib.js'

window.onload = () => document.body.innerHTML += '<br>Path: ' + window.location.pathname
+ '<br>' + lib
window.onload = () =>
(document.body.innerHTML +=
'<br>Path: ' + window.location.pathname +
'<br>' + lib)
2 changes: 1 addition & 1 deletion test/fallback.html
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
<!doctype html>
<!DOCTYPE html>
Fallback
2 changes: 1 addition & 1 deletion test/frames.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!doctype html>
<!DOCTYPE html>
<style type="text/css">
* {
vertical-align: top;
Expand Down
2 changes: 1 addition & 1 deletion test/index.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<!doctype html>
<!DOCTYPE html>
File: /index.html
<script src="dest.js"></script>