Full Code of nestjs/azure-func-http for AI

master ed87cce6b3cc cached
49 files
51.6 KB
14.4k tokens
47 symbols
1 requests
Download .txt
Repository: nestjs/azure-func-http
Branch: master
Commit: ed87cce6b3cc
Files: 49
Total size: 51.6 KB

Directory structure:
gitextract_sh6w41v4/

├── .circleci/
│   └── config.yml
├── .commitlintrc.json
├── .eslintrc.js
├── .github/
│   ├── ISSUE_TEMPLATE.md
│   └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .npmignore
├── .prettierignore
├── .prettierrc
├── .release-it.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── index.d.ts
├── index.js
├── index.ts
├── jest.json
├── lib/
│   ├── adapter/
│   │   ├── azure-adapter.ts
│   │   ├── azure-reply.ts
│   │   ├── azure-request.ts
│   │   └── index.ts
│   ├── azure-http.adapter.ts
│   ├── index.ts
│   └── router/
│       ├── azure-http.router.ts
│       └── index.ts
├── package.json
├── renovate.json
├── schematics/
│   ├── collection.json
│   └── install/
│       ├── files/
│       │   ├── project/
│       │   │   ├── .funcignore
│       │   │   ├── __project__/
│       │   │   │   ├── function.json
│       │   │   │   ├── index.ts
│       │   │   │   └── webpack.config.js
│       │   │   ├── __sourceRoot__/
│       │   │   │   └── main.azure.ts
│       │   │   ├── host.json
│       │   │   ├── local.settings.json
│       │   │   └── proxies.json
│       │   └── root/
│       │       ├── .funcignore
│       │       ├── __rootDir__/
│       │       │   └── main.azure.ts
│       │       ├── host.json
│       │       ├── local.settings.json
│       │       ├── main/
│       │       │   ├── function.json
│       │       │   └── index.ts
│       │       └── proxies.json
│       ├── index.test.ts
│       ├── index.ts
│       ├── schema.json
│       └── schema.ts
├── tsconfig.json
└── tsconfig.schematics.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .circleci/config.yml
================================================
version: 2

aliases:
  - &restore-cache
    restore_cache:
      name: Restore Yarn Package Cache
      keys:
        - yarn-packages-{{ checksum "yarn.lock" }}
  - &install-deps
    run:
      name: Install dependencies
      command: yarn
  - &build-packages
    run:
      name: Build
      command: npm run build

jobs:
  build:
    working_directory: ~/nest
    docker:
      - image: cimg/node:20.3
    steps:
      - checkout
      - restore_cache:
          name: Restore Yarn Package Cache
          keys:
            - yarn-packages-{{ checksum "yarn.lock" }}
      - run:
          name: Install dependencies
          command: yarn
      - save_cache:
          name: Save Yarn Package Cache
          key: yarn-packages-{{ checksum "yarn.lock" }}
          paths:
            - ~/.cache/yarn
      - run:
          name: Build
          command: npm run build

  unit_tests:
    working_directory: ~/nest
    docker:
      - image: cimg/node:20.3
    steps:
      - checkout
      - restore_cache:
          name: Restore Yarn Package Cache
          keys:
            - yarn-packages-{{ checksum "yarn.lock" }}
      - run:
          name: Install dependencies
          command: yarn
      - save_cache:
          name: Save Yarn Package Cache
          key: yarn-packages-{{ checksum "yarn.lock" }}
          paths:
            - ~/.cache/yarn
      - run:
          name: Tests
          command: npm run test

workflows:
  version: 2
  build-and-test:
    jobs:
      - build
      - unit_tests:
          requires:
            - build


================================================
FILE: .commitlintrc.json
================================================
{
  "extends": ["@commitlint/config-angular"],
  "rules": {
    "subject-case": [
      2,
      "always",
      ["sentence-case", "start-case", "pascal-case", "upper-case", "lower-case"]
    ],
    "type-enum": [
      2,
      "always",
      [
        "build",
        "chore",
        "ci",
        "docs",
        "feat",
        "fix",
        "perf",
        "refactor",
        "revert",
        "style",
        "test",
        "sample"
      ]
    ]
  }
}


================================================
FILE: .eslintrc.js
================================================
module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    sourceType: 'module'
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier'
  ],
  root: true,
  env: {
    node: true,
    jest: true
  },
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'off'
  }
};


================================================
FILE: .github/ISSUE_TEMPLATE.md
================================================
<!--
PLEASE HELP US PROCESS GITHUB ISSUES FASTER BY PROVIDING THE FOLLOWING INFORMATION.

ISSUES MISSING IMPORTANT INFORMATION MAY BE CLOSED WITHOUT INVESTIGATION.
-->

## I'm submitting a...
<!-- 
Please search GitHub for a similar issue or PR before submitting.
Check one of the following options with "x" -->
<pre><code>
[ ] Regression <!--(a behavior that used to work and stopped working in a new release)-->
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
</code></pre>

## Current behavior
<!-- Describe how the issue manifests. -->


## Expected behavior
<!-- Describe what the desired behavior would be. -->


## Minimal reproduction of the problem with instructions
<!-- Please share a repo, a gist, or step-by-step instructions. -->

## What is the motivation / use case for changing the behavior?
<!-- Describe the motivation or the concrete use case. -->


## Environment

<pre><code>
Nest version: X.Y.Z
<!-- Check whether this is still an issue in the most recent Nest version -->
 
For Tooling issues:
- Node version: XX  <!-- run `node --version` -->
- Platform:  <!-- Mac, Linux, Windows -->

Others:
<!-- Anything else relevant?  Operating system version, IDE, package manager, ... -->
</code></pre>


================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
## PR Checklist
Please check if your PR fulfills the following requirements:

- [ ] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)


## PR Type
What kind of change does this PR introduce?

<!-- Please check the one that applies to this PR using "x". -->
- [ ] Bugfix
- [ ] Feature
- [ ] Code style update (formatting, local variables)
- [ ] Refactoring (no functional changes, no api changes)
- [ ] Build related changes
- [ ] CI related changes
- [ ] Other... Please describe:

## What is the current behavior?
<!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->

Issue Number: N/A


## What is the new behavior?


## Does this PR introduce a breaking change?
- [ ] Yes
- [ ] No

<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->


## Other information


================================================
FILE: .gitignore
================================================
# dependencies
/node_modules

# IDE
/.idea
/.awcache
/.vscode

# misc
npm-debug.log
.DS_Store

# tests
/test
/coverage
/.nyc_output

# source
dist

# schematics
schematics/install/*.js
schematics/install/*.d.ts
schematics/install/express-engine/*.js
schematics/install/express-engine/*.d.ts

================================================
FILE: .npmignore
================================================
# source
lib
/index.ts
package-lock.json
tslint.json
.prettierrc

# schematics
schematics/install/*.ts
schematics/install/express-engine/*.ts

# misc
.DS_Store

================================================
FILE: .prettierignore
================================================
schematics/install/files/**/*.ts

================================================
FILE: .prettierrc
================================================
{
  "trailingComma": "none",
  "singleQuote": true
}

================================================
FILE: .release-it.json
================================================
{
  "git": {
    "commitMessage": "chore(): release v${version}"
  },
  "github": {
    "release": true
  }
}


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Nest

We would love for you to contribute to Nest and help make it even better than it is
today! As a contributor, here are the guidelines we would like you to follow:

 - [Code of Conduct](#coc)
 - [Question or Problem?](#question)
 - [Issues and Bugs](#issue)
 - [Feature Requests](#feature)
 - [Submission Guidelines](#submit)
 - [Coding Rules](#rules)
 - [Commit Message Guidelines](#commit)
 <!-- - [Signing the CLA](#cla) -->

<!-- ## <a name="coc"></a> Code of Conduct
Help us keep Nest open and inclusive. Please read and follow our [Code of Conduct][coc]. -->

## <a name="question"></a> Got a Question or Problem?

**Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.** You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com/questions/tagged/nestjs) where the questions should be tagged with tag `nestjs`.

Stack Overflow is a much better place to ask questions since:

<!-- - there are thousands of people willing to help on Stack Overflow [maybe one day] -->
- questions and answers stay available for public viewing so your question / answer might help someone else
- Stack Overflow's voting system assures that the best answers are prominently visible.

To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.

If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter].

## <a name="issue"></a> Found a Bug?
If you find a bug in the source code, you can help us by
[submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.

## <a name="feature"></a> Missing a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
Please consider what kind of change it is:

* For a **Major Feature**, first open an issue and outline your proposal so that it can be
discussed. This will also allow us to better coordinate our efforts, prevent duplication of work,
and help you to craft the change so that it is successfully accepted into the project. For your issue name, please prefix your proposal with `[discussion]`, for example "[discussion]: your feature idea".
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).

## <a name="submit"></a> Submission Guidelines

### <a name="submit-issue"></a> Submitting an Issue

Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.

We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using a repository or [Gist](https://gist.github.com/). Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like:

- version of NestJS used
- 3rd-party libraries and their versions
- and most importantly - a use-case that fails

<!--
// TODO we need to create a playground, similar to plunkr

A minimal reproduce scenario using a repository or Gist allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem. If neither of these are not a suitable way to demonstrate the problem (for example for issues related to our npm packaging), please create a standalone git repository demonstrating the problem. -->

<!-- We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it. -->

Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced.

You can file new issues by filling out our [new issue form](https://github.com/nestjs/nest/issues/new).


### <a name="submit-pr"></a> Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:

1. Search [GitHub](https://github.com/nestjs/nest/pulls) for an open or closed PR
  that relates to your submission. You don't want to duplicate effort.
<!-- 1. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
  We cannot accept code without this. -->
1. Fork the nestjs/nest repo.
1. Make your changes in a new git branch:

     ```shell
     git checkout -b my-fix-branch master
     ```

1. Create your patch, **including appropriate test cases**.
1. Follow our [Coding Rules](#rules).
1. Run the full Nest test suite, as described in the [developer documentation][dev-doc],
  and ensure that all tests pass.
1. Commit your changes using a descriptive commit message that follows our
  [commit message conventions](#commit). Adherence to these conventions
  is necessary because release notes are automatically generated from these messages.

     ```shell
     git commit -a
     ```
    Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.

1. Push your branch to GitHub:

    ```shell
    git push origin my-fix-branch
    ```

1. In GitHub, send a pull request to `nestjs:master`.
* If we suggest changes then:
  * Make the required updates.
  * Re-run the Nest test suites to ensure tests are still passing.
  * Rebase your branch and force push to your GitHub repository (this will update your Pull Request):

    ```shell
    git rebase master -i
    git push -f
    ```

That's it! Thank you for your contribution!

#### After your pull request is merged

After your pull request is merged, you can safely delete your branch and pull the changes
from the main (upstream) repository:

* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:

    ```shell
    git push origin --delete my-fix-branch
    ```

* Check out the master branch:

    ```shell
    git checkout master -f
    ```

* Delete the local branch:

    ```shell
    git branch -D my-fix-branch
    ```

* Update your master with the latest upstream version:

    ```shell
    git pull --ff upstream master
    ```

## <a name="rules"></a> Coding Rules
To ensure consistency throughout the source code, keep these rules in mind as you are working:

* All features or bug fixes **must be tested** by one or more specs (unit-tests).
<!--
// We're working on auto-documentation.
* All public API methods **must be documented**. (Details TBC). -->
* We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at
  **100 characters**. An automated formatter is available, see
  [DEVELOPER.md](docs/DEVELOPER.md#clang-format).

## <a name="commit"></a> Commit Message Guidelines

We have very precise rules over how our git commit messages can be formatted.  This leads to **more
readable messages** that are easy to follow when looking through the **project history**.  But also,
we use the git commit messages to **generate the Nest change log**.

### Commit Message Format
Each commit message consists of a **header**, a **body** and a **footer**.  The header has a special
format that includes a **type**, a **scope** and a **subject**:

```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```

The **header** is mandatory and the **scope** of the header is optional.

Any line of the commit message cannot be longer 100 characters! This allows the message to be easier
to read on GitHub as well as in various git tools.

Footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.

Samples: (even more [samples](https://github.com/nestjs/nest/commits/master))

```
docs(changelog) update change log to beta.5
```
```
fix(@nestjs/core) need to depend on latest rxjs and zone.js

The version in our package.json gets copied to the one we publish, and users need the latest of these.
```

### Revert
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.

### Type
Must be one of the following:

* **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
* **chore**: Updating tasks etc; no production code change
* **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
* **docs**: Documentation only changes
* **feat**: A new feature
* **fix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
* **test**: Adding missing tests or correcting existing tests


### Subject
The subject contains succinct description of the change:

* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize first letter
* no dot (.) at the end

### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.

### Footer
The footer should contain any information about **Breaking Changes** and is also the place to
reference GitHub issues that this commit **Closes**.

**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.

A detailed explanation can be found in this [document][commit-message-format].

<!-- ## <a name="cla"></a> Signing the CLA

Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code
changes to be accepted, the CLA must be signed. It's a quick process, we promise!

* For individuals we have a [simple click-through form][individual-cla].
* For corporations we'll need you to
  [print, sign and one of scan+email, fax or mail the form][corporate-cla]. -->


<!-- [angular-group]: https://groups.google.com/forum/#!forum/angular -->
<!-- [coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md -->
[commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#
[corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html
[dev-doc]: https://github.com/nestjs/nest/blob/master/docs/DEVELOPER.md
[github]: https://github.com/nestjs/nest
[gitter]: https://gitter.im/nestjs/nest
[individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html
[js-style-guide]: https://google.github.io/styleguide/jsguide.html
[jsfiddle]: http://jsfiddle.net
[plunker]: http://plnkr.co/edit
[runnable]: http://runnable.com
<!-- [stackoverflow]: http://stackoverflow.com/questions/tagged/angular -->


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2017-2021 Kamil Mysliwiec <https://kamilmysliwiec.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
<p align="center">
  <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>

[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
[travis-url]: https://travis-ci.org/nestjs/nest
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest

  <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>
    <p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
  <a href="https://paypal.me/kamilmysliwiec"><img src="https://img.shields.io/badge/Donate-PayPal-dc3d53.svg"/></a>
  <a href="https://twitter.com/nestframework"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
  <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
  [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->

## Description

[Azure Functions](https://code.visualstudio.com/tutorials/functions-extension/getting-started) HTTP module for [Nest](https://github.com/nestjs/nest).

## Installation

Using the Nest CLI:

```bash
$ nest add @nestjs/azure-func-http
```

Example output:

```bash
✔ Installation in progress... ☕
CREATE /.funcignore (66 bytes)
CREATE /host.json (23 bytes)
CREATE /local.settings.json (116 bytes)
CREATE /proxies.json (72 bytes)
CREATE /main/function.json (294 bytes)
CREATE /main/index.ts (287 bytes)
CREATE /main/sample.dat (23 bytes)
CREATE /src/main.azure.ts (321 bytes)
UPDATE /package.json (1827 bytes)
```

## Tutorial

You can read more about this integration [here](https://trilon.io/blog/deploy-nestjs-azure-functions).

## Native routing

If you don't need the compatibility with `express` library, you can use a native routing instead:

```typescript
const app = await NestFactory.create(AppModule, new AzureHttpRouter());
```

`AzureHttpRouter` is exported from `@nestjs/azure-func-http`. Since `AzureHttpRouter` doesn't use `express` underneath, the routing itself is much faster.

## Additional options

You can pass additional flags to customize the post-install schematic. For example, if your base application directory is different than `src`, use `--rootDir` flag:

```bash
$ nest add @nestjs/azure-func-http --rootDir app
```

Other available flags:

- `rootModuleFileName` - the name of the root module file, default: `app.module`
- `rootModuleClassName` - the name of the root module class, default: `AppModule`
- `skipInstall` - skip installing dependencies, default: `false`

## Support

Nest 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).

## Stay in touch

- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)

## License

Nest is [MIT licensed](LICENSE).


================================================
FILE: index.d.ts
================================================
export * from './dist';


================================================
FILE: index.js
================================================
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
exports.__esModule = true;
__export(require("./dist"));


================================================
FILE: index.ts
================================================
export * from './dist';


================================================
FILE: jest.json
================================================
  
{
    "moduleFileExtensions": ["js", "ts"],
    "rootDir": ".",
    "testEnvironment": "node",
    "testRegex": ".(test|spec).ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "./coverage",
    "verbose": true,
    "bail": true,
    "testPathIgnorePatterns": ["/node_modules/", "files"]
  }

================================================
FILE: lib/adapter/azure-adapter.ts
================================================
import { AzureRequest } from './azure-request';
import { AzureReply } from './azure-reply';

export function createHandlerAdapter(handler) {
  return context => {
    context.res = context.res || {};
    const req = new AzureRequest(context);
    const res = new AzureReply(context);
    handler(req, res);
  };
}


================================================
FILE: lib/adapter/azure-reply.ts
================================================
import { OutgoingMessage } from 'http';

export class AzureReply extends OutgoingMessage {
  private readonly _headerSent: boolean;
  private readonly outputData: { data: any }[];
  statusCode?: number;

  constructor(context: Record<string, any>) {
    super();

    // Avoid issues when data is streamed out
    this._headerSent = true;

    this.writeHead = this.writeHead.bind(this, context);
    this.end = this.finish.bind(this, context);
  }

  writeHead(
    context: Record<string, any>,
    statusCode: number,
    statusMessage: string,
    headers: Record<string, any>
  ) {
    if (statusCode) {
      this.statusCode = statusCode;
    }
    if (headers) {
      const keys = Object.keys(headers);
      for (const key of keys) {
        this.setHeader(key, headers[key]);
      }
    }

    context.res.status = this.statusCode;
    context.res.headers = this.getHeaders() || {};
  }

  finish(context: Record<string, any>, body: Record<string, any> | undefined) {
    // If data was streamed out, get it back to body
    if (body === undefined && this.outputData.length > 0) {
      body = Buffer.concat(
        this.outputData.map(o =>
          Buffer.isBuffer(o.data) ? o.data : Buffer.from(o.data)
        )
      );
    }

    context.res.status = this.statusCode;
    context.res.body = body;
    context.done();
  }
}


================================================
FILE: lib/adapter/azure-request.ts
================================================
import { Readable } from 'stream';

export class AzureRequest extends Readable {
  readonly url: string;
  readonly context: Record<string, any>;
  readonly originalUrl: string;
  readonly headers: Record<string, any>;
  readonly body: any;

  constructor(context: Record<string, any>) {
    super();

    Object.assign(this, context.req);
    this.context = context;
    this.url = this.originalUrl;
    this.headers = this.headers || {};

    // Recreate original request stream from body
    const body = Buffer.isBuffer(context.req.body)
      ? context.req.body
      : context.req.rawBody;

    if (body !== null && body !== undefined) {
      this.push(body);
    }
    // Close the stream
    this.push(null);
  }
}


================================================
FILE: lib/adapter/index.ts
================================================
export * from './azure-adapter';
export * from './azure-reply';
export * from './azure-request';


================================================
FILE: lib/azure-http.adapter.ts
================================================
/* eslint-disable @typescript-eslint/ban-types */
import { Context, HttpRequest } from '@azure/functions';
import { HttpServer, INestApplication } from '@nestjs/common';
import { createHandlerAdapter } from './adapter/azure-adapter';
import { AzureHttpRouter } from './router';

let handler: Function;

export class AzureHttpAdapterStatic {
  handle(
    createApp: () => Promise<INestApplication>,
    context: Context,
    req: HttpRequest
  ) {
    if (handler) {
      return handler(context, req);
    }
    this.createHandler(createApp).then((fn) => fn(context, req));
  }

  private async createHandler(
    createApp: () => Promise<
      Omit<INestApplication, 'startAllMicroservicesAsync' | 'listenAsync'>
    >
  ) {
    const app = await createApp();
    const adapter = app.getHttpAdapter();
    if (this.hasGetTypeMethod(adapter) && adapter.getType() === 'azure-http') {
      return (adapter as any as AzureHttpRouter).handle.bind(adapter);
    }
    const instance = app.getHttpAdapter().getInstance();
    handler = createHandlerAdapter(instance);
    return handler;
  }

  private hasGetTypeMethod(
    adapter: HttpServer<any, any>
  ): adapter is HttpServer & { getType: Function } {
    return !!(adapter as any).getType;
  }
}

export const AzureHttpAdapter = new AzureHttpAdapterStatic();


================================================
FILE: lib/index.ts
================================================
export * from './azure-http.adapter';
export * from './router';
export * from './adapter';


================================================
FILE: lib/router/azure-http.router.ts
================================================
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-function */
import {
  HttpStatus,
  InternalServerErrorException,
  NotImplementedException,
  RequestMethod,
  VersioningOptions
} from '@nestjs/common';
import { VersionValue } from '@nestjs/common/interfaces';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { AbstractHttpAdapter } from '@nestjs/core';
import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory';
import * as cors from 'cors';
import TRouter from 'trouter';
import { AzureReply, AzureRequest } from '../adapter';

export class AzureHttpRouter extends AbstractHttpAdapter {
  private readonly routerMethodFactory = new RouterMethodFactory();

  constructor() {
    super(new TRouter());
  }

  public handle(context: Record<string, any>, request: any) {
    const req = context.req;
    const originalUrl = req.originalUrl as string;
    const path = new URL(originalUrl).pathname;

    const { params, handlers } = this.instance.find(req.method, path);
    req.params = params;

    if (handlers.length === 0) {
      return this.handleNotFound(context, req.method, originalUrl);
    }
    const azureRequest = new AzureRequest(context);
    const azureReply = new AzureReply(context);
    const nextRoute = (i = 0) =>
      handlers[i] &&
      handlers[i](azureRequest, azureReply, () => nextRoute(i + 1));
    nextRoute();
  }

  public handleNotFound(
    context: Record<string, any>,
    method: string,
    originalUrl: string
  ) {
    context.res.status = HttpStatus.NOT_FOUND;
    context.res.body = {
      statusCode: HttpStatus.NOT_FOUND,
      error: `Cannot ${method} ${originalUrl}`
    };
    context.done();
    return;
  }

  public enableCors(options: CorsOptions) {
    this.use(cors(options));
  }

  public reply(response: any, body: any, statusCode?: number) {
    response.writeHead(statusCode);
    response.end(body);
  }

  public status(response: any, statusCode: number) {
    response.statusCode = statusCode;
  }

  public end(response: any, message?: string) {
    return response.end(message);
  }

  public getHttpServer<T = any>(): T {
    return this.instance as T;
  }

  public getInstance<T = any>(): T {
    return this.instance as T;
  }

  public isHeadersSent(response: any): boolean {
    return response.headersSent;
  }

  public setHeader(response: any, name: string, value: string) {
    return response.setHeader(name, value);
  }

  public getRequestMethod(request: any): string {
    return request.method;
  }

  public getRequestUrl(request: any): string {
    return request.url;
  }

  public getRequestHostname(request: any): string {
    return request.hostname;
  }

  public createMiddlewareFactory(
    requestMethod: RequestMethod
  ): (path: string, callback: Function) => any {
    return this.routerMethodFactory
      .get(this.instance, requestMethod)
      .bind(this.instance);
  }

  public getType(): string {
    return 'azure-http';
  }

  public applyVersionFilter(
    handler: Function,
    version: VersionValue,
    versioningOptions: VersioningOptions
  ) {
    throw new NotImplementedException();
    return (req, res, next) => {
      return () => {};
    };
  }

  public listen(port: any, ...args: any[]) {}
  public render(response: any, view: string, options: any) {}
  public redirect(response: any, statusCode: number, url: string) {}
  public close() {}
  public initHttpServer() {}
  public useStaticAssets(options: any) {}
  public setViewEngine(options: any) {}
  public registerParserMiddleware() {}
  public setNotFoundHandler(handler: Function) {}
  public setErrorHandler(handler: Function) {}
}


================================================
FILE: lib/router/index.ts
================================================
export * from './azure-http.router';


================================================
FILE: package.json
================================================
{
  "name": "@nestjs/azure-func-http",
  "version": "0.10.0",
  "description": "Nest - modern, fast, powerful node.js web framework (@azure-func-http)",
  "author": "Kamil Mysliwiec",
  "license": "MIT",
  "scripts": {
    "build": "npm run build:lib && npm run build:schematics",
    "build:lib": "tsc -p tsconfig.json",
    "build:schematics": "tsc -p tsconfig.schematics.json",
    "lint": "eslint --ext ts --fix lib",
    "format": "prettier --write \"lib/**/*.ts\"",
    "precommit": "lint-staged",
    "prepublish:npm": "npm run build",
    "publish:npm": "npm publish --access public",
    "prepublish:next": "npm run build",
    "publish:next": "npm publish --access public --tag next",
    "prerelease": "npm run build",
    "release": "release-it",
    "test": "jest -w 1 --no-cache --config jest.json",
    "test:dev": "NODE_ENV=test npm run -s test -- --watchAll"
  },
  "peerDependencies": {
    "@azure/functions": "^1.0.3 || ^2.0.0 || ^3.0.0",
    "@nestjs/common": "^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
    "@nestjs/core": "^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
    "reflect-metadata": "^0.1.13"
  },
  "devDependencies": {
    "@angular-devkit/schematics": "^16.0.0",
    "@azure/functions": "3.5.1",
    "@commitlint/cli": "19.6.1",
    "@commitlint/config-angular": "19.7.0",
    "@nestjs/common": "10.2.7",
    "@nestjs/core": "10.2.7",
    "@nestjs/schematics": "10.0.2",
    "@types/node": "22.10.7",
    "@types/jest": "29.5.14",
    "@typescript-eslint/eslint-plugin": "7.18.0",
    "@typescript-eslint/parser": "7.18.0",
    "@schematics/angular": "16.2.16",
    "eslint": "8.57.1",
    "eslint-config-prettier": "10.0.1",
    "eslint-plugin-import": "2.31.0",
    "husky": "9.1.7",
    "lint-staged": "15.4.1",
    "prettier": "3.4.2",
    "release-it": "17.1.1",
    "typescript": "5.7.3",
    "jest": "29.7.0",
    "ts-jest": "29.2.5"
  },
  "dependencies": {
    "cors": "2.8.5",
    "jsonc-parser": "^3.2.0",
    "trouter": "3.2.1"
  },
  "schematics": "./schematics/collection.json",
  "lint-staged": {
    "*.ts": [
      "prettier --write"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -c .commitlintrc.json -E HUSKY_GIT_PARAMS"
    }
  }
}


================================================
FILE: renovate.json
================================================
{
  "semanticCommits": true,
  "packageRules": [{
    "depTypeList": ["devDependencies"],
    "automerge": true
  }],
  "extends": [
    "config:base"
  ]
}


================================================
FILE: schematics/collection.json
================================================
{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    "nest-add": {
      "description": "Adds Azure Functions HTTP template to the application without affecting any app files",
      "factory": "./install",
      "schema": "./install/schema.json",
      "aliases": ["nest-azure-shell"]
    }
  }
}


================================================
FILE: schematics/install/files/project/.funcignore
================================================
*.js.map
*.ts
.git*
.vscode
local.settings.json
test
tsconfig.json

================================================
FILE: schematics/install/files/project/__project__/function.json
================================================
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "<%= getProjectName() %>/{*segments}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "scriptFile": "../dist/<%= getProjectName() %>/index.js"
}


================================================
FILE: schematics/install/files/project/__project__/index.ts
================================================
import { Context, HttpRequest } from '@azure/functions';
import { AzureHttpAdapter } from '@nestjs/azure-func-http';
import { createApp } from '../apps/<%= getProjectName() %>/src/main.azure';

export default function(context: Context, req: HttpRequest): void {
  AzureHttpAdapter.handle(createApp, context, req);
}


================================================
FILE: schematics/install/files/project/__project__/webpack.config.js
================================================
module.exports = function (options) {
  return {
    ...options,
    entry: __dirname + '/index.ts',
    output: {
      libraryTarget: 'commonjs2',
      filename: '<%= getProjectName() %>/index.js'
    }
  };
};


================================================
FILE: schematics/install/files/project/__sourceRoot__/main.azure.ts
================================================
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { <%= getRootModuleName() %> } from './<%= getRootModulePath() %>';

export async function createApp(): Promise<INestApplication> {
  const app = await NestFactory.create(<%= getRootModuleName() %>);
  app.setGlobalPrefix('api/<%= getProjectName() %>');

  await app.init();
  return app;
}


================================================
FILE: schematics/install/files/project/host.json
================================================
{
  "version": "2.0"
}


================================================
FILE: schematics/install/files/project/local.settings.json
================================================
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}


================================================
FILE: schematics/install/files/project/proxies.json
================================================
{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {}
}


================================================
FILE: schematics/install/files/root/.funcignore
================================================
*.js.map
*.ts
.git*
.vscode
local.settings.json
test
tsconfig.json

================================================
FILE: schematics/install/files/root/__rootDir__/main.azure.ts
================================================
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { <%= getRootModuleName() %> } from './<%= getRootModulePath() %>';

export async function createApp(): Promise<INestApplication> {
  const app = await NestFactory.create(<%= getRootModuleName() %>);
  app.setGlobalPrefix('api');
  
  await app.init();
  return app;
}


================================================
FILE: schematics/install/files/root/host.json
================================================
{
  "version": "2.0"
}


================================================
FILE: schematics/install/files/root/local.settings.json
================================================
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}


================================================
FILE: schematics/install/files/root/main/function.json
================================================
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "{*segments}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "scriptFile": "../dist/main/index.js"
}


================================================
FILE: schematics/install/files/root/main/index.ts
================================================
import { Context, HttpRequest } from '@azure/functions';
import { AzureHttpAdapter } from '@nestjs/azure-func-http';
import { createApp } from '../<%= getRootDirectory() %>/main.azure';

export default function(context: Context, req: HttpRequest): void {
  AzureHttpAdapter.handle(createApp, context, req);
}


================================================
FILE: schematics/install/files/root/proxies.json
================================================
{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {}
}


================================================
FILE: schematics/install/index.test.ts
================================================
import { FileEntry, Tree } from '@angular-devkit/schematics';
import {
  SchematicTestRunner,
  UnitTestTree
} from '@angular-devkit/schematics/testing';
import * as path from 'path';
import { Schema } from './schema';

const getFileContent = (tree: UnitTestTree, path: string): string => {
  const fileEntry: FileEntry = tree.get(path);
  if (!fileEntry) {
    throw new Error(`The file does not exist.`);
  }
  return fileEntry.content.toString();
};
describe('Schematic Tests Nest Add', () => {
  let nestTree: Tree;

  const runner: SchematicTestRunner = new SchematicTestRunner(
    'azure-func-http',
    path.join(process.cwd(), 'schematics/collection.json')
  );

  beforeEach(async () => {
    nestTree = await createTestNest(runner);
  });

  describe('Test for default setup', () => {
    it('should add azure func for default setup', async () => {
      const options: Schema = {
        skipInstall: true,
        rootModuleFileName: 'app.module',
        rootModuleClassName: 'AppModule'
      };

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const files: string[] = tree.files;
      expect(files).toEqual([
        '/.eslintrc.js',
        '/.prettierrc',
        '/README.md',
        '/nest-cli.json',
        '/package.json',
        '/tsconfig.build.json',
        '/tsconfig.json',
        '/.funcignore',
        '/host.json',
        '/local.settings.json',
        '/proxies.json',
        '/src/app.controller.spec.ts',
        '/src/app.controller.ts',
        '/src/app.module.ts',
        '/src/app.service.ts',
        '/src/main.ts',
        '/src/main.azure.ts',
        '/test/app.e2e-spec.ts',
        '/test/jest-e2e.json',
        '/main/function.json',
        '/main/index.ts',
        '/main/sample.dat'
      ]);
    });

    it('should have a nest-cli.json for default app', async () => {
      const options: Schema = {
        sourceRoot: 'src',
        skipInstall: true,
        rootDir: 'src',
        rootModuleFileName: 'app.module',
        rootModuleClassName: 'AppModule'
      };

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = getFileContent(tree, '/nest-cli.json');
      expect(fileContent).toContain(`"sourceRoot": "src"`);
    });

    it('should import the app.module int main azure file for default app', async () => {
      const options: Schema = {
        sourceRoot: 'src',
        skipInstall: true,
        rootDir: 'src',
        rootModuleFileName: 'app.module',
        rootModuleClassName: 'AppModule'
      };

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = getFileContent(tree, '/src/main.azure.ts');

      expect(fileContent).toContain(
        `import { AppModule } from './app.module';`
      );
    });

    it('should have the root dir for index file in main azure dir for default app', async () => {
      const options: Schema = {
        sourceRoot: 'src',
        skipInstall: true,
        rootDir: 'src',
        rootModuleFileName: 'app.module',
        rootModuleClassName: 'AppModule'
      };

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = getFileContent(tree, '/main/index.ts');

      expect(fileContent).toContain(
        `import { createApp } from '../src/main.azure';`
      );
    });

    it('should not import the webpack config for a default app', async () => {
      const options: Schema = {
        sourceRoot: 'src',
        skipInstall: true,
        rootDir: 'src',
        rootModuleFileName: 'app.module',
        rootModuleClassName: 'AppModule'
      };

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = tree.get('webpack.config.js');

      expect(fileContent).toBeNull();
    });
  });

  describe('Tests for monorepo', () => {
    it('should add azure-func for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        rootDir: `apps/${projectName}`,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const files: string[] = tree.files;
      expect(files).toEqual([
        '/.eslintrc.js',
        '/.prettierrc',
        '/README.md',
        '/nest-cli.json',
        '/package.json',
        '/tsconfig.build.json',
        '/tsconfig.json',
        '/.funcignore',
        '/host.json',
        '/local.settings.json',
        '/proxies.json',
        '/src/app.controller.spec.ts',
        '/src/app.controller.ts',
        '/src/app.module.ts',
        '/src/app.service.ts',
        '/src/main.ts',
        '/test/app.e2e-spec.ts',
        '/test/jest-e2e.json',
        '/apps/nestjs-azure-func-http/tsconfig.app.json',
        `/apps/${projectName}/tsconfig.app.json`,
        `/apps/${projectName}/src/main.ts`,
        `/apps/${projectName}/src/${projectName}.controller.spec.ts`,
        `/apps/${projectName}/src/${projectName}.controller.ts`,
        `/apps/${projectName}/src/${projectName}.module.ts`,
        `/apps/${projectName}/src/${projectName}.service.ts`,
        `/apps/${projectName}/src/main.azure.ts`,
        `/apps/${projectName}/test/jest-e2e.json`,
        `/apps/${projectName}/test/app.e2e-spec.ts`,
        `/${projectName}/function.json`,
        `/${projectName}/index.ts`,
        `/${projectName}/sample.dat`,
        `/${projectName}/webpack.config.js`
      ]);
    });

    it('should have a nest-cli.json for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = getFileContent(tree, '/nest-cli.json');
      const parsedFile = JSON.parse(fileContent);
      expect(parsedFile.projects[projectName].sourceRoot).toEqual(
        `apps/${projectName}/src`
      );
    });

    it('should import the app.module int main azure file for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = getFileContent(
        tree,
        `/apps/${projectName}/src/main.azure.ts`
      );

      expect(fileContent).toContain(
        `import { AppModule } from './app.module';`
      );
    });

    it('should have the root dir for index file in main azure dir for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );

      const tree = await runner.runSchematic('nest-add', options, nestTree);
      const fileContent = getFileContent(tree, `/${projectName}/index.ts`);

      expect(fileContent).toContain(
        `import { createApp } from '../apps/${projectName}/src/main.azure';`
      );
    });

    it('should import the webpack config for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        rootDir: `apps/${projectName}`,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );
      const tree = await runner.runSchematic('nest-add', options, nestTree);

      const fileContent = getFileContent(
        tree,
        `/${projectName}/webpack.config.js`
      );
      expect(fileContent).toContain(`filename: '${projectName}/index.js'`);
    });

    it('should add a custom webpack config to the compilerOptions for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );
      const tree = await runner.runSchematic('nest-add', options, nestTree);

      const fileContent = getFileContent(tree, 'nest-cli.json');
      const parsedFile = JSON.parse(fileContent);
      const compilerOptions = parsedFile.projects[projectName].compilerOptions;
      expect(compilerOptions).toEqual({
        tsConfigPath: `apps/${projectName}/tsconfig.app.json`,
        webpack: true,
        webpackConfigPath: `${projectName}/webpack.config.js`
      });
    });

    it('should the scriptFile of functions to sub dir for monorepo app', async () => {
      const projectName = 'azure-2';
      const options: Schema = {
        skipInstall: true,
        project: projectName,
        rootDir: `apps.${projectName}`,
        sourceRoot: `apps/${projectName}/src`
      };

      await runner.runExternalSchematic(
        '@nestjs/schematics',
        'sub-app',
        {
          name: projectName
        },
        nestTree
      );
      const tree = await runner.runSchematic('nest-add', options, nestTree);

      const fileContent = getFileContent(tree, `${projectName}/function.json`);
      const parsedFile = JSON.parse(fileContent);
      expect(parsedFile.scriptFile).toEqual(`../dist/${projectName}/index.js`);
    });
  });

  async function createTestNest(
    runner: SchematicTestRunner,
    tree?: Tree
  ): Promise<UnitTestTree> {
    return await runner.runExternalSchematic(
      '@nestjs/schematics',
      'application',
      {
        name: 'newproject',
        directory: '.'
      },
      tree
    );
  }
});


================================================
FILE: schematics/install/index.ts
================================================
import { strings } from '@angular-devkit/core';
import { parse as parseJson } from 'jsonc-parser';
import {
  apply,
  chain,
  FileEntry,
  forEach,
  mergeWith,
  noop,
  Rule,
  SchematicContext,
  SchematicsException,
  template,
  Tree,
  url
} from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import {
  addPackageJsonDependency,
  NodeDependencyType
} from '@schematics/angular/utility/dependencies';
import { Schema as AzureOptions } from './schema';

type UpdateJsonFn<T> = (obj: T) => T | void;

function addDependenciesAndScripts(): Rule {
  return (host: Tree) => {
    addPackageJsonDependency(host, {
      type: NodeDependencyType.Default,
      name: '@azure/functions',
      version: '^1.0.3'
    });
    const pkgPath = '/package.json';
    const buffer = host.read(pkgPath);
    if (buffer === null) {
      throw new SchematicsException('Could not find package.json');
    }

    const pkg = JSON.parse(buffer.toString());
    pkg.scripts['start:azure'] = 'npm run build && func host start';

    host.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
    return host;
  };
}

function updateJsonFile<T>(
  host: Tree,
  path: string,
  callback: UpdateJsonFn<T>
): Tree {
  const source = host.read(path);
  if (source) {
    const sourceText = source.toString('utf-8');
    const json = parseJson(sourceText);
    callback(json as {} as T);
    host.overwrite(path, JSON.stringify(json, null, 2));
  }
  return host;
}
const applyProjectName = (projectName, host) => {
  if (projectName) {
    let nestCliFileExists = host.exists('nest-cli.json');

    if (nestCliFileExists) {
      updateJsonFile(
        host,
        'nest-cli.json',
        (optionsFile: Record<string, any>) => {
          if (optionsFile.projects[projectName].compilerOptions) {
            optionsFile.projects[projectName].compilerOptions = {
              ...optionsFile.projects[projectName].compilerOptions,
              ...{
                webpack: true,
                webpackConfigPath: `${projectName}/webpack.config.js`
              }
            };
          }
        }
      );
    }
  }
};

const rootFiles = [
  '/.funcignore',
  '/host.json',
  '/local.settings.json',
  '/proxies.json'
];

const validateExistingRootFiles = (host: Tree, file: FileEntry) => {
  return rootFiles.includes(file.path) && host.exists(file.path);
};

export default function (options: AzureOptions): Rule {
  return (host: Tree, context: SchematicContext) => {
    if (!options.skipInstall) {
      context.addTask(new NodePackageInstallTask());
    }
    const defaultSourceRoot =
      options.project !== undefined ? options.sourceRoot : options.rootDir;
    const rootSource = apply(
      options.project ? url('./files/project') : url('./files/root'),
      [
        template({
          ...strings,
          ...(options as AzureOptions),
          rootDir: options.rootDir,
          sourceRoot: defaultSourceRoot,
          getRootDirectory: () => options.rootDir,
          getProjectName: () => options.project,
          stripTsExtension: (s: string) => s.replace(/\.ts$/, ''),
          getRootModuleName: () => options.rootModuleClassName,
          getRootModulePath: () => options.rootModuleFileName
        }),
        forEach((file: FileEntry) => {
          if (validateExistingRootFiles(host, file)) return null;
          return file;
        })
      ]
    );

    return chain([
      (tree, context) =>
        options.project
          ? applyProjectName(options.project, host)
          : noop()(tree, context),
      addDependenciesAndScripts(),
      mergeWith(rootSource)
    ]);
  };
}


================================================
FILE: schematics/install/schema.json
================================================
{
  "$schema": "http://json-schema.org/schema",
  "$id": "SchematicsNestEngineInstall",
  "title": "Nest Engine Install Options Schema",
  "type": "object",
  "properties": {
    "rootDir": {
      "type": "string",
      "description": "Application root directory.",
      "default": "src"
    },
    "rootModuleFileName": {
      "type": "string",
      "format": "path",
      "description": "The name of the root module file (without extension)",
      "default": "app.module"
    },
    "rootModuleClassName": {
      "type": "string",
      "description": "The name of the root module class.",
      "default": "AppModule"
    },
    "skipInstall": {
      "description": "Skip installing dependency packages.",
      "type": "boolean",
      "default": false
    },
    "sourceRoot": {
      "type": "string",
      "description": "The source root directory."
    },
    "project": {
      "type": "string",
      "description": "The project where generate the azure files."
    }
  },
  "required": []
}


================================================
FILE: schematics/install/schema.ts
================================================
export interface Schema {
  /**
   * Application root directory
   */
  rootDir?: string;
  /**
   * The name of the root module file
   */
  rootModuleFileName?: string;
  /**
   * The name of the root module class.
   */
  rootModuleClassName?: string;
  /**
   * Skip installing dependency packages.
   */
  skipInstall?: boolean;
  /**
   * .
   */
  sourceRoot?: string;
  /**
   * The project where generate the azure files.
   */
  project?: string;
}


================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "ES2021",
    "sourceMap": false,
    "outDir": "./dist",
    "skipLibCheck": true
  },
  "include": ["lib/**/*", "../index.ts"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}


================================================
FILE: tsconfig.schematics.json
================================================
{
  "compilerOptions": {
    "rootDir": "schematics",
    "outDir": "./schematics"
  },
  "extends": "./tsconfig.json",
  "include": ["schematics/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts", "./schematics/install/files/**"]
}
Download .txt
gitextract_sh6w41v4/

├── .circleci/
│   └── config.yml
├── .commitlintrc.json
├── .eslintrc.js
├── .github/
│   ├── ISSUE_TEMPLATE.md
│   └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .npmignore
├── .prettierignore
├── .prettierrc
├── .release-it.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── index.d.ts
├── index.js
├── index.ts
├── jest.json
├── lib/
│   ├── adapter/
│   │   ├── azure-adapter.ts
│   │   ├── azure-reply.ts
│   │   ├── azure-request.ts
│   │   └── index.ts
│   ├── azure-http.adapter.ts
│   ├── index.ts
│   └── router/
│       ├── azure-http.router.ts
│       └── index.ts
├── package.json
├── renovate.json
├── schematics/
│   ├── collection.json
│   └── install/
│       ├── files/
│       │   ├── project/
│       │   │   ├── .funcignore
│       │   │   ├── __project__/
│       │   │   │   ├── function.json
│       │   │   │   ├── index.ts
│       │   │   │   └── webpack.config.js
│       │   │   ├── __sourceRoot__/
│       │   │   │   └── main.azure.ts
│       │   │   ├── host.json
│       │   │   ├── local.settings.json
│       │   │   └── proxies.json
│       │   └── root/
│       │       ├── .funcignore
│       │       ├── __rootDir__/
│       │       │   └── main.azure.ts
│       │       ├── host.json
│       │       ├── local.settings.json
│       │       ├── main/
│       │       │   ├── function.json
│       │       │   └── index.ts
│       │       └── proxies.json
│       ├── index.test.ts
│       ├── index.ts
│       ├── schema.json
│       └── schema.ts
├── tsconfig.json
└── tsconfig.schematics.json
Download .txt
SYMBOL INDEX (47 symbols across 11 files)

FILE: index.js
  function __export (line 2) | function __export(m) {

FILE: lib/adapter/azure-adapter.ts
  function createHandlerAdapter (line 4) | function createHandlerAdapter(handler) {

FILE: lib/adapter/azure-reply.ts
  class AzureReply (line 3) | class AzureReply extends OutgoingMessage {
    method constructor (line 8) | constructor(context: Record<string, any>) {
    method writeHead (line 18) | writeHead(
    method finish (line 38) | finish(context: Record<string, any>, body: Record<string, any> | undef...

FILE: lib/adapter/azure-request.ts
  class AzureRequest (line 3) | class AzureRequest extends Readable {
    method constructor (line 10) | constructor(context: Record<string, any>) {

FILE: lib/azure-http.adapter.ts
  class AzureHttpAdapterStatic (line 9) | class AzureHttpAdapterStatic {
    method handle (line 10) | handle(
    method createHandler (line 21) | private async createHandler(
    method hasGetTypeMethod (line 36) | private hasGetTypeMethod(

FILE: lib/router/azure-http.router.ts
  class AzureHttpRouter (line 19) | class AzureHttpRouter extends AbstractHttpAdapter {
    method constructor (line 22) | constructor() {
    method handle (line 26) | public handle(context: Record<string, any>, request: any) {
    method handleNotFound (line 45) | public handleNotFound(
    method enableCors (line 59) | public enableCors(options: CorsOptions) {
    method reply (line 63) | public reply(response: any, body: any, statusCode?: number) {
    method status (line 68) | public status(response: any, statusCode: number) {
    method end (line 72) | public end(response: any, message?: string) {
    method getHttpServer (line 76) | public getHttpServer<T = any>(): T {
    method getInstance (line 80) | public getInstance<T = any>(): T {
    method isHeadersSent (line 84) | public isHeadersSent(response: any): boolean {
    method setHeader (line 88) | public setHeader(response: any, name: string, value: string) {
    method getRequestMethod (line 92) | public getRequestMethod(request: any): string {
    method getRequestUrl (line 96) | public getRequestUrl(request: any): string {
    method getRequestHostname (line 100) | public getRequestHostname(request: any): string {
    method createMiddlewareFactory (line 104) | public createMiddlewareFactory(
    method getType (line 112) | public getType(): string {
    method applyVersionFilter (line 116) | public applyVersionFilter(
    method listen (line 127) | public listen(port: any, ...args: any[]) {}
    method render (line 128) | public render(response: any, view: string, options: any) {}
    method redirect (line 129) | public redirect(response: any, statusCode: number, url: string) {}
    method close (line 130) | public close() {}
    method initHttpServer (line 131) | public initHttpServer() {}
    method useStaticAssets (line 132) | public useStaticAssets(options: any) {}
    method setViewEngine (line 133) | public setViewEngine(options: any) {}
    method registerParserMiddleware (line 134) | public registerParserMiddleware() {}
    method setNotFoundHandler (line 135) | public setNotFoundHandler(handler: Function) {}
    method setErrorHandler (line 136) | public setErrorHandler(handler: Function) {}

FILE: schematics/install/files/project/__sourceRoot__/main.azure.ts
  function createApp (line 5) | async function createApp(): Promise<INestApplication> {

FILE: schematics/install/files/root/__rootDir__/main.azure.ts
  function createApp (line 5) | async function createApp(): Promise<INestApplication> {

FILE: schematics/install/index.test.ts
  function createTestNest (line 342) | async function createTestNest(

FILE: schematics/install/index.ts
  type UpdateJsonFn (line 24) | type UpdateJsonFn<T> = (obj: T) => T | void;
  function addDependenciesAndScripts (line 26) | function addDependenciesAndScripts(): Rule {
  function updateJsonFile (line 47) | function updateJsonFile<T>(

FILE: schematics/install/schema.ts
  type Schema (line 1) | interface Schema {
Condensed preview — 49 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (58K chars).
[
  {
    "path": ".circleci/config.yml",
    "chars": 1554,
    "preview": "version: 2\n\naliases:\n  - &restore-cache\n    restore_cache:\n      name: Restore Yarn Package Cache\n      keys:\n        - "
  },
  {
    "path": ".commitlintrc.json",
    "chars": 466,
    "preview": "{\n  \"extends\": [\"@commitlint/config-angular\"],\n  \"rules\": {\n    \"subject-case\": [\n      2,\n      \"always\",\n      [\"sente"
  },
  {
    "path": ".eslintrc.js",
    "chars": 559,
    "preview": "module.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    sourceTyp"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "chars": 1353,
    "preview": "<!--\nPLEASE HELP US PROCESS GITHUB ISSUES FASTER BY PROVIDING THE FOLLOWING INFORMATION.\n\nISSUES MISSING IMPORTANT INFOR"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "chars": 1068,
    "preview": "## PR Checklist\nPlease check if your PR fulfills the following requirements:\n\n- [ ] The commit message follows our guide"
  },
  {
    "path": ".gitignore",
    "chars": 290,
    "preview": "# dependencies\n/node_modules\n\n# IDE\n/.idea\n/.awcache\n/.vscode\n\n# misc\nnpm-debug.log\n.DS_Store\n\n# tests\n/test\n/coverage\n/"
  },
  {
    "path": ".npmignore",
    "chars": 159,
    "preview": "# source\nlib\n/index.ts\npackage-lock.json\ntslint.json\n.prettierrc\n\n# schematics\nschematics/install/*.ts\nschematics/instal"
  },
  {
    "path": ".prettierignore",
    "chars": 32,
    "preview": "schematics/install/files/**/*.ts"
  },
  {
    "path": ".prettierrc",
    "chars": 52,
    "preview": "{\n  \"trailingComma\": \"none\",\n  \"singleQuote\": true\n}"
  },
  {
    "path": ".release-it.json",
    "chars": 110,
    "preview": "{\n  \"git\": {\n    \"commitMessage\": \"chore(): release v${version}\"\n  },\n  \"github\": {\n    \"release\": true\n  }\n}\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 11619,
    "preview": "# Contributing to Nest\n\nWe would love for you to contribute to Nest and help make it even better than it is\ntoday! As a "
  },
  {
    "path": "LICENSE",
    "chars": 1106,
    "preview": "MIT License\n\nCopyright (c) 2017-2021 Kamil Mysliwiec <https://kamilmysliwiec.com>\n\nPermission is hereby granted, free of"
  },
  {
    "path": "README.md",
    "chars": 4192,
    "preview": "<p align=\"center\">\n  <a href=\"http://nestjs.com/\" target=\"blank\"><img src=\"https://nestjs.com/img/logo_text.svg\" width=\""
  },
  {
    "path": "index.d.ts",
    "chars": 24,
    "preview": "export * from './dist';\n"
  },
  {
    "path": "index.js",
    "chars": 167,
    "preview": "\"use strict\";\nfunction __export(m) {\n    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nexports._"
  },
  {
    "path": "index.ts",
    "chars": 24,
    "preview": "export * from './dist';\n"
  },
  {
    "path": "jest.json",
    "chars": 333,
    "preview": "  \n{\n    \"moduleFileExtensions\": [\"js\", \"ts\"],\n    \"rootDir\": \".\",\n    \"testEnvironment\": \"node\",\n    \"testRegex\": \".(te"
  },
  {
    "path": "lib/adapter/azure-adapter.ts",
    "chars": 314,
    "preview": "import { AzureRequest } from './azure-request';\nimport { AzureReply } from './azure-reply';\n\nexport function createHandl"
  },
  {
    "path": "lib/adapter/azure-reply.ts",
    "chars": 1341,
    "preview": "import { OutgoingMessage } from 'http';\n\nexport class AzureReply extends OutgoingMessage {\n  private readonly _headerSen"
  },
  {
    "path": "lib/adapter/azure-request.ts",
    "chars": 724,
    "preview": "import { Readable } from 'stream';\n\nexport class AzureRequest extends Readable {\n  readonly url: string;\n  readonly cont"
  },
  {
    "path": "lib/adapter/index.ts",
    "chars": 97,
    "preview": "export * from './azure-adapter';\nexport * from './azure-reply';\nexport * from './azure-request';\n"
  },
  {
    "path": "lib/azure-http.adapter.ts",
    "chars": 1313,
    "preview": "/* eslint-disable @typescript-eslint/ban-types */\nimport { Context, HttpRequest } from '@azure/functions';\nimport { Http"
  },
  {
    "path": "lib/index.ts",
    "chars": 91,
    "preview": "export * from './azure-http.adapter';\nexport * from './router';\nexport * from './adapter';\n"
  },
  {
    "path": "lib/router/azure-http.router.ts",
    "chars": 3783,
    "preview": "/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disab"
  },
  {
    "path": "lib/router/index.ts",
    "chars": 37,
    "preview": "export * from './azure-http.router';\n"
  },
  {
    "path": "package.json",
    "chars": 2259,
    "preview": "{\n  \"name\": \"@nestjs/azure-func-http\",\n  \"version\": \"0.10.0\",\n  \"description\": \"Nest - modern, fast, powerful node.js we"
  },
  {
    "path": "renovate.json",
    "chars": 157,
    "preview": "{\n  \"semanticCommits\": true,\n  \"packageRules\": [{\n    \"depTypeList\": [\"devDependencies\"],\n    \"automerge\": true\n  }],\n  "
  },
  {
    "path": "schematics/collection.json",
    "chars": 351,
    "preview": "{\n  \"$schema\": \"../node_modules/@angular-devkit/schematics/collection-schema.json\",\n  \"schematics\": {\n    \"nest-add\": {\n"
  },
  {
    "path": "schematics/install/files/project/.funcignore",
    "chars": 66,
    "preview": "*.js.map\n*.ts\n.git*\n.vscode\nlocal.settings.json\ntest\ntsconfig.json"
  },
  {
    "path": "schematics/install/files/project/__project__/function.json",
    "chars": 337,
    "preview": "{\n  \"bindings\": [\n    {\n      \"authLevel\": \"anonymous\",\n      \"type\": \"httpTrigger\",\n      \"direction\": \"in\",\n      \"nam"
  },
  {
    "path": "schematics/install/files/project/__project__/index.ts",
    "chars": 316,
    "preview": "import { Context, HttpRequest } from '@azure/functions';\nimport { AzureHttpAdapter } from '@nestjs/azure-func-http';\nimp"
  },
  {
    "path": "schematics/install/files/project/__project__/webpack.config.js",
    "chars": 214,
    "preview": "module.exports = function (options) {\n  return {\n    ...options,\n    entry: __dirname + '/index.ts',\n    output: {\n     "
  },
  {
    "path": "schematics/install/files/project/__sourceRoot__/main.azure.ts",
    "chars": 393,
    "preview": "import { INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { <%= getRootModul"
  },
  {
    "path": "schematics/install/files/project/host.json",
    "chars": 23,
    "preview": "{\n  \"version\": \"2.0\"\n}\n"
  },
  {
    "path": "schematics/install/files/project/local.settings.json",
    "chars": 116,
    "preview": "{\n  \"IsEncrypted\": false,\n  \"Values\": {\n    \"AzureWebJobsStorage\": \"\",\n    \"FUNCTIONS_WORKER_RUNTIME\": \"node\"\n  }\n}\n"
  },
  {
    "path": "schematics/install/files/project/proxies.json",
    "chars": 72,
    "preview": "{\n  \"$schema\": \"http://json.schemastore.org/proxies\",\n  \"proxies\": {}\n}\n"
  },
  {
    "path": "schematics/install/files/root/.funcignore",
    "chars": 66,
    "preview": "*.js.map\n*.ts\n.git*\n.vscode\nlocal.settings.json\ntest\ntsconfig.json"
  },
  {
    "path": "schematics/install/files/root/__rootDir__/main.azure.ts",
    "chars": 371,
    "preview": "import { INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { <%= getRootModul"
  },
  {
    "path": "schematics/install/files/root/host.json",
    "chars": 23,
    "preview": "{\n  \"version\": \"2.0\"\n}\n"
  },
  {
    "path": "schematics/install/files/root/local.settings.json",
    "chars": 116,
    "preview": "{\n  \"IsEncrypted\": false,\n  \"Values\": {\n    \"AzureWebJobsStorage\": \"\",\n    \"FUNCTIONS_WORKER_RUNTIME\": \"node\"\n  }\n}\n"
  },
  {
    "path": "schematics/install/files/root/main/function.json",
    "chars": 294,
    "preview": "{\n  \"bindings\": [\n    {\n      \"authLevel\": \"anonymous\",\n      \"type\": \"httpTrigger\",\n      \"direction\": \"in\",\n      \"nam"
  },
  {
    "path": "schematics/install/files/root/main/index.ts",
    "chars": 309,
    "preview": "import { Context, HttpRequest } from '@azure/functions';\nimport { AzureHttpAdapter } from '@nestjs/azure-func-http';\nimp"
  },
  {
    "path": "schematics/install/files/root/proxies.json",
    "chars": 72,
    "preview": "{\n  \"$schema\": \"http://json.schemastore.org/proxies\",\n  \"proxies\": {}\n}\n"
  },
  {
    "path": "schematics/install/index.test.ts",
    "chars": 10679,
    "preview": "import { FileEntry, Tree } from '@angular-devkit/schematics';\nimport {\n  SchematicTestRunner,\n  UnitTestTree\n} from '@an"
  },
  {
    "path": "schematics/install/index.ts",
    "chars": 3675,
    "preview": "import { strings } from '@angular-devkit/core';\nimport { parse as parseJson } from 'jsonc-parser';\nimport {\n  apply,\n  c"
  },
  {
    "path": "schematics/install/schema.json",
    "chars": 1012,
    "preview": "{\n  \"$schema\": \"http://json-schema.org/schema\",\n  \"$id\": \"SchematicsNestEngineInstall\",\n  \"title\": \"Nest Engine Install "
  },
  {
    "path": "schematics/install/schema.ts",
    "chars": 459,
    "preview": "export interface Schema {\n  /**\n   * Application root directory\n   */\n  rootDir?: string;\n  /**\n   * The name of the roo"
  },
  {
    "path": "tsconfig.json",
    "chars": 415,
    "preview": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"noImplicitAny\": false,\n    \"removeComme"
  },
  {
    "path": "tsconfig.schematics.json",
    "chars": 235,
    "preview": "{\n  \"compilerOptions\": {\n    \"rootDir\": \"schematics\",\n    \"outDir\": \"./schematics\"\n  },\n  \"extends\": \"./tsconfig.json\",\n"
  }
]

About this extraction

This page contains the full source code of the nestjs/azure-func-http GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 49 files (51.6 KB), approximately 14.4k tokens, and a symbol index with 47 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!