Commit Graph

54 Commits

Author SHA1 Message Date
Chris Olszewski
5dedc7b2ce feat(turbo): add support for turbo 2 configuration (#11680)
With the release of Turborepo 2 we're renaming `pipeline` to `tasks`. 

This PR updates the default settings logic to look in `tasks` for a
`build` task definition in addition to looking at `pipeline`. It also
updates the message to no longer mention Turbo configuration in
`package.json` as this is fully ignored in Turborepo 2.

Added a quick unit test to verify `build` task definitions are found in
the `tasks` section of `turbo.json`.

Please let me know if there are other tests/places I should update.
2024-06-04 10:36:35 -07:00
Nathan Rajlich
1333071a3a Remix Vite plugin support (#11031)
Adds support for Remix apps which use the new Remix Vite plugin.

* The vanilla Remix + Vite template deploys correctly out-of-the-box,
however only a single Node.js function will be used, and a warning will
be printed saying to configure the `vercelPreset()` Preset.
* When used in conjunction with the `vercelPreset()` Preset
(https://github.com/vercel/remix/pull/81), allows for the application to
utilize Vercel-specific features, like per-route `export const config`
configuration, including multi-runtime (Node.js / Edge runtimes) within
the same app.

## To test this today

1. Generate a Remix + Vite project from the template:
    ```
    npx create-remix@latest --template remix-run/remix/templates/vite
    ```
1. Install `@vercel/remix`:
    ```
    npm i --save-dev @vercel/remix
    ```
1. **(Before Remix v2.8.0 is released)** - Update the `@remix-run/dev`
dependency to use the "pre" tag which contains [a bug
fix](https://github.com/remix-run/remix/pull/8864):
    ```
    npm i --save--dev @remix-run/dev@pre @remix-run/serve@pre
    ```
1. Configure the `vercelPreset()` in the `vite.config.ts` file:
    ```diff
    --- a/vite.config.ts
    +++ b/vite.config.ts
    @@ -1,10 +1,11 @@
     import { vitePlugin as remix } from "@remix-run/dev";
     import { installGlobals } from "@remix-run/node";
     import { defineConfig } from "vite";
    +import { vercelPreset } from "@vercel/remix/vite";
     import tsconfigPaths from "vite-tsconfig-paths";
    
     installGlobals();
    
     export default defineConfig({
    -  plugins: [remix(), tsconfigPaths()],
    +  plugins: [remix({ presets: [vercelPreset()] }), tsconfigPaths()],
     });
    ```
1. Create a new Vercel Project in the dashboard, and ensure the Vercel
preset is set to "Remix" in the Project Settings. The autodetection will
work correctly once this PR is merged, but for now it gets incorrectly
detected as "Vite" preset.
* **Hint**: You can create a new empty Project by running the `vercel
link` command.
<img width="545" alt="Screenshot 2024-02-27 at 10 37 11"
src="https://github.com/vercel/vercel/assets/71256/f46baf57-5d97-4bde-9529-c9165632cb30">
1. Deploy to Vercel, setting the `VERCEL_CLI_VERSION` environment
variable to use the changes in this PR:
    ```
vercel deploy -b
VERCEL_CLI_VERSION=https://vercel-git-tootallnate-zero-1217-research-remix-v-next-vite.vercel.sh/tarballs/vercel.tgz
    ```
2024-02-28 11:22:05 -06:00
Chris Barber
5e6ef3d569 Enable source maps in tests (#10725)
The `tsconfig` files were unified with a common configuration in https://github.com/vercel/vercel/pull/10667 including disabling source maps. The source maps greatly increase the distribution size, but they are invaluable when the tests run, so this PR enables source maps for tests including adding a `tsconfig.json` where absent.

Linear: https://linear.app/vercel/issue/ZERO-364/enable-sourcemaps-in-all-testtsconfigjson-files
2023-10-17 15:15:29 +00:00
Trek Glowacki
2f5b0aeeb1 [cli] Update bun detection and add tests for projects with both bunlock.b and yarn.lock files (#10583)
Updates package manager detection to account for two lock files. All other managers will only have the one lock file. Bun, however, may have both a `bun.lockb` _and_ a `yarn.lock` file. To ensure bun is properly detected, the presence of `bun.lockb` with `yarn.lock` must occur before `yarn.lock` so we don't mistake the presence of a `yarn.lock` to mean "Yarn".

This PR also adds a test for this situation in `fs-detectors`. The behavior is currently correct there, but was not tested initially. It is now to avoid future regressions.
2023-09-26 21:11:57 +00:00
Steven
1b6f3a0f65 [fs-detectors] Add support for bun detection in monorepo (#10511)
E2E test looks like:

```sh
bunx create-turbo@canary
cd my-turborepo
gh repo create
vc link --repo
vc deploy
```
2023-09-15 14:13:26 -04:00
Nathan Rajlich
ed806d8a6b [frameworks][fs-detectors] Add "supersedes" prop to Framework interface (#10345)
The `supersedes` property on the `Framework` interface may be specified by a framework in which the superseded framework should _not_ be included in the resulting framework matches during detection.

For example, a Hydrogen v2 project matches both the "remix" and "hydrogen" framework detectors, but we really only want "remix" to be selected.
2023-08-17 07:30:32 +00:00
Trek Glowacki
19addabb6e [cli] Add tests to demonstrate function detection precedence (#10331)
Co-authored-by: Trek Glowacki <trek.glowacki@vercel.com>
2023-08-11 11:18:13 -05:00
Nathan Rajlich
abd1197c90 [fs-detectors] Fix "hydrogen-2" detection unit test (#10325)
Follow-up to https://github.com/vercel/vercel/pull/10319, which didn't exhibit this failing test since the fs-detectors package was not changed, and thus those tests didn't run.
2023-08-10 21:25:51 +00:00
Nathan Rajlich
f85df894c0 [fs-detectors] Add detectFrameworks() (#10195)
Similar to `detectFramework()`, but this version returns all detected frameworks at the given path. It also returns the full `Framework` objects instead of just the slug.

This will be useful for detecting when multiple Projects exist at the same root directory (i.e. Storybook).

**Note:** I rearranged some tests, so probably review with [whitespace changes hidden](https://github.com/vercel/vercel/pull/10195/files?diff=split&w=1).
2023-07-11 20:08:55 +00:00
Nathan Rajlich
8d7206f5b6 [cli] Run local Project detection during vc link --repo (#10094)
Run local Project detection during `vc link --repo`. This allows for creation of new Projects that do not yet exist under the selected scope.
2023-07-10 22:42:13 +00:00
Nathan Rajlich
3138415533 [fs-detectors] Resolve symlinks in LocalFileSystemDetector#readdir() (#10126)
`LocalFileSystemDetector#readdir()` was throwing an error when a symlink was encountered, due to `fs.readdir()` `withFileTypes: true` option performing an lstat instead of a stat operation.

So re-implement the `readdir()` logic to use `fs.stat()` so that the symlink is resolved (only "dir" and "file" types are expected in the result).
2023-06-22 18:19:28 +00:00
Nathan Rajlich
a5af8381ce [fs-detectors] Add test-e2e script (#10103)
Seems we have not been running the `fs-detectors` integration tests.
2023-06-14 19:20:20 +00:00
Nathan Rajlich
42c0b32a8d [fs-detectors] Use LocalFileSystemDetector instead of FixtureFilesystem (#10100)
The code for these two are almost identical, so consolidate into one codebase.

Also adjusts the `pnpm test` script to allow for specifying a file name to be executed, instead of running all tests.
2023-06-13 23:30:00 +00:00
Sean Massa
761db597be clarify next.js dupe api directory warning (#9979)
In a Next.js app, if you have Node.js Functions in both `api` and `pages/api`, you'll get a warning about moving those `api` functions into `pages/api`. This does specify Node.js Functions already, but a user was confused and tried to move their non-Node.js functions into `pages/api` as well.

This PR tries to make it clearer that you can do both. Note that this still requires a non-ideal local dev setup where you:

- update next config to fall back to the `vc dev` port for `api` handlers
- run `next dev` for the Next.js app on one port
- run `vc dev` for the top-level `api` Functions on another port

---

Example repo: https://github.com/rexfordessilfie/vercel-api-languages
2023-05-19 19:31:32 +00:00
Chris Barber
6cdd38d130 [tests] Pin Next.js version in test fixtures (#9910)
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2023-05-19 09:06:08 -05:00
Chris Barber
7a0dacf8bb [cli][fs-detectors][frameworks] Re-add Storybook support (#9891)
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2023-05-03 14:05:44 -05:00
Chris Barber
678e13af53 [cli][fs-detectors][frameworks] Revert Storybook support (#9890) 2023-05-02 10:03:28 -05:00
Nathan Rajlich
603a7d8787 [fs-detectors] Add disableRootMiddleware, bypass ignoreRuntimes for root-level "middleware" files (#9883)
`ignoreRuntimes: ['@vercel/node']` will also disable root-level middleware, which is not intended. So ensure that middleware still work, even for frameworks that have this `ignoreRuntimes` configuration enabled (Remix, RedwoodJS).
2023-05-01 20:53:35 +00:00
Chris Barber
9240cbc022 [cli][fs-detectors][frameworks] Add Storybook support (#9839)
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2023-05-01 11:25:06 -05:00
Sean Massa
e302631ded [fs-detectors] check turbo versions to allow for tags like "latest" (#9790)
When a project depends on `turbo` at version `latest`, this code was breaking because `latest` is not a valid range for `semver.intersects`.
2023-04-11 21:22:41 +00:00
Nathan Hammond
10d14488db [fs-detectors] Fix turbo@1.8 all filters are inferred (#9680)
We no longer need to specify the active folder for `turbo` to identify the context correctly.
2023-03-31 21:02:30 +00:00
Felix Haus
46c0fd153a [fs-detectors] Remove increments of 64 limit for function memory (#9465)
Missed this occurrence so it still prevents the upload of serverless
functions that have a mem value that is not dividable by 64.
Should be the last place before we can ship the documentation update.

#### Related PRs
- #9440

Co-authored-by: Steven <steven@ceriously.com>
2023-02-16 16:42:42 -05:00
chloetedder
084125d90f [fs-detectors] Add main to test package.json files (#9416)
Fix flakey tests
2023-02-10 22:56:01 +00:00
Steven
2b483b0fd0 [tests] Fix examples tests with shared util (#9415)
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2023-02-10 16:32:45 -06:00
chloetedder
2eef3e3ddb [fs-detectors] Add fix for if monorepo and proj at root (#9353)
If there is a monorepo that has one project at the root level we want to
return commands without the relative to root prefixes

---------

Co-authored-by: Chris Barber <chris.barber@vercel.com>
2023-02-03 16:56:22 -06:00
chloetedder
31f3daa5b4 [fs-detectors] getMonorepoDefaultSettings: Fix settings (#9315)
1. `commandForIgnoringBuildStep` should be run at the project directory level not the monorepo root level
2. Simplifying the `installCommand` because doesn't need the relative root unless it is `npm`
2023-01-30 18:35:42 +00:00
Steven
2004e3d734 [tests] Fix jest-haste-map: Haste module naming collision (#9317)
```
jest-haste-map: Haste module naming collision: app-three
The following files share their name; please adjust your hasteImpl:
  * <rootDir>/test/fixtures/33-hybrid-monorepo/backend/app-three/package.json
  * <rootDir>/test/fixtures/34-monorepo-no-workspaces/backend/app-three/package.json
```
2023-01-26 00:59:39 +00:00
Sean Massa
7c50f2916e [frameworks] update framework detectors with packages (#9167)
In [a different PR](https://github.com/vercel/vercel/pull/9009), detecting frameworks by package name will also provide framework version metadata to the build. Should we update these framework detectors to look up their respective packages or were they not doing that already for a reason?

I left the old detectors in place as fallbacks, which looks like:

```
some: [
  {
    path: 'package.json',
    matchContent:
      '"(dev)?(d|D)ependencies":\\s*{[^}]*"remix":\\s*".+?"[^}]*}',
  },
  {
    path: 'remix.config.js',
  },
],
```

Please review carefully.
2023-01-13 19:04:59 +00:00
Steven
1efb5d6c0d [fs-detectors] Add support for api/**/*.tsx zero config detection (#9216)
There are cases where you would want to use `.tsx` with Serverless Functions, such as OG Image Generation.

This PR adds zero config detection for `.tsx` file extensions and also consolidates the glob pattern into a single string matching all valid `@vercel/node` cases.

https://twitter.com/hasparus/status/1593136849404694528

https://linear.app/vercel/issue/VCCLI-322
2023-01-13 17:59:49 +00:00
Sean Massa
72df5ce8f6 [examples][frameworks] add tests for all examples being detected (#9197)
This PR adds tests (under `packages/fs-detectors`) that ensure are `./examples` get detected as the appropriate framework.
2023-01-13 17:24:00 +00:00
Sean Massa
8f1358bd15 [cli][frameworks][fs-detectors][next] detect framework versions (#9009)
This PR:

- updates `packages/frameworks` to have most supported frameworks specify which dependency version should reflect the overall framework version
- updates `packages/fs-detectors` to allow framework detection that returns the full `Framework` record instead of just the slug
- updates `packages/next` to return the detected Next.js version in the build result
- updates `packages/cli` to leverage these changes so that `vc build` can add `framework: { version: string; }` to `config.json` output

The result is that Build Output API and supported frameworks will return their framework version in the build result of `vc build` when possible, which is used by the build container  when creating the deployment. The dashboard later retrieves this value to display in richer deployment outputs.

Supports:

- https://github.com/vercel/api/pull/15601
- https://github.com/vercel/front/pull/18319

---

With the related build container updates, we get to see Next.js version in the build output. You'll see this with BOA+Prebuilt or a normal deploy:

<img width="1228" alt="Screen Shot 2022-12-09 at 2 48 12 PM" src="https://user-images.githubusercontent.com/41545/206793639-f9cd3bdf-b822-45dd-9564-95b94994271d.png">

---

### The Path to this PR

I went through all the supported frameworks and figured out how to best determine their versions. For most of them, we can check a known dependency's installed version number. 

We can get most of the way only checking npm. For a handful, we'd have to support Go/Ruby/Rust/Whatever dependencies.

I started with a more complex method signature to allow for later expansion without changing the signature. It looked like this, in practice:

```
async getVersion(dependencies: DependencyMap) => depedencies['next']
```

However, after checking all currently supported frameworks, I don't think this will end up being necessary. It also has the constraint that all dependencies have to be gathered and presented to the function even though it only needs to check for one or two. That's not a huge deal if we have them already where we need them, but we don't. We could use a variant here where this function does its own lookups, but this seemed unnecessary and would beg for duplication and small variances that could cause bugs.

Further, if we only look at `package.json`, we're going to either see a specific version of a version range. To be precise, we have to look at the installed version of the package. That means checking one of the various types of lockfiles that can exist or poking into node_modules.

If we poke into node_modules to detect the installed version, we introduce another point where Yarn 3 (default mode) will not be supported. If we read lockfiles, we have to potentially parse `npm`, `pnpm`, and `yarn` lockfiles.

If we use `npm ls <package-name>`, that also fails in Yarn 3 (default mode). We could accept that and go forward anyway, which would look like:

```
const args = `ls ${packageName} --depth=0 --json`.split(' ');
const { stdout } = await execa('npm', args, { cwd });
const regex = new RegExp(String.raw`${packageName}@([\.\d]+)`);
const matches = stdout.match(regex);
if (matches) {
  return matches[1];
}
```

But it turns out there's a `--json` option! That's what I ended up using, for now.

We could explore the lockfile route more, but after some initial digging, it' non-trivial. There are 3 main lockfiles we'd want to check for (npm, pnpm, and yarn) and there are different lockfile versions that put necessary data in different places. I looked for existing tools that parse this, but I didn't find any. We could certainly go down this path, but the effort doesn't seem worth it when `npm ls` gets us really close.

---

### Follow-up Versioning

Now that we know how to determine version per framework, we can vary configuration by version. In a future PR, we could allow a given value to vary by version number:

```
name: (version) => {
  if (semver.gt(version, '9.8.7')) {
    return 'some-framework-2''
  }

  return 'some-framework';
}
```

However, it may still be easier to differentiate significant versions by adding multiple entries in the list.
2023-01-13 07:50:00 +00:00
Ethan Arrowood
16a5867f6b [fs-detectors] use project path instead of name for turbo filter (#9210)
Fixes: https://github.com/orgs/vercel/discussions/1218
2023-01-12 18:01:38 +00:00
Ethan Arrowood
d800d9cd68 [fs-detectors][cli] move monorepo default setting code to fs-detectors (#9101)
Makes the monorepo default setting logic reusable by API and includes a `commandForIgnoringBuildStep` setting for Turbo projects.
2023-01-05 21:16:03 +00:00
Sean Massa
fe184618f4 [frameworks] fix blitzjs detection (#9166)
The framework detectors do not support this syntax:

```
path: 'blitz.config.(js|ts)',
```

This PR fixes framework detection for "Blitz.js (Legacy)".
2023-01-05 16:29:39 +00:00
Nathan Rajlich
896dd04cd7 [fs-detectors] Don't add "api/*" 404 route when only a middleware is present (#8920)
This route should not be added when there are no explicit builds under
the "api" directory.

Fixes https://github.com/sveltejs/kit/issues/6777.
2022-11-16 09:33:17 -08:00
Nathan Rajlich
2dae293c1e [fs-detectors] Remove limitedRoutes (#8921)
These were only used for FS API v2, and are no longer needed.
2022-11-16 17:21:45 +00:00
Ethan Arrowood
a8822170d6 [fs-detectors] restore rush support in fs-detectors (#8907)
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2022-11-14 14:23:12 -06:00
Ethan Arrowood
0663524cd7 [cli][fs-detectors] Improve vc build monorepo support (#8742)
### Related Issues

Improves how `vc build` handles monorepos. In short, this introduces
monorepo manager detection logic and then some helpful defaults so users
don't have to manually specify a `buildCommand` or `installCommand` when
linking a project within a monorepo.

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-11-14 10:23:33 -07:00
chloetedder
0d044b4eac [fs-detectors] Use json5 parser for Rush to have valid json parsing (#8645)
### Related Issues

Parse `rush.json` files with `json5` because it is very common for these
to have comments in them

[Template for people to clone for
Rush](https://rushjs.io/pages/configs/rush_json/) which has comments in
it as a default which most people will clone
 
Docs of Rush showing to not use `JSON.parse`

https://rushjs.io/pages/help/faq/#why-do-rushs-json-config-files-contain--comments-that-github-shows-in-red

Added in tests with block comments and single line comments

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR

Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2022-09-28 06:38:25 -05:00
Andrew Gadzik
288546659d [fs-detectors] ensure processing of potentialFiles for readdir cache hits (#8604)
This is to fix the issue with processing  new entries of `potentialFiles` when there was a `readdir` cache hit 

### Related Issues

Related to https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2022-09-21 20:59:21 +00:00
chloetedder
a6aee8b904 [fs-detectors] Rush json workspace (#8603)
### Related Issues

Add in getting the package paths for Rush workspaces.
First get the contents of the `rush.json` file. If the `projects`
property is an array, map through that array and return the
`projectFolder` as the package path.


### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
2022-09-21 13:00:21 -05:00
Steven
4536029d42 Revert "[fs-detectors] Rush json workspace" (#8591)
Reverts vercel/vercel#8565 since tests are failing on windows

https://github.com/vercel/vercel/actions/runs/3091763554/jobs/5002704682
2022-09-20 15:13:23 -04:00
chloetedder
c2bca954e0 [fs-detectors] Rush json workspace (#8565)
### Related Issues

Add in Rush workspace

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
2022-09-20 12:14:45 -05:00
chloetedder
6498fd1aab [fs-detectors] Add Nx Workspace (#8549)
### Related Issues


https://nx.dev/more-concepts/folder-structure#integrated-repo-folder-structure

Nx monorepo has an option to use Nx workspaces.
Nx workspace is defined within the root `workspace.json` file
Within this `workspace.json` file the workspace packages are under
projects
```{
  "$schema": "./node_modules/nx/schemas/workspace-schema.json",
  "version": 2,
  "projects": {
    "myblog": "apps/myblog",
    "svelte-app": "apps/svelte-app",
  }
}
```
Within `getNxWorkspacePackagePaths` get the projects object values for
the paths
Nx is listed as the last workspace manager within
`workspace-managers.ts` because other workspace managers could exist to
check for before Nx workspaces because the `workspace.json` could exist
but not be the correct workspace manager

Nx workspace file can exist when yarn/npm workspaces exist. When this
happens, the workspace.json file is empty with no projects so it will
not add any package paths to the list to look through for projects.


### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
2022-09-14 15:10:14 -05:00
chloetedder
f23c7fc4fc [fs-detectors] Add monorepo managers (#8534)
### Related Issues

Adding in Nx and Rush as monorepo managers.
This will allow to help with starting zero config for both the above managers.
I have added in unit tests for both Nx and Rush.

### 📋 Checklist

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2022-09-09 22:51:56 +00:00
Andrew Gadzik
28f8a38e00 [fs-detectors] Add the writeFile function to DetectorFilesystem (#8536)
Adds a `writeFile` function to `DetectorFilesystem` that will be used to update the various file cache maps.

**Why is this needed?**

When detecting npm7+ monorepos, we identified a performance improvement where the service can inspect the `package-lock.json` file for workspaces, and reuse the package information for each workspace in framework-detection.

The pseudo code in `vercel/api` will look something like this

For a given lockfile
```json
{
  ...,
  "packages": {
    "": {
      "name": "npm-workspaces",
      "version": "1.0.0",
      "license": "ISC",
      "workspaces": {
        "packages": [
          "apps/*"
        ]
      }
    },
    "apps/admin": {
      "version": "0.1.0",
      "dependencies": {
        "next": "12.2.5",
        "react": "18.2.0",
        "react-dom": "18.2.0"
      },
      "devDependencies": {
        "eslint": "8.23.0",
        "eslint-config-next": "12.2.5"
      }
    },
    ...,
}
```

```ts
// for each projectPath we detect in package-lock.json
// switch the cwd of the fs to the project directory
const projectFs = fs.chdir(projectPath);
// gets the package info from the lockfile
const projectPackageInfo = lockFile.packages[projectPath];
// insert this content into fs cache
await projectFs.writeFile('package.json', projectPackageInfo)
// call detectFramework, which should now have a cached "package.json" file 
const projectFramework = await detectFramework(projectFs);
```

### Related Issues

Related to https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
2022-09-09 19:39:05 +00:00
Andrew Gadzik
4b1736b2f2 [fs-detectors] optimize readdir for framework detection (#8497)
Adding the ability to explicitly set the `hasPath` and `isFile` caches via `readdir`

**Why is this needed?**

For framework detection, this allows us to fetch the contents of a directory (the root directory) of a git repo, and make assumptions about the existence of files,

```ts
import frameworks from "@vercel/frameworks";

// we can make the set of all file paths needed for framework detection like this
const setOfPaths = new Set(
  frameworks.frameworks
    .flatMap((f) => [
      ...(f.detectors?.every ?? []),
      ...(f.detectors?.some ?? []),
    ])
    .map((d) => d.path)
);

// then we can read the contents of the root directory of a git repo via the `DetectorFilesystem`
fs.readdir('./', { potentialFiles: [...setOfPaths] });

// The filesystem has been fully primed - any network calls from here will only happen if needed.
// This works because the logic of `detectFramework` calls `hasPath` and then `isFile` before 
// fetching file contents.  Since the filesystem knows this information, it doesn't have to make 
// any additional network calls 🙌 
const framework = detectFramework(fs);
```

### Related Issues

Related to [HIT-57](https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits)

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
2022-09-07 15:35:56 -04:00
Andrew Gadzik
b480e632a3 Add writeFile to DetectorFilesystem (#8493)
Adds a `writeFile` function to `DetectorFilesystem` that will be used to update the various file cache maps.

When detecting npm7+ monorepos, we identified a performance improvement where the service can inspect the `package-lock.json` file for workspaces, and reuse the package information for each workspace in framework-detection.

The pseudo code in `vercel/api` will look something like this

For a given lockfile
```json
{
  ...,
  "packages": {
    "": {
      "name": "npm-workspaces",
      "version": "1.0.0",
      "license": "ISC",
      "workspaces": {
        "packages": [
          "apps/*"
        ]
      }
    },
    "apps/admin": {
      "version": "0.1.0",
      "dependencies": {
        "next": "12.2.5",
        "react": "18.2.0",
        "react-dom": "18.2.0"
      },
      "devDependencies": {
        "eslint": "8.23.0",
        "eslint-config-next": "12.2.5"
      }
    },
    ...,
}
```

```ts
// for each projectPath we detect in package-lock.json
// switch the cwd of the fs to the project directory
const projectFs = fs.chdir(projectPath);
// gets the package info from the lockfile
const projectPackageInfo = lockFile.packages[projectPath];
// insert this content into fs cache
projectFs.writeFile('package.json', projectPackageInfo)
// call detectFramework, which should now have a cached "package.json" file 
const projectFramework = await detectFramework(projectFs);
```

### Related Issues

Related to [HIT-57](https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits)

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2022-08-31 18:51:03 +00:00
Andrew Gadzik
b63f444abd [fs-detectors] Add a default workspace manager when there's no lock file (#8469)
This fixes an issue with this example,

https://vercel.com/api/v1/integrations/detect-eligible-projects?url=https%3A%2F%2Fgithub.com%2Fvercel%2Fturborepo%2Ftree%2Fmain%2Fexamples%2Fkitchen-sink

Where the repo has no lockfile, and hence our workspace detection fails.  This fix is to add a fallback of "npm" in this scenario

### Related Issues

Fixes https://github.com/vercel/turbo-internal/issues/232

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2022-08-26 16:24:13 +00:00
Seiya Nuta
71b3ded398 [fs-detectors] Exclude the middleware builder if it's a Next.js app (#8239) 2022-08-01 08:18:29 -04:00