[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG] \"\nlabels: bug\nassignees: iamolegga\n\n---\n\n<!-- Please don't delete this template or we'll close your issue -->\n<!-- Before creating an issue please make sure you are using the latest version. -->\n\n[ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md)\n\n[ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md)\n\n[ ] I couldn't find the same [bug](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Abug)\n\n**What is the current behavior?**\n\n**What is the expected behavior?**\n\n**Please provide minimal example repo. Without it this issue will be closed**\n\n**Please mention other relevant information such as Node.js version and Operating System.**\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[FEATURE REQUEST] \"\nlabels: enhancement\nassignees: iamolegga\n\n---\n\n<!-- Please don't delete this template or we'll close your issue -->\n<!-- Before creating an issue please make sure you are using the latest version. -->\n\n[ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md)\n\n[ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md)\n\n[ ] I couldn't find the same [feature request](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Aenhancement)\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question.md",
    "content": "---\nname: Question\nabout: Please ask your question\ntitle: \"[QUESTION] \"\nlabels: question\nassignees: iamolegga\n\n---\n\n<!-- Please don't delete this template or we'll close your issue -->\n<!-- Before creating an issue please make sure you are using the latest version. -->\n\n[ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md)\n\n[ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md)\n\n[ ] I couldn't find the same [question](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Aquestion)\n\n**Question**\n\n\n\n**Please mention other relevant information such as Node.js version and Operating System.**\n\n\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: npm\n  directory: \"/\"\n  schedule:\n    interval: daily\n    time: \"02:00\"\n  open-pull-requests-limit: 10\n  ignore:\n    - dependency-name: \"reflect-metadata\"\n      update-types: [\"version-update:semver-major\", \"version-update:semver-minor\"]\n"
  },
  {
    "path": ".github/workflows/build-lint-test.yml",
    "content": "name: build-lint-test\n\non:\n  workflow_call:\n\njobs:\n  build-lint-test:\n    strategy:\n      fail-fast: false\n      matrix:\n        nestjs-version:\n          - \"8\"\n          - \"9\"\n          - \"10\"\n          - \"11\"\n        nodejs-version:\n          - 20\n          - 22\n        include:\n          - nestjs-version: 8\n            typescript-version: 4\n          - nestjs-version: 9\n            typescript-version: 4\n          - nestjs-version: 10\n            typescript-version: 5\n          - nestjs-version: 11\n            typescript-version: 5\n    \n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n\n      - uses: actions/setup-node@v3\n        with:\n          node-version: ${{ matrix.nodejs-version }}\n      - run: npm ci\n      - run: |\n          npm i @nestjs/core@${{ matrix.nestjs-version }} \\\n                @nestjs/common@${{ matrix.nestjs-version }} \\\n                @nestjs/platform-express@${{ matrix.nestjs-version }} \\\n                @types/node@${{ matrix.nodejs-version }} \\\n                typescript@${{ matrix.typescript-version }} \\\n                -D\n      - run: npm run lint\n      - uses: actions/cache@v3\n        with:\n          path: coverage\n          key: ${{ github.sha }}-${{ matrix.nestjs-version }}-${{ matrix.nodejs-version }}\n      - run: npm t\n      - run: npm run build\n"
  },
  {
    "path": ".github/workflows/on-pr-master.yml",
    "content": "name: on-pr-master\n\non:\n  pull_request:\n    branches:\n      - master\n\njobs:\n  build-lint-test:\n    uses: ./.github/workflows/build-lint-test.yml\n    secrets: inherit\n"
  },
  {
    "path": ".github/workflows/on-push-master.yml",
    "content": "name: on-push\n\non:\n  push:\n    branches:\n      - master\n\njobs:\n  build-lint-test:\n    uses: ./.github/workflows/build-lint-test.yml\n    secrets: inherit\n\n  publish-alpha:\n    if: github.actor != 'dependabot[bot]' && github.actor != 'mergify[bot]'\n    needs:\n      - build-lint-test\n    uses: ./.github/workflows/publish-alpha.yml\n    secrets: inherit\n\n  coverage:\n    needs:\n      - build-lint-test\n    uses: ./.github/workflows/publish-coverage.yml\n    secrets: inherit\n"
  },
  {
    "path": ".github/workflows/on-release.yml",
    "content": "name: on-release\n\non:\n  release:\n    types: [created]\n\njobs:\n  publish-with-git-tag-version:\n    uses: ./.github/workflows/publish-with-git-tag-version.yml\n    secrets: inherit\n"
  },
  {
    "path": ".github/workflows/publish-alpha.yml",
    "content": "name: publish-alpha\n\non:\n  workflow_call:\n\njobs:\n  publish-alpha:\n    if: github.ref == 'refs/heads/master' && github.actor != 'dependabot[bot]' && github.actor != 'mergify[bot]'\n    runs-on: ubuntu-latest\n    steps:\n\n      - uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n\n      - uses: actions/setup-node@v3\n        with:\n          node-version: 22\n          registry-url: 'https://registry.npmjs.org'\n\n      - run: npm ci\n\n      - run: npm version --no-git-tag-version $(git describe --abbrev=0 --tags)-alpha.$(git rev-parse --short=6 ${{ github.sha }}) || true\n\n      - run: npm publish --tag alpha || true\n        env:\n          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/publish-coverage.yml",
    "content": "name: publish-coverage\n\non:\n  workflow_call:\n\njobs:\n  publish-coverage:\n    runs-on: ubuntu-latest\n    steps:\n\n      - uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n\n      - uses: actions/cache@v3\n        with:\n          path: coverage\n          # restore cache from build-lint-test wf with key=sha-(oneof nestjs version)-(oneof nodejs version)\n          key: ${{ github.sha }}-11-22\n\n      - uses: paambaati/codeclimate-action@v2.7.5\n        with:\n          coverageLocations: ${{github.workspace}}/coverage/lcov.info:lcov\n        env:\n          CC_TEST_REPORTER_ID: ${{ secrets.CODE_CLIMATE_REPORTER_ID }}\n"
  },
  {
    "path": ".github/workflows/publish-with-git-tag-version.yml",
    "content": "name: publish-with-git-tag-version\n\non:\n  workflow_call:\n\njobs:\n  publish-with-git-tag-version:\n    runs-on: ubuntu-latest\n    steps:\n\n      - uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n\n      - uses: actions/setup-node@v3\n        with:\n          node-version: 22\n          registry-url: 'https://registry.npmjs.org'\n\n      - run: npm ci\n\n      - run: npm version --no-git-tag-version $(git describe --abbrev=0 --tags)\n\n      - run: |\n          git config --local user.email \"github-actions[bot]@users.noreply.github.com\"\n          git config --local user.name \"github-actions[bot]\"\n          git commit -m \"update version\" -a\n\n      - uses: ad-m/github-push-action@master\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n\n      - run: npm publish\n        env:\n          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\ntypings/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n.env.test\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n\n# Next.js build output\n.next\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and *not* Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n"
  },
  {
    "path": ".mergify.yml",
    "content": "queue_rules:\n  - name: dependabot-nestjs-session\n    queue_conditions:\n      - author~=^dependabot(|-preview)\\[bot\\]$\n      - -check-failure~=build-lint-test\n      - check-success~=build-lint-test\n      - check-success=security/snyk (iamolegga)\n    merge_conditions:\n      - author~=^dependabot(|-preview)\\[bot\\]$\n      - -check-failure~=build-lint-test\n      - check-success~=build-lint-test\n      - check-success=security/snyk (iamolegga)\n    merge_method: rebase\n\npull_request_rules:\n  - name: refactored queue action rule\n    conditions: []\n    actions:\n      queue:\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n  \"typescript.tsdk\": \"node_modules/typescript/lib\"\n}"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\n advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at iamolegga@gmail.com. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "All pull requests that respect next rules are welcome:\n\n- Before opening pull request to this repo run `npm t` to run tests.\n- All bugfixes and features should contain tests and coverage must be 100%\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2019 iamolegga\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">NestJS-Session</h1>\n\n<p align=\"center\">\n  <a href=\"https://www.npmjs.com/package/nestjs-session\">\n    <img alt=\"npm\" src=\"https://img.shields.io/npm/v/nestjs-session\" />\n  </a>\n  <a href=\"https://www.npmjs.com/package/nestjs-session\">\n    <img alt=\"npm\" src=\"https://img.shields.io/npm/dm/nestjs-session\" />\n  </a>\n  <a href=\"https://github.com/iamolegga/nestjs-session/actions\">\n    <img alt=\"GitHub branch checks state\" src=\"https://badgen.net/github/checks/iamolegga/nestjs-session\" />\n  </a>\n  <a href=\"https://codeclimate.com/github/iamolegga/nestjs-session/test_coverage\">\n    <img src=\"https://api.codeclimate.com/v1/badges/08bcbca7b2da14b3bbfd/test_coverage\" />\n  </a>\n  <a href=\"https://snyk.io/test/github/iamolegga/nestjs-session\">\n    <img alt=\"Known Vulnerabilities\" src=\"https://snyk.io/test/github/iamolegga/nestjs-session/badge.svg\" />\n  </a>\n  <a href=\"https://libraries.io/npm/nestjs-session\">\n    <img alt=\"Libraries.io\" src=\"https://img.shields.io/librariesio/release/npm/nestjs-session\" />\n  </a>\n  <img alt=\"Dependabot\" src=\"https://badgen.net/github/dependabot/iamolegga/nestjs-session\" />\n  <img alt=\"Supported platforms: Express\" src=\"https://img.shields.io/badge/platforms-Express-green\" />\n</p>\n\n<p align=\"center\">Idiomatic Session Module for NestJS. Built on top of <a href=\"https://npm.im/express-session\">express-session</a> 😎</p>\n\nThis module implements a session with storing data in one of [external stores](https://github.com/expressjs/session#compatible-session-stores) and passing ID of session to client via `Cookie`/`Set-Cookie` headers.\n\nIf you want to store data directly in `Cookie`, you can look at [nestjs-cookie-session](https://github.com/iamolegga/nestjs-cookie-session).\n\n## Example\n\nRegister module:\n\n```ts\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { NestSessionOptions, SessionModule } from 'nestjs-session';\nimport { ViewsController } from './views.controller';\n\n@Module({\n  imports: [\n    // sync params:\n\n    SessionModule.forRoot({\n      session: { secret: 'keyboard cat' },\n    }),\n\n    // or async:\n\n    SessionModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [Config],\n      //              TIP: to get autocomplete in return object\n      //                  add `NestSessionOptions` here ↓↓↓\n      useFactory: async (config: Config): Promise<NestSessionOptions> => {\n        return {\n          session: { secret: config.secret },\n        };\n      },\n    }),\n  ],\n  controllers: [ViewsController],\n})\nexport class AppModule {}\n```\n\nIn controllers use NestJS built-in `Session` decorator:\n\n```ts\n// views.controller.ts\nimport { Controller, Get, Session } from '@nestjs/common';\n\n@Controller('views')\nexport class ViewsController {\n  @Get()\n  getViews(@Session() session: { views?: number }) {\n    session.views = (session.views || 0) + 1;\n    return session.views;\n  }\n}\n```\n\n---\n\n**BE AWARE THAT THIS EXAMPLE IS NOT FOR PRODUCTION! IT USES IN-MEMORY STORE, SO YOUR DATA WILL BE LOST ON RESTART. USE OTHER [STORES](https://github.com/expressjs/session#compatible-session-stores)**\n\n---\n\nSee [redis-store](https://github.com/tj/connect-redis) example in `examples` folder.\n\nTo run examples:\n\n```sh\ngit clone https://github.com/iamolegga/nestjs-session.git\ncd nestjs-session\nnpm i\nnpm run build\ncd examples/in-memory # or `cd examples/redis-store`\nnpm i\nnpm start\n```\n\nFor Redis example, you should start Redis on localhost:6379.\nIf you have Docker installed you can start Redis image by `npm run redis` from `redis-store` directory.\n\n## Install\n\n```sh\nnpm i nestjs-session express-session @types/express-session\n```\n\n## API\n\n### SessionModule\n\n`SessionModule` class has two static methods, that returns `DynamicModule`, that you need to import:\n\n- `SessionModule.forRoot` for sync configuration without dependencies\n- `SessionModule.forRootAsync` for sync/async configuration with dependencies\n\n### SessionModule.forRoot\n\nAccept `NestSessionOptions`. Returns NestJS `DynamicModule` for import.\n\n### SessionModule.forRootAsync\n\nAccept `NestSessionAsyncOptions`. Returns NestJS `DynamicModule` for import.\n\n### NestSessionOptions\n\n`NestSessionOptions` is the interface of all options. It has next properties:\n\n- `session` - **required** - [express-session options](https://github.com/expressjs/session#options).\n- `forRoutes` - **optional** - same as NestJS buil-in `MiddlewareConfigProxy['forRoutes']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes.\n- `exclude` - **optional** - same as NestJS buil-in `MiddlewareConfigProxy['exclude']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should not have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes.\n- `retries` - **optional** - `number` - by default if your session store lost connection to database it will return session as `undefined`, and no errors will be thrown, and then you need to check session in controller. But you can set this property how many times it should retry to get session, and on fail `InternalServerErrorException` will be thrown. If you don't want retries, but just want to `InternalServerErrorException` to be throw, then set to `0`. Set this option, if you dont't want manualy check session inside controllers.\n- `retriesStrategy` - **optional** - `(attempt: number) => number` - function that returns number of ms to wait between next attempt. Not calls on first attempt.\n\n### NestSessionAsyncOptions\n\n`NestSessionAsyncOptions` is the interface of options to create session module, that depends on other modules. It has next properties:\n\n- `imports` - **optional** - modules, that session module depends on. See [official docs](https://docs.nestjs.com/modules).\n- `inject` - **optional** - providers from `imports`-property modules, that will be passed as arguments to `useFactory` method.\n- `useFactory` - **required** - method, that returns `NestSessionOptions`.\n\n## Migration\n\n### v2\n\n`express-session` and `@types/express-session` are moved to peer dependencies, so you can update them independently.\n\n<h2 align=\"center\">Do you use this library?<br/>Don't be shy to give it a star! ★</h2>\n\n<h3 align=\"center\">Also if you are into NestJS you might be interested in one of my <a href=\"https://github.com/iamolegga#nestjs\">other NestJS libs</a>.</h3>\n"
  },
  {
    "path": "__tests__/forRoot.spec.ts",
    "content": "import { Controller, Get, Module, Session } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport { SessionModule } from '../src';\n\nimport { platforms } from './utils/platforms';\nimport { doubleRequest } from './utils/request';\n\ndescribe(SessionModule.forRoot.name, () => {\n  for (const PlatformAdapter of platforms) {\n    describe(PlatformAdapter.name, () => {\n      it('works', async () => {\n        @Controller('/')\n        class TestController {\n          @Get()\n          get(@Session() session?: { views?: number }) {\n            if (!session) {\n              return { views: 0 };\n            }\n\n            session.views = (session.views || 0) + 1;\n            return { views: session.views };\n          }\n        }\n\n        @Module({\n          imports: [SessionModule.forRoot({ session: { secret: 'test' } })],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n        const [res1, res2] = await doubleRequest(server);\n        await app.close();\n\n        expect(res1.body.views).toBe(1);\n        expect(res2.body.views).toBe(2);\n      });\n    });\n  }\n});\n"
  },
  {
    "path": "__tests__/forRootAsync.spec.ts",
    "content": "import { Controller, Get, Module, Session } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport { NestSessionOptions, SessionModule } from '../src';\n\nimport { platforms } from './utils/platforms';\nimport { doubleRequest } from './utils/request';\n\ndescribe(SessionModule.forRootAsync.name, () => {\n  for (const PlatformAdapter of platforms) {\n    describe(PlatformAdapter.name, () => {\n      it('works', async () => {\n        @Controller('/')\n        class TestController {\n          @Get()\n          get(@Session() session?: { views?: number }) {\n            if (!session) {\n              return { views: 0 };\n            }\n\n            session.views = (session.views || 0) + 1;\n            return { views: session.views };\n          }\n        }\n\n        @Module({\n          imports: [\n            SessionModule.forRootAsync({\n              useFactory: ():\n                | NestSessionOptions\n                | Promise<NestSessionOptions> => ({\n                session: { secret: 'test' },\n              }),\n            }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n        const [res1, res2] = await doubleRequest(server);\n        await app.close();\n\n        expect(res1.body.views).toBe(1);\n        expect(res2.body.views).toBe(2);\n      });\n    });\n  }\n});\n"
  },
  {
    "path": "__tests__/retires.spec.ts",
    "content": "import { Controller, Get, Module, Session } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Handler } from 'express';\nimport { MemoryStore } from 'express-session';\nimport request from 'supertest';\n\nimport { SessionModule } from '../src';\n\nimport { platforms } from './utils/platforms';\nimport { doubleRequest } from './utils/request';\n\ndescribe('retries', () => {\n  for (const PlatformAdapter of platforms) {\n    describe(PlatformAdapter.name, () => {\n      it('session is undefined with disconnected store', async () => {\n        @Controller('/')\n        class TestController {\n          @Get()\n          get(@Session() session?: { views?: number }) {\n            return { sessionType: typeof session };\n          }\n        }\n\n        const store = new MemoryStore();\n\n        @Module({\n          imports: [\n            SessionModule.forRoot({ session: { secret: 'test', store } }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n\n        store.emit('disconnect');\n\n        const result = await request(server).get('/');\n        await app.close();\n\n        expect(result.body).toEqual({ sessionType: 'undefined' });\n      });\n\n      it('controllers should be blocked with disconnected store and set retries', async () => {\n        let isControllerCalled = false;\n\n        @Controller('/')\n        class TestController {\n          @Get()\n          get() {\n            isControllerCalled = true;\n          }\n        }\n\n        const store = new MemoryStore();\n\n        @Module({\n          imports: [\n            SessionModule.forRoot({\n              session: { secret: 'test', store },\n              retries: 0,\n            }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n\n        store.emit('disconnect');\n        const result = await request(server).get('/');\n        await app.close();\n\n        expect(result.status).toBe(500);\n        expect(isControllerCalled).toBeFalsy();\n      });\n\n      it('retries should work when reconnected', async () => {\n        let isControllerCalled = false;\n\n        @Controller('/')\n        class TestController {\n          @Get()\n          get() {\n            isControllerCalled = true;\n          }\n        }\n\n        const store = new MemoryStore();\n\n        @Module({\n          imports: [\n            SessionModule.forRoot({\n              session: { secret: 'test', store },\n              retries: 1,\n            }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        app.use(((_req, _res, next) => {\n          next();\n          process.nextTick(() => {\n            store.emit('connect');\n          });\n        }) as Handler);\n        const server = app.getHttpServer();\n\n        await app.init();\n\n        store.emit('disconnect');\n        const reqPromise = request(server).get('/');\n\n        const result = await reqPromise;\n        await app.close();\n\n        expect(result.status).toBe(200);\n        expect(isControllerCalled).toBeTruthy();\n      });\n\n      it('controllers should be blocked with error in store and set retries', async () => {\n        let callTimes = 0;\n\n        @Controller('/')\n        class TestController {\n          @Get()\n          get() {\n            callTimes++;\n          }\n        }\n\n        const store = new MemoryStore();\n        store.get = (_sid, cb) => cb(new Error());\n\n        @Module({\n          imports: [\n            SessionModule.forRoot({\n              session: { secret: 'test', store },\n              retries: 0,\n            }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n\n        const [, result] = await doubleRequest(server);\n        await app.close();\n\n        expect(result.status).toBe(500);\n        expect(callTimes).toBe(1);\n      });\n    });\n  }\n});\n"
  },
  {
    "path": "__tests__/routing.spec.ts",
    "content": "import {\n  Controller,\n  Get,\n  Module,\n  RequestMethod,\n  Session,\n} from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport { SessionModule } from '../src';\n\nimport { platforms } from './utils/platforms';\nimport { doubleRequest } from './utils/request';\n\ndescribe('routing', () => {\n  for (const PlatformAdapter of platforms) {\n    describe(PlatformAdapter.name, () => {\n      it('forRoutes', async () => {\n        @Controller('/')\n        class TestController {\n          @Get('with-session')\n          withSession(@Session() session?: { views?: number }) {\n            if (!session) {\n              return { views: 1 };\n            }\n            session.views = (session.views || 0) + 1;\n            return { views: session.views };\n          }\n\n          @Get('without-session')\n          withoutSession(@Session() session?: { views?: number }) {\n            if (!session) {\n              return { views: 1 };\n            }\n\n            session.views = (session.views || 0) + 1;\n            return { views: session.views };\n          }\n        }\n\n        @Module({\n          imports: [\n            SessionModule.forRoot({\n              session: { secret: 'test' },\n              forRoutes: [{ method: RequestMethod.ALL, path: 'with-session' }],\n            }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n        const [sessRes1, sessRes2] = await doubleRequest(\n          server,\n          '/with-session',\n        );\n        const [noSessRes1, noSessRes2] = await doubleRequest(\n          server,\n          '/without-session',\n        );\n        await app.close();\n\n        expect(sessRes1.body.views).toBe(1);\n        expect(sessRes2.body.views).toBe(2);\n\n        expect(noSessRes1.body.views).toBe(1);\n        expect(noSessRes2.body.views).toBe(1);\n      });\n\n      it('exclude', async () => {\n        @Controller('/')\n        class TestController {\n          @Get('with-session')\n          withSession(@Session() session?: { views?: number }) {\n            if (!session) {\n              return { views: 1 };\n            }\n            session.views = (session.views || 0) + 1;\n            return { views: session.views };\n          }\n\n          @Get('without-session')\n          withoutSession(@Session() session?: { views?: number }) {\n            if (!session) {\n              return { views: 1 };\n            }\n\n            session.views = (session.views || 0) + 1;\n            return { views: session.views };\n          }\n        }\n\n        @Module({\n          imports: [\n            SessionModule.forRoot({\n              session: { secret: 'test' },\n              exclude: [{ method: RequestMethod.ALL, path: 'without-session' }],\n              forRoutes: [TestController],\n            }),\n          ],\n          controllers: [TestController],\n        })\n        class TestModule {}\n\n        const app = await NestFactory.create(\n          TestModule,\n          new PlatformAdapter(),\n          { logger: false },\n        );\n        const server = app.getHttpServer();\n\n        await app.init();\n        const [sessRes1, sessRes2] = await doubleRequest(\n          server,\n          '/with-session',\n        );\n        const [noSessRes1, noSessRes2] = await doubleRequest(\n          server,\n          '/without-session',\n        );\n        await app.close();\n\n        expect(sessRes1.body.views).toBe(1);\n        expect(sessRes2.body.views).toBe(2);\n\n        expect(noSessRes1.body.views).toBe(1);\n        expect(noSessRes2.body.views).toBe(1);\n      });\n    });\n  }\n});\n"
  },
  {
    "path": "__tests__/utils/platforms.ts",
    "content": "import { Type } from '@nestjs/common';\nimport { AbstractHttpAdapter } from '@nestjs/core';\nimport { ExpressAdapter } from '@nestjs/platform-express';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Adapter = Type<AbstractHttpAdapter<any, any, any>>;\n\nexport const platforms: Adapter[] = [ExpressAdapter];\n"
  },
  {
    "path": "__tests__/utils/request.ts",
    "content": "import request from 'supertest';\n\nexport async function doubleRequest(\n  server: Parameters<typeof request>[0],\n  path = '/',\n) {\n  const result1 = await request(server).get(path);\n\n  const cookie = result1.header['set-cookie'];\n\n  const result2 = await request(server)\n    .get(path)\n    .set('Cookie', cookie ? [cookie] : []);\n\n  return [result1, result2] as [request.Response, request.Response];\n}\n"
  },
  {
    "path": "eslint.config.cjs",
    "content": "const { fixupConfigRules, fixupPluginRules } = require('@eslint/compat');\nconst { FlatCompat } = require('@eslint/eslintrc');\nconst js = require('@eslint/js');\nconst typescriptEslintEslintPlugin = require('@typescript-eslint/eslint-plugin');\nconst tsParser = require('@typescript-eslint/parser');\nconst globals = require('globals');\n\nconst compat = new FlatCompat({\n  baseDirectory: __dirname,\n  recommendedConfig: js.configs.recommended,\n  allConfig: js.configs.all,\n});\n\nmodule.exports = [\n  {\n    ignores: ['eslint.config.cjs'],\n  },\n  ...fixupConfigRules(\n    compat.extends(\n      'plugin:@typescript-eslint/recommended',\n      'plugin:import/recommended',\n      'plugin:import/typescript',\n      'plugin:prettier/recommended',\n    ),\n  ),\n  {\n    plugins: {\n      '@typescript-eslint': fixupPluginRules(typescriptEslintEslintPlugin),\n    },\n\n    languageOptions: {\n      globals: {\n        ...globals.node,\n        ...globals.jest,\n      },\n\n      parser: tsParser,\n      ecmaVersion: 5,\n      sourceType: 'module',\n\n      parserOptions: {\n        project: 'tsconfig.json',\n      },\n    },\n\n    rules: {\n      '@typescript-eslint/no-explicit-any': [\n        'error',\n        {\n          fixToUnknown: true,\n          ignoreRestArgs: false,\n        },\n      ],\n\n      '@typescript-eslint/no-floating-promises': [\n        'error',\n        {\n          ignoreIIFE: true,\n        },\n      ],\n\n      '@typescript-eslint/no-unused-vars': [\n        'error',\n        {\n          varsIgnorePattern: '^_',\n          argsIgnorePattern: '^_',\n          ignoreRestSiblings: true,\n        },\n      ],\n\n      '@typescript-eslint/explicit-member-accessibility': [\n        'error',\n        {\n          accessibility: 'no-public',\n        },\n      ],\n\n      '@typescript-eslint/member-ordering': [\n        'error',\n        {\n          default: [\n            'public-static-field',\n            'public-static-get',\n            'public-static-set',\n            'public-static-method',\n            'protected-static-field',\n            'protected-static-get',\n            'protected-static-set',\n            'protected-static-method',\n            'private-static-field',\n            'private-static-get',\n            'private-static-set',\n            'private-static-method',\n            'signature',\n            'public-abstract-field',\n            'protected-abstract-field',\n            'public-decorated-field',\n            'public-instance-field',\n            'protected-decorated-field',\n            'protected-instance-field',\n            'private-decorated-field',\n            'private-instance-field',\n            'public-constructor',\n            'protected-constructor',\n            'private-constructor',\n            'public-abstract-get',\n            'public-abstract-set',\n            'public-abstract-method',\n            'public-decorated-get',\n            'public-instance-get',\n            'public-decorated-set',\n            'public-instance-set',\n            'public-decorated-method',\n            'public-instance-method',\n            'protected-abstract-get',\n            'protected-abstract-set',\n            'protected-abstract-method',\n            'protected-decorated-get',\n            'protected-instance-get',\n            'protected-decorated-set',\n            'protected-instance-set',\n            'protected-decorated-method',\n            'protected-instance-method',\n            'private-decorated-get',\n            'private-instance-get',\n            'private-decorated-set',\n            'private-instance-set',\n            'private-decorated-method',\n            'private-instance-method',\n          ],\n        },\n      ],\n\n      'import/order': [\n        'error',\n        {\n          alphabetize: {\n            order: 'asc',\n            caseInsensitive: true,\n          },\n\n          'newlines-between': 'always',\n        },\n      ],\n    },\n  },\n];\n"
  },
  {
    "path": "examples/in-memory/.eslintrc.js",
    "content": "module.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceType: 'module',\n  },\n  plugins: ['@typescript-eslint/eslint-plugin'],\n  extends: [\n    'plugin:@typescript-eslint/recommended',\n    'plugin:prettier/recommended',\n  ],\n  root: true,\n  env: {\n    node: true,\n    jest: true,\n  },\n  ignorePatterns: ['.eslintrc.js'],\n  rules: {\n    '@typescript-eslint/interface-name-prefix': 'off',\n    '@typescript-eslint/explicit-function-return-type': 'off',\n    '@typescript-eslint/explicit-module-boundary-types': 'off',\n    '@typescript-eslint/no-explicit-any': 'off',\n  },\n};\n"
  },
  {
    "path": "examples/in-memory/.gitignore",
    "content": "# compiled output\n/dist\n/node_modules\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\npnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# OS\n.DS_Store\n\n# Tests\n/coverage\n/.nyc_output\n\n# IDEs and editors\n/.idea\n.project\n.classpath\n.c9/\n*.launch\n.settings/\n*.sublime-workspace\n\n# IDE - VSCode\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json"
  },
  {
    "path": "examples/in-memory/.prettierrc",
    "content": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}"
  },
  {
    "path": "examples/in-memory/README.md",
    "content": "<p align=\"center\">\n  <a href=\"http://nestjs.com/\" target=\"blank\"><img src=\"https://nestjs.com/img/logo_text.svg\" width=\"320\" alt=\"Nest Logo\" /></a>\n</p>\n\n[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456\n[circleci-url]: https://circleci.com/gh/nestjs/nest\n\n  <p align=\"center\">A progressive <a href=\"http://nodejs.org\" target=\"_blank\">Node.js</a> framework for building efficient and scalable server-side applications.</p>\n    <p align=\"center\">\n<a href=\"https://www.npmjs.com/~nestjscore\" target=\"_blank\"><img src=\"https://img.shields.io/npm/v/@nestjs/core.svg\" alt=\"NPM Version\" /></a>\n<a href=\"https://www.npmjs.com/~nestjscore\" target=\"_blank\"><img src=\"https://img.shields.io/npm/l/@nestjs/core.svg\" alt=\"Package License\" /></a>\n<a href=\"https://www.npmjs.com/~nestjscore\" target=\"_blank\"><img src=\"https://img.shields.io/npm/dm/@nestjs/common.svg\" alt=\"NPM Downloads\" /></a>\n<a href=\"https://circleci.com/gh/nestjs/nest\" target=\"_blank\"><img src=\"https://img.shields.io/circleci/build/github/nestjs/nest/master\" alt=\"CircleCI\" /></a>\n<a href=\"https://coveralls.io/github/nestjs/nest?branch=master\" target=\"_blank\"><img src=\"https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9\" alt=\"Coverage\" /></a>\n<a href=\"https://discord.gg/G7Qnnhy\" target=\"_blank\"><img src=\"https://img.shields.io/badge/discord-online-brightgreen.svg\" alt=\"Discord\"/></a>\n<a href=\"https://opencollective.com/nest#backer\" target=\"_blank\"><img src=\"https://opencollective.com/nest/backers/badge.svg\" alt=\"Backers on Open Collective\" /></a>\n<a href=\"https://opencollective.com/nest#sponsor\" target=\"_blank\"><img src=\"https://opencollective.com/nest/sponsors/badge.svg\" alt=\"Sponsors on Open Collective\" /></a>\n  <a href=\"https://paypal.me/kamilmysliwiec\" target=\"_blank\"><img src=\"https://img.shields.io/badge/Donate-PayPal-ff3f59.svg\"/></a>\n    <a href=\"https://opencollective.com/nest#sponsor\"  target=\"_blank\"><img src=\"https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg\" alt=\"Support us\"></a>\n  <a href=\"https://twitter.com/nestframework\" target=\"_blank\"><img src=\"https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow\"></a>\n</p>\n  <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)\n  [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->\n\n## Description\n\n[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.\n\n## Installation\n\n```bash\n$ npm install\n```\n\n## Running the app\n\n```bash\n# development\n$ npm run start\n\n# watch mode\n$ npm run start:dev\n\n# production mode\n$ npm run start:prod\n```\n\n## Test\n\n```bash\n# unit tests\n$ npm run test\n\n# e2e tests\n$ npm run test:e2e\n\n# test coverage\n$ npm run test:cov\n```\n\n## Support\n\nNest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).\n\n## Stay in touch\n\n- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)\n- Website - [https://nestjs.com](https://nestjs.com/)\n- Twitter - [@nestframework](https://twitter.com/nestframework)\n\n## License\n\nNest is [MIT licensed](LICENSE).\n"
  },
  {
    "path": "examples/in-memory/nest-cli.json",
    "content": "{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\"\n}\n"
  },
  {
    "path": "examples/in-memory/package.json",
    "content": "{\n  \"name\": \"in-memory\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^11.0.16\",\n    \"@nestjs/core\": \"^11.1.18\",\n    \"@nestjs/platform-express\": \"^11.1.19\",\n    \"@types/express-session\": \"^1.17.4\",\n    \"express-session\": \"^1.18.2\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^7.2.0\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^11.0.16\",\n    \"@nestjs/schematics\": \"^8.0.0\",\n    \"@nestjs/testing\": \"^11.0.16\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"^27.0.1\",\n    \"@types/node\": \"^16.0.0\",\n    \"@types/supertest\": \"^2.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^4.28.2\",\n    \"@typescript-eslint/parser\": \"^4.28.2\",\n    \"eslint\": \"^7.30.0\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-prettier\": \"^3.4.0\",\n    \"jest\": \"^30.2.0\",\n    \"prettier\": \"^2.3.2\",\n    \"supertest\": \"^7.0.0\",\n    \"ts-jest\": \"^27.0.3\",\n    \"ts-loader\": \"^9.2.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"tsconfig-paths\": \"^3.14.1\",\n    \"typescript\": \"^4.3.5\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"collectCoverageFrom\": [\n      \"**/*.(t|j)s\"\n    ],\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  }\n}\n"
  },
  {
    "path": "examples/in-memory/src/app.controller.ts",
    "content": "import { Controller, Get, Session } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  getHello(@Session() session: { views?: number }) {\n    session.views = (session.views || 0) + 1;\n    return session.views;\n  }\n}\n"
  },
  {
    "path": "examples/in-memory/src/app.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { SessionModule } from '../../../dist';\nimport { AppController } from './app.controller';\n\n@Module({\n  imports: [\n    SessionModule.forRoot({\n      session: { secret: 'qwerty' },\n    }),\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n"
  },
  {
    "path": "examples/in-memory/src/main.ts",
    "content": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n"
  },
  {
    "path": "examples/in-memory/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n"
  },
  {
    "path": "examples/in-memory/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": false,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false\n  }\n}\n"
  },
  {
    "path": "examples/redis-store/.eslintrc.js",
    "content": "module.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceType: 'module',\n  },\n  plugins: ['@typescript-eslint/eslint-plugin'],\n  extends: [\n    'plugin:@typescript-eslint/recommended',\n    'plugin:prettier/recommended',\n  ],\n  root: true,\n  env: {\n    node: true,\n    jest: true,\n  },\n  ignorePatterns: ['.eslintrc.js'],\n  rules: {\n    '@typescript-eslint/interface-name-prefix': 'off',\n    '@typescript-eslint/explicit-function-return-type': 'off',\n    '@typescript-eslint/explicit-module-boundary-types': 'off',\n    '@typescript-eslint/no-explicit-any': 'off',\n  },\n};\n"
  },
  {
    "path": "examples/redis-store/.gitignore",
    "content": "# compiled output\n/dist\n/node_modules\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\npnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# OS\n.DS_Store\n\n# Tests\n/coverage\n/.nyc_output\n\n# IDEs and editors\n/.idea\n.project\n.classpath\n.c9/\n*.launch\n.settings/\n*.sublime-workspace\n\n# IDE - VSCode\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json"
  },
  {
    "path": "examples/redis-store/.prettierrc",
    "content": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}"
  },
  {
    "path": "examples/redis-store/README.md",
    "content": "<p align=\"center\">\n  <a href=\"http://nestjs.com/\" target=\"blank\"><img src=\"https://nestjs.com/img/logo_text.svg\" width=\"320\" alt=\"Nest Logo\" /></a>\n</p>\n\n[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456\n[circleci-url]: https://circleci.com/gh/nestjs/nest\n\n  <p align=\"center\">A progressive <a href=\"http://nodejs.org\" target=\"_blank\">Node.js</a> framework for building efficient and scalable server-side applications.</p>\n    <p align=\"center\">\n<a href=\"https://www.npmjs.com/~nestjscore\" target=\"_blank\"><img src=\"https://img.shields.io/npm/v/@nestjs/core.svg\" alt=\"NPM Version\" /></a>\n<a href=\"https://www.npmjs.com/~nestjscore\" target=\"_blank\"><img src=\"https://img.shields.io/npm/l/@nestjs/core.svg\" alt=\"Package License\" /></a>\n<a href=\"https://www.npmjs.com/~nestjscore\" target=\"_blank\"><img src=\"https://img.shields.io/npm/dm/@nestjs/common.svg\" alt=\"NPM Downloads\" /></a>\n<a href=\"https://circleci.com/gh/nestjs/nest\" target=\"_blank\"><img src=\"https://img.shields.io/circleci/build/github/nestjs/nest/master\" alt=\"CircleCI\" /></a>\n<a href=\"https://coveralls.io/github/nestjs/nest?branch=master\" target=\"_blank\"><img src=\"https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9\" alt=\"Coverage\" /></a>\n<a href=\"https://discord.gg/G7Qnnhy\" target=\"_blank\"><img src=\"https://img.shields.io/badge/discord-online-brightgreen.svg\" alt=\"Discord\"/></a>\n<a href=\"https://opencollective.com/nest#backer\" target=\"_blank\"><img src=\"https://opencollective.com/nest/backers/badge.svg\" alt=\"Backers on Open Collective\" /></a>\n<a href=\"https://opencollective.com/nest#sponsor\" target=\"_blank\"><img src=\"https://opencollective.com/nest/sponsors/badge.svg\" alt=\"Sponsors on Open Collective\" /></a>\n  <a href=\"https://paypal.me/kamilmysliwiec\" target=\"_blank\"><img src=\"https://img.shields.io/badge/Donate-PayPal-ff3f59.svg\"/></a>\n    <a href=\"https://opencollective.com/nest#sponsor\"  target=\"_blank\"><img src=\"https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg\" alt=\"Support us\"></a>\n  <a href=\"https://twitter.com/nestframework\" target=\"_blank\"><img src=\"https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow\"></a>\n</p>\n  <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)\n  [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->\n\n## Description\n\n[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.\n\n## Installation\n\n```bash\n$ npm install\n```\n\n## Running the app\n\n```bash\n# development\n$ npm run start\n\n# watch mode\n$ npm run start:dev\n\n# production mode\n$ npm run start:prod\n```\n\n## Test\n\n```bash\n# unit tests\n$ npm run test\n\n# e2e tests\n$ npm run test:e2e\n\n# test coverage\n$ npm run test:cov\n```\n\n## Support\n\nNest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).\n\n## Stay in touch\n\n- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)\n- Website - [https://nestjs.com](https://nestjs.com/)\n- Twitter - [@nestframework](https://twitter.com/nestframework)\n\n## License\n\nNest is [MIT licensed](LICENSE).\n"
  },
  {
    "path": "examples/redis-store/nest-cli.json",
    "content": "{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\"\n}\n"
  },
  {
    "path": "examples/redis-store/package.json",
    "content": "{\n  \"name\": \"redis-store\",\n  \"version\": \"0.0.1\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"test/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,test}/**/*.ts\\\" --fix\",\n    \"test\": \"jest\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest --config ./test/jest-e2e.json\",\n    \"redis\": \"docker run -p 6379:6379 redis\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^11.0.16\",\n    \"@nestjs/core\": \"^11.1.18\",\n    \"@nestjs/platform-express\": \"^11.1.16\",\n    \"@types/connect-redis\": \"^0.0.17\",\n    \"@types/express-session\": \"^1.17.4\",\n    \"connect-redis\": \"^6.0.0\",\n    \"express-session\": \"^1.18.2\",\n    \"nestjs-redis\": \"^1.3.3\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^7.2.0\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^11.0.16\",\n    \"@nestjs/schematics\": \"^8.0.0\",\n    \"@nestjs/testing\": \"^11.1.13\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"^27.0.1\",\n    \"@types/node\": \"^16.0.0\",\n    \"@types/supertest\": \"^2.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^4.28.2\",\n    \"@typescript-eslint/parser\": \"^4.28.2\",\n    \"eslint\": \"^7.30.0\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-prettier\": \"^3.4.0\",\n    \"jest\": \"^30.2.0\",\n    \"prettier\": \"^2.3.2\",\n    \"supertest\": \"^7.0.0\",\n    \"ts-jest\": \"^27.0.3\",\n    \"ts-loader\": \"^9.2.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"tsconfig-paths\": \"^3.14.1\",\n    \"typescript\": \"^4.3.5\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"collectCoverageFrom\": [\n      \"**/*.(t|j)s\"\n    ],\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  }\n}\n"
  },
  {
    "path": "examples/redis-store/src/app.controller.ts",
    "content": "import { Controller, Get, Session } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  getHello(@Session() session: { views?: number }) {\n    session.views = (session.views || 0) + 1;\n    return session.views;\n  }\n}\n"
  },
  {
    "path": "examples/redis-store/src/app.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { Session } from './session.module';\n\n@Module({\n  imports: [Session],\n  controllers: [AppController],\n})\nexport class AppModule {}\n"
  },
  {
    "path": "examples/redis-store/src/config.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { ConfigService } from './config.service';\n\n@Module({\n  providers: [ConfigService],\n  exports: [ConfigService],\n})\nexport class ConfigModule {}\n"
  },
  {
    "path": "examples/redis-store/src/config.service.ts",
    "content": "import { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ConfigService {\n  public readonly REDIS_PORT = Number(process.env.REDIS_PORT || 6379);\n  public readonly REDIS_HOST = process.env.REDIS_HOST;\n  public readonly SESSION_SECRET = process.env.SESSION_SECRET || 'supersecret';\n}\n"
  },
  {
    "path": "examples/redis-store/src/main.ts",
    "content": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n"
  },
  {
    "path": "examples/redis-store/src/redis.module.ts",
    "content": "import { DynamicModule } from '@nestjs/common';\nimport { RedisModule, RedisModuleOptions } from 'nestjs-redis';\nimport { ConfigModule } from './config.module';\nimport { ConfigService } from './config.service';\n\nexport const Redis: DynamicModule = RedisModule.forRootAsync({\n  imports: [ConfigModule],\n  inject: [ConfigService],\n  useFactory: (config: ConfigService): RedisModuleOptions => {\n    return {\n      host: config.REDIS_HOST,\n      port: config.REDIS_PORT,\n    };\n  },\n});\n"
  },
  {
    "path": "examples/redis-store/src/session.module.ts",
    "content": "import * as ConnectRedis from 'connect-redis';\nimport * as session from 'express-session';\nimport { RedisService } from 'nestjs-redis';\nimport { NestSessionOptions, SessionModule } from '../../../dist';\nimport { ConfigModule } from './config.module';\nimport { ConfigService } from './config.service';\nimport { Redis } from './redis.module';\n\nconst RedisStore = ConnectRedis(session);\n\nexport const Session = SessionModule.forRootAsync({\n  imports: [Redis, ConfigModule],\n  inject: [RedisService, ConfigService],\n  useFactory: (\n    redisService: RedisService,\n    config: ConfigService,\n  ): NestSessionOptions => {\n    const redisClient = redisService.getClient();\n    const store = new RedisStore({ client: redisClient as any });\n    return {\n      session: {\n        store,\n        secret: config.SESSION_SECRET,\n      },\n    };\n  },\n});\n"
  },
  {
    "path": "examples/redis-store/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n"
  },
  {
    "path": "examples/redis-store/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"target\": \"es2017\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": false,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false\n  }\n}\n"
  },
  {
    "path": "jest.config.js",
    "content": "module.exports = {\n  moduleFileExtensions: ['js', 'ts'],\n  testRegex: '.spec.ts$',\n  transform: {\n    '^.+\\\\.(t|j)s$': 'ts-jest',\n  },\n  collectCoverage: true,\n  coverageDirectory: './coverage',\n  collectCoverageFrom: ['src/**/*.ts'],\n  testEnvironment: 'node',\n  setupFiles: [],\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"nestjs-session\",\n  \"version\": \"4.0.0\",\n  \"description\": \"Idiomatic NestJS module for session\",\n  \"main\": \"index.js\",\n  \"typings\": \"index.d.ts\",\n  \"scripts\": {\n    \"test\": \"jest --verbose -i --detectOpenHandles\",\n    \"lint\": \"tsc --noemit && eslint \\\"{src,__tests__}/**/*.ts\\\" --fix\",\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"prepublishOnly\": \"npm run build && cp -r ./dist/* .\",\n    \"postpublish\": \"git clean -fd\"\n  },\n  \"files\": [\n    \"*.{js,d.ts}\",\n    \"!jest.config.js\",\n    \"!.eslintrc.js\"\n  ],\n  \"engineStrict\": true,\n  \"engines\": {\n    \"node\": \">=18.0.0\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/iamolegga/nestjs-session.git\"\n  },\n  \"keywords\": [\n    \"nestjs\",\n    \"nest.js\",\n    \"nest\",\n    \"session\",\n    \"express\",\n    \"express-session\"\n  ],\n  \"author\": \"iamolegga <iamolegga@gmail.com> (http://github.com/iamolegga)\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/iamolegga/nestjs-session/issues\"\n  },\n  \"homepage\": \"https://github.com/iamolegga/nestjs-session#readme\",\n  \"dependencies\": {\n    \"create-nestjs-middleware-module\": \"^0.4.0\"\n  },\n  \"devDependencies\": {\n    \"@eslint/compat\": \"^2.0.0\",\n    \"@eslint/eslintrc\": \"^3.2.0\",\n    \"@eslint/js\": \"^9.18.0\",\n    \"@nestjs/common\": \"^11.0.4\",\n    \"@nestjs/core\": \"^11.0.4\",\n    \"@nestjs/platform-express\": \"^11.0.4\",\n    \"@types/express-session\": \"^1.18.1\",\n    \"@types/jest\": \"^29.5.14\",\n    \"@types/node\": \"^25.0.0\",\n    \"@types/supertest\": \"^7.2.0\",\n    \"@typescript-eslint/eslint-plugin\": \"^8.21.0\",\n    \"@typescript-eslint/parser\": \"^8.21.0\",\n    \"eslint\": \"^9.18.0\",\n    \"eslint-config-prettier\": \"^10.0.1\",\n    \"eslint-plugin-import\": \"^2.31.0\",\n    \"eslint-plugin-prettier\": \"^5.2.3\",\n    \"express-session\": \"^1.18.1\",\n    \"jest\": \"30.0.0\",\n    \"prettier\": \"^3.4.2\",\n    \"reflect-metadata\": \"^0.1.14\",\n    \"rimraf\": \"^6.0.1\",\n    \"rxjs\": \"^7.8.1\",\n    \"supertest\": \"^7.0.0\",\n    \"ts-jest\": \"^29.2.5\",\n    \"ts-loader\": \"^9.5.2\",\n    \"ts-node\": \"^10.9.2\",\n    \"typescript\": \"^6.0.2\"\n  },\n  \"peerDependencies\": {\n    \"@types/express-session\": \"^1.17.4\",\n    \"express-session\": \"^1.17.2\"\n  }\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "import {\n  AsyncOptions,\n  createModule,\n  SyncOptions,\n} from 'create-nestjs-middleware-module';\nimport expressSession from 'express-session';\n\nimport { createRetriesMiddleware } from './retriesMiddleware';\n\ninterface Options {\n  /**\n   * express-session options. @see https://github.com/expressjs/session#options\n   */\n  session: expressSession.SessionOptions;\n  /**\n   * by default if your session store lost connection to database it will return\n   * session as `undefined`, and no errors will be thrown, and then you need to\n   * check session in controller. But you can set this property how many times\n   * it should retry to get session, and on fail `InternalServerErrorException`\n   * will be thrown. If you don't want retries, but just want to\n   * `InternalServerErrorException` to be throw, then set to `0`. Set this\n   * option, if you dont't want manualy check session inside controllers.\n   */\n  retries?: number;\n  /**\n   * function that returns number of ms to wait between next attempt. Not calls\n   * on first attempt.\n   */\n  retriesStrategy?: Parameters<typeof createRetriesMiddleware>[2];\n}\n\nexport type NestSessionOptions = SyncOptions<Options>;\n\nexport type NestSessionAsyncOptions = AsyncOptions<Options>;\n\nexport const SessionModule = createModule<Options>((options) => {\n  const { retries, session, retriesStrategy } = options;\n  let middleware = expressSession(session);\n\n  if (retries !== undefined) {\n    middleware = createRetriesMiddleware(middleware, retries, retriesStrategy);\n  }\n\n  return middleware;\n});\n"
  },
  {
    "path": "src/retriesMiddleware.ts",
    "content": "import { InternalServerErrorException } from '@nestjs/common';\nimport * as express from 'express';\n\ntype WaitingStrategy = (attempt: number) => number;\n\nexport function createRetriesMiddleware(\n  sessionMiddleware: express.RequestHandler,\n  retries: number,\n  retiesStrategy: WaitingStrategy = () => 0,\n): express.RequestHandler {\n  return async (req, res, next) => {\n    let attempt = 0;\n\n    async function lookupSession(error?: unknown) {\n      if (error) {\n        return next(error);\n      }\n\n      if (req.session !== undefined) {\n        return next();\n      }\n\n      if (attempt > retries) {\n        return next(new InternalServerErrorException('Cannot create session'));\n      }\n\n      if (attempt !== 0) {\n        await new Promise((r) => setTimeout(r, retiesStrategy(attempt)));\n      }\n\n      attempt++;\n\n      sessionMiddleware(req, res, lookupSession);\n    }\n\n    await lookupSession();\n  };\n}\n"
  },
  {
    "path": "tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"dist\", \"__tests__\", \"examples\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"lib\": [\"ES2022\"],\n    \"module\": \"node16\",\n    \"target\": \"ES2022\",\n    \"removeComments\": false,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"resolveJsonModule\": true,\n    \"esModuleInterop\": true,\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"typeRoots\": [\"src/typings\", \"node_modules/@types\"],\n    \"declaration\": true\n  },\n  \"exclude\": [\"examples\"]\n}\n"
  }
]