[
  {
    "path": ".gitignore",
    "content": "/node_modules\nnpm-debug.log\n.idea/\n/TAGS\n"
  },
  {
    "path": ".jshintrc",
    "content": "{\n    \"bitwise\"       : true,     // Prohibit bitwise operators (&, |, ^, etc.).\n    \"forin\"         : true,     // Tolerate `for in` loops without `hasOwnPrototype`.\n    \"immed\"         : true,     // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`\n    \"latedef\"       : true,     // Prohibit variable use before definition.\n    \"eqeqeq\"        : true,     // Require ===\n    \"newcap\"        : true,     // Require capitalization of all constructor functions e.g. `new F()`.\n    \"noempty\"       : true,     // Prohibit use of empty blocks.\n    \"nonew\"         : true,     // Prohibit use of constructors for side-effects.\n    \"regexp\"        : true,     // Prohibit `.` and `[^...]` in regular expressions.\n    \"undef\"         : true,     // Require all non-global variables be declared before they are used.\n    \"strict\"        : true,     // Require `use strict` pragma in every file.\n    \"trailing\"      : true,     // Prohibit trailing whitespaces.\n    \"asi\"           : true,     // Tolerate Automatic Semicolon Insertion (no semicolons).\n    \"boss\"          : false,    // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.\n    \"debug\"         : false,    // Allow debugger statements e.g. browser breakpoints.\n    \"eqnull\"        : true,    // Tolerate use of `== null`.\n    \"es5\"           : false,    // Allow EcmaScript 5 syntax.\n    \"esnext\"        : false,    // Allow ES.next specific features such as `const` and `let`.\n    \"evil\"          : false,    // Tolerate use of `eval`.\n    \"expr\"          : false,    // Tolerate `ExpressionStatement` as Programs.\n    \"funcscope\"     : false,    // Tolerate declarations of variables inside of control structures while accessing them later from the outside.\n    \"globalstrict\"  : false,    // Allow global \"use strict\" (also enables 'strict').\n    \"iterator\"      : false,    // Allow usage of __iterator__ property.\n    \"lastsemic\"     : false,    // Tolerat missing semicolons when the it is omitted for the last statement in a one-line block.\n    \"laxbreak\"      : false,    // Tolerate unsafe line breaks e.g. `return [\\n] x` without semicolons.\n    \"laxcomma\"      : false,    // Suppress warnings about comma-first coding style.\n    \"loopfunc\"      : false,    // Allow functions to be defined within loops.\n    \"multistr\"      : false,    // Tolerate multi-line strings.\n    \"onecase\"       : false,    // Tolerate switches with just one case.\n    \"proto\"         : false,    // Tolerate __proto__ property. This property is deprecated.\n    \"regexdash\"     : false,    // Tolerate unescaped last dash i.e. `[-...]`.\n    \"scripturl\"     : false,    // Tolerate script-targeted URLs.\n    \"smarttabs\"     : false,    // Tolerate mixed tabs and spaces when the latter are used for alignmnent only.\n    \"shadow\"        : false,    // Allows re-define variables later in code e.g. `var x=1; x=2;`.\n    \"sub\"           : false,    // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.\n    \"supernew\"      : false,    // Tolerate `new function () { ... };` and `new Object;`.\n    \"validthis\"     : false,    // Tolerate strict violations when the code is running in strict mode and you use this in a non-constructor function.\n    \"devel\"         : false,    // Allow development statements e.g. `console.log();`.\n    \"node\"          : true,     // Enable globals available when code is running inside of the NodeJS runtime environment.\n    \"nonstandard\"   : false,    // Define non-standard but widely adopted globals such as escape and unescape.\n\n    \"maxerr\"        : 100,      // Maximum errors before stopping.\n    \"indent\"        : 2,        // Specify indentation spacing\n    \"laxcomma\"      : true,     // tolerate comma first coding style\n\n    \"globals\"       : {         // Jasmine globals for spec files\n         \"afterEach\": false,\n         \"beforeEach\": false,\n         \"confirm\": false,\n         \"context\": false,\n         \"describe\": false,\n         \"expect\": false,\n         \"it\": false,\n         \"xit\": false,\n         \"jasmine\": false,\n         \"JSHINT\": false,\n         \"mostRecentAjaxRequest\": false,\n         \"qq\": false,\n         \"runs\": false,\n         \"spyOn\": false,\n         \"spyOnEvent\": false,\n         \"waitsFor\": false,\n         \"xdescribe\": false\n      }\n}\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nsudo: false\nnode_js:\n  - node\n  - lts/*\nscript: make\nnotifications:\n  webhooks:\n    urls:\n      - https://webhooks.gitter.im/e/30d8496b867bc082157a\n    on_success: change  # options: [always|never|change] default: always\n    on_failure: always  # options: [always|never|change] default: always\n    on_start: never     # options: [always|never|change] default: always\n\n"
  },
  {
    "path": "Makefile",
    "content": ".PHONY: test hint default\nCURRENT_BRANCH=$(shell git rev-parse --abbrev-ref HEAD)\n\ndefault: bootstrap hint test\n\nbootstrap:\n\tnpm install\n\ntest:\n\t./node_modules/.bin/jasmine-node --captureExceptions spec\n\tcd test && ./bin_test.sh\n\nhint:\n\t./node_modules/.bin/jshint bin/canned index.js lib/ spec/\n\nrelease: docs\n\t@read -p \"Version to release: \" version; \\\n\tgit tag -a $$version -m \"version $$version release\"\n\tgit push --tags\n\tnpm publish\n\ndocs:\n\t@git stash\n\t@git checkout gh-pages\n\t@git checkout master -- README.md\n\t@echo \"---\\nlayout: index\\n---\" | cat - README.md > index.md\n\t@git reset README.md\n\t@rm README.md\n\t@git add index.md\n\t-git commit -m \"updated docs\"\n\t-git push origin gh-pages\n\t@git checkout ${CURRENT_BRANCH}\n\t-@git stash apply\n"
  },
  {
    "path": "README.md",
    "content": "Canned fake API server\n======================\n\n[![Build Status](https://travis-ci.org/sideshowcoder/canned.png?branch=master)](https://travis-ci.org/sideshowcoder/canned)\n[![Code Climate](https://codeclimate.com/github/sideshowcoder/canned.png)](https://codeclimate.com/github/sideshowcoder/canned)\n[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sideshowcoder/canned?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)\n\nView the docs on [Docs](http://sideshowcoder.github.io/canned), and join the\nchat at [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sideshowcoder/canned?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)\n\nWorking with APIs, more often than not, during development you want to work\nwith a fixed version of the responses provided. This is especially true if the\nAPI is still under development, and maybe even still needs input on how to\noutput something. This is what Canned is for!\n\nWhat does it do?\n----------------\n\nCanned maps a folder structure to API responses. Given the following directory\nstructure:\n\n    /content/index.get.html\n    /comment/any.get.json\n    /comment/1/votes/index.get.json\n    /comment/any/votes/index.get.json\n\nrequests like\n\n    Accept: application/json\n    GET /comment/:id\n\nare served from the file `/comment/any.get.json` as\n\n    Content-Type: application/json\n    { \"content\": \"I am a comment\", \"author\": \"sideshowcoder\" }\n\nrequests like\n\n    Accept: text/html\n    GET /content/\n\nare served from the file `/content/index.get.html` as\n\n    Content-Type: text/html\n    <html>\n      <body>Some html in here</body>\n    </html>\n\n\nrequests like\n\n    Accept: application/json\n    GET /comment/1/votes\n\nare served from the file `/comment/1/index.get.json` as\n\n    Content-Type: application/json\n    { \"content\": \"I am comment 1\", \"author\": \"sideshowcoder\" }\n\nrequests like\n\n    Accept: application/json\n    GET /comment/123456789/votes\n\nare served from the file `/comment/any/index.get.json`\n\n    Content-Type: application/json\n    { \"content\": \"I am a wildcard comment for any id\", \"author\": \"sideshowcoder\" }\n\nThe matching works on the filename by treating it as `PATH.VERB.CONTENT_TYPE` so\n`index.get.json` has the path `index` the verb is `get` and the content-type\n`json`. Supported content types are\n\n```\njson   => application/json\nhtml   => text/html\ntxt    => text/plain\njs     => application/javascript\ncsv    => text/csv\n// linked-data formats:\nnt     => application/n-triples\njsonld => application/ld+json\n```\n\nSo an example is for querying (with canned running on localhost:3000)\n\n```\n$ curl -H \"Accept: text/javascript\" http://localhost:3000/comment/1\n> { \"content\": \"I am a comment\", \"author\": \"sideshowcoder\" }\n```\n\nAwesome! so what is supported?\n------------------------------\nCurrently Canned supports the basic REST-API mapping, as well as custom method\nmapping with nested endpoints.\n\n    file                            | resquest\n    /index.get.json                 | GET /\n    /any.get.json                   | GET /:id\n    /_search.get.json               | GET /search\n    /comments/index.get.json        | GET /comments/\n    /comments/any.get.json          | GET /comments/:id\n    /comments/_search.get.json      | GET /comments/search\n    /comments/any/index.get.json    | GET /comments/:id/\n\nYou can even add query parameters to your filenames to return different\nresponses on the same route. If the all query params in a filename match the\nincoming request, this file will be returned. It will fall back to returning the\nfile with no query params if it exists.\n\n*Warning this will be deprecated in the future since canned now supports\nmultiple response based on the request body or GET URL parameters in one file.\nThis is the preferred way since files with ? in the name do not work on Windows*\n\n    file                            | resquest\n    /index?name=Superman.get.json   | GET /?name=Superman&NotAllParams=NeedToMatch\n    /_search?q=hello.get.json       | GET /comments/search?q=hello\n    /_search.get.json               | GET /comments/search?iam=soignored\n\nSame support is available for PUT, POST, etc.\n\n    /index.post.json            | POST serves /... + CORS Headers\n    /index.put.json             | PUT serves /... + CORS Headers\n\nIf CORS support is enabled additionally options will be available as a http verb\nand all requests will serve the CORS Headers as well\n\n    /                           | OPTIONS serve all the options needed for CORS\n    /index.get.json             | GET serves /... + CORS Headers\n\nIf you need some custom return codes, just add them to the file via adding a\nfile header like so\n\n    //! statusCode: 201\n    <html>\n      <body>Created something successfully! Happy!</body>\n    </html>\n\nThe header will be stripped before sending and the statusCode will be set.\n\nYou can also override the default content types by adding a custom content type to the file header:\n\n    //! contentType: \"application/vnd.custom+xml\"\n    <xml>\n        <created>1</created>\n    </xml>\n\nThis will be returned with a `Content-type: application/vnd.custom+xml` header.\n\nMultiple headers need to be written on one single line and comma-separated, like so:\n\n    //! statusCode: 201, contentType: \"application/vnd.custom+xml\"\n\nIf you need to send bind custom HTTP headers to the response you can add them as headers to the response file using\n the keyword `customHeader`:\n\n    //! customHeader: {\"MyCustomHeaderName\": \"MyCustomHeaderValue\"}\n\nIn case you need more then one custom header in the response, you can just use the same keyword multiple times:\n\n    //! customHeader: {\"MyCustomHeaderName\": \"MyCustomHeaderValue\"}\n    //! customHeader: {\"SecondHeaderName\": \"SecondHeaderValue\"}\n\nVariable responses\n------------------\nYou can get a different response by specifying request data in variant\ncomments. If the request data matches the comment data the matching response is\nreturned. If there is no match the first response is returned\n\n*Note: comments must be on a single line*\n\nCustom headers:\n\n    //! header: {\"authorization\": \"abc\"}\n    {\n        \"response\": \"response for abc\"\n    }\n\n    //! header: {\"authorization\": \"123\"}\n    {\n        \"response\": \"response for 123\"\n    }\n\nIf you need different responses based on request body then you can specify the\nrequest you want matched via body comments:\n\n    //! body: {\"email\": \"one@example.com\"}\n    {\n        \"response\": \"response for one@example.com\"\n    }\n\n    //! body: {\"email\": \"two@example.com\"}\n    {\n        \"response\": \"response for two@example.com\"\n    }\n\nIf you need different responses based on request parameters then you can specify\nthem via parameters comments:\n\n    //! params: {\"foo\": \"bar\"}\n    {\n        \"response\": \"response for bar\"\n    }\n\n    //! params: {\"foo\": \"baz\"}\n    {\n        \"response\": \"response for baz\"\n    }\n\nthis would match `http://my.local.server/my_get_request_path?foo=bar` or\n`http://my.local.server/my_get_request_path?foo=baz` respectively.\n\nTo use in conjunction with response headers and status codes, just add them on\nthe line above.\n\n\t//! statusCode: 201\n\t//! header: {\"authorization\": \"abc\"}\n\t{\n\t    \"response\": \"response for abc\"\n\t}\n\n  \t//! statusCode: 201, contentType: \"application/my-personal-json\"\n\t//! header: {\"authorization\": \"123\"}\n\t{\n\t    \"response\": \"response for 123\"\n\t}\n\nWildcard responses are also supported, very useful to have 'wildcard'\ndirectories, so that if for given a request like:\n\n  \tGET /api/users/1/profile/\n\nyou don't have a file in `./canned/api/users/1/profile/index.get.json` then\nit would look for a file in `./canned/api/users/any/index.get.json` or\nsimilar. Wildcards can be specified on the command line via\n\n  \tcanned --wildcard myany\n\nThis would change the lookup to `./canned/api/users/myany/index.get.json`\n\nHow about some docs inside for the responses?\n---------------------------------------------\nMost content types support comments natively, like html or javascript. Sadly the\nprobably most used type (JSON) does not :(. So canned actually extends the JSON\nsyntax a little so it can include comments with _//_ or _/**/_. In case you use\nthe JSON files directly on the backend side as test cases make sure you strip\nthose out as well!\n\n\nOk I need this!\n---------------\nJust install via npm\n\n    $ npm install canned\n\nwhich will install it locally in node\\_modules, if you want to have it\navailable from anywhere just install globally\n\n    $ npm install -g canned\n\nHow do I use it\n---------------\nThere are 2 ways here, either you embed it somewhere programmatically\n\n    var canned = require('canned')\n    ,   http = require('http')\n    ,   opts = { logger: process.stdout }\n\n    can = canned('/path/to/canned/response/folder', opts)\n\n    http.createServer(can).listen(3000)\n\nOr just run the provided canned server script\n\n    $ canned\n\nWhich serves the current folder with canned responses on port 3000\n\n    $ canned -p 5000 ./my/responses/\n\nwill serve the relative folder via port 5000\n\nIf you need canned to respond with some delay, pass delay in ms to `response_delay` arg\n\n    $ canned --response_delay=1000 ./my/reponses/\n\nIf you want canned to iterate through all accepted content types in the `Accept` header, use\n\n    $ canned --relaxed_accept=true ./my/reponses/\n\nIf for whatever reason you want to turn of CORS support do so via\n\n    $ canned --cors=false ./my/responses/\n\nAlso if you need additional headers to be served alongside the CORS headers\nthese can be added like this (thanks to runemadsen)\n\n    $ canned --headers \"Authorization, Another-Header\"\n\nTo enable CORS programmatically, you can use the following options:\n\n    var canned = require('canned')\n    ,   http = require('http')\n    ,   opts = {\n            cors: true,\n            cors_headers: [\"Content-Type\", \"Location\"]\n        }\n\nOptionally, the cors_headers value can be a comma-separated string, as per the CLI option.\n\nOther optional options include:\n    \n    var opts = {\n            sanitize: false, // get responses as is without any sanitization\n            response_delay: 2000, // delay the response for 2 seconds\n            relaxed_accept: true // iterate through all accepted content types in the `Accept` header\n            wildcard: 'myany', // specify 'wildcard' directory, e.g. ./canned/api/users/myany/index.get.json\n        }\n\nFor more information checkout [the pull request](https://github.com/sideshowcoder/canned/pull/9)\n\nAlready using grunt? [Great there is a plugin for that,](https://github.com/jkjustjoshing/grunt-canned)\nthanks to jkjustjoshing.\n\n\nIt does not work :(\n-------------------\n\n### canned not found\nmake sure you either install globally or put ./node\\_modules/.bin in your PATH\n\n### it is still not found, and I installed globally\nmake sure /usr/local/share/npm/bin is in your path, this should be true for\nevery install since you won't be able to run any global module bins if not.\n(like express, and such)\n\n### the encoding looks wrong\nmake sure you run a version of node which is 0.10.3 or higher, because it fixes\na problem for the encoding handling when reading files\n\n### My JSON request body is not matching any responses\nSet the \"Content-Type\" header to contain \"application/json\".\n\nHow to Contribute\n-----------------\n* Checkout the repository\n* Run the tests and jshint\n    ```$ make```\n* Create a topic branch\n    ```$ git checkout -b my-new-feature```\n* Code test and make jshint happy!\n    ```$ make test```\n    ```$ make hint```\n* Push the branch and create a Pull-Request\n\nI try to review the pull requests as quickly as possible, should it take to long\nfeel free to [bug me on twitter](https://twitter.com/ischi)\n\nRelease History\n---------------\n### next\n* adding PATCH to default Access-Control-Allow-Method Cors header #113 (@william-mcmillian)\n* adding support for delayed responses #114 (@Onatolich)\n* adding support to make sanatize optional #115 (@YuliyaMarholina)\n\n### 0.3.10\n* Windows line ending support #102 (@antxxxx)\n* cleanup and documentation #95 (@wadtech)\n* customHeader handling #110 (@mazoni)\n\n### 0.3.9\n* relaxed handling for accept headers, meaning select the first result that can be \n  served even if it is not the first accepted content type. option \n`--relaxed-accept` #100 (@CheungJ)\n\n### 0.3.8\n* fix improper handling of carriage return in windows #79 (@git-jiby-me)\n* fix handling for urls in request body #90 (@wadtech)\n* documentation and test cases for cors headers #91 (@wadtech)\n* enable matching raw request body rather than property-based #96 (@ftes)\n* fix query string param handling #97 (@wadtech @targoo)\n\n### 0.3.7\n* The regex for matching request, was not considering arrays in the request JSON\n  #82\n* For request with a request body, canned was checking content type to exactly\n  match application/json, which is not good as browsers may sent charset as well\n  with the content type. #82\n* For matching request and filters with more accuracy, we were converting the\n  values of all keys in request to string before comparing, but this was being\n  done wrong as it was creating string of Objects and arrays as well, which it\n  shouldn’t #82\n\n### 0.3.6\n* support checking the `ACCEPT HEADER` for the response type (thanks git-jiby-me) #81\n\n### 0.3.5\n* support for custom HTTP headers in responses\n* fix for matching multiple parameters in response #73 thanks\n  [xdemocle](https://github.com/xdemocle)\n* fix any wildcard in the middle of the path #66 thanks\n  [msurdi](https://github.com/msurdi)\n\n### 0.3.4\n* update dependencies and dev-dependencies\n* wildcard parameters thanks to [msurdi](https://github.com/msurdi) see\n  https://github.com/sideshowcoder/canned/pull/64\n\n### 0.3.3\n* fix support for special characters in the header / params / body matches\n  (@simonprickett, @kevinschumacher, @sideshowcoder)\n* support differet statusCodes and content types in multiple response files\n  (@sideshowcoder)\n\n### 0.3.2\n* support for XML headers to support SOAP (@vikalp)\n* fix relative path again... (@sideshowcoder)\n\n### 0.3.1\n* fixes for variable responses with JSON body (@bibounde)\n* fixes for relative paths on start (@sideshowcoder)\n* complex get parameters causing regexp match on file to fail (@sideshowcoder)\n\n### 0.3\n* support for multiple responses per file (@hungrydavid)\n* support for GET responses without the need for special characters in the\n  filename (@sideshowcoder based on the work by @hungrydavid)\n\n### 0.2.3\n* added support for empty response with 204 for no content (@jkjustjoshing)\n\n### everything before\n* sorry haven't kept a version history, yet. Will now!\n\nContributors\n------------\n* [sideshowcoder](https://github.com/sideshowcoder)\n* [leifg](https://github.com/leifg)\n* [runemadsen](https://github.com/runemadsen)\n* [mulderp](https://github.com/mulderp)\n* [creynders](https://github.com/creynders)\n* [jkjustjoshing](https://github.com/jkjustjoshing)\n* [hungrydavid](https://github.com/hungrydavid)\n* [bibounde](https://github.com/bibounde)\n* [vikalp](https://github.com/vikalp)\n* [simonprickett](https://github.com/simonprickett)\n* [kevinschumacher](https://github.com/kevinschumacher)\n* [msurdi](https://github.com/msurdi)\n* [Brendan Rius](https://github.com/brendan-rius)\n* [Rocco Russo](https://github.com/xdemocle)\n* [git-jiby-me](https://github.com/git-jiby-me)\n* [wadtech](https://github.com/wadtech)\n* [ftes](https://github.com/ftes)\n* [targoo](https://github.com/targoo)\n* [CheungJ](https://github.com/CheungJ)\n* [antxxxx](https://github.com/antxxxx)\n* [mazoni](https://github.com/mazoni)\n* [william-mcmillian](https://github.com/william-mcmillian)\n* [Onatolich](https://github.com/Onatolich)\n\nLicense\n-------\nMIT 2013 Philipp Fehre alias @sideshowcoder, or @ischi on twitter\n"
  },
  {
    "path": "bin/canned",
    "content": "#!/usr/bin/env node\nvar canned = require('../index')\n,   path = require('path')\n,   http = require('http')\n,   optimist = require('optimist')\n,   argv = optimist\n          .default('p', 3000)\n          .alias('p', 'port')\n          .describe('p', 'server port')\n          .default('w', 'any')\n          .alias('w', 'wildcard')\n          .describe('w', 'wildcard path name for ids')\n          .default('response_delay', 0)\n          .describe('response_delay', 'response resolve delay')\n          .default('relaxed_accept', false)\n          .describe('relaxed_accept', 'iterates through Accept header values from beginning to end')\n          .default('cors', true)\n          .describe('cors', 'disable cors support')\n          .default('headers', false)\n          .describe('headers', 'add custom headers allowed in cors requests')\n          .default('h', false)\n          .alias('h', 'help')\n          .describe('h', 'show the help')\n          .usage('Usage: $0 [dir]')\n          .argv\n\nif (argv.h) {\n  optimist.showHelp()\n  return\n}\n\nvar dir = ''\n,   port = argv.p\n,   relaxed_accept = argv.relaxed_accept\n,   cors = argv.cors\n,   cors_headers = argv.headers\n,   logger\n,   cannedDir\n,   wildcard = argv.wildcard\n,   response_delay = argv.response_delay\n\nif (argv._.length === 1) dir = argv._[0] // use the passed directory\nif (argv.q) {\n  logger = null // be quiet\n} else {\n  logger = process.stdout\n  cannedDir = path.resolve(dir)\n  process.stdout.write('starting canned on port ' + port + ' for ' + cannedDir + '\\n')\n}\n\nvar can = canned(dir, {\n  logger: logger,\n  relaxed_accept: relaxed_accept,\n  cors: cors,\n  cors_headers: cors_headers,\n  wildcard: wildcard,\n  response_delay: response_delay\n})\n\nhttp.createServer(can).listen(port)\n"
  },
  {
    "path": "example/_search.get.json",
    "content": "// this response is the default: \n//! params: {\"search\": \"default\"}\n{\n  \"search\":\"result\",\n  \"key\":\"value\"\n}\n\n//! params: {\"search\": \"specific\"}\n{\n  \"search\" : \"specific result\",\n  \"key\": \"value\"\n}\n\n//! params: {\"search\": \"apostrophe\"}\n{\n  \"search\":\"Mary\",\n  \"results\": [\n    {\n      \"id\":1,\n      \"title\":\"There's something about Mary\"\n    }\n  ]\n}"
  },
  {
    "path": "example/comment/_myfunc.get.json",
    "content": "{\n  \"myfunc\":\"result\",\n  \"key\":\"value\"\n}\n\n"
  },
  {
    "path": "example/comment/any.get.json",
    "content": "{\n  \"id\":\"get\",\n  \"key\":\"value\"\n}\n\n"
  },
  {
    "path": "example/comment/any.put.json",
    "content": "{\n  \"id\":\"put\",\n  \"key\":\"value\"\n}\n\n"
  },
  {
    "path": "example/comment/index.get.json",
    "content": "{\n  \"index\":\"get\",\n  \"key\":\"value\"\n}\n\n"
  },
  {
    "path": "example/comment/index.post.json",
    "content": "{\n  \"index\":\"post\",\n  \"key\":\"value\"\n}\n\n"
  },
  {
    "path": "index.js",
    "content": "\"use strict\";\n\nvar path = require('path')\nvar Canned = require('./lib/canned')\n\nvar canned = function (dir, options) {\n  if (!options) options = {}\n  dir = path.relative(process.cwd(), dir)\n  var c = new Canned(dir, options)\n  return c.responseFilter.bind(c)\n}\n\nmodule.exports = canned\n\n"
  },
  {
    "path": "lib/canned.js",
    "content": "\"use strict\";\n\nvar url = require('url')\nvar fs = require('fs')\nvar util = require('util')\nvar Response = require('./response')\nvar querystring = require('querystring')\nvar cannedUtils = require('./utils')\nvar lookup = require('./lookup')\nvar _ = require('lodash')\n\nfunction Canned(dir, options) {\n  this.logger = options.logger\n  this.wildcard = options.wildcard || 'any'\n  this.relaxed_accept = options.relaxed_accept\n  this.sanitize = options.sanitize !== undefined ? options.sanitize : true\n  var cors_headers = options.cors_headers\n  if (cors_headers && cors_headers.join) {\n    cors_headers = cors_headers.join(', ')\n  }\n  this.response_opts = {\n    response_delay: options.response_delay,\n    cors_enabled: options.cors,\n    cors_headers: cors_headers\n  }\n  this.dir = process.cwd() + '/' + dir\n}\n\nfunction matchFile(matchString, fname, method, ctype) {\n  if(!ctype) {\n    ctype = '(.+)';\n  }\n  return matchString.match(\n    new RegExp(fname + '\\\\.' + method + '\\\\.' + ctype)\n  )\n}\n\nfunction matchFileWithQuery(matchString, ctype) {\n  if(!ctype) {\n    ctype = '(.+)';\n  }\n  return matchString.match(\n    new RegExp('(.*)\\\\?(.*)\\\\.(.*)\\\\.' + ctype)\n    )\n}\n\nfunction matchFileWithExactQuery(matchString, fname, queryString, method, ctype) {\n  var escapedQueryString = cannedUtils.escapeRegexSpecialChars(queryString)\n  return matchString.match(\n    new RegExp(fname +\n               \"(?=.*\" +\n               escapedQueryString.split(\"&\").join(\")(?=.*\") +\n               \").+\" +\n               method + \"\\\\.\" + ctype)\n  )\n}\n\nCanned.prototype._getFileFromRequest = function(httpObj, files) {\n\n  if (!files) return false\n\n  var m, i, e, matchString, fileMatch, ctype\n\n  // if query params, match regexp based on fname to request\n  if(httpObj.query)\n  {\n    for (i = 0, e = files[i]; e != null; e = files[++i]) {\n      fileMatch = matchFileWithQuery(e, httpObj.ctype)\n      if (fileMatch)\n      {\n        ctype = httpObj.ctype || fileMatch[4];\n        matchString = httpObj.fname + \"?\" + httpObj.query + \".\" + httpObj.method + \".\" + ctype\n        m = matchFileWithExactQuery(matchString, fileMatch[1], fileMatch[2], fileMatch[3], ctype)\n        if (m) return { fname: e, mimetype: ctype }\n      }\n    }\n  }\n\n  // if match regexp based on request to fname\n  for (i = 0, e = files[i]; e != null; e = files[++i]) {\n    var contentTypes = [httpObj.ctype];\n    if (this.relaxed_accept) {\n      contentTypes = httpObj.matchingContentTypes;\n    }\n    for (var j = 0; j < contentTypes.length; j++) {\n      m = matchFile(e, httpObj.fname, httpObj.method, contentTypes[j])\n      if (m) {\n        ctype = contentTypes[j] || m[1];\n        return { fname : m[0], mimetype : ctype }\n      }\n    }\n  }\n  return false\n}\n\nfunction getContentType(mimetype){\n  return Response.content_types[mimetype]\n}\n\nfunction stringifyValues(object) {\n  _.each(object, function(value, key) {\n    if (typeof value === \"object\") {\n      stringifyValues(value);\n    } else {\n      object[key] = String(value)\n    }\n  })\n}\n\nfunction isContentTypeJson(request) {\n  return request.headers &&\n         request.headers['content-type'] &&\n         request.headers['content-type'].indexOf('application/json') !== -1;\n}\n\nCanned.prototype.parseMetaData = function(response) {\n  var metaData = {}\n  // convert CR+LF => LF+LF, CR => LF, fixes line breaks causing issues in windows\n  response = response.replace(\"\\r\", \"\\n\");\n  var lines = response.split(\"\\n\")\n  var that = this\n  var requestMatch = new RegExp(/\\/\\/! [body|params|header]+: (.*)/g)\n  lines.forEach(function(line) {\n    var optionsMatch = new RegExp(/\\/\\/!.*[statusCode|contentType|customHeader]/g)\n\n    if(line.indexOf(\"//!\") === 0) { // special comment line\n      var matchedRequest = requestMatch.exec(line)\n      if(matchedRequest) {\n        try {\n          metaData.request = JSON.parse(matchedRequest[1])\n          stringifyValues(metaData.request);\n        } catch (e) {\n          metaData.request = matchedRequest[1];\n        }\n        return\n      }\n      var matchedOptions = optionsMatch.exec(line)\n      if(matchedOptions) {\n        try {\n          line = line.replace(\"//!\", '')\n          var content = line.split(',').map(function (s) {\n            var parts = s.split(':');\n            parts[0] = '\"' + parts[0].trim() + '\"'\n            return parts.join(':')\n          }).join(',')\n          var opts = JSON.parse('{' + content  + '}')\n          if(opts.hasOwnProperty('customHeader')) {\n              if(metaData.hasOwnProperty('customHeaders')) metaData.customHeaders.push(opts.customHeader)\n              else metaData.customHeaders = [opts.customHeader]\n          } else {\n            cannedUtils.extend(metaData, opts)\n          }\n        } catch(e) {\n          that._log('Invalid file header format try //! statusCode: 201')\n        }\n        return\n      }\n    }\n  })\n\n  return metaData\n}\n\nCanned.prototype.getSelectedResponse = function(responses, content, headers) {\n  var that = this\n  var inputObj\n  var response = responses[0]\n  var metaData = that.parseMetaData(response)\n  var selectedResponse = {\n    data: cannedUtils.removeSpecialComments(response),\n    statusCode: metaData.statusCode || 200,\n    contentType: metaData.contentType,\n    customHeaders: metaData.customHeaders\n  }\n\n  stringifyValues(content);\n  // put the contents of the body and the headers into a big, indexed object.\n  inputObj = cannedUtils.extend({}, content, headers)\n\n  responses.forEach(function(response) {\n    var metaData = that.parseMetaData(response)\n\n    for(var contentString in content) {\n      if (Object.hasOwnProperty.call(content, contentString)) break\n    }\n\n    if (contentString === metaData.request) {\n      //exact match of request body with body comment in file\n      selectedResponse.data = cannedUtils.removeSpecialComments(response)\n      if(metaData.statusCode) selectedResponse.statusCode = metaData.statusCode\n      return\n    }\n\n    if (typeof metaData.request !== 'object') return;\n\n    if(_.isMatch(inputObj, metaData.request)) {\n        selectedResponse.data = cannedUtils.removeSpecialComments(response)\n        if(metaData.statusCode) selectedResponse.statusCode = metaData.statusCode\n      }\n    })\n\n  return selectedResponse\n}\n\n// return multiple response bodies as array\nCanned.prototype.getEachResponse = function(data) {\n  if (this.sanitize) {\n    data = cannedUtils.removeJSLikeComments(data)\n  }\n  var responses = data.split(/\\n\\n(?=[\\/\\/!])/).filter(function (e) { return e !== '' })\n  return responses\n}\n\nCanned.prototype.getVariableResponse = function(data, content, headers) {\n  if(!data.length) {\n    return { statusCode: 204, data: '' }\n  }\n\n  var responses = this.getEachResponse(data)\n  var response = this.getSelectedResponse(responses, content, headers)\n  return response\n}\n\nCanned.prototype.sanatizeContent = function (data, fileObject) {\n  var sanatized\n\n  if (data.length === 0 || !this.sanitize) {\n    return data\n  }\n\n  switch (fileObject.mimetype) {\n  case 'json':\n    // make sure we return valid JSON even so we support comments\n    try {\n      sanatized = JSON.stringify(JSON.parse(cannedUtils.removeJSLikeComments(data)))\n    } catch (err) {\n      this._log(\"problem sanatizing content for \" + fileObject.fname + \" \" + err)\n      return false\n    }\n    break\n  default:\n    sanatized = data\n  }\n  return sanatized\n}\n\nCanned.prototype._responseForFile = function (httpObj, files, cb) {\n  var that = this\n  var fileObject = this._getFileFromRequest(httpObj, files);\n  httpObj.filename = fileObject.fname\n  if (fileObject) {\n    var filePath = httpObj.path + '/' + fileObject.fname\n    fs.readFile(filePath, { encoding: 'utf8' }, function (err, data) {\n      var response\n      if (err) {\n        response = new Response(getContentType('html'), '', 404, httpObj.res, that.response_opts)\n        cb('Not found', response)\n      } else {\n        data = data.replace(/\\r/g, \"\");\n        var _data = that.getVariableResponse(data, httpObj.content, httpObj.headers)\n        data = _data.data\n        var statusCode = _data.statusCode\n        var content = that.sanatizeContent(data, fileObject)\n\n        if (content !== false) {\n          response = new Response(_data.contentType || getContentType(fileObject.mimetype), content, statusCode, httpObj.res, that.response_opts, _data.customHeaders)\n          cb(null, response)\n        } else {\n          content = 'Internal Server error invalid input file'\n          response = new Response(getContentType('html'), content, 500, httpObj.res, that.response_opts)\n          cb(null, response)\n        }\n      }\n    })\n  } else {\n    var response = new Response(getContentType('html'), '', 404, httpObj.res, that.response_opts)\n    cb('Not found', response)\n  }\n}\n\nCanned.prototype._log = function (message) {\n  if (this.logger) this.logger.write(message)\n}\n\nCanned.prototype._logHTTPObject = function (httpObj) {\n  this._log(' served via: .' + httpObj.pathname.join('/') + '/' + httpObj.filename + '\\n')\n}\n\nCanned.prototype.respondWithDir = function (httpObj, cb) {\n  var that = this;\n\n  var fpath = httpObj.path + '/' + httpObj.dname\n  fs.readdir(fpath, function (err, files) {\n    httpObj.fname = 'index'\n    httpObj.path  = fpath\n    that._responseForFile(httpObj, files, function (err, resp) {\n      return cb(err, resp)\n    })\n  })\n}\n\nCanned.prototype.respondWithAny = function (httpObj, files, cb) {\n  var that = this;\n\n  httpObj.fname = 'any';\n  that._responseForFile(httpObj, files, function (err, resp) {\n    return cb(err, resp);\n  })\n}\n\nCanned.prototype.responder = function(body, req, res) {\n  var responseHandler\n  var httpObj = {}\n  var that = this\n  var parsedurl = url.parse(req.url)\n  httpObj.headers   = req.headers\n  httpObj.accept    = (req.headers && req.headers.accept) ? req.headers.accept.trim().split(',') : []\n  httpObj.content   = body\n  httpObj.pathname  = parsedurl.pathname.split('/')\n  httpObj.dname     = httpObj.pathname.pop()\n  httpObj.fname     = '_' + httpObj.dname\n  httpObj.path      = this.dir + httpObj.pathname.join('/')\n  httpObj.query     = parsedurl.query\n  httpObj.method    = req.method.toLowerCase()\n  httpObj.res       = res\n  httpObj.ctype     = ''\n  httpObj.matchingContentTypes  = []\n\n  this._log('request: ' + httpObj.method + ' ' + req.url)\n\n  if (httpObj.method === 'options') {\n    that._log('Options request, serving CORS Headers\\n')\n    var response = new Response(null, '', 200, res, this.response_opts)\n    return response.send()\n  }\n\n  if (httpObj.accept.length) {\n    for(var type in Response.content_types){\n      if (Response.content_types.hasOwnProperty(type)) {\n        if (Response.content_types[type] === httpObj.accept[0].trim()){\n          httpObj.ctype = type;\n        }\n        for(var i = 0; i < httpObj.accept.length; i++){\n          if(Response.content_types[type] === httpObj.accept[i].trim()){\n            httpObj.matchingContentTypes.push(type);\n          }\n        }\n      }\n    }\n  }\n\n  var paths = lookup(httpObj.pathname.join('/'), that.wildcard);\n  paths.splice(0,1); // The first path is the default\n  responseHandler = function (err, resp) {\n    if (err) {\n      // Try more paths, if there are any still\n      if (paths.length > 0) {\n        httpObj.path = that.dir + paths.splice(0, 1)[0];\n        httpObj.fname = '_' + httpObj.dname;\n        return that.findResponse(httpObj, responseHandler);\n      } else {\n        that._log(' not found\\n');\n      }\n    } else {\n      that._logHTTPObject(httpObj)\n    }\n    return resp.send();\n  }\n\n  // Find a response for the first path\n  that.findResponse(httpObj, responseHandler);\n\n}\n\nCanned.prototype.findResponse = function(httpObj, cb) {\n  var that = this;\n  fs.readdir(httpObj.path, function (err, files) {\n    fs.stat(httpObj.path + '/' + httpObj.dname, function (err, stats) {\n      if (err) {\n        that._responseForFile(httpObj, files, function (err, resp) {\n          if (err) {\n            that.respondWithAny(httpObj, files, cb)\n          } else {\n            cb(null, resp)\n          }\n        })\n      } else {\n        if (stats.isDirectory()) {\n          that.respondWithDir(httpObj, cb)\n        } else {\n          cb(null, new Response('html', '', 500, httpObj.res))\n        }\n      }\n    })\n  })\n}\n\nCanned.prototype.responseFilter = function (req, res) {\n  var that = this\n  var body = ''\n\n  // assemble response body if GET/POST/PUT\n  switch(req.method) {\n  case 'PUT':\n  case 'POST':\n    req.on('data', function (data) {\n      body += data\n    })\n    req.on('end', function () {\n      var responderBody = querystring.parse(body);\n      if (isContentTypeJson(req)) {\n        try {\n          responderBody = JSON.parse(body)\n        } catch (e) {\n          that._log('Invalid json content')\n        }\n      }\n      that.responder(responderBody, req, res)\n    })\n    break\n  case 'GET':\n    var query = url.parse(req.url).query\n    if (query && query.length > 0) {\n      body = querystring.parse(query)\n    }\n    that.responder(body, req, res)\n    break\n  default:\n    that.responder(body, req, res)\n    break\n  }\n}\n\nmodule.exports = Canned;\n"
  },
  {
    "path": "lib/lookup.js",
    "content": "\"use strict\";\n\n\n/***\n * Given a path and a wildcard string, return a list of paths\n * with every combination possible resulting from t he replacement of\n * any integer id found in the path with the wildcard string.\n *\n * The resulting list of paths is ordered by more \"specific\" to more\n * \"generic\" paths, for example using a wildcard of 'any' for the path:\n *\n *     api/2/customer/123/invoice/321/\n *\n * will return:\n *\n * [\n *   '/api/2/customer/123/invoice/321/',\n *   '/api/2/customer/123/invoice/any/',\n *   '/api/2/customer/any/invoice/321/',\n *   '/api/2/customer/any/invoice/any/',\n *   '/api/any/customer/123/invoice/321/',\n *   '/api/any/customer/123/invoice/any/',\n *   '/api/any/customer/any/invoice/321/',\n *   '/api/any/customer/any/invoice/any/'\n * ]\n *\n * @param path - the original path\n * @param wildcard - the replacmeent string\n * @returns {Array} - the resulting combination, ordered by specificity\n */\n\nvar lookup = module.exports = function (path, wildcard) {\n\n  // Split the path and calculate how many paths will be generated\n  var parts = path.split('/')\n  var matches = path.match(/\\/\\d+(\\/|$)/gi)\n  var i\n\n  if (!matches){\n    return [path]\n  }\n\n  var lookPathsParts = [];\n\n  // Locate replaceable parts indexes\n  var matchesIndexes = []\n  parts.forEach(function (p, i) {\n    if (p.match(/^\\d+$/)) {\n      matchesIndexes.push(i)\n    }\n  })\n\n  // Copy the original parts as a starting point for the new parts\n  for (i = 0; i < Math.pow(2, matches.length); i++) {\n    lookPathsParts.push(parts.slice())\n  }\n\n  // Generate the new paths parts\n  for (i = matches.length; i > 0; --i) {\n    var skip = Math.pow(2, i) / 2\n    var replacePartIndex = matches.length - i\n    for (var j = skip; j < lookPathsParts.length; j += (skip * 2)) {\n      for (var k = 0; k < skip; k++) {\n        lookPathsParts[j + k][matchesIndexes[replacePartIndex]] = wildcard\n      }\n    }\n  }\n\n  // Build the final path strings\n  var lookPaths = []\n  lookPathsParts.forEach(function (p) {\n    lookPaths.push(p.join('/'))\n  })\n  return lookPaths\n}\n"
  },
  {
    "path": "lib/response.js",
    "content": "\"use strict\";\nvar fs = require('fs')\n\nfunction Response(content_type, content, statusCode, res, options, custom_headers) {\n  this.cors_enabled = !!options.cors_enabled\n  this.cors_headers = options.cors_headers\n  this.response_delay = options.response_delay\n  this.content_type = content_type\n  this.content = content\n  this.statusCode = statusCode\n  this.res = res\n  this.custom_headers = custom_headers || []\n}\n\nResponse.content_types = {\n  'json': 'application/json',\n  'html': 'text/html',\n  'txt': 'text/plain',\n  'js': 'application/javascript',\n  'nt': 'application/n-triples',\n  'csv': 'text/csv',\n  'jsonld': 'application/ld+json'\n}\n\nResponse.cors_headers = [\n  ['Access-Control-Allow-Origin', '*'],\n  ['Access-Control-Allow-Headers', 'X-Requested-With'],\n  ['Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS']\n]\n\nResponse.prototype.send = function () {\n  this.headers().forEach(function (header) {\n    this.res.setHeader(header[0], header[1])\n  }, this)\n  this.res.statusCode = this.statusCode\n\n  setTimeout(this.res.end.bind(this.res, this.content), this.response_delay)\n}\n\nResponse.prototype.headers = function () {\n  var headers = []\n  headers = this._addContentTypeHeaders(headers)\n  headers = this._addCORSHeaders(headers)\n  headers = this._addCustomHeaders(headers)\n  return headers\n}\n\nResponse.prototype._addContentTypeHeaders = function (headers) {\n  if (this.content_type) {\n    headers.push(['Content-Type', this.content_type])\n  }\n  return headers\n}\n\nResponse.prototype._addCORSHeaders = function (headers) {\n  var that = this;\n  if (this.cors_enabled) {\n    Response.cors_headers.forEach(function (h) {\n      if (!!that.cors_headers && h[0] === 'Access-Control-Allow-Headers')\n        headers.push([h[0], h[1] + \", \" + that.cors_headers])\n      else\n        headers.push(h)\n    })\n  }\n  return headers\n}\n\nResponse.prototype._addCustomHeaders = function (headers) {\n  this.custom_headers.forEach(function(header) {\n    var key = Object.keys(header)[0]\n    headers.push([key, header[key]])\n  })\n  return headers\n}\n\nmodule.exports = Response\n"
  },
  {
    "path": "lib/utils.js",
    "content": "\"use strict\";\n\nvar utils = module.exports = {}\n\nutils.escapeRegexSpecialChars = function (text) {\n  return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\")\n}\n\nutils.extend = function (target) {\n  var sources = [].slice.call(arguments, 1);\n  sources.forEach(function (source) {\n    for (var prop in source) {\n      if(Object.hasOwnProperty.call(source, prop)){\n        target[prop] = source[prop]\n      }\n    }\n  })\n  return target\n}\n\nutils.removeJSLikeComments = function (text) {\n  return text.replace(/\\/\\*.+?\\*\\/|\\/\\/\\s.*(?=[\\n\\r])/g, '')\n}\n\nutils.removeSpecialComments = function (data) {\n  return data.split(\"\\n\").filter(function(line) {\n    return line.indexOf(\"//!\") !== 0\n  }).join(\"\\n\").trim()\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"canned\",\n  \"version\": \"0.3.13\",\n  \"description\": \"serve canned responses to mock an api, based on files in a folder\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"make test\",\n    \"start\": \"./bin/canned\"\n  },\n  \"bin\": \"./bin/canned\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/sideshowcoder/canned\"\n  },\n  \"dependencies\": {\n    \"lodash\": \"^4.17.15\",\n    \"optimist\": \"^0.6.0\"\n  },\n  \"devDependencies\": {\n    \"jasmine-node\": \"^3.0.0\",\n    \"jshint\": \"^2.10.2\",\n    \"node-dev\": \"^4.0.0\"\n  },\n  \"engines\": {\n    \"node\": \">=0.10.3\"\n  },\n  \"keywords\": [\n    \"mock\",\n    \"api\",\n    \"server\"\n  ],\n  \"author\": \"Philipp Fehre @sideshowcoder\",\n  \"license\": \"MIT\"\n}\n"
  },
  {
    "path": "spec/canned.spec.js",
    "content": "\"use strict\";\nvar querystring = require(\"querystring\")\nvar canned = require('../index')\nvar path = require('path')\n\ndescribe('canned', function () {\n\n  var can, req, res\n  beforeEach(function () {\n    can = canned('./spec/test_responses')\n    req = { method: 'GET' }\n    res = { setHeader: function () {}, end: function () {} }\n    spyOn(res, 'setHeader')\n\n  })\n\n  describe('paths', function () {\n    beforeEach(function () {\n      var fullpath = path.resolve('./spec/test_responses')\n      can = canned(fullpath)\n    })\n\n    it('resolve requests when passed an absolute path', function (done) {\n      req.url = '/a'\n      res.end = function () {\n        expect(res.statusCode).toBe(200)\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n  describe('error messages', function () {\n    var writeLog, logCan\n    beforeEach(function () {\n      var logger = {\n        write: function (msg) {\n          if (writeLog) writeLog(msg)\n        }\n      }\n      logCan = canned('./spec/test_responses', { logger: logger })\n    })\n\n    it('displays an error for unparsable json files', function (done) {\n      var regex = new RegExp('.*Syntax.*')\n      writeLog = function (message) {\n        if (regex.test(message)) {\n          expect(message).toContain(\"problem sanatizing content for _invalid_syntax.get.json SyntaxError: Unexpected token I\")\n          done()\n        }\n      }\n      req.url = '/invalid_syntax'\n      logCan(req, res)\n    })\n  })\n\n  describe('sanitization', function () {\n    var writeLog, logCan\n    var logger = {\n      write: function (msg) {\n        if (writeLog) writeLog(msg)\n      }\n    }\n    describe('with sanitization enabled', function() {\n      beforeEach(function () {\n        logCan = canned('./spec/test_responses', { logger: logger })\n      })\n\n      it('displays an error for json containing unexpected markup', function (done) {\n        var regex = new RegExp('.*Syntax.*')\n        writeLog = function (message) {\n          if (regex.test(message)) {\n            expect(message).toContain(\"problem sanatizing content for _broken_sanitize.get.json SyntaxError: Unexpected token\")\n            done()\n          }\n        }\n        req.url = '/broken_sanitize'\n        logCan(req, res)\n      })\n    })\n\n    describe('with sanitization disabled', function() {\n      beforeEach(function () {\n        logCan = canned('./spec/test_responses', { logger: logger, sanitize: false })\n      })\n\n      it('loads content from _broken_sanitize.get.json', function (done) {\n        req.url = '/broken_sanitize'\n        res.end = function (content) {\n          expect(content).toContain('\"whatAmI\": \"I have been copy/pasted into a WYSIWYG editor by your grandma\"')\n          done()\n        }\n        logCan(req, res)\n      })\n    })\n  })\n\n  describe('status codes', function () {\n    it('sets 404 for non resolveable request', function (done) {\n      req.url = '/i_do_not_exist'\n      res.end = function () {\n        expect(res.statusCode).toBe(404)\n        done()\n      }\n      can(req, res)\n    })\n\n    it('sets 200 for resolveable requests', function (done) {\n      req.url = '/a'\n      res.end = function () {\n        expect(res.statusCode).toBe(200)\n        done()\n      }\n      can(req, res)\n    })\n\n    it('sets 201 if specified in file', function (done) {\n      req.url = '/201'\n      res.end = function () {\n        expect(res.statusCode).toBe(201)\n        done()\n      }\n      can(req, res)\n    })\n\n    it('sets 204 for empty file', function (done) {\n      req.url = '/empty'\n      res.end = function () {\n        expect(res.statusCode).toBe(204)\n        done()\n      }\n      can(req, res)\n    })\n\n    it('sets specified status for empty file with headers set', function (done) {\n      req.url = '/empty_with_headers'\n      res.end = function () {\n        expect(res.statusCode).toBe(420)\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n  describe('content type', function () {\n    it('sets text/plain for txt', function (done) {\n      req.url = '/b'\n      res.setHeader = function (name, value) {\n        expect(value).toBe('text/plain')\n        expect(name).toBe('Content-Type')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('sets text/html for errors', function (done) {\n      req.url = '/i_do_not_exist'\n      res.setHeader = function (name, value) {\n        expect(value).toBe('text/html')\n        expect(name).toBe('Content-Type')\n        done()\n      }\n      can(req, res)\n    })\n    it('sets Content-type header if specified in file', function(done){\n      req.url = '/vendor_type'\n      res.setHeader = function(name, value){\n        expect(value).toBe('application/vnd.custom+xml')\n        expect(name).toBe('Content-Type')\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n    describe('custom response header', function(){\n      it('populates custom header with single header', function(done){\n          req.url = '/single_custom_header'\n          res.end = function() {\n            expect(res.setHeader).toHaveBeenCalledWith('Header-Key', 'Header-Content')\n            done()\n        }\n          can(req, res)\n      })\n\n      it('populates custom headers with multiple headers', function(done){\n          req.url = '/multiple_custom_header'\n          res.end = function() {\n            expect(res.setHeader).toHaveBeenCalledWith('Header-Key', 'Header-Content')\n            expect(res.setHeader).toHaveBeenCalledWith('Header-Key2', 'Header-Content2')\n            done()\n        }\n          can(req, res)\n      })\n    })\n\n  describe('resolve file paths', function () {\n\n    it('loads index for /', function (done) {\n      req.url = '/'\n      res.end = function (content) {\n        expect(content).toContain('index.get.json')\n        done()\n      }\n      can(req, res)\n    });\n\n    it('loads index for /d with d being a directory', function (done) {\n      req.url = '/d'\n      res.end = function (content) {\n        expect(content).toContain('d/index.get.json')\n        done()\n      }\n      can(req, res)\n    });\n\n    it('loads index for /d/e with both being directories', function (done) {\n      req.url = '/d/e'\n      res.end = function (content) {\n        expect(content).toContain('d/e/index.get.html')\n        done()\n      }\n      can(req, res);\n    });\n\n    it('loads any for /d/something', function (done) {\n      req.url = '/d/i_am_an_id'\n      res.end = function (content) {\n        expect(content).toContain('d/any.get.json')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('loads index from wildcard path for /d/1/', function (done) {\n      req.url = '/d/1/'\n      res.end = function (content) {\n        expect(content).toContain('{\"wildcard\":1}')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('loads named response from wildcard path for /d/1/bar', function (done) {\n      req.url = '/d/1/bar'\n      res.end = function (content) {\n        expect(content).toContain('{\"wildcard\":\"named_response\"}')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('loads index from real path for /d/2/', function (done) {\n      req.url = '/d/2/'\n      res.end = function (content) {\n        expect(content).toContain('{\"not-wildcard\":1}')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('looks for _file with query params', function (done) {\n      req.url = '/multimatch_query_param?name=Superman&age=30&idontneed=everyparaminfilename'\n      res.end = function (content) {\n        expect(content).toContain('Superman!')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('can tell different query param files a part', function (done) {\n      req.url = '/multimatch_query_param?name=Batman&age=30&idontneed=everyparaminfilename'\n      res.end = function (content) {\n        expect(content).toContain('Batman!')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('falls back to file without query params if one or more params dont match', function (done) {\n      req.url = '/a?foo=bar'\n      res.end = function (content) {\n        expect(content).toContain('_a.get.json')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('works for nested folder being not present', function (done) {\n      req.url = '/foo/bar/baz'\n      res.end = function () {\n        expect(res.statusCode).toBe(404)\n        done()\n      }\n      can(req, res)\n    })\n\n    it('allows for multiple files to match via the .NUMBER extension and pick 1 by default', function (done) {\n      req.url = '/multimatch'\n      res.end = function (content) {\n        var multimatch = JSON.parse(content).multimatch\n        expect(multimatch).toBe(1)\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects json file for request with application/json accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'application/json'\n      }\n      res.end = function (content) {\n        var jsonResponse = JSON.parse(content)\n        expect(jsonResponse.type).toBe('json')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects jsonld file for request with application/ld+json accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'application/ld+json'\n      }\n      res.end = function (content) {\n        var jsonResponse = JSON.parse(content)\n        expect(jsonResponse['@context']).toBe('http://schema.org/')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects nt file for request with application/n-triples accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'application/n-triples'\n      }\n      res.end = function (content) {\n        expect(content).toBe('_:b0 <http://schema.org/name> \\\"Jane Doe\\\" .')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects csv file for request with text/csv accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'text/csv'\n      }\n      res.end = function (content) {\n        expect(content).toBe('Jane Doe,Professor,(425) 123-4567,http://www.janedoe.com')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects js file for request with application/javascript accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'application/javascript'\n      }\n      res.end = function (content) {\n        expect(content).toBe('var type = \\'js\\';')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects txt file for request with text/plain accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'text/plain'\n      }\n      res.end = function (content) {\n        expect(content).toBe('text type')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects txt file for request with text/html accept header', function (done) {\n      req.url = '/multiple_type';\n      req.headers = {\n        accept: 'text/html'\n      }\n      res.end = function (content) {\n        expect(content).toBe('<type>html</type>')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('selects json file when application/json is not first in the Accept header', function (done) {\n      can = canned('./spec/test_responses', {\"relaxed_accept\": true})\n      req.url = '/d/multiple-accept-types'\n      req.headers = {\n        accept: 'text/html, application/json'\n      }\n      res.end = function (content) {\n        expect(content).toBe('{\"type\":\"json\"}');\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n  describe('content modifier', function () {\n    it('removes comments from json', function (done) {\n      req.url = '/d/commented'\n      res.end = function (content) {\n        expect(content).toBe('{\"no\":\"comments\"}');\n        done()\n      }\n      can(req, res)\n    })\n\n    it('works with http:// in json strings', function (done) {\n      req.url = '/chartest'\n      res.end = function (content) {\n        expect(content).toBe('{\"my_url\":\"http://www.mywebsite.com\"}');\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n  describe('CORS', function () {\n    var can = canned('./spec/test_responses', { cors: true })\n    it('accepts the options verb', function (done) {\n      req.method = 'OPTIONS'\n      req.url = '/'\n      res.end = function (content) {\n        // serves no content\n        expect(content).toBe('')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('sets the headers', function (done) {\n      req.url = '/'\n      var expectedHeaders = {\n        'Access-Control-Allow-Origin': \"*\",\n        'Access-Control-Allow-Headers': \"X-Requested-With\",\n        'Access-Control-Allow-Methods': \"GET, POST, PUT, PATCH, DELETE, OPTIONS\"\n      }\n      res.setHeader = function (name, value) {\n        if (expectedHeaders[name]) {\n          expect(expectedHeaders[name]).toBe(value)\n          delete expectedHeaders[name]\n        }\n        // all expected headers have been set!\n        if (Object.keys(expectedHeaders).length === 0) done()\n      }\n      can(req, res)\n    })\n\n    it('adds custom headers from a string', function (done) {\n      var can2 = canned('./spec/test_responses', { cors: true, cors_headers: \"Authorization, Content-Type\" })\n      req.url = '/'\n      var expectedHeaders = {\n        'Access-Control-Allow-Headers': \"X-Requested-With, Authorization, Content-Type\"\n      }\n      res.setHeader = function (name, value) {\n        if (expectedHeaders[name]) {\n          expect(expectedHeaders[name]).toBe(value)\n          delete expectedHeaders[name]\n        }\n        // all expected headers have been set!\n        if (Object.keys(expectedHeaders).length === 0) done()\n      }\n      can2(req, res)\n    })\n\n    it('adds custom headers from an array', function (done) {\n      var can2 = canned('./spec/test_responses', { cors: true, cors_headers: [\"Authorization\", \"Content-Type\"] })\n      req.url = '/'\n      var expectedHeaders = {\n        'Access-Control-Allow-Headers': \"X-Requested-With, Authorization, Content-Type\"\n      }\n      res.setHeader = function (name, value) {\n        if (expectedHeaders[name]) {\n          expect(expectedHeaders[name]).toBe(value)\n          delete expectedHeaders[name]\n        }\n        // all expected headers have been set!\n        if (Object.keys(expectedHeaders).length === 0) done()\n      }\n      can2(req, res)\n    })\n  })\n\n  describe('variable GET responses', function () {\n    it('should return the first JSON response body if no header match', function (done) {\n      req.headers = {}\n      req.url = '/multiple_responses'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\":\"response for abc\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first text response body if no header match', function (done) {\n      req.headers = {}\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('response for abc')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first JSON response body on header match', function (done) {\n      req.headers = {\n        \"authorization\": 'abc'\n      }\n      req.url = '/multiple_responses'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\":\"response for abc\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first text response body on header match', function (done) {\n      req.headers = {\n        \"authorization\": 'abc'\n      }\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('response for abc')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response body on header match', function (done) {\n      req.headers = {\n        \"authorization\": '123'\n      }\n      req.url = '/multiple_responses'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\":\"response for 123\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response body on header match', function (done) {\n      req.headers = {\n        \"authorization\": '123'\n      }\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('response for 123')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should be able to return html', function (done) {\n      req.headers = {\n        \"authorization\": 'html'\n      }\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('<h1>response for html</h1>')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return correct status code and the first JSON response body on header match', function (done) {\n      req.headers = {\n        \"authorization\": 'abc'\n      }\n      req.url = '/201_multiple_responses'\n      res.end = function (content) {\n        expect(res.statusCode).toBe(201)\n        expect(content).toEqual(JSON.stringify({\"response\":\"response for abc\"}))\n        done()\n      }\n      can(req, res)\n    })\n    it('should return correct status code and the second response body on header match', function (done) {\n      req.headers = {\n        \"authorization\": '123'\n      }\n      req.url = '/201_multiple_responses'\n      res.end = function (content) {\n        expect(res.statusCode).toBe(201)\n        expect(content).toEqual(JSON.stringify({\"response\":\"response for 123\"}))\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n  describe(\"variable GET responses based on params\", function() {\n    var req, data\n    beforeEach(function() {\n      req = { method: 'GET' }\n    })\n\n    it(\"should select the right response based on the GET request data\", function (done) {\n      req.url = \"/multiple_get_responses?\" + querystring.stringify({ foo: \"bar\" })\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for bar\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it(\"should select the right response based on the GET request data\", function (done) {\n      req.url = \"/multiple_get_responses?\" + querystring.stringify({ foo: \"apostrophe\" })\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response with 'apostrophes'\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it(\"should select the right response based on the GET request data\", function (done) {\n      req.url = \"/multiple_get_responses?\" + querystring.stringify({ foo: \"bar\", index: 1 })\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response with index 1\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it(\"should select the first response with no query string\", function (done) {\n      req.url = \"/multiple_get_responses\"\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for baz\"}))\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n  describe(\"Issues\", function () {\n    it(\"#58\", function(done) {\n      req.url = \"/multiple_get_responses?\" + querystring.stringify({foo: \"apostrophe\"})\n      res.end = function(content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response with 'apostrophes'\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it(\"#73\", function (done) {\n      req.url = \"/multiple_get_responses?\" + querystring.stringify({\"foo\": \"bar\", \"index\": 1})\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response with index 1\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it(\"#79\", function (done) {\n        var Canned = require('../lib/canned')\n        var can = new Canned('./spec/test_responses', {});\n        var mock_text = '//! params: {\"serialkey\": \"abc\"}\\r\\n{\\r\\n\"errorCode\": \"ERROR1\"\\r\\n}\\r\\n' +\n                        '//! params: {\"serialkey\": \"12121\"}\\r\\n{\\r\\n\"errorCode\": \"ERROR2\"\\r\\n}';\n        var parsedMeta = can.parseMetaData(mock_text);\n        expect(parsedMeta).toEqual({\n          request: {\n            serialkey: 'abc'\n          },\n          params: {\n            serialkey: '12121'\n          }\n        });\n        done();\n    })\n  })\n\n  describe(\"variable POST responses\", function() {\n    var req, data\n    beforeEach(function() {\n      req = {\n        method: 'POST',\n        headers: {},\n        on: function(event, fn) {\n          fn(data)\n        }\n      }\n    })\n\n    it('should return the first response body if no payload match', function (done) {\n      data = 'email=nobody@example.com'\n      req.url = '/multiple_responses'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for one@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response body if no payload match', function (done) {\n      data = 'email=nobody@example.com'\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('response for one@example.com')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response body on payload match', function (done) {\n      data = 'email=one@example.com'\n      req.url = '/multiple_responses'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for one@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response JSON body on payload match', function (done) {\n      data = '{\"email\":\"one@example.com\"}'\n      req.url = '/multiple_responses'\n      req.headers['content-type'] = 'application/json'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for one@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response JSON body on payload match even if content type has charset', function (done) {\n      data = '{\"email\":\"one@example.com\"}'\n      req.url = '/multiple_responses'\n      req.headers['content-type'] = 'application/json; charset=UTF-8'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for one@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should handle request bodies containing arrays', function (done) {\n      data = '{\"email\": \"two@example.com\",\"topics\": [1,2]}'\n      req.url = '/multiple_responses'\n      req.headers['content-type'] = 'application/json; charset=UTF-8'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for two@example.com topics 1,2\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should handle request bodies containing urls', function (done) {\n      data = '{\"url\": \"http://example.com\"}'\n      req.url = '/response_with_url_param'\n      req.headers['content-type'] = 'application/json'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for url in param\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response JSON body on payload match (because JSON body is invalid)', function (done) {\n      data = 'bad json data'\n      req.url = '/multiple_responses'\n      req.headers['content-type'] = 'application/json'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for one@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response body on payload match', function (done) {\n      data = 'email=one@example.com'\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('response for one@example.com')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response body on payload match', function (done) {\n      data = 'email=two@example.com'\n      req.url = '/multiple_responses'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for two@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response JSON body on payload match', function (done) {\n      data = '{\"email\":\"two@example.com\"}'\n      req.url = '/multiple_responses'\n      req.headers['content-type'] = 'application/json'\n      res.end = function (content) {\n        expect(content).toEqual(JSON.stringify({\"response\": \"response for two@example.com\"}))\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response body on payload match', function (done) {\n      data = 'email=two@example.com'\n      req.url = '/multiple_responses_text'\n      res.end = function (content) {\n        expect(content).toEqual('response for two@example.com')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response body on xml (or really any string) payload match', function (done) {\n      data = '<xml>b</xml>'\n      req.url = '/multiple_responses_xml_request_body'\n      res.end = function (content) {\n        expect(content).toEqual('<xml>B</xml>')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the first response xml on header match', function (done) {\n      data = ''\n      req.url = '/multiple_responses_xml'\n      req.headers = {\n        \"action\": 'foo'\n      }\n      res.end = function (content) {\n        expect(content).toEqual('<SOAP:Envelope><SOAP:Body><Foo Time=\"2015-01-22T08:30:00.000+05:30\"/></SOAP:Body></SOAP:Envelope>')\n        done()\n      }\n      can(req, res)\n    })\n\n    it('should return the second response xml on header match', function (done) {\n      data = ''\n      req.url = '/multiple_responses_xml'\n      req.headers = {\n        \"action\": 'bar'\n      }\n      res.end = function (content) {\n        expect(content).toEqual('<SOAP:Envelope><SOAP:Body><Bar Time=\"2015-01-22T08:30:00.000+05:30\"/></SOAP:Body></SOAP:Envelope>')\n        done()\n      }\n      can(req, res)\n    })\n  })\n\n})\n"
  },
  {
    "path": "spec/lookup.spec.js",
    "content": "\"use strict\";\n\nvar lookup = require('../lib/lookup')\n\ndescribe('lookup', function () {\n  it('should generate a list of paths in the correct order', function (done) {\n    var testPath = '/api/2/customer/123/invoice/321/'\n    var expectedPaths = [\n      '/api/2/customer/123/invoice/321/',\n      '/api/2/customer/123/invoice/any/',\n      '/api/2/customer/any/invoice/321/',\n      '/api/2/customer/any/invoice/any/',\n      '/api/any/customer/123/invoice/321/',\n      '/api/any/customer/123/invoice/any/',\n      '/api/any/customer/any/invoice/321/',\n      '/api/any/customer/any/invoice/any/'\n    ]\n    expect(lookup(testPath, 'any')).toEqual(expectedPaths)\n    done()\n  });\n});\n"
  },
  {
    "path": "spec/test_responses/_201.get.json",
    "content": "//! statusCode: 201\n{\n  \"created\": 1\n}\n"
  },
  {
    "path": "spec/test_responses/_201_multiple_responses.get.json",
    "content": "//! statusCode: 201\n//! header: {\"authorization\": \"123\"}\n{\n    \"response\": \"response for 123\"\n}\n\n//! statusCode: 201\n//! header: {\"authorization\": \"abc\"}\n{\n    \"response\": \"response for abc\"\n}\n"
  },
  {
    "path": "spec/test_responses/_a.get.html",
    "content": "_a.get.json\n"
  },
  {
    "path": "spec/test_responses/_b.get.txt",
    "content": "_b.get.txt\n"
  },
  {
    "path": "spec/test_responses/_broken_sanitize.get.json",
    "content": "{\n  \"whatAmI\": \"I have been copy/pasted into a WYSIWYG editor by your grandma\",\n  \"embedCode\": \"<div class=\\\"nasty-3rd-party-code\\\">\\n\\n\\n<script type=\\\"text/javascript\\\">\\nvar someValue = 'I will make you cry';\\n// --></script>\\n</script>  </p>\\n\\nHuh?<p>\\n\\n</div>\\n\\nYes, true story!\",\n  \"honestly\": \"Can we get an Internet User Licence introduced already?\"\n}\n"
  },
  {
    "path": "spec/test_responses/_chartest.get.json",
    "content": "{\n  \"my_url\":\"http://www.mywebsite.com\"\n}"
  },
  {
    "path": "spec/test_responses/_empty.get.json",
    "content": ""
  },
  {
    "path": "spec/test_responses/_empty_with_headers.get.json",
    "content": "//! statusCode: 420"
  },
  {
    "path": "spec/test_responses/_invalid_syntax.get.json",
    "content": "I am not valid JSON!\n"
  },
  {
    "path": "spec/test_responses/_multimatch.get.json.1",
    "content": "{\n  \"multimatch\": 1\n}\n"
  },
  {
    "path": "spec/test_responses/_multimatch.get.json.2",
    "content": "{\n  \"multimatch\": 2\n}\n"
  },
  {
    "path": "spec/test_responses/_multimatch_query_param.get.html",
    "content": "//! params: {\"name\": \"Batman\", \"age\": \"30\"}\nBatman!\n\n//! params: {\"name\": \"Superman\", \"age\": \"30\"}\nSuperman!\n"
  },
  {
    "path": "spec/test_responses/_multiple_custom_header.get.json",
    "content": "//! customHeader: {\"Header-Key\": \"Header-Content\"}\n//! customHeader: {\"Header-Key2\": \"Header-Content2\"}\n"
  },
  {
    "path": "spec/test_responses/_multiple_get_responses.get.json",
    "content": "//! params: {\"foo\": \"baz\"}\n{\n    \"response\": \"response for baz\"\n}\n\n//! params: {\"foo\": \"bar\"}\n{\n    \"response\": \"response for bar\"\n}\n\n//! params: {\"foo\": \"apostrophe\"}\n{\n    \"response\": \"response with 'apostrophes'\"\n}\n\n//! params: {\"foo\": \"bar\", \"index\": 1}\n{\n    \"response\": \"response with index 1\"\n}\n"
  },
  {
    "path": "spec/test_responses/_multiple_responses.get.json",
    "content": "//! header: {\"authorization\": \"abc\"}\n{\n    \"response\": \"response for abc\"\n}\n\n//! header: {\"authorization\": \"123\"}\n{\n    \"response\": \"response for 123\"\n}"
  },
  {
    "path": "spec/test_responses/_multiple_responses.post.json",
    "content": "//! body: {\"email\": \"one@example.com\"}\n{\n    \"response\": \"response for one@example.com\"\n}\n\n//! body: {\"email\": \"two@example.com\"}\n{\n    \"response\": \"response for two@example.com\"\n}\n\n//! body: {\"email\": \"two@example.com\", \"topics\": [\"1\",\"2\"]}\n{\n    \"response\": \"response for two@example.com topics 1,2\"\n}"
  },
  {
    "path": "spec/test_responses/_multiple_responses_text.get.html",
    "content": "//! header: {\"authorization\": \"abc\"}\nresponse for abc\n\n//! header: {\"authorization\": \"123\"}\nresponse for 123\n\n//! header: {\"authorization\": \"html\"}\n<h1>response for html</h1>"
  },
  {
    "path": "spec/test_responses/_multiple_responses_text.post.html",
    "content": "//! body: {\"email\": \"one@example.com\"}\nresponse for one@example.com\n\n//! body: {\"email\": \"two@example.com\"}\nresponse for two@example.com"
  },
  {
    "path": "spec/test_responses/_multiple_responses_xml.post.xml",
    "content": "//! header: {\"action\": \"foo\"}\n<SOAP:Envelope><SOAP:Body><Foo Time=\"2015-01-22T08:30:00.000+05:30\"/></SOAP:Body></SOAP:Envelope>\n\n//! header: {\"action\": \"bar\"}\n<SOAP:Envelope><SOAP:Body><Bar Time=\"2015-01-22T08:30:00.000+05:30\"/></SOAP:Body></SOAP:Envelope>\n"
  },
  {
    "path": "spec/test_responses/_multiple_responses_xml_request_body.post.xml",
    "content": "//! body: <xml>a</xml>\n<xml>A</xml>\n\n//! body: <xml>b</xml>\n<xml>B</xml>\n"
  },
  {
    "path": "spec/test_responses/_multiple_type.get.csv",
    "content": "Jane Doe,Professor,(425) 123-4567,http://www.janedoe.com"
  },
  {
    "path": "spec/test_responses/_multiple_type.get.html",
    "content": "<type>html</type>"
  },
  {
    "path": "spec/test_responses/_multiple_type.get.js",
    "content": "var type = 'js';"
  },
  {
    "path": "spec/test_responses/_multiple_type.get.json",
    "content": "{\n\t\"type\": \"json\"\n}"
  },
  {
    "path": "spec/test_responses/_multiple_type.get.jsonld",
    "content": "{\n  \"@context\": \"http://schema.org/\",\n  \"@type\": \"Person\",\n  \"name\": \"Jane Doe\",\n  \"jobTitle\": \"Professor\",\n  \"telephone\": \"(425) 123-4567\",\n  \"url\": \"http://www.janedoe.com\"\n}"
  },
  {
    "path": "spec/test_responses/_multiple_type.get.nt",
    "content": "_:b0 <http://schema.org/name> \"Jane Doe\" ."
  },
  {
    "path": "spec/test_responses/_multiple_type.get.txt",
    "content": "text type"
  },
  {
    "path": "spec/test_responses/_response_with_url_param.post.json",
    "content": "//! body: {\"url\":\"http://example.com\"}\n{\n    \"response\": \"response for url in param\"\n}\n\n"
  },
  {
    "path": "spec/test_responses/_single_custom_header.get.json",
    "content": "//! customHeader: {\"Header-Key\": \"Header-Content\"}\n"
  },
  {
    "path": "spec/test_responses/_vendor_type.get.xml",
    "content": "//! statusCode  :  200   ,contentType  :     \"application/vnd.custom+xml\"   \n<xml>\n\t<created>1</created>\n</xml>"
  },
  {
    "path": "spec/test_responses/d/2/index.get.json",
    "content": "{\"not-wildcard\":1}"
  },
  {
    "path": "spec/test_responses/d/_commented.get.json",
    "content": "// to level comment\n{\n  // nested comment\n  \"no\":\"comments\"\n}\n"
  },
  {
    "path": "spec/test_responses/d/any/_bar.get.json",
    "content": "{\n  \"wildcard\": \"named_response\"\n}\n"
  },
  {
    "path": "spec/test_responses/d/any/index.get.json",
    "content": "{\n  \"wildcard\": 1\n}\n"
  },
  {
    "path": "spec/test_responses/d/any.get.html",
    "content": "d/any.get.json\n"
  },
  {
    "path": "spec/test_responses/d/e/index.get.html",
    "content": "d/e/index.get.html"
  },
  {
    "path": "spec/test_responses/d/index.get.html",
    "content": "d/index.get.json\n"
  },
  {
    "path": "spec/test_responses/d/multiple-accept-types/index.get.json",
    "content": "{\n  \"type\":\"json\"\n}\n"
  },
  {
    "path": "spec/test_responses/index.get.html",
    "content": "index.get.json\n"
  },
  {
    "path": "test/assert.sh",
    "content": "#!/bin/bash\n# assert.sh 1.0 - bash unit testing framework\n# Copyright (C) 2009, 2010, 2011, 2012 Robert Lehmann\n#\n# http://github.com/lehmannro/assert.sh\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nexport DISCOVERONLY=${DISCOVERONLY:-}\nexport DEBUG=${DEBUG:-}\nexport STOP=${STOP:-}\nexport INVARIANT=${INVARIANT:-}\n\nargs=\"$(getopt -n \"$0\" -l verbose,help,stop,discover,invariant vhxdi $*)\" \\\n|| exit -1\nfor arg in $args; do\n    case \"$arg\" in\n        -h)\n            echo \"$0 [-vxid] [--verbose] [--stop] [--invariant] [--discover]\"\n            echo \"`sed 's/./ /g' <<< \"$0\"` [-h] [--help]\"\n            exit 0;;\n        --help)\n            cat <<EOF\nUsage: $0 [options]\nLanguage-agnostic unit tests for subprocesses.\n\nOptions:\n  -v, --verbose    generate output for every individual test case\n  -x, --stop       stop running tests after the first failure\n  -i, --invariant  do not measure timings to remain invariant between runs\n  -d, --discover   collect test suites only, do not run any tests\n  -h               show brief usage information and exit\n  --help           show this help message and exit\nEOF\n            exit 0;;\n        -v|--verbose)\n            DEBUG=1;;\n        -x|--stop)\n            STOP=1;;\n        -i|--invariant)\n            INVARIANT=1;;\n        -d|--discover)\n            DISCOVERONLY=1;;\n    esac\ndone\n\nprintf -v _indent \"\\n\\t\" # local format helper\n\n_assert_reset() {\n    tests_ran=0\n    tests_failed=0\n    tests_errors=()\n    tests_starttime=\"$(date +%s.%N)\" # seconds_since_epoch.nanoseconds\n}\n\nassert_end() {\n    # assert_end [suite ..]\n    tests_endtime=\"$(date +%s.%N)\"\n    tests=\"$tests_ran ${*:+$* }tests\"\n    [[ -n \"$DISCOVERONLY\" ]] && echo \"collected $tests.\" && _assert_reset && return\n    [[ -n \"$DEBUG\" ]] && echo\n    [[ -z \"$INVARIANT\" ]] && report_time=\" in $(bc \\\n        <<< \"${tests_endtime%.N} - ${tests_starttime%.N}\" \\\n        | sed -e 's/\\.\\([0-9]\\{0,3\\}\\)[0-9]*/.\\1/' -e 's/^\\./0./')s\" \\\n        || report_time=\n\n    if [[ \"$tests_failed\" -eq 0 ]]; then\n        echo \"all $tests passed$report_time.\"\n    else\n        for error in \"${tests_errors[@]}\"; do echo \"$error\"; done\n        echo \"$tests_failed of $tests failed$report_time.\"\n    fi\n    tests_failed_previous=$tests_failed\n    _assert_reset\n    return $tests_failed_previous\n}\n\nassert() {\n    # assert <command> <expected stdout> [stdin]\n    (( tests_ran++ ))\n    [[ -n \"$DISCOVERONLY\" ]] && return\n    # printf required for formatting\n    printf -v expected \"x${2:-}\" # x required to overwrite older results\n    result=\"$(eval 2>/dev/null $1 <<< ${3:-})\"\n    # Note: $expected is already decorated\n    if [[ \"x$result\" == \"$expected\" ]]; then\n        [[ -n \"$DEBUG\" ]] && echo -n .\n        return\n    fi\n    [[ -n \"$DEBUG\" ]] && echo -n X\n    result=\"$(sed -e :a -e '$!N;s/\\n/\\\\n/;ta' <<< \"$result\")\"\n    [[ -z \"$result\" ]] && result=\"nothing\" || result=\"\\\"$result\\\"\"\n    [[ -z \"$2\" ]] && expected=\"nothing\" || expected=\"\\\"$2\\\"\"\n    failure=\"expected $expected${_indent}got $result\"\n    report=\"test #$tests_ran \\\"$1${3:+ <<< $3}\\\" failed:${_indent}$failure\"\n    tests_errors[$tests_failed]=\"$report\"\n    (( tests_failed++ ))\n    if [[ -n \"$STOP\" ]]; then\n        [[ -n \"$DEBUG\" ]] && echo\n        echo \"$report\"\n        exit 1\n    fi\n}\n\nassert_raises() {\n    # assert_raises <command> <expected code> [stdin]\n    (( tests_ran++ ))\n    [[ -n \"$DISCOVERONLY\" ]] && return\n    (eval $1 <<< ${3:-}) > /dev/null 2>&1\n    status=$?\n    expected=${2:-0}\n    if [[ \"$status\" -eq \"$expected\" ]]; then\n        [[ -n \"$DEBUG\" ]] && echo -n .\n        return\n    fi\n    [[ -n \"$DEBUG\" ]] && echo -n X\n    failure=\"program terminated with code $status instead of $expected\"\n    report=\"test #$tests_ran \\\"$1${3:+ <<< $3}\\\" failed:${_indent}$failure\"\n    tests_errors[$tests_failed]=\"$report\"\n    (( tests_failed++ ))\n    if [[ -n \"$STOP\" ]]; then\n        [[ -n \"$DEBUG\" ]] && echo\n        echo \"$report\"\n        exit 1\n    fi\n}\n\n_assert_reset\n"
  },
  {
    "path": "test/bin_test.sh",
    "content": "#!/bin/bash\n. assert.sh\n\n# start canned on port\n../bin/canned -p 8765 ../example &\nCPID=$!\nsleep 1\nassert \"lsof -i:8765 | grep node | awk '{print \\$1}'\" \"node\"\n\ncurl -sL -w \" %{http_code}\" http://127.0.0.1:8765/search | grep 200\nassert  \"echo $?\" \"0\"\n\ncurl -sL http://127.0.0.1:8765/search?search=specific | grep \"specific result\"\nassert \"echo $?\" \"0\"\n\ncurl -sL http://127.0.0.1:8765/search?search=apostrophe | grep \"There's something about Mary\"\nassert \"echo $?\" \"0\"\n\nkill $CPID\n\nassert_end examples\n\n\n"
  }
]