forked from sintaxi/harp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
282 lines (234 loc) · 7.29 KB
/
middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
var path = require("path")
var fs = require("fs")
var jade = require("jade")
var helpers = require("./helpers")
var mime = require("mime")
var polymer = require('terraform')
var pkg = require('../package.json')
var send = require('../node_modules/connect/node_modules/send')
, utils = require('../node_modules/connect/lib/utils')
, parse = utils.parseUrl
, url = require('url')
exports.notMultihostURL = function(req, rsp, next){
var host = req.headers.host
var hostname = host.split(':')[0]
var arr = hostname.split(".")
var port = host.split(':')[1] ? ':' + host.split(':')[1] : ''
if(hostname == "127.0.0.1" || hostname == "localhost"){
rsp.statusCode = 307
rsp.setHeader('Location', 'http://harp.nu' + port)
rsp.end("redirecting you to http://harp.nu" + port)
}else if(arr.length == 4){
arr.pop()
arr.push('io')
var link = 'http://' + arr.join('.') + port
var body = "Local server does not support history. Perhaps you are looking for <href='" + link + "'>" + link + "</a>."
rsp.statusCode = 307
rsp.end(body)
}else if(arr.length > 4){
arr.shift()
var link = 'http://' + arr.join('.') + port
rsp.statusCode = 307
rsp.setHeader('Location', link)
rsp.end("redirecting you to " + link)
}else{
next()
}
}
exports.index = function(dirPath){
return function(req, rsp, next){
var host = req.headers.host
var hostname = host.split(':')[0]
var arr = hostname.split(".")
var port = host.split(':')[1] ? ':' + host.split(':')[1] : ''
if(arr.length == 2){
fs.readdir(dirPath, function(err, files){
var projects = []
files.forEach(function(file){
if(file.split(".").length == 3){
var portal = file.split('.')
portal.shift()
var local = file.split('.')
local.pop()
local.pop()
local.push(host)
projects.push({
"name" : file,
"localUrl" : 'http://' + local.join('.'),
"remoteUrl" : 'http://' + file,
"portalUrl" : 'http://' + portal.join('.') + '/apps/' + file,
"localPath" : path.resolve(dirPath, file)
})
}
})
var poly = polymer.root(__dirname + "/templates")
poly.render("index.jade", { pkg: pkg, projects: projects, layout: "layout.jade" }, function(error, body){
rsp.end(body)
})
})
}else{
next()
}
}
}
exports.hostProjectFinder = function(dirPath){
return function(req, rsp, next){
var host = req.headers.host
var hostname = host.split(':')[0]
var matches = []
fs.readdir(dirPath, function(err, files){
[".io", ".me"].forEach(function(ext){
var val = hostname.replace(/\.\w+$/, ext)
if(files.indexOf(val) !== -1){
matches.push(val)
}
})
;[".harpapp.io"].forEach(function(ext){
var val = hostname.replace(/\.\w+\.\w+$/, ext)
if(files.indexOf(val) !== -1){
matches.push(val)
}
})
if(matches.length > 0){
req.projectPath = path.resolve(dirPath, matches[0])
next()
}else{
rsp.end("Cannot find project")
}
})
}
}
exports.regProjectFinder = function(projectPath){
return function(req, rsp, next){
req.projectPath = projectPath
next()
}
}
exports.static = function(req, res, next) {
var options = {}
var redirect = true
if ('GET' != req.method && 'HEAD' != req.method) return next();
var pathn = parse(req).pathname;
var pause = utils.pause(req);
function resume() {
next();
pause.resume();
}
function directory() {
if (!redirect) return resume();
var pathname = url.parse(req.originalUrl).pathname;
res.statusCode = 301;
res.setHeader('Location', pathname + '/');
res.end('Redirecting to ' + utils.escape(pathname) + '/');
}
function error(err) {
if (404 == err.status) return resume();
next(err);
}
send(req, pathn)
.maxage(options.maxAge || 0)
.root(path.resolve(req.projectPath, "public"))
.hidden(options.hidden)
.on('error', error)
.on('directory', directory)
.pipe(res)
}
/**
* Opens the (optional) harp.json file and sets the config settings.
*/
exports.parseHarpConfig = function(req, rsp, next){
try{
req.config = helpers.config(req.projectPath)
}catch(error){
error.project = req.headers.host
return polymer.root(__dirname + "/templates").render("error.jade", error, function(err, body){
rsp.statusCode = 500
rsp.end(body)
})
}
next()
}
/**
* Sets up the poly object
*/
exports.poly = function(req, rsp, next){
req.poly = polymer.root(path.join(req.projectPath, 'public'), req.config.globals)
next()
}
/**
* Asset Pipeline
*/
exports.process = function(req, rsp, next){
var normalizedPath = helpers.normalizeUrl(req.url)
var priorityList = polymer.helpers.buildPriorityList(normalizedPath)
var sourceFile = polymer.helpers.findFirstFile(path.join(req.projectPath, "public"), priorityList)
/**
* We GTFO if we don't have a source file.
*/
if(!sourceFile) return next()
/**
* Now we let Polymer handle the asset pipeline.
*/
req.poly.render(sourceFile, function(error, body){
if(error){
var locals = {
project: req.headers.host,
name: error.name,
message: error.message,
filename: sourceFile,
stack: error.stack
}
if(polymer.helpers.outputType(sourceFile) == 'css'){
rsp.status = 500
rsp.end(helpers.cssError(locals))
}else{
polymer.root(__dirname + "/templates").render("error.jade", locals, function(err, body){
rsp.status = 500
rsp.end(body)
})
}
}else{
if(!body) return next() // 404
var outputType = polymer.helpers.outputType(sourceFile)
var mimeType = helpers.mimeType(outputType)
var charset = mime.charsets.lookup(mimeType)
rsp.statusCode = 200
rsp.setHeader('Content-Type', mimeType + (charset ? '; charset=' + charset : ''))
rsp.setHeader('Content-Length', body.length)
rsp.end(body)
}
})
}
exports.customNotFound = function(req, rsp, next){
// TODO: look for 404.html first
var publicPath = path.join(req.projectPath, "public")
var priorityList = polymer.helpers.buildPriorityList("404.html")
var sourceFile = polymer.helpers.findFirstFile(publicPath, priorityList)
if(!sourceFile) return next()
req.poly.render(sourceFile, function(error, body){
if(error){
// TODO: make this better
rsp.statusCode = 404;
rsp.end("There is an error in your " + sourceFile + " file")
}else{
if(!body) return next()
var type = helpers.mimeType("html")
var charset = mime.charsets.lookup(type)
rsp.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
rsp.setHeader('Content-Length', body.length);
rsp.statusCode = 404;
rsp.end(body)
}
})
}
exports.devFallbackNotFound = function(req, rsp){
var locals = {
project: req.headers.host,
name: "Page Not Found",
layout: "layout.jade"
}
polymer.root(__dirname + "/templates").render("404.jade", locals, function(err, body){
rsp.status = 500
rsp.end(body)
})
}