[
  {
    "path": ".babelrc.js",
    "content": "module.exports = {\n  presets : [[\n    \"@babel/preset-env\", {\n      loose : true,\n      useBuiltIns : \"entry\",\n      targets : {\n        node : \"6.11\" // Minimum supported version\n      }\n    }\n  ]],\n  plugins : [\n    [\"@babel/plugin-proposal-export-default-from\", { loose: true }],\n    [\"@babel/plugin-proposal-export-namespace-from\", { loose: true }],\n    [\"@babel/plugin-proposal-object-rest-spread\", { loose: true }],\n    [\"add-module-exports\", { loose: true }]\n  ]\n};\n"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\ncharset = utf-8\nindent_style = space\nindent_size = 2\nend_of_line = lf\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nmax_line_length=80\n\n[*.md]\ninsert_final_newline = false\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".eslintrc.js",
    "content": "module.exports = {\n  parser  : \"babel-eslint\",\n  extends : \"airbnb-base\",\n  rules   : {\n\n    // Enforce the consistent use of double quotes\n    quotes : [\"error\", \"double\", { avoidEscape: true }],\n\n    // Allow bitwise operators\n    \"no-bitwise\"  : \"off\",\n\n    // Allow the unary operators ++ and --\n    \"no-plusplus\" : \"off\",\n\n    // Require or disallow trailing commas\n    \"comma-dangle\": [\"error\", \"only-multiline\"],\n\n    // Disallow Reassignment of Function Parameters\n    \"no-param-reassign\" : [\"error\", { props: false }],\n\n    // Enforce consistent spacing between keys and values in object literal properties\n    \"key-spacing\" : [\"error\", {\n      singleLine : {\n        beforeColon : false,\n        afterColon  : true\n      },\n      multiLine : {\n        beforeColon : true,\n        afterColon  : true,\n        mode        : \"minimum\"\n      }\n    }],\n\n    // Disallow multiple spaces\n    \"no-multi-spaces\" : [\"error\", { ignoreEOLComments: true }],\n\n    // Require or disallow padding within blocks\n    \"padded-blocks\": [\"error\", { classes: \"always\" }]\n  }\n};\n"
  },
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\n*.log\nnpm-debug.log*\n\n# Dependencies\nnode_modules\nyarn.lock\n\n# Coverage\n/coverage\n\n# Build\n/lib\n\n# OS - OSX\n.DS_Store\n\n# OS - Windows\nThumbs.db\nehthumbs.db\n"
  },
  {
    "path": ".nvmrc",
    "content": "v6.11.2\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nsudo: false\n\nnode_js:\n  - \"6\"\n  - \"8\"\n  - \"10\"\n\nbefore_install:\n  - if [[ `npm -v` != 6* ]]; then npm i -g npm@6; fi\n\ninstall:\n  - npm install -g codecov\n  - npm run bootstrap\n\nscript:\n  - npm run style\n  - npm run coverage\n\nafter_success:\n  - codecov\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nSee https://github.com/yvele/azure-function-express/releases\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\n[Setup](#setup) |\n[Commands](#command) |\n[Unit Testing](#test) |\n[Git Commit Guidelines](#commit)\n\n## <a name=\"setup\"></a> Setup\n\n```sh\n$ npm run bootstrap\n```\n\n## <a name=\"test\"></a> Unit Testing\n\n### Running tests\n\n```sh\n$ npm run test\n```\n\nwith coverage:\n\n```sh\n$ npm run coverage\n```\n\n### Writing tests\n\nTest can be asserted with [Should.js](https://shouldjs.github.io) :\n\n```js\ntest().should.be.type(\"string\");\n\ntest().should.eql({ foo: \"foo\", bar: \"bar\" });\n\ntest().should.be.equal(\"foobar\");\n```\n\n```js\nimport should from \"should\";\n\nshould.throws(() => {\n  throw new ArgumentError();\n}, /ArgumentError/);\n```\n\n```js\nit(\"Should fail\", () => {\n  return testAsync().should.be.rejectedWith(\"Error message\");\n});\n```\n\n```js\nimport should from \"should\";\n\nshould.equal(test(), null);\n\nshould(\"foobar\" == \"foobar\").be.ok;\n```\n\n## <a name=\"command\"></a> Commands\n\nAll commands should be run at the root path of the project.\n\n| Command                      | Description       |\n|------------------------------|-------------------|\n| `$ npm run bootstrap`        | Setup the project for development\n| `$ npm run build`            | Build (with babel)\n| `$ npm run clean`            | Delete all temporary files (NPM, build, etc.)\n| `$ npm run clean:build`      | Delete build files (babel, etc.)\n| `$ npm run clean:npm`        | Delete NPM generated files (node_modules, logs, etc.)\n| `$ npm run coverage`         | Run unit tests with code coverage\n| `$ npm run style`            | Check code style\n| `$ npm run test`             | Run tests\n| `$ npm run validate`         | Check the code is valid by checking code style and running tests\n\n## <a name=\"commit\"></a> Git Commit Guidelines\n\nWrite meaningful and straightforward commit summaries.\n\n```sh\n# Bad\ngit commit assets -m 'change something' # ORLY? What change?\n\n# Good\ngit commit assets -m 'style(css): Switch `reset.css` to `normalize.css`'\n```\n\nAvoid long commit summaries by limiting the maximum characters to `50`.\n\n> Detailed descriptions should go on the commit message.\n\n```sh\n# Bad\ngit commit assets/javascripts -m 'Add `FIXME` note to dropdown module because it wasnt working on IE8'\n\n# Good\ngit commit assets/javascripts -m 'style(dropdown): Add `FIXME` note to dropdown module'\n```\n\nWrite commit summaries in the imperative, present tense.\n\n```sh\n# Bad\ngit commit scripts -m 'Fixed CI integration'\n\n# Bad\ngit commit scripts -m 'Fixes CI integration'\n\n# Bad\ngit commit scripts -m 'Fixing CI integration'\n\n# Good\ngit commit scripts -m 'fix(ci): Fix CI integration'\n```\n\nUse proper english writing on commits.\n\n> Because SCM is also code documentation.\n\n```sh\n# Bad (Everything in lower case, no proper punctuation and \"whatever\" really?)\ngit commit assets/stylesheets -m 'update clearfix or whatever'\n\n# Bad (Why are you screaming?)\ngit commit assets/stylesheets -m 'UPDATE CLEARFIX'\n\n# Good (Meaningful commit summary with proper orthography)\ngit commit assets/stylesheets -m 'fix(clearfix): Update clearfix implementation to use a more modern approach'\n```\n\n### Type\n\nMust be one of the following:\n\n| Prefix      | Description   |\n|-------------|---------------|\n| `feat`      | A new feature\n| `fix`       | A bug fix\n| `docs`      | Documentation only changes\n| `style`     | Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)\n| `refactor ` | A code change that neither fixes a bug or adds a feature\n| `test`      | Adding missing tests\n| `chore`     | Changes to the build process or auxiliary tools and libraries such as documentation generation\n\n### Scope\nThe scope could be anything specifying place of the commit change. For example `readme`,\n`package.json`, `OptionManager`, `docs/Components`, etc...\n\n### Subject\nThe subject contains succinct description of the change:\n\n* Use the imperative, present tense: \"change\" not \"changed\" nor \"changes\"\n* Capitalize first letter\n* No dot (.) at the end\n\n### Body\nJust as in the **subject**, use the imperative, present tense: \"change\" not \"changed\" nor \"changes\".\nThe body should include the motivation for the change and contrast this with previous behavior.\n\n### About\n\nThose rules have been inspired by AngularJS [contributing page](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md) and Netshoes [styleguide](https://github.com/netshoes/styleguide).\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# azure-function-express\n\n<a href=\"https://azure.microsoft.com/en-us/services/functions/\">\n  <img align=\"right\" alt=\"Function logo\" src=\"docs/media/function.png\" title=\"Function\" width=\"150\"/>\n</a>\n\n> Allows Express usage with Azure Function\n\n[![npm version](https://img.shields.io/npm/v/azure-function-express.svg)](https://www.npmjs.com/package/azure-function-express)\n[![Node](https://img.shields.io/badge/node-v6-blue.svg)](https://github.com/Azure/azure-webjobs-sdk-script/issues/2036#issuecomment-336942961)\n![Node](https://img.shields.io/badge/node-v8-blue.svg)\n![Node](https://img.shields.io/badge/node-v10-blue.svg)\n[![Travis Status](https://img.shields.io/travis/yvele/azure-function-express/master.svg?label=travis)](https://travis-ci.org/yvele/azure-function-express)\n[![Coverage Status](https://img.shields.io/codecov/c/github/yvele/azure-function-express/master.svg)](https://codecov.io/github/yvele/azure-function-express)\n[![MIT licensed](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)\n\n\n## Description\n\n[Connect](https://github.com/senchalabs/connect) your [Express](https://expressjs.com) application to an [Azure Function handler](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node), and make seamless usage of [all middlewares](http://expressjs.com/en/guide/using-middleware.html) you are already familiar with.\n\n\n## Usage\n\nIn your `index.js`:\n\n```js\nconst createHandler = require(\"azure-function-express\").createHandler;\nconst express = require(\"express\");\n\n// Create express app as usual\nconst app = express();\napp.get(\"/api/:foo/:bar\", (req, res) => {\n  res.json({\n    foo  : req.params.foo,\n    bar  : req.params.bar\n  });\n});\n\n// Binds the express app to an Azure Function handler\nmodule.exports = createHandler(app);\n```\n\nMake sure you are binding `req` and `res` in your `function.json`:\n\n```json\n{\n  \"bindings\": [{\n    \"authLevel\" : \"anonymous\",\n    \"type\"      : \"httpTrigger\",\n    \"direction\" : \"in\",\n    \"name\"      : \"req\",\n    \"route\"     : \"foo/{bar}/{id}\"\n  }, {\n    \"type\"      : \"http\",\n    \"direction\" : \"out\",\n    \"name\"      : \"res\"\n  }]\n}\n```\n\nTo allow Express handles all HTTP routes itself you may set a glob star route in a single root `function.json`:\n\n```json\n{\n  \"bindings\": [{\n    \"authLevel\" : \"anonymous\",\n    \"type\"      : \"httpTrigger\",\n    \"direction\" : \"in\",\n    \"name\"      : \"req\",\n    \"route\"     : \"{*segments}\"\n  }, {\n    \"type\"      : \"http\",\n    \"direction\" : \"out\",\n    \"name\"      : \"res\"\n  }]\n}\n```\n\nNote that `segments` is not used and could be anything. See [Azure Function documentation](https://github.com/Azure/azure-webjobs-sdk-script/wiki/Http-Functions).\n\nAll examples [here](/examples/).\n\n\n## Context\n\nAll native Azure Functions [context](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object) properties, except `done`, are exposed through `req.context`.\n\nAs en example, you can [log](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#writing-trace-output-to-the-console) using:\n\n```js\napp.get(\"/api/hello-world\", (req, res) => {\n  req.context.log({ hello: \"world\" });\n  ...\n});\n```\n\n\n## Runtime compatibility\n\nSupported Node version are:\n - Node 6.11.2 ([first node version supported by Azure Functions](https://github.com/Azure/azure-webjobs-sdk-script/issues/2036#issuecomment-336942961))\n - Node 8 (LTS)\n - Node 10\n\nAzure Functions runtime v1 and v2 beta are both supported.\n\n\n## License\n\n[Apache 2.0](LICENSE) © Yves Merlicco\n"
  },
  {
    "path": "docs/azure-function.md",
    "content": "# Azure Function\n\n## Documentation\n\n- Documentation\n  - [Node Documentation](https://azure.microsoft.com/en-us/documentation/articles/functions-reference-node/)\n  - [WebJobs SDK Wiki](https://github.com/Azure/azure-webjobs-sdk-script/wiki)\n- Changelog\n  - [Azure WebJobs SDK Releases](https://github.com/Azure/azure-webjobs-sdk-script/releases)\n  - [Azure WebJobs SDK Changelog](https://github.com/Azure/azure-webjobs-sdk/wiki/Release-Notes) (outdated!)\n- [Data binding](https://azure.microsoft.com/en-us/documentation/articles/functions-bindings-http-webhook/)\n\n## Response example\n\n```js\ncontext.res = { status: 202, body: \"You successfully ordered more coffee!\" };\n```\n\n## Context example\n\n```js\ncontext = {\n  invocationId  : 'f0f6e586-0b79-4407-aa53-97919f45eba6',\n  log           : [Function],\n  bindings: {\n    req: {\n      originalUrl: 'https://my-deployment-id.azurewebsites.net/api/get',\n      method: 'POST',\n      query: {},\n      headers: {\n        \"connection\"            : \"Keep-Alive\",\n        \"authorization\"         : \"Bearer eyJhbGciOiJIUzI1NiIsIn...\",\n        \"host\"                  : \"my-deployment-id.azurewebsites.net\",\n        \"max-forwards\"          : \"10\",\n        \"x-liveupgrade\"         : \"1\",\n        \"x-arr-log-id\"          : \"fe0ba896-00d0-4ce7-a790-c8978fcaa1fd\",\n        \"disguised-host\"        : \"my-deployment-id.azurewebsites.net\",\n        \"x-site-deployment-id\"  : \"my-deployment-id\",\n        \"was-default-hostname\"  : \"my-deployment-id.azurewebsites.net\",\n        \"x-original-url\"        : \"/api/get\",\n        \"x-forwarded-for\"       : \"92.103.167.115:57996\",\n        \"x-arr-ssl\"             : \"2048|256|C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=Microsoft IT, CN=Microsoft IT SSL SHA2|CN=*.azurewebsites.net\",\n      },\n\n      // form-data\n      body: \"------WebKitFormBoundaryUPAtNZMGi7yHMoIX\\r\\nContent-Disposition: form-data; name=\\\"a\\\"\\r\\n\\r\\nb\\r\\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX\\r\\nContent-Disposition: form-data; name=\\\"aa\\\"\\r\\n\\r\\nbb\\r\\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX--\\r\\n\",\n      rawBody: \"------WebKitFormBoundaryUPAtNZMGi7yHMoIX\\r\\nContent-Disposition: form-data; name=\\\"a\\\"\\r\\n\\r\\nb\\r\\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX\\r\\nContent-Disposition: form-data; name=\\\"aa\\\"\\r\\n\\r\\nbb\\r\\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX--\\r\\n\",\n\n      // x-www-form-urlencoded\n      body: \"foo=bar&fou=barre\",\n      rawBody: \"foo=bar&fou=barre\",\n\n      // raw --> application/json\n      \"body\": {\n        \"foo\": \"bar\",\n        \"fou\": \"barre\"\n      },\n      \"rawBody\": \"{\\n    \\\"foo\\\": \\\"bar\\\",\\n    \\\"fou\\\": \\\"barre\\\"\\n    \\n}\",\n    }\n  },\n  bind: [Function],\n  bindingData: {\n    req: 'Method: POST, RequestUri: \\'https://my-deployment-id.azurewebsites.net/api/get\\', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:\\r\\n{\\r\\n  Connection: Keep-Alive\\r\\n  Accept: application/json\\r\\n  Accept: */*\\r\\n  Accept-Encoding: gzip\\r\\n  Accept-Encoding: deflate\\r\\n  Accept-Encoding: br\\r\\n  Accept-Language: fr\\r\\n  Accept-Language: en-US; q=0.8\\r\\n  Accept-Language: en; q=0.6\\r\\n  Host: my-deployment-id.azurewebsites.net\\r\\n  Max-Forwards: 10\\r\\n  Referer: https://functions.azure.com/?trustedAuthority=https://portal.azure.com/\\r\\n  User-Agent: Mozilla/5.0\\r\\n  User-Agent: (Macintosh; Intel Mac OS X 10_11_6)\\r\\n  User-Agent: AppleWebKit/537.36\\r\\n  User-Agent: (KHTML, like Gecko)\\r\\n  User-Agent: Chrome/52.0.2743.116\\r\\n  User-Agent: Safari/537.36\\r\\n  x-functions-key: G/6oEOahmJgI5Y1jfstIEpd1ygWwvERuylzEOnvUTUapJUsCYoEAyQ==\\r\\n  Origin: https://functions.azure.com\\r\\n  X-LiveUpgrade: 1\\r\\n  X-ARR-LOG-ID: 865e04b5-923e-496a-a759-b0b36ab5b99b\\r\\n  DISGUISED-HOST: my-deployment-id.azurewebsites.net\\r\\n  X-SITE-DEPLOYMENT-ID: my-deployment-id\\r\\n  WAS-DEFAULT-HOSTNAME: my-deployment-id.azurewebsites.net\\r\\n  X-Original-URL: /api/get\\r\\n  X-Forwarded-For: 92.103.167.115:58342\\r\\n  X-ARR-SSL: 2048|256|C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=Microsoft IT, CN=Microsoft IT SSL SHA2|CN=*.azurewebsites.net\\r\\n  Content-Length: 0\\r\\n  Content-Type: plain/text\\r\\n}',\n    InvocationId: 'f0f6e586-0b79-4407-aa53-97919f45eba6'\n  },\n  done  : [Function],\n  res   : {}\n}\n```\n"
  },
  {
    "path": "examples/all-routes/function.json",
    "content": "{\n  \"disabled\" : false,\n  \"bindings\" : [{\n    \"authLevel\" : \"anonymous\",\n    \"type\"      : \"httpTrigger\",\n    \"direction\" : \"in\",\n    \"name\"      : \"req\",\n    \"route\"     : \"{*segments}\"\n  }, {\n    \"type\"      : \"http\",\n    \"direction\" : \"out\",\n    \"name\"      : \"res\"\n  }]\n}\n"
  },
  {
    "path": "examples/all-routes/index.js",
    "content": "const createAzureFunctionHandler = require(\"azure-function-express\").createAzureFunctionHandler;\nconst express = require(\"express\");\n\n// Create express app as usual\nconst app = express();\napp.get(\"/api/:foo\", (req, res) => res.json({ foo: req.params.foo }));\napp.get(\"/api/:foo/:bar\", (req, res) => res.json({ foo: req.params.foo, bar: req.params.bar }));\n\n// Binds the express app to an Azure Function handler\nmodule.exports = createAzureFunctionHandler(app);\n"
  },
  {
    "path": "examples/basic/function.json",
    "content": "{\n  \"bindings\": [{\n    \"authLevel\" : \"anonymous\",\n    \"type\"      : \"httpTrigger\",\n    \"direction\" : \"in\",\n    \"name\"      : \"req\",\n    \"route\"     : \"foo/{bar}/{id}\"\n  }, {\n    \"type\"      : \"http\",\n    \"direction\" : \"out\",\n    \"name\"      : \"res\"\n  }]\n}\n"
  },
  {
    "path": "examples/basic/index.js",
    "content": "const createAzureFunctionHandler = require(\"azure-function-express\").createAzureFunctionHandler;\nconst express = require(\"express\");\n\n// Create express app as usual\nconst app = express();\napp.get(\"/api/:foo/:bar\", (req, res) => {\n  res.json({\n    foo  : req.params.foo,\n    bar  : req.params.bar\n  });\n});\n\n// Binds the express app to an Azure Function handler\nmodule.exports = createAzureFunctionHandler(app);\n"
  },
  {
    "path": "examples/basic-module/function.json",
    "content": "{\n  \"bindings\": [{\n    \"authLevel\" : \"anonymous\",\n    \"type\"      : \"httpTrigger\",\n    \"direction\" : \"in\",\n    \"name\"      : \"req\",\n    \"route\"     : \"foo/{bar}/{id}\"\n  }, {\n    \"type\"      : \"http\",\n    \"direction\" : \"out\",\n    \"name\"      : \"res\"\n  }]\n}\n"
  },
  {
    "path": "examples/basic-module/index.js",
    "content": "import { createAzureFunctionHandler } from \"azure-function-express\";\nimport express from \"express\";\n\n// Create express app as usual\nconst app = express();\napp.get(\"/api/:foo/:bar\", (req, res) => {\n  res.json({\n    foo  : req.params.foo,\n    bar  : req.params.bar\n  });\n});\n\n// Binds the express app to an Azure Function handler\nexport default createAzureFunctionHandler(app);\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"azure-function-express\",\n  \"version\": \"2.0.0\",\n  \"sideEffects\": false,\n  \"description\": \"Allows Express usage with Azure Function\",\n  \"keywords\": [\n    \"azure function\",\n    \"express\",\n    \"connect\",\n    \"azure\",\n    \"koa\"\n  ],\n  \"homepage\": \"https://github.com/yvele/azure-function-express\",\n  \"bugs\": {\n    \"url\": \"https://github.com/yvele/azure-function-express/issues\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/yvele/azure-function-express\"\n  },\n  \"files\": [\n    \"lib/\"\n  ],\n  \"main\": \"lib/index.js\",\n  \"author\": {\n    \"name\": \"Merlicco Yves\",\n    \"email\": \"merlicco@gmail.com\"\n  },\n  \"contributors\": [\n    \"Yves Merlicco <merlicco@gmail.com>\"\n  ],\n  \"scripts\": {\n    \"bootstrap\": \"npm install\",\n    \"build\": \"rm -rf lib && babel src --out-dir lib\",\n    \"clean\": \"rm -rf lib coverage node_modules\",\n    \"clean:build\": \"rm -rf lib\",\n    \"clean:npm\": \"rm -rf node_modules\",\n    \"coverage\": \"jest --coverage\",\n    \"publish\": \"npm run validate && npm run build && npm publish\",\n    \"style\": \"eslint src/**\",\n    \"test\": \"jest\",\n    \"validate\": \"npm run style && npm run coverage\"\n  },\n  \"engines\": {\n    \"node\": \">=6.11.2 <11\",\n    \"npm\": \">=6\"\n  },\n  \"devDependencies\": {\n    \"@babel/cli\": \"^7.0.0\",\n    \"@babel/core\": \"^7.0.0\",\n    \"@babel/plugin-proposal-export-default-from\": \"^7.0.0\",\n    \"@babel/plugin-proposal-export-namespace-from\": \"^7.0.0\",\n    \"@babel/plugin-proposal-object-rest-spread\": \"^7.0.0\",\n    \"@babel/preset-env\": \"^7.0.0\",\n    \"@babel/register\": \"^7.0.0\",\n    \"babel-core\": \"^7.0.0-bridge.0\",\n    \"babel-eslint\": \"^9.0.0\",\n    \"babel-plugin-add-module-exports\": \"^0.2.1\",\n    \"eslint\": \"^5.5.0\",\n    \"eslint-config-airbnb-base\": \"^13.1.0\",\n    \"eslint-plugin-import\": \"^2.14.0\",\n    \"express\": \"^4.16.3\",\n    \"jest\": \"^23.5.0\"\n  }\n}\n"
  },
  {
    "path": "src/ExpressAdapter.js",
    "content": "import EventEmitter from \"events\";\nimport OutgoingMessage from \"./OutgoingMessage\";\nimport IncomingMessage from \"./IncomingMessage\";\n\n/**\n * @param {Object} context Azure Function native context object\n * @throws {Error}\n * @private\n */\nfunction assertContext(context) {\n  if (!context) {\n    throw new Error(\"context is null or undefined\");\n  }\n\n  if (!context.bindings) {\n    throw new Error(\"context.bindings is null or undefined\");\n  }\n\n  if (!context.bindings.req) {\n    throw new Error(\"context.bindings.req is null or undefined\");\n  }\n\n  if (!context.bindings.req.originalUrl) {\n    throw new Error(\"context.bindings.req.originalUrl is null or undefined\");\n  }\n}\n\n/**\n * Express adapter allowing to handle Azure Function requests by wrapping in request events.\n *\n * @class\n * @fires request\n */\nexport default class ExpressAdapter extends EventEmitter {\n\n  /**\n   * @param {Object=} requestListener Request listener (typically an express/connect instance)\n   */\n  constructor(requestListener) {\n    super();\n\n    if (requestListener !== undefined) {\n      this.addRequestListener(requestListener);\n    }\n  }\n\n  /**\n   * Adds a request listener (typically an express/connect instance).\n   *\n   * @param {Object} requestListener Request listener (typically an express/connect instance)\n   */\n  addRequestListener(requestListener) {\n    this.addListener(\"request\", requestListener);\n  }\n\n  /**\n   * Handles Azure Function requests.\n   *\n   * @param {Object} context Azure context object for a single request\n   */\n  handleAzureFunctionRequest(context) {\n    assertContext(context);\n\n    // 1. Context basic initialization\n    context.res = context.res || {};\n\n    // 2. Wrapping\n    const req = new IncomingMessage(context);\n    const res = new OutgoingMessage(context);\n\n    // 3. Synchronously calls each of the listeners registered for the event\n    this.emit(\"request\", req, res);\n  }\n\n  /**\n   * Create function ready to be exposed to Azure Function for request handling.\n   *\n   * @returns {function(context: Object)} Azure Function handle\n   */\n  createAzureFunctionHandler() {\n    return this.handleAzureFunctionRequest.bind(this);\n  }\n\n}\n"
  },
  {
    "path": "src/IncomingMessage.js",
    "content": "/* eslint-disable no-underscore-dangle */\nimport EventEmitter from \"events\";\n\nconst NOOP = () => {};\n\nfunction removePortFromAddress(address) {\n  return address\n    ? address.replace(/:[0-9]*$/, \"\")\n    : address;\n}\n\n/**\n * Create a fake connection object\n *\n * @param {Object} context Raw Azure context object for a single HTTP request\n * @returns {object} Connection object\n */\nfunction createConnectionObject(context) {\n  const { req } = context.bindings;\n  const xForwardedFor = req.headers ? req.headers[\"x-forwarded-for\"] : undefined;\n\n  return {\n    encrypted     : req.originalUrl && req.originalUrl.toLowerCase().startsWith(\"https\"),\n    remoteAddress : removePortFromAddress(xForwardedFor)\n  };\n}\n\n/**\n * Copy usefull context properties from the native context provided by the Azure Function engine\n *\n * See:\n * - https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object\n * - https://github.com/christopheranderson/azure-functions-typescript/blob/master/src/context.d.ts\n *\n * @param {Object} context Raw Azure context object for a single HTTP request\n * @returns {Object} Filtered context\n */\nfunction sanitizeContext(context) {\n  const sanitizedContext = {\n    ...context,\n    log : context.log.bind(context)\n  };\n\n  // We don't want the developper to mess up express flow\n  // See https://github.com/yvele/azure-function-express/pull/12#issuecomment-336733540\n  delete sanitizedContext.done;\n\n  return sanitizedContext;\n}\n\n/**\n * Request object wrapper\n *\n * @private\n */\nexport default class IncomingMessage extends EventEmitter {\n\n  /**\n   * Note: IncomingMessage assumes that all HTTP in is binded to \"req\" property\n   *\n   * @param {Object} context Sanitized Azure context object for a single HTTP request\n   */\n  constructor(context) {\n    super();\n\n    Object.assign(this, context.bindings.req); // Inherit\n\n    this.url = this.originalUrl;\n    this.headers = this.headers || {}; // Should always have a headers object\n\n    this._readableState = { pipesCount: 0 }; // To make unpipe happy\n    this.resume = NOOP;\n    this.socket = { destroy: NOOP };\n    this.connection = createConnectionObject(context);\n\n    this.context = sanitizeContext(context); // Specific to Azure Function\n  }\n\n}\n"
  },
  {
    "path": "src/OutgoingMessage.js",
    "content": "/* eslint-disable no-magic-numbers, no-underscore-dangle */\nimport { OutgoingMessage as NativeOutgoingMessage } from \"http\";\nimport statusCodes from \"./statusCodes\";\n\n/**\n * @param {Object|string|Buffer} body Express/connect body object\n * @param {string} encoding\n * @returns {Object|string} Azure Function body\n */\nfunction convertToBody(body, encoding) {\n  // This may be removed on Azure Function native support for Buffer\n  // https://github.com/Azure/azure-webjobs-sdk-script/issues/814\n  // https://github.com/Azure/azure-webjobs-sdk-script/pull/781\n  return Buffer.isBuffer(body)\n    ? body.toString(encoding)\n    : body;\n}\n\n/**\n * @param {Object} context Azure Function context\n * @param {string|Buffer} data\n * @param {string} encoding\n * @this {OutgoingMessage}\n */\nfunction end(context, data, encoding) {\n  // 1. Write head\n  this.writeHead(this.statusCode); // Make jshttp/on-headers able to trigger\n\n  // 2. Return raw body to Azure Function runtime\n  context.res.body = convertToBody(data, encoding);\n  context.res.isRaw = true;\n  context.done();\n}\n\n/**\n * https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers\n * Original implementation: https://github.com/nodejs/node/blob/v6.x/lib/_http_server.js#L160\n *\n * @param {Object} context Azure Function context\n * @param {number} statusCode\n * @param {string} statusMessage\n * @param {Object} headers\n * @this {OutgoingMessage}\n */\nfunction writeHead(context, statusCode, statusMessage, headers) {\n  // 1. Status code\n  statusCode |= 0; // eslint-disable-line no-param-reassign\n  if (statusCode < 100 || statusCode > 999) {\n    throw new RangeError(`Invalid status code: ${statusCode}`);\n  }\n\n  // 2. Status message\n  if (typeof statusMessage === \"string\") {\n    this.statusMessage = statusMessage;\n  } else {\n    this.statusMessage = statusCodes[statusCode] || \"unknown\";\n  }\n\n  // 3. Headers\n  if (typeof statusMessage === \"object\" && typeof headers === \"undefined\") {\n    headers = statusMessage; // eslint-disable-line no-param-reassign\n  }\n  if (this._headers) {\n    // Slow-case: when progressive API and header fields are passed.\n    if (headers) {\n      const keys = Object.keys(headers);\n      for (let i = 0; i < keys.length; i++) {\n        const k = keys[i];\n        if (k) {\n          this.setHeader(k, headers[k]);\n        }\n      }\n    }\n    // only progressive api is used\n    headers = this._renderHeaders(); // eslint-disable-line no-param-reassign\n  }\n\n  // 4. Sets everything\n  context.res.status = statusCode;\n  // In order to uniformize node 6 behaviour with node 8 and 10,\n  // we want to never have undefined headers, but instead empty object\n  context.res.headers = headers || {};\n}\n\n/**\n * OutgoingMessage mock based on https://github.com/nodejs/node/blob/v6.x\n *\n * Note: This implementation is only meant to be working with Node.js v6.x\n *\n * @private\n */\nexport default class OutgoingMessage extends NativeOutgoingMessage {\n\n  /**\n   * Original implementation: https://github.com/nodejs/node/blob/v6.x/lib/_http_outgoing.js#L48\n   */\n  constructor(context) {\n    super();\n    this._headers = null;\n    this._headerNames = {};\n    this._removedHeader = {};\n    this._hasBody = true;\n\n    // Those methods cannot be prototyped because express explicitelly overrides __proto__\n    // See https://github.com/expressjs/express/blob/master/lib/middleware/init.js#L29\n    this.writeHead = writeHead.bind(this, context);\n    this.end = end.bind(this, context);\n  }\n\n}\n"
  },
  {
    "path": "src/createAzureFunctionHandler.js",
    "content": "import ExpressAdapter from \"./ExpressAdapter\";\n\n/**\n * Creates a function ready to be exposed to Azure Function for request handling.\n *\n * @param {Object} requestListener Request listener (typically an express/connect instance)\n * @returns {function(context: Object)} Azure Function handle\n */\nexport default function createAzureFunctionHandler(requestListener) {\n  const adapter = new ExpressAdapter(requestListener);\n  return adapter.createAzureFunctionHandler();\n}\n"
  },
  {
    "path": "src/index.js",
    "content": "import createAzureFunctionHandler from \"./createAzureFunctionHandler\";\n\nexport ExpressAdapter from \"./ExpressAdapter\";\nexport { createAzureFunctionHandler, createAzureFunctionHandler as createHandler };\n"
  },
  {
    "path": "src/statusCodes.js",
    "content": "export default {\n  100 : \"Continue\",\n  101 : \"Switching Protocols\",\n  102 : \"Processing\",                 // RFC 2518, obsoleted by RFC 4918\n  200 : \"OK\",\n  201 : \"Created\",\n  202 : \"Accepted\",\n  203 : \"Non-Authoritative Information\",\n  204 : \"No Content\",\n  205 : \"Reset Content\",\n  206 : \"Partial Content\",\n  207 : \"Multi-Status\",               // RFC 4918\n  208 : \"Already Reported\",\n  226 : \"IM Used\",\n  300 : \"Multiple Choices\",\n  301 : \"Moved Permanently\",\n  302 : \"Found\",\n  303 : \"See Other\",\n  304 : \"Not Modified\",\n  305 : \"Use Proxy\",\n  307 : \"Temporary Redirect\",\n  308 : \"Permanent Redirect\",         // RFC 7238\n  400 : \"Bad Request\",\n  401 : \"Unauthorized\",\n  402 : \"Payment Required\",\n  403 : \"Forbidden\",\n  404 : \"Not Found\",\n  405 : \"Method Not Allowed\",\n  406 : \"Not Acceptable\",\n  407 : \"Proxy Authentication Required\",\n  408 : \"Request Timeout\",\n  409 : \"Conflict\",\n  410 : \"Gone\",\n  411 : \"Length Required\",\n  412 : \"Precondition Failed\",\n  413 : \"Payload Too Large\",\n  414 : \"URI Too Long\",\n  415 : \"Unsupported Media Type\",\n  416 : \"Range Not Satisfiable\",\n  417 : \"Expectation Failed\",\n  418 : \"I\\\"m a teapot\",              // RFC 2324\n  421 : \"Misdirected Request\",\n  422 : \"Unprocessable Entity\",       // RFC 4918\n  423 : \"Locked\",                     // RFC 4918\n  424 : \"Failed Dependency\",          // RFC 4918\n  425 : \"Unordered Collection\",       // RFC 4918\n  426 : \"Upgrade Required\",           // RFC 2817\n  428 : \"Precondition Required\",      // RFC 6585\n  429 : \"Too Many Requests\",          // RFC 6585\n  431 : \"Request Header Fields Too Large\", // RFC 6585\n  451 : \"Unavailable For Legal Reasons\",\n  500 : \"Internal Server Error\",\n  501 : \"Not Implemented\",\n  502 : \"Bad Gateway\",\n  503 : \"Service Unavailable\",\n  504 : \"Gateway Timeout\",\n  505 : \"HTTP Version Not Supported\",\n  506 : \"Variant Also Negotiates\",    // RFC 2295\n  507 : \"Insufficient Storage\",       // RFC 4918\n  508 : \"Loop Detected\",\n  509 : \"Bandwidth Limit Exceeded\",\n  510 : \"Not Extended\",               // RFC 2774\n  511 : \"Network Authentication Required\" // RFC 6585\n};\n"
  },
  {
    "path": "test/ExpressAdapter.test.js",
    "content": "import { ExpressAdapter } from \"../src\";\n\nconst NOOP = () => {};\n\ndescribe(\"ExpressAdapter\", () => {\n\n  it(\"Should work\", done => {\n\n    let listenerCalled = false;\n\n    const adapter = new ExpressAdapter((req, res) => {\n      listenerCalled = true;\n      expect(req.url).toBe(\"http://foo.com/bar\");\n      res.statusCode = 200;\n      res.end(\"body\", \"utf8\");\n    });\n\n    const context = {\n      log       : NOOP,\n      bindings  : { req: { originalUrl: \"http://foo.com/bar\" } },\n      done      : () => {\n        expect(listenerCalled).toBe(true);\n\n        // Response that will be sent to Azure Function runtime\n        expect(context.res).toEqual({\n          body    : \"body\",\n          headers : {},\n          isRaw   : true,\n          status  : 200\n        });\n        done();\n      }\n    };\n\n    const handler = adapter.createAzureFunctionHandler();\n    handler(context);\n  });\n\n  it(\"Should work with a buffer\", done => {\n\n    let listenerCalled = false;\n\n    const adapter = new ExpressAdapter((req, res) => {\n      listenerCalled = true;\n      expect(req.url).toBe(\"http://foo.com/bar\");\n      res.statusCode = 200;\n      res.end(Buffer.from(\"body\", \"utf8\"), \"utf8\");\n    });\n\n    const context = {\n      log       : NOOP,\n      bindings  : { req: { originalUrl: \"http://foo.com/bar\" } },\n      done      : () => {\n        expect(listenerCalled).toBe(true);\n\n        // Response that will be sent to Azure Function runtime\n        expect(context.res).toEqual({\n          body    : \"body\",\n          headers : {},\n          isRaw   : true,\n          status  : 200\n        });\n        done();\n      }\n    };\n\n    const handler = adapter.createAzureFunctionHandler();\n    handler(context);\n  });\n\n  describe(\"handleAzureFunctionRequest\", () => {\n\n    it(\"Should throws with no context\", () => {\n      const adapter = new ExpressAdapter();\n      expect(() => {\n        adapter.handleAzureFunctionRequest();\n      }).toThrowError(/^context is null or undefined/);\n    });\n\n    it(\"Should throws with a context with no bindings\", () => {\n      const adapter = new ExpressAdapter();\n      expect(() => {\n        adapter.handleAzureFunctionRequest({});\n      }).toThrowError(/^context.bindings is null or undefined/);\n    });\n\n    it(\"Should throws with a context with no req binding\", () => {\n      const adapter = new ExpressAdapter();\n      expect(() => {\n        adapter.handleAzureFunctionRequest({ bindings: {} });\n      }).toThrowError(/^context.bindings.req is null or undefined/);\n    });\n\n    it(\"Should throws with a context with a req binding having no originalUrl\", () => {\n      const adapter = new ExpressAdapter();\n      expect(() => {\n        adapter.handleAzureFunctionRequest({ bindings: { req: {} } });\n      }).toThrowError(/^context.bindings.req.originalUrl is null or undefined/);\n    });\n\n  });\n\n});\n"
  },
  {
    "path": "test/IncomingMessage.test.js",
    "content": "import IncomingMessage from \"../src/IncomingMessage\";\n\ndescribe(\"IncomingMessage\", () => {\n\n  it(\"Should work\", () => {\n\n    const context = {\n      bindings : {\n        req : {\n          originalUrl : \"https://foo.com/bar\",\n          headers     : { \"x-forwarded-for\": \"192.168.0.1:57996\" }\n        }\n      },\n      log : () => {}\n    };\n\n    const req = new IncomingMessage(context);\n    req.resume();\n    req.socket.destroy();\n\n    expect(req).toMatchObject({\n      url         : \"https://foo.com/bar\",\n      connection  : {\n        encrypted     : true,\n        remoteAddress : \"192.168.0.1\"\n      }\n    });\n  });\n\n  it(\"Should work with no headers\", () => {\n\n    const context = {\n      bindings : {\n        req : {\n          originalUrl : \"http://foo.com/bar\"\n        }\n      },\n      log : () => {}\n    };\n\n    const req = new IncomingMessage(context);\n    req.resume();\n    req.socket.destroy();\n\n    expect(req).toMatchObject({\n      url         : \"http://foo.com/bar\",\n      connection  : {\n        encrypted     : false,\n        remoteAddress : undefined\n      }\n    });\n  });\n\n  it(\"Should work with a full native context object\", () => {\n\n    const context = {\n      invocationId : \"f0f6e586-0b79-4407-aa53-97919f45eba5\",\n      bindingData : { foo: \"bar\" },\n      bindings : {\n        req : {\n          originalUrl : \"http://foo.com/bar\"\n        }\n      },\n      log   : () => {},\n      done  : () => {}\n    };\n\n    const req = new IncomingMessage(context);\n    req.resume();\n    req.socket.destroy();\n\n    expect(req).toMatchObject({\n      url         : \"http://foo.com/bar\",\n      connection  : {\n        encrypted     : false,\n        remoteAddress : undefined\n      }\n    });\n\n    expect(req.context).toBeDefined();\n    expect(req.context).not.toBe(context);\n    expect(req.context.invocationId).toBe(context.invocationId);\n    expect(req.context.bindingData).toBe(context.bindingData);\n    expect(req.context.bindings).toBe(context.bindings);\n    expect(req.context.log).not.toBe(context.log);\n    expect(req.context.log).toBeInstanceOf(Function);\n    expect(req.context.done).toBeUndefined(); // We don't want to pass done\n\n  });\n\n});\n"
  },
  {
    "path": "test/OutgoingMessage.test.js",
    "content": "import OutgoingMessage from \"../src/OutgoingMessage\";\n\ndescribe(\"OutgoingMessage\", () => {\n\n  describe(\"writeHead\", () => {\n\n    it(\"Should throws with an invalid status code\", () => {\n      const res = new OutgoingMessage();\n      expect(() => {\n        res.writeHead(1);\n      }).toThrow(/^Invalid status code: 1/);\n    });\n\n    it(\"Should handle unknown status codes\", () => {\n      const context = { res: {} };\n      const res = new OutgoingMessage(context);\n\n      res.writeHead(998);\n\n      expect(res.statusMessage).toBe(\"unknown\");\n      expect(context.res.status).toBe(998);\n    });\n\n    it(\"Should work with headers\", () => {\n      const context = { res: {} };\n      const res = new OutgoingMessage(context);\n\n      res.writeHead(200, null, { foo: \"bar\" });\n\n      expect(res.statusMessage).toBe(\"OK\");\n      expect(context.res.status).toBe(200);\n      expect(context.res.headers).toEqual({ foo: \"bar\" });\n    });\n\n    it(\"Should work with headers with previous headers\", () => {\n      const context = { res: {} };\n      const res = new OutgoingMessage(context);\n      res._headers = { previous: \"previous\" };\n      res._renderHeaders = () => res._headers;\n\n      res.writeHead(200, null, { foo: \"bar\" });\n\n      expect(res.statusMessage).toBe(\"OK\");\n      expect(context.res.status).toBe(200);\n      expect(context.res.headers).toEqual({ foo: \"bar\", previous: \"previous\" });\n    });\n\n    it(\"Should work with a status message\", () => {\n      const context = { res: {} };\n      const res = new OutgoingMessage(context);\n\n      res.writeHead(200, \"baz\", { foo: \"bar\" });\n\n      expect(res.statusMessage).toBe(\"baz\");\n      expect(context.res.status).toBe(200);\n      expect(context.res.headers).toEqual({ foo: \"bar\" });\n    });\n\n    it(\"Should work with a headers as second parameter if no status message is given\", () => {\n      const context = { res: {} };\n      const res = new OutgoingMessage(context);\n\n      res.writeHead(200, { foo: \"bar\" });\n\n      expect(res.statusMessage).toBe(\"OK\");\n      expect(context.res.status).toBe(200);\n      expect(context.res.headers).toEqual({ foo: \"bar\" });\n    });\n\n  });\n\n});\n"
  },
  {
    "path": "test/expressIntegration.test.js",
    "content": "import express from \"express\";\nimport { createAzureFunctionHandler } from \"../src\";\n\ndescribe(\"express integration\", () => {\n\n  it(\"should work with x-powered-by\", done => {\n\n    // 1. Create express app\n    const app = express();\n\n    app.get(\"/api/:foo/:bar\", (req, res) => {\n      res.set(\"Cache-Control\", \"max-age=600\");\n      res.json({ foo: req.params.foo, bar: req.params.bar });\n    });\n\n    // 2. Create handle\n    const handle = createAzureFunctionHandler(app);\n\n    // 3. Mock Azure Function context\n    var context = {\n      bindings  : { req: { method: \"GET\", originalUrl: \"https://lol.com/api/foo/bar\" } },\n      log       : () => { throw new Error(\"Log should not be called\"); },\n      done : (error) => {\n        expect(error).toBeUndefined();\n        expect(context.res.status).toBe(200);\n        expect(context.res.body).toBe('{\"foo\":\"foo\",\"bar\":\"bar\"}');\n        expect(context.res.headers).toEqual({\n          \"X-Powered-By\"    : \"Express\",\n          \"Cache-Control\"   : \"max-age=600\",\n          \"Content-Type\"    : \"application/json; charset=utf-8\",\n          \"Content-Length\"  : \"25\",\n          ETag              : 'W/\"19-0CKEGOfZ5AYCM4LPaa4gzWL6olU\"'\n        });\n\n        done();\n      }\n    };\n\n    // 4. Call the handle with the mockup\n    handle(context, context.req);\n  });\n\n  it(\"should work without x-powered-by\", done => {\n\n    // 1. Create express app\n    const app = express();\n    app.disable(\"x-powered-by\");\n\n    app.get(\"/api/:foo/:bar\", (req, res) => {\n      res.json({ foo: req.params.foo, bar: req.params.bar });\n    });\n\n    // 2. Create handle\n    const handle = createAzureFunctionHandler(app);\n\n    // 3. Mock Azure Function context\n    var context = {\n      bindings  : { req: { method: \"GET\", originalUrl: \"https://lol.com/api/foo/bar\" } },\n      log       : () => { throw new Error(\"Log should not be called\"); },\n      done : (error) => {\n        expect(error).toBeUndefined();\n        expect(context.res.status).toBe(200);\n        expect(context.res.body).toBe('{\"foo\":\"foo\",\"bar\":\"bar\"}');\n        expect(context.res.headers).toEqual({\n          \"Content-Type\"    : \"application/json; charset=utf-8\",\n          \"Content-Length\"  : \"25\",\n          ETag              : 'W/\"19-0CKEGOfZ5AYCM4LPaa4gzWL6olU\"'\n        });\n\n        done();\n      }\n    };\n\n    // 4. Call the handle with the mockup\n    handle(context, context.req);\n  });\n\n});\n"
  },
  {
    "path": "test/main.test.js",
    "content": "import { createAzureFunctionHandler, createHandler } from \"../src\";\n\nconst NOOP = () => {};\n\ndescribe(\"main\", () => {\n\n  it(\"createAzureFunctionHandler should work\", () => {\n    expect(createAzureFunctionHandler(NOOP)).toBeInstanceOf(Function);\n  });\n\n  it(\"createHandler should work\", () => {\n    expect(createHandler(NOOP)).toBeInstanceOf(Function);\n  });\n\n});\n"
  }
]