feat: remove fresh cli, do manifest generation in process (#223)

This commit removes the `fresh` cli, replacing it with a small bootstrap script,
and JIT generation of the manifest that happens in process during development.
This commit is contained in:
Luca Casonato
2022-06-14 09:39:38 +02:00
committed by GitHub
parent 844ded8cfd
commit 836cc24bdd
40 changed files with 362 additions and 730 deletions
+7 -7
View File
@@ -33,7 +33,7 @@ jobs:
run: deno lint
- name: Cache dependencies
run: deno cache --no-check src/cli/deps.ts src/runtime/deps.ts src/server/deps.ts
run: deno cache --no-check src/dev/deps.ts src/runtime/deps.ts src/server/deps.ts
- name: Cache Chrome (Linux)
if: startsWith(matrix.os, 'ubuntu')
@@ -70,21 +70,21 @@ jobs:
- name: Run tests
run: deno test -A
- name: Type check CLI
run: deno check --remote cli.ts
- name: Type check init script
run: deno check --remote init.ts
- name: Type check website
run: deno check --remote main.ts
run: deno check --remote main.ts dev.ts
working-directory: www/
- name: Type check examples/counter
run: deno check --remote main.ts
run: deno check --remote main.ts dev.ts
working-directory: examples/counter
- name: Type check tests/fixture
run: deno check main.ts
run: deno check main.ts dev.ts
working-directory: tests/fixture/
- name: Type check tests/fixture_error
run: deno check main.ts
run: deno check main.ts dev.ts
working-directory: tests/fixture_error/
+6 -15
View File
@@ -29,22 +29,13 @@ the framework.
The [documentation](https://fresh.deno.dev/docs/) is available on
[fresh.deno.dev](https://fresh.deno.dev/).
## Install
To install, run the following command. This will add `fresh` CLI to your PATH.
Make sure to have Deno 1.12.0 or later installed.
```sh
deno install -A -f --no-check -n fresh -r https://raw.githubusercontent.com/lucacasonato/fresh/main/cli.ts
```
## Getting started
The `fresh` CLI can scaffold a new project for you. To scaffold a project in the
`myproject` folder, run the following:
You can scaffold a new project by running the Fresh init script. To scaffold a
project in the `myproject` folder, run the following:
```sh
fresh init my-project
deno run -A --no-check https://raw.githubusercontent.com/lucacasonato/fresh/main/init.ts my-project
```
To now start the project, use `deno task`:
@@ -54,9 +45,9 @@ deno task start
```
To deploy the script to [Deno Deploy](https://deno.com/deploy), push your
project to GitHub, create a `fresh` project, and link it to `main.ts` file in
project to GitHub, create a Fresh project, and link it to **`main.ts`** file in
the created repository.
For a more in-depth getting started guide, visit the
[Getting Started](https://fresh.deno.dev/docs/getting-started) page in the
`fresh` docs.
[Getting Started](https://fresh.deno.dev/docs/getting-started) page in the Fresh
docs.
-53
View File
@@ -1,53 +0,0 @@
import { parseArgs } from "./src/cli/deps.ts";
import { initSubcommand } from "./src/cli/init.ts";
import { manifestSubcommand } from "./src/cli/manifest.ts";
const VERSION = "0.1.0";
const help = `fresh ${VERSION}
The next-gen web framework.
To initalize a new project:
fresh init ./myproject
To (re-)generate the manifest file:
fresh manifest
SUBCOMMANDS:
init Initalize a fresh project
manifest (Re-)generate the manifest file
`;
const args = parseArgs(Deno.args, {
alias: {
"help": "h",
"version": "V",
"watch": "w",
},
boolean: [
"help",
"version",
"watch",
],
});
const subcommand = args._.shift();
switch (subcommand) {
case "init":
await initSubcommand(args);
break;
case "manifest":
await manifestSubcommand(args);
break;
default:
if (args.version) {
console.log(`fresh ${VERSION}`);
Deno.exit(0);
}
if (args.help) {
console.log(help);
Deno.exit(0);
}
console.error(help);
Deno.exit(1);
}
+3 -3
View File
@@ -1,8 +1,8 @@
{
"tasks": {
"test": "deno test -A --no-check=remote && deno check --config=www/deno.json www/main.ts && deno check cli.ts",
"fixture": "deno run -A --watch ./tests/fixture/main.ts & deno run -A ./cli.ts manifest --watch ./tests/fixture",
"www": "deno run -A --watch=www/static,docs/ ./www/main.ts & deno run -A ./cli.ts manifest --watch ./www"
"test": "deno test -A --no-check=remote && deno check --config=www/deno.json www/main.ts www/dev.ts && deno check init.ts",
"fixture": "deno run -A --watch=static/,routes/,islands/ tests/fixture/dev.ts",
"www": "deno run -A --watch=static/,routes/,islands/ www/dev.ts"
},
"importMap": "./tests/fixture/import_map.json"
}
+2
View File
@@ -0,0 +1,2 @@
import { dev } from "./src/dev/mod.ts";
export default dev;
-62
View File
@@ -1,62 +0,0 @@
# Data fetching
Not all pages can be server rendered synchronously - some pages are dynamic and
require fetching some data from an external source. This data fetching is often
asynchronous.
Fresh supports asynchronous data fetching in handlers. This is not done during
rendering, but before rendering in the route
handler<!-- TODO: link route handlers page -->.
## Fetching data in a `handler`
To fetch data, you must first define a custom `handler` function. This function
is called when the route is requested. In there you can do some handling, and
then return a `Response` object. If you want to render the page, you can call
the `ctx.render` function. This returns a `Promise<Response>` that you can
return from the handler.
The `ctx.render` function takes a single argument, which is some data that you
want to pass to the page template. The data can be accessed in the template via
the `props.data` property.
Here is a usage example of a `handler` fetches a URL as JSON and provides the
resulting data to the template:
```tsx
import { h, Handlers, PageProps, useData } from "../deps.ts";
interface ModuleInfo {
latest: string;
versions: string[];
}
export const handler: Handlers<ModuleInfo> = {
async GET(ctx) {
const resp = await fetch("https://cdn.deno.land/std/meta/versions.json");
let data = null;
if (resp.status === 200) data = await resp.json();
return ctx.render(data);
},
};
export default function Page(props: PageProps<ModuleInfo>) {
const data = props.data;
if (data === null) {
return <div>Data not available.</div>;
}
const { latest, versions } = data;
return (
<p>
The Deno standard library has {versions.length} versions, with {latest}
{" "}
being the most recent.
</p>
);
}
```
If you want to fetch data client side, inside of an island, you can use
libraries like `"swr"`, or raw `useEffect` and `useState` as you usually would.
-28
View File
@@ -1,28 +0,0 @@
# File system routing
The naming and location of files in the `routes` folder is important because
these are used to specify the route where a specific API endpoint or HTML page
is available. This concept is called file system routing.
As an example, the HTML page described by `index.tsx` would be served at `/`,
while the `about.tsx` page would be served at `/about`. File system routing is
also capable of dynamic path segments: `/posts/[post].jsx` would be used for
requests to `/posts/foo`, `/posts/bar`, or `/posts/baz`, but not for
`/posts/foo/comments` (that would be matched by `/posts/[post]/comments.tsx`).
Multi-level dynamic segments are also possible: `/[owner]/[repo]/[...path]`
would match `/denoland/deno/README.md` and `/lucacasonato/fresh/cli/build.rs`.
Multi level dynamic segments can only be used as the last path segment.
## Comparison with path-to-regex
If you are more familiar with path-to-regex style routes, here is a simple
translation table to get you up to speed.
| `path-to-regex` | File system routing |
| ----------------------- | ------------------------------------------------------------------ |
| `/` | `/index.tsx` |
| `/about` | `/about.tsx` or `/about/index.tsx` |
| `/posts/:name` | `/posts/[name].tsx` or `/posts/[name]/index.tsx` |
| `/posts/:name/comments` | `/posts/[name]/comments.tsx` or `/posts/[name]/comments/index.tsx` |
| `/x/:module/:path*` | `/x/[module]/[...path].tsx` |
-85
View File
@@ -1,85 +0,0 @@
# Getting Started
Welcome to the `fresh` documentation.
## Requirements
The documentation assumes you have Deno 1.20.1 or later installed.
To install Deno, follow the installation instructions in the manual:
https://deno.land/manual/getting_started/installation
## Setup
`fresh` comes with a CLI tool, conveniently also called `fresh`. It is used to
scaffold new projects and generate the route manifest. You will only need this
tool if you are creating a new project, or are creating or moving pages around
inside an existing project. The `fresh` CLI is not required for most development
or in CI, as `fresh` does not have a build step. To install `fresh`:
```
deno install -A -f --no-check -n fresh -r https://raw.githubusercontent.com/lucacasonato/fresh/main/cli.ts
```
## Creating a new project
Creating a new project can be done as follows:
```
fresh init my-project
```
The first argument passed to `fresh init` (in the above case `my-project`), is
the path to a folder you would like to initalize a `fresh` project in. To
initalize a project in the current working directory, pass `.` as the first
argument.
Now move into the directory you just created / initalized (for example
`cd my-project`).
To learn more about how projects are structured, take a look at the
[Project Structure](./project-structure.md) documentation.
## Running the project locally
You can now run your new project locally using the `deno` CLI:
```
deno task start
```
The `--watch` option in `start` task will cause your script to be reloaded on
any changes to the source. If you do not want this you can omit the `--watch`
option in `deno.json`.
After you have started the project, you can view it in your browser at
http://localhost:8000. You will first get served a JIT server rendered page,
which will get hydrated using client side JS after a few moments.
## Deploying the project to Deno Deploy
To deploy your project you will need to push the source code to either a web
server, or GitHub.com. Fresh currently only supports public GitHub repositories.
For this guide we will use GitHub.com and the Deno Deploy GitHub integration.
First create a new repository on GitHub.com with the same account you signed up
to Deno Deploy with (or an organization you can access from that account). Then
follow the setup instructions for GitHub on your machine, and push your code
into the repository.
Visit your project on dash.deno.com, go to the "Git" tab in the settings, select
your organization and repository, select your production branch (usually
`main`), and finally select your entrypoint module (`main.ts`. You might need to
grant the Deno Deploy app permission to the repository at this point (follow
prompts on the Deno Deploy dashboard).
Your project is now linked to Deno Deploy and will automatically deployed on
every push. Your project now has a URL you can visit to view your site live.
Example: https://fresh.deno.dev
## Next steps
Now that the project is deployed, it is time to make some changes to the default
project. For that read the guides on
[project structure](./project-structure.md), [data fetching](./data-fetching.md)
and [file system routing](./file-system-routing.md)
+4 -8
View File
@@ -17,10 +17,10 @@ static page might need a little bit of JavaScript to power a image carousel or
[islands architecture][islands-architecture]. This refers to a page having
little "islands" of interactivity, in a sea of otherwise static content.
`fresh` embraces this model. All pages are rendered server side, but you can
Fresh embraces this model. All pages are rendered server side, but you can
create "island components" that are _also_ rendered client side. To do this,
`fresh` projects have a special `islands/` folder. The modules in this folder
each encapsulate a single island component. The name of the module should be the
Fresh projects have a special `islands/` folder. The modules in this folder each
encapsulate a single island component. The name of the module should be the
[pascal case][pascal-case] name of the island component. For example a counter
component would be defined in the file `islands/Counter.tsx`. A buy now button
would be defined in the file `islands/BuyNowButton.tsx`.
@@ -87,11 +87,7 @@ export default function Page() {
}
```
Before trying this out, one must run `fresh manifest` again to update the
`fresh.gen.ts` file with the new island component. Just like routes, island
components need to be registered in the manifest file. This means that
`fresh manifest` needs to be run every time a new island component is added,
removed, or renamed.
The page that is rendered on the client now has an interactive countdown.
[islands-architecture]: https://jasonformat.com/islands-architecture
[pascal-case]: https://en.wiktionary.org/wiki/Pascal_case
+18 -14
View File
@@ -1,30 +1,34 @@
---
description: |
Create a new fresh project by running `fresh init`. This scaffolds out the
various files and folders a fresh project needs.
Create a new fresh project by running the fresh project creation tool. This
scaffolds out the various files and folders a fresh project needs.
---
New `fresh` projects can be created with the `fresh` CLI tool. It will scaffold
out a new project with some example files to get you started.
New Fresh projects can be created with using the fresh project creation tool. It
will scaffold out a new project with some example files to get you started.
To create a new project in the directory `"my-project"`, run:
```
$ fresh init my-project
Manifest generated and written to ./my-project/fresh.gen.ts
$ deno run -A --no-check https://raw.githubusercontent.com/lucacasonato/fresh/main/init.ts my-project
The manifest has been generated for 3 routes and 1 islands.
Project created!
Run `deno task start` in the project directory to get started.
```
This will create a directory containing some files and directories. There are 3
This will create a directory containing some files and directories. There are 4
files that are strictly necessary to run a fresh project:
- **`main.ts`**: This is the entrypoint for your project. It is the file that
will you run to start your fresh application. This file doesn't actually need
to be called `main.ts`, but it's best practice to call the entrypoint
`main.ts`.
- **`dev.ts`**: This is the development entrypoint for your project. This is the
file that you run to start your project. This file doesn't need to be called
`dev.ts`, but this is the convention.
- **`main.ts`**: This is the production entrypoint for your project. It is the
file that you link to Deno Deploy. This file doesn't actually need to be
`main.ts`, but this is the convention.
- **`fresh.gen.ts`**: This is the manifest file that contains information about
your routes and islands. This file is automatically generated based on your
`routes/` and `islands/` folder by the `fresh` CLI when running the
`fresh manifest` command.
your routes and islands. This file is automatically generated in development
based on your `routes/` and `islands/` folders.
- **`import_map.json`**: This is an [import map][import-map] that is used to
manage dependencies for the project. This allows for easy importing and
updating of dependencies.
+2 -19
View File
@@ -30,7 +30,7 @@ declare a component that should be rendered every time a user visits the page.
This is done with JSX.
> ℹ️ To learn more about JSX, you can read [this article][jsx] in the React
> documentation. Beware that `fresh` does not use React, but rather
> documentation. Beware that Fresh does not use React, but rather
> [Preact][preact], a lighter weight virtual dom library that works similar to
> React.
@@ -54,24 +54,7 @@ export default function AboutPage() {
> element function. These are just boilerplate. You don't need to know exactly
> what they do - they just ensure that JSX get's rendered correctly.
This alone is not yet enough to actually view the page in the browser though. If
one tries to visit `http://localhost:8000/about`, the server will return a 404
code.
Before `fresh` can render the page, the `fresh.gen.ts` manifest needs to be
updated to reflect this new route. To do this, one can run the `fresh manifest`
command:
```
$ fresh manifest
Manifest generated and written to ./my-project/fresh.gen.ts
```
> ℹ️ Updating the manifest needs to be done every time you add, remove, or
> rename a page. It does not need to be done if just the contents of a page are
> edited.
Now the page will be visible at `http://localhost:8000/about`.
The new page will be visible at `http://localhost:8000/about`.
<!-- You can find more in depth information about routes on the
[_Concepts: Routes_][concepts-routes] documentation page page. The following
-2
View File
@@ -44,8 +44,6 @@ The `PageProps` interface actually contains a bunch of useful properties that
can be used to customize the rendered output. Next to the matched url pattern
parameters, the raw `url`, and the `route` name can also be found in here.
As this is a new page, the manifest needs to be updated again: `fresh manifest`.
Navigating to `https://localhost:8000/greet/Luca` will now render a page showing
"Greetings to you, Luca!".
+4 -4
View File
@@ -11,9 +11,9 @@ for interactivity, but it is much worse for resiliency and user experience as a
whole. Browsers have great built in systems for form submission, revolving
around the HTML `<form>` element.
`fresh` builds the core of it's form submission infrastructure around the native
`<form>` element. This page explains how to use `<form>` in `fresh`, and the
next chapter explains how to progressively enhance your forms with client side
Fresh builds the core of it's form submission infrastructure around the native
`<form>` element. This page explains how to use `<form>` in Fresh, and the next
chapter explains how to progressively enhance your forms with client side
JavaScript to make them more interactive.
The way forms work in the browser, is that they perform a HTML navigation action
@@ -21,7 +21,7 @@ when the user submits the form. In most cases this means that when the form is
submitted, a GET or POST request is sent to the server with the form data, which
then responds with a new page to render.
`fresh` can handle both GET and POST requests through the
Fresh can handle both GET and POST requests through the
[custom handlers][custom-handlers] feature of routes. The handlers can perform
any necessary processing on the form data, and then pass data to the
`ctx.render()` call to render a new page.
+3 -3
View File
@@ -1,16 +1,16 @@
---
description: |
In this chapter of the `fresh` documentation, you'll be introduced to the
In this chapter of the Fresh documentation, you'll be introduced to the
framework. Create a new project, run it locally, edit and create pages, fetch
data, handle user interactions, and deploy it.
---
In this chapter of the `fresh` documentation, you'll be introduced to the
In this chapter of the Fresh documentation, you'll be introduced to the
framework. You'll learn how to create a new project, run it locally, edit and
create pages, fetch data, handle user interactions, and how to then deploy the
project to [Deno Deploy][deno-deploy].
The documentation assumes you have Deno 1.12.0 or later installed.
The documentation assumes you have Deno 1.22.3 or later installed.
To install Deno, follow the
[installation instructions in the Deno manual][manual-installation].
-40
View File
@@ -1,40 +0,0 @@
---
description: |
Install the `fresh` CLI tool to scaffold new projects and generate the fresh
manifest. The CLI tool can be installed with `deno install`.
---
`fresh` comes with a CLI tool, conveniently also called `fresh`. It is used to
scaffold new projects and generate the fresh manifest (more on that later). This
tool is only needed to create a new project, or to re-generate the fresh
manifest after you have added, removed, or renamed a pages or islands in an
existing project.
The CLI tool is not required for most development or in CI, as `fresh` does not
have a build step. This means that if you are only doing some light editing on
an existing project, you do not need to install or use the `fresh` CLI.
To install the `fresh` CLI:
```
deno install -A -f --no-check -n fresh -r https://raw.githubusercontent.com/lucacasonato/fresh/main/cli.ts
```
The tool should now be available as `fresh` in your terminal. To try out if
installation was successful you can just run `fresh` without any arguments:
```
$ fresh
fresh 0.1.0
The next-gen web framework.
To initalize a new project:
fresh init ./myproject
To (re-)generate the manifest file:
fresh manifest
SUBCOMMANDS:
init Initalize a fresh project
manifest (Re-)generate the manifest file
```
+10 -10
View File
@@ -1,30 +1,30 @@
---
description: |
`fresh` is a full stack modern web framework for JavaScript and TypeScript
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers, designed to make it trivial to create high-quality, performant,
and personalized web applications.
---
`fresh` is a full stack modern web framework for JavaScript and TypeScript
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers, designed to make it trivial to create high-quality, performant, and
personalized web applications. You can use it to create your home page, a blog,
a large web application like GitHub or Twitter, or anything else you can think
of.
At its core, `fresh` is a combination of a routing framework and templating
engine that renders pages on demand, on the server. In addition to this
just-in-time (JIT) rendering on the server, `fresh` also provides an interface
for seamlessly rendering some components on the client for maximum
interactivity. The framework uses [Preact][preact] and JSX for rendering and
templating on both the server and the client.
At its core, Fresh is a combination of a routing framework and templating engine
that renders pages on demand, on the server. In addition to this just-in-time
(JIT) rendering on the server, Fresh also provides an interface for seamlessly
rendering some components on the client for maximum interactivity. The framework
uses [Preact][preact] and JSX for rendering and templating on both the server
and the client.
`fresh` also does not have a build step. The code you write is also directly the
Fresh also does not have a build step. The code you write is also directly the
code that is run on the server, and the code that is executed on the client. Any
necessary transpilation of TypeScript or JSX to plain JavaScript is done on the
fly, just when it is needed. This allows for insanely fast iteration loops, and
very very fast deployments.
`fresh` projects can be deployed manually to any platform with `deno`, but it is
Fresh projects can be deployed manually to any platform with `deno`, but it is
intended to be deployed to an edge runtime like [Deno Deploy][deno-deploy] for
the best experience.
-24
View File
@@ -1,24 +0,0 @@
# Project strcture
Initalizing a fresh project will generate multiple files. For now the most
important files are `main.ts`, `fresh.gen.ts`, the route modules in the `routes`
subdirectory, and the islands in the `islands` subdirectory.
The `main.ts` file is the entrypoint to your project. It is the file you link in
Deno Deploy, or run locally with the `deno` CLI.
The `fresh.gen.ts` file is a manifest of all routes and islands in a project.
When moving around or creating new pages or islands, this file needs to be
updated. This is done automatically when you run the `fresh manifest` command.
You never have to edit this file manually.
The files in the `routes` subfolder describe the HTML pages and API endpoints of
your application. All routes can act as both API endpoints and dynamic HTML
pages. More info about how the `routes` subdirectory works can be found on the
[file system routing](./file-system-routing.md) page.
Finally there is a `deps.client.ts` and `deps.server.ts`. These files are the
central location for all external imports. The `deps.client.ts` file is used for
runtime dependencies (ones that are used both in routes and islands), and the
`deps.server.ts` file is used for server only dependencies (for example ones
used in API routes or middleware).
-1
View File
@@ -5,7 +5,6 @@
"getting-started": {
"title": "Getting Started",
"pages": [
["installation", "Installation"],
["create-a-project", "Create a project"],
["running-locally", "Running locally"],
["create-a-route", "Create a route"],
+1 -6
View File
@@ -8,9 +8,4 @@ Start the project:
deno task start
```
After adding, removing, or moving a page in the `routes` or directory, or
adding, removing, or moving an island in the `islands` directory, run:
```
fresh manifest
```
This will watch the project directory and restart as necessary.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"tasks": {
"start": "deno run -A --watch main.ts & deno run -A ../../cli.ts manifest --watch"
"start": "deno run -A --watch=static/,routes/,islands/ dev.ts"
},
"importMap": "./import_map.json"
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/,islands/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+2 -2
View File
@@ -1,6 +1,6 @@
// DO NOT EDIT. This file is generated by `fresh`.
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh manifest`.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/index.tsx";
import * as $$0 from "./islands/Counter.tsx";
+1 -1
View File
@@ -6,7 +6,7 @@ export default function Home() {
return (
<div>
<p>
Welcome to `fresh`. Try update this message in the ./routes/index.tsx
Welcome to Fresh. Try update this message in the ./routes/index.tsx
file, and refresh.
</p>
<Counter start={3} />
+221
View File
@@ -0,0 +1,221 @@
import { join, resolve } from "./src/dev/deps.ts";
import { error } from "./src/dev/error.ts";
import { collect, generate } from "./src/dev/mod.ts";
const help = `fresh-init
Initialize a new Fresh project. This will create all the necessary files for a
new project.
To generate a project in the './foobar' subdirectory:
fresh-init ./foobar
To generate a project in the current directory:
fresh-init .
USAGE:
fresh-init <DIRECTORY>
`;
const CONFIRM_EMPTY_MESSAGE =
"The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
if (Deno.args.length !== 1) {
error(help);
}
let directory = Deno.args[0];
directory = resolve(directory);
try {
const dir = [...Deno.readDirSync(directory)];
const isEmpty = dir.length === 0 ||
dir.length === 1 && dir[0].name === ".git";
if (!isEmpty && !confirm(CONFIRM_EMPTY_MESSAGE)) {
error("Directory is not empty.");
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
await Deno.mkdir(join(directory, "routes", "api"), { recursive: true });
await Deno.mkdir(join(directory, "islands"), { recursive: true });
await Deno.mkdir(join(directory, "static"), { recursive: true });
const IMPORT_MAP_JSON = JSON.stringify(
{
"imports": {
"$fresh/": new URL("./", import.meta.url).href,
},
},
null,
2,
);
await Deno.writeTextFile(join(directory, "import_map.json"), IMPORT_MAP_JSON);
const ROUTES_INDEX_TSX = `/** @jsx h */
import { h } from "$fresh/runtime.ts";
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div>
<img src="/logo.svg" height="100px" alt="the fresh logo: a sliced lemon dripping with juice" />
<p>
Welcome to \`fresh\`. Try update this message in the ./routes/index.tsx
file, and refresh.
</p>
<Counter start={3} />
</div>
);
}
`;
await Deno.writeTextFile(
join(directory, "routes", "index.tsx"),
ROUTES_INDEX_TSX,
);
const ISLANDS_COUNTER_TSX = `/** @jsx h */
import { h, IS_BROWSER, useState } from "$fresh/runtime.ts";
interface CounterProps {
start: number;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
-1
</button>
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
+1
</button>
</div>
);
}
`;
await Deno.writeTextFile(
join(directory, "islands", "Counter.tsx"),
ISLANDS_COUNTER_TSX,
);
const ROUTES_GREET_TSX = `/** @jsx h */
import { h, PageProps } from "$fresh/runtime.ts";
export default function Greet(props: PageProps) {
return <div>Hello {props.params.name}</div>;
}
`;
await Deno.writeTextFile(
join(directory, "routes", "[name].tsx"),
ROUTES_GREET_TSX,
);
const ROUTES_API_JOKE_TS = `import { HandlerContext } from "$fresh/server.ts";
// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/
const JOKES = [
"Why do Java developers often wear glasses? They can't C#.",
"A SQL query walks into a bar, goes up to two tables and says “can I join you?”",
"Wasn't hard to crack Forrest Gump's password. 1forrest1.",
"I love pressing the F5 key. It's refreshing.",
"Called IT support and a chap from Australia came to fix my network connection. I asked “Do you come from a LAN down under?”",
"There are 10 types of people in the world. Those who understand binary and those who don't.",
"Why are assembly programmers often wet? They work below C level.",
"My favourite computer based band is the Black IPs.",
"What programme do you use to predict the music tastes of former US presidential candidates? An Al Gore Rhythm.",
"An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.",
];
export const handler = (_req: Request, _ctx: HandlerContext): Response => {
const randomIndex = Math.floor(Math.random() * 10);
const body = JOKES[randomIndex];
return new Response(body);
};
`;
await Deno.writeTextFile(
join(directory, "routes", "api", "joke.ts"),
ROUTES_API_JOKE_TS,
);
const STATIC_LOGO =
`<svg width="40" height="40" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M34.092 8.845C38.929 20.652 34.092 27 30 30.5c1 3.5-2.986 4.222-4.5 2.5-4.457 1.537-13.512 1.487-20-5C2 24.5 4.73 16.714 14 11.5c8-4.5 16-7 20.092-2.655Z" fill="#FFDB1E"/>
<path d="M14 11.5c6.848-4.497 15.025-6.38 18.368-3.47C37.5 12.5 21.5 22.612 15.5 25c-6.5 2.587-3 8.5-6.5 8.5-3 0-2.5-4-5.183-7.75C2.232 23.535 6.16 16.648 14 11.5Z" fill="#fff" stroke="#FFDB1E"/>
<path d="M28.535 8.772c4.645 1.25-.365 5.695-4.303 8.536-3.732 2.692-6.606 4.21-7.923 4.83-.366.173-1.617-2.252-1.617-1 0 .417-.7 2.238-.934 2.326-1.365.512-4.223 1.29-5.835 1.29-3.491 0-1.923-4.754 3.014-9.122.892-.789 1.478-.645 2.283-.645-.537-.773-.534-.917.403-1.546C17.79 10.64 23 8.77 25.212 8.42c.366.014.82.35.82.629.41-.14 2.095-.388 2.503-.278Z" fill="#FFE600"/>
<path d="M14.297 16.49c.985-.747 1.644-1.01 2.099-2.526.566.121.841-.08 1.29-.701.324.466 1.657.608 2.453.701-.715.451-1.057.852-1.452 2.106-1.464-.611-3.167-.302-4.39.42Z" fill="#fff"/>
</svg>`;
await Deno.writeTextFile(
join(directory, "static", "logo.svg"),
STATIC_LOGO,
);
const MAIN_TS = `/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
`;
const MAIN_TS_PATH = join(directory, "main.ts");
await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS);
const DEV_TS = `#!/usr/bin/env -S deno run -A --watch=static/,routes/,islands/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
`;
const DEV_TS_PATH = join(directory, "dev.ts");
await Deno.writeTextFile(DEV_TS_PATH, DEV_TS);
try {
await Deno.chmod(DEV_TS_PATH, 0o777);
} catch {
// this throws on windows
}
const DENO_CONFIG = JSON.stringify(
{
tasks: {
start: "deno run -A --watch=static/,routes/,islands/ --no-check dev.ts",
},
importMap: "./import_map.json",
},
null,
2,
);
await Deno.writeTextFile(join(directory, "deno.json"), DENO_CONFIG);
const README_MD = `# fresh project
### Usage
Start the project:
\`\`\`
deno task start
\`\`\`
This will watch the project directory and restart as necessary.
`;
await Deno.writeTextFile(
join(directory, "README.md"),
README_MD,
);
const manifest = await collect(directory);
await generate(directory, manifest);
console.log("\n%cProject created!", "color: green; font-weight: bold");
console.log("Run \`deno task start\` in the project directory to get started.");
-15
View File
@@ -1,15 +0,0 @@
// std
export {
extname,
join,
resolve,
toFileUrl,
} from "https://deno.land/std@0.128.0/path/mod.ts";
export { walk } from "https://deno.land/std@0.128.0/fs/walk.ts";
export { parse as parseArgs } from "https://deno.land/std@0.128.0/flags/mod.ts";
export {
bold,
green,
red,
yellow,
} from "https://deno.land/std@0.128.0/fmt/colors.ts";
-239
View File
@@ -1,239 +0,0 @@
import { join, resolve } from "./deps.ts";
import { error } from "./error.ts";
import { manifest } from "./manifest.ts";
const help = `fresh init
Initialize a new \`fresh\` project. This will create all the necessary files for
a new project.
To generate a project in the './foobar' subdirectory:
fresh init ./foobar
To generate a project in the current directory:
fresh init .
USAGE:
fresh init [OPTIONS] <DIRECTORY>
OPTIONS:
-h, --help Prints help information
`;
const CONFIRM_EMPTY_MESSAGE =
"The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
export interface Args {
help: boolean;
}
// deno-lint-ignore no-explicit-any
export async function initSubcommand(rawArgs: Record<string, any>) {
const args: Args = {
help: !!rawArgs.help,
};
const directory: string | null = typeof rawArgs._[0] === "string"
? rawArgs._[0]
: null;
if (args.help) {
console.log(help);
Deno.exit(0);
}
if (directory === null) {
console.error(help);
error("No directory given.");
}
await init(directory);
}
async function init(directory: string) {
directory = resolve(directory);
try {
const dir = [...Deno.readDirSync(directory)];
const isEmpty = dir.length === 0 ||
dir.length === 1 && dir[0].name === ".git";
if (!isEmpty && !confirm(CONFIRM_EMPTY_MESSAGE)) {
error("Directory is not empty.");
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
await Deno.mkdir(join(directory, "routes", "api"), { recursive: true });
await Deno.mkdir(join(directory, "islands"), { recursive: true });
await Deno.mkdir(join(directory, "static"), { recursive: true });
const IMPORT_MAP_JSON = JSON.stringify(
{
"imports": {
"$fresh/": new URL("../../", import.meta.url).href,
},
},
null,
2,
);
await Deno.writeTextFile(join(directory, "import_map.json"), IMPORT_MAP_JSON);
const ROUTES_INDEX_TSX = `/** @jsx h */
import { h } from "$fresh/runtime.ts";
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div>
<img src="/logo.svg" height="100px" alt="the fresh logo: a sliced lemon dripping with juice" />
<p>
Welcome to \`fresh\`. Try update this message in the ./routes/index.tsx
file, and refresh.
</p>
<Counter start={3} />
</div>
);
}
`;
await Deno.writeTextFile(
join(directory, "routes", "index.tsx"),
ROUTES_INDEX_TSX,
);
const ISLANDS_COUNTER_TSX = `/** @jsx h */
import { h, IS_BROWSER, useState } from "$fresh/runtime.ts";
interface CounterProps {
start: number;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
-1
</button>
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
+1
</button>
</div>
);
}
`;
await Deno.writeTextFile(
join(directory, "islands", "Counter.tsx"),
ISLANDS_COUNTER_TSX,
);
const ROUTES_GREET_TSX = `/** @jsx h */
import { h, PageProps } from "$fresh/runtime.ts";
export default function Greet(props: PageProps) {
return <div>Hello {props.params.name}</div>;
}
`;
await Deno.writeTextFile(
join(directory, "routes", "[name].tsx"),
ROUTES_GREET_TSX,
);
const ROUTES_API_JOKE_TS = `import { HandlerContext } from "$fresh/server.ts";
// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/
const JOKES = [
"Why do Java developers often wear glasses? They can’t C#.",
"A SQL query walks into a bar, goes up to two tables and says “can I join you?“",
"Wasn’t hard to crack Forrest Gump’s password. 1forrest1.",
"I love pressing the F5 key. It’s refreshing.",
"Called IT support and a chap from Australia came to fix my network connection. I asked “Do you come from a LAN down under?”",
"There are 10 types of people in the world. Those who understand binary and those who don’t.",
"Why are assembly programmers often wet? They work below C level.",
"My favourite computer based band is the Black IPs.",
"What programme do you use to predict the music tastes of former US presidential candidates? An Al Gore Rhythm.",
"An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.",
];
export const handler = (_req: Request, _ctx: HandlerContext): Response => {
const randomIndex = Math.floor(Math.random() * 10);
const body = JOKES[randomIndex];
return new Response(body);
};
`;
await Deno.writeTextFile(
join(directory, "routes", "api", "joke.ts"),
ROUTES_API_JOKE_TS,
);
const STATIC_LOGO =
`<svg width="40" height="40" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M34.092 8.845C38.929 20.652 34.092 27 30 30.5c1 3.5-2.986 4.222-4.5 2.5-4.457 1.537-13.512 1.487-20-5C2 24.5 4.73 16.714 14 11.5c8-4.5 16-7 20.092-2.655Z" fill="#FFDB1E"/>
<path d="M14 11.5c6.848-4.497 15.025-6.38 18.368-3.47C37.5 12.5 21.5 22.612 15.5 25c-6.5 2.587-3 8.5-6.5 8.5-3 0-2.5-4-5.183-7.75C2.232 23.535 6.16 16.648 14 11.5Z" fill="#fff" stroke="#FFDB1E"/>
<path d="M28.535 8.772c4.645 1.25-.365 5.695-4.303 8.536-3.732 2.692-6.606 4.21-7.923 4.83-.366.173-1.617-2.252-1.617-1 0 .417-.7 2.238-.934 2.326-1.365.512-4.223 1.29-5.835 1.29-3.491 0-1.923-4.754 3.014-9.122.892-.789 1.478-.645 2.283-.645-.537-.773-.534-.917.403-1.546C17.79 10.64 23 8.77 25.212 8.42c.366.014.82.35.82.629.41-.14 2.095-.388 2.503-.278Z" fill="#FFE600"/>
<path d="M14.297 16.49c.985-.747 1.644-1.01 2.099-2.526.566.121.841-.08 1.29-.701.324.466 1.657.608 2.453.701-.715.451-1.057.852-1.452 2.106-1.464-.611-3.167-.302-4.39.42Z" fill="#fff"/>
</svg>`;
await Deno.writeTextFile(
join(directory, "static", "logo.svg"),
STATIC_LOGO,
);
const MAIN_TS =
`#!/usr/bin/env -S deno run --allow-read --allow-net --allow-env --allow-run --allow-hrtime --no-check --watch
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
`;
const MAIN_TS_PATH = join(directory, "main.ts");
await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS);
try {
await Deno.chmod(MAIN_TS_PATH, 0o777);
} catch {
// this throws on windows
}
const DENO_CONFIG = JSON.stringify(
{
tasks: {
start: "deno run -A --watch --no-check main.ts",
},
importMap: "./import_map.json",
},
null,
2,
);
await Deno.writeTextFile(join(directory, "deno.json"), DENO_CONFIG);
const README_MD = `# fresh project
### Usage
Start the project:
\`\`\`
deno task start
\`\`\`
After adding, removing, or moving a page in the \`routes\` or directory, or adding,
removing, or moving an island in the \`islands\` directory, run:
\`\`\`
fresh manifest
\`\`\`
`;
await Deno.writeTextFile(
join(directory, "README.md"),
README_MD,
);
await manifest(directory, false);
}
+11
View File
@@ -0,0 +1,11 @@
// std
export {
dirname,
extname,
fromFileUrl,
join,
resolve,
toFileUrl,
} from "https://deno.land/std@0.128.0/path/mod.ts";
export { walk } from "https://deno.land/std@0.128.0/fs/walk.ts";
export { bold, red } from "https://deno.land/std@0.128.0/fmt/colors.ts";
+29 -59
View File
@@ -1,45 +1,13 @@
import { extname, join, resolve, toFileUrl, walk } from "./deps.ts";
import {
dirname,
extname,
fromFileUrl,
join,
toFileUrl,
walk,
} from "./deps.ts";
import { error } from "./error.ts";
const help = `fresh manifest
Regenerate the fresh.gen.ts manifest for your fresh project.
To regenerate the mapping in the current directory:
fresh manifest
To regenerate the mapping in the './foobar' subdirectory:
fresh manifest ./foobar
USAGE:
fresh manifest [OPTIONS] [DIRECTORY]
OPTIONS:
-h, --help Prints help information
-w, --watch Watch for changes and regenerate as needed
`;
export interface Args {
help: boolean;
watch: boolean;
}
// deno-lint-ignore no-explicit-any
export async function manifestSubcommand(rawArgs: Record<string, any>) {
const args: Args = {
help: !!rawArgs.help,
watch: !!rawArgs.watch,
};
const directory: string | null = typeof rawArgs._[0] === "string"
? rawArgs._[0]
: Deno.cwd();
if (args.help) {
console.log(help);
Deno.exit(0);
}
await manifest(directory, args.watch);
}
interface Manifest {
routes: string[];
islands: string[];
@@ -111,9 +79,9 @@ export async function collect(directory: string): Promise<Manifest> {
export async function generate(directory: string, manifest: Manifest) {
const { routes, islands } = manifest;
const output = `// DO NOT EDIT. This file is generated by \`fresh\`.
const output = `// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// To update this file, run \`fresh manifest\`.
// This file is automatically updated during development when running \`dev.ts\`.
${
routes.map((file, i) => `import * as $${i} from "./routes${file}";`).join(
@@ -171,26 +139,28 @@ export default manifest;
);
}
export async function manifest(directory: string, watch: boolean) {
directory = resolve(directory);
export async function dev(base: string, entrypoint: string) {
entrypoint = new URL(entrypoint, base).href;
let currentManifest = await collect(directory);
await generate(directory, currentManifest);
const dir = dirname(fromFileUrl(base));
if (!watch) return;
const watcher = Deno.watchFs(directory, { recursive: true });
for await (const e of watcher) {
if (e.kind === "access") continue;
const newManifest = await collect(directory);
if (
!arraysEqual(newManifest.routes, currentManifest.routes) ||
!arraysEqual(newManifest.islands, currentManifest.islands)
) {
currentManifest = newManifest;
await generate(directory, currentManifest);
}
let currentManifest: Manifest;
const prevManifest = Deno.env.get("FRSH_DEV_PREVIOUS_MANIFEST");
if (prevManifest) {
currentManifest = JSON.parse(prevManifest);
} else {
currentManifest = { islands: [], routes: [] };
}
const newManifest = await collect(dir);
Deno.env.set("FRSH_DEV_PREVIOUS_MANIFEST", JSON.stringify(newManifest));
const manifestChanged =
!arraysEqual(newManifest.routes, currentManifest.routes) ||
!arraysEqual(newManifest.islands, currentManifest.islands);
if (manifestChanged) await generate(dir, newManifest);
await import(entrypoint);
}
function arraysEqual<T>(a: T[], b: T[]): boolean {
+2 -2
View File
@@ -39,14 +39,14 @@ const assertFileExistence = async (tree: FileTree[], dirname?: string) => {
};
Deno.test({
name: "fresh init",
name: "fresh-init",
async fn(t) {
// Preparation
const tmpDirName = await Deno.makeTempDir();
await t.step("execute init command", async () => {
const cliProcess = Deno.run({
cmd: ["deno", "run", "-A", "--no-check", "cli.ts", "init", tmpDirName],
cmd: ["deno", "run", "-A", "--no-check", "init.ts", tmpDirName],
stdout: "null",
});
const { code } = await cliProcess.status();
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/,islands/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+2 -2
View File
@@ -1,6 +1,6 @@
// DO NOT EDIT. This file is generated by `fresh`.
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh manifest`.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/[name].tsx";
import * as $1 from "./routes/_404.tsx";
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/,islands/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+2 -2
View File
@@ -1,6 +1,6 @@
// DO NOT EDIT. This file is generated by `fresh`.
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh manifest`.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/index.tsx";
import * as $1 from "./routes/[...all].ts";
+1 -5
View File
@@ -13,8 +13,4 @@ Start the project:
deno run -A --watch main.ts
```
After adding, removing, or moving a page in the `pages` directory, run:
```
fresh manifest
```
This will watch the project directory and restart as necessary.
+4 -4
View File
@@ -7,10 +7,10 @@ export default function WarningBanner() {
const warning = tw`bg-yellow-100 border(1 yellow-200) p-4 mb-4`;
return (
<div class={warning}>
⚠️ Do not use `fresh` for production usecases yet, unless you are very
actively tracking the `fresh` repository for updates. The framework is
still undergoing very frequent core functionality changes. You can expect
a mostly stable release very soon.
⚠️ Do not use Fresh for production usecases yet, unless you are very
actively tracking the Fresh repository for updates. The framework is still
undergoing very frequent core functionality changes. You can expect a
mostly stable release very soon.
</div>
);
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"tasks": {
"start": "deno run -A --watch main.ts & deno run -A ../cli.ts manifest --watch"
"start": "deno run -A --watch=static/,routes/,islands/ dev.ts"
},
"importMap": "./import_map.json"
}
Executable
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/,islands/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+2 -2
View File
@@ -1,6 +1,6 @@
// DO NOT EDIT. This file is generated by `fresh`.
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh manifest`.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/_render.ts";
import * as $1 from "./routes/docs/[...slug].tsx";
+3 -11
View File
@@ -160,21 +160,13 @@ function GettingStarted() {
<a href="https://deno.land" class={tw`text-blue-600 hover:underline`}>
Deno CLI
</a>{" "}
installed.
version 1.23.0 or higher installed.
</p>
<p class={tw`text-gray-600`}>
Then, run the following command to install the `fresh` CLI:
Then you can use the Fresh init script to bootstrap a new project:
</p>
<pre class={tw`overflow-x-auto py-2 px-4 bg(gray-100)`}>
deno install -A -f --no-check -n fresh -r
https://raw.githubusercontent.com/lucacasonato/fresh/main/cli.ts
</pre>
<p class={tw`text-gray-600`}>
Once installed, you can use the `fresh` command to bootstrap a new
project:
</p>
<pre class={tw`overflow-x-auto py-2 px-4 bg(gray-100)`}>
fresh init my-app
{"deno run -A --no-check https://raw.githubusercontent.com/lucacasonato/fresh/main/init.ts my-app"}
</pre>
<p class={tw`text-gray-600`}>
Enter the newly created project directory and run the following command