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.

318 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
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. ctx.status = 403
  80. } else {
  81. return next()
  82. }
  83. }
  84. }
  85. }
  86. })
  87. return this
  88. }
  89. /* cache */
  90. addCache () {
  91. this.push({
  92. optionDefinitions: {
  93. name: 'no-cache', alias: 'n', type: Boolean,
  94. description: 'Disable etag-based caching - forces loading from disk each request.'
  95. },
  96. middleware: function (cliOptions) {
  97. const noCache = cliOptions['no-cache']
  98. if (!noCache) {
  99. return [
  100. require('koa-conditional-get')(),
  101. require('koa-etag')()
  102. ]
  103. }
  104. }
  105. })
  106. return this
  107. }
  108. /* mime-type overrides */
  109. addMimeOverride (mime) {
  110. this.push({
  111. middleware: function (cliOptions) {
  112. mime = cliOptions.mime || mime
  113. if (mime) {
  114. debug('mime override', JSON.stringify(mime))
  115. return mw.mime(mime)
  116. }
  117. }
  118. })
  119. return this
  120. }
  121. /* compress response */
  122. addCompression (compress) {
  123. this.push({
  124. optionDefinitions: {
  125. name: 'compress', alias: 'c', type: Boolean,
  126. description: 'Serve gzip-compressed resources, where applicable.'
  127. },
  128. middleware: function (cliOptions) {
  129. compress = t.isDefined(cliOptions.compress)
  130. ? cliOptions.compress
  131. : compress
  132. if (compress) {
  133. debug('compression', 'enabled')
  134. return require('koa-compress')()
  135. }
  136. }
  137. })
  138. return this
  139. }
  140. /* Logging */
  141. addLogging (format, options) {
  142. options = options || {}
  143. this.push({
  144. optionDefinitions: {
  145. name: 'log-format',
  146. alias: 'f',
  147. type: String,
  148. 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')."
  149. },
  150. middleware: function (cliOptions) {
  151. format = cliOptions['log-format'] || format
  152. if (cliOptions.verbose && !format) {
  153. format = 'none'
  154. }
  155. if (format !== 'none') {
  156. const morgan = require('koa-morgan')
  157. if (!format) {
  158. const streamLogStats = require('stream-log-stats')
  159. options.stream = streamLogStats({ refreshRate: 500 })
  160. return morgan('common', options)
  161. } else if (format === 'logstalgia') {
  162. morgan.token('date', () => {
  163. var d = new Date()
  164. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`).replace('GMT', '').replace(' (BST)', '')
  165. })
  166. return morgan('combined', options)
  167. } else {
  168. return morgan(format, options)
  169. }
  170. }
  171. }
  172. })
  173. return this
  174. }
  175. /* Mock Responses */
  176. addMockResponses (mocks) {
  177. this.push({
  178. middleware: function (cliOptions) {
  179. mocks = arrayify(cliOptions.mocks || mocks)
  180. return mocks.map(mock => {
  181. if (mock.module) {
  182. const modulePath = path.resolve(path.join(cliOptions.directory, mock.module))
  183. mock.responses = require(modulePath)
  184. }
  185. if (mock.responses) {
  186. return mw.mockResponses(mock.route, mock.responses)
  187. } else if (mock.response) {
  188. mock.target = {
  189. request: mock.request,
  190. response: mock.response
  191. }
  192. return mw.mockResponses(mock.route, mock.target)
  193. }
  194. })
  195. }
  196. })
  197. return this
  198. }
  199. /* for any URL not matched by static (e.g. `/search`), serve the SPA */
  200. addSpa (spa, assetTest) {
  201. this.push({
  202. optionDefinitions: {
  203. name: 'spa', alias: 's', type: String, typeLabel: '[underline]{file}',
  204. description: 'Path to a Single Page App, e.g. app.html.'
  205. },
  206. middleware: function (cliOptions) {
  207. spa = cliOptions.spa || spa || 'index.html'
  208. assetTest = new RegExp(cliOptions['spa-asset-test'] || assetTest || '\\.')
  209. if (spa) {
  210. const send = require('koa-send')
  211. const _ = require('koa-route')
  212. debug('SPA', spa)
  213. return _.get('*', function spaMw (ctx, route, next) {
  214. const root = path.resolve(cliOptions.directory || process.cwd())
  215. if (ctx.accepts('text/html') && !assetTest.test(route)) {
  216. debug(`SPA request. Route: ${route}, isAsset: ${assetTest.test(route)}`)
  217. return send(ctx, spa, { root: root }).then(next)
  218. } else {
  219. return send(ctx, route, { root: root }).then(next)
  220. }
  221. })
  222. }
  223. }
  224. })
  225. return this
  226. }
  227. /* serve static files */
  228. addStatic (root, options) {
  229. this.push({
  230. optionDefinitions: {
  231. name: 'directory', alias: 'd', type: String, typeLabel: '[underline]{path}',
  232. description: 'Root directory, defaults to the current directory.'
  233. },
  234. middleware: function (cliOptions) {
  235. /* update global cliOptions */
  236. cliOptions.directory = cliOptions.directory || root || process.cwd()
  237. options = Object.assign({ hidden: true }, options)
  238. if (cliOptions.directory) {
  239. const serve = require('koa-static')
  240. return serve(cliOptions.directory, options)
  241. }
  242. }
  243. })
  244. return this
  245. }
  246. /* serve directory index */
  247. addIndex (path, options) {
  248. this.push({
  249. middleware: function (cliOptions) {
  250. path = cliOptions.directory || path || process.cwd()
  251. options = Object.assign({ icons: true, hidden: true }, options)
  252. if (path) {
  253. const serveIndex = require('koa-serve-index')
  254. return serveIndex(path, options)
  255. }
  256. }
  257. })
  258. return this
  259. }
  260. getOptionDefinitions () {
  261. return this
  262. .filter(mw => mw.optionDefinitions)
  263. .map(mw => mw.optionDefinitions)
  264. .reduce(flatten, [])
  265. .map(def => {
  266. def.group = 'middleware'
  267. return def
  268. })
  269. }
  270. compose (options) {
  271. const convert = require('koa-convert')
  272. const middlewareStack = this
  273. .filter(mw => mw.middleware)
  274. .map(mw => mw.middleware)
  275. .map(middleware => middleware(options))
  276. .filter(middleware => middleware)
  277. .reduce(flatten, [])
  278. .map(convert)
  279. // console.error(require('util').inspect(middlewareStack, { depth: 3, colors: true }))
  280. return compose(middlewareStack)
  281. }
  282. }
  283. module.exports = MiddlewareStack
  284. function parseRewriteRules (rules) {
  285. return rules && rules.map(rule => {
  286. if (t.isString(rule)) {
  287. const matches = rule.match(/(\S*)\s*->\s*(\S*)/)
  288. if (!(matches && matches.length >= 3)) throw new Error('Invalid rule: ' + rule)
  289. return {
  290. from: matches[1],
  291. to: matches[2]
  292. }
  293. } else {
  294. return rule
  295. }
  296. })
  297. }