Unverified Commit 286169a9 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Remove `turbopack/packages` and relocate devlow to `packages/` (#96860)

## Summary

`@vercel/devlow-bench` hasn't published since December 2024. The job
that published it was removed in #93064; it was gated on the head commit
message starting with `chore: release turbopack npm packages`, which
squash-merge rewrites, so it couldn't fire through normal review —
#93951 bumped the version correctly and still published nothing.

Rather than rebuild that machinery for `turbopack/packages/*`, this
moves the one remaining package to `packages/`, where lerna and the
existing recursive publish already handle everything.
**`publish-release.js` is unchanged.**

The tradeoff is that the package joins the Next.js lockstep version,
going from `0.4.0` to the current canary, and ships nightly instead of
on manual bumps. At ~10k downloads/month, essentially all CI, nobody is
reading its version for compatibility — not worth ~300 lines of bespoke
release code in the script that gates Next.js releases.

`packages/` already holds unscoped, non-`@next/` packages
(`create-next-app`, `eslint-config-next`, `next-rspack`), all lockstep.

The root eslint config covers `packages/` but never applied to
`turbopack/`, so this exempts the three rules the source doesn't satisfy
and prefixes six unused parameters, rather than reformatting the package
as part of a move.

## Deletions

Three nft packages, last published in 2022, none with a build script or
any consumer:

- `@vercel/experimental-nft` — a stub containing only a `package.json`
- `@vercel/webpack-nft` — resolved binaries built from a
`node-file-trace` crate that no longer exists, so its core codepath
couldn't work
- `@vercel/experimental-nft-next-plugin` — depends on the above

`turbopack/xtask/src/publish.rs` goes with them: its only caller was the
workflow removed in #93064, its `npm` subcommand targeted that same
missing crate, and nothing invokes `cargo xtask`.

`turbopack/packages/` no longer exists.

## Verification

- `publish-release.js --dry-run` — publishes `@vercel/devlow-bench` via
the untouched recursive publish
- `lerna list` and `turbo run build` both resolve it at the new path
- `pnpm run --filter=devlow-bench test` — 3/3, and the CI jobs reference
it by name, not path
- Root eslint and the package's own `lint` script both clean
- `cargo check`/`clippy`/`fmt -p xtask`
- Not run: a real publish, which only CI can exercise

`pnpm-lock.yaml` is hand-edited to repoint the workspace entry and drop
the three removed ones. A full `pnpm install` rewrites ~1800 unrelated
lines, and `--frozen-lockfile` fails identically on unmodified `canary`
from pre-existing `apps/docs` drift.

<!-- NEXT_JS_LLM -->
parent b3bc5cd2
...@@ -1906,22 +1906,6 @@ version = "0.8.20" ...@@ -1906,22 +1906,6 @@ version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
[[package]]
name = "crossterm"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
dependencies = [
"bitflags 1.3.2",
"crossterm_winapi",
"libc",
"mio 0.8.11",
"parking_lot",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]] [[package]]
name = "crossterm" name = "crossterm"
version = "0.26.1" version = "0.26.1"
...@@ -3879,22 +3863,6 @@ dependencies = [ ...@@ -3879,22 +3863,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "inquire"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a94f0659efe59329832ba0452d3ec753145fc1fb12a8e1d60de4ccf99f5364"
dependencies = [
"bitflags 1.3.2",
"crossterm 0.25.0",
"dyn-clone",
"lazy_static",
"newline-converter",
"thiserror 1.0.69",
"unicode-segmentation",
"unicode-width 0.1.13",
]
[[package]] [[package]]
name = "insta" name = "insta"
version = "1.46.3" version = "1.46.3"
...@@ -4891,15 +4859,6 @@ version = "1.0.6" ...@@ -4891,15 +4859,6 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "newline-converter"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f71d09d5c87634207f894c6b31b6a2b2c64ea3bdcf71bd5599fdbbe1600c00f"
dependencies = [
"unicode-segmentation",
]
[[package]] [[package]]
name = "next-api" name = "next-api"
version = "0.1.0" version = "0.1.0"
...@@ -10471,7 +10430,7 @@ version = "0.1.0" ...@@ -10471,7 +10430,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
"crossterm 0.26.1", "crossterm",
"owo-colors", "owo-colors",
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
"serde", "serde",
...@@ -13036,12 +12995,10 @@ dependencies = [ ...@@ -13036,12 +12995,10 @@ dependencies = [
"chrono", "chrono",
"clap", "clap",
"indexmap 2.13.0", "indexmap 2.13.0",
"inquire",
"num-format", "num-format",
"owo-colors", "owo-colors",
"plotters", "plotters",
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
"semver",
"serde", "serde",
"serde_json", "serde_json",
"tabled", "tabled",
......
...@@ -601,4 +601,15 @@ export default defineConfig([ ...@@ -601,4 +601,15 @@ export default defineConfig([
'no-console': 'off', 'no-console': 'off',
}, },
}, },
{
// Moved from turbopack/, where the root config never applied. Exempted from
// the rules it doesn't currently satisfy rather than reformatting it as
// part of the move.
files: ['packages/devlow-bench/**'],
rules: {
'@typescript-eslint/no-shadow': 'off',
'@typescript-eslint/consistent-type-imports': 'off',
'import/no-extraneous-dependencies': 'off',
},
},
]) ])
{ {
"name": "@vercel/devlow-bench", "name": "@vercel/devlow-bench",
"version": "0.4.0", "version": "16.3.1-canary.4",
"description": "Benchmarking tool for the developer workflow", "description": "Benchmarking tool for the developer workflow",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/vercel/next.js", "url": "https://github.com/vercel/next.js",
"directory": "turbopack/packages/devlow-bench" "directory": "packages/devlow-bench"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
...@@ -15,7 +15,6 @@ ...@@ -15,7 +15,6 @@
"bin": "dist/cli.js", "bin": "dist/cli.js",
"scripts": { "scripts": {
"lint": "eslint src/", "lint": "eslint src/",
"prerelease": "pnpm run build",
"test": "node --import tsx --test src/**/*-test.ts", "test": "node --import tsx --test src/**/*-test.ts",
"build": "tsc" "build": "tsc"
}, },
......
...@@ -8,7 +8,7 @@ export async function waitForFile( ...@@ -8,7 +8,7 @@ export async function waitForFile(
): Promise<void> { ): Promise<void> {
let currentAction = '' let currentAction = ''
let timeoutRef let timeoutRef
const timeoutPromise = new Promise<void>((resolve, reject) => { const timeoutPromise = new Promise<void>((_resolve, reject) => {
timeoutRef = setTimeout(() => { timeoutRef = setTimeout(() => {
reject( reject(
new Error(`Timed out waiting for file ${path} (${currentAction}))`) new Error(`Timed out waiting for file ${path} (${currentAction}))`)
......
...@@ -58,7 +58,7 @@ export default function createInterface({ ...@@ -58,7 +58,7 @@ export default function createInterface({
const dataPoints: DistributionPointsSeries[] = [] const dataPoints: DistributionPointsSeries[] = []
const metricMetadata: Record<string, MetricMetadata> = {} const metricMetadata: Record<string, MetricMetadata> = {}
const iface: Interface = { const iface: Interface = {
measurement: async (scenario, props, name, value, unit, relativeTo) => { measurement: async (scenario, props, name, value, unit, _relativeTo) => {
const ts = Math.round(Date.now() / 1000) const ts = Math.round(Date.now() / 1000)
const metric = toIdentifier(`devlow_bench/${scenario}/${name}`) const metric = toIdentifier(`devlow_bench/${scenario}/${name}`)
if (UNIT_MAPPING[unit]) { if (UNIT_MAPPING[unit]) {
...@@ -80,7 +80,7 @@ export default function createInterface({ ...@@ -80,7 +80,7 @@ export default function createInterface({
points: [[ts, [value]]], points: [[ts, [value]]],
}) })
}, },
end: async (scenario, props) => { end: async (_scenario, _props) => {
await api.submitDistributionPoints({ await api.submitDistributionPoints({
body: { body: {
series: dataPoints, series: dataPoints,
......
...@@ -83,7 +83,7 @@ export default function createInterface({ ...@@ -83,7 +83,7 @@ export default function createInterface({
git_branch: GIT_BRANCH, git_branch: GIT_BRANCH,
}) })
}, },
end: async (scenario, props) => { end: async (_scenario, _props) => {
await trackAnalytics(gatewayUri, topicName, schemaId, records) await trackAnalytics(gatewayUri, topicName, schemaId, records)
}, },
} }
......
...@@ -249,7 +249,7 @@ importers: ...@@ -249,7 +249,7 @@ importers:
version: 2.3.2(patch_hash=cb53bfa5effb15b3a361e176003df667cadf757b27b7c9b458c2f0fce86ea893) version: 2.3.2(patch_hash=cb53bfa5effb15b3a361e176003df667cadf757b27b7c9b458c2f0fce86ea893)
'@vercel/devlow-bench': '@vercel/devlow-bench':
specifier: workspace:* specifier: workspace:*
version: link:turbopack/packages/devlow-bench version: link:packages/devlow-bench
'@vercel/kv': '@vercel/kv':
specifier: 3.0.0 specifier: 3.0.0
version: 3.0.0 version: 3.0.0
...@@ -2003,7 +2003,7 @@ importers: ...@@ -2003,7 +2003,7 @@ importers:
specifier: ^5.1.2 specifier: ^5.1.2
version: 5.1.6(@babel/core@7.26.10)(babel-plugin-macros@3.1.0)(react@19.3.0-canary-11eddecd-20260805) version: 5.1.6(@babel/core@7.26.10)(babel-plugin-macros@3.1.0)(react@19.3.0-canary-11eddecd-20260805)
turbopack/packages/devlow-bench: packages/devlow-bench:
dependencies: dependencies:
'@datadog/datadog-api-client': '@datadog/datadog-api-client':
specifier: ^1.13.0 specifier: ^1.13.0
...@@ -2049,31 +2049,6 @@ importers: ...@@ -2049,31 +2049,6 @@ importers:
specifier: 4.19.2 specifier: 4.19.2
version: 4.19.2 version: 4.19.2
turbopack/packages/node-module-trace: {}
turbopack/packages/turbo-tracing-next-plugin:
dependencies:
'@vercel/webpack-nft':
specifier: workspace:*
version: link:../webpack-nmt
devDependencies:
next:
specifier: workspace:*
version: link:../../../packages/next
turbopack/packages/webpack-nmt:
dependencies:
'@vercel/experimental-nft':
specifier: workspace:*
version: link:../node-module-trace
devDependencies:
'@types/webpack':
specifier: ^5.28.0
version: 5.28.5(@swc/core@1.11.24(@swc/helpers@0.5.23))
webpack:
specifier: 5.98.0
version: 5.98.0(@swc/core@1.11.24(@swc/helpers@0.5.23))
packages: packages:
'@actions/core@1.10.1': '@actions/core@1.10.1':
...@@ -5,7 +5,6 @@ packages: ...@@ -5,7 +5,6 @@ packages:
- 'crates/*/js' - 'crates/*/js'
- 'turbopack/crates/*/js' - 'turbopack/crates/*/js'
- 'turbopack/crates/turbopack-tests/tests/execution' - 'turbopack/crates/turbopack-tests/tests/execution'
- 'turbopack/packages/*'
updateNotifier: false updateNotifier: false
publicHoistPattern: publicHoistPattern:
- '*eslint*' - '*eslint*'
......
...@@ -8,14 +8,7 @@ const repoRoot = path.join(scriptDir, '..') ...@@ -8,14 +8,7 @@ const repoRoot = path.join(scriptDir, '..')
const placeholders = [ const placeholders = [
path.join(repoRoot, 'packages', 'next', 'dist', 'bin', 'next'), path.join(repoRoot, 'packages', 'next', 'dist', 'bin', 'next'),
path.join(repoRoot, 'packages', 'create-next-app', 'dist', 'index.js'), path.join(repoRoot, 'packages', 'create-next-app', 'dist', 'index.js'),
path.join( path.join(repoRoot, 'packages', 'devlow-bench', 'dist', 'cli.js'),
repoRoot,
'turbopack',
'packages',
'devlow-bench',
'dist',
'cli.js'
),
] ]
for (const binPath of placeholders) { for (const binPath of placeholders) {
......
{
"name": "@vercel/experimental-nft",
"version": "0.0.5-alpha.0",
"description": "Node.js module trace",
"license": "MIT",
"alias": "node-file-trace",
"publishConfig": {
"access": "public"
}
}
# `@vercel/experimental-nft-next-plugin`
## Installation
- yarn add -D `@vercel/experimental-nft-next-plugin`
- npm install -D `@vercel/experimental-nft-next-plugin`
- pnpm install -D `@vercel/experimental-nft-next-plugin`
## Usage
```js
// next.config.js
const { createNodeFileTrace } = require('@vercel/experimental-nft-next-plugin')
const withNodeFileTrace = createNodeFileTrace({
// experimental nft options
log: {
all: true,
},
})
module.exports = withNodeFileTrace({
// next config
})
```
### experimental nft options
> **Note**
>
> The default options should work fine.
- `cwd?: string`, default is `process.cwd()`, you can override it to specify another directory to run experimental nft.
- `contextDirectory?: string`, relative to cwd, default is `.`. It must be the directory where the `node_modules` directory is located. If you are in the monorepo, you should set it to the root directory of the monorepo. For yarn2+/npm workspaces, the default value will respect the `PROJECT_CWD` and `npm_config_local_prefix` environment variables injected by yarn/npm client. If the default value doesn't work, you can override it to specify the root directory of the monorepo.
- `path?: string`, additional path which will be appended into the `PATH` environment variable.
- `log?.all?: boolean`, default is `false`, whether to show all logs.
- `log?.level?: string`, default is `error`, the log level.
- `log?.detail?: boolean`, default is `false`, whether to expand the log details.
{
"name": "@vercel/experimental-nft-next-plugin",
"version": "0.0.3-alpha.2",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist/**/*"
],
"publishConfig": {
"access": "public"
},
"dependencies": {
"@vercel/webpack-nft": "workspace:*"
},
"peerDependencies": {
"next": ">= 12"
},
"devDependencies": {
"next": "workspace:*"
},
"scripts": {
"lint": "eslint src/",
"lint:prettier": "prettier -c . --cache --ignore-path=../../.prettierignore"
}
}
import {
NodeModuleTracePlugin,
NodeModuleTracePluginOptions,
} from '@vercel/webpack-nft'
import type { NextConfig } from 'next'
export function createNodeFileTrace(options?: NodeModuleTracePluginOptions) {
return function withNodeFileTrace(config: NextConfig = {}) {
const createWebpackConfig = config.webpack
config.outputFileTracing = false
config.webpack = (webpackConfig, context) => {
const config =
createWebpackConfig?.(webpackConfig, context) ?? webpackConfig
if (context.isServer && !context.dev) {
const plugin = new NodeModuleTracePlugin(options)
if (config.plugins) {
config.plugins.push(plugin)
} else {
config.plugins = [plugin]
}
}
return config
}
return config
}
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# MongoDB and Mongoose with Next.js
Copied from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb.
Run `pnpm run --filter @vercel/turbo-tracing-test-app build` to build this application.
import { useState } from 'react'
import { useRouter } from 'next/router'
import { mutate } from 'swr'
const Form = ({ formId, petForm, forNewPet = true }) => {
const router = useRouter()
const contentType = 'application/json'
const [errors, setErrors] = useState({})
const [message, setMessage] = useState('')
const [form, setForm] = useState({
name: petForm.name,
owner_name: petForm.owner_name,
species: petForm.species,
age: petForm.age,
poddy_trained: petForm.poddy_trained,
diet: petForm.diet,
image_url: petForm.image_url,
likes: petForm.likes,
dislikes: petForm.dislikes,
})
/* The PUT method edits an existing entry in the mongodb database. */
const putData = async (form) => {
const { id } = router.query
try {
const res = await fetch(`/api/pets/${id}`, {
method: 'PUT',
headers: {
Accept: contentType,
'Content-Type': contentType,
},
body: JSON.stringify(form),
})
// Throw error with status code in case Fetch API req failed
if (!res.ok) {
throw new Error(res.status)
}
const { data } = await res.json()
mutate(`/api/pets/${id}`, data, false) // Update the local data without a revalidation
router.push('/')
} catch (error) {
setMessage('Failed to update pet')
}
}
/* The POST method adds a new entry in the mongodb database. */
const postData = async (form) => {
try {
const res = await fetch('/api/pets', {
method: 'POST',
headers: {
Accept: contentType,
'Content-Type': contentType,
},
body: JSON.stringify(form),
})
// Throw error with status code in case Fetch API req failed
if (!res.ok) {
throw new Error(res.status)
}
router.push('/')
} catch (error) {
setMessage('Failed to add pet')
}
}
const handleChange = (e) => {
const target = e.target
const value =
target.name === 'poddy_trained' ? target.checked : target.value
const name = target.name
setForm({
...form,
[name]: value,
})
}
const handleSubmit = (e) => {
e.preventDefault()
const errs = formValidate()
if (Object.keys(errs).length === 0) {
forNewPet ? postData(form) : putData(form)
} else {
setErrors({ errs })
}
}
/* Makes sure pet info is filled for pet name, owner name, species, and image url*/
const formValidate = () => {
let err = {}
if (!form.name) err.name = 'Name is required'
if (!form.owner_name) err.owner_name = 'Owner is required'
if (!form.species) err.species = 'Species is required'
if (!form.image_url) err.image_url = 'Image URL is required'
return err
}
return (
<>
<form id={formId} onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input
type="text"
maxLength="20"
name="name"
value={form.name}
onChange={handleChange}
required
/>
<label htmlFor="owner_name">Owner</label>
<input
type="text"
maxLength="20"
name="owner_name"
value={form.owner_name}
onChange={handleChange}
required
/>
<label htmlFor="species">Species</label>
<input
type="text"
maxLength="30"
name="species"
value={form.species}
onChange={handleChange}
required
/>
<label htmlFor="age">Age</label>
<input
type="number"
name="age"
value={form.age}
onChange={handleChange}
/>
<label htmlFor="poddy_trained">Potty Trained</label>
<input
type="checkbox"
name="poddy_trained"
checked={form.poddy_trained}
onChange={handleChange}
/>
<label htmlFor="diet">Diet</label>
<textarea
name="diet"
maxLength="60"
value={form.diet}
onChange={handleChange}
/>
<label htmlFor="image_url">Image URL</label>
<input
type="url"
name="image_url"
value={form.image_url}
onChange={handleChange}
required
/>
<label htmlFor="likes">Likes</label>
<textarea
name="likes"
maxLength="60"
value={form.likes}
onChange={handleChange}
/>
<label htmlFor="dislikes">Dislikes</label>
<textarea
name="dislikes"
maxLength="60"
value={form.dislikes}
onChange={handleChange}
/>
<button type="submit" className="btn">
Submit
</button>
</form>
<p>{message}</p>
<div>
{Object.keys(errors).map((err, index) => (
<li key={index}>{err}</li>
))}
</div>
</>
)
}
export default Form
form {
width: 90%;
margin: auto;
max-width: 550px;
}
input,
form button,
label {
display: block;
}
form button,
input,
textarea {
outline: none;
}
input,
textarea {
border: 1px solid rgb(199, 199, 199);
border-radius: 10px;
padding: 10px;
font-size: 90%;
width: 100%;
height: 30px;
color: rgb(53, 53, 53);
}
textarea {
height: 50px;
}
label {
margin-top: 10px;
}
form button {
--accent: rgb(0, 162, 255);
margin-top: 20px;
}
.form-container {
width: 90%;
}
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
* {
font-family: 'Open Sans', sans-serif;
box-sizing: border-box;
}
/* Nav Area */
.top-bar {
width: 100%;
margin-top: 0;
position: relative;
height: 80px;
text-align: right;
}
#title {
position: absolute;
left: 20px;
top: 0;
display: inline-block;
height: 100%;
}
.nav {
height: 100%;
display: inline-block;
}
.nav a {
margin: 0 20px;
font-size: 120%;
height: 100%;
display: inline-flex;
justify-content: center;
align-items: center;
}
.grid {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
/* Styles for Cards */
.card {
display: inline-block;
width: 300px;
height: 400px;
overflow: hidden;
border: 1.25px solid rgb(233, 233, 233);
border-radius: 16px;
margin: 10px;
transition: 0.5s all;
--shadow: transparent;
box-shadow: 0 0 10px 5px var(--shadow);
position: relative;
font-size: 100%;
}
.card:hover {
--shadow: rgba(53, 53, 53, 0.103);
/* transform: rotateY(180deg) translate(20px, 20px);
background: pink; */
}
.card:hover .main-content {
pointer-events: initial;
opacity: 1;
}
.card * {
margin: 0;
}
.card img {
width: 100%;
height: 100%;
object-fit: cover;
}
.main-content {
padding: 25px;
position: absolute;
top: 0;
left: 0;
background-color: rgba(255, 255, 255, 0.9);
width: 100%;
height: 100%;
opacity: 0;
pointer-events: none;
transition: 0.5s all;
}
.owner {
color: grey;
font-size: 110%;
}
.pet-name {
font-weight: bold;
font-size: 130%;
}
h5.pet-name {
color: white;
position: absolute;
left: 0;
bottom: 0;
padding: 10px;
text-shadow: 0px 0px 4px black;
}
.info ul {
padding: 10px;
padding-top: 0px;
border-radius: 7px;
}
li {
list-style-type: none;
margin: 0;
}
.info {
color: rgb(83, 83, 83);
position: relative;
overflow: hidden;
}
.info.likes {
margin-top: 25px;
}
.label {
font-weight: bold;
}
.btn-container {
text-align: right;
padding: 10px;
position: absolute;
bottom: 10px;
right: 10px;
}
.btn {
--accent: grey;
cursor: pointer;
background: transparent;
border: 1.5px solid var(--accent);
color: var(--accent);
border-radius: 10px;
padding: 10px 15px;
font-size: 90%;
letter-spacing: 1px;
transition: 0.5s all;
outline: none;
}
.btn:hover {
background: var(--accent);
color: white;
}
.edit.btn {
--accent: green;
}
.delete.btn {
--accent: red;
margin-left: 10px;
}
.view.btn {
--accent: blue;
margin-left: 10px;
}
/* Delete Pet */
.pet-container {
width: 100%;
}
.confirmation-box.show {
display: block;
}
import mongoose from 'mongoose'
const MONGODB_URI = process.env.MONGODB_URI
if (!MONGODB_URI) {
throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local'
)
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongoose
if (!cached) {
cached = global.mongoose = { conn: null, promise: null }
}
async function dbConnect() {
if (cached.conn) {
return cached.conn
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
}
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
return mongoose
})
}
cached.conn = await cached.promise
return cached.conn
}
export default dbConnect
import mongoose from 'mongoose'
/* PetSchema will correspond to a collection in your MongoDB database. */
const PetSchema = new mongoose.Schema({
name: {
/* The name of this pet */
type: String,
required: [true, 'Please provide a name for this pet.'],
maxlength: [60, 'Name cannot be more than 60 characters'],
},
owner_name: {
/* The owner of this pet */
type: String,
required: [true, "Please provide the pet owner's name"],
maxlength: [60, "Owner's Name cannot be more than 60 characters"],
},
species: {
/* The species of your pet */
type: String,
required: [true, 'Please specify the species of your pet.'],
maxlength: [40, 'Species specified cannot be more than 40 characters'],
},
age: {
/* Pet's age, if applicable */
type: Number,
},
poddy_trained: {
/* Boolean poddy_trained value, if applicable */
type: Boolean,
},
diet: {
/* List of dietary needs, if applicable */
type: Array,
},
image_url: {
/* Url to pet image */
required: [true, 'Please provide an image url for this pet.'],
type: String,
},
likes: {
/* List of things your pet likes to do */
type: Array,
},
dislikes: {
/* List of things your pet does not like to do */
type: Array,
},
})
export default mongoose.models.Pet || mongoose.model('Pet', PetSchema)
const { join } = require('path')
const { createNodeFileTrace } = require('../..')
module.exports = createNodeFileTrace({
path: join(__dirname, '..', '..', '..', '..', 'target', 'debug'),
})({
reactStrictMode: true,
})
{
"name": "@vercel/turbo-tracing-test-app",
"private": true,
"scripts": {
"dev": "next dev",
"build": "cross-env MONGODB_URI=localhost:27017 next build",
"start": "next start",
"lint:prettier": "prettier -c . --cache --ignore-path=../../../../.prettier-ignore"
},
"dependencies": {
"mongoose": "^6.4.5",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"swr": "^1.3.0"
},
"devDependencies": {
"@vercel/experimental-nft-next-plugin": "workspace:*",
"cross-env": "^7.0.3"
}
}
import { useRouter } from 'next/router'
import useSWR from 'swr'
import Form from '../../components/Form'
const fetcher = (url) =>
fetch(url)
.then((res) => res.json())
.then((json) => json.data)
const EditPet = () => {
const router = useRouter()
const { id } = router.query
const { data: pet, error } = useSWR(id ? `/api/pets/${id}` : null, fetcher)
if (error) return <p>Failed to load</p>
if (!pet) return <p>Loading...</p>
const petForm = {
name: pet.name,
owner_name: pet.owner_name,
species: pet.species,
age: pet.age,
poddy_trained: pet.poddy_trained,
diet: pet.diet,
image_url: pet.image_url,
likes: pet.likes,
dislikes: pet.dislikes,
}
return <Form formId="edit-pet-form" petForm={petForm} forNewPet={false} />
}
export default EditPet
import { useState } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'
import dbConnect from '../../lib/dbConnect'
import Pet from '../../models/Pet'
/* Allows you to view pet card info and delete pet card*/
const PetPage = ({ pet }) => {
const router = useRouter()
const [message, setMessage] = useState('')
const handleDelete = async () => {
const petID = router.query.id
try {
await fetch(`/api/pets/${petID}`, {
method: 'Delete',
})
router.push('/')
} catch (error) {
setMessage('Failed to delete the pet.')
}
}
return (
<div key={pet._id}>
<div className="card">
<img src={pet.image_url} />
<h5 className="pet-name">{pet.name}</h5>
<div className="main-content">
<p className="pet-name">{pet.name}</p>
<p className="owner">Owner: {pet.owner_name}</p>
{/* Extra Pet Info: Likes and Dislikes */}
<div className="likes info">
<p className="label">Likes</p>
<ul>
{pet.likes.map((data, index) => (
<li key={index}>{data} </li>
))}
</ul>
</div>
<div className="dislikes info">
<p className="label">Dislikes</p>
<ul>
{pet.dislikes.map((data, index) => (
<li key={index}>{data} </li>
))}
</ul>
</div>
<div className="btn-container">
<Link href="/[id]/edit" as={`/${pet._id}/edit`}>
<button className="btn edit">Edit</button>
</Link>
<button className="btn delete" onClick={handleDelete}>
Delete
</button>
</div>
</div>
</div>
{message && <p>{message}</p>}
</div>
)
}
export async function getServerSideProps({ params }) {
await dbConnect()
const pet = await Pet.findById(params.id).lean()
pet._id = pet._id.toString()
return { props: { pet } }
}
export default PetPage
import '../css/style.css'
import '../css/form.css'
import Head from 'next/head'
import Link from 'next/link'
function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<title>Pet Care App</title>
</Head>
<div className="top-bar">
<div className="nav">
<Link href="/">
<a>Home</a>
</Link>
<Link href="/new">
<a>Add Pet</a>
</Link>
</div>
<img
id="title"
src="https://upload.wikimedia.org/wikipedia/commons/1/1f/Pet_logo_with_flowers.png"
alt="pet care logo"
></img>
</div>
<div className="grid wrapper">
<Component {...pageProps} />
</div>
</>
)
}
export default MyApp
import dbConnect from '../../../lib/dbConnect'
import Pet from '../../../models/Pet'
export default async function handler(req, res) {
const {
query: { id },
method,
} = req
await dbConnect()
switch (method) {
case 'GET' /* Get a model by its ID */:
try {
const pet = await Pet.findById(id)
if (!pet) {
return res.status(400).json({ success: false })
}
res.status(200).json({ success: true, data: pet })
} catch (error) {
res.status(400).json({ success: false })
}
break
case 'PUT' /* Edit a model by its ID */:
try {
const pet = await Pet.findByIdAndUpdate(id, req.body, {
new: true,
runValidators: true,
})
if (!pet) {
return res.status(400).json({ success: false })
}
res.status(200).json({ success: true, data: pet })
} catch (error) {
res.status(400).json({ success: false })
}
break
case 'DELETE' /* Delete a model by its ID */:
try {
const deletedPet = await Pet.deleteOne({ _id: id })
if (!deletedPet) {
return res.status(400).json({ success: false })
}
res.status(200).json({ success: true, data: {} })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
import dbConnect from '../../../lib/dbConnect'
import Pet from '../../../models/Pet'
export default async function handler(req, res) {
const { method } = req
await dbConnect()
switch (method) {
case 'GET':
try {
const pets = await Pet.find({}) /* find all the data in our database */
res.status(200).json({ success: true, data: pets })
} catch (error) {
res.status(400).json({ success: false })
}
break
case 'POST':
try {
const pet = await Pet.create(
req.body
) /* create a new model in the database */
res.status(201).json({ success: true, data: pet })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
import Link from 'next/link'
import dbConnect from '../lib/dbConnect'
import Pet from '../models/Pet'
const Index = ({ pets }) => (
<>
{/* Create a card for each pet */}
{pets.map((pet) => (
<div key={pet._id}>
<div className="card">
<img src={pet.image_url} />
<h5 className="pet-name">{pet.name}</h5>
<div className="main-content">
<p className="pet-name">{pet.name}</p>
<p className="owner">Owner: {pet.owner_name}</p>
{/* Extra Pet Info: Likes and Dislikes */}
<div className="likes info">
<p className="label">Likes</p>
<ul>
{pet.likes.map((data, index) => (
<li key={index}>{data} </li>
))}
</ul>
</div>
<div className="dislikes info">
<p className="label">Dislikes</p>
<ul>
{pet.dislikes.map((data, index) => (
<li key={index}>{data} </li>
))}
</ul>
</div>
<div className="btn-container">
<Link href="/[id]/edit" as={`/${pet._id}/edit`}>
<button className="btn edit">Edit</button>
</Link>
<Link href="/[id]" as={`/${pet._id}`}>
<button className="btn view">View</button>
</Link>
</div>
</div>
</div>
</div>
))}
</>
)
/* Retrieves pet(s) data from mongodb database */
export async function getServerSideProps() {
await dbConnect()
/* find all the data in our database */
const result = await Pet.find({})
const pets = result.map((doc) => {
const pet = doc.toObject()
pet._id = pet._id.toString()
return pet
})
return { props: { pets: pets } }
}
export default Index
import Form from '../components/Form'
const NewPet = () => {
const petForm = {
name: '',
owner_name: '',
species: '',
age: 0,
poddy_trained: false,
diet: [],
image_url: '',
likes: [],
dislikes: [],
}
return <Form formId="add-pet-form" petForm={petForm} />
}
export default NewPet
<svg width="82" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill="url(#prefix__paint0_linear)" d="M9.018 0l9.019 16H0L9.018 0z"/>
<path fill="#333" fill-rule="evenodd" d="M51.634 12.028h-6.492V2.052h6.492v1.256H46.61v3.007h4.37V7.57h-4.37v3.202h5.024v1.255zm-14.063 0h-7.235v-1.096l5.342-7.624h-5.253V2.052h7.058v1.097l-5.342 7.623h5.43v1.256zm21.88 0h6.333v-1.256h-2.423V3.308h2.423V2.052h-6.332v1.256h2.441v7.465h-2.441v1.255zm18.22 0h-1.468v-8.72h-3.36V2.052h8.225v1.256H77.67v8.72z" clip-rule="evenodd"/>
<defs>
<linearGradient id="prefix__paint0_linear" x1="28.022" x2="16.189" y1="22.991" y2="8.569" gradientUnits="userSpaceOnUse">
<stop stop-color="#fff"/>
<stop offset="1"/>
</linearGradient>
</defs>
</svg>
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src"],
"references": [
{
"path": "../webpack-nmt"
}
]
}
{
"name": "@vercel/webpack-nft",
"version": "0.0.15-alpha.2",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist/**/*"
],
"publishConfig": {
"access": "public"
},
"dependencies": {
"@vercel/experimental-nft": "workspace:*"
},
"peerDependencies": {
"webpack": "^5.0.0"
},
"devDependencies": {
"@types/webpack": "^5.28.0",
"webpack": "^5.75.0"
},
"scripts": {
"lint": "eslint src/",
"lint:prettier": "prettier -c . --cache --ignore-path=../../.prettierignore"
}
}
import { spawn } from 'node:child_process'
import { join } from 'node:path'
import type { WebpackPluginInstance, Compiler } from 'webpack'
import { Compilation } from 'webpack'
export interface NodeModuleTracePluginOptions {
cwd?: string
// relative to cwd
contextDirectory?: string
// additional PATH environment variable to use for spawning the `node-file-trace` process
path?: string
// control the maximum number of files that are passed to the `node-file-trace` command
// default is 128
maxFiles?: number
// log options
log?: {
all?: boolean
detail?: boolean
// Default is `error`
level?:
| 'bug'
| 'fatal'
| 'error'
| 'warning'
| 'hint'
| 'note'
| 'suggestions'
| 'info'
}
}
export class NodeModuleTracePlugin implements WebpackPluginInstance {
static PluginName = 'NodeModuleTracePlugin'
private readonly chunksToTrace = new Set<string>()
constructor(private readonly options?: NodeModuleTracePluginOptions) {}
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(
NodeModuleTracePlugin.PluginName,
(compilation) => {
compilation.hooks.processAssets.tap(
{
name: NodeModuleTracePlugin.PluginName,
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
},
() => {
this.createTraceAssets(compilation)
}
)
}
)
compiler.hooks.afterEmit.tapPromise(NodeModuleTracePlugin.PluginName, () =>
this.runTrace()
)
}
private createTraceAssets(compilation: Compilation) {
const outputPath = compilation.outputOptions.path!
const isTraceable = (file: string) =>
!file.endsWith('.wasm') && !file.endsWith('.map')
for (const entrypoint of compilation.entrypoints.values()) {
const file = entrypoint.getFiles().pop()
if (file && isTraceable(file)) {
this.chunksToTrace.add(join(outputPath, file))
}
}
}
private async runTrace() {
process.stdout.write('\n')
const cwd = this.options?.cwd ?? process.cwd()
const args = [
'annotate',
'--context-directory',
// `npm_config_local_prefix` set by `npm` to the root of the project, include workspaces
// `PROJECT_CWD` set by `yarn` to the root of the project, include workspaces
this.options?.contextDirectory ??
process.env.npm_config_local_prefix ??
process.env.PROJECT_CWD ??
cwd,
'--exact',
]
if (this.options?.log?.detail) {
args.push('--log-detail')
}
if (this.options?.log?.all) {
args.push('--show-all')
}
const logLevel = this.options?.log?.level
if (logLevel) {
args.push(`--log-level`)
args.push(logLevel)
}
let turboTracingPackagePath = ''
let turboTracingBinPath = ''
try {
turboTracingPackagePath = require.resolve(
'@vercel/experimental-nft/package.json'
)
} catch (e) {
console.warn(
`Could not resolve the @vercel/experimental-nft directory, turbo tracing may fail.`
)
}
if (turboTracingPackagePath) {
try {
const turboTracingBinPackageJsonPath = require.resolve(
`@vercel/experimental-nft-${process.platform}-${process.arch}/package.json`,
{
paths: [join(turboTracingPackagePath, '..')],
}
)
turboTracingBinPath = join(turboTracingBinPackageJsonPath, '..')
} catch (e) {
console.warn(
`Could not resolve the @vercel/experimental-nft-${process.platform}-${process.arch} directory, turbo tracing may fail.`
)
}
}
const pathSep = process.platform === 'win32' ? ';' : ':'
let paths = `${this.options?.path ?? ''}${pathSep}${process.env.PATH}`
if (turboTracingBinPath) {
paths = `${turboTracingBinPath}${pathSep}${paths}`
}
const maxFiles = this.options?.maxFiles ?? 128
let chunks = [...this.chunksToTrace]
let restChunks = chunks.length > maxFiles ? chunks.splice(maxFiles) : []
while (chunks.length) {
await traceChunks(args, paths, chunks, cwd)
chunks = restChunks
if (restChunks.length) {
restChunks = chunks.length > maxFiles ? chunks.splice(maxFiles) : []
}
}
}
}
function traceChunks(
args: Array<string>,
paths: string,
chunks: Array<string>,
cwd?: string
) {
const turboTracingProcess = spawn('node-file-trace', [...args, ...chunks], {
stdio: 'pipe',
env: {
...process.env,
PATH: paths,
RUST_BACKTRACE: '1',
},
cwd,
})
return new Promise<void>((resolve, reject) => {
turboTracingProcess.on('error', (err) => {
console.error(err)
})
turboTracingProcess.stdout.on('data', (chunk: string | Uint8Array) => {
process.stdout.write(chunk)
})
turboTracingProcess.stderr.on('data', (chunk: string | Uint8Array) => {
process.stderr.write(chunk)
})
turboTracingProcess.once('exit', (code) => {
if (!code) {
resolve()
} else {
reject(code)
}
})
})
}
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src"]
}
...@@ -7,10 +7,7 @@ ...@@ -7,10 +7,7 @@
"importHelpers": false, "importHelpers": false,
"noEmitHelpers": false, "noEmitHelpers": false,
"skipLibCheck": true, "skipLibCheck": true,
"outDir": "./dist", "outDir": "./dist"
"paths": {
"@vercel/webpack-nft": ["./packages/webpack-nmt/src/index.ts"]
}
}, },
"exclude": ["node_modules", "target"] "exclude": ["node_modules", "target"]
} }
...@@ -22,11 +22,9 @@ cargo-lock = "8.0.2" ...@@ -22,11 +22,9 @@ cargo-lock = "8.0.2"
chrono = { workspace = true } chrono = { workspace = true }
clap = { workspace = true } clap = { workspace = true }
indexmap = { workspace = true } indexmap = { workspace = true }
inquire = { version = "0.5.1" }
num-format = "0.4.4" num-format = "0.4.4"
owo-colors = { workspace = true } owo-colors = { workspace = true }
rustc-hash = { workspace = true } rustc-hash = { workspace = true }
semver = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true, features = ["preserve_order"] } serde_json = { workspace = true, features = ["preserve_order"] }
tabled = { version = "0.10.0", features = ["color"] } tabled = { version = "0.10.0", features = ["color"] }
......
use std::{
path::PathBuf,
process::{self, Stdio},
};
pub struct Command {
bin: String,
args: Vec<String>,
error_message: String,
dry_run: bool,
current_dir: Option<PathBuf>,
}
impl Command {
pub fn program<S: AsRef<str>>(bin: S) -> Self {
Self {
bin: bin.as_ref().to_owned(),
args: vec![],
error_message: String::new(),
dry_run: false,
current_dir: None,
}
}
pub fn args<S: AsRef<str>, V: AsRef<[S]>>(mut self, args: V) -> Self {
self.args
.extend(args.as_ref().iter().map(|s| s.as_ref().to_string()));
self
}
pub fn error_message<S: AsRef<str>>(mut self, message: S) -> Self {
message.as_ref().clone_into(&mut self.error_message);
self
}
pub fn dry_run(mut self, dry_run: bool) -> Self {
self.dry_run = dry_run;
self
}
pub fn current_dir(mut self, current_dir: PathBuf) -> Self {
self.current_dir = Some(current_dir);
self
}
pub fn execute(self) {
let mut cmd = process::Command::new(self.bin);
cmd.args(&self.args)
.stderr(Stdio::inherit())
.stdout(Stdio::inherit());
if let Some(current_dir) = self.current_dir {
cmd.current_dir(&current_dir);
}
if self.dry_run {
println!("{cmd:?}");
return;
}
let status = cmd.status();
assert!(
{
if self.error_message.is_empty() {
status.unwrap()
} else {
status.expect(&self.error_message)
}
}
.success()
);
}
pub fn output_string(self) -> String {
let mut cmd = process::Command::new(self.bin);
cmd.args(&self.args).stderr(Stdio::inherit());
if let Some(current_dir) = self.current_dir {
cmd.current_dir(&current_dir);
}
let output = cmd.output();
String::from_utf8({
if self.error_message.is_empty() {
output.unwrap().stdout
} else {
output.expect(&self.error_message).stdout
}
})
.expect("Stdout contains non UTF-8 characters")
}
}
...@@ -7,14 +7,11 @@ use std::{ ...@@ -7,14 +7,11 @@ use std::{
use anyhow::Result; use anyhow::Result;
use clap::{Command, arg}; use clap::{Command, arg};
mod command;
mod nft_bench; mod nft_bench;
mod publish;
mod summarize_bench; mod summarize_bench;
mod visualize_bundler_bench; mod visualize_bundler_bench;
use nft_bench::show_result; use nft_bench::show_result;
use publish::{publish_workspace, run_bump, run_publish};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
fn cli() -> Command { fn cli() -> Command {
...@@ -23,20 +20,6 @@ fn cli() -> Command { ...@@ -23,20 +20,6 @@ fn cli() -> Command {
.subcommand_required(true) .subcommand_required(true)
.arg_required_else_help(true) .arg_required_else_help(true)
.allow_external_subcommands(true) .allow_external_subcommands(true)
.subcommand(
Command::new("npm")
.about("Publish binaries to npm")
.arg(arg!(<NAME> "the package to publish"))
.arg_required_else_help(true),
)
.subcommand(
Command::new("workspace")
.arg(arg!(--publish "publish npm packages in pnpm workspace"))
.arg(arg!(--bump "bump new version for npm package in pnpm workspace"))
.arg(arg!(--"dry-run" "dry run all operations"))
.arg(arg!([NAME] "the package to bump"))
.about("Manage packages in pnpm workspaces"),
)
.subcommand( .subcommand(
Command::new("nft-bench-result") Command::new("nft-bench-result")
.about("Print node-file-trace benchmark result against @vercel/nft"), .about("Print node-file-trace benchmark result against @vercel/nft"),
...@@ -77,29 +60,6 @@ Visualizations generated by this command will appear in a sibling directory to t ...@@ -77,29 +60,6 @@ Visualizations generated by this command will appear in a sibling directory to t
fn main() -> Result<()> { fn main() -> Result<()> {
let matches = cli().get_matches(); let matches = cli().get_matches();
match matches.subcommand() { match matches.subcommand() {
Some(("npm", sub_matches)) => {
let name = sub_matches
.get_one::<String>("NAME")
.expect("NAME is required");
run_publish(name);
Ok(())
}
Some(("workspace", sub_matches)) => {
let is_bump = sub_matches.get_flag("bump");
let is_publish = sub_matches.get_flag("publish");
let dry_run = sub_matches.get_flag("dry-run");
if is_bump {
let names = sub_matches
.get_many::<String>("NAME")
.map(|names| names.cloned().collect::<FxHashSet<_>>())
.unwrap_or_default();
run_bump(names, dry_run);
}
if is_publish {
publish_workspace(dry_run);
}
Ok(())
}
Some(("nft-bench-result", _)) => { Some(("nft-bench-result", _)) => {
show_result(); show_result();
Ok(()) Ok(())
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment