{"commit":"ec288cbba4266625ef896bcf3f999c6b39f7a1cb","subject":"Disable auto-etaging","message":"Disable auto-etaging\n","repos":"Turistforeningen\/Turbasen,Turbasen\/Turbasen","old_file":"coffee\/server.litcoffee","new_file":"coffee\/server.litcoffee","new_contents":" raven = require 'raven'\n sentry = require '.\/db\/sentry'\n express = require 'express'\n\n auth = require '.\/helper\/auth'\n\n system = require '.\/system'\n collection = require '.\/collection'\n document = require '.\/document'\n\n## Init\n\n app = express()\n\n### Authentication\n\nThis routine is called for all request to the API. It is reponsible for\nauthenticating the user by validating the `api\\_key`. It then sets some request\nsession variables so they become accessible throughout the entire system during\nthe rquest.\n\n app.use '\/', (req, res, next) ->\n return next() if req.originalUrl.substr(0, 17) is '\/CloudHealthCheck'\n\n auth.check req.query.api_key, (err, user) ->\n if user\n res.set 'X-RateLimit-Limit', user.limit\n res.set 'X-RateLimit-Remaining', user.remaining\n res.set 'X-RateLimit-Reset', user.reset\n\n req.user = user\n\n return next err if err\n\n next()\n\n### Configuration\n\n app.use(express.favicon())\n app.use(express.logger(':date :remote-addr - :method :url :status :res[content-length] - :response-time ms')) if not process.env.SILENT\n app.use(express.compress())\n app.use(express.json())\n app.disable('x-powered-by')\n app.disable('etag')\n app.set 'port', process.env.APP_PORT or 8080\n app.use(app.router)\n\n### Error handling\n\nBefore handling the error ours self make sure that it is propperly logged in\nSentry by using the express\/connect middleware.\n\n app.use raven.middleware.express sentry\n\nAll errors passed to `next` or exceptions ends up here. We set the status code\nto `500` if it is not already defined in the `Error` object. We then print the\nerror mesage and stack trace to the console for debug purposes.\n\nLog 401 Unauthorized (warning) and 403 Forbidden (notice) errors to Sentry to\nenhance debugging and oversight as Nasjonal Turbase gets more used.\n\nBefore returning a response to the user the request method is check. HEAD\nrequests shall not contain any body \u2013 this applies for errors as well.\n\n app.use (err, req, res, next) ->\n res.status err.status or 500\n\n if res.statusCode is 401\n sentry.captureMessage \"Invalid API-key #{req.query.api_key}\",\n level: 'warning'\n extra: sentry.parseRequest req, user: req.user\n\n if res.statusCode is 403\n sentry.captureMessage \"Rate limit exceeded for #{req.user.tilbyder}\",\n level: 'notice'\n extra: sentry.parseRequest req, user: req.user\n\n if res.statusCode >= 500\n console.error err.message\n console.error err.stack\n\n return res.end() if req.method is 'HEAD'\n return res.json message: err.message or 'Ukjent feil'\n\nThis the fmous 404 Not Found handler. If no route configuration for the request\nis found, it ends up here. We don't do much fancy about it \u2013 just a standard\nerror message and HTTP status code.\n\n app.use (req, res) -> res.json 404, message: \"Resurs ikke funnet\"\n\n## GET \/\n\n app.get '\/', (req, res) ->\n res.json message: 'Here be dragons'\n\n## GET \/CloudHealthCheck\n\n> So...You\u2019re seeing the dotCloud active health check looking to make sure that\n> your service is up. There is no way for you to disable it, but you can prevent\n> it and you can handle it [1]!\n\n[1] [dotCloud](http:\/\/docs.dotcloud.com\/tutorials\/more\/cloud-health-check\/)\n\n app.all '\/CloudHealthCheck', system.check\n\n## GET \/objekttyper\n\n app.get '\/objekttyper', (req, res, next) ->\n res.json 200, ['turer', 'steder', 'omr\u00e5der', 'grupper', 'arrangementer', 'bilder']\n\n## ALL \/{collection}\n\n app.param 'collection', collection.param\n app.all '\/:collection', (req, res, next) ->\n switch req.method\n when 'OPTIONS' then collection.options req, res, next\n when 'HEAD', 'GET' then collection.get req, res, next\n when 'POST' then collection.post req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## ALL \/{collection}\/{objectid}\n\n app.param 'objectid', document.param\n app.options '\/:collection\/:ojectid', document.options\n app.all '\/:collection\/:objectid', document.all, (req, res, next) ->\n switch req.method\n when 'HEAD', 'GET' then document.get req, res, next\n when 'PUT' then document.put req, res, next\n when 'PATCH' then document.patch req, res, next\n when 'DELETE' then document.delete req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## Start\n\nOk, so if the server is running in stand-alone mode i.e. there is not\n`module.parent` then continue with starting the databse and listening to a port.\n\n if not module.parent\n require('.\/db\/redis')\n require('.\/db\/mongo').once 'ready', ->\n console.log 'Database is open...'\n\n app.listen app.get('port'), ->\n console.log \"Server is listening on port #{app.get('port')}\"\n\nHowever, if there is a `module.parent` don't do all the stuff above. This means\nthat there is some program that is including the server from it, e.g a test, and\nhence it should not listen to a port for incomming connections and rather just\nreturn the application instance so that we can do some testing on it.\n\n else\n module.exports = app\n\n","old_contents":" raven = require 'raven'\n sentry = require '.\/db\/sentry'\n express = require 'express'\n\n auth = require '.\/helper\/auth'\n\n system = require '.\/system'\n collection = require '.\/collection'\n document = require '.\/document'\n\n## Init\n\n app = express()\n\n### Authentication\n\nThis routine is called for all request to the API. It is reponsible for\nauthenticating the user by validating the `api\\_key`. It then sets some request\nsession variables so they become accessible throughout the entire system during\nthe rquest.\n\n app.use '\/', (req, res, next) ->\n return next() if req.originalUrl.substr(0, 17) is '\/CloudHealthCheck'\n\n auth.check req.query.api_key, (err, user) ->\n if user\n res.set 'X-RateLimit-Limit', user.limit\n res.set 'X-RateLimit-Remaining', user.remaining\n res.set 'X-RateLimit-Reset', user.reset\n\n req.user = user\n\n return next err if err\n\n next()\n\n### Configuration\n\n app.use(express.favicon())\n app.use(express.logger(':date :remote-addr - :method :url :status :res[content-length] - :response-time ms')) if not process.env.SILENT\n app.use(express.compress())\n app.use(express.json())\n app.disable('x-powered-by')\n app.set 'port', process.env.APP_PORT or 8080\n app.use(app.router)\n\n### Error handling\n\nBefore handling the error ours self make sure that it is propperly logged in\nSentry by using the express\/connect middleware.\n\n app.use raven.middleware.express sentry\n\nAll errors passed to `next` or exceptions ends up here. We set the status code\nto `500` if it is not already defined in the `Error` object. We then print the\nerror mesage and stack trace to the console for debug purposes.\n\nLog 401 Unauthorized (warning) and 403 Forbidden (notice) errors to Sentry to\nenhance debugging and oversight as Nasjonal Turbase gets more used.\n\nBefore returning a response to the user the request method is check. HEAD\nrequests shall not contain any body \u2013 this applies for errors as well.\n\n app.use (err, req, res, next) ->\n res.status err.status or 500\n\n if res.statusCode is 401\n sentry.captureMessage \"Invalid API-key #{req.query.api_key}\",\n level: 'warning'\n extra: sentry.parseRequest req, user: req.user\n\n if res.statusCode is 403\n sentry.captureMessage \"Rate limit exceeded for #{req.user.tilbyder}\",\n level: 'notice'\n extra: sentry.parseRequest req, user: req.user\n\n if res.statusCode >= 500\n console.error err.message\n console.error err.stack\n\n return res.end() if req.method is 'HEAD'\n return res.json message: err.message or 'Ukjent feil'\n\nThis the fmous 404 Not Found handler. If no route configuration for the request\nis found, it ends up here. We don't do much fancy about it \u2013 just a standard\nerror message and HTTP status code.\n\n app.use (req, res) -> res.json 404, message: \"Resurs ikke funnet\"\n\n## GET \/\n\n app.get '\/', (req, res) ->\n res.json message: 'Here be dragons'\n\n## GET \/CloudHealthCheck\n\n> So...You\u2019re seeing the dotCloud active health check looking to make sure that\n> your service is up. There is no way for you to disable it, but you can prevent\n> it and you can handle it [1]!\n\n[1] [dotCloud](http:\/\/docs.dotcloud.com\/tutorials\/more\/cloud-health-check\/)\n\n app.all '\/CloudHealthCheck', system.check\n\n## GET \/objekttyper\n\n app.get '\/objekttyper', (req, res, next) ->\n res.json 200, ['turer', 'steder', 'omr\u00e5der', 'grupper', 'arrangementer', 'bilder']\n\n## ALL \/{collection}\n\n app.param 'collection', collection.param\n app.all '\/:collection', (req, res, next) ->\n switch req.method\n when 'OPTIONS' then collection.options req, res, next\n when 'HEAD', 'GET' then collection.get req, res, next\n when 'POST' then collection.post req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## ALL \/{collection}\/{objectid}\n\n app.param 'objectid', document.param\n app.options '\/:collection\/:ojectid', document.options\n app.all '\/:collection\/:objectid', document.all, (req, res, next) ->\n switch req.method\n when 'HEAD', 'GET' then document.get req, res, next\n when 'PUT' then document.put req, res, next\n when 'PATCH' then document.patch req, res, next\n when 'DELETE' then document.delete req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## Start\n\nOk, so if the server is running in stand-alone mode i.e. there is not\n`module.parent` then continue with starting the databse and listening to a port.\n\n if not module.parent\n require('.\/db\/redis')\n require('.\/db\/mongo').once 'ready', ->\n console.log 'Database is open...'\n\n app.listen app.get('port'), ->\n console.log \"Server is listening on port #{app.get('port')}\"\n\nHowever, if there is a `module.parent` don't do all the stuff above. This means\nthat there is some program that is including the server from it, e.g a test, and\nhence it should not listen to a port for incomming connections and rather just\nreturn the application instance so that we can do some testing on it.\n\n else\n module.exports = app\n\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"f26a367636c5e1d0e76b5c10bec849e0f7ce4e3f","subject":"Only print 5xx errors to console","message":"Only print 5xx errors to console\n","repos":"Turistforeningen\/Turbasen,Turbasen\/Turbasen","old_file":"coffee\/server.litcoffee","new_file":"coffee\/server.litcoffee","new_contents":" raven = require 'raven'\n sentry = require '.\/db\/sentry'\n express = require 'express'\n\n auth = require '.\/helper\/auth'\n\n system = require '.\/system'\n collection = require '.\/collection'\n document = require '.\/document'\n\n## Init\n\n app = express()\n\n### Authentication\n\nThis routine is called for all request to the API. It is reponsible for\nauthenticating the user by validating the `api\\_key`. It then sets some request\nsession variables so they become accessible throughout the entire system during\nthe rquest.\n\n app.use '\/', (req, res, next) ->\n return next() if req.originalUrl.substr(0, 17) is '\/CloudHealthCheck'\n\n auth.check req.query.api_key, (err, user) ->\n if user\n res.set 'X-RateLimit-Limit', user.limit\n res.set 'X-RateLimit-Remaining', user.remaining\n res.set 'X-RateLimit-Reset', user.reset\n\n req.user = user\n\n return next err if err\n\n next()\n\n### Configuration\n\n app.use(express.favicon())\n app.use(express.logger(':date :remote-addr - :method :url :status :res[content-length] - :response-time ms')) if not process.env.SILENT\n app.set('json spaces', 0) if app.get('env') isnt 'testing'\n app.use(express.compress())\n app.use(express.json())\n app.disable('x-powered-by')\n app.set 'port', process.env.PORT_WWW or 8080\n app.use(app.router)\n\n### Error handling\n\nBefore handling the error ours self make sure that it is propperly logged in\nSentry by using the express\/connect middleware.\n\n app.use raven.middleware.express sentry\n\nAll errors passed to `next` or exceptions ends up here. We set the status code\nto `500` if it is not already defined in the `Error` object. We then print the\nerror mesage and stack trace to the console for debug purposes.\n\nBefore returning a response to the user the request method is check. HEAD\nrequests shall not contain any body \u2013 this applies for errors as well.\n\n app.use (err, req, res, next) ->\n res.status err.status or 500\n\n if res.status >= 500\n console.error err.message\n console.error err.stack\n\n return res.end() if req.method is 'HEAD'\n return res.json message: err.message or 'Ukjent feil'\n\nThis the fmous 404 Not Found handler. If no route configuration for the request\nis found, it ends up here. We don't do much fancy about it \u2013 just a standard\nerror message and HTTP status code.\n\n app.use (req, res) -> res.json 404, message: \"Resurs ikke funnet\"\n\n## GET \/\n\n app.get '\/', (req, res) ->\n res.json message: 'Here be dragons'\n\n## GET \/CloudHealthCheck\n\n> So...You\u2019re seeing the dotCloud active health check looking to make sure that\n> your service is up. There is no way for you to disable it, but you can prevent\n> it and you can handle it [1]!\n\n[1] [dotCloud](http:\/\/docs.dotcloud.com\/tutorials\/more\/cloud-health-check\/)\n\n app.get '\/CloudHealthCheck', system.check\n\n## GET \/objekttyper\n\n app.get '\/objekttyper', (req, res, next) ->\n res.json 200, ['turer', 'steder', 'omr\u00e5der', 'grupper', 'arrangementer', 'bilder']\n\n## ALL \/{collection}\n\n app.param 'collection', collection.param\n app.all '\/:collection', (req, res, next) ->\n switch req.method\n when 'OPTIONS' then collection.options req, res, next\n when 'HEAD', 'GET' then collection.get req, res, next\n when 'POST' then collection.post req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## ALL \/{collection}\/{objectid}\n\n app.param 'objectid', document.param\n app.options '\/:collection\/:ojectid', document.options\n app.all '\/:collection\/:objectid', document.all, (req, res, next) ->\n switch req.method\n when 'HEAD', 'GET' then document.get req, res, next\n when 'PUT' then document.put req, res, next\n when 'PATCH' then document.patch req, res, next\n when 'DELETE' then document.delete req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## Start\n\nOk, so if the server is running in stand-alone mode i.e. there is not\n`module.parent` then continue with starting the databse and listening to a port.\n\n if not module.parent\n require('.\/db\/redis')\n require('.\/db\/mongo').once 'ready', ->\n console.log 'Database is open...'\n\n app.listen app.get('port'), ->\n console.log \"Server is listening on port #{app.get('port')}\"\n\nHowever, if there is a `module.parent` don't do all the stuff above. This means\nthat there is some program that is including the server from it, e.g a test, and\nhence it should not listen to a port for incomming connections and rather just\nreturn the application instance so that we can do some testing on it.\n\n else\n module.exports = app\n\n","old_contents":" raven = require 'raven'\n sentry = require '.\/db\/sentry'\n express = require 'express'\n\n auth = require '.\/helper\/auth'\n\n system = require '.\/system'\n collection = require '.\/collection'\n document = require '.\/document'\n\n## Init\n\n app = express()\n\n### Authentication\n\nThis routine is called for all request to the API. It is reponsible for\nauthenticating the user by validating the `api\\_key`. It then sets some request\nsession variables so they become accessible throughout the entire system during\nthe rquest.\n\n app.use '\/', (req, res, next) ->\n return next() if req.originalUrl.substr(0, 17) is '\/CloudHealthCheck'\n\n auth.check req.query.api_key, (err, user) ->\n if user\n res.set 'X-RateLimit-Limit', user.limit\n res.set 'X-RateLimit-Remaining', user.remaining\n res.set 'X-RateLimit-Reset', user.reset\n\n req.user = user\n\n return next err if err\n\n next()\n\n### Configuration\n\n app.use(express.favicon())\n app.use(express.logger(':date :remote-addr - :method :url :status :res[content-length] - :response-time ms')) if not process.env.SILENT\n app.set('json spaces', 0) if app.get('env') isnt 'testing'\n app.use(express.compress())\n app.use(express.json())\n app.disable('x-powered-by')\n app.set 'port', process.env.PORT_WWW or 8080\n app.use(app.router)\n\n### Error handling\n\nBefore handling the error ours self make sure that it is propperly logged in\nSentry by using the express\/connect middleware.\n\n app.use raven.middleware.express sentry\n\nAll errors passed to `next` or exceptions ends up here. We set the status code\nto `500` if it is not already defined in the `Error` object. We then print the\nerror mesage and stack trace to the console for debug purposes.\n\nBefore returning a response to the user the request method is check. HEAD\nrequests shall not contain any body \u2013 this applies for errors as well.\n\n app.use (err, req, res, next) ->\n res.status(err.status or 500)\n\n console.error err.message\n console.error err.stack\n\n return res.end() if req.method is 'HEAD'\n return res.json message: err.message or 'Ukjent feil'\n\nThis the fmous 404 Not Found handler. If no route configuration for the request\nis found, it ends up here. We don't do much fancy about it \u2013 just a standard\nerror message and HTTP status code.\n\n app.use (req, res) -> res.json 404, message: \"Resurs ikke funnet\"\n\n## GET \/\n\n app.get '\/', (req, res) ->\n res.json message: 'Here be dragons'\n\n## GET \/CloudHealthCheck\n\n> So...You\u2019re seeing the dotCloud active health check looking to make sure that\n> your service is up. There is no way for you to disable it, but you can prevent\n> it and you can handle it [1]!\n\n[1] [dotCloud](http:\/\/docs.dotcloud.com\/tutorials\/more\/cloud-health-check\/)\n\n app.get '\/CloudHealthCheck', system.check\n\n## GET \/objekttyper\n\n app.get '\/objekttyper', (req, res, next) ->\n res.json 200, ['turer', 'steder', 'omr\u00e5der', 'grupper', 'arrangementer', 'bilder']\n\n## ALL \/{collection}\n\n app.param 'collection', collection.param\n app.all '\/:collection', (req, res, next) ->\n switch req.method\n when 'OPTIONS' then collection.options req, res, next\n when 'HEAD', 'GET' then collection.get req, res, next\n when 'POST' then collection.post req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## ALL \/{collection}\/{objectid}\n\n app.param 'objectid', document.param\n app.options '\/:collection\/:ojectid', document.options\n app.all '\/:collection\/:objectid', document.all, (req, res, next) ->\n switch req.method\n when 'HEAD', 'GET' then document.get req, res, next\n when 'PUT' then document.put req, res, next\n when 'PATCH' then document.patch req, res, next\n when 'DELETE' then document.delete req, res, next\n else res.json 405, message: \"HTTP Method #{req.method.toUpperCase()} Not Allowed\"\n\n## Start\n\nOk, so if the server is running in stand-alone mode i.e. there is not\n`module.parent` then continue with starting the databse and listening to a port.\n\n if not module.parent\n require('.\/db\/redis')\n require('.\/db\/mongo').once 'ready', ->\n console.log 'Database is open...'\n\n app.listen app.get('port'), ->\n console.log \"Server is listening on port #{app.get('port')}\"\n\nHowever, if there is a `module.parent` don't do all the stuff above. This means\nthat there is some program that is including the server from it, e.g a test, and\nhence it should not listen to a port for incomming connections and rather just\nreturn the application instance so that we can do some testing on it.\n\n else\n module.exports = app\n\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"67cb9df3dd983929201d2178c1ac2fff218f644e","subject":"Literate CofeeScript underway","message":"Literate CofeeScript underway\n","repos":"funjs\/friebyrd","old_file":"lib\/friebyrd.litcoffee","new_file":"lib\/friebyrd.litcoffee","new_contents":"We always start with the JavaScript-like magic scoping mojo!\n\n ((root) ->\n root = this\n _ = root._ || require 'underscore'\n F = {}\n\nNon-determinism\n---------------\n\nNon-deterministic functions are functions that can have more (or less) than one result. As known from logic, a binary relation xRy (where x \u2208 X, y \u2208 Y) can be represented by a *function* `X -> PowerSet{Y}`. As usual in computer science, we interpret the set `PowerSet{Y}` as a multi-set (realized as a regular scheme list). Compare with SQL, which likewise uses multisets and sequences were sets are properly called for. Also compare with [Wadler's \"representing failure as a list of successes.\"](http:\/\/citeseer.uark.edu:8080\/citeseerx\/showciting;jsessionid=FF5F5EAA9D94B1A8618C49C37451D762?cid=377301).\n\nThus, we represent a 'relation' (aka `non-deterministic function') as a regular CoffeeScript function that returns an array of possible results.\n\nFirst, we define two primitive non-deterministic functions; one of them yields no result whatsoever for any argument; the other merely returns its argument as the sole result.\n\n F.succeed = (result) -> [result]\n F.fail = _.always []\n\n\n\n disjunction = (l, r) ->\n (x) -> _.cat(l(x), r(x))\n conjunction = (l, r) ->\n (x) -> _.mapcat(l(x), r)\n\n F.disj = () ->\n return F.fail if _.isEmpty(arguments)\n disjunction(_.first(arguments), F.disj.apply(this, _.rest(arguments)))\n\n F.conj = () ->\n clauses = _.toArray(arguments)\n return F.succeed if _.isEmpty(clauses)\n return _.first(clauses) if _.size(clauses) is 1\n conjunction(_.first(clauses),\n (s) -> F.conj.apply(null, _.rest(clauses))(s))\n\n # Knowledge representation\n # ------------------------\n\n class LVar\n constructor: (@name) ->\n\n F.lvar = (name) -> new LVar(name)\n F.isLVar = (v) -> (v instanceof LVar)\n\n find = (v, bindings) ->\n lvar = bindings.lookup(v)\n return lvar if F.isLVar(v)\n if _.isArray(lvar)\n if _.isEmpty(lvar)\n return lvar\n else\n return _.cons(find(_.first(lvar), bindings), find(_.rest(lvar), bindings))\n lvar\n\n class Bindings\n constructor: (seed = {}) ->\n @binds = _.merge({}, seed)\n extend: (lvar, value) ->\n o = {}\n o[lvar.name] = value\n new Bindings(_.merge(@binds, o))\n has: (lvar) ->\n @binds.hasOwnProperty(lvar.name)\n lookup: (lvar) ->\n return lvar if !F.isLVar(lvar)\n return this.lookup(@binds[lvar.name]) if this.has(lvar)\n lvar\n\n F.ignorance = new Bindings()\n\n # Unification\n # -----------\n\n F.unify = (l, r, bindings) ->\n t1 = bindings.lookup(l)\n t2 = bindings.lookup(r)\n\n if _.isEqual(t1, t2)\n return s\n if F.isLVar(t1)\n return bindings.extend(t1, t2)\n if F.isLVar(t2)\n return bindings.extend(t2, t1)\n if _.isArray(t1) && _.isArray(t2)\n s = F.unify(_.first(t1), _.first(t2), bindings)\n s = if (s isnt null) then F.unify(_.rest(t1), _.rest(t2), bindings) else s\n return s\n return null\n\n # Operational logic\n # -----------------\n\n F.goal = (l, r) ->\n (bindings) ->\n result = F.unify(l, r, bindings)\n return F.succeed(result) if result isnt null\n return F.fail(bindings)\n\n F.run = (goal) ->\n goal(F.ignorance)\n\n # Logico\n # ------\n\n F.choice = ($v, list) ->\n return F.fail if _.isEmpty(list)\n\n F.disj(F.goal($v, _.first(list)),\n F.choice($v, _.rest(list)))\n\n # Exports and sundries\n # --------------------\n\n if module?\n module.exports = F\n else\n root.F = F\n\n)(this)\n","old_contents":"We always start with the JavaScript-like magic scoping mojo!\n\n ((root) ->\n root = this\n _ = root._ || require 'underscore'\n F = {}\n\nNon-determinism\n---------------\n\nNon-deterministic functions are functions that can have more (or less) than one result. As known from logic, a binary relation xRy (where x \u2208 X, y \u2208 Y) can be represented by a *function* `X -> PowerSet{Y}`. As usual in computer science, we interpret the set `PowerSet{Y}` as a multi-set (realized as a regular scheme list). Compare with SQL, which likewise uses multisets and sequences were sets are properly called for. Also compare with [Wadler's \"representing failure as a list of successes.\"](http:\/\/citeseer.uark.edu:8080\/citeseerx\/showciting;jsessionid=FF5F5EAA9D94B1A8618C49C37451D762?cid=377301).\n\nThus, we represent a 'relation' (aka `non-deterministic function') as a regular CoffeeScript function that returns an array of possible results.\n\n F.succeed = (result) -> [result]\n F.fail = _.always []\n\n disjunction = (l, r) ->\n (x) -> _.cat(l(x), r(x))\n conjunction = (l, r) ->\n (x) -> _.mapcat(l(x), r)\n\n F.disj = () ->\n return F.fail if _.isEmpty(arguments)\n disjunction(_.first(arguments), F.disj.apply(this, _.rest(arguments)))\n\n F.conj = () ->\n clauses = _.toArray(arguments)\n return F.succeed if _.isEmpty(clauses)\n return _.first(clauses) if _.size(clauses) is 1\n conjunction(_.first(clauses),\n (s) -> F.conj.apply(null, _.rest(clauses))(s))\n\n # Knowledge representation\n # ------------------------\n\n class LVar\n constructor: (@name) ->\n\n F.lvar = (name) -> new LVar(name)\n F.isLVar = (v) -> (v instanceof LVar)\n\n find = (v, bindings) ->\n lvar = bindings.lookup(v)\n return lvar if F.isLVar(v)\n if _.isArray(lvar)\n if _.isEmpty(lvar)\n return lvar\n else\n return _.cons(find(_.first(lvar), bindings), find(_.rest(lvar), bindings))\n lvar\n\n class Bindings\n constructor: (seed = {}) ->\n @binds = _.merge({}, seed)\n extend: (lvar, value) ->\n o = {}\n o[lvar.name] = value\n new Bindings(_.merge(@binds, o))\n has: (lvar) ->\n @binds.hasOwnProperty(lvar.name)\n lookup: (lvar) ->\n return lvar if !F.isLVar(lvar)\n return this.lookup(@binds[lvar.name]) if this.has(lvar)\n lvar\n\n F.ignorance = new Bindings()\n\n # Unification\n # -----------\n\n F.unify = (l, r, bindings) ->\n t1 = bindings.lookup(l)\n t2 = bindings.lookup(r)\n\n if _.isEqual(t1, t2)\n return s\n if F.isLVar(t1)\n return bindings.extend(t1, t2)\n if F.isLVar(t2)\n return bindings.extend(t2, t1)\n if _.isArray(t1) && _.isArray(t2)\n s = F.unify(_.first(t1), _.first(t2), bindings)\n s = if (s isnt null) then F.unify(_.rest(t1), _.rest(t2), bindings) else s\n return s\n return null\n\n # Operational logic\n # -----------------\n\n F.goal = (l, r) ->\n (bindings) ->\n result = F.unify(l, r, bindings)\n return F.succeed(result) if result isnt null\n return F.fail(bindings)\n\n F.run = (goal) ->\n goal(F.ignorance)\n\n # Logico\n # ------\n\n F.choice = ($v, list) ->\n return F.fail if _.isEmpty(list)\n\n F.disj(F.goal($v, _.first(list)),\n F.choice($v, _.rest(list)))\n\n # Exports and sundries\n # --------------------\n\n if module?\n module.exports = F\n else\n root.F = F\n\n)(this)\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"f9aa4a07598792bd32c61d2b0266151b43536f67","subject":"log.time leaks support","message":"log.time leaks support\n","repos":"Neft-io\/neft,Neft-io\/neft,Neft-io\/neft,Neft-io\/neft,Neft-io\/neft,Neft-io\/neft","old_file":"src\/log\/index.litcoffee","new_file":"src\/log\/index.litcoffee","new_contents":"# Log\n\nAccess it with:\n```javascript\nconst { log } = Neft;\n```\n\n 'use strict'\n\n utils = require 'src\/utils'\n assert = require 'src\/assert'\n\n {bind} = Function\n {isArray} = Array\n {unshift} = Array::\n\n linesPrefix = ''\n\n fromArgs = (args) ->\n str = ''\n str += \"#{arg} \u2192 \" for arg in args\n str = str.substring 0, str.length - 3\n\n lines = str.split '\\n'\n str = ''\n for line in lines\n str += \"#{linesPrefix}#{line}\\n\"\n str = str.slice 0, -1\n\n str\n\n callOnce = do ->\n usedMessages = Object.create null\n ->\n msg = fromArgs arguments\n if usedMessages[msg]\n return -1\n usedMessages[msg] = true\n @ arguments...\n\n## **Class** Log\n\n class Log\n @LOGS_METHODS = ['log', 'info', 'warn', 'error', 'time', 'ok']\n\n @MARKERS =\n white: (str) -> \"LOG: #{str}\"\n green: (str) -> \"OK: #{str}\"\n gray: (str) -> \"#{str}\"\n blue: (str) -> \"INFO: #{str}\"\n yellow: (str) -> \"WARN: #{str}\"\n red: (str) -> \"ERROR: #{str}\"\n\n @setGlobalLinesPrefix = (prefix) ->\n linesPrefix = prefix\n\n @time = Date.now\n @timeDiff = (since) -> Log.time() - since\n\n constructor: (prefixes = [], @parentScope) ->\n @prefixes = prefixes\n assert.isArray prefixes\n\n # bind all logs methods\n args = utils.clone(prefixes)\n args.unshift @\n\n for name in @constructor.LOGS_METHODS\n @[name] = bind.apply @[name], args\n @[name].once = callOnce\n\n @[key] = value for key, value of @\n if typeof @['lo' + 'g'] is 'function'\n func = =>\n @log.apply func, arguments\n func.once = callOnce\n func.constructor = @constructor\n return utils.merge func, @\n\n _write: console?['lo' + 'g'].bind(console) or (->)\n _writeError: console?['erro' + 'r'].bind(console) or (->)\n\n### *Integer* log.LOG\n\n### *Integer* log.INFO\n\n### *Integer* log.OK\n\n### *Integer* log.WARN\n\n### *Integer* log.ERROR\n\n### *Integer* log.TIME\n\n### *Integer* log.ALL\n\n i = 0\n LOG: 1<\n unless log.enabled & type\n false\n else if log.parentScope\n isEnabled log.parentScope, type\n else\n true\n\n### log([*Any* messages...])\n\nPrints the given messages into the console.\n\n```javascript\nlog(\"Log me now!\");\n\nlog(\"setName()\", \"db time\");\n\/\/ will be logged as \"setName() \u2192 db time\"\n```\n\n @::['log'] = ->\n if isEnabled(@, @LOG)\n @_write @constructor.MARKERS.white fromArgs arguments\n return\n\n### log.info([*Any* messages...])\n\nPrints the given messages into the console with a blue color.\n\n info: ->\n if isEnabled(@, @INFO)\n @_write @constructor.MARKERS.blue fromArgs arguments\n return\n\n### log.ok([*Any* messages...])\n\nPrints the given messages into the console with a green color.\n\n```javascript\nlog.ok(\"Data has been successfully sent!\");\n```\n\n ok: ->\n if isEnabled(@, @OK)\n @_write @constructor.MARKERS.green fromArgs arguments\n return\n\n### log.warn([*Any* messages...])\n\nPrints the given messages into the console with a yellow color.\n\n```javascript\nlog.warn(\"Example warning with some recommendations\");\n```\n\n warn: ->\n if isEnabled(@, @WARN)\n @_write @constructor.MARKERS.yellow fromArgs arguments\n return\n\n### log.error([*Any* messages...])\n\nPrints the given messages into the console with a red color.\n\n```javascript\nlog.error(\"Error occurs, ... in file ...\");\n```\n\n error: ->\n if isEnabled(@, @ERROR)\n @_writeError @constructor.MARKERS.red fromArgs arguments\n return\n\n### *Array* log.time()\n\nReturns an id used to measure execution time by the `log.end()` function.\n\n```javascript\nfunction findPath(){\n var logtime = log.time('findPath()');\n\n \/\/ ... some complex algorithm ...\n\n log.end(logtime);\n}\n\nfindPath();\n```\n\n time: ->\n unless isEnabled(@, @TIME)\n return -1\n\n [@constructor.time(), fromArgs(arguments)]\n\n### log.end(*Array* logTime)\n\nPrints an information about the execution time for the given timer id.\n\n end: (logTime) ->\n diff = @constructor.timeDiff logTime[0]\n diff = diff.toFixed 2\n\n str = \"#{logTime[1]}: #{diff} ms\"\n @_write @constructor.MARKERS.gray str\n\n logTime[0] = 0\n return\n\n### log.scope([*Any* names...])\n\nReturns a new `log` function.\n\nAll prints will be prefixed by the given names.\n\n```javascript\nvar log = log.scope(\"Example file\");\n\nlog(\"hello\");\n\/\/ \"Example file \u2192 hello\"\n```\n\n scope: (args...) ->\n if @prefixes\n unshift.apply args, @prefixes\n\n new @constructor args, @\n\n # implementation\n impl = switch true\n when utils.isNode\n require '.\/impls\/node\/index.coffee'\n when utils.isBrowser\n require '.\/impls\/browser\/index.coffee'\n\n LogImpl = if typeof impl is 'function' then impl Log else Log\n exports = module.exports = new LogImpl\n exports.Log = Log\n","old_contents":"# Log\n\nAccess it with:\n```javascript\nconst { log } = Neft;\n```\n\n 'use strict'\n\n utils = require 'src\/utils'\n assert = require 'src\/assert'\n\n {bind} = Function\n {isArray} = Array\n {unshift} = Array::\n\n linesPrefix = ''\n\n fromArgs = (args) ->\n str = ''\n str += \"#{arg} \u2192 \" for arg in args\n str = str.substring 0, str.length - 3\n\n lines = str.split '\\n'\n str = ''\n for line in lines\n str += \"#{linesPrefix}#{line}\\n\"\n str = str.slice 0, -1\n\n str\n\n callOnce = do ->\n usedMessages = Object.create null\n ->\n msg = fromArgs arguments\n if usedMessages[msg]\n return -1\n usedMessages[msg] = true\n @ arguments...\n\n## **Class** Log\n\n class Log\n @LOGS_METHODS = ['log', 'info', 'warn', 'error', 'time', 'ok']\n\n @TIMES_LEN = 50\n\n @MARKERS =\n white: (str) -> \"LOG: #{str}\"\n green: (str) -> \"OK: #{str}\"\n gray: (str) -> \"#{str}\"\n blue: (str) -> \"INFO: #{str}\"\n yellow: (str) -> \"WARN: #{str}\"\n red: (str) -> \"ERROR: #{str}\"\n\n @setGlobalLinesPrefix = (prefix) ->\n linesPrefix = prefix\n\n @time = Date.now\n @timeDiff = (since) -> Log.time() - since\n @times = new Array Log.TIMES_LEN\n\n for _, i in @times\n @times[i] = [0, '']\n\n constructor: (prefixes = [], @parentScope) ->\n @prefixes = prefixes\n assert.isArray prefixes\n\n # bind all logs methods\n args = utils.clone(prefixes)\n args.unshift @\n\n for name in @constructor.LOGS_METHODS\n @[name] = bind.apply @[name], args\n @[name].once = callOnce\n\n @[key] = value for key, value of @\n if typeof @['lo' + 'g'] is 'function'\n func = =>\n @log.apply func, arguments\n func.once = callOnce\n func.constructor = @constructor\n return utils.merge func, @\n\n _write: console?['lo' + 'g'].bind(console) or (->)\n _writeError: console?['erro' + 'r'].bind(console) or (->)\n\n### *Integer* log.LOG\n\n### *Integer* log.INFO\n\n### *Integer* log.OK\n\n### *Integer* log.WARN\n\n### *Integer* log.ERROR\n\n### *Integer* log.TIME\n\n### *Integer* log.ALL\n\n i = 0\n LOG: 1<\n unless log.enabled & type\n false\n else if log.parentScope\n isEnabled log.parentScope, type\n else\n true\n\n### log([*Any* messages...])\n\nPrints the given messages into the console.\n\n```javascript\nlog(\"Log me now!\");\n\nlog(\"setName()\", \"db time\");\n\/\/ will be logged as \"setName() \u2192 db time\"\n```\n\n @::['log'] = ->\n if isEnabled(@, @LOG)\n @_write @constructor.MARKERS.white fromArgs arguments\n return\n\n### log.info([*Any* messages...])\n\nPrints the given messages into the console with a blue color.\n\n info: ->\n if isEnabled(@, @INFO)\n @_write @constructor.MARKERS.blue fromArgs arguments\n return\n\n### log.ok([*Any* messages...])\n\nPrints the given messages into the console with a green color.\n\n```javascript\nlog.ok(\"Data has been successfully sent!\");\n```\n\n ok: ->\n if isEnabled(@, @OK)\n @_write @constructor.MARKERS.green fromArgs arguments\n return\n\n### log.warn([*Any* messages...])\n\nPrints the given messages into the console with a yellow color.\n\n```javascript\nlog.warn(\"Example warning with some recommendations\");\n```\n\n warn: ->\n if isEnabled(@, @WARN)\n @_write @constructor.MARKERS.yellow fromArgs arguments\n return\n\n### log.error([*Any* messages...])\n\nPrints the given messages into the console with a red color.\n\n```javascript\nlog.error(\"Error occurs, ... in file ...\");\n```\n\n error: ->\n if isEnabled(@, @ERROR)\n @_writeError @constructor.MARKERS.red fromArgs arguments\n return\n\n### *Integer* log.time()\n\nReturns an id used to measure execution time by the `log.end()` function.\n\n```javascript\nfunction findPath(){\n var logtime = log.time('findPath()');\n\n \/\/ ... some complex algorithm ...\n\n log.end(logtime);\n}\n\nfindPath();\n```\n\n time: ->\n unless isEnabled(@, @TIME)\n return -1\n\n {times} = @constructor\n\n # get time id and set current time\n for v, i in times when not v[0]\n id = i\n times[i][0] = @constructor.time()\n times[i][1] = fromArgs arguments\n break\n\n assert id?, 'Log times out of range'\n\n id\n\n### log.end(*Integer* id)\n\nPrints an information about the execution time for the given timer id.\n\n end: (id) ->\n if id is -1\n return\n\n time = @constructor.times[id]\n diff = @constructor.timeDiff time[0]\n diff = diff.toFixed 2\n\n str = \"#{time[1]}: #{diff} ms\"\n @_write @constructor.MARKERS.gray str\n\n time[0] = 0\n return\n\n### log.scope([*Any* names...])\n\nReturns a new `log` function.\n\nAll prints will be prefixed by the given names.\n\n```javascript\nvar log = log.scope(\"Example file\");\n\nlog(\"hello\");\n\/\/ \"Example file \u2192 hello\"\n```\n\n scope: (args...) ->\n if @prefixes\n unshift.apply args, @prefixes\n\n new @constructor args, @\n\n # implementation\n impl = switch true\n when utils.isNode\n require '.\/impls\/node\/index.coffee'\n when utils.isBrowser\n require '.\/impls\/browser\/index.coffee'\n\n LogImpl = if typeof impl is 'function' then impl Log else Log\n exports = module.exports = new LogImpl\n exports.Log = Log\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Literate CoffeeScript"} {"commit":"7016a2dcc7aff98c3a8231ce986e67b8ebeb58c5","subject":"progress helper","message":"progress helper\n","repos":"vpj\/IO","old_file":"io.litcoffee","new_file":"io.litcoffee","new_contents":" _self = this\n\n POLL_TYPE =\n progress: true\n\n##Response class\n\n class Response\n constructor: (data, port, options) ->\n @id = data.id\n @port = port\n @options = options\n @queue = []\n @fresh = true\n\n progress: (progress, data) ->\n @queue.push method: 'progress', data: data, options: {progress: progress}\n @_handleQueue()\n\n success: (data) ->\n @queue.push method: 'success', data: data, options: {}\n @_handleQueue()\n\n fail: (data) ->\n @queue.push method: 'fail', data: data, options: {}\n @_handleQueue()\n\n setOptions: (options) ->\n @options = options\n @fresh = true\n @_handleQueue()\n\n _handleQueue: ->\n return unless @queue.length > 0\n\n d = @queue[0]\n\n if @port.isStreaming\n @port.respond this, d.method, d.data, d.options, @options\n @queue.shift()\n else if @fresh\n @port.respond this, d.method, d.data, d.options, @options\n @queue.shift()\n @fresh = false\n\n##Call class\n\n class Call\n constructor: (@id, @method, @data, @callbacks, @options) -> null\n\n handle: (data, options) ->\n if not @callbacks[options.status]?\n return if options.status is 'progress'\n throw new Error \"No callback registered #{@method} #{options.status}\"\n @callbacks[options.status] data, options\n\n##Port base class\n\n class Port\n constructor: ->\n @handlers = {}\n @callsCache = {}\n @callsCounter = 0\n @id = parseInt Math.random() * 1000\n @responses = {}\n @wrappers =\n send: []\n respond: []\n handleCall: []\n handleResponse: []\n\n isStreaming: true\n\n onerror: (msg, options) ->\n console.log msg, options\n\n wrap: (wrapper) ->\n for key, f of wrapper\n if @wrappers[key]?\n @wrappers[key].push f\n else\n this[key] = f\n\n###Send RPC call\n\n send: (method, data, callbacks, options = {}) ->\n if (typeof callbacks) is 'function'\n callbacks =\n success: callbacks\n\n for f in @wrappers.send\n return unless f.apply this, [method, data, callbacks, options]\n\n @_send @_createCall method, data, callbacks, options\n\n###Respond to a RPC call\n\n respond: (response, status, data, options = {}, portOptions = {}) ->\n for f in @wrappers.respond\n return unless f.apply this, [response, status, data, options, portOptions]\n\n @_respond (@_createResponse response, status, data, options), portOptions\n if not POLL_TYPE[status]?\n delete @responses[response.id]\n\n\n###Create Call object\nThis is a private function\n\n _createCall: (method, data, callbacks, options) ->\n call = new Call \"#{@id}-#{@callsCounter}\", method, data, callbacks, options\n @callsCounter++\n @callsCache[call.id] = call\n\n params =\n type: 'call'\n id: call.id\n method: call.method\n data: call.data\n\n params[k] = v for k, v of options\n return params\n\n###Create Response object\n\n _createResponse: (response, status, data, options) ->\n params =\n type: 'response'\n id: response.id\n status: status\n data: data\n\n params[k] = v for k, v of options\n\n return params\n\n###Add handler\n\n on: (method, callback) ->\n @handlers[method] = callback\n\n###Handle incoming message\n\n _handleMessage: (data, options) ->\n switch data.type\n when 'response'\n @_handleResponse data, options\n when 'call'\n @_handleCall data, options\n when 'poll'\n @_handlePoll data, options\n\n _handleCall: (data, options) ->\n for f in @wrappers.handleCall\n return unless f.apply this, arguments\n if not @handlers[data.method]?\n throw new Error \"Unknown method: #{data.method}\"\n @responses[data.id] = new Response data, this, options\n @handlers[data.method] data.data, data, @responses[data.id]\n\n _handleResponse: (data, options) ->\n for f in @wrappers.handleResponse\n return unless f.apply this, arguments\n if not @callsCache[data.id]?\n throw new Error \"Response without call: #{data.id}\"\n @callsCache[data.id].handle data.data, data\n\n _handlePoll: (data, options) ->\n throw new Error \"Poll not implemented\"\n\n##WorkerPort class\nUsed for browser and worker\n\n class WorkerPort extends Port\n constructor: (worker) ->\n super()\n @worker = worker\n @worker.onmessage = @_onMessage.bind this\n @worker.onerror = @_onError.bind this\n\n _send: (data) -> @worker.postMessage data\n _respond: (data) -> @worker.postMessage data\n\n _onMessage: (e) ->\n data = e.data\n @_handleMessage data\n\n _onError: (e) -> console.log e\n\n\n\n##SocketPort class\n\n class SocketPort extends Port\n constructor: (socket) ->\n super()\n @socket = socket\n @socket.on 'message', @_onMessage.bind this\n\n _send: (data) -> @socket.emit 'message', data\n _respond: (data) -> @worker.emit 'message', data\n\n _onMessage: (e) ->\n data = e.data\n @_handleMessage data\n\n\n\n##ServerSocketPort class\n\n class ServerSocketPort extends Port\n constructor: (server) ->\n super()\n @server = server\n @server.on 'connection', @_onConnection.bind this\n\n _onConnection: (socket) ->\n new SocketPort handlers: @handlers, socket\n\n\n\n##AJAX class\n\n class AjaxHttpPort extends Port\n constructor: (options) ->\n super()\n @host = options.host ? 'localhost'\n @port = options.port ? 80\n @path = options.path ? '\/'\n\n isStreaming: false\n\n _onRequest: (xhr) ->\n return unless xhr.readyState is 4\n status = xhr.status\n if ((not status and xhr.responseText?) or\n (status >= 200 and status < 300) or\n (status is 304))\n try\n jsonData = JSON.parse xhr.responseText\n catch e\n @onerror 'ParseError', e\n return\n\n @_handleMessage jsonData, xhr: xhr\n else\n @onerror 'xhr error'\n\n _respond: (data, options) ->\n throw new Error 'AJAX cannot respond'\n\n _send: (data) ->\n data = JSON.stringify data\n xhr = new XMLHttpRequest\n xhr.open 'POST', \"http:\/\/#{@host}:#{@port}#{@path}\"\n xhr.onreadystatechange = =>\n @_onRequest xhr\n xhr.setRequestHeader 'Accept', 'application\/json'\n #xhr.setRequestHeader 'Content-Type', 'application\/json'\n xhr.send data\n\n _handleResponse: (data, options) ->\n for f in @wrappers.handleResponse\n return unless f.apply this, arguments\n if not @callsCache[data.id]?\n throw new Error \"Response without call: #{data.id}\"\n call = @callsCache[data.id]\n call.handle data.data, data\n if POLL_TYPE[data.status]?\n params =\n type: 'poll'\n id: call.id\n params[k] = v for k, v of call.options\n @_send params\n\n\n\n##NodeHttpPort class\n\n class NodeHttpPort extends Port\n constructor: (options, http) ->\n super()\n @host = options.host ? 'localhost'\n @port = options.port ? 80\n @path = options.path ? '\/'\n @http = http\n @_createHttpOptions()\n\n isStreaming: false\n\n _createHttpOptions: ->\n @httpOptions =\n hostname: @host\n port: @port\n path: @path\n method: 'POST'\n headers:\n accept: 'application\/json'\n 'content-type': 'application\/json'\n\n\n _onRequest: (res) ->\n data = ''\n #console.log 'STATUS: ' + res.statusCode\n #console.log 'HEADERS: ' + JSON.stringify res.headers\n res.setEncoding 'utf8'\n res.on 'data', (chunk) ->\n data += chunk\n #console.log 'result', res\n res.on 'end', =>\n try\n jsonData = JSON.parse data\n catch e\n console.log 'ParseError', e\n return\n\n @_handleMessage jsonData, response: res\n\n _respond: (data, options) ->\n data = JSON.stringify data\n res = options.response\n res.setHeader 'content-length', data.length\n res.write data\n res.end()\n\n _send: (data) ->\n data = JSON.stringify data\n options = @httpOptions\n options.headers['content-length'] = data.length\n\n req = @http.request options, @_onRequest.bind this\n delete options.headers['content-length']\n req.on 'error', (e) ->\n console.log 'error', e\n\n req.write data\n req.end()\n\n _handleResponse: (data, options) ->\n for f in @wrappers.handleResponse\n return unless f.apply this, arguments\n if not @callsCache[data.id]?\n throw new Error \"Response without call: #{data.id}\"\n call = @callsCache[data.id]\n call.handle data.data, data\n if POLL_TYPE[data.status]?\n params =\n type: 'poll'\n id: call.id\n params[k] = v for k, v of call.options\n @_send params\n\n\n\n##NodeHttpServerPort class\n\n class NodeHttpServerPort extends Port\n constructor: (options, http) ->\n super()\n @port = options.port\n @http = http\n\n isStreaming: false\n\n _onRequest: (req, res) ->\n data = ''\n res.setHeader 'content-type', 'application\/json'\n\n req.on 'data', (chunk) ->\n data += chunk\n req.on 'end', =>\n try\n jsonData = JSON.parse data\n catch e\n console.log 'ParseError', e, data\n return\n\n @_handleMessage jsonData, response: res\n\n _respond: (data, options) ->\n data = JSON.stringify data\n res = options.response\n res.setHeader 'content-length', data.length\n res.write data\n res.end()\n\n listen: ->\n @server = @http.createServer @_onRequest.bind this\n @server.listen @port\n\n _handlePoll: (data, options) ->\n for f in @wrappers.handleCall\n return unless f.apply this, arguments\n if not @responses[data.id]?\n throw new Error \"Poll without response: #{data.id}\"\n @responses[data.id].setOptions options\n\n\n\n#IO Module\n\n IO =\n addPort: (name, port) ->\n IO[name] = port\n\n ports:\n WorkerPort: WorkerPort\n SocketPort: SocketPort\n AjaxHttpPort: AjaxHttpPort\n NodeHttpPort: NodeHttpPort\n NodeHttpServerPort: NodeHttpServerPort\n ServerSocketPort: ServerSocketPort\n\n Helpers:\n progress: (from, to, func) ->\n (progress, data) ->\n func? progress * (to - from) + from, data\n\n setup_____: (options) ->\n options.workers ?= []\n switch options.platform\n when 'ui'\n for worker in options.workers\n IO.addPort worker.name, new WorkerPort worker.js\n for socket in options.sockets\n IO.addPort socket.name, new SocketPort socket.url\n when 'node'\n for socket in options.listenSockets\n IO.addPort socket.name, new SocketListenPort socket.port\n for socket in options.sockets\n IO.addPort socket.name, new SocketPort socket.url\n when 'worker'\n IO.addPort 'UI', new WorkerListenPort _self\n\n if exports?\n module.exports = IO\n else\n _self.IO = IO\n\n","old_contents":" _self = this\n\n POLL_TYPE =\n progress: true\n\n##Response class\n\n class Response\n constructor: (data, port, options) ->\n @id = data.id\n @port = port\n @options = options\n @queue = []\n @fresh = true\n\n progress: (progress, data) ->\n @queue.push method: 'progress', data: data, options: {progress: progress}\n @_handleQueue()\n\n success: (data) ->\n @queue.push method: 'success', data: data, options: {}\n @_handleQueue()\n\n fail: (data) ->\n @queue.push method: 'fail', data: data, options: {}\n @_handleQueue()\n\n setOptions: (options) ->\n @options = options\n @fresh = true\n @_handleQueue()\n\n _handleQueue: ->\n return unless @queue.length > 0\n\n d = @queue[0]\n\n if @port.isStreaming\n @port.respond this, d.method, d.data, d.options, @options\n @queue.shift()\n else if @fresh\n @port.respond this, d.method, d.data, d.options, @options\n @queue.shift()\n @fresh = false\n\n##Call class\n\n class Call\n constructor: (@id, @method, @data, @callbacks, @options) -> null\n\n handle: (data, options) ->\n if not @callbacks[options.status]?\n return if options.status is 'progress'\n throw new Error \"No callback registered #{@method} #{options.status}\"\n @callbacks[options.status] data, options\n\n##Port base class\n\n class Port\n constructor: ->\n @handlers = {}\n @callsCache = {}\n @callsCounter = 0\n @id = parseInt Math.random() * 1000\n @responses = {}\n @wrappers =\n send: []\n respond: []\n handleCall: []\n handleResponse: []\n\n isStreaming: true\n\n onerror: (msg, options) ->\n console.log msg, options\n\n wrap: (wrapper) ->\n for key, f of wrapper\n if @wrappers[key]?\n @wrappers[key].push f\n else\n this[key] = f\n\n###Send RPC call\n\n send: (method, data, callbacks, options = {}) ->\n if (typeof callbacks) is 'function'\n callbacks =\n success: callbacks\n\n for f in @wrappers.send\n return unless f.apply this, [method, data, callbacks, options]\n\n @_send @_createCall method, data, callbacks, options\n\n###Respond to a RPC call\n\n respond: (response, status, data, options = {}, portOptions = {}) ->\n for f in @wrappers.respond\n return unless f.apply this, [response, status, data, options, portOptions]\n\n @_respond (@_createResponse response, status, data, options), portOptions\n if not POLL_TYPE[status]?\n delete @responses[response.id]\n\n\n###Create Call object\nThis is a private function\n\n _createCall: (method, data, callbacks, options) ->\n call = new Call \"#{@id}-#{@callsCounter}\", method, data, callbacks, options\n @callsCounter++\n @callsCache[call.id] = call\n\n params =\n type: 'call'\n id: call.id\n method: call.method\n data: call.data\n\n params[k] = v for k, v of options\n return params\n\n###Create Response object\n\n _createResponse: (response, status, data, options) ->\n params =\n type: 'response'\n id: response.id\n status: status\n data: data\n\n params[k] = v for k, v of options\n\n return params\n\n###Add handler\n\n on: (method, callback) ->\n @handlers[method] = callback\n\n###Handle incoming message\n\n _handleMessage: (data, options) ->\n switch data.type\n when 'response'\n @_handleResponse data, options\n when 'call'\n @_handleCall data, options\n when 'poll'\n @_handlePoll data, options\n\n _handleCall: (data, options) ->\n for f in @wrappers.handleCall\n return unless f.apply this, arguments\n if not @handlers[data.method]?\n throw new Error \"Unknown method: #{data.method}\"\n @responses[data.id] = new Response data, this, options\n @handlers[data.method] data.data, data, @responses[data.id]\n\n _handleResponse: (data, options) ->\n for f in @wrappers.handleResponse\n return unless f.apply this, arguments\n if not @callsCache[data.id]?\n throw new Error \"Response without call: #{data.id}\"\n @callsCache[data.id].handle data.data, data\n\n _handlePoll: (data, options) ->\n throw new Error \"Poll not implemented\"\n\n##WorkerPort class\nUsed for browser and worker\n\n class WorkerPort extends Port\n constructor: (worker) ->\n super()\n @worker = worker\n @worker.onmessage = @_onMessage.bind this\n @worker.onerror = @_onError.bind this\n\n _send: (data) -> @worker.postMessage data\n _respond: (data) -> @worker.postMessage data\n\n _onMessage: (e) ->\n data = e.data\n @_handleMessage data\n\n _onError: (e) -> console.log e\n\n\n\n##SocketPort class\n\n class SocketPort extends Port\n constructor: (socket) ->\n super()\n @socket = socket\n @socket.on 'message', @_onMessage.bind this\n\n _send: (data) -> @socket.emit 'message', data\n _respond: (data) -> @worker.emit 'message', data\n\n _onMessage: (e) ->\n data = e.data\n @_handleMessage data\n\n\n\n##ServerSocketPort class\n\n class ServerSocketPort extends Port\n constructor: (server) ->\n super()\n @server = server\n @server.on 'connection', @_onConnection.bind this\n\n _onConnection: (socket) ->\n new SocketPort handlers: @handlers, socket\n\n\n\n##AJAX class\n\n class AjaxHttpPort extends Port\n constructor: (options) ->\n super()\n @host = options.host ? 'localhost'\n @port = options.port ? 80\n @path = options.path ? '\/'\n\n isStreaming: false\n\n _onRequest: (xhr) ->\n return unless xhr.readyState is 4\n status = xhr.status\n if ((not status and xhr.responseText?) or\n (status >= 200 and status < 300) or\n (status is 304))\n try\n jsonData = JSON.parse xhr.responseText\n catch e\n @onerror 'ParseError', e\n return\n\n @_handleMessage jsonData, xhr: xhr\n else\n @onerror 'xhr error'\n\n _respond: (data, options) ->\n throw new Error 'AJAX cannot respond'\n\n _send: (data) ->\n data = JSON.stringify data\n xhr = new XMLHttpRequest\n xhr.open 'POST', \"http:\/\/#{@host}:#{@port}#{@path}\"\n xhr.onreadystatechange = =>\n @_onRequest xhr\n xhr.setRequestHeader 'Accept', 'application\/json'\n #xhr.setRequestHeader 'Content-Type', 'application\/json'\n xhr.send data\n\n _handleResponse: (data, options) ->\n for f in @wrappers.handleResponse\n return unless f.apply this, arguments\n if not @callsCache[data.id]?\n throw new Error \"Response without call: #{data.id}\"\n call = @callsCache[data.id]\n call.handle data.data, data\n if POLL_TYPE[data.status]?\n params =\n type: 'poll'\n id: call.id\n params[k] = v for k, v of call.options\n @_send params\n\n\n\n##NodeHttpPort class\n\n class NodeHttpPort extends Port\n constructor: (options, http) ->\n super()\n @host = options.host ? 'localhost'\n @port = options.port ? 80\n @path = options.path ? '\/'\n @http = http\n @_createHttpOptions()\n\n isStreaming: false\n\n _createHttpOptions: ->\n @httpOptions =\n hostname: @host\n port: @port\n path: @path\n method: 'POST'\n headers:\n accept: 'application\/json'\n 'content-type': 'application\/json'\n\n\n _onRequest: (res) ->\n data = ''\n #console.log 'STATUS: ' + res.statusCode\n #console.log 'HEADERS: ' + JSON.stringify res.headers\n res.setEncoding 'utf8'\n res.on 'data', (chunk) ->\n data += chunk\n #console.log 'result', res\n res.on 'end', =>\n try\n jsonData = JSON.parse data\n catch e\n console.log 'ParseError', e\n return\n\n @_handleMessage jsonData, response: res\n\n _respond: (data, options) ->\n data = JSON.stringify data\n res = options.response\n res.setHeader 'content-length', data.length\n res.write data\n res.end()\n\n _send: (data) ->\n data = JSON.stringify data\n options = @httpOptions\n options.headers['content-length'] = data.length\n\n req = @http.request options, @_onRequest.bind this\n delete options.headers['content-length']\n req.on 'error', (e) ->\n console.log 'error', e\n\n req.write data\n req.end()\n\n _handleResponse: (data, options) ->\n for f in @wrappers.handleResponse\n return unless f.apply this, arguments\n if not @callsCache[data.id]?\n throw new Error \"Response without call: #{data.id}\"\n call = @callsCache[data.id]\n call.handle data.data, data\n if POLL_TYPE[data.status]?\n params =\n type: 'poll'\n id: call.id\n params[k] = v for k, v of call.options\n @_send params\n\n\n\n##NodeHttpServerPort class\n\n class NodeHttpServerPort extends Port\n constructor: (options, http) ->\n super()\n @port = options.port\n @http = http\n\n isStreaming: false\n\n _onRequest: (req, res) ->\n data = ''\n res.setHeader 'content-type', 'application\/json'\n\n req.on 'data', (chunk) ->\n data += chunk\n req.on 'end', =>\n try\n jsonData = JSON.parse data\n catch e\n console.log 'ParseError', e, data\n return\n\n @_handleMessage jsonData, response: res\n\n _respond: (data, options) ->\n data = JSON.stringify data\n res = options.response\n res.setHeader 'content-length', data.length\n res.write data\n res.end()\n\n listen: ->\n @server = @http.createServer @_onRequest.bind this\n @server.listen @port\n\n _handlePoll: (data, options) ->\n for f in @wrappers.handleCall\n return unless f.apply this, arguments\n if not @responses[data.id]?\n throw new Error \"Poll without response: #{data.id}\"\n @responses[data.id].setOptions options\n\n\n\n#IO Module\n\n IO =\n addPort: (name, port) ->\n IO[name] = port\n\n ports:\n WorkerPort: WorkerPort\n SocketPort: SocketPort\n AjaxHttpPort: AjaxHttpPort\n NodeHttpPort: NodeHttpPort\n NodeHttpServerPort: NodeHttpServerPort\n ServerSocketPort: ServerSocketPort\n\n setup_____: (options) ->\n options.workers ?= []\n switch options.platform\n when 'ui'\n for worker in options.workers\n IO.addPort worker.name, new WorkerPort worker.js\n for socket in options.sockets\n IO.addPort socket.name, new SocketPort socket.url\n when 'node'\n for socket in options.listenSockets\n IO.addPort socket.name, new SocketListenPort socket.port\n for socket in options.sockets\n IO.addPort socket.name, new SocketPort socket.url\n when 'worker'\n IO.addPort 'UI', new WorkerListenPort _self\n\n if exports?\n module.exports = IO\n else\n _self.IO = IO\n\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"24ae68555da0589135eccf7d59955786d5aa9c4f","subject":"zones were still lurking","message":"zones were still lurking\n","repos":"nhz-io\/cnl","old_file":"source\/shape.litcoffee","new_file":"source\/shape.litcoffee","new_contents":"# CLASS: Shape\n* Extends: [Element][Element]\n* Parent: [Index][Parent]\n\nA drawable shape. Manages **regions**.\n\n---\n\n module.exports = class Shape extends require '.\/element'\n\n## CONSTRUCTOR\n\n### new Shape(args)\n\nCreates Shape instance.\n\n constructor: ->\n super\n\nCopy the element regions if they were set from named arguments\n\n if regions = @regions\n @regions = {}\n @regions[name] = region for name, region of regions\n\n#### PARAMETERS\n* **args** - named arguments\n\n---\n\n## PROPERTIES\n### #regions\n* Type: [Object][Object] - region name\/value pairs\n* **{REGION NAME}**\n * Type: [Array][Array] - [x, y, width, height]\n\n---\n\n## METHODS\n### #draw(context, args)\n* Returns: [Shape][Shape]\n\nA draw method stub\n\n draw: -> this\n\n---\n\n### #getEventRegions(event)\n* Returns: [Object][Object] - named set of matching regions\n\nHelper method, to get element regions that match the event.\n\n getEventRegions: (event) ->\n result = null\n\nProceed only if event coordinates are localized\n\n if event and (x = event.localX)? and (y = event.localY)?\n\nWalk through the element regions\n\n for name, $ of @regions\n\nand add the region to the result if event localized coordinates are within\nthe region rectangle.\n\n if $[0] <= x <= ($[0] + $[2]) and $[1] <= y <= ($[1] + $[3])\n\nInitialize result only if at least one region matches\n\n result or= {}\n result[name] = $\n\n return result\n\n---\n\n## LISTENERS\n\n### #mousemoveCaptureListener(event)\n* Returns: [Shape][Shape]\n\nCapture **mousemove** events passing through this shape\n\n mousemoveCaptureListener: (event) ->\n super\n\n if regions = @getEventRegions event\n\nGet shape regions that match the event and store them in the event.\n\n event.regions = regions\n\nSet the shape state to the first matching region name in order.\n\n for name in ['active', 'hover', 'normal'] when regions[name]\n state = name\n break\n\nIf any state was set then make this shape a target of the event.\nReset the state if no region was found.\n\n if (@state = state or null) then event.target = this\n\n return this\n\n#### PARAMETERS\n**event**\n* Type: [Event][Event] - captured event\n\n\n---\n\n### #mousedownCaptureListener(event)\n* Returns: [Shape][Shape]\n\nCapture **mousedown** events passing through this shape\n\n mousedownCaptureListener: (event) ->\n super\n\n if regions = @getEventRegions event\n\nGet shape regions that match the event and store them in the event.\n\n event.regions = regions\n\nSet the shape state to the first matching region name in order\n\n for name in ['active', 'hover', 'normal'] when regions[name]\n state = name\n break\n\nIf any state was set then make this shape a target of the event.\nReset the state if no region was found.\n\n if (@state = state or null) then event.target = this\n\n return this\n\n#### PARAMETERS\n**event**\n* Type: [Event][Event] - captured event\n\n---\n\n### #mouseupCaptureListener(event)\n* Returns: [Event][Event]\n\nCapture **mouseup** events passing through this shape\n\n mouseupCaptureListener: (event) ->\n super\n\n if regions = @getEventRegions event\n\nGet shape regions that match the event and store them in the event.\n\n event.regions = regions\n\nSet the shape state to the first matching region name in order\n\n for name in ['active', 'hover', 'normal'] when regions[name]\n state = name\n break\n\n\nIf any state was set then make this shape a target of the event.\nReset the state if no region was found.\n\n if (@state = state or null) then event.target = this\n\n return this\n\n#### PARAMETERS\n**event**\n* Type: [Event][Event] - captured event\n\n[Shape]: .\/shape.litcoffee\n[Element]: .\/element.litcoffee\n[Event]: .\/event.litcoffee\n[Object]: https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\n","old_contents":"# CLASS: Shape\n* Extends: [Element][Element]\n* Parent: [Index][Parent]\n\nA drawable shape. Manages **regions**.\n\n---\n\n module.exports = class Shape extends require '.\/element'\n\n## CONSTRUCTOR\n\n### new Shape(args)\n\nCreates Shape instance.\n\n constructor: ->\n super\n\nCopy the element regions if they were set from named arguments\n\n if regions = @regions\n @regions = {}\n @regions[name] = region for name, region of regions\n\n#### PARAMETERS\n* **args** - named arguments\n\n---\n\n## PROPERTIES\n### #regions\n* Type: [Object][Object] - region name\/value pairs\n* **{REGION NAME}**\n * Type: [Array][Array] - [x, y, width, height]\n\n---\n\n## METHODS\n### #draw(context, args)\n* Returns: [Shape][Shape]\n\nA draw method stub\n\n draw: -> this\n\n---\n\n### #getEventRegions(event)\n* Returns: [Object][Object] - named set of matching regions\n\nHelper method, to get element regions that match the event.\n\n getEventRegions: (event) ->\n result = null\n\nProceed only if event coordinates are localized\n\n if event and (x = event.localX)? and (y = event.localY)?\n\nWalk through the element regions\n\n for name, $ of @regions\n\nand add the region to the result if event localized coordinates are within\nthe region rectangle.\n\n if $[0] <= x <= ($[0] + $[2]) and $[1] <= y <= ($[1] + $[3])\n\nInitialize result only if at least one region matches\n\n result or= {}\n result[name] = $\n\n return result\n\n---\n\n## LISTENERS\n\n### #mousemoveCaptureListener(event)\n* Returns: [Shape][Shape]\n\nCapture **mousemove** events passing through this shape\n\n mousemoveCaptureListener: (event) ->\n super\n\n if regions = @getEventRegions event\n\nGet shape regions that match the event and store them in the event.\n\n event.regions = regions\n\nSet the shape state to the first matching region name in order.\n\n for name in ['active', 'hover', 'normal'] when regions[name]\n state = name\n break\n\nIf any state was set then make this shape a target of the event.\nReset the state if no region was found.\n\n if (@state = state or null) then event.target = this\n\n return this\n\n#### PARAMETERS\n**event**\n* Type: [Event][Event] - captured event\n\n\n---\n\n### #mousedownCaptureListener(event)\n* Returns: [Shape][Shape]\n\nCapture **mousedown** events passing through this shape\n\n mousedownCaptureListener: (event) ->\n super\n\n if regions = @getEventRegions event\n\nGet shape regions that match the event and store them in the event.\n\n event.regions = regions\n\nSet the shape state to the first matching region name in order\n\n for name in ['active', 'hover', 'normal'] when zones[name]\n state = name\n break\n\nIf any state was set then make this shape a target of the event.\nReset the state if no region was found.\n\n if (@state = state or null) then event.target = this\n\n return this\n\n#### PARAMETERS\n**event**\n* Type: [Event][Event] - captured event\n\n---\n\n### #mouseupCaptureListener(event)\n* Returns: [Event][Event]\n\nCapture **mouseup** events passing through this shape\n\n mouseupCaptureListener: (event) ->\n super\n\n if regions = @getEventRegions event\n\nGet shape regions that match the event and store them in the event.\n\n event.regions = regions\n\nSet the shape state to the first matching region name in order\n\n for name in ['active', 'hover', 'normal'] when zones[name]\n state = name\n break\n\n\nIf any state was set then make this shape a target of the event.\nReset the state if no region was found.\n\n if (@state = state or null) then event.target = this\n\n return this\n\n#### PARAMETERS\n**event**\n* Type: [Event][Event] - captured event\n\n[Shape]: .\/shape.litcoffee\n[Element]: .\/element.litcoffee\n[Event]: .\/event.litcoffee\n[Object]: https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"a281391a520662c175fac479e688bb30ee8a0350","subject":"improve property.inspect","message":"improve property.inspect\n","repos":"corenova\/yang-js","old_file":"src\/property.litcoffee","new_file":"src\/property.litcoffee","new_contents":"# Property - controller of Object properties\n\nThe `Property` class is the *secretive shadowy* element that governs\n`Object` behavior and are bound to the `Object` via\n`Object.defineProperty`. It acts like a shadow `Proxy\/Reflector` to\nthe `Object` instance and provides tight control via the\n`Getter\/Setter` interfaces.\n\nBelow are list of properties available to every instance of `Property`:\n\nproperty | type | mapping | description\n--- | --- | --- | ---\nname | string | direct | name of the property\nschema | object | direct | a schema instance (usually [Yang](.\/src\/yang.listcoffee))\nstate | object | direct | *private* object holding internal state\ncontainer | object | access(state) | reference to object containing this property\nconfigurable | boolean | getter(state) | defines whether this property can be redefined\nenumerable | boolean | getter(state) | defines whether this property is enumerable\ncontent | any | computed | getter\/setter for `state.value`\ncontext | object | computed | dynamically generated using [context](.\/src\/context.coffee)\nroot | [Property](.\/src\/property.litcoffee) | computed | dynamically returns the root Property instance\npath | [XPath](.\/src\/xpath.coffee) | computed | dynamically generate XPath for this Property from root\n\n## Class Property\n\n debug = require('debug')('yang:property')\n delegate = require 'delegates'\n context = require '.\/context'\n XPath = require '.\/xpath'\n\n class Property\n @property: (prop, desc) ->\n Object.defineProperty @prototype, prop, desc\n\n constructor: (@name, @schema={}) ->\n unless this instanceof Property then return new Property arguments...\n\n @state = \n value: undefined\n parent: null\n container: null\n private: false\n mutable: @schema.config?.valueOf() isnt false\n attached: false\n changed: false\n \n @schema.kind ?= 'anydata'\n \n # soft freeze this instance\n Object.preventExtensions this\n\n debug: -> debug @uri, arguments...\n \n delegate @prototype, 'state'\n .access 'container'\n .access 'parent'\n .access 'strict'\n .getter 'mutable'\n .getter 'private'\n .getter 'prev'\n .getter 'value'\n .getter 'changed'\n .getter 'attached'\n\n delegate @prototype, 'schema'\n .getter 'tag'\n .getter 'kind'\n .getter 'type'\n .getter 'default'\n .getter 'external'\n .getter 'binding'\n .method 'locate'\n .method 'lookup'\n\n### Computed Properties\n\n @property 'enumerable',\n get: -> not @private and (@value? or @binding?)\n\n @property 'content',\n set: (value) -> @set value, { force: true, suppress: true }\n get: -> @value\n\n @property 'active',\n get: -> @enumerable and @value?\n\n @property 'change',\n get: -> switch\n when @changed and not @active then null\n when @changed then @content\n\n @property 'context',\n get: ->\n ctx = Object.create(context)\n ctx.state = {}\n ctx.property = this\n Object.preventExtensions ctx\n return ctx\n\n @property 'root',\n get: ->\n return this if @kind is 'module'\n root = switch\n when @parent is this then this\n when @parent instanceof Property then @parent.root\n else this\n @state.path = undefined unless @state.root is root\n return @state.root = root\n\n @property 'path',\n get: ->\n if this is @root\n entity = switch\n when @kind is 'module' then '\/'\n else '.'\n return XPath.parse entity, @schema\n @state.path ?= @parent.path.clone().append @name\n return @state.path\n\n @property 'uri',\n get: -> @schema.datapath ? @schema.uri\n\n## Instance-level methods\n\n clone: (state = {}) ->\n throw @error 'must clone with state typeof object' unless typeof state is 'object'\n copy = new @constructor @name, @schema\n copy.state = Object.assign(Object.create(@state), state, origin: this)\n return copy\n\n emit: -> @parent?.emit? arguments...\n\n clean: -> @state.changed = false\n\n equals: (a, b) -> switch @kind\n when 'leaf-list'\n return false unless a and b\n a = Array.from(new Set([].concat(a)))\n b = Array.from(new Set([].concat(b)))\n return false unless a.length is b.length\n a.every (x) => b.some (y) => x is y\n else a is b\n\n### get (key)\n\nThis is the main `Getter` for the target object's property value. When\ncalled with optional `key` it will perform an internal\n[find](#find-xpath) operation to traverse\/locate that value being\nrequested instead of returning its own `@content`.\n\nIt also provides special handling based on different types of\n`@content` currently held.\n\nWhen `@content` is a function, it will call it with the current\n`@context` instance as the bound context for the function being\ncalled.\n\n get: (key) -> switch\n when key? \n try match = @find key\n return unless match? and match.length\n switch\n when match.length is 1 then match[0].get()\n when match.length > 1 then match.map (x) -> x.get()\n else undefined\n when @binding?\n try @binding.call @context\n catch e\n throw @error e, 'getter'\n else @content\n\n### set (value)\n\nThis is the main `Setter` for the target object's property value. It\nutilizes internal `@schema` attribute if available to enforce schema\nvalidations.\n\n set: (value, opts={}) ->\n @state.changed = false\n # @debug \"[set] enter...\"\n\n unless @mutable or not value? or opts.force\n throw @error \"cannot set data on read-only (config false) element\"\n \n if @binding?.length is 1 and not opts.force\n try value = @binding.call @context, value \n catch e\n throw @error e, 'setter'\n\n return this if value? and @equals value, @value\n \n @state.prev = @value\n bypass = opts.bypass and @kind in [\"leaf\", \"leaf-list\"]\n # @debug \"[set] applying schema...\"\n value = switch\n when @schema.apply? and not bypass\n @schema.apply value, this, Object.assign {}, opts, suppress: true\n else value\n # @debug \"[set] done applying schema...\", value\n return this if value instanceof Error or @equals value, @prev\n \n @state.value = value\n @state.changed = true\n \n # update enumerable state on every set operation\n try Object.defineProperty @container, @name, configurable: true, enumerable: true if @attached\n\n @commit opts\n # @debug \"[set] completed\"\n return this\n\n### delete\n\n delete: (opts={}) ->\n if @binding?.length is 1 and not opts.force\n try @binding.call @context, null\n catch e\n throw @error \"failed executing delete() binding: #{e.message}\", e\n @state.prev = @value\n @state.value = null\n\n @parent?.remove? this, opts # remove from parent\n \n # update enumerable state on every set operation\n try Object.defineProperty @container, @name, enumerable: false if @attached\n\n @state.changed = true\n @commit opts\n return this\n\n### merge (value)\n\nPerforms a granular merge of `value` into existing `@content` if\navailable, otherwise performs [set](#set-value) operation.\n\n merge: (value, opts) ->\n return @delete opts if value is null\n @set value, Object.assign {}, opts, merge: true\n\n### commit (opts)\n\nCommits the changes to the data to the data model\n\n commit: (opts={}) ->\n return unless @changed\n if @attached and @parent?\n @parent.changes.add this\n @parent.commit suppress: true\n \n { suppress = false, inner = false, actor } = opts\n return if suppress\n unless inner\n try @emit 'update', this, actor\n catch error\n # console.warn('commit error, rolling back!');\n @rollback()\n throw error\n @emit 'change', this, actor if @attached\n\n rollback: ->\n @state.value = @prev\n @clean()\n return this\n\n### attach (obj, parent, opts)\n\nThis call is the primary mechanism via which the `Property` instance\nattaches itself to the provided target `obj`. It defines itself in the\ntarget `obj` via `Object.defineProperty`.\n\n attach: (obj, parent, opts) ->\n return obj unless obj instanceof Object\n opts ?= { replace: false, suppress: false, force: false }\n\n detached = true unless @container?\n @container = obj\n @parent = parent\n\n # if joining for the first time, apply existing data unless explicit replace\n if detached and opts.replace isnt true\n # @debug \"[join] applying existing data for #{@name} (external: #{@external}) to:\"\n # @debug obj\n name = switch\n when @parent?.external and @tag of obj then @tag\n when @external then @name\n when @name of obj then @name\n else \"#{@root.name}:#{@name}\" # should we ensure root is kind = module?\n @set obj[name], Object.assign {}, opts, suppress: true\n\n @parent?.add? this, opts # add to parent\n\n try Object.defineProperty obj, @name,\n configurable: true\n enumerable: @enumerable\n get: => @get arguments...\n set: => @set arguments...\n \n @state.attached = true\n # @debug \"[join] attached into #{obj.constructor.name} container\"\n @emit 'attach', this\n return obj\n\n### find (pattern)\n\nThis helper routine can be used to allow traversal to other elements\nin the data tree from the relative location of the current `Property`\ninstance. It returns matching `Property` instances based on the\nprovided `pattern` in the form of XPATH or YPATH.\n\nIt is internally used via [get](#get) and generally used inside\ncontroller logic bound inside the [Yang expression](.\/yang.litcoffee)\nas well as event handler listening on [Model](.\/model.litcoffee)\nevents.\n\nIt *always* returns an array (empty to denote no match) unless it\nencounters an error, in which case it will throw an Error.\n\n find: (pattern='.', opts={}) ->\n @debug \"[find] #{pattern}\"\n pattern = XPath.parse pattern, @schema\n switch\n when pattern.tag is '\/' and this isnt @root then @root.find(pattern)\n when pattern.tag is '..' then @parent?.find pattern.xpath\n else pattern.apply(this) ? []\n\n### in (pattern)\n\nA convenience routine to locate one or more matching Property\ninstances based on `pattern` (XPATH or YPATH) from this Model.\n\n in: (pattern) ->\n try props = @find pattern\n return unless props? and props.length\n return switch\n when props.length > 1 then props\n else props[0]\n\n### defer (value)\n\nOptionally defer setting the value to the property until root has been updated.\n\n defer: (value) ->\n @debug \"deferring '#{@kind}(#{@name})' until update at #{@root.name}\"\n @root.once 'update', =>\n @debug \"applying deferred data (#{typeof value})\"\n @content = value\n return value\n \n### error (msg)\n\nProvides more contextual error message pertaining to the Property instance.\n \n error: (err, ctx=this) ->\n err = new Error err unless err instanceof Error\n err.uri = @uri \n err.src = this\n err.ctx = ctx\n return err\n\n### throw (msg)\n\n throw: (err) -> throw @error(err)\n\n### toJSON\n\nThis call creates a new copy of the current `Property.content`\ncompletely detached\/unbound to the underlying data schema. It's main\nutility is to represent the current data state for subsequent\nserialization\/transmission. It accepts optional argument `tag` which\nwhen called with `true` will tag the produced object with the current\nproperty's `@name`.\n\n toJSON: (key, state = true) ->\n value = switch\n when @kind is 'anydata' then undefined\n when state isnt true and not @mutable then undefined\n else @value\n value = \"#{@name}\": value if key is true\n return value\n\n### inspect\n\n inspect: ->\n return {\n name: @tag ? @name\n kind: @kind\n path: @path.toString()\n schema: switch\n when @schema.uri?\n uri: @schema.uri\n summary: @schema.description?.tag\n datakey: @schema.datakey\n datapath: @schema.datapath\n external: @schema.external\n children: @schema.children\n else false\n active: @active\n changed: @changed\n mutable: @mutable\n content: @toJSON()\n }\n\n## Export Property Class\n\n module.exports = Property\n","old_contents":"# Property - controller of Object properties\n\nThe `Property` class is the *secretive shadowy* element that governs\n`Object` behavior and are bound to the `Object` via\n`Object.defineProperty`. It acts like a shadow `Proxy\/Reflector` to\nthe `Object` instance and provides tight control via the\n`Getter\/Setter` interfaces.\n\nBelow are list of properties available to every instance of `Property`:\n\nproperty | type | mapping | description\n--- | --- | --- | ---\nname | string | direct | name of the property\nschema | object | direct | a schema instance (usually [Yang](.\/src\/yang.listcoffee))\nstate | object | direct | *private* object holding internal state\ncontainer | object | access(state) | reference to object containing this property\nconfigurable | boolean | getter(state) | defines whether this property can be redefined\nenumerable | boolean | getter(state) | defines whether this property is enumerable\ncontent | any | computed | getter\/setter for `state.value`\ncontext | object | computed | dynamically generated using [context](.\/src\/context.coffee)\nroot | [Property](.\/src\/property.litcoffee) | computed | dynamically returns the root Property instance\npath | [XPath](.\/src\/xpath.coffee) | computed | dynamically generate XPath for this Property from root\n\n## Class Property\n\n debug = require('debug')('yang:property')\n delegate = require 'delegates'\n context = require '.\/context'\n XPath = require '.\/xpath'\n\n class Property\n @property: (prop, desc) ->\n Object.defineProperty @prototype, prop, desc\n\n constructor: (@name, @schema={}) ->\n unless this instanceof Property then return new Property arguments...\n\n @state = \n value: undefined\n parent: null\n container: null\n private: false\n mutable: @schema.config?.valueOf() isnt false\n attached: false\n changed: false\n \n @schema.kind ?= 'anydata'\n \n # soft freeze this instance\n Object.preventExtensions this\n\n debug: -> debug @uri, arguments...\n \n delegate @prototype, 'state'\n .access 'container'\n .access 'parent'\n .access 'strict'\n .getter 'mutable'\n .getter 'private'\n .getter 'prev'\n .getter 'value'\n .getter 'changed'\n .getter 'attached'\n\n delegate @prototype, 'schema'\n .getter 'tag'\n .getter 'kind'\n .getter 'type'\n .getter 'default'\n .getter 'external'\n .getter 'binding'\n .method 'locate'\n .method 'lookup'\n\n### Computed Properties\n\n @property 'enumerable',\n get: -> not @private and (@value? or @binding?)\n\n @property 'content',\n set: (value) -> @set value, { force: true, suppress: true }\n get: -> @value\n\n @property 'active',\n get: -> @enumerable and @value?\n\n @property 'change',\n get: -> switch\n when @changed and not @active then null\n when @changed then @content\n\n @property 'context',\n get: ->\n ctx = Object.create(context)\n ctx.state = {}\n ctx.property = this\n Object.preventExtensions ctx\n return ctx\n\n @property 'root',\n get: ->\n return this if @kind is 'module'\n root = switch\n when @parent is this then this\n when @parent instanceof Property then @parent.root\n else this\n @state.path = undefined unless @state.root is root\n return @state.root = root\n\n @property 'path',\n get: ->\n if this is @root\n entity = switch\n when @kind is 'module' then '\/'\n else '.'\n return XPath.parse entity, @schema\n @state.path ?= @parent.path.clone().append @name\n return @state.path\n\n @property 'uri',\n get: -> @schema.datapath ? @schema.uri\n\n## Instance-level methods\n\n clone: (state = {}) ->\n throw @error 'must clone with state typeof object' unless typeof state is 'object'\n copy = new @constructor @name, @schema\n copy.state = Object.assign(Object.create(@state), state, origin: this)\n return copy\n\n emit: -> @parent?.emit? arguments...\n\n clean: -> @state.changed = false\n\n equals: (a, b) -> switch @kind\n when 'leaf-list'\n return false unless a and b\n a = Array.from(new Set([].concat(a)))\n b = Array.from(new Set([].concat(b)))\n return false unless a.length is b.length\n a.every (x) => b.some (y) => x is y\n else a is b\n\n### get (key)\n\nThis is the main `Getter` for the target object's property value. When\ncalled with optional `key` it will perform an internal\n[find](#find-xpath) operation to traverse\/locate that value being\nrequested instead of returning its own `@content`.\n\nIt also provides special handling based on different types of\n`@content` currently held.\n\nWhen `@content` is a function, it will call it with the current\n`@context` instance as the bound context for the function being\ncalled.\n\n get: (key) -> switch\n when key? \n try match = @find key\n return unless match? and match.length\n switch\n when match.length is 1 then match[0].get()\n when match.length > 1 then match.map (x) -> x.get()\n else undefined\n when @binding?\n try @binding.call @context\n catch e\n throw @error e, 'getter'\n else @content\n\n### set (value)\n\nThis is the main `Setter` for the target object's property value. It\nutilizes internal `@schema` attribute if available to enforce schema\nvalidations.\n\n set: (value, opts={}) ->\n @state.changed = false\n # @debug \"[set] enter...\"\n\n unless @mutable or not value? or opts.force\n throw @error \"cannot set data on read-only (config false) element\"\n \n if @binding?.length is 1 and not opts.force\n try value = @binding.call @context, value \n catch e\n throw @error e, 'setter'\n\n return this if value? and @equals value, @value\n \n @state.prev = @value\n bypass = opts.bypass and @kind in [\"leaf\", \"leaf-list\"]\n # @debug \"[set] applying schema...\"\n value = switch\n when @schema.apply? and not bypass\n @schema.apply value, this, Object.assign {}, opts, suppress: true\n else value\n # @debug \"[set] done applying schema...\", value\n return this if value instanceof Error or @equals value, @prev\n \n @state.value = value\n @state.changed = true\n \n # update enumerable state on every set operation\n try Object.defineProperty @container, @name, configurable: true, enumerable: true if @attached\n\n @commit opts\n # @debug \"[set] completed\"\n return this\n\n### delete\n\n delete: (opts={}) ->\n if @binding?.length is 1 and not opts.force\n try @binding.call @context, null\n catch e\n throw @error \"failed executing delete() binding: #{e.message}\", e\n @state.prev = @value\n @state.value = null\n\n @parent?.remove? this, opts # remove from parent\n \n # update enumerable state on every set operation\n try Object.defineProperty @container, @name, enumerable: false if @attached\n\n @state.changed = true\n @commit opts\n return this\n\n### merge (value)\n\nPerforms a granular merge of `value` into existing `@content` if\navailable, otherwise performs [set](#set-value) operation.\n\n merge: (value, opts) ->\n return @delete opts if value is null\n @set value, Object.assign {}, opts, merge: true\n\n### commit (opts)\n\nCommits the changes to the data to the data model\n\n commit: (opts={}) ->\n return unless @changed\n if @attached and @parent?\n @parent.changes.add this\n @parent.commit suppress: true\n \n { suppress = false, inner = false, actor } = opts\n return if suppress\n unless inner\n try @emit 'update', this, actor\n catch error\n # console.warn('commit error, rolling back!');\n @rollback()\n throw error\n @emit 'change', this, actor if @attached\n\n rollback: ->\n @state.value = @prev\n @clean()\n return this\n\n### attach (obj, parent, opts)\n\nThis call is the primary mechanism via which the `Property` instance\nattaches itself to the provided target `obj`. It defines itself in the\ntarget `obj` via `Object.defineProperty`.\n\n attach: (obj, parent, opts) ->\n return obj unless obj instanceof Object\n opts ?= { replace: false, suppress: false, force: false }\n\n detached = true unless @container?\n @container = obj\n @parent = parent\n\n # if joining for the first time, apply existing data unless explicit replace\n if detached and opts.replace isnt true\n # @debug \"[join] applying existing data for #{@name} (external: #{@external}) to:\"\n # @debug obj\n name = switch\n when @parent?.external and @tag of obj then @tag\n when @external then @name\n when @name of obj then @name\n else \"#{@root.name}:#{@name}\" # should we ensure root is kind = module?\n @set obj[name], Object.assign {}, opts, suppress: true\n\n @parent?.add? this, opts # add to parent\n\n try Object.defineProperty obj, @name,\n configurable: true\n enumerable: @enumerable\n get: => @get arguments...\n set: => @set arguments...\n \n @state.attached = true\n # @debug \"[join] attached into #{obj.constructor.name} container\"\n @emit 'attach', this\n return obj\n\n### find (pattern)\n\nThis helper routine can be used to allow traversal to other elements\nin the data tree from the relative location of the current `Property`\ninstance. It returns matching `Property` instances based on the\nprovided `pattern` in the form of XPATH or YPATH.\n\nIt is internally used via [get](#get) and generally used inside\ncontroller logic bound inside the [Yang expression](.\/yang.litcoffee)\nas well as event handler listening on [Model](.\/model.litcoffee)\nevents.\n\nIt *always* returns an array (empty to denote no match) unless it\nencounters an error, in which case it will throw an Error.\n\n find: (pattern='.', opts={}) ->\n @debug \"[find] #{pattern}\"\n pattern = XPath.parse pattern, @schema\n switch\n when pattern.tag is '\/' and this isnt @root then @root.find(pattern)\n when pattern.tag is '..' then @parent?.find pattern.xpath\n else pattern.apply(this) ? []\n\n### in (pattern)\n\nA convenience routine to locate one or more matching Property\ninstances based on `pattern` (XPATH or YPATH) from this Model.\n\n in: (pattern) ->\n try props = @find pattern\n return unless props? and props.length\n return switch\n when props.length > 1 then props\n else props[0]\n\n### defer (value)\n\nOptionally defer setting the value to the property until root has been updated.\n\n defer: (value) ->\n @debug \"deferring '#{@kind}(#{@name})' until update at #{@root.name}\"\n @root.once 'update', =>\n @debug \"applying deferred data (#{typeof value})\"\n @content = value\n return value\n \n### error (msg)\n\nProvides more contextual error message pertaining to the Property instance.\n \n error: (err, ctx=this) ->\n err = new Error err unless err instanceof Error\n err.uri = @uri \n err.src = this\n err.ctx = ctx\n return err\n\n### throw (msg)\n\n throw: (err) -> throw @error(err)\n\n### toJSON\n\nThis call creates a new copy of the current `Property.content`\ncompletely detached\/unbound to the underlying data schema. It's main\nutility is to represent the current data state for subsequent\nserialization\/transmission. It accepts optional argument `tag` which\nwhen called with `true` will tag the produced object with the current\nproperty's `@name`.\n\n toJSON: (key, state = true) ->\n value = switch\n when @kind is 'anydata' then undefined\n when state isnt true and not @mutable then undefined\n else @value\n value = \"#{@name}\": value if key is true\n return value\n\n### inspect\n\n inspect: ->\n return {\n name: @tag ? @name\n kind: @kind\n path: @path.toString()\n schema: @schema.toJSON? tag: false, extended: true\n active: @active\n changed: @changed\n mutable: @mutable\n content: @toJSON()\n }\n\n## Export Property Class\n\n module.exports = Property\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Literate CoffeeScript"} {"commit":"1fe12bfcb95281d2b06e43693a77f6531bd0b59d","subject":"Use to path data structure (no row\/col - now it's x\/y)","message":"Use to path data structure (no row\/col - now it's x\/y)\n","repos":"bsgbryan\/skyll,bsgbryan\/skyll","old_file":"lib\/render-pipelines\/png\/png_blocks.litcoffee","new_file":"lib\/render-pipelines\/png\/png_blocks.litcoffee","new_contents":" PngRenderer = require '.\/png_renderer'\n\n class PngBlocks extends PngRenderer\n\n do_render: (ctx, path) =>\n width = @config.width\n height = @config.height\n\n for step in path\n ctx.fillStyle = @config.block.fill_color\n\n ctx.beginPath()\n ctx.rect width * step.x, height * step.y, width, height\n ctx.fill()\n\n module.exports = PngBlocks\n","old_contents":" PngRenderer = require '.\/png_renderer'\n\n class PngBlocks extends PngRenderer\n\n do_render: (ctx, path) =>\n width = @config.width\n height = @config.height\n\n for step in path\n ctx.fillStyle = @config.block.fill_color\n\n ctx.beginPath()\n ctx.rect width * step.col, height * step.row, width, height\n ctx.fill()\n\n module.exports = PngBlocks\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"dd865a8d7c1264d228765eebe6a211eda6ba62ba","subject":"Formatting fix","message":"Formatting fix\n","repos":"cha0s\/shrub,cha0s\/shrub,cha0s\/shrub","old_file":"client\/modules\/middleware.litcoffee","new_file":"client\/modules\/middleware.litcoffee","new_contents":"# Abstract middleware stacks\n\n {EventEmitter} = require 'events'\n\n config = require 'config'\n pkgman = require 'pkgman'\n\n exports.Middleware = class Middleware extends EventEmitter\n\nImplements a middleware stack. Middleware functions can be added to the stack\nwith `use`. Calling `dispatch` invokes the middleware functions serially.\n\nEach middleware accepts an arbitrary parameters and finally a `next` function.\nWhen a middleware finishes, it must call the `next` function. If there was an\nerror, it must be thrown or passed as the first argument to `next`. If no error\noccurred, `next` must be invoked without arguments.\n\nError-handling middleware can also be defined. These middleware take an\nadditional parameter at the beginning of the function signature: `error`.\nError-handling middleware are only called if a previous middleware threw or\npassed an error. Conversely, non-error-handling middleware are skipped if a\nprevious error occurred.\n\n## *constructor*\n\n*Create a middleware stack.*\n\n constructor: -> @_middleware = []\n\n## Middlware#use\n\n* (function) `fn` - A middleware function.\n\n*Add a middleware function to the stack.*\n\n use: (fn) -> @_middleware.push fn\n\n## Middleware#dispatch\n\n* (mixed) `...` - One or more values to pass to the middleware.\n* (function) `fn` - A function invoked when the middleware stack has\n finished. If an error occurred, it will be passed as the first\n argument.\n\n*Invoke the middleware functions serially.*\n\n dispatch: (args..., fn) ->\n self = this\n\n index = 0\n\n invoke = (error) ->\n\n self.emit 'invoked', self._middleware[index - 1] if index > 0\n\nCall `fn` with any error if we're done.\n\n return fn error if index is self._middleware.length\n\n current = self._middleware[index++]\n\nError-handling middleware.\n\n if current.length is args.length + 2\n\nAn error occurred previously.\n\n if error?\n\nTry to invoke the middleware, if it throws, just catch the error and pass it\nalong.\n\n try\n localArgs = args.concat()\n localArgs.unshift error\n localArgs.push invoke\n self.emit 'invoking', current\n current localArgs...\n catch error\n invoke error\n\nNo previous error; skip this middleware.\n\n else\n\n invoke error\n\nNon-error-handling middleware.\n\n else\n\nAn error occurred previously, skip this middleware.\n\n if error?\n\n invoke error\n\nNo previous error.\n\n else\n\nTry to invoke the middleware, if it throws, just catch the error and pass it along.\n\n try\n localArgs = args.concat()\n localArgs.push invoke\n self.emit 'invoking', current\n current localArgs...\n catch error\n invoke error\n\nKick things off.\n\n invoke()\n\n debug = require('debug') 'shrub:middleware'\n debugSilly = require('debug') 'shrub-silly:middleware'\n\n## middleware.fromHook\n\n*Create a middleware stack from the results of a hook and path configuration.*\n\n exports.fromHook = (hook, paths, args...) ->\n\n middleware = new Middleware()\n\nInvoke the hook and `use` the middleware in the paths configuration order.\n\n args.unshift hook\n hookResults = pkgman.invoke args...\n for path in paths ? []\n continue unless (spec = hookResults[path])?\n\n debugSilly \"- - #{spec.label}\"\n\n for fn in spec.middleware ? []\n fn.label = spec.label\n middleware.use fn, spec.label\n\n middleware.on 'invoking', (fn) -> debugSilly \"Invoking #{fn.label}\"\n middleware.on 'invoked', (fn) -> debugSilly \"Invoked #{fn.label}\"\n\n middleware\n\n## middleware.fromShortName\n\n*Create a middleware stack from a short name. e.g. \"example thing hook\".*\n\nThe short name is converted into log messages, a hook name, and configuration\nkey. In the case where we passed in \"user before login\", this would look\nlike:\n\n```coffeescript\ndebug \"Loading user before login middleware...\"\n\nmiddleware = exports.fromHook(\n\t\"userBeforeLoginMiddleware\"\n\tconfig.get \"packageSettings:user:beforeLoginMiddleware\"\n)\n\ndebug \"User before login middleware loaded.\"\n```\n\n###### TODO: This is bad and it should go away.\n\n exports.fromShortName = (shortName, packageName) ->\n\n i8n = require 'inflection'\n\n debugSilly \"- Loading #{shortName} middleware...\"\n\n [firstPart, keyParts...] = shortName.split ' '\n packageName ?= firstPart\n key = keyParts.join '_'\n\n###### TODO: this really should be unified, making this unnecessary.\n\n configKey = if global? then 'packageSettings' else 'packageConfig'\n\n middleware = exports.fromHook(\n \"#{firstPart}#{i8n.camelize key}Middleware\"\n\n config.get \"#{configKey}:#{packageName}:#{\n i8n.camelize key, true\n }Middleware\"\n )\n\n debugSilly \"- #{i8n.capitalize shortName} middleware loaded.\"\n\n middleware\n","old_contents":"# Abstract middleware stacks\n\n {EventEmitter} = require 'events'\n\n config = require 'config'\n pkgman = require 'pkgman'\n\n exports.Middleware = class Middleware extends EventEmitter\n\nImplements a middleware stack. Middleware functions can be added to the stack\nwith `use`. Calling `dispatch` invokes the middleware functions serially.\n\nEach middleware accepts an arbitrary parameters and finally a `next` function.\nWhen a middleware finishes, it must call the `next` function. If there was an\nerror, it must be thrown or passed as the first argument to `next`. If no error\noccurred, `next` must be invoked without arguments.\n\nError-handling middleware can also be defined. These middleware take an\nadditional parameter at the beginning of the function signature: `error`.\nError-handling middleware are only called if a previous middleware threw or\npassed an error. Conversely, non-error-handling middleware are skipped if a\nprevious error occurred.\n\n## *constructor*\n\n*Create a middleware stack.*\n\n constructor: -> @_middleware = []\n\n## Middlware#use\n\n* (function) `fn` - A middleware function.\n\n*Add a middleware function to the stack.*\n\n use: (fn) -> @_middleware.push fn\n\n## Middleware#dispatch\n\n* (mixed) `...` - One or more values to pass to the middleware.\n* (function) `fn` - A function invoked when the middleware stack has\n finished. If an error occurred, it will be passed as the first\n argument.\n\n*Invoke the middleware functions serially.*\n\n dispatch: (args..., fn) ->\n self = this\n\n index = 0\n\n invoke = (error) ->\n\n self.emit 'invoked', self._middleware[index - 1] if index > 0\n\nCall `fn` with any error if we're done.\n\n return fn error if index is self._middleware.length\n\n current = self._middleware[index++]\n\nError-handling middleware.\n\n if current.length is args.length + 2\n\nAn error occurred previously.\n\n if error?\n\nTry to invoke the middleware, if it throws, just catch the error and pass it\nalong.\n\n try\n localArgs = args.concat()\n localArgs.unshift error\n localArgs.push invoke\n self.emit 'invoking', current\n current localArgs...\n catch error\n invoke error\n\nNo previous error; skip this middleware.\n\n else\n\n invoke error\n\nNon-error-handling middleware.\n\n else\n\nAn error occurred previously, skip this middleware.\n\n if error?\n\n invoke error\n\nNo previous error.\n\n else\n\nTry to invoke the middleware, if it throws, just catch the error and pass it along.\n try\n localArgs = args.concat()\n localArgs.push invoke\n self.emit 'invoking', current\n current localArgs...\n catch error\n invoke error\n\nKick things off.\n\n invoke()\n\n debug = require('debug') 'shrub:middleware'\n debugSilly = require('debug') 'shrub-silly:middleware'\n\n## middleware.fromHook\n\n*Create a middleware stack from the results of a hook and path configuration.*\n\n exports.fromHook = (hook, paths, args...) ->\n\n middleware = new Middleware()\n\nInvoke the hook and `use` the middleware in the paths configuration order.\n\n args.unshift hook\n hookResults = pkgman.invoke args...\n for path in paths ? []\n continue unless (spec = hookResults[path])?\n\n debugSilly \"- - #{spec.label}\"\n\n for fn in spec.middleware ? []\n fn.label = spec.label\n middleware.use fn, spec.label\n\n middleware.on 'invoking', (fn) -> debugSilly \"Invoking #{fn.label}\"\n middleware.on 'invoked', (fn) -> debugSilly \"Invoked #{fn.label}\"\n\n middleware\n\n## middleware.fromShortName\n\n*Create a middleware stack from a short name. e.g. \"example thing hook\".*\n\nThe short name is converted into log messages, a hook name, and configuration\nkey. In the case where we passed in \"user before login\", this would look\nlike:\n\n```coffeescript\ndebug \"Loading user before login middleware...\"\n\nmiddleware = exports.fromHook(\n\t\"userBeforeLoginMiddleware\"\n\tconfig.get \"packageSettings:user:beforeLoginMiddleware\"\n)\n\ndebug \"User before login middleware loaded.\"\n```\n\n###### TODO: This is bad and it should go away.\n\n exports.fromShortName = (shortName, packageName) ->\n\n i8n = require 'inflection'\n\n debugSilly \"- Loading #{shortName} middleware...\"\n\n [firstPart, keyParts...] = shortName.split ' '\n packageName ?= firstPart\n key = keyParts.join '_'\n\n###### TODO: this really should be unified, making this unnecessary.\n\n configKey = if global? then 'packageSettings' else 'packageConfig'\n\n middleware = exports.fromHook(\n \"#{firstPart}#{i8n.camelize key}Middleware\"\n\n config.get \"#{configKey}:#{packageName}:#{\n i8n.camelize key, true\n }Middleware\"\n )\n\n debugSilly \"- #{i8n.capitalize shortName} middleware loaded.\"\n\n middleware\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"ebe0c83ab16b07e2a17196a6227ca10350c0b41a","subject":"Remove unused import","message":"Remove unused import\n","repos":"Turistforeningen\/Turbasen,Turbasen\/Turbasen","old_file":"coffee\/collection.litcoffee","new_file":"coffee\/collection.litcoffee","new_contents":" ObjectID = require('mongodb').ObjectID\n stringify = require('JSONStream').stringify\n\n Document = require '.\/model\/Document'\n\n sentry = require '.\/db\/sentry'\n mongo = require '.\/db\/mongo'\n\n## PARAM {collection}\n\n exports.param = (req, res, next, col) ->\n if col not in ['turer', 'steder', 'grupper', 'omr\u00e5der', 'bilder', 'arrangementer']\n return res.json 404, message: 'Objekttype ikke funnet'\n\n req.type = col\n req.db = col: mongo[col]\n\n next()\n\n## OPTIONS \/{collection}\n\n exports.options = (req, res, next) ->\n res.setHeader 'Access-Control-Expose-Headers', [\n 'ETag', 'Location', 'Last-Modified', 'Count-Return', 'Count-Total'\n ].join(', ')\n res.setHeader 'Access-Control-Max-Age', 86400\n res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'\n res.setHeader 'Access-Control-Allow-Methods', 'HEAD, GET, POST'\n res.send 204\n\n## HEAD \/{collection}\n## GET \/{collection}\n\n exports.get = (req, res, next) ->\n query = {}\n\n### ?tag=`String`\n\n if typeof req.query.tag is 'string' and req.query.tag isnt ''\n if req.query.tag.charAt(0) is '!' and req.query.tag.length > 1\n query['tags.0'] = $ne: req.query.tag.substr(1)\n else\n query['tags.0'] = req.query.tag\n\n### ?grupper=`String`\n\n if typeof req.query.gruppe is 'string' and req.query.gruppe isnt ''\n query['grupper'] = req.query.gruppe\n\n### ?after=`Mixed`\n\n if typeof req.query.after is 'string' and req.query.after isnt ''\n time = req.query.after\n\n if not isNaN time\n # Make unix timestamp into milliseconds\n time = time + '000' if (time + '').length is 10\n time = parseInt time\n\n time = new Date time\n\n if time.toString() isnt 'Invalid Date'\n query.endret = $gte: time.toISOString()\n\n### ?bbox=`min_lng`,`min_lat`,`max_lng`,`max_lat`\n\n if typeof req.query.bbox is 'string' and req.query.bbox.split(',').length is 4\n bbox = req.query.bbox.split(',')\n bbox[i] = parseFloat(val) for val, i in bbox\n\n query.geojson =\n '$geoWithin':\n '$geometry':\n type: 'Polygon'\n coordinates: [[\n [bbox[0], bbox[1]]\n [bbox[2], bbox[1]]\n [bbox[2], bbox[3]]\n [bbox[0], bbox[3]]\n [bbox[0], bbox[1]]\n ]]\n\n### ?privat.`String`=`String`\n\nThis allows the user to filter documents based on private document properties.\nThis will autumaticly limit returned documents to those owned by the current\nuser.\n\n#### ToDo\n\n * Limit number of private fields?\n * Limit depth of private fields?\n\n`NB` This section is looping through all of the url query parameters and hence\nshould take the queries from above sections into concideration so we don't need\nto do double amount of work.\n\n for key, val of req.query when key.substr(0,7) is 'privat.'\n if \/^[a-z\u00e6\u00f8\u00e5A-Z\u00c6\u00d8\u00c50-9_.]+$\/.test key\n val = parseFloat(val) if not isNaN val # @TODO(starefossen) is this acceptable?\n query.tilbyder = req.usr\n query[key] = val\n\nLimit queries to own documents or public documents i.e. where `doc.status` is\n`Offentlig` if not `query.tilbyder` is set.\n\n query['$or'] = [{status: 'Offentlig'}, {tilbyder: req.usr}] if not query.tilbyder\n\nOnly project a few fields to since lists are mostly used intermediate before\nfetching the entire document.\n\n fields = tilbyder: true, endret: true, status: true, navn: true, tags: true\n\nSet up MongoDB options.\n\n options =\n limit: Math.min((parseInt(req.query.limit, 10) or 20), 50)\n skip: parseInt(req.query.skip, 10) or 0\n sort: 'endret'\n\nRetrive matching documents from MongoDB.\n\n cursor = req.db.col.find(query, fields, options)\n cursor.count (err, total) ->\n return next err if err\n res.set 'Count-Return', Math.min(options.limit, total)\n res.set 'Count-Total', total\n return res.send 204 if req.method is 'HEAD'\n return res.json documents: [], count: 0, total: 0 if total is 0\n res.set 'Content-Type', 'application\/json; charset=utf-8'\n\nCalculate number of rows returned since we don't know that in advanced (due to\nthe nature of streaming).\n\n count = Math.min(options.limit, Math.max(total - options.skip, 0))\n\nStream documents user in order to prevent loading them into memory.\n\n op = '{\"documents\":['\n cl = '],\"count\":' + count + ',\"total\":' + total + '}'\n\n cursor.stream().pipe(stringify(op, ',', cl)).pipe(res)\n\n## POST \/{collection}\n\n exports.post = (req, res, next) ->\n return res.json 400, message: 'Body is missing' if Object.keys(req.body).length is 0\n return res.json 422, message: 'Body should be a JSON Hash' if req.body instanceof Array\n\n req.body.tilbyder = req.usr\n\n new Document(req.type, null).once('error', next).once 'ready', ->\n @insert req.body, (err, warn, data) ->\n if err\n return next(err) if err.name isnt 'ValidationError'\n\n sentry.captureDocumentError req, err\n\n return res.json 422,\n document: req.body\n message: 'Validation Failed'\n errors: err.details #TODO(starefossen) document this\n\n res.set 'ETag', \"\\\"#{data.checksum}\\\"\"\n res.set 'Last-Modified', new Date(data.endret).toUTCString()\n # res.set 'Location', req.get 'host'\n\n return res.json 201,\n document: data\n message: 'Validation Warnings' if warn.length > 0\n warnings: warn if warn.length > 0\n\n","old_contents":" ObjectID = require('mongodb').ObjectID\n stringify = require('JSONStream').stringify\n createHash = require('crypto').createHash\n\n Document = require '.\/model\/Document'\n\n sentry = require '.\/db\/sentry'\n mongo = require '.\/db\/mongo'\n\n## PARAM {collection}\n\n exports.param = (req, res, next, col) ->\n if col not in ['turer', 'steder', 'grupper', 'omr\u00e5der', 'bilder', 'arrangementer']\n return res.json 404, message: 'Objekttype ikke funnet'\n\n req.type = col\n req.db = col: mongo[col]\n\n next()\n\n## OPTIONS \/{collection}\n\n exports.options = (req, res, next) ->\n res.setHeader 'Access-Control-Expose-Headers', [\n 'ETag', 'Location', 'Last-Modified', 'Count-Return', 'Count-Total'\n ].join(', ')\n res.setHeader 'Access-Control-Max-Age', 86400\n res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'\n res.setHeader 'Access-Control-Allow-Methods', 'HEAD, GET, POST'\n res.send 204\n\n## HEAD \/{collection}\n## GET \/{collection}\n\n exports.get = (req, res, next) ->\n query = {}\n\n### ?tag=`String`\n\n if typeof req.query.tag is 'string' and req.query.tag isnt ''\n if req.query.tag.charAt(0) is '!' and req.query.tag.length > 1\n query['tags.0'] = $ne: req.query.tag.substr(1)\n else\n query['tags.0'] = req.query.tag\n\n### ?grupper=`String`\n\n if typeof req.query.gruppe is 'string' and req.query.gruppe isnt ''\n query['grupper'] = req.query.gruppe\n\n### ?after=`Mixed`\n\n if typeof req.query.after is 'string' and req.query.after isnt ''\n time = req.query.after\n\n if not isNaN time\n # Make unix timestamp into milliseconds\n time = time + '000' if (time + '').length is 10\n time = parseInt time\n\n time = new Date time\n\n if time.toString() isnt 'Invalid Date'\n query.endret = $gte: time.toISOString()\n\n### ?bbox=`min_lng`,`min_lat`,`max_lng`,`max_lat`\n\n if typeof req.query.bbox is 'string' and req.query.bbox.split(',').length is 4\n bbox = req.query.bbox.split(',')\n bbox[i] = parseFloat(val) for val, i in bbox\n\n query.geojson =\n '$geoWithin':\n '$geometry':\n type: 'Polygon'\n coordinates: [[\n [bbox[0], bbox[1]]\n [bbox[2], bbox[1]]\n [bbox[2], bbox[3]]\n [bbox[0], bbox[3]]\n [bbox[0], bbox[1]]\n ]]\n\n### ?privat.`String`=`String`\n\nThis allows the user to filter documents based on private document properties.\nThis will autumaticly limit returned documents to those owned by the current\nuser.\n\n#### ToDo\n\n * Limit number of private fields?\n * Limit depth of private fields?\n\n`NB` This section is looping through all of the url query parameters and hence\nshould take the queries from above sections into concideration so we don't need\nto do double amount of work.\n\n for key, val of req.query when key.substr(0,7) is 'privat.'\n if \/^[a-z\u00e6\u00f8\u00e5A-Z\u00c6\u00d8\u00c50-9_.]+$\/.test key\n val = parseFloat(val) if not isNaN val # @TODO(starefossen) is this acceptable?\n query.tilbyder = req.usr\n query[key] = val\n\nLimit queries to own documents or public documents i.e. where `doc.status` is\n`Offentlig` if not `query.tilbyder` is set.\n\n query['$or'] = [{status: 'Offentlig'}, {tilbyder: req.usr}] if not query.tilbyder\n\nOnly project a few fields to since lists are mostly used intermediate before\nfetching the entire document.\n\n fields = tilbyder: true, endret: true, status: true, navn: true, tags: true\n\nSet up MongoDB options.\n\n options =\n limit: Math.min((parseInt(req.query.limit, 10) or 20), 50)\n skip: parseInt(req.query.skip, 10) or 0\n sort: 'endret'\n\nRetrive matching documents from MongoDB.\n\n cursor = req.db.col.find(query, fields, options)\n cursor.count (err, total) ->\n return next err if err\n res.set 'Count-Return', Math.min(options.limit, total)\n res.set 'Count-Total', total\n return res.send 204 if req.method is 'HEAD'\n return res.json documents: [], count: 0, total: 0 if total is 0\n res.set 'Content-Type', 'application\/json; charset=utf-8'\n\nCalculate number of rows returned since we don't know that in advanced (due to\nthe nature of streaming).\n\n count = Math.min(options.limit, Math.max(total - options.skip, 0))\n\nStream documents user in order to prevent loading them into memory.\n\n op = '{\"documents\":['\n cl = '],\"count\":' + count + ',\"total\":' + total + '}'\n\n cursor.stream().pipe(stringify(op, ',', cl)).pipe(res)\n\n## POST \/{collection}\n\n exports.post = (req, res, next) ->\n return res.json 400, message: 'Body is missing' if Object.keys(req.body).length is 0\n return res.json 422, message: 'Body should be a JSON Hash' if req.body instanceof Array\n\n req.body.tilbyder = req.usr\n\n new Document(req.type, null).once('error', next).once 'ready', ->\n @insert req.body, (err, warn, data) ->\n if err\n return next(err) if err.name isnt 'ValidationError'\n\n sentry.captureDocumentError req, err\n\n return res.json 422,\n document: req.body\n message: 'Validation Failed'\n errors: err.details #TODO(starefossen) document this\n\n res.set 'ETag', \"\\\"#{data.checksum}\\\"\"\n res.set 'Last-Modified', new Date(data.endret).toUTCString()\n # res.set 'Location', req.get 'host'\n\n return res.json 201,\n document: data\n message: 'Validation Warnings' if warn.length > 0\n warnings: warn if warn.length > 0\n\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"} {"commit":"65689c02bd0e8062bd11513e2b63db7cf38adec8","subject":"support fenced code blocks with syntax highlight in markdown","message":"support fenced code blocks with syntax highlight in markdown\n","repos":"romanpitak\/pitak.net,romanpitak\/pitak.net","old_file":"src\/jade\/build.litcoffee","new_file":"src\/jade\/build.litcoffee","new_contents":"# The build script\n\nThis is a very simple build script that puts together the YAML + JADE page files\nand the pure JADE template files. It also builds the blog index.\n\nLoad modules\n\n fs = require 'fs'\n mkdirp = require('mkdirp').sync;\n jade = require 'jade'\n yaml = require 'js-yaml'\n config = require '.\/config'\n\n### Markdown\n\nAdd custom markdown parser\nwith custom code parsing function\nthat highlights with Pygments\n\n**note**: We are overriding `renderer.code`\ninstead of `renderer.options.highlight`\nbecause it wraps the highlihter result in unnecessary `
`.\n\n**note**: Since Jade doesn't support async filters,\nwe have to use `child_process.execSync`.\nThis requires Node >= 0.11.12\n\nFurther reading:\n- [Marked overriding-renderer-methods](https:\/\/www.npmjs.com\/package\/marked#overriding-renderer-methods)\n- [Node child_process.execSync](http:\/\/nodejs.org\/docs\/v0.12.0\/api\/child_process.html#child_process_child_process_execsync_command_options)\n- [Jade How to define\/install custom filter?](https:\/\/github.com\/jadejs\/jade\/issues\/1055)\n- [Pygments lexers](http:\/\/pygments.org\/docs\/lexers\/)\n\n    execSync = (require 'child_process').execSync\n    marked = require 'marked'\n\n    renderer = new marked.Renderer\n    renderer.code = (code, lexer = 'text') ->\n        result = execSync \"pygmentize -l #{lexer} -f html\",\n            input: code\n        return result.toString()\n\n    marked.setOptions\n        renderer: renderer\n\n    jade.filters.markdown = marked\n\n### Template loader\n\nTemplates are different from pages in that they don't have a YAML front matter.\nThey are written in clean jade and can extend and include other templates.\n\n    class Template\n        constructor: (@name = 'page', @location = config.templatesPath) ->\n        getHtml: (options) ->\n            cwd = process.cwd()\n            options.pretty = config.pretty\n            options.filename = @name\n            try\n                process.chdir @location\n                content = fs.readFileSync \"#{@name}.jade\", 'utf8'\n                @html = jade.render content, options\n            catch error\n                console.log error\n            finally\n                process.chdir cwd\n            return @html\n\n## Page loader\n\n    class Page\n\nA nice \/regexp?\/ from the\n[dworthen\/js-yaml-front-matter](https:\/\/github.com\/dworthen\/js-yaml-front-matter\/blob\/master\/lib\/js-yaml-front.js)\nrepo to separate the YAML front matter from the JADE page content.\n\n        re: \/^(-{3}(?:\\n|\\r)([\\w\\W]+?)(?:\\n|\\r)-{3})?([\\w\\W]*)*\/\n\nSet the file name and location\n\n        constructor: (@pageFile, @location = config.pagesPath) ->\n\nRender the HTML\n\n        render: ->\n\nMake sure we have content\n\n            if not @content?\n                if not @pageFile?\n                    throw new Error 'pageFile not set'\n                location = \"#{@location}\/#{@pageFile}\"\n                @content = fs.readFileSync location, 'utf8'\n\nParse the content\n\n            parts = @re.exec @content\n            if ! @frontMatter?\n                @frontMatter = if parts[2]? then yaml.safeLoad parts[2] else {}\n            this[key] = value for key, value of @frontMatter\n            if ! @containerContent?\n                @containerContent = jade.render parts[3] or '',\n                    filename: @pageFile\n                    pretty: config.pretty\n\nParse the template\n\n            template = new Template @template or null\n            @html = template.getHtml this\n\nWrite the page into the output directory. I might move this to a separate\nfunction (class) later on maybe?\n\n        write: ->\n            folder = \"#{config.htmlPath}#{@url}\"\n            mkdirp folder unless fs.existsSync folder\n            fs.writeFileSync \"#{folder}\/index.html\", @html\n\n#### Blog\n\nIt's the blog index page.\n\n    class Blog extends Page\n        posts: []\n        content: ''\n        template: 'blog'\n        title: 'Blog'\n        url: '\/blog'\n\n#### Pages\n\nIterate through a given directory and process the given pages.\n\nEach page is pushed into a list of pages that will later be used for blog building\nand sitemap.xml\n\n    class Pages\n        constructor: (@location) ->\n            @pages = []\n        render: ->\n            for pageFile in (fs.readdirSync @location).reverse()\n                page = new Page pageFile, @location\n                page.render()\n                page.write()\n                @pages.push page\n\n#### Blogs\n\nDo the Pages thing and build a blog index on top.\n\n    class Blogs extends Pages\n        render: ->\n            super()\n            blog = new Blog\n            blog.posts = @pages\n            do blog.render\n            do blog.write\n\n# Render\n\n    pages = new Pages config.pagesPath\n    pages.render()\n    blogs = new Blogs config.blogPath\n    blogs.render()\n","old_contents":"# The build script\n\nThis is a very simple build script that puts together the YAML + JADE page files\nand the pure JADE template files. It also builds the blog index.\n\nLoad modules\n\n    fs = require 'fs'\n    mkdirp = require('mkdirp').sync;\n    jade = require 'jade'\n    yaml = require 'js-yaml'\n    config = require '.\/config'\n    execSync = (require 'child_process').execSync\n\nAdd custom Pygments filters to Jade\n\n    jade.filters.bashcode = (text) ->\n        result = execSync 'pygmentize -l bash -f html',\n            input: text\n        return result.toString()\n\n### Template loader\n\nTemplates are different from pages in that they don't have a YAML front matter.\nThey are written in clean jade and can extend and include other templates.\n\n    class Template\n        constructor: (@name = 'page', @location = config.templatesPath) ->\n        getHtml: (options) ->\n            cwd = process.cwd()\n            options.pretty = config.pretty\n            options.filename = @name\n            try\n                process.chdir @location\n                content = fs.readFileSync \"#{@name}.jade\", 'utf8'\n                @html = jade.render content, options\n            catch error\n                console.log error\n            finally\n                process.chdir cwd\n            return @html\n\n## Page loader\n\n    class Page\n\nA nice \/regexp?\/ from the\n[dworthen\/js-yaml-front-matter](https:\/\/github.com\/dworthen\/js-yaml-front-matter\/blob\/master\/lib\/js-yaml-front.js)\nrepo to separate the YAML front matter from the JADE page content.\n\n        re: \/^(-{3}(?:\\n|\\r)([\\w\\W]+?)(?:\\n|\\r)-{3})?([\\w\\W]*)*\/\n\nSet the file name and location\n\n        constructor: (@pageFile, @location = config.pagesPath) ->\n\nRender the HTML\n\n        render: ->\n\nMake sure we have content\n\n            if not @content?\n                if not @pageFile?\n                    throw new Error 'pageFile not set'\n                location = \"#{@location}\/#{@pageFile}\"\n                @content = fs.readFileSync location, 'utf8'\n\nParse the content\n\n            parts = @re.exec @content\n            if ! @frontMatter?\n                @frontMatter = if parts[2]? then yaml.safeLoad parts[2] else {}\n            this[key] = value for key, value of @frontMatter\n            if ! @containerContent?\n                @containerContent = jade.render parts[3] or '',\n                    filename: @pageFile\n                    pretty: config.pretty\n\nParse the template\n\n            template = new Template @template or null\n            @html = template.getHtml this\n\nWrite the page into the output directory. I might move this to a separate\nfunction (class) later on maybe?\n\n        write: ->\n            folder = \"#{config.htmlPath}#{@url}\"\n            mkdirp folder unless fs.existsSync folder\n            fs.writeFileSync \"#{folder}\/index.html\", @html\n\n#### Blog\n\nIt's the blog index page.\n\n    class Blog extends Page\n        posts: []\n        content: ''\n        template: 'blog'\n        title: 'Blog'\n        url: '\/blog'\n\n#### Pages\n\nIterate through a given directory and process the given pages.\n\nEach page is pushed into a list of pages that will later be used for blog building\nand sitemap.xml\n\n    class Pages\n        constructor: (@location) ->\n            @pages = []\n        render: ->\n            for pageFile in (fs.readdirSync @location).reverse()\n                page = new Page pageFile, @location\n                page.render()\n                page.write()\n                @pages.push page\n\n#### Blogs\n\nDo the Pages thing and build a blog index on top.\n\n    class Blogs extends Pages\n        render: ->\n            super()\n            blog = new Blog\n            blog.posts = @pages\n            do blog.render\n            do blog.write\n\n# Render\n\n    pages = new Pages config.pagesPath\n    pages.render()\n    blogs = new Blogs config.blogPath\n    blogs.render()\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"}
{"commit":"352a498c9eae5b2f170fa6989fbdc5daa3d0db26","subject":"Item::pointer::pressed and hover props are initialized when possible","message":"Item::pointer::pressed and hover props are initialized when possible\n","repos":"Neft-io\/neft,Neft-io\/neft,Neft-io\/neft,Neft-io\/neft,Neft-io\/neft,Neft-io\/neft","old_file":"src\/renderer\/types\/basics\/item\/pointer.litcoffee","new_file":"src\/renderer\/types\/basics\/item\/pointer.litcoffee","new_contents":"# Pointer\n\n```javascript\nRectangle {\n    width: 100\n    height: 100\n    color: 'green'\n    if (this.pointer.hover) {\n        color: 'red'\n    }\n}\n```\n\n    'use strict'\n\n    utils = require 'src\/utils'\n    signal = require 'src\/signal'\n    assert = require 'src\/assert'\n\n    NOP = ->\n\n    module.exports = (Renderer, Impl, itemUtils, Item) -> (ctor) -> class Pointer extends itemUtils.DeepObject\n        @__name__ = 'Pointer'\n\n        itemUtils.defineProperty\n            constructor: ctor\n            name: 'pointer'\n            valueConstructor: Pointer\n\nEnables mouse and touch handling.\n\n        constructor: (ref) ->\n            super ref\n            @_enabled = true\n            @_draggable = false\n            @_dragActive = false\n            @_pressed = false\n            @_hover = false\n            @_pressedInitialized = false\n            @_hoverInitialized = false\n\n            Object.preventExtensions @\n\n## *Boolean* Pointer::enabled = `true`\n\n## *Signal* Pointer::onEnabledChange(*Boolean* oldValue)\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'enabled'\n            defaultValue: true\n            namespace: 'pointer'\n            parentConstructor: ctor\n            implementation: Impl.setItemPointerEnabled\n            developmentSetter: (val) ->\n                assert.isBoolean val\n\n## Hidden *Boolean* Pointer::draggable = `false`\n\n## Hidden *Signal* Pointer::onDraggableChange(*Boolean* oldValue)\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'draggable'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            implementation: Impl.setItemPointerDraggable\n            developmentSetter: (val) ->\n                assert.isBoolean val\n\n## Hidden *Boolean* Pointer::dragActive = `false`\n\n## Hidden *Signal* Pointer::onDragActiveChange(*Boolean* oldValue)\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'dragActive'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            implementation: Impl.setItemPointerDragActive\n            developmentSetter: (val) ->\n                assert.isBoolean val\n\n## *Signal* Pointer::onClick(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onPress(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onRelease(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onEnter(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onExit(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onWheel(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onMove(*Item.Pointer.Event* event)\n\n        PRESS_SIGNALS =\n            onClick: true\n            onPress: true\n            onRelease: true\n\n        MOVE_SIGNALS =\n            onEnter: true\n            onExit: true\n            onMove: true\n\n        onLazySignalInitialized = (pointer, name) ->\n            # automatically initialize pressed and hover properties\n            # if required events will be listened\n            if PRESS_SIGNALS[name] or MOVE_SIGNALS[name]\n                initializePressed pointer\n                if MOVE_SIGNALS[name]\n                    initializeHover pointer\n            Impl.attachItemSignal.call pointer, 'pointer', name # TODO: send here an item\n            return\n\n        @SIGNALS = Object.keys(PRESS_SIGNALS).concat(Object.keys(MOVE_SIGNALS)).concat [\n            'onWheel'\n            # 'onDragStart', 'onDragEnd',\n            # 'onDragEnter', 'onDragExit', 'onDrop'\n        ]\n\n        for signalName in @SIGNALS\n            signal.Emitter.createSignal @, signalName, onLazySignalInitialized\n\n## *Boolean* Pointer::pressed = `false`\n\nWhether the pointer is currently pressed.\n\n## *Signal* Pointer::onPressedChange(*Boolean* oldValue)\n\n        initializePressed = do ->\n            onPress = (event) ->\n                event.stopPropagation = false\n                @pressed = true\n            onRelease = ->\n                @pressed = false\n\n            (pointer) ->\n                unless pointer._pressedInitialized\n                    pointer._pressedInitialized = true\n                    pointer.onPress onPress\n                    pointer.onRelease onRelease\n                return\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'pressed'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            signalInitializer: initializePressed\n            getter: (_super) -> ->\n                initializePressed @\n                _super.call @\n\n## *Boolean* Pointer::hover = `false`\n\nWhether the pointer is currently under the item.\n\n## *Signal* Pointer::onHoverChange(*Boolean* oldValue)\n\n        initializeHover = do ->\n            onEnter = ->\n                @hover = true\n            onExit = ->\n                @hover = false\n\n            (pointer) ->\n                unless pointer._hoverInitialized\n                    pointer._hoverInitialized = true\n                    pointer.onEnter onEnter\n                    pointer.onExit onExit\n                return\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'hover'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            signalInitializer: initializeHover\n            getter: (_super) -> ->\n                initializeHover @\n                _super.call @\n\n## **Class** Pointer.Event : *Device.PointerEvent*\n\nEvents order:\n 1. Press\n 2. Enter\n 3. Move\n 4. Move (not captured ensured items)\n 5. Exit\n 6. Release\n 7. Click\n 8. Release (not captured ensured items)\n\nStopped 'Enter' event will emit 'Move' event on this item.\n\nStopped 'Exit' event will emit 'Release' event on this item.\n\n        @Event = class PointerEvent\n            constructor: ->\n                @_stopPropagation = true\n                @_checkSiblings = false\n                @_ensureRelease = true\n                @_ensureMove = true\n                Object.preventExtensions @\n\n            @:: = Object.create Renderer.Device.pointer\n            @::constructor = PointerEvent\n\n### *Boolean* PointerEvent::stopPropagation = `false`\n\nEnable this property to stop further event propagation.\n\n            utils.defineProperty @::, 'stopPropagation', null, ->\n                @_stopPropagation\n            , (val) ->\n                assert.isBoolean val\n                @_stopPropagation = val\n\n### *Boolean* PointerEvent::checkSiblings = `false`\n\nBy default first deepest captured item will propagate this event only by his parents.\n\nChange this value to test previous siblings as well.\n\n            utils.defineProperty @::, 'checkSiblings', null, ->\n                @_checkSiblings\n            , (val) ->\n                assert.isBoolean val\n                @_checkSiblings = val\n\n### *Boolean* PointerEvent::ensureRelease = `true`\n\nDefine whether pressed item should get 'onRelease' signal even\nif the pointer has been released outside of this item.\n\nCan be changed only in the 'onPress' signal.\n\n            utils.defineProperty @::, 'ensureRelease', null, ->\n                @_ensureRelease\n            , (val) ->\n                assert.isBoolean val\n                @_ensureRelease = val\n\n### *Boolean* PointerEvent::ensureMove = `true`\n\nDefine whether the pressed item should get 'onMove' signals even\nif the pointer is outside of this item.\n\nCan be changed only in the 'onPress' signal.\n\n            utils.defineProperty @::, 'ensureMove', null, ->\n                @_ensureMove\n            , (val) ->\n                assert.isBoolean val\n                @_ensureMove = val\n\n## *Item.Pointer.Event* Pointer.event\n\n        @event = new PointerEvent\n","old_contents":"# Pointer\n\n```javascript\nRectangle {\n    width: 100\n    height: 100\n    color: 'green'\n    if (this.pointer.hover) {\n        color: 'red'\n    }\n}\n```\n\n    'use strict'\n\n    utils = require 'src\/utils'\n    signal = require 'src\/signal'\n    assert = require 'src\/assert'\n\n    NOP = ->\n\n    module.exports = (Renderer, Impl, itemUtils, Item) -> (ctor) -> class Pointer extends itemUtils.DeepObject\n        @__name__ = 'Pointer'\n\n        itemUtils.defineProperty\n            constructor: ctor\n            name: 'pointer'\n            valueConstructor: Pointer\n\nEnables mouse and touch handling.\n\n        constructor: (ref) ->\n            super ref\n            @_enabled = true\n            @_draggable = false\n            @_dragActive = false\n            @_pressed = false\n            @_hover = false\n            @_pressedInitialized = false\n            @_hoverInitialized = false\n\n            Object.preventExtensions @\n\n## *Boolean* Pointer::enabled = `true`\n\n## *Signal* Pointer::onEnabledChange(*Boolean* oldValue)\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'enabled'\n            defaultValue: true\n            namespace: 'pointer'\n            parentConstructor: ctor\n            implementation: Impl.setItemPointerEnabled\n            developmentSetter: (val) ->\n                assert.isBoolean val\n\n## Hidden *Boolean* Pointer::draggable = `false`\n\n## Hidden *Signal* Pointer::onDraggableChange(*Boolean* oldValue)\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'draggable'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            implementation: Impl.setItemPointerDraggable\n            developmentSetter: (val) ->\n                assert.isBoolean val\n\n## Hidden *Boolean* Pointer::dragActive = `false`\n\n## Hidden *Signal* Pointer::onDragActiveChange(*Boolean* oldValue)\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'dragActive'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            implementation: Impl.setItemPointerDragActive\n            developmentSetter: (val) ->\n                assert.isBoolean val\n\n## *Signal* Pointer::onClick(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onPress(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onRelease(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onEnter(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onExit(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onWheel(*Item.Pointer.Event* event)\n\n## *Signal* Pointer::onMove(*Item.Pointer.Event* event)\n\n## Hidden *Signal* Pointer::onDragStart()\n\n## Hidden *Signal* Pointer::onDragEnd()\n\n## Hidden *Signal* Pointer::onDragEnter()\n\n## Hidden *Signal* Pointer::onDragExit()\n\n## Hidden *Signal* Pointer::onDrop()\n\n        onLazySignalInitialized = (pointer, name) ->\n            Impl.attachItemSignal.call pointer, 'pointer', name # TODO: send here an item\n            return\n\n        @SIGNALS = ['onClick', 'onPress', 'onRelease',\n                    'onEnter', 'onExit', 'onWheel', 'onMove',\n                    'onDragStart', 'onDragEnd',\n                    'onDragEnter', 'onDragExit', 'onDrop']\n\n        for signalName in @SIGNALS\n            signal.Emitter.createSignal @, signalName, onLazySignalInitialized\n\n## *Boolean* Pointer::pressed = `false`\n\nWhether the pointer is currently pressed.\n\n## *Signal* Pointer::onPressedChange(*Boolean* oldValue)\n\n        intitializePressed = do ->\n            onPress = (event) ->\n                event.stopPropagation = false\n                @pressed = true\n            onRelease = ->\n                @pressed = false\n\n            (pointer) ->\n                unless pointer._pressedInitialized\n                    pointer._pressedInitialized = true\n                    pointer.onPress onPress\n                    pointer.onRelease onRelease\n                return\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'pressed'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            signalInitializer: intitializePressed\n            getter: (_super) -> ->\n                intitializePressed @\n                _super.call @\n\n## *Boolean* Pointer::hover = `false`\n\nWhether the pointer is currently under the item.\n\n## *Signal* Pointer::onHoverChange(*Boolean* oldValue)\n\n        initializeHover = do ->\n            onEnter = ->\n                @hover = true\n            onExit = ->\n                @hover = false\n\n            (pointer) ->\n                unless pointer._hoverInitialized\n                    pointer._hoverInitialized = true\n                    pointer.onEnter onEnter\n                    pointer.onExit onExit\n                return\n\n        itemUtils.defineProperty\n            constructor: Pointer\n            name: 'hover'\n            defaultValue: false\n            namespace: 'pointer'\n            parentConstructor: ctor\n            signalInitializer: initializeHover\n            getter: (_super) -> ->\n                initializeHover @\n                _super.call @\n\n## **Class** Pointer.Event : *Device.PointerEvent*\n\nEvents order:\n 1. Press\n 2. Enter\n 3. Move\n 4. Move (not captured ensured items)\n 5. Exit\n 6. Release\n 7. Click\n 8. Release (not captured ensured items)\n\nStopped 'Enter' event will emit 'Move' event on this item.\n\nStopped 'Exit' event will emit 'Release' event on this item.\n\n        @Event = class PointerEvent\n            constructor: ->\n                @_stopPropagation = true\n                @_checkSiblings = false\n                @_ensureRelease = true\n                @_ensureMove = true\n                Object.preventExtensions @\n\n            @:: = Object.create Renderer.Device.pointer\n            @::constructor = PointerEvent\n\n### *Boolean* PointerEvent::stopPropagation = `false`\n\nEnable this property to stop further event propagation.\n\n            utils.defineProperty @::, 'stopPropagation', null, ->\n                @_stopPropagation\n            , (val) ->\n                assert.isBoolean val\n                @_stopPropagation = val\n\n### *Boolean* PointerEvent::checkSiblings = `false`\n\nBy default first deepest captured item will propagate this event only by his parents.\n\nChange this value to test previous siblings as well.\n\n            utils.defineProperty @::, 'checkSiblings', null, ->\n                @_checkSiblings\n            , (val) ->\n                assert.isBoolean val\n                @_checkSiblings = val\n\n### *Boolean* PointerEvent::ensureRelease = `true`\n\nDefine whether pressed item should get 'onRelease' signal even\nif the pointer has been released outside of this item.\n\nCan be changed only in the 'onPress' signal.\n\n            utils.defineProperty @::, 'ensureRelease', null, ->\n                @_ensureRelease\n            , (val) ->\n                assert.isBoolean val\n                @_ensureRelease = val\n\n### *Boolean* PointerEvent::ensureMove = `true`\n\nDefine whether the pressed item should get 'onMove' signals even\nif the pointer is outside of this item.\n\nCan be changed only in the 'onPress' signal.\n\n            utils.defineProperty @::, 'ensureMove', null, ->\n                @_ensureMove\n            , (val) ->\n                assert.isBoolean val\n                @_ensureMove = val\n\n## *Item.Pointer.Event* Pointer.event\n\n        @event = new PointerEvent\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"Literate CoffeeScript"}
{"commit":"756845f026fac83fb1c00faba269527beb3a7923","subject":"change port for heroku tests","message":"change port for heroku tests\n","repos":"pirati-cz\/gapi-sparql","old_file":"src\/gapi_sparql.litcoffee","new_file":"src\/gapi_sparql.litcoffee","new_contents":"\nGapiSparql - Main class for GAPI SPARQL component\n\n    restify = require('restify')\n    self = null\n\n    class GapiSparql\n\n        constructor: (options) ->\n            console.log('GapiSparql construct...')\n            self = @\n            @options = options or {}\n            \n            @options.name = 'gapi-sparql'\n            @options.version = '0.0.1'\n            @options.accept = \n            #@options.formatters = {}\n            #@options.formatters['application\/sparql-query'] = @sparqlQuery\n            @options.listenPort ?= 80\n            # @options.accept \n            \n            server = restify.createServer(@options)\n            #server.pre( (req, res, next) ->\n            #    req.headers.accept = 'application\/sparql-query'\n            #    return next()\n            #)\n            server.listen(@options.listenPort, () ->\n                console.log('%s listening at %s', server.name, server.url)\n            )\n            server.get('\/.*\/', (req, res, next) -> \n                # console.log(res)\n                d = \"ahoj svete\"\n                res.writeHead(200, {\n                    'Content-Length': Buffer.byteLength(d),\n                    'Content-Type': 'text\/plain'\n                })\n                res.write(d)\n                res.end()\n                next()\n            )\n            @server = server\n\n        @run: (argv, exit) ->\n            console.log('GapiSparql @run()')\n            gapisparql = new GapiSparql()\n            \n        sparqlQuery: (req, res, body) ->\n            console.log('GapiSparql @sparqlQuery()')\n            body = \"ahok\"\n            #console.log(body)\n            #console.log('----- GapiSparql @sparqlQuery() -----');\n            ###\n            if body instanceof Error\n                res.statusCode = body.statusCode || 500\n                if body.body\n                    #console.log('dada');\n                    #body = body.body.message\n                    body = \"ttt\"\n                else\n                    #body = message: body.message\n                    body = \"fifif\"\n                data = \"err\"\n            else\n                body = \"body pyco\"\n                data = \"aaa\"\n            console.log(body)\n            #console.log(req)\n            #console.log(res)\n            #console.log(body)\n            res.setHeader('Content-Length', Buffer.byteLength(body))\n            return body\n            ###\n            return body\n        \n        use: (pluginName) ->\n            \n      \n    module.exports = GapiSparql","old_contents":"\nGapiSparql - Main class for GAPI SPARQL component\n\n    restify = require('restify')\n    self = null\n\n    class GapiSparql\n\n        constructor: (options) ->\n            console.log('GapiSparql construct...')\n            self = @\n            @options = options or {}\n            \n            @options.name = 'gapi-sparql'\n            @options.version = '0.0.1'\n            @options.accept = \n            #@options.formatters = {}\n            #@options.formatters['application\/sparql-query'] = @sparqlQuery\n            @options.listenPort ?= 8008\n            # @options.accept \n            \n            server = restify.createServer(@options)\n            #server.pre( (req, res, next) ->\n            #    req.headers.accept = 'application\/sparql-query'\n            #    return next()\n            #)\n            server.listen(@options.listenPort, () ->\n                console.log('%s listening at %s', server.name, server.url)\n            )\n            server.get('\/.*\/', (req, res, next) -> \n                # console.log(res)\n                d = \"ahoj svete\"\n                res.writeHead(200, {\n                    'Content-Length': Buffer.byteLength(d),\n                    'Content-Type': 'text\/plain'\n                })\n                res.write(d)\n                res.end()\n                next()\n            )\n            @server = server\n\n        @run: (argv, exit) ->\n            console.log('GapiSparql @run()')\n            gapisparql = new GapiSparql()\n            \n        sparqlQuery: (req, res, body) ->\n            console.log('GapiSparql @sparqlQuery()')\n            body = \"ahok\"\n            #console.log(body)\n            #console.log('----- GapiSparql @sparqlQuery() -----');\n            ###\n            if body instanceof Error\n                res.statusCode = body.statusCode || 500\n                if body.body\n                    #console.log('dada');\n                    #body = body.body.message\n                    body = \"ttt\"\n                else\n                    #body = message: body.message\n                    body = \"fifif\"\n                data = \"err\"\n            else\n                body = \"body pyco\"\n                data = \"aaa\"\n            console.log(body)\n            #console.log(req)\n            #console.log(res)\n            #console.log(body)\n            res.setHeader('Content-Length', Buffer.byteLength(body))\n            return body\n            ###\n            return body\n        \n        use: (pluginName) ->\n            \n      \n    module.exports = GapiSparql","returncode":0,"stderr":"","license":"unlicense","lang":"Literate CoffeeScript"}
{"commit":"d50697bb597c63e0186164f059040b624b55f9ba","subject":"typo fix","message":"typo fix\n","repos":"vpj\/IO","old_file":"io.litcoffee","new_file":"io.litcoffee","new_contents":"    _self = this\n\n    if console?.log?\n     LOG = console.log.bind console\n    else\n     LOG = -> null\n\n    if console?.error?\n     ERROR_LOG = console.error.bind console\n    else\n     ERROR_LOG = -> null\n\n\n    POLL_TYPE =\n     progress: true\n\n##Response class\n\n    class Response\n     constructor: (data, port, options) ->\n      @id = data.id\n      @port = port\n      @options = options\n      @queue = []\n      @fresh = true\n\n     progress: (progress, data, callback) ->\n      @queue.push\n       method: 'progress'\n       data: data\n       options: {progress: progress}\n       callback: callback\n      @_handleQueue()\n\n     success: (data) ->\n      @queue.push method: 'success', data: data, options: {}\n      @_handleQueue()\n\n     fail: (data) ->\n      @queue.push method: 'fail', data: data, options: {}\n      @_handleQueue()\n\n     setOptions: (options) ->\n      @options = options\n      @fresh = true\n      @_handleQueue()\n\n     _multipleResponse: ->\n      responseList = []\n      callbacks = []\n      for d in @queue\n       responseList.push\n        status: d.method\n        data: d.data\n        options: d.options\n       if d.callback?\n        callbacks.push d.callback\n\n      done = ->\n       for callback in callbacks\n        callback()\n\n      if @port.isStreaming\n       @port.respondMultiple this, responseList, @options, done\n      else if @fresh\n       @port.respondMultiple this, responseList, @options, done\n       @fresh = false\n\n      @queue = []\n\n\n     _handleQueue: ->\n      return unless @queue.length > 0\n      return if not @port.isStreaming and not @fresh\n\n      if @queue.length > 1\n       return @_multipleResponse()\n\n\n      d = @queue[0]\n\n      if @port.isStreaming\n       @port.respond this, d.method, d.data, d.options, @options, d.callback\n      else if @fresh\n       @port.respond this, d.method, d.data, d.options, @options, d.callback\n       @fresh = false\n\n      @queue = []\n\n##Call class\n\n    class Call\n     constructor: (@id, @method, @data, @callbacks, @options, @port) -> null\n\n     handle: (data, options) ->\n      if not @callbacks[options.status]?\n       return if options.status is 'progress'\n       #Handled by caller\n       throw new Error \"No callback registered #{@method} #{options.status}\"\n      self = this\n      setTimeout ->\n       try\n        self.callbacks[options.status] data, options\n       catch e\n        if self.port.onerror?\n         self.port.onerror e\n        else\n         throw e\n      , 0\n\n      if POLL_TYPE[options.status]?\n       return false\n      else\n       return true\n\n##Port base class\n\n    class Port\n     constructor: ->\n      @handlers = {}\n      @callsCache = {}\n      @callsCounter = 0\n      @id = parseInt Math.random() * 1000\n      @responses = {}\n      @wrappers =\n       send: []\n       respond: []\n       handleCall: []\n       handleResponse: []\n\n     isStreaming: true\n\n     onCallError: (msg, options) ->\n      callsCache = @callsCache\n      @callsCache = {}\n      for id, call of callsCache\n       if not call.callbacks.fail?\n        ERROR_LOG 'fail callback not registered', call.method, call.data\n       else\n        call.callbacks.fail error: 'connectionError', msg: msg, options: options, {}\n\n      @errorCallback msg, options\n\n     onHandleError: (msg, data, options) ->\n      @errorCallback msg, data\n      response = new Response data, this, options\n      response.fail msg\n\n     errorCallback: (msg, options) ->\n      ERROR_LOG msg, options\n\n     wrap: (wrapper) ->\n      for key, f of wrapper\n       if @wrappers[key]?\n        @wrappers[key].push f\n       else\n        this[key] = f\n\n###Send RPC call\n\n     send: (method, data, callbacks, options = {}) ->\n      if (typeof callbacks) is 'function'\n       callbacks =\n        success: callbacks\n\n      for f in @wrappers.send\n       return unless f.apply this, [method, data, callbacks, options]\n\n      params = @_createCall method, data, callbacks, options\n      @_send params, callbacks\n\n###Respond to a RPC call\n\n     respond: (response, status, data, options = {}, portOptions = {}, callback = null) ->\n      if not POLL_TYPE[status]?\n       delete @responses[response.id]\n\n      for f in @wrappers.respond\n       return unless f.apply this, [response, status, data, options, portOptions]\n\n      @_respond (@_createResponse response, status, data, options), portOptions, callback\n\n     respondMultiple: (response, list, portOptions = {}, callback = null) ->\n      for d in list\n       if not POLL_TYPE[d.status]?\n        delete @responses[response.id]\n        break\n\n      data = []\n      for d in list\n       cancel = false\n       d.options ?= {}\n       for f in @wrappers.respond\n        r = f.apply this, [response, d.status, d.data, d.options, portOptions]\n        if not r\n         cancel = true\n         break\n\n        continue if cancel\n\n       data.push @_createResponse response, d.status, d.data, d.options\n\n      return if data.length is 0\n\n      data =\n       type: 'list'\n       list: data\n\n      @_respond data, portOptions, callback\n\n\n\n###Create Call object\nThis is a private function\n\n     _createCall: (method, data, callbacks, options) ->\n      call = new Call \"#{@id}-#{@callsCounter}\",\n                      method\n                      data\n                      callbacks\n                      options\n                      this\n      @callsCounter++\n      @callsCache[call.id] = call\n\n      params =\n       type: 'call'\n       id: call.id\n       method: call.method\n       data: call.data\n\n      params[k] = v for k, v of options\n      return params\n\n###Create Response object\n\n     _createResponse: (response, status, data, options) ->\n      params =\n       type: 'response'\n       id: response.id\n       status: status\n       data: data\n\n      params[k] = v for k, v of options\n\n      return params\n\n###Add handler\n\n     on: (method, callback) ->\n      @handlers[method] = callback\n\n###Handle incoming message\n\n     _handleMessage: (data, options, last = true) ->\n      switch data.type\n       when 'list'\n        for d, i in data.list\n         @_handleMessage d, options, (last and i + 1 is data.list.length)\n       when 'response'\n        try\n         @_handleResponse data, options, last\n        catch e\n         @onerror? e\n       when 'call'\n        try\n         @_handleCall data, options, last\n        catch e\n         @onerror? e\n       when 'poll'\n        try\n         @_handlePoll data, options, last\n        catch e\n         @onerror? e\n\n     _handleCall: (data, options) ->\n      for f in @wrappers.handleCall\n       return unless f.apply this, arguments\n      if not @handlers[data.method]?\n       @onHandleError \"Unknown method: #{data.method}\", data, options\n       return\n      @responses[data.id] = new Response data, this, options\n      @handlers[data.method] data.data, data, @responses[data.id]\n\n     _handleResponse: (data, options) ->\n      for f in @wrappers.handleResponse\n       return unless f.apply this, arguments\n      if not @callsCache[data.id]?\n       #Cannot reply\n       @errorCallback \"Response without call: #{data.id}\", data\n       return\n      try\n       if @callsCache[data.id].handle data.data, data\n        delete @callsCache[data.id]\n      catch e\n       @errorCallback e.message, data\n       delete @callsCache[data.id]\n\n     _handlePoll: (data, options) ->\n      @onHandleError \"Poll not implemented\", data, options\n\n##WorkerPort class\nUsed for browser and worker\n\n    class WorkerPort extends Port\n     constructor: (worker) ->\n      super()\n      @worker = worker\n      @worker.onmessage = @_onMessage.bind this\n      #@worker.onerror = @onCallError.bind this\n\n     _send: (data) ->\n      dd = data.data\n      if dd? and dd._transferList?\n       transferList = dd._transferList\n       delete dd._transferList\n      else\n       transferList = []\n      @worker.postMessage data, transferList\n\n     _respond: (data, options, callback) ->\n      dd = data.data\n      if dd? and dd._transferList?\n       transferList = dd._transferList\n       delete dd._transferList\n      else\n       transferList = []\n      @worker.postMessage data, transferList\n      callback?()\n\n     _onMessage: (e) ->\n      data = e.data\n      @_handleMessage data\n\n\n\n##FramePort class\nUsed for browser and worker\n\n    class FramePort extends Port\n     constructor: (source, dest) ->\n      super()\n      @source = source\n      @dest = dest\n      @source.addEventListener 'message', @_onMessage.bind this\n\n     _send: (data) ->\n      @dest.postMessage data, '*'\n\n     _respond: (data, options, callback) ->\n      @dest.postMessage data, '*'\n      callback?()\n\n     _onMessage: (e) ->\n      data = e.data\n      @_handleMessage data\n\n\n\n##SocketPort class\n\n    class SocketPort extends Port\n     constructor: (socket) ->\n      super()\n      @socket = socket\n      @socket.on 'message', @_onMessage.bind this\n\n     _send: (data) ->  @socket.emit 'message', data\n     _respond: (data, options, callback) ->\n      @worker.emit 'message', data\n      callback?()\n\n     _onMessage: (e) ->\n      data = e.data\n      @_handleMessage data\n\n\n\n##ServerSocketPort class\n\n    class ServerSocketPort extends Port\n     constructor: (server) ->\n      super()\n      @server = server\n      @server.on 'connection', @_onConnection.bind this\n\n     _onConnection: (socket) ->\n      new SocketPort handlers: @handlers, socket\n\n\n\n##AJAX class\n\n    class AjaxHttpPort extends Port\n     constructor: (options) ->\n      super()\n      @protocol = options.protocol\n      @host = options.host\n      @port = options.port\n      @path = options.path ? '\/'\n      @url = @path\n      if @protocol?\n       if @host? and not @port?\n        @url = \"#{@protocol}:\/\/#{@host}#{@path}\"\n       else if @host? and @port?\n        @url = \"#{@protocol}:\/\/#{@host}:#{@port}#{@path}\"\n      else\n       if @host? and not @port?\n        @url = \"\/\/#{@host}#{@path}\"\n       else if @host? and @port?\n        @url = \"\/\/#{@host}:#{@port}#{@path}\"\n\n     isStreaming: false\n\n     _onRequest: (xhr) ->\n      return unless xhr.readyState is 4\n      status = xhr.status\n      if ((not status and xhr.responseText? and xhr.responseText != '') or\n          (status >= 200 and status < 300) or\n          (status is 304))\n       try\n        jsonData = JSON.parse xhr.responseText\n       catch e\n        @onCallError 'ParseError', e\n        return\n\n       @_handleMessage jsonData, xhr: xhr\n      else\n       @onCallError 'Cannot connect to server'\n\n     _respond: (data, options, callback) ->\n      @errorCallback 'AJAX cannot respond', data\n      callback?()\n\n     _send: (data) ->\n      data = JSON.stringify data\n      xhr = new XMLHttpRequest\n      xhr.open 'POST', @url\n      xhr.onreadystatechange = =>\n       @_onRequest xhr\n      xhr.setRequestHeader 'Accept', 'application\/json'\n      #xhr.setRequestHeader 'Content-Type', 'application\/json'\n      xhr.send data\n\n     _handleResponse: (data, options, last = true) ->\n      for f in @wrappers.handleResponse\n       return unless f.apply this, arguments\n      if not @callsCache[data.id]?\n       @errorCallback \"Response without call: #{data.id}\", data\n       return\n      call = @callsCache[data.id]\n      try\n       if call.handle data.data, data\n        delete @callsCache[data.id]\n       else if last\n        params =\n         type: 'poll'\n         id: call.id\n        params[k] = v for k, v of call.options\n        @_send params\n      catch e\n       @errorCallback e.message, data\n       delete @callsCache[data.id]\n\n\n\n##NodeHttpPort class\n\n    class NodeHttpPort extends Port\n     constructor: (options, http) ->\n      super()\n      @host = options.host ? 'localhost'\n      @port = options.port ? 80\n      @path = options.path ? '\/'\n      @http = http\n      @_createHttpOptions()\n\n     isStreaming: false\n\n     _createHttpOptions: ->\n      @httpOptions =\n       hostname: @host\n       port: @port\n       path: @path\n       method: 'POST'\n       agent: false\n       headers:\n        accept: 'application\/json'\n       'content-type': 'application\/json'\n\n\n     _onRequest: (res) ->\n      data = ''\n      #LOG 'STATUS: ' + res.statusCode\n      #LOG 'HEADERS: ' + JSON.stringify res.headers\n      res.setEncoding 'utf8'\n      res.on 'data', (chunk) ->\n       data += chunk\n      #LOG 'result', res\n      res.on 'end', =>\n       try\n        jsonData = JSON.parse data\n       catch e\n        @onCallError 'ParseError', e\n        return\n\n       @_handleMessage jsonData, response: res\n\n     _respond: (data, options, callback) ->\n      data = JSON.stringify data\n      res = options.response\n      res.setHeader 'content-length', Buffer.byteLength data, 'utf8'\n      if callback?\n       res.once 'finish', ->\n        callback()\n       res.once 'close', ->\n        callback()\n\n      res.write data\n      res.end()\n\n     _send: (data, callbacks) ->\n      data = JSON.stringify data\n      options = @httpOptions\n      options.headers['content-length'] = Buffer.byteLength data, 'utf8'\n\n      req = @http.request options, @_onRequest.bind this\n      delete options.headers['content-length']\n      req.on 'error', (e) =>\n       try\n        callbacks.fail? e\n       catch err\n        @onerror? err\n\n      req.write data\n      req.end()\n\n     _handleResponse: (data, options, last = true) ->\n      for f in @wrappers.handleResponse\n       return unless f.apply this, arguments\n      if not @callsCache[data.id]?\n       @errorCallback \"Response without call: #{data.id}\", data\n       return\n      call = @callsCache[data.id]\n      if not call.handle data.data, data\n       return if not last\n       params =\n        type: 'poll'\n        id: call.id\n       params[k] = v for k, v of call.options\n       @_send params, call.callbacks\n\n\n\n##NodeHttpServerPort class\n\n    class NodeHttpServerPort extends Port\n     constructor: (options, http, zlib = null) ->\n      super()\n      @port = options.port\n      @http = http\n      @zlib = zlib\n      @allowOrigin = options.allowOrigin\n\n     isStreaming: false\n\n     _onRequest: (req, res) ->\n      data = ''\n      res.setHeader 'content-type', 'application\/json'\n\n      req.on 'data', (chunk) ->\n       data += chunk\n      req.on 'end', =>\n       try\n        jsonData = JSON.parse data\n       catch e\n        @errorCallback 'ParseError', e\n        return\n\n       @_handleMessage jsonData, response: res, request: req\n\n     _respond: (data, options, callback) ->\n      if @allowOrigin?\n       options.response.setHeader 'Access-Control-Allow-Origin', @allowOrigin\n\n      accept = options.request.headers['accept-encoding']\n      accept ?= ''\n      if not @zlib?\n       accept = ''\n\n      data = JSON.stringify data\n      buffer = new Buffer data, 'utf8'\n      if accept.match \/\\bgzip\\b\/\n       options.response.setHeader 'content-encoding', 'gzip'\n       @zlib.gzip buffer, (err, result) =>\n        if err?\n         return @errorCallback 'GZipeError', e\n        @_sendBuffer result, options.response, callback\n      else if accept.match \/\\bdeflate\\b\/\n       options.response.setHeader 'content-encoding', 'deflate'\n       @zlib.deflate buffer, (err, result) =>\n        if err?\n         return @errorCallback 'DeflateError', e\n        @_sendBuffer result, options.response, callback\n      else\n       @_sendBuffer buffer, options.response, callback\n\n     _sendBuffer: (buf, res, callback) ->\n       res.setHeader 'content-length', buf.length\n       if callback?\n        res.once 'finish', ->\n         callback()\n        res.once 'close', ->\n         callback()\n\n       res.write buf\n       res.end()\n\n     listen: ->\n      @server = @http.createServer @_onRequest.bind this\n      @server.listen @port\n\n     _handlePoll: (data, options) ->\n      for f in @wrappers.handleCall\n       return unless f.apply this, arguments\n      if not @responses[data.id]?\n       @onHandleError \"Poll without response: #{data.id}\", data, options\n       return\n      @responses[data.id].setOptions options\n\n##NodeHttpsServerPort class\n\n    class NodeHttpsServerPort extends NodeHttpServerPort\n     constructor: (options, http) ->\n      super options, http\n      @_key = options.key\n      @_cert = options.cert\n\n     listen: ->\n      options =\n       key: @_key\n       cert: @_cert\n\n      @server = @http.createServer options, @_onRequest.bind this\n      @server.listen @port\n\n\n#IO Module\n\n    IO =\n     addPort: (name, port) ->\n      IO[name] = port\n\n     ports:\n      WorkerPort: WorkerPort\n      FramePort: FramePort\n      SocketPort: SocketPort\n      AjaxHttpPort: AjaxHttpPort\n      NodeHttpPort: NodeHttpPort\n      NodeHttpServerPort: NodeHttpServerPort\n      NodeHttpsServerPort: NodeHttpsServerPort\n      ServerSocketPort: ServerSocketPort\n\n     Helpers:\n      progress: (from, to, func) ->\n       (progress, data) ->\n        func? progress * (to - from) + from, data\n\n     setup_____: (options) ->\n      options.workers ?= []\n      switch options.platform\n       when 'ui'\n        for worker in options.workers\n         IO.addPort worker.name, new WorkerPort worker.js\n        for socket in options.sockets\n         IO.addPort socket.name, new SocketPort socket.url\n       when 'node'\n        for socket in options.listenSockets\n         IO.addPort socket.name, new SocketListenPort socket.port\n        for socket in options.sockets\n         IO.addPort socket.name, new SocketPort socket.url\n       when 'worker'\n        IO.addPort 'UI', new WorkerListenPort _self\n\n    if exports?\n     module.exports = IO\n    else\n     _self.IO = IO\n\n","old_contents":"    _self = this\n\n    if console?.log?\n     LOG = console.log.bind console\n    else\n     LOG = -> null\n\n    if console?.error?\n     ERROR_LOG = console.error.bind console\n    else\n     ERROR_LOG = -> null\n\n\n    POLL_TYPE =\n     progress: true\n\n##Response class\n\n    class Response\n     constructor: (data, port, options) ->\n      @id = data.id\n      @port = port\n      @options = options\n      @queue = []\n      @fresh = true\n\n     progress: (progress, data, callback) ->\n      @queue.push\n       method: 'progress'\n       data: data\n       options: {progress: progress}\n       callback: callback\n      @_handleQueue()\n\n     success: (data) ->\n      @queue.push method: 'success', data: data, options: {}\n      @_handleQueue()\n\n     fail: (data) ->\n      @queue.push method: 'fail', data: data, options: {}\n      @_handleQueue()\n\n     setOptions: (options) ->\n      @options = options\n      @fresh = true\n      @_handleQueue()\n\n     _multipleResponse: ->\n      responseList = []\n      callbacks = []\n      for d in @queue\n       responseList.push\n        status: d.method\n        data: d.data\n        options: d.options\n       if d.callback?\n        callbacks.push d.callback\n\n      done = ->\n       for callback in callbacks\n        callback()\n\n      if @port.isStreaming\n       @port.respondMultiple this, responseList, @options, done\n      else if @fresh\n       @port.respondMultiple this, responseList, @options, done\n       @fresh = false\n\n      @queue = []\n\n\n     _handleQueue: ->\n      return unless @queue.length > 0\n      return if not @queue.isStreaming and not @fresh\n\n      if @queue.length > 1\n       return @_multipleResponse()\n\n\n      d = @queue[0]\n\n      if @port.isStreaming\n       @port.respond this, d.method, d.data, d.options, @options, d.callback\n      else if @fresh\n       @port.respond this, d.method, d.data, d.options, @options, d.callback\n       @fresh = false\n\n      @queue = []\n\n##Call class\n\n    class Call\n     constructor: (@id, @method, @data, @callbacks, @options, @port) -> null\n\n     handle: (data, options) ->\n      if not @callbacks[options.status]?\n       return if options.status is 'progress'\n       #Handled by caller\n       throw new Error \"No callback registered #{@method} #{options.status}\"\n      self = this\n      setTimeout ->\n       try\n        self.callbacks[options.status] data, options\n       catch e\n        if self.port.onerror?\n         self.port.onerror e\n        else\n         throw e\n      , 0\n\n      if POLL_TYPE[options.status]?\n       return false\n      else\n       return true\n\n##Port base class\n\n    class Port\n     constructor: ->\n      @handlers = {}\n      @callsCache = {}\n      @callsCounter = 0\n      @id = parseInt Math.random() * 1000\n      @responses = {}\n      @wrappers =\n       send: []\n       respond: []\n       handleCall: []\n       handleResponse: []\n\n     isStreaming: true\n\n     onCallError: (msg, options) ->\n      callsCache = @callsCache\n      @callsCache = {}\n      for id, call of callsCache\n       if not call.callbacks.fail?\n        ERROR_LOG 'fail callback not registered', call.method, call.data\n       else\n        call.callbacks.fail error: 'connectionError', msg: msg, options: options, {}\n\n      @errorCallback msg, options\n\n     onHandleError: (msg, data, options) ->\n      @errorCallback msg, data\n      response = new Response data, this, options\n      response.fail msg\n\n     errorCallback: (msg, options) ->\n      ERROR_LOG msg, options\n\n     wrap: (wrapper) ->\n      for key, f of wrapper\n       if @wrappers[key]?\n        @wrappers[key].push f\n       else\n        this[key] = f\n\n###Send RPC call\n\n     send: (method, data, callbacks, options = {}) ->\n      if (typeof callbacks) is 'function'\n       callbacks =\n        success: callbacks\n\n      for f in @wrappers.send\n       return unless f.apply this, [method, data, callbacks, options]\n\n      params = @_createCall method, data, callbacks, options\n      @_send params, callbacks\n\n###Respond to a RPC call\n\n     respond: (response, status, data, options = {}, portOptions = {}, callback = null) ->\n      if not POLL_TYPE[status]?\n       delete @responses[response.id]\n\n      for f in @wrappers.respond\n       return unless f.apply this, [response, status, data, options, portOptions]\n\n      @_respond (@_createResponse response, status, data, options), portOptions, callback\n\n     respondMultiple: (response, list, portOptions = {}, callback = null) ->\n      for d in list\n       if not POLL_TYPE[d.status]?\n        delete @responses[response.id]\n        break\n\n      data = []\n      for d in list\n       cancel = false\n       d.options ?= {}\n       for f in @wrappers.respond\n        r = f.apply this, [response, d.status, d.data, d.options, portOptions]\n        if not r\n         cancel = true\n         break\n\n        continue if cancel\n\n       data.push @_createResponse response, d.status, d.data, d.options\n\n      return if data.length is 0\n\n      data =\n       type: 'list'\n       list: data\n\n      @_respond data, portOptions, callback\n\n\n\n###Create Call object\nThis is a private function\n\n     _createCall: (method, data, callbacks, options) ->\n      call = new Call \"#{@id}-#{@callsCounter}\",\n                      method\n                      data\n                      callbacks\n                      options\n                      this\n      @callsCounter++\n      @callsCache[call.id] = call\n\n      params =\n       type: 'call'\n       id: call.id\n       method: call.method\n       data: call.data\n\n      params[k] = v for k, v of options\n      return params\n\n###Create Response object\n\n     _createResponse: (response, status, data, options) ->\n      params =\n       type: 'response'\n       id: response.id\n       status: status\n       data: data\n\n      params[k] = v for k, v of options\n\n      return params\n\n###Add handler\n\n     on: (method, callback) ->\n      @handlers[method] = callback\n\n###Handle incoming message\n\n     _handleMessage: (data, options, last = true) ->\n      switch data.type\n       when 'list'\n        for d, i in data.list\n         @_handleMessage d, options, (last and i + 1 is data.list.length)\n       when 'response'\n        try\n         @_handleResponse data, options, last\n        catch e\n         @onerror? e\n       when 'call'\n        try\n         @_handleCall data, options, last\n        catch e\n         @onerror? e\n       when 'poll'\n        try\n         @_handlePoll data, options, last\n        catch e\n         @onerror? e\n\n     _handleCall: (data, options) ->\n      for f in @wrappers.handleCall\n       return unless f.apply this, arguments\n      if not @handlers[data.method]?\n       @onHandleError \"Unknown method: #{data.method}\", data, options\n       return\n      @responses[data.id] = new Response data, this, options\n      @handlers[data.method] data.data, data, @responses[data.id]\n\n     _handleResponse: (data, options) ->\n      for f in @wrappers.handleResponse\n       return unless f.apply this, arguments\n      if not @callsCache[data.id]?\n       #Cannot reply\n       @errorCallback \"Response without call: #{data.id}\", data\n       return\n      try\n       if @callsCache[data.id].handle data.data, data\n        delete @callsCache[data.id]\n      catch e\n       @errorCallback e.message, data\n       delete @callsCache[data.id]\n\n     _handlePoll: (data, options) ->\n      @onHandleError \"Poll not implemented\", data, options\n\n##WorkerPort class\nUsed for browser and worker\n\n    class WorkerPort extends Port\n     constructor: (worker) ->\n      super()\n      @worker = worker\n      @worker.onmessage = @_onMessage.bind this\n      #@worker.onerror = @onCallError.bind this\n\n     _send: (data) ->\n      dd = data.data\n      if dd? and dd._transferList?\n       transferList = dd._transferList\n       delete dd._transferList\n      else\n       transferList = []\n      @worker.postMessage data, transferList\n\n     _respond: (data, options, callback) ->\n      dd = data.data\n      if dd? and dd._transferList?\n       transferList = dd._transferList\n       delete dd._transferList\n      else\n       transferList = []\n      @worker.postMessage data, transferList\n      callback?()\n\n     _onMessage: (e) ->\n      data = e.data\n      @_handleMessage data\n\n\n\n##FramePort class\nUsed for browser and worker\n\n    class FramePort extends Port\n     constructor: (source, dest) ->\n      super()\n      @source = source\n      @dest = dest\n      @source.addEventListener 'message', @_onMessage.bind this\n\n     _send: (data) ->\n      @dest.postMessage data, '*'\n\n     _respond: (data, options, callback) ->\n      @dest.postMessage data, '*'\n      callback?()\n\n     _onMessage: (e) ->\n      data = e.data\n      @_handleMessage data\n\n\n\n##SocketPort class\n\n    class SocketPort extends Port\n     constructor: (socket) ->\n      super()\n      @socket = socket\n      @socket.on 'message', @_onMessage.bind this\n\n     _send: (data) ->  @socket.emit 'message', data\n     _respond: (data, options, callback) ->\n      @worker.emit 'message', data\n      callback?()\n\n     _onMessage: (e) ->\n      data = e.data\n      @_handleMessage data\n\n\n\n##ServerSocketPort class\n\n    class ServerSocketPort extends Port\n     constructor: (server) ->\n      super()\n      @server = server\n      @server.on 'connection', @_onConnection.bind this\n\n     _onConnection: (socket) ->\n      new SocketPort handlers: @handlers, socket\n\n\n\n##AJAX class\n\n    class AjaxHttpPort extends Port\n     constructor: (options) ->\n      super()\n      @protocol = options.protocol\n      @host = options.host\n      @port = options.port\n      @path = options.path ? '\/'\n      @url = @path\n      if @protocol?\n       if @host? and not @port?\n        @url = \"#{@protocol}:\/\/#{@host}#{@path}\"\n       else if @host? and @port?\n        @url = \"#{@protocol}:\/\/#{@host}:#{@port}#{@path}\"\n      else\n       if @host? and not @port?\n        @url = \"\/\/#{@host}#{@path}\"\n       else if @host? and @port?\n        @url = \"\/\/#{@host}:#{@port}#{@path}\"\n\n     isStreaming: false\n\n     _onRequest: (xhr) ->\n      return unless xhr.readyState is 4\n      status = xhr.status\n      if ((not status and xhr.responseText? and xhr.responseText != '') or\n          (status >= 200 and status < 300) or\n          (status is 304))\n       try\n        jsonData = JSON.parse xhr.responseText\n       catch e\n        @onCallError 'ParseError', e\n        return\n\n       @_handleMessage jsonData, xhr: xhr\n      else\n       @onCallError 'Cannot connect to server'\n\n     _respond: (data, options, callback) ->\n      @errorCallback 'AJAX cannot respond', data\n      callback?()\n\n     _send: (data) ->\n      data = JSON.stringify data\n      xhr = new XMLHttpRequest\n      xhr.open 'POST', @url\n      xhr.onreadystatechange = =>\n       @_onRequest xhr\n      xhr.setRequestHeader 'Accept', 'application\/json'\n      #xhr.setRequestHeader 'Content-Type', 'application\/json'\n      xhr.send data\n\n     _handleResponse: (data, options, last = true) ->\n      for f in @wrappers.handleResponse\n       return unless f.apply this, arguments\n      if not @callsCache[data.id]?\n       @errorCallback \"Response without call: #{data.id}\", data\n       return\n      call = @callsCache[data.id]\n      try\n       if call.handle data.data, data\n        delete @callsCache[data.id]\n       else if last\n        params =\n         type: 'poll'\n         id: call.id\n        params[k] = v for k, v of call.options\n        @_send params\n      catch e\n       @errorCallback e.message, data\n       delete @callsCache[data.id]\n\n\n\n##NodeHttpPort class\n\n    class NodeHttpPort extends Port\n     constructor: (options, http) ->\n      super()\n      @host = options.host ? 'localhost'\n      @port = options.port ? 80\n      @path = options.path ? '\/'\n      @http = http\n      @_createHttpOptions()\n\n     isStreaming: false\n\n     _createHttpOptions: ->\n      @httpOptions =\n       hostname: @host\n       port: @port\n       path: @path\n       method: 'POST'\n       agent: false\n       headers:\n        accept: 'application\/json'\n       'content-type': 'application\/json'\n\n\n     _onRequest: (res) ->\n      data = ''\n      #LOG 'STATUS: ' + res.statusCode\n      #LOG 'HEADERS: ' + JSON.stringify res.headers\n      res.setEncoding 'utf8'\n      res.on 'data', (chunk) ->\n       data += chunk\n      #LOG 'result', res\n      res.on 'end', =>\n       try\n        jsonData = JSON.parse data\n       catch e\n        @onCallError 'ParseError', e\n        return\n\n       @_handleMessage jsonData, response: res\n\n     _respond: (data, options, callback) ->\n      data = JSON.stringify data\n      res = options.response\n      res.setHeader 'content-length', Buffer.byteLength data, 'utf8'\n      if callback?\n       res.once 'finish', ->\n        callback()\n       res.once 'close', ->\n        callback()\n\n      res.write data\n      res.end()\n\n     _send: (data, callbacks) ->\n      data = JSON.stringify data\n      options = @httpOptions\n      options.headers['content-length'] = Buffer.byteLength data, 'utf8'\n\n      req = @http.request options, @_onRequest.bind this\n      delete options.headers['content-length']\n      req.on 'error', (e) =>\n       try\n        callbacks.fail? e\n       catch err\n        @onerror? err\n\n      req.write data\n      req.end()\n\n     _handleResponse: (data, options, last = true) ->\n      for f in @wrappers.handleResponse\n       return unless f.apply this, arguments\n      if not @callsCache[data.id]?\n       @errorCallback \"Response without call: #{data.id}\", data\n       return\n      call = @callsCache[data.id]\n      if not call.handle data.data, data\n       return if not last\n       params =\n        type: 'poll'\n        id: call.id\n       params[k] = v for k, v of call.options\n       @_send params, call.callbacks\n\n\n\n##NodeHttpServerPort class\n\n    class NodeHttpServerPort extends Port\n     constructor: (options, http, zlib = null) ->\n      super()\n      @port = options.port\n      @http = http\n      @zlib = zlib\n      @allowOrigin = options.allowOrigin\n\n     isStreaming: false\n\n     _onRequest: (req, res) ->\n      data = ''\n      res.setHeader 'content-type', 'application\/json'\n\n      req.on 'data', (chunk) ->\n       data += chunk\n      req.on 'end', =>\n       try\n        jsonData = JSON.parse data\n       catch e\n        @errorCallback 'ParseError', e\n        return\n\n       @_handleMessage jsonData, response: res, request: req\n\n     _respond: (data, options, callback) ->\n      if @allowOrigin?\n       options.response.setHeader 'Access-Control-Allow-Origin', @allowOrigin\n\n      accept = options.request.headers['accept-encoding']\n      accept ?= ''\n      if not @zlib?\n       accept = ''\n\n      data = JSON.stringify data\n      buffer = new Buffer data, 'utf8'\n      if accept.match \/\\bgzip\\b\/\n       options.response.setHeader 'content-encoding', 'gzip'\n       @zlib.gzip buffer, (err, result) =>\n        if err?\n         return @errorCallback 'GZipeError', e\n        @_sendBuffer result, options.response, callback\n      else if accept.match \/\\bdeflate\\b\/\n       options.response.setHeader 'content-encoding', 'deflate'\n       @zlib.deflate buffer, (err, result) =>\n        if err?\n         return @errorCallback 'DeflateError', e\n        @_sendBuffer result, options.response, callback\n      else\n       @_sendBuffer buffer, options.response, callback\n\n     _sendBuffer: (buf, res, callback) ->\n       res.setHeader 'content-length', buf.length\n       if callback?\n        res.once 'finish', ->\n         callback()\n        res.once 'close', ->\n         callback()\n\n       res.write buf\n       res.end()\n\n     listen: ->\n      @server = @http.createServer @_onRequest.bind this\n      @server.listen @port\n\n     _handlePoll: (data, options) ->\n      for f in @wrappers.handleCall\n       return unless f.apply this, arguments\n      if not @responses[data.id]?\n       @onHandleError \"Poll without response: #{data.id}\", data, options\n       return\n      @responses[data.id].setOptions options\n\n##NodeHttpsServerPort class\n\n    class NodeHttpsServerPort extends NodeHttpServerPort\n     constructor: (options, http) ->\n      super options, http\n      @_key = options.key\n      @_cert = options.cert\n\n     listen: ->\n      options =\n       key: @_key\n       cert: @_cert\n\n      @server = @http.createServer options, @_onRequest.bind this\n      @server.listen @port\n\n\n#IO Module\n\n    IO =\n     addPort: (name, port) ->\n      IO[name] = port\n\n     ports:\n      WorkerPort: WorkerPort\n      FramePort: FramePort\n      SocketPort: SocketPort\n      AjaxHttpPort: AjaxHttpPort\n      NodeHttpPort: NodeHttpPort\n      NodeHttpServerPort: NodeHttpServerPort\n      NodeHttpsServerPort: NodeHttpsServerPort\n      ServerSocketPort: ServerSocketPort\n\n     Helpers:\n      progress: (from, to, func) ->\n       (progress, data) ->\n        func? progress * (to - from) + from, data\n\n     setup_____: (options) ->\n      options.workers ?= []\n      switch options.platform\n       when 'ui'\n        for worker in options.workers\n         IO.addPort worker.name, new WorkerPort worker.js\n        for socket in options.sockets\n         IO.addPort socket.name, new SocketPort socket.url\n       when 'node'\n        for socket in options.listenSockets\n         IO.addPort socket.name, new SocketListenPort socket.port\n        for socket in options.sockets\n         IO.addPort socket.name, new SocketPort socket.url\n       when 'worker'\n        IO.addPort 'UI', new WorkerListenPort _self\n\n    if exports?\n     module.exports = IO\n    else\n     _self.IO = IO\n\n","returncode":0,"stderr":"","license":"mit","lang":"Literate CoffeeScript"}
{"commit":"abde9d573debd3a17dbcfe6b9fca825a83c560af","subject":"move how-to into guides, add listing, document data-track and data-debug","message":"move how-to into guides, add listing, document data-track and data-debug\n","repos":"getshuvo\/batman,getshuvo\/batman","old_file":"docs\/14_bindings.litcoffee","new_file":"docs\/14_bindings.litcoffee","new_contents":"# \/api\/App Components\/Batman.View\/Batman.View Bindings\n\nSee the [guide](\/docs\/bindings.html) for an overview of view bindings. All bindings take a keypath as an attribute value unless otherwise specified.\n\nBinding | Description | Example\n-----|----|----\n`data-bind`| Binds `innerHTML` or input value. Great for all kinds of inputs. | ``\n`data-bind-#{attr}`| Binds node's `attr` to the keypath | `data-bind-id='post.id'`\n`data-source`| `innerHTML` or value will get value from the keypath, but not set it | `

<\/p>`\n`data-source-#{attr}`| Node's `attr` will get its value from the keypath | `

<\/h1>`\n`data-target`| Changes to the node will set the keypath, but not get from the keypath |``\n`data-context-#{name}`| Makes keypath value accessible as `name` inside node | `data-context-lastcomment='mostRecentPost.comments.last'`\n`data-context`| Makes attributes of keypath directly accessible inside node|\n`data-showif`| Shows node if keypath returns truthy | `data-showif='user.isAuthorized'`\n`data-hideif`| Hides node if keypath returns truthy | `data-hideif='post.alreadyPublished'`\n`data-insertif`| The node will be present in the DOM if the keypath returns truthy | `data-insertif='post.isPublished'`\n`data-removeif`| The node will be removed from the DOM if the keypath returns truthy | `data-removeif='comment.isNotAppropriate'`\n`data-renderif`| Node's contents will only be rendered if the keypath returns truthy |\n`data-deferif`| Node's contents will only be rendered if the keypath returns falsey|\n`data-route`| Takes a `Batman.NamedRouteQuery`. Clicking this node will route to the keypath. | `data-route='routes.posts[post].edit'`\n`data-route-params` | Appends the keypath the route generated by a `data-route` on the node | `data-route-params='myParamString'\n`data-view`| Wraps the node in the view specified | `data-view='NavigatorView'`\n`data-view-#{optionName}`| Passes keypath value to `data-view` as `optionName` (see `View.option`) | `data-view-user='currentUser'`\n`data-partial`| Takes a __string__, renders the template with that path | `data-partial='posts\/_form'`\n`data-defineview`| Wraps HTML which should be stored by `Batman.View` | `data-defineview='posts\/index'`\n`data-yield`| Creates a named yield for the application | `data-yield='modal'`\n`data-contentfor`| Wraps content for a non-default yield | `data-contentfor='modal'`\n`data-debug`| Calls `debugger` when instantiating the binding | `data-debug=\"true\"`\n`data-event-#{eventName}`| Binds keypath value to `eventName` on this node | `data-event-click='notifyAllUsers'`\n`data-addclass-#{className}`| Adds class `className` if keypath returns truthy | `data-addclass-selected='item.selected'`\n`data-removeclass-#{className}`| Removes class `className` if keypath returns truthy | `data-removeclass-highlight='item.isPast'`\n`data-foreach-#{itemName}`| Make a copy of this node for each member in keypath; children accessible as `itemName` | `data-foreach-item='myCollection'`\n`data-formfor-#{name}`| Inputs for keypath value will observe errors; keypath value aliased as `name`| `data-formfor-comment='newComment'`\n`data-style-#{styleAttrName}`| Bind the node's style attribute `styleAttrName` to the keypath value| `data-style-float='leftOrRight'`\n`data-track-#{clickOrView}`| Track clicks or views on this node. | `data-track-view='logView'`\n\n\n#### Available Keypath Filters\n\nThe following is a list of available keypaths that can be used with bindings. For a more complete description with accompanying examples see `Batman.View Filters`\n + `lt` : Checks if left content is _less than_ the right content.\n + `gt` : Checks if left content is _greater than_ the right content.\n + `lteq` : Checks if left content is _less than or equal to_ the right content.\n + `gteq` : Checks if left content is _greater than or equal to_ the right content.\n + `equal` or `eq` : Checks if left content is _is equal to_ the right content.\n + `neq` : Checks if left content is _is NOT equal to_ the right content.\n + `ceil` : Runs `Math.ceil` on input value.\n + `floor` : Runs `Math.floor` on input value.\n + `round` : Runs `Math.round` on input value.\n + `precision` : Runs `toPrecision()` on input value.\n + `fixed` : Runs `toFixed()` on input value.\n + `delimitNumber` : Adds comma delimiters to a number\n\n## data-bind\n\n`data-bind` creates a two way binding between a property on a `Batman.Object` and an HTML element. Bindings created via `data-bind` will update the HTML element with the value of the JS land property as soon as they are created and each time the property changes after, and if the HTML element can be observed for changes, it will update the JS land property with the value from the HTML.\n\n`data-bind` will change its behaviour depending on what kind of tag it is attached to:\n\n + ``: the binding will edit the `checked` property of the checkbox and populate the keypath with a boolean.\n + `` and similar, `: the binding will edit the `value` property of the input and populate the keypath with the string found at `value`.\n + ``: the binding will _not_ edit the `value` property of the input, but it will update the keypath with a host `File` object or objects if the node has the `multiple` attribute.\n + `` matching the property at the keypath. If the `\n```\n\n_Note_: `data-bind` will not update a JavaScript property if filters are used in the keypath.\n\n## data-source\n\n`data-source` creates a one way binding which propagates only changes from JavaScript land to the DOM, and never vice versa. `data-source` has the same semantics with regards to how it operates on different tags as `data-bind`, but it will only ever update the DOM and never the JavaScript land property.\n\nFor example, the HTML below will never update the `title` property on the product, even if the user changes it. Each time the `title` attribute changes from a `set` in JavaScript land, the value of the input will be updated to the new value of `title`, erasing any potential changes that have been made to the value of the input by the user.\n\n```html\n\n```\n\n_Note_: `data-source-attribute` is equivalent to `data-bind-attribute`, since the former is defined as never making JS land changes, and the latter is unable to.\n\n## data-target\n\n`data-target` creates a one way binding which propagates only changes from the DOM to JavaScript land, and never vice versa. `data-target` has the same semantics with regards to how it operates on different tags as `data-bind`, but it will never update the DOM even if the JavaScript land value changes.\n\n_Note_: `data-target-attribute` is unavailable, because DOM changes to node attributes can't be monitored.\n\n\n## data-showif \/ data-hideif\n\n`data-showif` and `data-hideif` bind to keypaths and show or hide the node they appear on based on the truthiness of the result. `data-showif` will show a node if the given keypath evaluates to something truthy, and `data-hideif` will leave a node visible until its given keypath becomes truthy, at which point the node will be hidden. `data-showif` and `data-hideif` show and hide nodes by adding `display: none !important;` to the node's `style` attribute.\n\nFor example, if the HTML below is rendered where the keypath `product.published` evaluated to true, the `