Compare commits

..

5 Commits

Author SHA1 Message Date
Ethan Arrowood
a419762690 config changes 2022-11-01 13:49:48 -06:00
Ethan Arrowood
7759f36894 fix import 2022-11-01 13:19:47 -06:00
Ethan Arrowood
4fa050ea25 rename to error-utils and convert to jest 2022-11-01 13:17:26 -06:00
Ethan Arrowood
1e229b8bbb replace is-error with new package 2022-11-01 12:40:47 -06:00
Ethan Arrowood
caa3245fc8 add errors package 2022-10-31 16:23:03 -06:00
205 changed files with 2887 additions and 29269 deletions

View File

@@ -82,11 +82,11 @@ jobs:
- run: yarn install --network-timeout 1000000
- name: Build ${{matrix.packageName}} and all its dependencies
run: node utils/gen.js && node_modules/.bin/turbo run build --cache-dir=".turbo" --scope=${{matrix.packageName}} --include-dependencies --no-deps
run: node_modules/.bin/turbo run build --cache-dir=".turbo" --scope=${{matrix.packageName}} --include-dependencies --no-deps
env:
FORCE_COLOR: '1'
- name: Test ${{matrix.packageName}}
run: node utils/gen.js && node_modules/.bin/turbo run test --cache-dir=".turbo" --scope=${{matrix.packageName}} --no-deps -- ${{ join(matrix.testPaths, ' ') }}
run: node_modules/.bin/turbo run test --cache-dir=".turbo" --scope=${{matrix.packageName}} --no-deps -- ${{ join(matrix.testPaths, ' ') }}
shell: bash
env:
VERCEL_CLI_VERSION: ${{ needs.setup.outputs.dplUrl }}/tarballs/vercel.tgz

1
.gitignore vendored
View File

@@ -28,4 +28,3 @@ test/lib/deployment/failed-page.txt
__pycache__
.vercel
.turbo
turbo-cache-key.json

View File

@@ -16,7 +16,7 @@
"unzip-stream": "0.3.0"
},
"devDependencies": {
"@types/node": "14.18.33",
"@types/node": "13.1.4",
"@types/node-fetch": "2.5.4",
"@vercel/node": "1.9.0",
"typescript": "3.9.6"

View File

@@ -1,13 +0,0 @@
# Deployment failed
## Why This Error Occurred
When deploying this project, there was not a successful deployment into the `READY` state.
## How to Fix It
This is a generic error to catch problems in the deployment. The error is likely to vary depending on the deployment and the conditions at the time.
Try looking in the logs for information about the deployment and the failure, this could be done at (vercel.com)[https://vercel.com]. You can also use the `vc logs` command to display the build logs for the deployment.
This might not be a permanent error and retrying the deployment might also resolve it.

View File

@@ -8,7 +8,6 @@
"astro": "astro"
},
"devDependencies": {
"astro": "^1.0.0-rc.8",
"web-vitals": "^3.0.0"
"astro": "^1.0.0-rc.8"
}
}

View File

@@ -1,9 +1 @@
/// <reference types="astro/client" />
interface ImportMetaEnv {
readonly PUBLIC_VERCEL_ANALYTICS_ID: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

View File

@@ -14,19 +14,6 @@ const { title } = Astro.props as Props;
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
<script>
import { webVitals } from "../lib/vitals";
let analyticsId = import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID;
if (analyticsId) {
webVitals({
path: location.pathname,
params: location.search,
analyticsId,
});
}
</script>
</head>
<body>
<slot />

View File

@@ -1,66 +0,0 @@
import { onCLS, onFCP, onFID, onLCP, onTTFB } from "web-vitals";
const vitalsUrl = "https://vitals.vercel-analytics.com/v1/vitals";
function getConnectionSpeed() {
return "connection" in navigator &&
navigator["connection"] &&
"effectiveType" in navigator["connection"]
? // @ts-ignore
navigator["connection"]["effectiveType"]
: "";
}
/**
* @param {import("web-vitals").Metric} metric
* @param {{ params: { [s: string]: any; } | ArrayLike<any>; path: string; analyticsId: string; debug: boolean; }} options
*/
export function sendToAnalytics(metric, options) {
const page = Object.entries(options.params).reduce(
(acc, [key, value]) => acc.replace(value, `[${key}]`),
options.path
);
const body = {
dsn: options.analyticsId,
id: metric.id,
page,
href: location.href,
event_name: metric.name,
value: metric.value.toString(),
speed: getConnectionSpeed(),
};
if (options.debug) {
console.log("[Analytics]", metric.name, JSON.stringify(body, null, 2));
}
const blob = new Blob([new URLSearchParams(body).toString()], {
// This content type is necessary for `sendBeacon`
type: "application/x-www-form-urlencoded",
});
if (navigator.sendBeacon) {
navigator.sendBeacon(vitalsUrl, blob);
} else
fetch(vitalsUrl, {
body: blob,
method: "POST",
credentials: "omit",
keepalive: true,
});
}
/**
* @param {any} options
*/
export function webVitals(options) {
try {
onFID((metric) => sendToAnalytics(metric, options));
onTTFB((metric) => sendToAnalytics(metric, options));
onLCP((metric) => sendToAnalytics(metric, options));
onCLS((metric) => sendToAnalytics(metric, options));
onFCP((metric) => sendToAnalytics(metric, options));
} catch (err) {
console.error("[Analytics]", err);
}
}

View File

@@ -1,6 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
}
module.exports = nextConfig

File diff suppressed because it is too large Load Diff

View File

@@ -9,10 +9,12 @@
"lint": "next lint"
},
"dependencies": {
"eslint": "8.27.0",
"eslint-config-next": "13.0.3",
"next": "13.0.3",
"next": "13.0.0",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"eslint": "8.26.0",
"eslint-config-next": "13.0.0"
}
}

View File

@@ -8,13 +8,6 @@ This directory is a brief example of a [Remix](https://remix.run/docs) site that
_Live Example: https://remix-run-template.vercel.app_
You can also deploy using the [Vercel CLI](https://vercel.com/cli):
```sh
npm i -g vercel
vercel
```
## Development
To run your Remix app locally, make sure your project's local dependencies are installed:
@@ -30,3 +23,5 @@ npm run dev
```
Open up [http://localhost:3000](http://localhost:3000) and you should be ready to go!
If you're used to using the `vercel dev` command provided by [Vercel CLI](https://vercel.com/cli) instead, you can also use that, but it's not needed.

View File

@@ -1,22 +1,4 @@
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { hydrate } from "react-dom";
function hydrate() {
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>
);
});
}
if (window.requestIdleCallback) {
window.requestIdleCallback(hydrate);
} else {
// Safari doesn't support requestIdleCallback
// https://caniuse.com/requestidlecallback
window.setTimeout(hydrate, 1);
}
hydrate(<RemixBrowser />, document);

View File

@@ -8,14 +8,14 @@ export default function handleRequest(
responseHeaders: Headers,
remixContext: EntryContext
) {
const markup = renderToString(
let markup = renderToString(
<RemixServer context={remixContext} url={request.url} />
);
responseHeaders.set("Content-Type", "text/html");
return new Response("<!DOCTYPE html>" + markup, {
headers: responseHeaders,
status: responseStatusCode,
headers: responseHeaders,
});
}

View File

@@ -1,34 +1,182 @@
import type { MetaFunction } from "@remix-run/node";
import type { LinksFunction, MetaFunction } from "@remix-run/node";
import {
Link,
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useCatch,
} from "@remix-run/react";
import { Analytics } from '@vercel/analytics/react';
export const meta: MetaFunction = () => ({
import darkStylesUrl from "~/styles/dark.css";
import globalStylesUrl from "~/styles/global.css";
// https://remix.run/api/conventions#links
export let links: LinksFunction = () => {
return [
{ rel: "stylesheet", href: globalStylesUrl },
{
rel: "stylesheet",
href: darkStylesUrl,
media: "(prefers-color-scheme: dark)"
}
];
};
// https://remix.run/api/conventions#meta
export let meta: MetaFunction = () => ({
charset: "utf-8",
title: "New Remix App",
viewport: "width=device-width,initial-scale=1",
});
// https://remix.run/api/conventions#default-export
// https://remix.run/api/conventions#route-filenames
export default function App() {
return (
<Document>
<Layout>
<Outlet />
</Layout>
</Document>
);
}
// https://remix.run/api/conventions#errorboundary
export function ErrorBoundary({ error }: { error: Error }) {
console.error(error);
return (
<Document title="Error!">
<Layout>
<div>
<h1>There was an error</h1>
<p>{error.message}</p>
<hr />
<p>
Hey, developer, you should replace this with what you want your
users to see.
</p>
</div>
</Layout>
</Document>
);
}
// https://remix.run/api/conventions#catchboundary
export function CatchBoundary() {
let caught = useCatch();
let message;
switch (caught.status) {
case 401:
message = (
<p>
Oops! Looks like you tried to visit a page that you do not have access
to.
</p>
);
break;
case 404:
message = (
<p>Oops! Looks like you tried to visit a page that does not exist.</p>
);
break;
default:
throw new Error(caught.data || caught.statusText);
}
return (
<Document title={`${caught.status} ${caught.statusText}`}>
<Layout>
<h1>
{caught.status}: {caught.statusText}
</h1>
{message}
</Layout>
</Document>
);
}
function Document({
children,
title
}: {
children: React.ReactNode;
title?: string;
}) {
return (
<html lang="en">
<head>
{title ? <title>{title}</title> : null}
<Meta />
<Links />
</head>
<body>
<Outlet />
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
<Analytics />
</body>
</html>
);
}
function Layout({ children }: { children: React.ReactNode }) {
return (
<div className="remix-app">
<header className="remix-app__header">
<div className="container remix-app__header-content">
<Link to="/" title="Remix" className="remix-app__header-home-link">
<RemixLogo />
</Link>
<nav aria-label="Main navigation" className="remix-app__header-nav">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<a href="https://remix.run/docs">Remix Docs</a>
</li>
<li>
<a href="https://github.com/remix-run/remix">GitHub</a>
</li>
</ul>
</nav>
</div>
</header>
<div className="remix-app__main">
<div className="container remix-app__main-content">{children}</div>
</div>
<footer className="remix-app__footer">
<div className="container remix-app__footer-content">
<p>&copy; You!</p>
</div>
</footer>
</div>
);
}
function RemixLogo() {
return (
<svg
viewBox="0 0 659 165"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
aria-labelledby="remix-run-logo-title"
role="img"
width="106"
height="30"
fill="currentColor"
>
<title id="remix-run-logo-title">Remix Logo</title>
<path d="M0 161V136H45.5416C53.1486 136 54.8003 141.638 54.8003 145V161H0Z M133.85 124.16C135.3 142.762 135.3 151.482 135.3 161H92.2283C92.2283 158.927 92.2653 157.03 92.3028 155.107C92.4195 149.128 92.5411 142.894 91.5717 130.304C90.2905 111.872 82.3473 107.776 67.7419 107.776H54.8021H0V74.24H69.7918C88.2407 74.24 97.4651 68.632 97.4651 53.784C97.4651 40.728 88.2407 32.816 69.7918 32.816H0V0H77.4788C119.245 0 140 19.712 140 51.2C140 74.752 125.395 90.112 105.665 92.672C122.32 96 132.057 105.472 133.85 124.16Z" />
<path d="M229.43 120.576C225.59 129.536 218.422 133.376 207.158 133.376C194.614 133.376 184.374 126.72 183.35 112.64H263.478V101.12C263.478 70.1437 243.254 44.0317 205.11 44.0317C169.526 44.0317 142.902 69.8877 142.902 105.984C142.902 142.336 169.014 164.352 205.622 164.352C235.83 164.352 256.822 149.76 262.71 123.648L229.43 120.576ZM183.862 92.6717C185.398 81.9197 191.286 73.7277 204.598 73.7277C216.886 73.7277 223.542 82.4317 224.054 92.6717H183.862Z" />
<path d="M385.256 66.5597C380.392 53.2477 369.896 44.0317 349.672 44.0317C332.52 44.0317 320.232 51.7117 314.088 64.2557V47.1037H272.616V161.28H314.088V105.216C314.088 88.0638 318.952 76.7997 332.52 76.7997C345.064 76.7997 348.136 84.9917 348.136 100.608V161.28H389.608V105.216C389.608 88.0638 394.216 76.7997 408.04 76.7997C420.584 76.7997 423.4 84.9917 423.4 100.608V161.28H464.872V89.5997C464.872 65.7917 455.656 44.0317 424.168 44.0317C404.968 44.0317 391.4 53.7597 385.256 66.5597Z" />
<path d="M478.436 47.104V161.28H519.908V47.104H478.436ZM478.18 36.352H520.164V0H478.18V36.352Z" />
<path d="M654.54 47.1035H611.788L592.332 74.2395L573.388 47.1035H527.564L568.78 103.168L523.98 161.28H566.732L589.516 130.304L612.3 161.28H658.124L613.068 101.376L654.54 47.1035Z" />
</svg>
);
}

View File

@@ -0,0 +1,44 @@
import type { MetaFunction, LinksFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import stylesUrl from "~/styles/demos/about.css";
export let meta: MetaFunction = () => {
return {
title: "About Remix"
};
};
export let links: LinksFunction = () => {
return [{ rel: "stylesheet", href: stylesUrl }];
};
export default function Index() {
return (
<div className="about">
<div className="about__intro">
<h2>About Us</h2>
<p>
Ok, so this page isn't really <em>about us</em>, but we did want to
show you a few more things Remix can do.
</p>
<p>
Did you notice that things look a little different on this page? The
CSS that we import in the route file and include in its{" "}
<code>links</code> export is only included on this route and its
children.
</p>
<p>
Wait a sec...<em>its children</em>? To understand what we mean by
this,{" "}
<a href="https://remix.run/docs/en/v1/guides/routing">
read all about nested routes in the docs
</a>
.
</p>
<hr />
<Outlet />
</div>
</div>
);
}

View File

@@ -0,0 +1,17 @@
import { Link } from "@remix-run/react";
export default function AboutIndex() {
return (
<div>
<p>
You are looking at the index route for the <code>/about</code> URL
segment, but there are nested routes as well!
</p>
<p>
<strong>
<Link to="whoa">Check out one of them here.</Link>
</strong>
</p>
</div>
);
}

View File

@@ -0,0 +1,20 @@
import { Link } from "@remix-run/react";
export default function AboutIndex() {
return (
<div>
<p>
Whoa, this is a nested route! We render the <code>/about</code> layout
route component, and its <code>Outlet</code> renders our route
component. 🤯
</p>
<p>
<strong>
<Link to="..">
Go back to the <code>/about</code> index.
</Link>
</strong>
</p>
</div>
);
}

View File

@@ -0,0 +1,102 @@
import type { ActionFunction } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData } from "@remix-run/react";
import { useEffect, useRef } from "react";
export function meta() {
return { title: "Actions Demo" };
}
// When your form sends a POST, the action is called on the server.
// - https://remix.run/api/conventions#action
// - https://remix.run/guides/data-updates
export let action: ActionFunction = async ({ request }) => {
let formData = await request.formData();
let answer = formData.get("answer");
// Typical action workflows start with validating the form data that just came
// over the network. Clientside validation is fine, but you definitely need it
// server side. If there's a problem, return the the data and the component
// can render it.
if (typeof answer !== "string") {
return json("Come on, at least try!", { status: 400 });
}
if (answer !== "egg") {
return json(`Sorry, ${answer} is not right.`, { status: 400 });
}
// Finally, if the data is valid, you'll typically write to a database or send or
// email or log the user in, etc. It's recommended to redirect after a
// successful action, even if it's to the same place so that non-JavaScript workflows
// from the browser doesn't repost the data if the user clicks back.
return redirect("/demos/correct");
};
export default function ActionsDemo() {
// https://remix.run/api/remix#useactiondata
let actionMessage = useActionData<string>();
let answerRef = useRef<HTMLInputElement>(null);
// This form works without JavaScript, but when we have JavaScript we can make
// the experience better by selecting the input on wrong answers! Go ahead, disable
// JavaScript in your browser and see what happens.
useEffect(() => {
if (actionMessage && answerRef.current) {
answerRef.current.select();
}
}, [actionMessage]);
return (
<div className="remix__page">
<main>
<h2>Actions!</h2>
<p>
This form submission will send a post request that we handle in our
`action` export. Any route can export an action to handle data
mutations.
</p>
<Form method="post" className="remix__form">
<h3>Post an Action</h3>
<p>
<i>What is more useful when it is broken?</i>
</p>
<label>
<div>Answer:</div>
<input ref={answerRef} name="answer" type="text" />
</label>
<div>
<button>Answer!</button>
</div>
{actionMessage ? (
<p>
<b>{actionMessage}</b>
</p>
) : null}
</Form>
</main>
<aside>
<h3>Additional Resources</h3>
<ul>
<li>
Guide:{" "}
<a href="https://remix.run/guides/data-writes">Data Writes</a>
</li>
<li>
API:{" "}
<a href="https://remix.run/api/conventions#action">
Route Action Export
</a>
</li>
<li>
API:{" "}
<a href="https://remix.run/api/remix#useactiondata">
<code>useActionData</code>
</a>
</li>
</ul>
</aside>
</div>
);
}

View File

@@ -0,0 +1,3 @@
export default function NiceWork() {
return <h1>You got it right!</h1>;
}

View File

@@ -0,0 +1,43 @@
import type { MetaFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Link, Outlet, useCatch, useLoaderData } from "@remix-run/react";
export let meta: MetaFunction = () => ({ title: "Boundaries Demo" });
export default function Boundaries() {
return (
<div className="remix__page">
<main>
<Outlet />
</main>
<aside>
<h2>Click these Links</h2>
<ul>
<li>
<Link to=".">Start over</Link>
</li>
<li>
<Link to="one">
Param: <i>one</i>
</Link>
</li>
<li>
<Link to="two">
Param: <i>two</i>
</Link>
</li>
<li>
<Link to="this-record-does-not-exist">This will be a 404</Link>
</li>
<li>
<Link to="shh-its-a-secret">And this will be 401 Unauthorized</Link>
</li>
<li>
<Link to="kaboom">This one will throw an error</Link>
</li>
</ul>
</aside>
</div>
);
}

View File

@@ -0,0 +1,111 @@
import type { LoaderFunction, MetaFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Link, useCatch, useLoaderData } from "@remix-run/react";
// The `$` in route filenames becomes a pattern that's parsed from the URL and
// passed to your loaders so you can look up data.
// - https://remix.run/api/conventions#loader-params
export let loader: LoaderFunction = async ({ params }) => {
// pretend like we're using params.id to look something up in the db
if (params.id === "this-record-does-not-exist") {
// If the record doesn't exist we can't render the route normally, so
// instead we throw a 404 reponse to stop running code here and show the
// user the catch boundary.
throw new Response("Not Found", { status: 404 });
}
// now pretend like the record exists but the user just isn't authorized to
// see it.
if (params.id === "shh-its-a-secret") {
// Again, we can't render the component if the user isn't authorized. You
// can even put data in the response that might help the user rectify the
// issue! Like emailing the webmaster for access to the page. (Oh, right,
// `json` is just a Response helper that makes it easier to send JSON
// responses).
throw json({ webmasterEmail: "hello@remix.run" }, { status: 401 });
}
// Sometimes your code just blows up and you never anticipated it. Remix will
// automatically catch it and send the UI to the error boundary.
if (params.id === "kaboom") {
lol();
}
// but otherwise the record was found, user has access, so we can do whatever
// else we needed to in the loader and return the data. (This is boring, we're
// just gonna return the params.id).
return { param: params.id };
};
export default function ParamDemo() {
let data = useLoaderData();
return (
<h1>
The param is <i style={{ color: "red" }}>{data.param}</i>
</h1>
);
}
// https://remix.run/api/conventions#catchboundary
// https://remix.run/api/remix#usecatch
// https://remix.run/api/guides/not-found
export function CatchBoundary() {
let caught = useCatch();
let message: React.ReactNode;
switch (caught.status) {
case 401:
message = (
<p>
Looks like you tried to visit a page that you do not have access to.
Maybe ask the webmaster ({caught.data.webmasterEmail}) for access.
</p>
);
case 404:
message = (
<p>Looks like you tried to visit a page that does not exist.</p>
);
default:
message = (
<p>
There was a problem with your request!
<br />
{caught.status} {caught.statusText}
</p>
);
}
return (
<>
<h2>Oops!</h2>
<p>{message}</p>
<p>
(Isn't it cool that the user gets to stay in context and try a different
link in the parts of the UI that didn't blow up?)
</p>
</>
);
}
// https://remix.run/api/conventions#errorboundary
// https://remix.run/api/guides/not-found
export function ErrorBoundary({ error }: { error: Error }) {
console.error(error);
return (
<>
<h2>Error!</h2>
<p>{error.message}</p>
<p>
(Isn't it cool that the user gets to stay in context and try a different
link in the parts of the UI that didn't blow up?)
</p>
</>
);
}
export let meta: MetaFunction = ({ data }) => {
return {
title: data ? `Param: ${data.param}` : "Oops...",
};
};

View File

@@ -0,0 +1,41 @@
import type { LoaderFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Link, Outlet, useCatch, useLoaderData } from "@remix-run/react";
export default function Boundaries() {
return (
<>
<h2>Params</h2>
<p>
When you name a route segment with $ like{" "}
<code>routes/users/$userId.js</code>, the $ segment will be parsed from
the URL and sent to your loaders and actions by the same name.
</p>
<h2>Errors</h2>
<p>
When a route throws and error in it's action, loader, or component,
Remix automatically catches it, won't even try to render the component,
but it will render the route's ErrorBoundary instead. If the route
doesn't have one, it will bubble up to the routes above it until it hits
the root.
</p>
<p>So be as granular as you want with your error handling.</p>
<h2>Not Found</h2>
<p>
(and other{" "}
<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses">
client errors
</a>
)
</p>
<p>
Loaders and Actions can throw a <code>Response</code> instead of an
error and Remix will render the CatchBoundary instead of the component.
This is great when loading data from a database isn't found. As soon as
you know you can't render the component normally, throw a 404 response
and send your app into the catch boundary. Just like error boundaries,
catch boundaries bubble, too.
</p>
</>
);
}

View File

@@ -1,32 +1,101 @@
import type { MetaFunction, LoaderFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Link, useLoaderData } from "@remix-run/react";
type IndexData = {
resources: Array<{ name: string; url: string }>;
demos: Array<{ name: string; to: string }>;
};
// Loaders provide data to components and are only ever called on the server, so
// you can connect to a database or run any server side code you want right next
// to the component that renders it.
// https://remix.run/api/conventions#loader
export let loader: LoaderFunction = () => {
let data: IndexData = {
resources: [
{
name: "Remix Docs",
url: "https://remix.run/docs"
},
{
name: "React Router Docs",
url: "https://reactrouter.com/docs"
},
{
name: "Remix Discord",
url: "https://discord.gg/VBePs6d"
}
],
demos: [
{
to: "demos/actions",
name: "Actions"
},
{
to: "demos/about",
name: "Nested Routes, CSS loading/unloading"
},
{
to: "demos/params",
name: "URL Params and Error Boundaries"
}
]
};
// https://remix.run/api/remix#json
return json(data);
};
// https://remix.run/api/conventions#meta
export let meta: MetaFunction = () => {
return {
title: "Remix Starter",
description: "Welcome to remix!"
};
};
// https://remix.run/guides/routing#index-routes
export default function Index() {
let data = useLoaderData<IndexData>();
return (
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.4" }}>
<h1>Welcome to Remix</h1>
<ul>
<li>
<a
target="_blank"
href="https://remix.run/tutorials/blog"
rel="noreferrer"
>
15m Quickstart Blog Tutorial
</a>
</li>
<li>
<a
target="_blank"
href="https://remix.run/tutorials/jokes"
rel="noreferrer"
>
Deep Dive Jokes App Tutorial
</a>
</li>
<li>
<a target="_blank" href="https://remix.run/docs" rel="noreferrer">
Remix Docs
</a>
</li>
</ul>
<div className="remix__page">
<main>
<h2>Welcome to Remix!</h2>
<p>We're stoked that you're here. 🥳</p>
<p>
Feel free to take a look around the code to see how Remix does things,
it might be a bit different than what youre used to. When you're
ready to dive deeper, we've got plenty of resources to get you
up-and-running quickly.
</p>
<p>
Check out all the demos in this starter, and then just delete the{" "}
<code>app/routes/demos</code> and <code>app/styles/demos</code>{" "}
folders when you're ready to turn this into your next project.
</p>
</main>
<aside>
<h2>Demos In This App</h2>
<ul>
{data.demos.map(demo => (
<li key={demo.to} className="remix__page__resource">
<Link to={demo.to} prefetch="intent">
{demo.name}
</Link>
</li>
))}
</ul>
<h2>Resources</h2>
<ul>
{data.resources.map(resource => (
<li key={resource.url} className="remix__page__resource">
<a href={resource.url}>{resource.name}</a>
</li>
))}
</ul>
</aside>
</div>
);
}

View File

@@ -0,0 +1,7 @@
:root {
--color-foreground: hsl(0, 0%, 100%);
--color-background: hsl(0, 0%, 7%);
--color-links: hsl(213, 100%, 73%);
--color-links-hover: hsl(213, 100%, 80%);
--color-border: hsl(0, 0%, 25%);
}

View File

@@ -0,0 +1,26 @@
/*
* Whoa whoa whoa, wait a sec...why are we overriding global CSS selectors?
* Isn't that kind of scary? How do we know this won't have side effects?
*
* In Remix, CSS that is included in a route file will *only* show up on that
* route (and for nested routes, its children). When the user navigates away
* from that route the CSS files linked from those routes will be automatically
* unloaded, making your styles much easier to predict and control.
*
* Read more about styling routes in the docs:
* https://remix.run/guides/styling
*/
:root {
--color-foreground: hsl(0, 0%, 7%);
--color-background: hsl(56, 100%, 50%);
--color-links: hsl(345, 56%, 39%);
--color-links-hover: hsl(345, 51%, 49%);
--color-border: rgb(184, 173, 20);
--font-body: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
Liberation Mono, Courier New, monospace;
}
.about__intro {
max-width: 500px;
}

View File

@@ -0,0 +1,216 @@
/*
* You can just delete everything here or keep whatever you like, it's just a
* quick baseline!
*/
:root {
--color-foreground: hsl(0, 0%, 7%);
--color-background: hsl(0, 0%, 100%);
--color-links: hsl(213, 100%, 52%);
--color-links-hover: hsl(213, 100%, 43%);
--color-border: hsl(0, 0%, 82%);
--font-body: -apple-system, "Segoe UI", Helvetica Neue, Helvetica, Roboto,
Arial, sans-serif, system-ui, "Apple Color Emoji", "Segoe UI Emoji";
}
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
:-moz-focusring {
outline: auto;
}
:focus {
outline: var(--color-links) solid 2px;
outline-offset: 2px;
}
html,
body {
padding: 0;
margin: 0;
background-color: var(--color-background);
color: var(--color-foreground);
}
body {
font-family: var(--font-body);
line-height: 1.5;
}
a {
color: var(--color-links);
text-decoration: none;
}
a:hover {
color: var(--color-links-hover);
text-decoration: underline;
}
hr {
display: block;
height: 1px;
border: 0;
background-color: var(--color-border);
margin-top: 2rem;
margin-bottom: 2rem;
}
input:where([type="text"]),
input:where([type="search"]) {
display: block;
border: 1px solid var(--color-border);
width: 100%;
font: inherit;
line-height: 1;
height: calc(1ch + 1.5em);
padding-right: 0.5em;
padding-left: 0.5em;
background-color: hsl(0 0% 100% / 20%);
color: var(--color-foreground);
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
.container {
--gutter: 16px;
width: 1024px;
max-width: calc(100% - var(--gutter) * 2);
margin-right: auto;
margin-left: auto;
}
.remix-app {
display: flex;
flex-direction: column;
min-height: 100vh;
min-height: calc(100vh - env(safe-area-inset-bottom));
}
.remix-app > * {
width: 100%;
}
.remix-app__header {
padding-top: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--color-border);
}
.remix-app__header-content {
display: flex;
justify-content: space-between;
align-items: center;
}
.remix-app__header-home-link {
width: 106px;
height: 30px;
color: var(--color-foreground);
}
.remix-app__header-nav ul {
list-style: none;
margin: 0;
display: flex;
align-items: center;
gap: 1.5em;
}
.remix-app__header-nav li {
font-weight: bold;
}
.remix-app__main {
flex: 1 1 100%;
}
.remix-app__footer {
padding-top: 1rem;
padding-bottom: 1rem;
border-top: 1px solid var(--color-border);
}
.remix-app__footer-content {
display: flex;
justify-content: center;
align-items: center;
}
.remix__page {
--gap: 1rem;
--space: 2rem;
display: grid;
grid-auto-rows: min-content;
gap: var(--gap);
padding-top: var(--space);
padding-bottom: var(--space);
}
@media print, screen and (min-width: 640px) {
.remix__page {
--gap: 2rem;
grid-auto-rows: unset;
grid-template-columns: repeat(2, 1fr);
}
}
@media screen and (min-width: 1024px) {
.remix__page {
--gap: 4rem;
}
}
.remix__page > main > :first-child {
margin-top: 0;
}
.remix__page > main > :last-child {
margin-bottom: 0;
}
.remix__page > aside {
margin: 0;
padding: 1.5ch 2ch;
border: solid 1px var(--color-border);
border-radius: 0.5rem;
}
.remix__page > aside > :first-child {
margin-top: 0;
}
.remix__page > aside > :last-child {
margin-bottom: 0;
}
.remix__form {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
border: 1px solid var(--color-border);
border-radius: 0.5rem;
}
.remix__form > * {
margin-top: 0;
margin-bottom: 0;
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,22 +6,21 @@
"dev": "remix dev"
},
"dependencies": {
"@remix-run/node": "^1.7.5",
"@remix-run/react": "^1.7.5",
"@remix-run/vercel": "^1.7.5",
"@vercel/analytics": "^0.1.3",
"@vercel/node": "^2.4.4",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"@remix-run/node": "^1.5.1",
"@remix-run/react": "^1.5.1",
"@remix-run/vercel": "^1.5.1",
"@vercel/node": "^2.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@remix-run/dev": "^1.7.5",
"@remix-run/eslint-config": "^1.7.5",
"@remix-run/serve": "^1.7.5",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"eslint": "^8.23.1",
"typescript": "^4.7.4"
"@remix-run/dev": "^1.5.1",
"@remix-run/eslint-config": "^1.5.1",
"@remix-run/serve": "^1.5.1",
"@types/react": "^17.0.45",
"@types/react-dom": "^17.0.17",
"eslint": "^8.15.0",
"typescript": "^4.6.4"
},
"engines": {
"node": ">=14"

View File

@@ -1,4 +1,6 @@
/** @type {import('@remix-run/dev').AppConfig} */
/**
* @type {import('@remix-run/dev').AppConfig}
*/
module.exports = {
serverBuildTarget: "vercel",
// When running locally in development mode, we use the built in remix

View File

@@ -1,2 +1,2 @@
/// <reference types="@remix-run/dev" />
/// <reference types="@remix-run/node" />
/// <reference types="@remix-run/node/globals" />

View File

@@ -1,4 +1,4 @@
import { createRequestHandler } from "@remix-run/vercel";
import * as build from "@remix-run/dev/server-build";
import { createRequestHandler } from "@remix-run/vercel";
export default createRequestHandler({ build, mode: process.env.NODE_ENV });

View File

@@ -2,16 +2,12 @@
"include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2019"],
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"moduleResolution": "node",
"resolveJsonModule": true,
"target": "ES2019",
"strict": true,
"allowJs": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"~/*": ["./app/*"]
},

View File

@@ -7,16 +7,12 @@
"type": "module",
"private": true,
"devDependencies": {
"solid-start-vercel": "^0.2.0",
"typescript": "^4.8.3",
"vite": "^3.1.0"
},
"dependencies": {
"@solidjs/meta": "^0.28.2",
"@solidjs/router": "^0.5.0",
"solid-js": "^1.6.0",
"solid-start": "^0.2.0",
"undici": "^5.11.0"
"solid-app-router": "^0.3.2",
"solid-js": "^1.3.15",
"solid-meta": "^0.27.3",
"solid-start": "next",
"solid-start-vercel": "next",
"vite": "^2.9.9"
},
"engines": {
"node": "16.x"

View File

@@ -1,3 +1,4 @@
import { mount, StartClient } from 'solid-start/entry-client';
import { hydrate } from "solid-js/web";
import { StartClient } from "solid-start/entry-client";
mount(() => <StartClient />, document);
hydrate(() => <StartClient />, document);

View File

@@ -1,9 +1,7 @@
import {
StartServer,
createHandler,
renderAsync,
} from 'solid-start/entry-server';
import { StartServer, createHandler, renderAsync } from "solid-start/entry-server";
import { inlineServerModules } from "solid-start/server";
export default createHandler(
renderAsync(event => <StartServer event={event} />)
inlineServerModules,
renderAsync((context) => <StartServer context={context} />)
);

View File

@@ -1,33 +1,25 @@
// @refresh reload
import {
Html,
Head,
Body,
Meta,
Routes,
FileRoutes,
Scripts,
ErrorBoundary,
} from 'solid-start';
import { Suspense } from 'solid-js';
import { Links, Meta, Routes, Scripts } from "solid-start/root";
import { ErrorBoundary } from "solid-start/error-boundary";
import { Suspense } from "solid-js";
export default function Root() {
return (
<Html lang="en">
<Head>
<Meta charset="utf-8" />
<Meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<Body>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<ErrorBoundary>
<Suspense>
<Routes>
<FileRoutes />
</Routes>
<Routes />
</Suspense>
</ErrorBoundary>
<Scripts />
</Body>
</Html>
</body>
</html>
);
}

View File

@@ -8,8 +8,8 @@ export default function Home() {
<Counter />
<p>
Visit{" "}
<a href="https://start.solidjs.com" target="_blank">
start.solidjs.com
<a href="https://solidjs.com" target="_blank">
solidjs.com
</a>{" "}
to learn how to build Solid apps.
</p>

View File

@@ -0,0 +1,7 @@
{
"build": {
"env": {
"ENABLE_VC_BUILD": "1"
}
}
}

View File

@@ -1,5 +1,5 @@
import { defineConfig } from "vite";
import solid from "solid-start/vite";
import solid from "solid-start";
import vercel from "solid-start-vercel";
export default defineConfig({

File diff suppressed because it is too large Load Diff

View File

@@ -44,14 +44,14 @@
"publish-canary": "git checkout main && git pull && lerna version prerelease --preid canary --message \"Publish Canary\" --exact",
"publish-from-github": "./utils/publish.sh",
"changelog": "node utils/changelog.js",
"build": "node utils/gen.js && turbo run build",
"build": "turbo run build",
"vercel-build": "yarn build && yarn run pack && cd api && node -r ts-eager/register ./_lib/script/build.ts",
"pre-commit": "lint-staged",
"test": "jest --rootDir=\"test\" --testPathPattern=\"\\.test.js\"",
"test-unit": "yarn test && node utils/gen.js && turbo run test-unit",
"test-integration-cli": "node utils/gen.js && turbo run test-integration-cli",
"test-integration-once": "node utils/gen.js && turbo run test-integration-once",
"test-integration-dev": "node utils/gen.js && turbo run test-integration-dev",
"test-unit": "yarn test && turbo run test-unit",
"test-integration-cli": "turbo run test-integration-cli",
"test-integration-once": "turbo run test-integration-once",
"test-integration-dev": "turbo run test-integration-dev",
"lint": "eslint . --ext .ts,.js",
"prepare": "husky install",
"pack": "cd utils && node -r ts-eager/register ./pack.ts"

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/build-utils",
"version": "5.5.7",
"version": "5.5.5",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.js",

View File

@@ -3,37 +3,28 @@ import { NodeVersion } from '../types';
import { NowBuildError } from '../errors';
import debug from '../debug';
function getOptions() {
const options = [
{ major: 16, range: '16.x', runtime: 'nodejs16.x' },
{ major: 14, range: '14.x', runtime: 'nodejs14.x' },
{
major: 12,
range: '12.x',
runtime: 'nodejs12.x',
discontinueDate: new Date('2022-10-03'),
},
{
major: 10,
range: '10.x',
runtime: 'nodejs10.x',
discontinueDate: new Date('2021-04-20'),
},
{
major: 8,
range: '8.10.x',
runtime: 'nodejs8.10',
discontinueDate: new Date('2020-01-06'),
},
] as const;
if (process.env.VERCEL_ALLOW_NODEJS18 === '1') {
return [
{ major: 18, range: '18.x', runtime: 'nodejs18.x' },
...options,
] as const;
}
return options;
}
const allOptions = [
{ major: 16, range: '16.x', runtime: 'nodejs16.x' },
{ major: 14, range: '14.x', runtime: 'nodejs14.x' },
{
major: 12,
range: '12.x',
runtime: 'nodejs12.x',
discontinueDate: new Date('2022-10-03'),
},
{
major: 10,
range: '10.x',
runtime: 'nodejs10.x',
discontinueDate: new Date('2021-04-20'),
},
{
major: 8,
range: '8.10.x',
runtime: 'nodejs8.10',
discontinueDate: new Date('2020-01-06'),
},
] as const;
function getHint(isAuto = false) {
const { major, range } = getLatestNodeVersion();
@@ -43,11 +34,11 @@ function getHint(isAuto = false) {
}
export function getLatestNodeVersion() {
return getOptions()[0];
return allOptions[0];
}
export function getDiscontinuedNodeVersions(): NodeVersion[] {
return getOptions().filter(isDiscontinued);
return allOptions.filter(isDiscontinued);
}
export async function getSupportedNodeVersion(
@@ -59,7 +50,7 @@ export async function getSupportedNodeVersion(
if (engineRange) {
const found =
validRange(engineRange) &&
getOptions().some(o => {
allOptions.some(o => {
// the array is already in order so return the first
// match which will be the newest version of node
selection = o;

View File

@@ -23,7 +23,6 @@ export interface LambdaOptionsBase {
regions?: string[];
supportsMultiPayloads?: boolean;
supportsWrapper?: boolean;
experimentalResponseStreaming?: boolean;
}
export interface LambdaOptionsWithFiles extends LambdaOptionsBase {
@@ -61,7 +60,6 @@ export class Lambda {
zipBuffer?: Buffer;
supportsMultiPayloads?: boolean;
supportsWrapper?: boolean;
experimentalResponseStreaming?: boolean;
constructor(opts: LambdaOptions) {
const {
@@ -74,7 +72,6 @@ export class Lambda {
regions,
supportsMultiPayloads,
supportsWrapper,
experimentalResponseStreaming,
} = opts;
if ('files' in opts) {
assert(typeof opts.files === 'object', '"files" must be an object');
@@ -135,7 +132,6 @@ export class Lambda {
this.zipBuffer = 'zipBuffer' in opts ? opts.zipBuffer : undefined;
this.supportsMultiPayloads = supportsMultiPayloads;
this.supportsWrapper = supportsWrapper;
this.experimentalResponseStreaming = experimentalResponseStreaming;
}
async createZip(): Promise<Buffer> {

View File

@@ -285,23 +285,6 @@ it('should match all semver ranges', async () => {
);
});
it('should only allow nodejs18.x when env var is set', async () => {
try {
expect(getLatestNodeVersion()).toHaveProperty('major', 16);
expect(getSupportedNodeVersion('18.x')).rejects.toThrow();
process.env.VERCEL_ALLOW_NODEJS18 = '1';
expect(getLatestNodeVersion()).toHaveProperty('major', 18);
expect(await getSupportedNodeVersion('18.x')).toHaveProperty('major', 18);
expect(await getSupportedNodeVersion('18')).toHaveProperty('major', 18);
expect(await getSupportedNodeVersion('18.1.0')).toHaveProperty('major', 18);
expect(await getSupportedNodeVersion('>=16')).toHaveProperty('major', 18);
} finally {
delete process.env.VERCEL_ALLOW_NODEJS18;
}
});
it('should ignore node version in vercel dev getNodeVersion()', async () => {
expect(
await getNodeVersion(

View File

@@ -1,6 +1,6 @@
{
"name": "vercel",
"version": "28.5.0",
"version": "28.4.12",
"preferGlobal": true,
"license": "Apache-2.0",
"description": "The command-line interface for Vercel",
@@ -12,7 +12,7 @@
},
"scripts": {
"preinstall": "node ./scripts/preinstall.js",
"test": "jest --env node --verbose --bail --forceExit",
"test": "jest --env node --verbose --runInBand --bail --forceExit",
"test-unit": "yarn test test/unit/",
"test-integration-cli": "rimraf test/fixtures/integration && ava test/integration.js --serial --fail-fast --verbose",
"test-integration-dev": "yarn test test/dev/",
@@ -41,16 +41,17 @@
"node": ">= 14"
},
"dependencies": {
"@vercel/build-utils": "5.5.7",
"@vercel/go": "2.2.15",
"@vercel/hydrogen": "0.0.29",
"@vercel/next": "3.2.11",
"@vercel/node": "2.6.2",
"@vercel/python": "3.1.25",
"@vercel/redwood": "1.0.35",
"@vercel/remix": "1.0.35",
"@vercel/ruby": "1.3.41",
"@vercel/static-build": "1.0.36",
"@vercel/build-utils": "5.5.5",
"@vercel/error-utils": "1.0.0",
"@vercel/go": "2.2.13",
"@vercel/hydrogen": "0.0.26",
"@vercel/next": "3.2.6",
"@vercel/node": "2.5.26",
"@vercel/python": "3.1.22",
"@vercel/redwood": "1.0.31",
"@vercel/remix": "1.0.32",
"@vercel/ruby": "1.3.39",
"@vercel/static-build": "1.0.32",
"update-notifier": "5.1.0"
},
"devDependencies": {
@@ -81,7 +82,7 @@
"@types/minimatch": "3.0.3",
"@types/mri": "1.1.0",
"@types/ms": "0.7.30",
"@types/node": "14.18.33",
"@types/node": "11.11.0",
"@types/node-fetch": "2.5.10",
"@types/npm-package-arg": "6.1.0",
"@types/pluralize": "0.0.29",
@@ -95,10 +96,9 @@
"@types/which": "1.3.2",
"@types/write-json-file": "2.2.1",
"@types/yauzl-promise": "2.1.0",
"@vercel/client": "12.2.17",
"@vercel/error-utils": "1.0.3",
"@vercel/frameworks": "1.1.12",
"@vercel/fs-detectors": "3.5.0",
"@vercel/client": "12.2.13",
"@vercel/frameworks": "1.1.8",
"@vercel/fs-detectors": "3.4.5",
"@vercel/fun": "1.0.4",
"@vercel/ncc": "0.24.0",
"@zeit/source-map-support": "0.6.2",
@@ -172,6 +172,7 @@
"typescript": "4.7.4",
"universal-analytics": "0.4.20",
"utility-types": "2.1.0",
"which": "2.0.2",
"write-json-file": "2.2.0",
"xdg-app-paths": "5.1.0",
"yauzl-promise": "2.1.3"

View File

@@ -58,8 +58,6 @@ import { sortBuilders } from '../util/build/sort-builders';
import { toEnumerableError } from '../util/error';
import { validateConfig } from '../util/validate-config';
import { setMonorepoDefaultSettings } from '../util/build/monorepo';
type BuildResult = BuildResultV2 | BuildResultV3;
interface SerializedBuilder extends Builder {
@@ -101,7 +99,7 @@ const help = () => {
${chalk.dim('Examples:')}
${chalk.gray('-')} Build the project
${chalk.gray('')} Build the project
${chalk.cyan(`$ ${cli.name} build`)}
${chalk.cyan(`$ ${cli.name} build --cwd ./path-to-project`)}
@@ -273,7 +271,6 @@ async function doBuild(
outputDir: string
): Promise<void> {
const { output } = client;
const workPath = join(cwd, project.settings.rootDirectory || '.');
const [pkg, vercelConfig, nowConfig] = await Promise.all([
@@ -304,8 +301,6 @@ async function doBuild(
...pickOverrides(localConfig),
};
await setMonorepoDefaultSettings(cwd, workPath, projectSettings, output);
// Get a list of source files
const files = (await getFiles(workPath, client)).map(f =>
normalizePath(relative(workPath, f))

View File

@@ -1,139 +0,0 @@
import fs from 'fs-extra';
import { join, relative, basename } from 'path';
import {
detectFramework,
monorepoManagers,
LocalFileSystemDetector,
packageManagers,
} from '@vercel/fs-detectors';
import { ProjectLinkAndSettings } from '../projects/project-settings';
import { Output } from '../output';
import title from 'title';
export async function setMonorepoDefaultSettings(
cwd: string,
workPath: string,
projectSettings: ProjectLinkAndSettings['settings'],
output: Output
) {
const localFileSystem = new LocalFileSystemDetector(cwd);
const [monorepoManager, packageManager] = await Promise.all([
detectFramework({
fs: localFileSystem,
frameworkList: monorepoManagers,
}),
detectFramework({
fs: localFileSystem,
frameworkList: packageManagers,
}),
]);
const projectName = basename(workPath);
const relativeToRoot = relative(workPath, cwd);
const setCommand = (
command: 'buildCommand' | 'installCommand',
value: string
) => {
if (projectSettings[command]) {
output.warn(
`Cannot automatically assign ${command} as it is already set via project settings or configuarion overrides.`
);
} else {
projectSettings[command] = value;
}
};
if (monorepoManager) {
output.log(
`Automatically detected ${title(
monorepoManager
)} monorepo manager. Attempting to assign default \`buildCommand\` and \`installCommand\` settings.`
);
}
if (monorepoManager === 'turbo') {
// No ENOENT handling required here since conditional wouldn't be `true` unless `turbo.json` was found.
const turboJSON = JSON.parse(
fs.readFileSync(join(cwd, 'turbo.json'), 'utf-8')
);
if (!turboJSON?.pipeline?.build) {
output.warn(
'Missing required `build` pipeline in turbo.json. Skipping automatic setting assignment.'
);
return;
}
setCommand(
'buildCommand',
`cd ${relativeToRoot} && npx turbo run build --filter=${projectName}...`
);
setCommand(
'installCommand',
`cd ${relativeToRoot} && ${packageManager} install`
);
} else if (monorepoManager === 'nx') {
// No ENOENT handling required here since conditional wouldn't be `true` unless `nx.json` was found.
const nxJSON = JSON.parse(fs.readFileSync(join(cwd, 'nx.json'), 'utf-8'));
if (!nxJSON?.targetDefaults?.build) {
output.log(
'Missing default `build` target in nx.json. Checking for project level Nx configuration...'
);
const [projectJSONBuf, packageJsonBuf] = await Promise.all([
fs.readFile(join(workPath, 'project.json')).catch(() => null),
fs.readFile(join(workPath, 'package.json')).catch(() => null),
]);
let hasBuildTarget = false;
if (projectJSONBuf) {
output.log('Found project.json Nx configuration.');
const projectJSON = JSON.parse(projectJSONBuf.toString('utf-8'));
if (projectJSON?.targets?.build) {
hasBuildTarget = true;
}
}
if (packageJsonBuf) {
const packageJSON = JSON.parse(packageJsonBuf.toString('utf-8'));
if (packageJSON?.nx) {
output.log('Found package.json Nx configuration.');
if (packageJSON.nx.targets?.build) {
hasBuildTarget = true;
}
}
}
if (!hasBuildTarget) {
output.warn(
'Missing required `build` target in either project.json or package.json Nx configuration. Skipping automatic setting assignment.'
);
return;
}
}
setCommand(
'buildCommand',
`cd ${relativeToRoot} && npx nx build ${projectName}`
);
setCommand(
'installCommand',
`cd ${relativeToRoot} && ${packageManager} install`
);
}
// TODO (@Ethan-Arrowood) - Revisit rush support when we can test it better
/* else if (monorepoManager === 'rush') {
setCommand(
'buildCommand',
`node ${relativeToRoot}/common/scripts/install-run-rush.js build --to ${projectName}`
);
setCommand(
'installCommand',
`node ${relativeToRoot}/common/scripts/install-run-rush.js install`
);
} */
}

View File

@@ -1,7 +1,8 @@
import { bold } from 'chalk';
import inquirer from 'inquirer';
import { EventEmitter } from 'events';
import { URL } from 'url';
import { URLSearchParams } from 'url';
import { parse as parseUrl } from 'url';
import { VercelConfig } from '@vercel/client';
import retry, { RetryFunction, Options as RetryOptions } from 'async-retry';
import fetch, { BodyInit, Headers, RequestInit, Response } from 'node-fetch';
@@ -86,18 +87,25 @@ export default class Client extends EventEmitter implements Stdio {
}
private _fetch(_url: string, opts: FetchOptions = {}) {
const url = new URL(_url, this.apiUrl);
const parsedUrl = parseUrl(_url, true);
const apiUrl = parsedUrl.host
? `${parsedUrl.protocol}//${parsedUrl.host}`
: '';
if (opts.accountId || opts.useCurrentTeam !== false) {
const query = new URLSearchParams(parsedUrl.query);
if (opts.accountId) {
if (opts.accountId.startsWith('team_')) {
url.searchParams.set('teamId', opts.accountId);
query.set('teamId', opts.accountId);
} else {
url.searchParams.delete('teamId');
query.delete('teamId');
}
} else if (opts.useCurrentTeam !== false && this.config.currentTeam) {
url.searchParams.set('teamId', this.config.currentTeam);
query.set('teamId', this.config.currentTeam);
}
_url = `${apiUrl}${parsedUrl.pathname}?${query}`;
}
const headers = new Headers(opts.headers);
@@ -114,6 +122,7 @@ export default class Client extends EventEmitter implements Stdio {
body = opts.body;
}
const url = `${apiUrl ? '' : this.apiUrl}${_url}`;
const requestId = this.requestIdCounter++;
return this.output.time(res => {
if (res) {
@@ -121,7 +130,7 @@ export default class Client extends EventEmitter implements Stdio {
res.statusText
}: ${res.headers.get('x-vercel-id')}`;
} else {
return `#${requestId}${opts.method || 'GET'} ${url.href}`;
return `#${requestId}${opts.method || 'GET'} ${url}`;
}
}, fetch(url, { ...opts, headers, body }));
}

View File

@@ -87,12 +87,8 @@ async function createBuildProcess(
return new Promise((resolve, reject) => {
// The first message that the builder process sends is the `ready` event
buildProcess.once('message', data => {
if (
data !== null &&
typeof data === 'object' &&
(data as { type: string }).type !== 'ready'
) {
buildProcess.once('message', ({ type }) => {
if (type !== 'ready') {
reject(new Error('Did not get "ready" event from builder'));
} else {
resolve(buildProcess);

View File

@@ -31,11 +31,11 @@ export function parseListen(str: string, defaultPort = 3000): ListenSpec {
return [url.pathname];
case 'tcp:':
url.port = url.port || String(defaultPort);
return [parseInt(url.port, 10), url.hostname ?? undefined];
return [parseInt(url.port, 10), url.hostname];
default:
if (!url.slashes) {
if (url.protocol === null) {
return [defaultPort, url.pathname ?? undefined];
return [defaultPort, url.pathname];
}
port = Number(url.hostname);
if (url.protocol && !isNaN(port)) {

View File

@@ -4,7 +4,7 @@
* @param querystring - The querystring to parse, also known as the "search" string.
*/
export function parseQueryString(
querystring?: string | null
querystring?: string
): Record<string, string[]> {
const query: Record<string, string[]> = Object.create(null);
if (!querystring || !querystring.startsWith('?') || querystring === '?') {
@@ -38,9 +38,9 @@ export function parseQueryString(
*/
export function formatQueryString(
query: Record<string, string[]> | undefined
): string | null {
): string | undefined {
if (!query) {
return null;
return undefined;
}
let s = '';
let prefix = '?';
@@ -55,5 +55,5 @@ export function formatQueryString(
prefix = '&';
}
}
return s || null;
return s || undefined;
}

View File

@@ -57,8 +57,7 @@ export async function devRouter(
phase?: HandleValue | null
): Promise<RouteResult> {
let result: RouteResult | undefined;
let { pathname: reqPathname, search: reqSearch } = url.parse(reqUrl);
reqPathname ??= '/';
let { pathname: reqPathname = '/', search: reqSearch } = url.parse(reqUrl);
const reqQuery = parseQueryString(reqSearch);
const combinedHeaders: HttpHeadersConfig = { ...previousHeaders };
let status: number | undefined;
@@ -131,8 +130,7 @@ export async function devRouter(
phase !== 'hit' &&
!isDestUrl
) {
let { pathname } = url.parse(destPath);
pathname ??= '/';
const { pathname = '/' } = url.parse(destPath);
const hasDestFile = await devServer.hasFilesystem(
pathname,
vercelConfig
@@ -188,9 +186,8 @@ export async function devRouter(
if (!destPath.startsWith('/')) {
destPath = `/${destPath}`;
}
let { pathname: destPathname, search: destSearch } =
const { pathname: destPathname = '/', search: destSearch } =
url.parse(destPath);
destPathname ??= '/';
const destQuery = parseQueryString(destSearch);
Object.assign(destQuery, reqQuery);
result = {

View File

@@ -18,6 +18,7 @@ import directoryTemplate from 'serve-handler/src/directory';
import getPort from 'get-port';
import isPortReachable from 'is-port-reachable';
import deepEqual from 'fast-deep-equal';
import which from 'which';
import npa from 'npm-package-arg';
import type { ChildProcess } from 'child_process';
@@ -32,7 +33,6 @@ import {
Builder,
cloneEnv,
Env,
getNodeBinPath,
StartDevServerResult,
FileFsRef,
PackageJson,
@@ -1448,9 +1448,7 @@ export default class DevServer {
}
);
const middlewareBody = await middlewareRes.buffer();
if (middlewareRes.status === 500 && middlewareBody.byteLength === 0) {
if (middlewareRes.status === 500) {
await this.sendError(
req,
res,
@@ -1495,6 +1493,7 @@ export default class DevServer {
}
if (!shouldContinue) {
const middlewareBody = await middlewareRes.buffer();
this.setResponseHeaders(res, requestId);
if (middlewareBody.length > 0) {
res.setHeader('content-length', middlewareBody.length);
@@ -2238,10 +2237,6 @@ export default class DevServer {
}
);
// add the node_modules/.bin directory to the PATH
const nodeBinPath = await getNodeBinPath({ cwd });
env.PATH = `${nodeBinPath}${path.delimiter}${env.PATH}`;
// This is necesary so that the dev command in the Project
// will work cross-platform (especially Windows).
let command = devCommand
@@ -2256,6 +2251,22 @@ export default class DevServer {
})}`
);
const isNpxAvailable = await which('npx')
.then(() => true)
.catch(() => false);
if (isNpxAvailable) {
command = `npx --no-install ${command}`;
} else {
const isYarnAvailable = await which('yarn')
.then(() => true)
.catch(() => false);
if (isYarnAvailable) {
command = `yarn run --silent ${command}`;
}
}
this.output.debug(`Spawning dev command: ${command}`);
const proxyPort = new RegExp(port.toString(), 'g');

View File

@@ -1,4 +1,4 @@
import type Client from '../client';
import Client from '../client';
export default async function confirm(
client: Client,

View File

@@ -34,10 +34,7 @@ export async function ensureLink(
): Promise<LinkResult | number> {
let link = await getLinkedProject(client, cwd);
if (
(link.status === 'linked' && opts.forceDelete) ||
link.status === 'not_linked'
) {
if (link.status === 'not_linked') {
link = await setupAndLink(client, cwd, opts);
if (link.status === 'not_linked') {

View File

@@ -6,7 +6,7 @@
},
"dependencies": {
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react": "^17.0.0",
"react-dom": "^17.0.0"
}
}

View File

@@ -1 +1 @@
export default () => new Response('Example Error', { status: 500 });
export default () => new Response(null, { status: 500 });

View File

@@ -104,38 +104,13 @@ test(
test('[vercel dev] 08-hugo', async () => {
if (process.platform === 'darwin') {
// 1. run the test without Hugo in the PATH
let tester = await testFixtureStdio(
'08-hugo',
async () => {
throw new Error('Expected dev server to fail to be ready');
},
{
readyTimeout: 2000,
// Important: for the first test, we MUST deploy this app so that the
// framework (e.g. Hugo) will be detected by the server and associated
// with the project since `vc dev` doesn't do framework detection
skipDeploy: false,
}
);
await expect(tester()).rejects.toThrow(
new Error('Dev server timed out while waiting to be ready')
);
// 2. Update PATH to find the Hugo executable installed via GH Actions
// Update PATH to find the Hugo executable installed via GH Actions
process.env.PATH = `${resolve(fixture('08-hugo'))}${delimiter}${
process.env.PATH
}`;
// 3. Rerun the test now that Hugo is in the PATH
tester = testFixtureStdio(
'08-hugo',
async (testPath: any) => {
await testPath(200, '/', /Hugo/m);
},
{ skipDeploy: true }
);
const tester = testFixtureStdio('08-hugo', async (testPath: any) => {
await testPath(200, '/', /Hugo/m);
});
await tester();
} else {
console.log(`Skipping 08-hugo on platform ${process.platform}`);

View File

@@ -551,7 +551,7 @@ test(
test(
'[vercel dev] Middleware with an explicit 500 response',
testFixtureStdio('middleware-500-response', async (testPath: any) => {
await testPath(500, '/', 'Example Error');
await testPath(500, '/', /EDGE_FUNCTION_INVOCATION_FAILED/);
})
);

View File

@@ -61,13 +61,8 @@ function fetchWithRetry(url, opts = {}) {
function createResolver() {
let resolver;
let rejector;
const p = new Promise((resolve, reject) => {
resolver = resolve;
rejector = reject;
});
const p = new Promise(res => (resolver = res));
p.resolve = resolver;
p.reject = rejector;
return p;
}
@@ -279,13 +274,7 @@ async function testFixture(directory, opts = {}, args = []) {
function testFixtureStdio(
directory,
fn,
{
expectedCode = 0,
skipDeploy,
isExample,
projectSettings,
readyTimeout = 0,
} = {}
{ expectedCode = 0, skipDeploy, isExample, projectSettings } = {}
) {
return async () => {
const nodeMajor = Number(process.versions.node.split('.')[0]);
@@ -396,18 +385,6 @@ function testFixtureStdio(
const readyResolver = createResolver();
const exitResolver = createResolver();
// By default, tests will wait 6 minutes for the dev server to be ready and
// perform the tests, however a `readyTimeout` can be used to reduce the
// wait time if the dev server is expected to fail to start or hang
let readyTimer = null;
if (readyTimeout > 0) {
readyTimer = setTimeout(() => {
readyResolver.reject(
new Error('Dev server timed out while waiting to be ready')
);
}, readyTimeout);
}
try {
let printedOutput = false;
@@ -447,7 +424,6 @@ function testFixtureStdio(
stderr += data;
if (stripAnsi(data).includes('Ready! Available at')) {
clearTimeout(readyTimer);
readyResolver.resolve();
}
@@ -531,6 +507,5 @@ module.exports = {
shouldSkip,
fixture,
fetch,
fetchWithRetry,
validateResponseHeaders,
};

View File

@@ -1,2 +1,2 @@
!/**/*/.vercel
/**/*/.vercel/output
!/*/.vercel
/*/.vercel/output

View File

@@ -1,5 +0,0 @@
{
"orgId": ".",
"projectId": ".",
"settings": { "outputDirectory": "dist", "rootDirectory": "packages/app-1" }
}

View File

@@ -1,4 +0,0 @@
{
"extends": "nx/presets/npm.json",
"tasksRunnerOptions": { "default": { "runner": "nx/tasks-runners/default" } }
}

View File

@@ -1,9 +0,0 @@
{
"private": true,
"workspaces": [
"packages/*"
],
"devDependencies": {
"nx": "15.0.1"
}
}

View File

@@ -1,8 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const world = require('app-2');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.txt'), `Hello, ${world}`);

View File

@@ -1,23 +0,0 @@
{
"name": "app-1",
"version": "0.0.1",
"scripts": {
"build": "node index.js"
},
"dependencies": {
"app-2": "*"
},
"nx": {
"targets": {
"build": {
"executor": "nx:run-script",
"options": {
"script": "build"
},
"dependsOn": [
"^build"
]
}
}
}
}

View File

@@ -1,24 +0,0 @@
{
"name": "app-2",
"version": "0.0.1",
"main": "dist/index.js",
"files": [
"dist"
],
"scripts": {
"build": "node script.js"
},
"nx": {
"targets": {
"build": {
"executor": "nx:run-script",
"options": {
"script": "build"
},
"dependsOn": [
"^build"
]
}
}
}
}

View File

@@ -1,7 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.js'), 'module.exports = "world"');

View File

@@ -1,5 +0,0 @@
{
"orgId": ".",
"projectId": ".",
"settings": { "outputDirectory": "dist", "rootDirectory": "packages/app-1" }
}

View File

@@ -1,4 +0,0 @@
{
"extends": "nx/presets/npm.json",
"tasksRunnerOptions": { "default": { "runner": "nx/tasks-runners/default" } }
}

View File

@@ -1,9 +0,0 @@
{
"private": true,
"workspaces": [
"packages/*"
],
"devDependencies": {
"nx": "15.0.1"
}
}

View File

@@ -1,8 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const world = require('app-2');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.txt'), `Hello, ${world}`);

View File

@@ -1,13 +0,0 @@
{
"name": "app-1",
"version": "0.0.1",
"scripts": {
"build": "node index.js"
},
"dependencies": {
"app-2": "*"
},
"nx": {
"targets": {}
}
}

View File

@@ -1,9 +0,0 @@
{
"targets": {
"build": {
"executor": "nx:run-script",
"options": { "script": "build" },
"dependsOn": ["^build"]
}
}
}

View File

@@ -1,11 +0,0 @@
{
"name": "app-2",
"version": "0.0.1",
"main": "dist/index.js",
"files": [
"dist"
],
"scripts": {
"build": "node script.js"
}
}

View File

@@ -1,9 +0,0 @@
{
"targets": {
"build": {
"executor": "nx:run-script",
"options": { "script": "build" },
"dependsOn": ["^build"]
}
}
}

View File

@@ -1,7 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.js'), 'module.exports = "world"');

View File

@@ -1,5 +0,0 @@
{
"orgId": ".",
"projectId": ".",
"settings": { "outputDirectory": "dist", "rootDirectory": "packages/app-1" }
}

View File

@@ -1,4 +0,0 @@
{
"extends": "nx/presets/npm.json",
"tasksRunnerOptions": { "default": { "runner": "nx/tasks-runners/default" } }
}

View File

@@ -1,9 +0,0 @@
{
"private": true,
"workspaces": [
"packages/*"
],
"devDependencies": {
"nx": "15.0.1"
}
}

View File

@@ -1,8 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const world = require('app-2');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.txt'), `Hello, ${world}`);

View File

@@ -1,23 +0,0 @@
{
"name": "app-1",
"version": "0.0.1",
"scripts": {
"build": "node index.js"
},
"dependencies": {
"app-2": "*"
},
"nx": {
"targets": {
"build": {
"executor": "nx:run-script",
"options": {
"script": "build"
},
"dependsOn": [
"^build"
]
}
}
}
}

View File

@@ -1,11 +0,0 @@
{
"name": "app-2",
"version": "0.0.1",
"main": "dist/index.js",
"files": [
"dist"
],
"scripts": {
"build": "node script.js"
}
}

View File

@@ -1,9 +0,0 @@
{
"targets": {
"build": {
"executor": "nx:run-script",
"options": { "script": "build" },
"dependsOn": ["^build"]
}
}
}

View File

@@ -1,7 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.js'), 'module.exports = "world"');

View File

@@ -1,5 +0,0 @@
{
"orgId": ".",
"projectId": ".",
"settings": { "outputDirectory": "dist", "rootDirectory": "packages/app-1" }
}

View File

@@ -1,4 +0,0 @@
{
"extends": "nx/presets/npm.json",
"tasksRunnerOptions": { "default": { "runner": "nx/tasks-runners/default" } }
}

View File

@@ -1,9 +0,0 @@
{
"private": true,
"workspaces": [
"packages/*"
],
"devDependencies": {
"nx": "15.0.1"
}
}

View File

@@ -1,8 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const world = require('app-2');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.txt'), `Hello, ${world}`);

View File

@@ -1,10 +0,0 @@
{
"name": "app-1",
"version": "0.0.1",
"scripts": {
"build": "node index.js"
},
"dependencies": {
"app-2": "*"
}
}

View File

@@ -1,9 +0,0 @@
{
"targets": {
"build": {
"executor": "nx:run-script",
"options": { "script": "build" },
"dependsOn": ["^build"]
}
}
}

View File

@@ -1,11 +0,0 @@
{
"name": "app-2",
"version": "0.0.1",
"main": "dist/index.js",
"files": [
"dist"
],
"scripts": {
"build": "node script.js"
}
}

View File

@@ -1,9 +0,0 @@
{
"targets": {
"build": {
"executor": "nx:run-script",
"options": { "script": "build" },
"dependsOn": ["^build"]
}
}
}

View File

@@ -1,7 +0,0 @@
const path = require('node:path');
const fs = require('node:fs');
const dist = path.join(__dirname, 'dist');
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(dist);
fs.writeFileSync(path.join(dist, 'index.js'), 'module.exports = "world"');

View File

@@ -1,5 +0,0 @@
{
"orgId": ".",
"projectId": ".",
"settings": { "outputDirectory": "dist", "rootDirectory": "packages/app-1" }
}

View File

@@ -1,5 +0,0 @@
{
"extends": "nx/presets/npm.json",
"tasksRunnerOptions": { "default": { "runner": "nx/tasks-runners/default" } },
"targetDefaults": { "build": { "dependsOn": ["^build"] } }
}

View File

@@ -1,9 +0,0 @@
{
"private": true,
"workspaces": [
"packages/*"
],
"devDependencies": {
"nx": "15.0.1"
}
}

Some files were not shown because too many files have changed in this diff Show More