You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

315 lines
9.3 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. 'use strict'
  2. const arrayify = require('array-back')
  3. const path = require('path')
  4. const url = require('url')
  5. const debug = require('./debug')
  6. const mw = require('./middleware')
  7. const t = require('typical')
  8. const compose = require('koa-compose')
  9. const flatten = require('reduce-flatten')
  10. class MiddlewareStack extends Array {
  11. add (middleware) {
  12. this.push(middleware)
  13. return this
  14. }
  15. /**
  16. * allow from any origin
  17. */
  18. addCors () {
  19. this.push({ middleware: require('kcors') })
  20. return this
  21. }
  22. /* pretty print JSON */
  23. addJson () {
  24. this.push({ middleware: require('koa-json') })
  25. return this
  26. }
  27. /* rewrite rules */
  28. addRewrite (rewriteRules) {
  29. this.push({
  30. optionDefinitions: {
  31. name: 'rewrite', alias: 'r', type: String, multiple: true,
  32. typeLabel: '[underline]{expression} ...',
  33. description: "A list of URL rewrite rules. For each rule, separate the 'from' and 'to' routes with '->'. Whitespace surrounded the routes is ignored. E.g. '/from -> /to'."
  34. },
  35. middleware: function (cliOptions) {
  36. const options = parseRewriteRules(arrayify(cliOptions.rewrite || rewriteRules))
  37. if (options.length) {
  38. return options.map(route => {
  39. if (route.to) {
  40. /* `to` address is remote if the url specifies a host */
  41. if (url.parse(route.to).host) {
  42. const _ = require('koa-route')
  43. debug('proxy rewrite', `${route.from} -> ${route.to}`)
  44. return _.all(route.from, mw.proxyRequest(route))
  45. } else {
  46. const rewrite = require('koa-rewrite')
  47. const rmw = rewrite(route.from, route.to)
  48. rmw._name = 'rewrite'
  49. return rmw
  50. }
  51. }
  52. })
  53. }
  54. }
  55. })
  56. return this
  57. }
  58. /* must come after rewrite.
  59. See https://github.com/nodejitsu/node-http-proxy/issues/180. */
  60. addBodyParser () {
  61. this.push({ middleware: require('koa-bodyparser') })
  62. return this
  63. }
  64. /* path blacklist */
  65. addBlacklist (forbidList) {
  66. this.push({
  67. optionDefinitions: {
  68. name: 'forbid', alias: 'b', type: String,
  69. multiple: true, typeLabel: '[underline]{path} ...',
  70. description: 'A list of forbidden routes.'
  71. },
  72. middleware: function (cliOptions) {
  73. forbidList = arrayify(cliOptions.forbid || forbidList)
  74. if (forbidList.length) {
  75. const pathToRegexp = require('path-to-regexp')
  76. debug('forbid', forbidList.join(', '))
  77. return function blacklist (ctx, next) {
  78. if (forbidList.some(expression => pathToRegexp(expression).test(ctx.path))) {
  79. const http = require('http')
  80. ctx.throw(403, http.STATUS_CODES[403])
  81. } else {
  82. return next()
  83. }
  84. }
  85. }
  86. }
  87. })
  88. return this
  89. }
  90. /* cache */
  91. addCache () {
  92. this.push({
  93. optionDefinitions: {
  94. name: 'no-cache', alias: 'n', type: Boolean,
  95. description: 'Disable etag-based caching - forces loading from disk each request.'
  96. },
  97. middleware: function (cliOptions) {
  98. const noCache = cliOptions['no-cache']
  99. if (!noCache) {
  100. return [
  101. require('koa-conditional-get')(),
  102. require('koa-etag')()
  103. ]
  104. }
  105. }
  106. })
  107. return this
  108. }
  109. /* mime-type overrides */
  110. addMimeType (mime) {
  111. this.push({
  112. middleware: function (cliOptions) {
  113. mime = cliOptions.mime || mime
  114. if (mime) {
  115. debug('mime override', JSON.stringify(mime))
  116. return mw.mime(mime)
  117. }
  118. }
  119. })
  120. return this
  121. }
  122. /* compress response */
  123. addCompression (compress) {
  124. this.push({
  125. optionDefinitions: {
  126. name: 'compress', alias: 'c', type: Boolean,
  127. description: 'Serve gzip-compressed resources, where applicable.'
  128. },
  129. middleware: function (cliOptions) {
  130. compress = t.isDefined(cliOptions.compress)
  131. ? cliOptions.compress
  132. : compress
  133. if (compress) {
  134. debug('compression', 'enabled')
  135. return require('koa-compress')()
  136. }
  137. }
  138. })
  139. return this
  140. }
  141. /* Logging */
  142. addLogging (format, options) {
  143. options = options || {}
  144. this.push({
  145. optionDefinitions: {
  146. name: 'log-format',
  147. alias: 'f',
  148. type: String,
  149. description: "If a format is supplied an access log is written to stdout. If not, a dynamic statistics view is displayed. Use a preset ('none', 'dev','combined', 'short', 'tiny' or 'logstalgia') or supply a custom format (e.g. ':method -> :url')."
  150. },
  151. middleware: function (cliOptions) {
  152. format = cliOptions['log-format'] || format
  153. if (cliOptions.verbose && !format) {
  154. format = 'none'
  155. }
  156. if (format !== 'none') {
  157. const morgan = require('koa-morgan')
  158. if (!format) {
  159. const streamLogStats = require('stream-log-stats')
  160. options.stream = streamLogStats({ refreshRate: 500 })
  161. return morgan('common', options)
  162. } else if (format === 'logstalgia') {
  163. morgan.token('date', () => {
  164. var d = new Date()
  165. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`).replace('GMT', '').replace(' (BST)', '')
  166. })
  167. return morgan('combined', options)
  168. } else {
  169. return morgan(format, options)
  170. }
  171. }
  172. }
  173. })
  174. return this
  175. }
  176. /* Mock Responses */
  177. addMockResponses (mocks) {
  178. this.push({
  179. middleware: function (cliOptions) {
  180. mocks = arrayify(cliOptions.mocks || mocks)
  181. return mocks.map(mock => {
  182. if (mock.module) {
  183. const modulePath = path.resolve(path.join(cliOptions.directory, mock.module))
  184. mock.responses = require(modulePath)
  185. }
  186. if (mock.responses) {
  187. return mw.mockResponses(mock.route, mock.responses)
  188. } else if (mock.response) {
  189. mock.target = {
  190. request: mock.request,
  191. response: mock.response
  192. }
  193. return mw.mockResponses(mock.route, mock.target)
  194. }
  195. })
  196. }
  197. })
  198. return this
  199. }
  200. /* for any URL not matched by static (e.g. `/search`), serve the SPA */
  201. addSpa (spa, assetTest) {
  202. this.push({
  203. optionDefinitions: {
  204. name: 'spa', alias: 's', type: String, typeLabel: '[underline]{file}',
  205. description: 'Path to a Single Page App, e.g. app.html.'
  206. },
  207. middleware: function (cliOptions) {
  208. spa = cliOptions.spa || spa || 'index.html'
  209. assetTest = new RegExp(cliOptions['spa-asset-test'] || assetTest || '\\.')
  210. if (spa) {
  211. const send = require('koa-send')
  212. const _ = require('koa-route')
  213. debug('SPA', spa)
  214. return _.get('*', function spaMw (ctx, route, next) {
  215. const root = path.resolve(cliOptions.directory || process.cwd())
  216. debug(`SPA request. Route: ${route}, isAsset: ${assetTest.test(route)}`)
  217. return send(ctx, assetTest.test(route) ? route : spa, { root: root }).then(next)
  218. })
  219. }
  220. }
  221. })
  222. return this
  223. }
  224. /* serve static files */
  225. addStatic (root, options) {
  226. this.push({
  227. optionDefinitions: {
  228. name: 'directory', alias: 'd', type: String, typeLabel: '[underline]{path}',
  229. description: 'Root directory, defaults to the current directory.'
  230. },
  231. middleware: function (cliOptions) {
  232. /* update global cliOptions */
  233. cliOptions.directory = cliOptions.directory || root || process.cwd()
  234. options = Object.assign({ hidden: true }, options)
  235. if (cliOptions.directory) {
  236. const serve = require('koa-static')
  237. return serve(cliOptions.directory, options)
  238. }
  239. }
  240. })
  241. return this
  242. }
  243. /* serve directory index */
  244. addIndex (path, options) {
  245. this.push({
  246. middleware: function (cliOptions) {
  247. path = cliOptions.directory || path || process.cwd()
  248. options = Object.assign({ icons: true, hidden: true }, options)
  249. if (path) {
  250. const serveIndex = require('koa-serve-index')
  251. return serveIndex(path, options)
  252. }
  253. }
  254. })
  255. return this
  256. }
  257. getOptionDefinitions () {
  258. return this
  259. .filter(mw => mw.optionDefinitions)
  260. .map(mw => mw.optionDefinitions)
  261. .reduce(flatten, [])
  262. .map(def => {
  263. def.group = 'middleware'
  264. return def
  265. })
  266. }
  267. compose (options) {
  268. const convert = require('koa-convert')
  269. const middlewareStack = this
  270. .filter(mw => mw.middleware)
  271. .map(mw => mw.middleware)
  272. .map(middleware => middleware(options))
  273. .filter(middleware => middleware)
  274. .reduce(flatten, [])
  275. .map(convert)
  276. // console.error(require('util').inspect(middlewareStack, { depth: 3, colors: true }))
  277. return compose(middlewareStack)
  278. }
  279. }
  280. module.exports = MiddlewareStack
  281. function parseRewriteRules (rules) {
  282. return rules && rules.map(rule => {
  283. if (t.isString(rule)) {
  284. const matches = rule.match(/(\S*)\s*->\s*(\S*)/)
  285. if (!(matches && matches.length >= 3)) throw new Error('Invalid rule: ' + rule)
  286. return {
  287. from: matches[1],
  288. to: matches[2]
  289. }
  290. } else {
  291. return rule
  292. }
  293. })
  294. }