forked from shimaore/zappajs
-
Notifications
You must be signed in to change notification settings - Fork 28
/
zappa.coffee
executable file
·607 lines (516 loc) · 18.6 KB
/
zappa.coffee
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# **Zappa** is a [CoffeeScript](http://coffeescript.org) DSL-ish interface for building web apps on the
# [node.js](http://nodejs.org) runtime, integrating [express](http://expressjs.com), [socket.io](http://socket.io)
# and other best-of-breed libraries.
zappa = version: '0.4.2'
codename = 'Wowie Zowie'
log = console.log
fs = require 'fs'
path = require 'path'
uuid = require 'node-uuid'
jquery = fs.readFileSync(__dirname + '/../vendor/jquery-1.7.2.min.js').toString()
sammy = fs.readFileSync(__dirname + '/../vendor/sammy-0.7.1.min.js').toString()
uglify = require 'uglify-js'
# Soft dependencies:
jsdom = null
# CoffeeScript-generated JavaScript may contain anyone of these; when we "rewrite"
# a function (see below) though, it loses access to its parent scope, and consequently to
# any helpers it might need. So we need to reintroduce these helpers manually inside any
# "rewritten" function.
coffeescript_helpers = """
var __slice = Array.prototype.slice;
var __hasProp = Object.prototype.hasOwnProperty;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
var __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype;
return child; };
var __indexOf = Array.prototype.indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] === item) return i;
} return -1; };
""".replace /\n/g, ''
minify = (js) ->
ast = uglify.parser.parse(js)
ast = uglify.uglify.ast_mangle(ast)
ast = uglify.uglify.ast_squeeze(ast)
uglify.uglify.gen_code(ast)
# Shallow copy attributes from `sources` (array of objects) to `recipient`.
# Does NOT overwrite attributes already present in `recipient`.
copy_data_to = (recipient, sources) ->
for obj in sources
for k, v of obj
recipient[k] = v unless recipient[k]
# Zappa FS
zappa_fs = {}
# Patch Node.js's `fs`.
native_readFileSync = fs.readFileSync
native_readFile = fs.readFile
native_name = (p) ->
p.replace /\/.zappa-[^\/]+/, ''
fs.readFileSync = (p,encoding) ->
zappa_fs[p] ? native_readFileSync.apply fs, [native_name(p), encoding]
fs.readFile = (p,encoding,callback) ->
view = zappa_fs[p]
if view
if typeof encoding is 'function' and not callback?
callback = encoding
callback null, view
else
native_readFile.apply fs, [native_name(p),encoding,callback]
native_existsSync = path.existsSync
native_exists = path.exists
path.existsSync = fs.existsSync = (p) ->
zappa_fs[p]? or native_existsSync native_name(p)
path.exists = fs.exists = (p,callback) ->
if zappa_fs[p]?
callback true
else
native_exists.apply p, [native_name(p),callback]
# Express must first be called after we modify the `fs` module.
express = require 'express'
socketio = require 'socket.io'
# Takes in a function and builds express/socket.io apps based on the rules contained in it.
zappa.app = (func,options={}) ->
context = {id: uuid(), zappa, express}
context.real_root = path.dirname(module.parent.filename)
context.root = path.join context.real_root, ".zappa-#{context.id}"
# Storage for user-provided stuff.
# Views are kept at the module level.
ws_handlers = {}
helpers = {}
postrenders = {}
app = context.app = express()
if options.https?
app.server = require('https').createServer options.https, app
else
app.server = require('http').createServer app
io = if options.disable_io then null else context.io = socketio.listen(app.server)
# Reference to the zappa client, the value will be set later.
client = null
# Tracks if the zappa middleware is already mounted (`@use 'zappa'`).
zappa_used = no
# Provide register (as in Express 2)
compilers = {}
get_compiler = (ext) ->
compile = compilers[ext]
if not compile?
compile = compilers[ext] = require(ext.slice 1).compile
if not compile?
throw new Error "Cannot find a compiler for #{ext}"
compile
register = (ext,obj) ->
if ext[0] isnt '.'
ext = '.' + ext
compile = obj.compile
if not compile
throw new Error "register #{ext} must provide a .compile"
# Register the compiler so that context.view may use it.
compilers[ext] = compile
# Register it with Express natively.
renderFile = (path,options,next) ->
# Use cached renderer if present.
tpl = renderFile[path]
if tpl
return next null, tpl options
# Build renderer.
fs.readFile path, 'utf8', (err,str) ->
if err then return next err
tpl = compile str, options
if options.cache then renderFile[path] = tpl
next null, tpl options
app.engine ext, renderFile
# Zappa's default settings.
app.set 'view engine', 'coffee'
register '.coffee', zappa.adapter 'coffeecup',
blacklist: ['format', 'autoescape', 'locals', 'hardcode', 'cache']
# Sets default view dir to @root (`path.dirname(module.parent.filename)`).
app.set 'views', path.join(context.root, '/views')
for verb in ['get', 'post', 'put', 'del']
do (verb) ->
context[verb] = (args...) ->
arity = args.length
if arity > 1
route
verb: verb
path: args[0]
middleware: args[1...arity-1]
handler: args[arity-1]
else
for k, v of arguments[0]
route verb: verb, path: k, handler: v
context.client = (obj) ->
context.use 'zappa' unless zappa_used
for k, v of obj
js = ";zappa.run(#{v});"
js = minify(js) if app.settings['minify']
route verb: 'get', path: k, handler: js, contentType: 'js'
context.coffee = (obj) ->
for k, v of obj
js = ";#{coffeescript_helpers}(#{v})();"
js = minify(js) if app.settings['minify']
route verb: 'get', path: k, handler: js, contentType: 'js'
context.js = (obj) ->
for k, v of obj
js = String(v)
js = minify(js) if app.settings['minify']
route verb: 'get', path: k, handler: js, contentType: 'js'
context.css = (obj) ->
for k, v of obj
css = String(v)
route verb: 'get', path: k, handler: css, contentType: 'css'
options.require_css ?= []
if typeof options.require_css is 'string'
options.require_css = [options.require_css]
for name in options.require_css
context[name] = (obj) ->
for k, v of obj
css = require(name).render v, filename: k, (err, css) ->
throw err if err
route verb: 'get', path: k, handler: css, contentType: 'css'
context.helper = (obj) ->
for k, v of obj
helpers[k] = v
context.postrender = (obj) ->
jsdom = require 'jsdom'
for k, v of obj
postrenders[k] = v
context.on = (obj) ->
for k, v of obj
ws_handlers[k] = v
partial = (k,options) ->
ext = path.extname k
if not ext
ext = '.' + app.get 'view engine'
k = k + ext
tpl = partial[k]
# Use cached renderer
if options.cache and tpl
return tpl options
# Compile renderer
file = path.join context.root, k
compile = get_compiler ext
tpl = compile fs.readFileSync(file, 'utf8'), options
if options.cache then partial[k] = tpl
tpl options
context.view = (obj) ->
for k, v of obj
ext = path.extname k
p = path.join app.get('views'), k
zappa_fs[p] = v # I'm not even sure this is needed -- Express doesn't ask for it
if not ext
ext = '.' + app.get 'view engine'
zappa_fs[p+ext] = v
context.register = (obj) ->
for k, v of obj
register '.' + k, v
context.set = (obj) ->
for k, v of obj
app.set k, v
context.enable = ->
app.enable i for i in arguments
context.disable = ->
app.disable i for i in arguments
context.use = ->
zappa_middleware =
# Connect `static` middlewate uses fs.stat().
static: (p = path.join(context.real_root, '/public')) ->
express.static(p)
zappa: ->
(req, res, next) ->
send = (code) ->
res.contentType 'js'
res.send code
if req.method.toUpperCase() isnt 'GET' then next()
else
switch req.url
when '/zappa/zappa.js' then send client
when '/zappa/jquery.js' then send jquery
when '/zappa/sammy.js' then send sammy
else next()
use = (name, arg = null) ->
zappa_used = yes if name is 'zappa'
if zappa_middleware[name]
app.use zappa_middleware[name](arg)
else if typeof express[name] is 'function'
app.use express[name](arg)
for a in arguments
switch typeof a
when 'function' then app.use a
when 'string' then use a
when 'object'
if a.stack? or a.route?
app.use a
else
use k, v for k, v of a
context.configure = (p) ->
if typeof p is 'function' then app.configure p
else app.configure k, v for k, v of p
context.settings = app.settings
context.shared = (obj) ->
context.use 'zappa' unless zappa_used
for k, v of obj
js = ";zappa.run(#{v});"
js = minify(js) if app.settings['minify']
route verb: 'get', path: k, handler: js, contentType: 'js'
v.apply(context, [context])
context.include = (p) ->
sub = if typeof p is 'string' then require path.join(context.root, p) else p
sub.include.apply(context, [context])
apply_helpers = (ctx) ->
for name, helper of helpers
do (name, helper) ->
if typeof helper is 'function'
ctx[name] = (args...) ->
args.push ctx
helper.apply ctx, args
else
ctx[name] = helper
ctx
# Register a route with express.
route = (r) ->
r.middleware ?= []
# Rewrite middleware
r.middleware = r.middleware.map (f) ->
(req,res,next) ->
ctx =
app: app
settings: app.settings
request: req
query: req.query
params: req.params
body: req.body
session: req.session
response: res
next: next
apply_helpers ctx
if app.settings['databag']
data = {}
copy_data_to data, [req.query, req.params, req.body]
switch app.settings['databag']
when 'this' then f.apply(data, [ctx])
when 'param' then f.apply(ctx, [data])
else result = f.apply(ctx, [ctx])
if typeof r.handler is 'string'
app[r.verb] r.path, r.middleware..., (req, res) ->
res.contentType r.contentType if r.contentType?
res.send r.handler
else
app[r.verb] r.path, r.middleware..., (req, res, next) ->
ctx =
app: app
settings: app.settings
request: req
query: req.query
params: req.params
body: req.body
session: req.session
response: res
next: next
send: -> res.send.apply res, arguments
json: -> res.json.apply res, arguments
redirect: -> res.redirect.apply res, arguments
render: ->
if typeof arguments[0] isnt 'object'
render.apply @, arguments
else
for k, v of arguments[0]
render.apply @, [k, v]
render = (name,opts = {},fn) ->
report = fn ? next
# Make sure the second arg is an object.
if typeof opts is 'function'
fn = opts
opts = {}
if app.settings['databag']
opts.params = data
if not opts.postrender?
postrender = fn
else
postrender = (err, str) ->
if err then return report err
# Apply postrender before sending response.
jsdom.env html: str, src: [jquery], done: (err, window) ->
if err then return report err
ctx.window = window
rendered = postrenders[opts.postrender].apply(ctx, [window.$, ctx])
doctype = (window.document.doctype or '') + "\n"
html = doctype + window.document.documentElement.outerHTML
report null, html
if opts.layout is false
layout = postrender
else
# Use the default layout if one isn't given, or layout: true
if opts.layout is true or not opts.layout?
opts.layout = 'layout'
layout = (err,str) ->
if err then return report err
opts.body = str
res.render.call res, opts.layout, opts, postrender
opts.locals ?= {}
opts.locals.partial = (name) ->
partial name, opts
res.render.call res, name, opts, layout
apply_helpers ctx
if app.settings['databag']
data = {}
copy_data_to data, [req.query, req.params, req.body]
# Go!
switch app.settings['databag']
when 'this' then result = r.handler.apply(data, [ctx])
when 'param' then result = r.handler.apply(ctx, [data])
else result = r.handler.apply(ctx, [ctx])
res.contentType(r.contentType) if r.contentType?
if typeof result is 'string' then res.send result
else return result
# Register socket.io handlers.
io?.sockets.on 'connection', (socket) ->
c = {}
build_ctx = ->
ctx =
app: app
io: io
settings: app.settings
socket: socket
id: socket.id
client: c
join: (room) ->
socket.join room
leave: (room) ->
socket.leave room
emit: ->
if typeof arguments[0] isnt 'object'
socket.emit.apply socket, arguments
else
for k, v of arguments[0]
socket.emit.apply socket, [k, v]
broadcast: ->
if typeof arguments[0] isnt 'object'
socket.broadcast.emit.apply socket.broadcast, arguments
else
for k, v of arguments[0]
socket.broadcast.emit.apply socket.broadcast, [k, v]
broadcast_to: (room, args...) ->
if typeof args[0] isnt 'object'
socket.broadcast.to(room).emit.apply socket.broadcast, args
else
for k, v of args[0]
socket.broadcast.to(room).emit.apply socket.broadcast, [k, v]
broadcast_to_all: (room, args...) ->
if typeof args[0] isnt 'object'
socket.broadcast.to(room).emit.apply socket.broadcast, args
socket.emit.apply socket, args
else
for k, v of args[0]
socket.broadcast.to(room).emit.apply socket.broadcast, [k, v]
socket.emit.apply socket, [k, v]
apply_helpers ctx
ctx
ctx = build_ctx()
ws_handlers.connection.apply(ctx, [ctx]) if ws_handlers.connection?
socket.on 'disconnect', ->
ctx = build_ctx()
ws_handlers.disconnect.apply(ctx, [ctx]) if ws_handlers.disconnect?
for name, h of ws_handlers
do (name, h) ->
if name isnt 'connection' and name isnt 'disconnect'
socket.on name, (data, ack) ->
ctx = build_ctx()
ctx.data = data
ctx.ack = ack
switch app.settings['databag']
when 'this' then h.apply(data, [ctx])
when 'param' then h.apply(ctx, [data])
else h.apply(ctx, [ctx])
# Go!
func.apply(context, [context])
# The stringified zappa client.
client = require('./client').build(zappa.version, app.settings)
client = ";#{coffeescript_helpers}(#{client})();"
client = minify(client) if app.settings['minify']
if app.settings['default layout']
context.view layout: ->
doctype 5
html ->
head ->
title @title if @title
if @scripts
for s in @scripts
script src: s + '.js'
script(src: @script + '.js') if @script
if @stylesheets
for s in @stylesheets
link rel: 'stylesheet', href: s + '.css'
link(rel: 'stylesheet', href: @stylesheet + '.css') if @stylesheet
style @style if @style
body @body
context
# zappa.run [host,] [port,] [{options},] root_function
# Takes a function and runs it as a zappa app. Optionally accepts a port number, and/or
# a hostname (any order). The hostname must be a string, and the port number must be
# castable as a number.
# Returns an object where `app` is the express server and `io` is the socket.io handle.
zappa.run = ->
host = null
port = 3000
root_function = null
options =
disable_io: false
require_css: ['stylus']
for a in arguments
switch typeof a
when 'string'
if isNaN( (Number) a ) then host = a
else port = (Number) a
when 'number' then port = a
when 'function' then root_function = a
when 'object'
for k, v of a
switch k
when 'host' then host = v
when 'port' then port = v
when 'css' then options.require_css = v
when 'disable_io' then options.disable_io = v
when 'https' then options.https = v
zapp = zappa.app(root_function,options)
app = zapp.app
if host
app.server.listen port, host
else
app.server.listen port
log 'Express server listening on port %d in %s mode',
app.server.address()?.port, app.settings.env
log "Zappa #{zappa.version} \"#{codename}\" orchestrating the show"
zapp
# Creates a zappa view adapter for templating engine `engine`. This adapter
# can be used with `context.register` and creates params "shortcuts".
#
# Zappa, by default, automatically sends all request params to templates,
# but inside the `params` local.
#
# This adapter adds a "root local" for each of these params, *only*
# if a local with the same name doesn't exist already, *and* the name is not
# in the optional blacklist.
#
# The blacklist is useful to prevent request params from triggering unset
# template engine options.
#
# If `engine` is a string, the adapter will use `require(engine)`. Otherwise,
# it will assume the `engine` param is an object with a `compile` function.
zappa.adapter = (engine, options = {}) ->
options.blacklist ?= []
engine = require(engine) if typeof engine is 'string'
compile: (template, data) ->
template = engine.compile(template, data)
(data) ->
# Merge down `@params` into `@`
# Bonus: if `databag` is enabled, `@params` will be the complete databag.
for k, v of data.params
if typeof data[k] is 'undefined' and k not in options.blacklist
data[k] = v
template(data)
module.exports = zappa.run
module.exports.run = zappa.run
module.exports.app = zappa.app
module.exports.adapter = zappa.adapter
module.exports.version = zappa.version