feat(init): template based init script (#3524)

Supersedes earlier attempt ->
https://github.com/denoland/fresh/pull/3517

This is now ready for review.

The major upside and motivation for this template based approach is that
it is now possible to view what gets generated in the repository as
actual valid files including syntax highlighting and formatting.

Previously those files where just strings inside the old `init` script,
which is IMHO a nightmare for maintainability.

The approach for this template system is loosely based on Vite's
`create-vite`, which also includes (redundant) templates inside the
repository, see here ->
https://github.com/vitejs/vite/tree/main/packages/create-vite

Included in the tests are compatibility checks against the current
`@fresh/init@2.0.9`, those can get removed at a later point when the
templates start to diverge. They are only included for demonstration
purposes, that this new implementation generates 100% identical output.

This means that the first PR after this got included, which modifies the
templates so the output differs from the old `init` script, also needs
to include:
```shell
rm packages/init/tests/compatibility_test.ts
```

Since this is a rather large PR, it may be more approachable to view the
branch directly ->
https://github.com/fry69/fresh/tree/fry69/refactor-init-template-rename/packages/init

Generated PR message below:

---

Replaces inline string-based project generation with file-based
templates for improved maintainability and extensibility.

### Architecture

**Template structure:**
- `assets/template/` - Complete project templates (vite, vite-tailwind,
builder, builder-tailwind)
- `assets/variants/` - Additive overlays (docker, vscode,
vscode-tailwind)
- `assets/base/` - Common files synced across template variants

Templates use `__VARIABLE__` syntax for substitution (project name,
dependency versions). Files with `__` prefix are renamed to `.` prefix
during generation (e.g., `__gitignore` → .gitignore).

**Template selection logic:**
```
Base: vite|vite-tailwind|builder|builder-tailwind
Variants: +docker, +vscode, +vscode-tailwind
```

### Maintenance workflow

Edit shared files in `assets/base/vite/` or `assets/base/builder/`, then
run `deno task sync` to propagate changes to template variants.
Template-specific files (deno.json, vite.config.ts, styles.css) are
never overwritten.

### Version resolution

Matches existing behavior: only Fresh core version is fetched from JSR,
all other dependencies use fixed versions updated by release scripts.

### Testing

55 tests covering:
- Unit tests for core functionality
- Integration tests (project generation, builds, dev servers)
- CLI argument parsing
- Compatibility tests verifying output matches v2.0.9 (pre-refactor
baseline)
- Template sync workflow

### Breaking changes

None. CLI interface and programmatic API remain identical. Package
publishes to same `@fresh/init` scope at JSR.

### Documentation

- README.md - User-facing usage documentation
- DESIGN.md - Maintainer documentation (architecture, template
maintenance, development setup)
This commit is contained in:
fry69
2025-10-06 09:12:07 +02:00
committed by GitHub
parent 317f1cb95f
commit 198816b042
98 changed files with 4615 additions and 1236 deletions
Generated
+12
View File
@@ -19,6 +19,7 @@
"jsr:@std/async@^1.0.13": "1.0.14",
"jsr:@std/bytes@^1.0.5": "1.0.6",
"jsr:@std/bytes@^1.0.6": "1.0.6",
"jsr:@std/cli@1": "1.0.22",
"jsr:@std/cli@^1.0.19": "1.0.22",
"jsr:@std/cli@^1.0.21": "1.0.22",
"jsr:@std/collections@^1.1.2": "1.1.3",
@@ -29,6 +30,7 @@
"jsr:@std/encoding@1": "1.0.10",
"jsr:@std/encoding@^1.0.10": "1.0.10",
"jsr:@std/expect@^1.0.16": "1.0.17",
"jsr:@std/fmt@1": "1.0.8",
"jsr:@std/fmt@1.0.3": "1.0.3",
"jsr:@std/fmt@^1.0.3": "1.0.8",
"jsr:@std/fmt@^1.0.7": "1.0.8",
@@ -3752,6 +3754,16 @@
"npm:@types/node@^24.2.1"
]
},
"packages/init": {
"dependencies": [
"jsr:@std/cli@1",
"jsr:@std/fmt@1",
"jsr:@std/fs@1",
"jsr:@std/jsonc@1",
"jsr:@std/path@1",
"jsr:@std/semver@1"
]
},
"packages/plugin-tailwindcss-v3": {
"dependencies": [
"npm:autoprefixer@^10.4.21",
+135
View File
@@ -0,0 +1,135 @@
# Architecture & Maintenance
Maintainer documentation for `@fresh/init`.
## Design Philosophy
Templates are **complete, standalone projects**. The system selects one base
template and optionally applies variant overlays on top.
## Directory Structure
```
packages/init/
├── src/
│ ├── mod.ts # CLI entry point (package default export)
│ ├── init.ts # Core initialization logic
│ ├── types.ts # Type definitions
│ ├── utils.ts # File operations, version resolution
│ └── sync.ts # Template synchronization tool
├── assets/
│ ├── base/ # Common files (edit here!)
│ │ ├── vite/ # Shared between vite templates
│ │ └── builder/ # Shared between builder templates
│ ├── template/ # Complete project templates
│ │ ├── vite/
│ │ ├── vite-tailwind/
│ │ ├── builder/
│ │ └── builder-tailwind/
│ └── variants/ # Additive overlays
│ ├── docker/
│ ├── vscode/
│ └── vscode-tailwind/
├── tests/ # Test suite
├── deno.json # Package configuration
├── README.md # User documentation
└── DESIGN.md # This file
```
## Template Maintenance
Common files are stored in `assets/base/` and synced to template variants.
### Editing Common Files
1. Edit files in `assets/base/vite/` or `assets/base/builder/`
2. Run `deno task sync` to propagate changes
3. Template-specific files are preserved:
- `deno.json` - Different dependencies per variant
- `vite.config.ts` - Tailwind plugin configuration
- `assets/styles.css` / `static/styles.css` - Tailwind imports
### Sync Commands
```bash
deno task sync # Apply changes
deno task sync --dry-run # Preview without applying
```
The sync script (`src/sync.ts`) copies:
- `assets/base/vite/` → `vite/` and `vite-tailwind/`
- `assets/base/builder/` → `builder/` and `builder-tailwind/`
## File Processing
### Naming Convention
- `__filename` → `.filename` (e.g., `__gitignore` → `.gitignore`)
### Variable Substitution
Template files use `__VARIABLE__` syntax for text replacement:
**Project Variables:**
- `__PROJECT_NAME__` - Project name (from directory basename)
**Version Variables:**
- `__FRESH_VERSION__` - Fresh core version
- `__FRESH_TAILWIND_VERSION__` - Fresh Tailwind plugin version
- `__FRESH_VITE_PLUGIN_VERSION__` - Fresh Vite plugin version
- `__PREACT_VERSION__` - Preact version
- `__PREACT_SIGNALS_VERSION__` - Preact Signals version
- `__TAILWINDCSS_VERSION__` - Tailwind CSS version
- `__TAILWINDCSS_POSTCSS_VERSION__` - Tailwind CSS PostCSS version
- `__TAILWINDCSS_VITE_VERSION__` - Tailwind CSS Vite plugin version
- `__POSTCSS_VERSION__` - PostCSS version
- `__VITE_VERSION__` - Vite version
- `__DENO_VERSION__` - Deno version (current runtime)
Text files are processed for variable substitution. Binary files are copied
as-is.
**Note:** Boolean flags (tailwind, vscode, docker, builder) are used for
**template/variant selection logic**, not as substitutable variables in template
files.
## Template Selection
```typescript
// Base template
if (vite && tailwind) → "vite-tailwind"
else if (vite) → "vite"
else if (tailwind) → "builder-tailwind"
else → "builder"
// Variants (additive)
if (docker) → add "docker"
if (vscode && tailwind) → add "vscode-tailwind"
else if (vscode) → add "vscode"
```
## Version Resolution
Matches `@fresh/init` behavior:
- Fresh core: Fetched from network
- Other dependencies: Fixed versions (updated by release script)
## Development
```bash
deno task test # Run test suite (55 tests)
deno task check # Format, lint, type check
deno task sync # Sync templates
```
## Testing
- **Unit tests** - Core functionality
- **Integration tests** - Full project generation and builds
- **CLI tests** - Command-line interface
- **Compatibility tests** - Verify output matches v2.0.9 (pre-refactor baseline)
- **Sync tests** - Template synchronization
+58 -6
View File
@@ -1,10 +1,62 @@
# Create a new Fresh project.
# @fresh/init
This is a CLI tool to bootstrap a new Fresh project. To do so, run this command:
Template-based initialization system for Fresh projects.
```sh
deno run -Ar jsr:@fresh/init
## Usage
### CLI
```bash
# Interactive mode
deno run -Ar jsr:@fresh/init my-project
# With options
deno run -Ar jsr:@fresh/init my-app --tailwind --vscode --docker
```
Go to [https://fresh.deno.dev/](https://fresh.deno.dev/) for more information
about Fresh.
**Options:**
- `--force` - Overwrite existing files
- `--tailwind` - Include Tailwind CSS
- `--vscode` - Add VS Code configuration
- `--docker` - Add Docker support
- `--builder` - Use builder instead of Vite
- `--help` - Show help message
### Programmatic
```typescript
import { initProject, resolveVersions } from "jsr:@fresh/init/src/init";
const versions = await resolveVersions();
await initProject(Deno.cwd(), {
directory: "./my-fresh-app",
tailwind: true,
vscode: true,
docker: false,
builder: false,
force: false,
}, versions);
```
## Templates
**Build Systems:**
- **Vite** (default) - Modern build system with HMR
- **Builder** - Traditional Deno-based build system
**Styling:**
- **Plain CSS** (default)
- **Tailwind CSS** (`--tailwind`)
**Optional Features:**
- **VS Code** configuration (`--vscode`)
- **Docker** support (`--docker`)
## Maintainer Documentation
See [DESIGN.md](./DESIGN.md) for architecture, maintenance workflows, and
development setup.
@@ -0,0 +1,17 @@
# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "Getting
Started" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno:
https://docs.deno.com/runtime/getting_started/installation
Then start the project in development mode:
```
deno task dev
```
This will watch the project directory and restart as necessary.
@@ -0,0 +1,13 @@
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Fresh build directory
_fresh/
# npm + other dependencies
node_modules/
vendor/
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
{...props}
class="px-2 py-1 border-gray-500 border-2 rounded-sm bg-white hover:bg-gray-200 transition-colors"
/>
);
}
@@ -0,0 +1,16 @@
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button id="decrement" onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button id="increment" onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { App, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
});
// this can also be defined via a file. feel free to delete this!
const exampleLoggerMiddleware = define.middleware((ctx) => {
console.log(`${ctx.req.method} ${ctx.req.url}`);
return ctx.next();
});
app.use(exampleLoggerMiddleware);
// Include file-system based routes here
app.fsRoutes();
@@ -0,0 +1,17 @@
import { define } from "../utils.ts";
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__PROJECT_NAME__</title>
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
<Component />
</body>
</html>
);
});
@@ -0,0 +1,10 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
@@ -0,0 +1,33 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
});
@@ -0,0 +1,19 @@
<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>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,9 @@
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
}
export const define = createDefine<State>();
+17
View File
@@ -0,0 +1,17 @@
# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "Getting
Started" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno:
https://docs.deno.com/runtime/getting_started/installation
Then start the project in development mode:
```
deno task dev
```
This will watch the project directory and restart as necessary.
@@ -0,0 +1,13 @@
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Fresh build directory
_fresh/
# npm + other dependencies
node_modules/
vendor/
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
{...props}
class="px-2 py-1 border-gray-500 border-2 rounded-sm bg-white hover:bg-gray-200 transition-colors"
/>
);
}
@@ -0,0 +1,16 @@
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button id="decrement" onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button id="increment" onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { App, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
});
// this can also be defined via a file. feel free to delete this!
const exampleLoggerMiddleware = define.middleware((ctx) => {
console.log(`${ctx.req.method} ${ctx.req.url}`);
return ctx.next();
});
app.use(exampleLoggerMiddleware);
// Include file-system based routes here
app.fsRoutes();
@@ -0,0 +1,16 @@
import { define } from "../utils.ts";
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__PROJECT_NAME__</title>
</head>
<body>
<Component />
</body>
</html>
);
});
@@ -0,0 +1,10 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
@@ -0,0 +1,33 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
});
@@ -0,0 +1,19 @@
<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>

After

Width:  |  Height:  |  Size: 1.1 KiB

+9
View File
@@ -0,0 +1,9 @@
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
}
export const define = createDefine<State>();
@@ -0,0 +1,17 @@
# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "Getting
Started" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno:
https://docs.deno.com/runtime/getting_started/installation
Then start the project in development mode:
```
deno task dev
```
This will watch the project directory and restart as necessary.
@@ -0,0 +1,13 @@
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Fresh build directory
_fresh/
# npm + other dependencies
node_modules/
vendor/
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
{...props}
class="px-2 py-1 border-gray-500 border-2 rounded-sm bg-white hover:bg-gray-200 transition-colors"
/>
);
}
@@ -0,0 +1,56 @@
{
"nodeModulesDir": "auto",
"tasks": {
"check": "deno fmt --check . && deno lint . && deno check",
"dev": "deno run -A --watch=static/,routes/ dev.ts",
"build": "deno run -A dev.ts build",
"start": "deno serve -A _fresh/server.js",
"update": "deno run -A -r jsr:@fresh/update ."
},
"lint": {
"rules": {
"tags": [
"fresh",
"recommended"
]
}
},
"exclude": [
"**/_fresh/*"
],
"imports": {
"fresh": "jsr:@fresh/core@^__FRESH_VERSION__",
"preact": "npm:preact@^__PREACT_VERSION__",
"@preact/signals": "npm:@preact/signals@^__PREACT_SIGNALS_VERSION__",
"tailwindcss": "npm:tailwindcss@^__TAILWINDCSS_VERSION__",
"@fresh/plugin-tailwind": "jsr:@fresh/plugin-tailwind@^__FRESH_TAILWIND_VERSION__",
"@tailwindcss/postcss": "npm:@tailwindcss/postcss@^__TAILWINDCSS_POSTCSS_VERSION__",
"postcss": "npm:postcss@^__POSTCSS_VERSION__"
},
"compilerOptions": {
"lib": [
"dom",
"dom.asynciterable",
"dom.iterable",
"deno.ns"
],
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template"
]
}
}
@@ -0,0 +1,12 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import { tailwind } from "@fresh/plugin-tailwind";
import { Builder } from "fresh/dev";
const builder = new Builder();
tailwind(builder);
if (Deno.args.includes("build")) {
await builder.build();
} else {
await builder.listen(() => import("./main.ts"));
}
@@ -0,0 +1,16 @@
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button id="decrement" onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button id="increment" onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
@@ -0,0 +1,30 @@
import { App, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
});
// this can also be defined via a file. feel free to delete this!
const exampleLoggerMiddleware = define.middleware((ctx) => {
console.log(`${ctx.req.method} ${ctx.req.url}`);
return ctx.next();
});
app.use(exampleLoggerMiddleware);
// Include file-system based routes here
app.fsRoutes();
@@ -0,0 +1,17 @@
import { define } from "../utils.ts";
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__PROJECT_NAME__</title>
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
<Component />
</body>
</html>
);
});
@@ -0,0 +1,10 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
@@ -0,0 +1,33 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
});
@@ -0,0 +1,19 @@
<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>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,10 @@
@import "tailwindcss";
.fresh-gradient {
background-color: rgb(134, 239, 172);
background-image: linear-gradient(
to right bottom,
rgb(219, 234, 254),
rgb(187, 247, 208),
rgb(254, 249, 195)
);
}
@@ -0,0 +1,9 @@
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
}
export const define = createDefine<State>();
@@ -0,0 +1,17 @@
# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "Getting
Started" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno:
https://docs.deno.com/runtime/getting_started/installation
Then start the project in development mode:
```
deno task dev
```
This will watch the project directory and restart as necessary.
@@ -0,0 +1,13 @@
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Fresh build directory
_fresh/
# npm + other dependencies
node_modules/
vendor/
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
{...props}
class="px-2 py-1 border-gray-500 border-2 rounded-sm bg-white hover:bg-gray-200 transition-colors"
/>
);
}
@@ -0,0 +1,52 @@
{
"nodeModulesDir": "auto",
"tasks": {
"check": "deno fmt --check . && deno lint . && deno check",
"dev": "deno run -A --watch=static/,routes/ dev.ts",
"build": "deno run -A dev.ts build",
"start": "deno serve -A _fresh/server.js",
"update": "deno run -A -r jsr:@fresh/update ."
},
"lint": {
"rules": {
"tags": [
"fresh",
"recommended"
]
}
},
"exclude": [
"**/_fresh/*"
],
"imports": {
"fresh": "jsr:@fresh/core@^__FRESH_VERSION__",
"preact": "npm:preact@^__PREACT_VERSION__",
"@preact/signals": "npm:@preact/signals@^__PREACT_SIGNALS_VERSION__"
},
"compilerOptions": {
"lib": [
"dom",
"dom.asynciterable",
"dom.iterable",
"deno.ns"
],
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template"
]
}
}
@@ -0,0 +1,11 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import { Builder } from "fresh/dev";
const builder = new Builder();
if (Deno.args.includes("build")) {
await builder.build();
} else {
await builder.listen(() => import("./main.ts"));
}
@@ -0,0 +1,16 @@
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button id="decrement" onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button id="increment" onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
@@ -0,0 +1,30 @@
import { App, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
});
// this can also be defined via a file. feel free to delete this!
const exampleLoggerMiddleware = define.middleware((ctx) => {
console.log(`${ctx.req.method} ${ctx.req.url}`);
return ctx.next();
});
app.use(exampleLoggerMiddleware);
// Include file-system based routes here
app.fsRoutes();
@@ -0,0 +1,17 @@
import { define } from "../utils.ts";
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__PROJECT_NAME__</title>
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
<Component />
</body>
</html>
);
});
@@ -0,0 +1,10 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
@@ -0,0 +1,33 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
});
@@ -0,0 +1,19 @@
<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>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,144 @@
*,
*::before,
*::after {
box-sizing: border-box;
}
* {
margin: 0;
}
button {
color: inherit;
}
button, [role="button"] {
cursor: pointer;
}
code {
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace;
font-size: 1em;
}
img,
svg {
display: block;
}
img,
video {
max-width: 100%;
height: auto;
}
html {
line-height: 1.5;
-webkit-text-size-adjust: 100%;
font-family:
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif,
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol",
"Noto Color Emoji";
}
.transition-colors {
transition-property: background-color, border-color, color, fill, stroke;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.my-6 {
margin-bottom: 1.5rem;
margin-top: 1.5rem;
}
.text-4xl {
font-size: 2.25rem;
line-height: 2.5rem;
}
.mx-2 {
margin-left: 0.5rem;
margin-right: 0.5rem;
}
.my-4 {
margin-bottom: 1rem;
margin-top: 1rem;
}
.mx-auto {
margin-left: auto;
margin-right: auto;
}
.px-4 {
padding-left: 1rem;
padding-right: 1rem;
}
.py-8 {
padding-bottom: 2rem;
padding-top: 2rem;
}
.bg-\[\#86efac\] {
background-color: #86efac;
}
.text-3xl {
font-size: 1.875rem;
line-height: 2.25rem;
}
.py-6 {
padding-bottom: 1.5rem;
padding-top: 1.5rem;
}
.px-2 {
padding-left: 0.5rem;
padding-right: 0.5rem;
}
.py-1 {
padding-bottom: 0.25rem;
padding-top: 0.25rem;
}
.border-gray-500 {
border-color: #6b7280;
}
.bg-white {
background-color: #fff;
}
.flex {
display: flex;
}
.gap-8 {
grid-gap: 2rem;
gap: 2rem;
}
.font-bold {
font-weight: 700;
}
.max-w-screen-md {
max-width: 768px;
}
.flex-col {
flex-direction: column;
}
.items-center {
align-items: center;
}
.justify-center {
justify-content: center;
}
.border-2 {
border-width: 2px;
}
.rounded-sm {
border-radius: 0.25rem;
}
.hover\:bg-gray-200:hover {
background-color: #e5e7eb;
}
.tabular-nums {
font-variant-numeric: tabular-nums;
}
.min-h-screen {
min-height: 100vh;
}
.fresh-gradient {
background-color: rgb(134, 239, 172);
background-image: linear-gradient(
to right bottom,
rgb(219, 234, 254),
rgb(187, 247, 208),
rgb(254, 249, 195)
);
}
@@ -0,0 +1,9 @@
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
}
export const define = createDefine<State>();
@@ -0,0 +1,17 @@
# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "Getting
Started" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno:
https://docs.deno.com/runtime/getting_started/installation
Then start the project in development mode:
```
deno task dev
```
This will watch the project directory and restart as necessary.
@@ -0,0 +1,13 @@
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Fresh build directory
_fresh/
# npm + other dependencies
node_modules/
vendor/
@@ -0,0 +1,10 @@
@import "tailwindcss";
.fresh-gradient {
background-color: rgb(134, 239, 172);
background-image: linear-gradient(
to right bottom,
rgb(219, 234, 254),
rgb(187, 247, 208),
rgb(254, 249, 195)
);
}
@@ -0,0 +1,2 @@
// Import CSS files here for hot module reloading to work.
import "./assets/styles.css";
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
{...props}
class="px-2 py-1 border-gray-500 border-2 rounded-sm bg-white hover:bg-gray-200 transition-colors"
/>
);
}
@@ -0,0 +1,59 @@
{
"nodeModulesDir": "auto",
"tasks": {
"check": "deno fmt --check . && deno lint . && deno check",
"dev": "vite",
"build": "vite build",
"start": "deno serve -A _fresh/server.js",
"update": "deno run -A -r jsr:@fresh/update ."
},
"lint": {
"rules": {
"tags": [
"fresh",
"recommended"
]
}
},
"exclude": [
"**/_fresh/*"
],
"imports": {
"fresh": "jsr:@fresh/core@^__FRESH_VERSION__",
"preact": "npm:preact@^__PREACT_VERSION__",
"@preact/signals": "npm:@preact/signals@^__PREACT_SIGNALS_VERSION__",
"@fresh/plugin-vite": "jsr:@fresh/plugin-vite@^__FRESH_VITE_PLUGIN_VERSION__",
"vite": "npm:vite@^__VITE_VERSION__",
"tailwindcss": "npm:tailwindcss@^__TAILWINDCSS_VERSION__",
"@tailwindcss/vite": "npm:@tailwindcss/vite@^__TAILWINDCSS_VITE_VERSION__"
},
"compilerOptions": {
"lib": [
"dom",
"dom.asynciterable",
"dom.iterable",
"deno.ns"
],
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template"
],
"types": [
"vite/client"
]
}
}
@@ -0,0 +1,16 @@
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button id="decrement" onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button id="increment" onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
@@ -0,0 +1,30 @@
import { App, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
});
// this can also be defined via a file. feel free to delete this!
const exampleLoggerMiddleware = define.middleware((ctx) => {
console.log(`${ctx.req.method} ${ctx.req.url}`);
return ctx.next();
});
app.use(exampleLoggerMiddleware);
// Include file-system based routes here
app.fsRoutes();
@@ -0,0 +1,16 @@
import { define } from "../utils.ts";
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__PROJECT_NAME__</title>
</head>
<body>
<Component />
</body>
</html>
);
});
@@ -0,0 +1,10 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
@@ -0,0 +1,33 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
});
@@ -0,0 +1,19 @@
<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>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,9 @@
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
}
export const define = createDefine<State>();
@@ -0,0 +1,7 @@
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [fresh(), tailwindcss()],
});
@@ -0,0 +1,17 @@
# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "Getting
Started" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno:
https://docs.deno.com/runtime/getting_started/installation
Then start the project in development mode:
```
deno task dev
```
This will watch the project directory and restart as necessary.
@@ -0,0 +1,13 @@
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Fresh build directory
_fresh/
# npm + other dependencies
node_modules/
vendor/
@@ -0,0 +1,144 @@
*,
*::before,
*::after {
box-sizing: border-box;
}
* {
margin: 0;
}
button {
color: inherit;
}
button, [role="button"] {
cursor: pointer;
}
code {
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace;
font-size: 1em;
}
img,
svg {
display: block;
}
img,
video {
max-width: 100%;
height: auto;
}
html {
line-height: 1.5;
-webkit-text-size-adjust: 100%;
font-family:
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif,
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol",
"Noto Color Emoji";
}
.transition-colors {
transition-property: background-color, border-color, color, fill, stroke;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.my-6 {
margin-bottom: 1.5rem;
margin-top: 1.5rem;
}
.text-4xl {
font-size: 2.25rem;
line-height: 2.5rem;
}
.mx-2 {
margin-left: 0.5rem;
margin-right: 0.5rem;
}
.my-4 {
margin-bottom: 1rem;
margin-top: 1rem;
}
.mx-auto {
margin-left: auto;
margin-right: auto;
}
.px-4 {
padding-left: 1rem;
padding-right: 1rem;
}
.py-8 {
padding-bottom: 2rem;
padding-top: 2rem;
}
.bg-\[\#86efac\] {
background-color: #86efac;
}
.text-3xl {
font-size: 1.875rem;
line-height: 2.25rem;
}
.py-6 {
padding-bottom: 1.5rem;
padding-top: 1.5rem;
}
.px-2 {
padding-left: 0.5rem;
padding-right: 0.5rem;
}
.py-1 {
padding-bottom: 0.25rem;
padding-top: 0.25rem;
}
.border-gray-500 {
border-color: #6b7280;
}
.bg-white {
background-color: #fff;
}
.flex {
display: flex;
}
.gap-8 {
grid-gap: 2rem;
gap: 2rem;
}
.font-bold {
font-weight: 700;
}
.max-w-screen-md {
max-width: 768px;
}
.flex-col {
flex-direction: column;
}
.items-center {
align-items: center;
}
.justify-center {
justify-content: center;
}
.border-2 {
border-width: 2px;
}
.rounded-sm {
border-radius: 0.25rem;
}
.hover\:bg-gray-200:hover {
background-color: #e5e7eb;
}
.tabular-nums {
font-variant-numeric: tabular-nums;
}
.min-h-screen {
min-height: 100vh;
}
.fresh-gradient {
background-color: rgb(134, 239, 172);
background-image: linear-gradient(
to right bottom,
rgb(219, 234, 254),
rgb(187, 247, 208),
rgb(254, 249, 195)
);
}
@@ -0,0 +1,2 @@
// Import CSS files here for hot module reloading to work.
import "./assets/styles.css";
@@ -0,0 +1,17 @@
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
{...props}
class="px-2 py-1 border-gray-500 border-2 rounded-sm bg-white hover:bg-gray-200 transition-colors"
/>
);
}
@@ -0,0 +1,57 @@
{
"nodeModulesDir": "auto",
"tasks": {
"check": "deno fmt --check . && deno lint . && deno check",
"dev": "vite",
"build": "vite build",
"start": "deno serve -A _fresh/server.js",
"update": "deno run -A -r jsr:@fresh/update ."
},
"lint": {
"rules": {
"tags": [
"fresh",
"recommended"
]
}
},
"exclude": [
"**/_fresh/*"
],
"imports": {
"fresh": "jsr:@fresh/core@^__FRESH_VERSION__",
"preact": "npm:preact@^__PREACT_VERSION__",
"@preact/signals": "npm:@preact/signals@^__PREACT_SIGNALS_VERSION__",
"@fresh/plugin-vite": "jsr:@fresh/plugin-vite@^__FRESH_VITE_PLUGIN_VERSION__",
"vite": "npm:vite@^__VITE_VERSION__"
},
"compilerOptions": {
"lib": [
"dom",
"dom.asynciterable",
"dom.iterable",
"deno.ns"
],
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template"
],
"types": [
"vite/client"
]
}
}
@@ -0,0 +1,16 @@
import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
return (
<div class="flex gap-8 py-6">
<Button id="decrement" onClick={() => props.count.value -= 1}>-1</Button>
<p class="text-3xl tabular-nums">{props.count}</p>
<Button id="increment" onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
@@ -0,0 +1,30 @@
import { App, staticFiles } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
});
// this can also be defined via a file. feel free to delete this!
const exampleLoggerMiddleware = define.middleware((ctx) => {
console.log(`${ctx.req.method} ${ctx.req.url}`);
return ctx.next();
});
app.use(exampleLoggerMiddleware);
// Include file-system based routes here
app.fsRoutes();
@@ -0,0 +1,16 @@
import { define } from "../utils.ts";
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__PROJECT_NAME__</title>
</head>
<body>
<Component />
</body>
</html>
);
});
@@ -0,0 +1,10 @@
import { define } from "../../utils.ts";
export const handler = define.handlers({
GET(ctx) {
const name = ctx.params.name;
return new Response(
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
);
},
});
@@ -0,0 +1,33 @@
import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</div>
);
});
@@ -0,0 +1,19 @@
<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>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,9 @@
import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
shared: string;
}
export const define = createDefine<State>();
@@ -0,0 +1,6 @@
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
export default defineConfig({
plugins: [fresh()],
});
@@ -0,0 +1,15 @@
FROM denoland/deno:__DENO_VERSION__
ARG GIT_REVISION
ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
WORKDIR /app
COPY . .
RUN deno cache _fresh/server.js
EXPOSE 8000
CMD ["serve", "-A", "_fresh/server.js"]
@@ -0,0 +1,6 @@
{
"recommendations": [
"denoland.vscode-deno",
"bradlc.vscode-tailwindcss"
]
}
@@ -0,0 +1,20 @@
{
"deno.enable": true,
"deno.lint": true,
"editor.defaultFormatter": "denoland.vscode-deno",
"[typescriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[typescript]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[javascriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[javascript]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"css.customData": [
".vscode/tailwind.json"
]
}
@@ -0,0 +1,55 @@
{
"version": 1.1,
"atDirectives": [
{
"name": "@tailwind",
"description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"
}
]
},
{
"name": "@apply",
"description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#apply"
}
]
},
{
"name": "@responsive",
"description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#responsive"
}
]
},
{
"name": "@screen",
"description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n /* ... */\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#screen"
}
]
},
{
"name": "@variants",
"description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#variants"
}
]
}
]
}
@@ -0,0 +1,5 @@
{
"recommendations": [
"denoland.vscode-deno"
]
}
@@ -0,0 +1,17 @@
{
"deno.enable": true,
"deno.lint": true,
"editor.defaultFormatter": "denoland.vscode-deno",
"[typescriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[typescript]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[javascriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[javascript]": {
"editor.defaultFormatter": "denoland.vscode-deno"
}
}
+27 -2
View File
@@ -1,15 +1,40 @@
{
"name": "@fresh/init",
"version": "2.0.9",
"version": "2.1.0",
"license": "MIT",
"exports": "./src/mod.ts",
"exclude": ["**/tmp/*"],
"lint": {
"rules": {
"exclude": ["no-console"]
}
},
"tasks": {
"check": "deno fmt --check . && deno lint . && deno check **/*.ts",
"test": "deno test -A",
"sync": "deno run -A src/sync.ts"
},
"imports": {
"@std/cli": "jsr:@std/cli@^1",
"@std/fmt": "jsr:@std/fmt@^1",
"@std/fs": "jsr:@std/fs@^1",
"@std/path": "jsr:@std/path@^1",
"@std/semver": "jsr:@std/semver@^1",
"@std/jsonc": "jsr:@std/jsonc@^1"
},
"publish": {
"include": [
"src/**/*.ts",
"assets/**/*",
"deno.json",
"README.md"
],
"exclude": ["**/*_test.*", "*.todo"]
"exclude": [
"**/*_test.*",
"*.todo",
"tests/",
"DESIGN.md",
"src/sync.ts"
]
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

+261 -842
View File
File diff suppressed because it is too large Load Diff
-363
View File
@@ -1,363 +0,0 @@
import { expect } from "@std/expect";
import {
CONFIRM_TAILWIND_MESSAGE,
CONFIRM_VITE_MESSAGE,
CONFIRM_VSCODE_MESSAGE,
HELP_TEXT,
initProject,
} from "./init.ts";
import * as path from "@std/path";
import { getStdOutput, withBrowser } from "../../fresh/tests/test_utils.tsx";
import { waitForText } from "../../fresh/tests/test_utils.tsx";
import { withChildProcessServer } from "../../fresh/tests/test_utils.tsx";
import { withTmpDir as withTmpDirBase } from "../../fresh/src/test_utils.ts";
import { stub } from "@std/testing/mock";
// deno-lint-ignore no-explicit-any
(globalThis as any).INIT_TEST = true;
function stubPrompt(result: string) {
return stub(globalThis, "prompt", () => result);
}
function stubConfirm(steps: Record<string, boolean> = {}) {
return stub(
globalThis,
"confirm",
(message) => message ? steps[message] : false,
);
}
function stubLogs() {
return stub(
console,
"log",
() => undefined,
);
}
function withTmpDir(): Promise<{ dir: string } & AsyncDisposable> {
// Windows need temporary files in the repository root
if (Deno.build.os === "windows") {
const dir = path.join(import.meta.dirname!, "..", "..", "..", "..");
return withTmpDirBase({ dir, prefix: "tmp_" });
}
return withTmpDirBase();
}
async function patchProject(dir: string): Promise<void> {
const jsonPath = path.join(dir, "deno.json");
const json = JSON.parse(await Deno.readTextFile(jsonPath));
json.workspace = [];
// See https://github.com/denoland/deno/issues/27313
// json.links = [path.fromFileURL(new URL("../..", import.meta.url))];
json.links = [new URL("../../fresh", import.meta.url).href];
// assert with this stricter rule, before adding it to initialized projects
json.lint.rules.include = ["verbatim-module-syntax"];
await Deno.writeTextFile(jsonPath, JSON.stringify(json, null, 2) + "\n");
}
async function expectProjectFile(dir: string, pathname: string) {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
const stat = await Deno.stat(filePath);
if (!stat.isFile) {
throw new Error(`Not a project file: ${filePath}`);
}
}
async function expectNotProjectFile(dir: string, pathname: string) {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
try {
const stat = await Deno.stat(filePath);
if (stat.isFile) {
throw new Error(`A project file but expected it not to be: ${filePath}`);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
async function readProjectFile(dir: string, pathname: string): Promise<string> {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
const content = await Deno.readTextFile(filePath);
return content;
}
Deno.test("init - show help", async () => {
using logs = stubLogs();
await initProject("", [], { help: true });
const args = logs.calls.flatMap((c) => c.args);
const out = args.join("\n");
await initProject("", [], { h: true });
expect(out).toBe(HELP_TEXT);
expect(args).toEqual(logs.calls.flatMap((c) => c.args).slice(args.length));
});
Deno.test("init - new project", async () => {
await using tmp = await withTmpDir();
using _promptStub = stubPrompt("fresh-init");
using _confirmStub = stubConfirm();
await initProject(tmp.dir, [], { builder: true });
});
Deno.test("init - create project dir", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt("fresh-init");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
const root = path.join(dir, "fresh-init");
await expectProjectFile(root, "deno.json");
await expectProjectFile(root, "main.ts");
await expectProjectFile(root, "dev.ts");
await expectProjectFile(root, ".gitignore");
await expectProjectFile(root, "static/styles.css");
});
Deno.test("init - with tailwind", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_TAILWIND_MESSAGE]: true,
});
await initProject(dir, [], { builder: true });
const css = await readProjectFile(dir, "static/styles.css");
expect(css).toMatch(/@import "tailwindcss"/);
const main = await readProjectFile(dir, "main.ts");
const dev = await readProjectFile(dir, "dev.ts");
expect(main).not.toMatch(/tailwind/);
expect(dev).toMatch(/tailwind/);
});
Deno.test("init - with vscode", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_VSCODE_MESSAGE]: true,
});
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, ".vscode/settings.json");
await expectProjectFile(dir, ".vscode/extensions.json");
});
Deno.test({
name: "init - fmt, lint, and type check project",
// Ignore this test on canary due to different formatting
// behaviours when the formatter changes.
ignore: Deno.version.deno.includes("+"),
fn: async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const check = await new Deno.Command(Deno.execPath(), {
args: ["task", "check"],
cwd: dir,
stderr: "inherit",
stdout: "inherit",
}).output();
expect(check.code).toEqual(0);
},
});
Deno.test(
"init with tailwind - fmt, lint, and type check project",
async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_TAILWIND_MESSAGE]: true,
});
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const check = await new Deno.Command(Deno.execPath(), {
args: ["task", "check"],
cwd: dir,
stderr: "inherit",
stdout: "inherit",
}).output();
expect(check.code).toEqual(0);
},
);
Deno.test({
// TODO: For some reason this test is flaky in GitHub CI. It works when
// testing locally on windows though. Not sure what's going on.
ignore: Deno.build.os === "windows" && Deno.env.get("CI") !== undefined,
name: "init - can start dev server",
fn: async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
await withChildProcessServer(
{ cwd: dir, args: ["task", "dev"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("#decrement").click();
await waitForText(page, "button + p", "2");
});
},
);
},
});
Deno.test("init - can start built project", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
// Build
await new Deno.Command(Deno.execPath(), {
args: ["task", "build"],
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
}).output();
await withChildProcessServer(
{ cwd: dir, env: { PORT: "0" }, args: ["task", "start"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("button").click();
await waitForText(page, "button + p", "2");
});
},
);
});
Deno.test("init - errors on missing build cache in prod", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const cp = await new Deno.Command(Deno.execPath(), {
args: ["task", "start"],
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
}).output();
const { stderr } = getStdOutput(cp);
expect(cp.code).toEqual(1);
expect(stderr).toMatch(/Module not found/);
});
// There is a peerDependency issue with links
Deno.test.ignore("init - vite dev server", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], {});
await expectProjectFile(dir, "vite.config.ts");
await expectNotProjectFile(dir, "dev.ts");
await patchProject(dir);
await withChildProcessServer(
{ cwd: dir, args: ["task", "dev"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("#decrement").click();
await waitForText(page, "button + p", "2");
});
},
);
});
// There is a peerDependency issue with links
Deno.test.ignore("init - vite build", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], {});
await expectProjectFile(dir, "vite.config.ts");
await patchProject(dir);
// Build
await new Deno.Command(Deno.execPath(), {
args: ["task", "build"],
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
}).output();
await withChildProcessServer(
{ cwd: dir, env: { PORT: "0" }, args: ["task", "start"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("button").click();
await waitForText(page, "button + p", "2");
});
},
);
});
Deno.test("init - with vite", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_VITE_MESSAGE]: true,
});
await initProject(dir, [], {});
await expectProjectFile(dir, "vite.config.ts");
await expectNotProjectFile(dir, "dev.ts");
});
+217 -23
View File
@@ -1,26 +1,220 @@
#!/usr/bin/env -S deno run -A
/**
* CLI entry point for @fresh/init
*
* This module serves two purposes:
* 1. CLI execution: Parses command-line arguments and runs the init script
* 2. Programmatic API: Exports initProject and resolveVersions for library use
*
* When run directly (deno run -Ar jsr:@fresh/init), this serves as
* the CLI entry point, providing interactive and non-interactive modes
* for creating new Fresh projects.
*/
import { parseArgs } from "@std/cli/parse-args";
import { initProject } from "./init.ts";
import { InitError } from "./init.ts";
import * as colors from "@std/fmt/colors";
import { initProject as initProjectImpl, resolveVersions } from "./init.ts";
import type { InitOptions } from "./types.ts";
import initConfig from "../deno.json" with { type: "json" };
const flags = parseArgs(Deno.args, {
boolean: ["force", "tailwind", "vscode", "docker", "help", "builder"],
default: {
force: null,
tailwind: null,
vscode: null,
docker: null,
builder: null,
},
alias: {
help: "h",
},
});
try {
await initProject(Deno.cwd(), flags._, flags);
} catch (err) {
if (err instanceof InitError) {
Deno.exit(1);
}
throw err;
const HELP_TEXT = `
${
colors.bgRgb8(
colors.rgb8(
` 🍋 @fresh/init${colors.rgb8(`@${initConfig.version}`, 248)} `,
0,
),
121,
)
}
Initialize a new Fresh project. This will create all the necessary files
for a new project.
To generate a project in the './foobar' subdirectory:
${colors.rgb8("deno run -Ar jsr:@fresh/init ./foobar", 245)}
To generate a project in the current directory:
${colors.rgb8("deno run -Ar jsr:@fresh/init .", 245)}
${colors.rgb8("USAGE:", 3)}
${colors.rgb8("deno run -Ar jsr:@fresh/init [DIRECTORY]", 245)}
${colors.rgb8("OPTIONS:", 3)}
${colors.rgb8("--force", 2)} Overwrite existing files
${colors.rgb8("--tailwind", 2)} Use Tailwind for styling
${colors.rgb8("--vscode", 2)} Setup project for VS Code
${colors.rgb8("--docker", 2)} Setup project to use Docker
${colors.rgb8("--builder", 2)} Setup with builder instead of vite
${colors.rgb8("--help, -h", 2)} Show this help message
`;
const CONFIRM_EMPTY_MESSAGE =
"The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
const CONFIRM_TAILWIND_MESSAGE = `Set up ${
colors.cyan("Tailwind CSS")
} for styling?`;
const CONFIRM_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`;
export class InitError extends Error {}
function error(message: string): never {
console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", "");
throw new InitError();
}
/**
* Initialize a Fresh project.
*
* This is the main CLI entry point that accepts command-line arguments
* and flags to create a new Fresh project.
*
* @param cwd - Current working directory
* @param input - Directory arguments from command line
* @param flags - CLI flags (force, tailwind, vscode, docker, builder, help)
*/
export async function initProject(
cwd: string = Deno.cwd(),
input: (string | number)[],
flags: {
docker?: boolean | null;
force?: boolean | null;
tailwind?: boolean | null;
vscode?: boolean | null;
builder?: boolean | null;
help?: boolean | null;
h?: boolean | null;
} = {},
): Promise<void> {
// Show help if requested
if (flags.help || flags.h) {
console.log(HELP_TEXT);
return;
}
// Display banner
console.log();
console.log(
colors.bgRgb8(
colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0),
121,
),
);
console.log();
// Get project directory
let directory: string;
if (input.length === 0) {
const userInput = prompt("Project Name:", "fresh-project");
if (!userInput) {
error(HELP_TEXT);
}
directory = userInput;
} else if (input.length === 1) {
directory = String(input[0]);
} else {
error("Too many arguments. Expected at most one directory argument.");
}
// Build options from CLI flags (with prompts for missing values)
const tailwind = flags.tailwind ?? confirm(CONFIRM_TAILWIND_MESSAGE);
const vscode = flags.vscode ?? confirm(CONFIRM_VSCODE_MESSAGE);
let force = flags.force ?? false;
// Check if directory is empty (if not forced)
if (!force) {
try {
const projectDir = new URL(directory, `file://${cwd}/`).pathname;
const entries = [...Deno.readDirSync(projectDir)];
const isEmpty = entries.length === 0 ||
(entries.length === 1 && entries[0].name === ".git");
if (!isEmpty) {
const shouldContinue = confirm(CONFIRM_EMPTY_MESSAGE);
if (!shouldContinue) {
error("Directory is not empty. Use --force to overwrite.");
}
force = true;
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
// Directory doesn't exist - that's fine
}
}
// Build fully resolved options
const options: Required<InitOptions> = {
directory,
builder: flags.builder ?? false,
tailwind,
vscode,
docker: flags.docker ?? false,
force,
};
// Resolve versions
const versions = await resolveVersions();
console.log(` version ${colors.rgb8(versions.FRESH_VERSION, 4)}`);
console.log();
// Call the template engine (pure processing, no output)
await initProjectImpl(cwd, options, versions);
// Display success messages
console.log(
"\n%cProject initialized!\n",
"color: green; font-weight: bold",
);
if (directory !== ".") {
console.log(
`Enter your project directory using %ccd ${directory}%c.`,
"color: cyan",
"",
);
}
console.log(
"Run %cdeno task dev%c to start the project. %cCTRL-C%c to stop.",
"color: cyan",
"",
"color: cyan",
"",
);
console.log();
console.log(
"Stuck? Join our Discord %chttps://discord.gg/deno",
"color: cyan",
"",
);
console.log();
console.log("%cHappy hacking! 🦕", "color: gray");
}
// When run as CLI
if (import.meta.main) {
const flags = parseArgs(Deno.args, {
boolean: ["force", "tailwind", "vscode", "docker", "help", "builder"],
default: {
force: null,
tailwind: null,
vscode: null,
docker: null,
builder: null,
},
alias: {
help: "h",
},
});
try {
await initProject(Deno.cwd(), flags._, flags);
} catch (err) {
if (err instanceof InitError) {
Deno.exit(1);
}
throw err;
}
}
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env -S deno run -A
/**
* Sync script for template maintenance.
*
* This script copies common files from base templates to their corresponding
* template variants, making it easier to maintain shared files across templates.
*
* Structure:
* - assets/base/vite/ -> Copied to assets/template/vite/ and vite-tailwind/
* - assets/base/builder/ -> Copied to assets/template/builder/ and builder-tailwind/
*
* Template-specific files (like deno.json.tmpl, styles.css) are never overwritten.
*
* Usage:
* deno run -A sync_templates.ts
* deno run -A sync_templates.ts --dry-run
*/
import * as path from "@std/path";
import * as fs from "@std/fs";
import * as colors from "@std/fmt/colors";
/**
* Files that should NOT be copied from base to templates.
* These are template-specific and should be maintained separately.
*/
const TEMPLATE_SPECIFIC_FILES = [
// Dependency files - different for each template variant
"deno.json.tmpl",
"deno.json",
// Build config - tailwind variants override these
"vite.config.ts",
// Styles - different content for tailwind vs regular
"assets/styles.css",
"static/styles.css",
];
/**
* Template configurations.
*/
const TEMPLATE_CONFIG = {
vite: {
base: "assets/base/vite",
targets: ["assets/template/vite", "assets/template/vite-tailwind"],
},
builder: {
base: "assets/base/builder",
targets: ["assets/template/builder", "assets/template/builder-tailwind"],
},
};
interface SyncResult {
copied: string[];
skipped: string[];
errors: string[];
}
/**
* Check if a file path should be skipped (template-specific).
*/
function isTemplateSpecific(relPath: string): boolean {
return TEMPLATE_SPECIFIC_FILES.some((specific) =>
relPath === specific || relPath.endsWith(`/${specific}`)
);
}
/**
* Recursively copy files from source to destination, skipping template-specific files.
*/
async function syncDirectory(
srcDir: string,
destDir: string,
baseDir: string,
dryRun: boolean,
): Promise<SyncResult> {
const result: SyncResult = { copied: [], skipped: [], errors: [] };
try {
for await (const entry of Deno.readDir(srcDir)) {
const srcPath = path.join(srcDir, entry.name);
const destPath = path.join(destDir, entry.name);
const relPath = path.relative(baseDir, srcPath);
if (entry.isDirectory) {
// Recursively sync directories
if (!dryRun) {
await fs.ensureDir(destPath);
}
const subResult = await syncDirectory(
srcPath,
destPath,
baseDir,
dryRun,
);
result.copied.push(...subResult.copied);
result.skipped.push(...subResult.skipped);
result.errors.push(...subResult.errors);
} else {
// Check if file is template-specific
if (isTemplateSpecific(relPath)) {
result.skipped.push(relPath);
continue;
}
// Copy file
try {
if (!dryRun) {
await fs.copy(srcPath, destPath, { overwrite: true });
}
result.copied.push(relPath);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
result.errors.push(`${relPath}: ${message}`);
}
}
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
result.errors.push(`Error reading ${srcDir}: ${message}`);
}
return result;
}
/**
* Sync base template to all its target templates.
*/
async function syncTemplate(
name: string,
config: { base: string; targets: string[] },
dryRun: boolean,
): Promise<void> {
console.log(colors.bold(colors.cyan(`\n📦 Syncing ${name} templates...`)));
console.log(colors.dim(` Base: ${config.base}`));
for (const target of config.targets) {
const targetName = path.basename(target);
console.log(colors.dim(` → ${targetName}`));
const result = await syncDirectory(
config.base,
target,
config.base,
dryRun,
);
if (result.copied.length > 0) {
console.log(
colors.green(
` ✓ ${result.copied.length} file(s) ${
dryRun ? "would be copied" : "copied"
}`,
),
);
}
if (result.skipped.length > 0) {
console.log(
colors.yellow(
` ⊘ ${result.skipped.length} file(s) skipped (template-specific)`,
),
);
}
if (result.errors.length > 0) {
console.log(colors.red(` ✗ ${result.errors.length} error(s):`));
for (const error of result.errors) {
console.log(colors.red(` ${error}`));
}
}
}
}
/**
* Main sync function.
*/
async function main() {
const args = Deno.args;
const dryRun = args.includes("--dry-run");
console.log(colors.bold("\n🔄 Template Sync Tool\n"));
if (dryRun) {
console.log(colors.yellow("🔍 DRY RUN MODE - No files will be modified\n"));
}
// Sync all template groups
for (const [name, config] of Object.entries(TEMPLATE_CONFIG)) {
await syncTemplate(name, config, dryRun);
}
console.log(colors.bold(colors.green("\n✅ Sync complete!")));
if (dryRun) {
console.log(
colors.dim("\nRun without --dry-run to actually copy files."),
);
} else {
console.log(
colors.dim(
"\nReview changes with git diff before committing.",
),
);
}
}
if (import.meta.main) {
await main();
}
+82
View File
@@ -0,0 +1,82 @@
/**
* Options for initializing a Fresh project.
* Optional fields will use defaults or prompt the user.
*
* @example
* ```ts
* const options: InitOptions = {
* directory: "./my-app",
* tailwind: true,
* vscode: false,
* docker: false,
* builder: false,
* force: false,
* };
* ```
*/
export interface InitOptions {
/** Target directory for the project */
directory: string;
/** Use legacy builder instead of Vite (default: false) */
builder?: boolean;
/** Include Tailwind CSS setup (default: prompt user) */
tailwind?: boolean;
/** Include VS Code configuration (default: prompt user) */
vscode?: boolean;
/** Include Docker setup (default: false) */
docker?: boolean;
/** Force overwrite existing files (default: false) */
force?: boolean;
}
/**
* Version overrides for testing or pinning specific versions.
* All fields are optional and use camelCase naming.
*/
export type VersionOverrides = Partial<{
fresh: string;
freshTailwind: string;
freshVitePlugin: string;
preact: string;
preactSignals: string;
tailwindcss: string;
tailwindcssPostcss: string;
tailwindcssVite: string;
postcss: string;
vite: string;
}>;
/**
* Variables available for template substitution using __VARIABLE__ syntax.
* All fields represent actual template placeholders in template files.
*
* @example
* ```ts
* const variables: TemplateVariables = {
* PROJECT_NAME: "my-app",
* FRESH_VERSION: "2.1.1",
* PREACT_VERSION: "10.27.2",
* // ... other version strings
* };
* // In templates: __PROJECT_NAME__, __FRESH_VERSION__, etc.
* ```
*/
export interface TemplateVariables {
PROJECT_NAME: string;
FRESH_VERSION: string;
FRESH_TAILWIND_VERSION: string;
FRESH_VITE_PLUGIN_VERSION: string;
PREACT_VERSION: string;
PREACT_SIGNALS_VERSION: string;
TAILWINDCSS_VERSION: string;
TAILWINDCSS_POSTCSS_VERSION: string;
TAILWINDCSS_VITE_VERSION: string;
POSTCSS_VERSION: string;
VITE_VERSION: string;
DENO_VERSION: string;
}
+186
View File
@@ -0,0 +1,186 @@
import * as path from "@std/path";
import * as fs from "@std/fs";
import * as semver from "@std/semver";
/**
* Fetch the latest version of a package from JSR or npm.
*/
export async function getLatestVersion(
pkg: string,
fallback: string,
): Promise<string> {
// In test mode, always use fallback to avoid network calls
// deno-lint-ignore no-explicit-any
if ((globalThis as any).INIT_TEST) {
return fallback;
}
try {
// Check if it's an npm package
if (pkg.startsWith("npm:")) {
const npmPkg = pkg.slice(4); // Remove "npm:" prefix
const res = await fetch(`https://registry.npmjs.org/${npmPkg}/latest`);
if (!res.ok) {
await res.body?.cancel();
throw new Error(`HTTP ${res.status}`);
}
const json = await res.json() as { version: string };
return json.version;
}
// JSR package
const res = await fetch(`https://jsr.io/${pkg}/meta.json`);
if (!res.ok) {
await res.body?.cancel(); // Consume the body to avoid leaks
throw new Error(`HTTP ${res.status}`);
}
const json = await res.json() as {
latest: string | null;
versions: Record<string, unknown>;
};
if (json.latest !== null) {
return json.latest;
}
const versions = Object.keys(json.versions);
if (versions.length === 0) {
throw new Error("No versions available");
}
versions.sort((a, b) => {
const s1 = semver.parse(a);
const s2 = semver.parse(b);
return semver.compare(s1, s2);
});
return versions.at(-1)!;
} catch (err) {
// Silent fallback for network or API errors
const message = err instanceof Error ? err.message : String(err);
console.error(
`Could not fetch latest ${pkg} version: ${message}. Using fallback: ${fallback}`,
);
return fallback;
}
}
/**
* Check if a directory exists and is empty (or only contains .git).
*/
export async function isDirectoryEmpty(dir: string): Promise<boolean> {
try {
const entries = [];
for await (const entry of Deno.readDir(dir)) {
entries.push(entry);
}
return entries.length === 0 ||
(entries.length === 1 && entries[0].name === ".git");
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return true; // Directory doesn't exist, so it's "empty"
}
throw err;
}
}
/**
* Recursively copy a directory.
*/
export async function copyDir(src: string, dest: string): Promise<void> {
await fs.ensureDir(dest);
for await (const entry of Deno.readDir(src)) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory) {
await copyDir(srcPath, destPath);
} else {
await fs.copy(srcPath, destPath, { overwrite: true });
}
}
}
/**
* Substitute variables in a template string.
* Replaces __VAR__ patterns with values.
*/
export function substituteVariables(
content: string,
variables: Record<string, string | boolean | number>,
): string {
let result = content;
for (const [key, value] of Object.entries(variables)) {
const regex = new RegExp(`__${key}__`, "g");
result = result.replace(regex, String(value));
}
return result;
}
/**
* Convert double-underscore-prefixed filename to dot-prefixed.
* Only converts files/dirs that start with double underscore (__).
* Files with single underscore (like _app.tsx) are NOT converted.
* Examples:
* - "__gitignore" -> ".gitignore"
* - "__vscode" -> ".vscode"
* - "_app.tsx" -> "_app.tsx" (unchanged)
*/
export function processFilename(filename: string): string {
if (filename.startsWith("__")) {
return "." + filename.slice(2);
}
return filename;
}
/**
* Get the template directory path.
*/
export function getTemplateDir(): string {
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
return path.join(moduleDir, "..", "assets", "template");
}
/**
* Get the variants directory path.
*/
export function getVariantsDir(): string {
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
return path.join(moduleDir, "..", "assets", "variants");
}
/**
* Prompt user for confirmation (or use provided value).
*/
export function confirmOrValue(
message: string,
providedValue: boolean | undefined,
): boolean {
if (providedValue !== undefined) {
return providedValue;
}
return confirm(message);
}
/**
* Prompt user for input (or use provided value).
*/
export function promptOrValue(
message: string,
defaultValue: string,
providedValue: string | undefined,
): string {
if (providedValue !== undefined) {
return providedValue;
}
const result = prompt(message, defaultValue);
if (!result) {
throw new Error("Input required");
}
return result;
}
+131
View File
@@ -0,0 +1,131 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
Deno.test({
name: "cli - shows help text",
async fn() {
const command = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(import.meta.dirname!, "..", "src", "mod.ts"),
"--help",
],
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("@fresh/init");
expect(output).toContain("USAGE:");
expect(output).toContain("OPTIONS:");
expect(output).toContain("--force");
expect(output).toContain("--tailwind");
expect(output).toContain("--vscode");
expect(output).toContain("--docker");
expect(output).toContain("--builder");
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "cli - creates project with flags",
async fn() {
const tmpDir = await Deno.makeTempDir();
const projectName = "test-cli-full";
try {
const command = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(import.meta.dirname!, "..", "src", "mod.ts"),
projectName,
"--force",
"--tailwind",
"--vscode",
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("Project initialized!");
// Verify project structure
const projectDir = path.join(tmpDir, projectName);
const stat = await Deno.stat(projectDir);
expect(stat.isDirectory).toBe(true);
// Verify key files exist
await Deno.stat(path.join(projectDir, "deno.json"));
await Deno.stat(path.join(projectDir, "vite.config.ts"));
await Deno.stat(path.join(projectDir, "assets", "styles.css"));
await Deno.stat(path.join(projectDir, ".vscode", "settings.json"));
await Deno.stat(path.join(projectDir, ".vscode", "tailwind.json"));
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "cli - creates builder project",
async fn() {
const tmpDir = await Deno.makeTempDir();
const projectName = "test-cli-builder";
try {
const command = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(import.meta.dirname!, "..", "src", "mod.ts"),
projectName,
"--force",
"--builder",
"--docker",
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
stdin: "null",
env: {
"NO_COLOR": "1", // Disable prompts in test
},
});
const { code } = await command.output();
expect(code).toBe(0);
// Verify builder project structure
const projectDir = path.join(tmpDir, projectName);
await Deno.stat(path.join(projectDir, "dev.ts"));
await Deno.stat(path.join(projectDir, "Dockerfile"));
// Should NOT have vite files
try {
await Deno.stat(path.join(projectDir, "vite.config.ts"));
throw new Error("Should not have vite.config.ts in builder mode");
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
},
sanitizeOps: false,
sanitizeResources: false,
});
+320
View File
@@ -0,0 +1,320 @@
/**
* Compatibility tests that compare the output of @fresh/init v2.0.9
* (last version before template-based refactor) with the current version
* to ensure 100% identical output for various option combinations.
*/
import { expect } from "@std/expect";
import * as path from "@std/path";
import * as fs from "@std/fs";
import { stub } from "@std/testing/mock";
import { initProject as newInitProject, resolveVersions } from "../src/init.ts";
import { withTmpDir } from "../../fresh/src/test_utils.ts";
/**
* Recursively get all files in a directory with their relative paths
*/
async function getAllFiles(dir: string, baseDir = dir): Promise<string[]> {
const files: string[] = [];
for await (const entry of fs.walk(dir, { includeFiles: true })) {
if (entry.isFile) {
const relativePath = path.relative(baseDir, entry.path);
files.push(relativePath);
}
}
return files.sort();
}
/**
* Compare two directories recursively, ensuring all files and contents match
*/
async function compareDirectories(
dir1: string,
dir2: string,
description: string,
): Promise<void> {
const files1 = await getAllFiles(dir1);
const files2 = await getAllFiles(dir2);
// Compare file lists
expect(files1).toEqual(files2);
// Compare file contents
for (const file of files1) {
const file1Path = path.join(dir1, file);
const file2Path = path.join(dir2, file);
let content1 = await Deno.readTextFile(file1Path);
let content2 = await Deno.readTextFile(file2Path);
// For deno.json, normalize dependency versions to allow minor/patch differences
// The current init fetches latest Fresh version from network, which may differ
// from the version that was current when 2.0.9 was released. This is expected.
if (file === "deno.json") {
content1 = normalizeDependencyVersions(content1);
content2 = normalizeDependencyVersions(content2);
}
if (content1 !== content2) {
console.error(`\nFile mismatch in ${description}: ${file}`);
console.error(`Version 2.0.9: ${file1Path}`);
console.error(`Current version: ${file2Path}`);
console.error("\n--- Expected (v2.0.9) ---");
console.error(content1.slice(0, 500));
console.error("\n--- Actual (current) ---");
console.error(content2.slice(0, 500));
}
expect(content2).toBe(content1);
}
}
/**
* Normalize dependency versions in deno.json to allow minor/patch differences.
* Replaces specific version numbers with major version only for comparison.
*/
function normalizeDependencyVersions(content: string): string {
return content
// Normalize preact signals version (2.3.x -> 2.x)
.replace(
/"npm:@preact\/signals@\^2\.\d+\.\d+"/g,
'"npm:@preact/signals@^2.x"',
)
// Normalize preact version (10.x.x -> 10.x)
.replace(/"npm:preact@\^10\.\d+\.\d+"/g, '"npm:preact@^10.x"')
// Normalize fresh/plugin-vite version (1.0.x -> 1.0)
.replace(
/"jsr:@fresh\/plugin-vite@\^1\.0\.\d+"/g,
'"jsr:@fresh/plugin-vite@^1.0"',
);
}
/**
* Run the reference init script (v2.0.9) from JSR using the CLI.
* This is the last version before the template-based refactor.
*/
async function runReferenceInit(
dir: string,
projectName: string,
flags: {
docker?: boolean;
tailwind?: boolean;
vscode?: boolean;
builder?: boolean;
},
): Promise<void> {
const args = [
"run",
"-A",
"jsr:@fresh/init@2.0.9",
projectName,
"--force",
];
if (flags.builder) args.push("--builder");
if (flags.tailwind) args.push("--tailwind");
if (flags.vscode) args.push("--vscode");
if (flags.docker) args.push("--docker");
const command = new Deno.Command("deno", {
args,
cwd: dir,
stdout: "null",
stderr: "null",
});
const { success } = await command.output();
if (!success) {
throw new Error("Reference init script (v2.0.9) failed");
}
}
/**
* Test helper that runs both v2.0.9 (reference) and current init with the same
* options and compares the output to ensure backward compatibility.
*/
async function testCompatibility(
testName: string,
flags: {
docker?: boolean;
tailwind?: boolean;
vscode?: boolean;
builder?: boolean;
},
): Promise<void> {
// Use temporary directories for both tests
await using tmpOld = await withTmpDir();
await using tmpNew = await withTmpDir();
const projectName = "test-project";
// Stub console.log to suppress init output
using _logs = stub(console, "log", () => undefined);
// Stub prompt and confirm to prevent waiting for user input
using _promptStub = stub(globalThis, "prompt", () => projectName);
using _confirmStub = stub(globalThis, "confirm", () => false);
// Run reference init script (v2.0.9) from JSR using CLI
await runReferenceInit(tmpOld.dir, projectName, flags);
// Resolve versions to match what v2.0.9 would use (fixed versions)
const versions = await resolveVersions({
fresh: "2.1.1",
freshTailwind: "1.0.0",
freshVitePlugin: "1.0.0",
preact: "10.27.2",
preactSignals: "2.3.1",
tailwindcss: "4.1.10",
tailwindcssPostcss: "4.1.10",
tailwindcssVite: "4.1.12",
postcss: "8.5.6",
vite: "7.1.3",
});
// Run current init script
await newInitProject(
tmpNew.dir,
{
directory: projectName,
builder: flags.builder ?? false,
tailwind: flags.tailwind ?? false,
vscode: flags.vscode ?? false,
docker: flags.docker ?? false,
force: true,
},
versions,
);
// Compare the outputs
const oldProjectDir = path.join(tmpOld.dir, projectName);
const newProjectDir = path.join(tmpNew.dir, projectName);
await compareDirectories(oldProjectDir, newProjectDir, testName);
}
// Test suite covering major option combinations
Deno.test({
name: "compatibility - default (builder, no extras)",
async fn() {
await testCompatibility("default", {
builder: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite only",
async fn() {
await testCompatibility("vite", {
builder: false,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + tailwind",
async fn() {
await testCompatibility("vite-tailwind", {
builder: false,
tailwind: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - builder + tailwind",
async fn() {
await testCompatibility("builder-tailwind", {
builder: true,
tailwind: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + vscode",
async fn() {
await testCompatibility("vite-vscode", {
builder: false,
vscode: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + docker",
async fn() {
await testCompatibility("vite-docker", {
builder: false,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + tailwind + vscode",
async fn() {
await testCompatibility("vite-tailwind-vscode", {
builder: false,
tailwind: true,
vscode: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - builder + tailwind + docker",
async fn() {
await testCompatibility("builder-tailwind-docker", {
builder: true,
tailwind: true,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + all extras",
async fn() {
await testCompatibility("vite-all", {
builder: false,
tailwind: true,
vscode: true,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - builder + all extras",
async fn() {
await testCompatibility("builder-all", {
builder: true,
tailwind: true,
vscode: true,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
+249
View File
@@ -0,0 +1,249 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { withTmpDir } from "../../fresh/src/test_utils.ts";
import { initProject, resolveVersions } from "../src/init.ts";
Deno.test("initProject - creates vite project with default options", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-project");
const versions = await resolveVersions({
fresh: "2.1.1",
preact: "10.27.2",
});
await initProject(tmp.dir, {
directory: "test-project",
builder: false,
tailwind: false,
vscode: false,
docker: false,
force: true,
}, versions);
// Check that key files exist
const files = [
"deno.json",
"vite.config.ts",
"main.ts",
"client.ts",
"utils.ts",
"README.md",
".gitignore",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"islands/Counter.tsx",
"components/Button.tsx",
"assets/styles.css",
"static/logo.svg",
// favicon.ico might not exist if network fails, so skip checking it
];
for (const file of files) {
const filePath = path.join(projectDir, file);
const stat = await Deno.stat(filePath);
expect(stat.isFile).toBe(true);
}
// Check that deno.json contains correct version
const denoJson = JSON.parse(
await Deno.readTextFile(path.join(projectDir, "deno.json")),
);
expect(denoJson.imports.fresh).toContain("2.1.1");
expect(denoJson.imports.preact).toContain("10.27.2");
// Check that vite.config.ts doesn't include tailwind
const viteConfig = await Deno.readTextFile(
path.join(projectDir, "vite.config.ts"),
);
expect(viteConfig).not.toContain("tailwindcss");
// Check that _app.tsx has project name
const appFile = await Deno.readTextFile(
path.join(projectDir, "routes/_app.tsx"),
);
expect(appFile).toContain("test-project");
});
Deno.test("initProject - creates vite project with tailwind", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-tailwind");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-tailwind",
builder: false,
tailwind: true,
vscode: false,
docker: false,
force: true,
}, versions);
// Check vite.config.ts includes tailwind
const viteConfig = await Deno.readTextFile(
path.join(projectDir, "vite.config.ts"),
);
expect(viteConfig).toContain("tailwindcss");
expect(viteConfig).toContain("@tailwindcss/vite");
// Check deno.json includes tailwind
const denoJson = JSON.parse(
await Deno.readTextFile(path.join(projectDir, "deno.json")),
);
expect(denoJson.imports.tailwindcss).toBeTruthy();
expect(denoJson.imports["@tailwindcss/vite"]).toBeTruthy();
// Check styles.css uses @import
const styles = await Deno.readTextFile(
path.join(projectDir, "assets/styles.css"),
);
expect(styles).toContain("@import");
});
Deno.test("initProject - creates builder project", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-builder",
builder: true,
tailwind: false,
vscode: false,
docker: false,
force: true,
}, versions);
// Check that dev.ts exists (not vite.config.ts)
const devTsPath = path.join(projectDir, "dev.ts");
const vitePath = path.join(projectDir, "vite.config.ts");
const devStat = await Deno.stat(devTsPath);
expect(devStat.isFile).toBe(true);
try {
await Deno.stat(vitePath);
throw new Error("vite.config.ts should not exist in builder mode");
} catch (err) {
expect(err).toBeInstanceOf(Deno.errors.NotFound);
}
// Check that static/styles.css exists (not assets/)
const stylesPath = path.join(projectDir, "static/styles.css");
const stylesStat = await Deno.stat(stylesPath);
expect(stylesStat.isFile).toBe(true);
// Check that _app.tsx has link to styles.css
const appFile = await Deno.readTextFile(
path.join(projectDir, "routes/_app.tsx"),
);
expect(appFile).toContain('href="/styles.css"');
});
Deno.test("initProject - creates project with vscode settings", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vscode");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-vscode",
builder: false,
tailwind: false,
vscode: true,
docker: false,
force: true,
}, versions);
// Check VS Code files exist
const vscodeFiles = [
".vscode/settings.json",
".vscode/extensions.json",
];
for (const file of vscodeFiles) {
const filePath = path.join(projectDir, file);
const stat = await Deno.stat(filePath);
expect(stat.isFile).toBe(true);
}
// Check settings.json content
const settings = JSON.parse(
await Deno.readTextFile(path.join(projectDir, ".vscode/settings.json")),
);
expect(settings["deno.enable"]).toBe(true);
expect(settings["deno.lint"]).toBe(true);
// Check extensions.json content
const extensions = JSON.parse(
await Deno.readTextFile(
path.join(projectDir, ".vscode/extensions.json"),
),
);
expect(extensions.recommendations).toContain("denoland.vscode-deno");
});
Deno.test("initProject - creates project with docker", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-docker");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-docker",
builder: false,
tailwind: false,
vscode: false,
docker: true,
force: true,
}, versions);
// Check Dockerfile exists
const dockerfilePath = path.join(projectDir, "Dockerfile");
const dockerStat = await Deno.stat(dockerfilePath);
expect(dockerStat.isFile).toBe(true);
// Check Dockerfile content
const dockerfile = await Deno.readTextFile(dockerfilePath);
expect(dockerfile).toContain("FROM denoland/deno");
expect(dockerfile).toContain("EXPOSE 8000");
});
Deno.test(
"initProject - creates tailwind.json when vscode + tailwind",
async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vscode-tailwind");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-vscode-tailwind",
builder: false,
tailwind: true,
vscode: true,
docker: false,
force: true,
}, versions);
// Check .vscode/tailwind.json exists
const tailwindJsonPath = path.join(
projectDir,
".vscode/tailwind.json",
);
const tailwindStat = await Deno.stat(tailwindJsonPath);
expect(tailwindStat.isFile).toBe(true);
// Check tailwind.json content
const tailwindJson = JSON.parse(
await Deno.readTextFile(tailwindJsonPath),
);
expect(tailwindJson.version).toBe(1.1);
expect(tailwindJson.atDirectives).toBeTruthy();
expect(tailwindJson.atDirectives.length).toBeGreaterThan(0);
expect(tailwindJson.atDirectives[0].name).toBe("@tailwind");
},
);
+273
View File
@@ -0,0 +1,273 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { initProject, resolveVersions } from "../src/init.ts";
import { withTmpDir } from "../../fresh/src/test_utils.ts";
import { withChildProcessServer } from "../../fresh/tests/test_utils.tsx";
/**
* Integration tests for validating generated projects.
*
* These tests generate complete projects and verify they work correctly:
* - Project files are valid and can be checked with `deno task check`
* - Development server starts successfully with `deno task dev`
* - Production build completes with `deno task build`
*
* Note: These tests are more extensive and slower than unit tests.
* They should be run less frequently, perhaps in CI or before releases.
*/
// Helper to run a command in a directory and check its exit code
async function runCommand(
dir: string,
cmd: string[],
): Promise<{ success: boolean; output: string }> {
const command = new Deno.Command(cmd[0], {
args: cmd.slice(1),
cwd: dir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout, stderr } = await command.output();
const output = new TextDecoder().decode(stdout) +
new TextDecoder().decode(stderr);
return { success: code === 0, output };
}
// Helper to initialize a project with resolved versions (for tests)
async function initTestProject(
cwd: string,
directory: string,
builder: boolean,
tailwind: boolean,
) {
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(cwd, {
directory,
builder,
tailwind,
vscode: false,
docker: false,
force: true,
}, versions);
}
Deno.test({
name: "integration - vite project passes check",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vite-check");
await initTestProject(tmp.dir, "test-vite-check", false, false);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "check"],
);
expect(success, `Check failed: ${output}`).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - builder project passes check",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder-check");
await initTestProject(tmp.dir, "test-builder-check", true, false);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "check"],
);
expect(success, `Check failed: ${output}`).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - vite with tailwind passes check",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vite-tailwind-check");
await initTestProject(tmp.dir, "test-vite-tailwind-check", false, true);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "check"],
);
expect(success, `Check failed: ${output}`).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - vite project can build",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vite-build");
await initTestProject(tmp.dir, "test-vite-build", false, false);
// Install dependencies first
await runCommand(projectDir, ["deno", "install"]);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "build"],
);
expect(success, `Build failed: ${output}`).toBe(true);
// Check that _fresh directory was created
const freshDir = path.join(projectDir, "_fresh");
const stat = await Deno.stat(freshDir);
expect(stat.isDirectory).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - builder project can build",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder-build");
await initTestProject(tmp.dir, "test-builder-build", true, false);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "build"],
);
expect(success, `Build failed: ${output}`).toBe(true);
// Check that _fresh directory was created
const freshDir = path.join(projectDir, "_fresh");
const stat = await Deno.stat(freshDir);
expect(stat.isDirectory).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - vite dev server works",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-dev-server");
await initTestProject(tmp.dir, "test-dev-server", false, false);
// Start dev server and verify it works
await withChildProcessServer(
{
cwd: projectDir,
args: ["task", "dev"],
},
async (address) => {
// Verify the home page responds with correct content
const res = await fetch(address);
expect(res.status).toBe(200);
const html = await res.text();
// Check for Fresh welcome message
expect(
html,
"Fresh welcome message should appear",
).toContain("Welcome to Fresh");
// Check for counter buttons (verifies island is rendered)
expect(
html,
"Counter buttons should be present",
).toContain('id="increment"');
expect(
html,
"Counter buttons should be present",
).toContain('id="decrement"');
// Check for logo
expect(
html,
"Fresh logo should be present",
).toContain("logo.svg");
// Test the API route
const apiRes = await fetch(`${address}/api/fresh`);
expect(apiRes.status).toBe(200);
const greeting = await apiRes.text();
expect(greeting, "API should return greeting").toBe("Hello, Fresh!");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - builder dev server works",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder-dev");
await initTestProject(tmp.dir, "test-builder-dev", true, false);
// Start dev server and verify it works
await withChildProcessServer(
{
cwd: projectDir,
args: ["task", "dev"],
},
async (address) => {
// Verify the home page responds with correct content
const res = await fetch(address);
expect(res.status).toBe(200);
const html = await res.text();
// Check for Fresh welcome message
expect(
html,
"Fresh welcome message should appear",
).toContain("Welcome to Fresh");
// Check for counter buttons (verifies island is rendered)
expect(
html,
"Counter buttons should be present",
).toContain('id="increment"');
expect(
html,
"Counter buttons should be present",
).toContain('id="decrement"');
// Check for logo
expect(
html,
"Fresh logo should be present",
).toContain("logo.svg");
// Test the API route
const apiRes = await fetch(`${address}/api/fresh`);
expect(apiRes.status).toBe(200);
const greeting = await apiRes.text();
expect(greeting, "API should return greeting").toBe("Hello, Fresh!");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
+379
View File
@@ -0,0 +1,379 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import * as fs from "@std/fs";
/**
* Helper to create a temporary directory structure for testing
*/
async function createTestStructure(baseDir: string): Promise<void> {
// Create base template structure
const baseVite = path.join(baseDir, "assets/base/vite");
const baseBuilder = path.join(baseDir, "assets/base/builder");
await fs.ensureDir(path.join(baseVite, "components"));
await fs.ensureDir(path.join(baseVite, "routes"));
await fs.ensureDir(path.join(baseBuilder, "components"));
await fs.ensureDir(path.join(baseBuilder, "static"));
// Create common files
await Deno.writeTextFile(
path.join(baseVite, "main.ts"),
"export const app = new App();",
);
await Deno.writeTextFile(
path.join(baseVite, "components/Button.tsx"),
"export function Button() {}",
);
await Deno.writeTextFile(
path.join(baseVite, "routes/index.tsx"),
"export default function Home() {}",
);
await Deno.writeTextFile(
path.join(baseBuilder, "main.ts"),
"export const app = new App();",
);
await Deno.writeTextFile(
path.join(baseBuilder, "components/Button.tsx"),
"export function Button() {}",
);
// Create template directories
const templateVite = path.join(baseDir, "assets/template/vite");
const templateViteTailwind = path.join(
baseDir,
"assets/template/vite-tailwind",
);
const templateBuilder = path.join(baseDir, "assets/template/builder");
const templateBuilderTailwind = path.join(
baseDir,
"assets/template/builder-tailwind",
);
await fs.ensureDir(templateVite);
await fs.ensureDir(templateViteTailwind);
await fs.ensureDir(templateBuilder);
await fs.ensureDir(templateBuilderTailwind);
// Create template-specific files
await Deno.writeTextFile(
path.join(templateVite, "deno.json.tmpl"),
'{"imports": {"vite": "npm:vite"}}',
);
await Deno.writeTextFile(
path.join(templateViteTailwind, "deno.json.tmpl"),
'{"imports": {"vite": "npm:vite", "tailwind": "npm:tailwindcss"}}',
);
await Deno.writeTextFile(
path.join(templateVite, "vite.config.ts"),
"export default { plugins: [] }",
);
await Deno.writeTextFile(
path.join(templateViteTailwind, "vite.config.ts"),
"export default { plugins: [tailwind()] }",
);
await fs.ensureDir(path.join(templateVite, "assets"));
await fs.ensureDir(path.join(templateViteTailwind, "assets"));
await Deno.writeTextFile(
path.join(templateVite, "assets/styles.css"),
".fresh { color: blue; }",
);
await Deno.writeTextFile(
path.join(templateViteTailwind, "assets/styles.css"),
"@import 'tailwindcss';",
);
await fs.ensureDir(path.join(templateBuilder, "static"));
await fs.ensureDir(path.join(templateBuilderTailwind, "static"));
await Deno.writeTextFile(
path.join(templateBuilder, "static/styles.css"),
".fresh { color: blue; }",
);
await Deno.writeTextFile(
path.join(templateBuilderTailwind, "static/styles.css"),
"@import 'tailwindcss';",
);
}
/**
* Test that isTemplateSpecific correctly identifies template-specific files
*/
Deno.test("isTemplateSpecific - identifies template-specific files", () => {
// Import the function from the script
const TEMPLATE_SPECIFIC_FILES = [
"deno.json.tmpl",
"deno.json",
"vite.config.ts",
"assets/styles.css",
"static/styles.css",
];
function isTemplateSpecific(relPath: string): boolean {
return TEMPLATE_SPECIFIC_FILES.some((specific) =>
relPath === specific || relPath.endsWith(`/${specific}`)
);
}
// Should return true for template-specific files
expect(isTemplateSpecific("deno.json.tmpl")).toBe(true);
expect(isTemplateSpecific("vite.config.ts")).toBe(true);
expect(isTemplateSpecific("assets/styles.css")).toBe(true);
expect(isTemplateSpecific("static/styles.css")).toBe(true);
expect(isTemplateSpecific("path/to/deno.json.tmpl")).toBe(true);
// Should return false for common files
expect(isTemplateSpecific("main.ts")).toBe(false);
expect(isTemplateSpecific("components/Button.tsx")).toBe(false);
expect(isTemplateSpecific("routes/index.tsx")).toBe(false);
expect(isTemplateSpecific("README.md")).toBe(false);
});
/**
* Test sync in dry-run mode
*/
Deno.test("sync_templates - dry run does not modify files", async () => {
const tmpDir = await Deno.makeTempDir();
try {
await createTestStructure(tmpDir);
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run sync in dry-run mode
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
"--dry-run",
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await process.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("DRY RUN MODE");
expect(output).toContain("would be copied");
// Verify templates are still empty (dry run didn't copy)
const viteMain = path.join(tmpDir, "assets/template/vite/main.ts");
const exists = await fs.exists(viteMain);
expect(exists).toBe(false);
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
/**
* Test actual sync operation
*/
Deno.test("sync_templates - syncs common files correctly", async () => {
const tmpDir = await Deno.makeTempDir();
try {
await createTestStructure(tmpDir);
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run actual sync
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await process.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("Sync complete");
// Verify common files were copied
const viteMain = path.join(tmpDir, "assets/template/vite/main.ts");
const viteButton = path.join(
tmpDir,
"assets/template/vite/components/Button.tsx",
);
const viteTailwindMain = path.join(
tmpDir,
"assets/template/vite-tailwind/main.ts",
);
expect(await fs.exists(viteMain)).toBe(true);
expect(await fs.exists(viteButton)).toBe(true);
expect(await fs.exists(viteTailwindMain)).toBe(true);
// Verify content is correct
const mainContent = await Deno.readTextFile(viteMain);
expect(mainContent).toBe("export const app = new App();");
// Verify template-specific files were NOT overwritten
const viteDeno = path.join(tmpDir, "assets/template/vite/deno.json.tmpl");
const viteConfig = path.join(tmpDir, "assets/template/vite/vite.config.ts");
const viteStyles = path.join(
tmpDir,
"assets/template/vite/assets/styles.css",
);
const denoContent = await Deno.readTextFile(viteDeno);
const configContent = await Deno.readTextFile(viteConfig);
const stylesContent = await Deno.readTextFile(viteStyles);
expect(denoContent).toBe('{"imports": {"vite": "npm:vite"}}');
expect(configContent).toBe("export default { plugins: [] }");
expect(stylesContent).toBe(".fresh { color: blue; }");
// Verify tailwind variant has different template-specific files
const viteTailwindDeno = path.join(
tmpDir,
"assets/template/vite-tailwind/deno.json.tmpl",
);
const viteTailwindConfig = path.join(
tmpDir,
"assets/template/vite-tailwind/vite.config.ts",
);
const viteTailwindStyles = path.join(
tmpDir,
"assets/template/vite-tailwind/assets/styles.css",
);
const tailwindDenoContent = await Deno.readTextFile(viteTailwindDeno);
const tailwindConfigContent = await Deno.readTextFile(viteTailwindConfig);
const tailwindStylesContent = await Deno.readTextFile(viteTailwindStyles);
expect(tailwindDenoContent).toBe(
'{"imports": {"vite": "npm:vite", "tailwind": "npm:tailwindcss"}}',
);
expect(tailwindConfigContent).toBe(
"export default { plugins: [tailwind()] }",
);
expect(tailwindStylesContent).toBe("@import 'tailwindcss';");
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
/**
* Test that sync handles builder templates correctly
*/
Deno.test("sync_templates - syncs builder templates", async () => {
const tmpDir = await Deno.makeTempDir();
try {
await createTestStructure(tmpDir);
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run sync
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code } = await process.output();
expect(code).toBe(0);
// Verify builder files were copied
const builderMain = path.join(tmpDir, "assets/template/builder/main.ts");
const builderButton = path.join(
tmpDir,
"assets/template/builder/components/Button.tsx",
);
const builderTailwindMain = path.join(
tmpDir,
"assets/template/builder-tailwind/main.ts",
);
expect(await fs.exists(builderMain)).toBe(true);
expect(await fs.exists(builderButton)).toBe(true);
expect(await fs.exists(builderTailwindMain)).toBe(true);
// Verify template-specific files were preserved
const builderStyles = path.join(
tmpDir,
"assets/template/builder/static/styles.css",
);
const builderTailwindStyles = path.join(
tmpDir,
"assets/template/builder-tailwind/static/styles.css",
);
const stylesContent = await Deno.readTextFile(builderStyles);
const tailwindStylesContent = await Deno.readTextFile(
builderTailwindStyles,
);
expect(stylesContent).toBe(".fresh { color: blue; }");
expect(tailwindStylesContent).toBe("@import 'tailwindcss';");
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
/**
* Test error handling when base directory doesn't exist
*/
Deno.test("sync_templates - handles missing base directory", async () => {
const tmpDir = await Deno.makeTempDir();
try {
// Create only template directories, not base
await fs.ensureDir(path.join(tmpDir, "assets/template/vite"));
await fs.ensureDir(path.join(tmpDir, "assets/template/vite-tailwind"));
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run sync (should handle missing base gracefully)
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await process.output();
const output = new TextDecoder().decode(stdout);
// Should complete but report errors
expect(code).toBe(0);
expect(output).toContain("error");
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
+219
View File
@@ -0,0 +1,219 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { getTemplateDir, getVariantsDir } from "../src/utils.ts";
Deno.test("vite - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "vite");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"vite.config.ts",
"main.ts",
"client.ts",
"utils.ts",
"assets/styles.css",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("vite-tailwind - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"vite.config.ts",
"main.ts",
"client.ts",
"utils.ts",
"assets/styles.css",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("builder - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "builder");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"dev.ts",
"main.ts",
"utils.ts",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/styles.css",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("builder-tailwind - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "builder-tailwind");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"dev.ts",
"main.ts",
"utils.ts",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/styles.css",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("vite deno.json - contains template variables", async () => {
const templateDir = path.join(getTemplateDir(), "vite");
const denoJsonPath = path.join(templateDir, "deno.json");
const content = await Deno.readTextFile(denoJsonPath);
expect(content).toContain("__FRESH_VERSION__");
expect(content).toContain("__PREACT_VERSION__");
expect(content).toContain("__PREACT_SIGNALS_VERSION__");
expect(content).toContain("__VITE_VERSION__");
});
Deno.test("vite-tailwind deno.json - contains Tailwind dependencies", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const denoJsonPath = path.join(templateDir, "deno.json");
const content = await Deno.readTextFile(denoJsonPath);
expect(content).toContain("__TAILWINDCSS_VERSION__");
expect(content).toContain("__TAILWINDCSS_VITE_VERSION__");
});
Deno.test("vite-tailwind vite.config.ts - imports Tailwind", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const configPath = path.join(templateDir, "vite.config.ts");
const content = await Deno.readTextFile(configPath);
expect(content).toContain("@tailwindcss/vite");
expect(content).toContain("tailwindcss()");
});
Deno.test("vite-tailwind assets/styles.css - uses Tailwind", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const cssPath = path.join(templateDir, "assets/styles.css");
const content = await Deno.readTextFile(cssPath);
expect(content).toContain('@import "tailwindcss"');
});
Deno.test("builder-tailwind deno.json - contains Tailwind dependencies", async () => {
const templateDir = path.join(getTemplateDir(), "builder-tailwind");
const denoJsonPath = path.join(templateDir, "deno.json");
const content = await Deno.readTextFile(denoJsonPath);
expect(content).toContain("__TAILWINDCSS_VERSION__");
expect(content).toContain("__FRESH_TAILWIND_VERSION__");
});
Deno.test("builder-tailwind static/styles.css - uses Tailwind", async () => {
const templateDir = path.join(getTemplateDir(), "builder-tailwind");
const cssPath = path.join(templateDir, "static/styles.css");
const content = await Deno.readTextFile(cssPath);
expect(content).toContain('@import "tailwindcss"');
});
Deno.test("vite _app.tsx - contains PROJECT_NAME variable", async () => {
const templateDir = path.join(getTemplateDir(), "vite");
const appPath = path.join(templateDir, "routes/_app.tsx");
const content = await Deno.readTextFile(appPath);
expect(content).toContain("__PROJECT_NAME__");
});
Deno.test("variants/docker - has Dockerfile", async () => {
const variantDir = path.join(getVariantsDir(), "docker");
const dockerfilePath = path.join(variantDir, "Dockerfile");
const stat = await Deno.stat(dockerfilePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
const content = await Deno.readTextFile(dockerfilePath);
expect(content).toContain("__DENO_VERSION__");
});
Deno.test("variants/vscode - has required files", async () => {
const variantDir = path.join(getVariantsDir(), "vscode");
const requiredFiles = [
"__vscode/settings.json",
"__vscode/extensions.json",
];
for (const file of requiredFiles) {
const filePath = path.join(variantDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("variants/vscode-tailwind - has tailwind.json", async () => {
const variantDir = path.join(getVariantsDir(), "vscode-tailwind");
const tailwindJsonPath = path.join(variantDir, "__vscode/tailwind.json");
const stat = await Deno.stat(tailwindJsonPath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
// Check content
const content = JSON.parse(await Deno.readTextFile(tailwindJsonPath));
expect(content.version).toBe(1.1);
expect(content.atDirectives).toBeTruthy();
expect(content.atDirectives.length).toBeGreaterThan(0);
expect(content.atDirectives[0].name).toBe("@tailwind");
});
+82
View File
@@ -0,0 +1,82 @@
import { expect } from "@std/expect";
import {
getLatestVersion,
isDirectoryEmpty,
processFilename,
substituteVariables,
} from "../src/utils.ts";
Deno.test("processFilename - converts double underscore prefix to dot", () => {
expect(processFilename("__gitignore")).toBe(".gitignore");
expect(processFilename("__vscode")).toBe(".vscode");
expect(processFilename("_app.tsx")).toBe("_app.tsx");
expect(processFilename("regular-file.ts")).toBe("regular-file.ts");
});
Deno.test("substituteVariables - replaces template variables", () => {
const template = "Hello __NAME__, version __VERSION__!";
const variables = { NAME: "Fresh", VERSION: "2.0.0" };
const result = substituteVariables(template, variables);
expect(result).toBe("Hello Fresh, version 2.0.0!");
});
Deno.test("substituteVariables - handles multiple occurrences", () => {
const template = "__X__ + __X__ = __Y__";
const variables = { X: "1", Y: "2" };
const result = substituteVariables(template, variables);
expect(result).toBe("1 + 1 = 2");
});
Deno.test("substituteVariables - handles boolean values", () => {
const template = "Enabled: __ENABLED__";
const variables = { ENABLED: true };
const result = substituteVariables(template, variables);
expect(result).toBe("Enabled: true");
});
Deno.test("isDirectoryEmpty - returns true for non-existent directory", async () => {
const isEmpty = await isDirectoryEmpty("/non/existent/path");
expect(isEmpty).toBe(true);
});
Deno.test("isDirectoryEmpty - returns false for directory with files", async () => {
const tempDir = await Deno.makeTempDir();
await Deno.writeTextFile(`${tempDir}/test.txt`, "test");
const isEmpty = await isDirectoryEmpty(tempDir);
expect(isEmpty).toBe(false);
await Deno.remove(tempDir, { recursive: true });
});
Deno.test("isDirectoryEmpty - returns true for empty directory", async () => {
const tempDir = await Deno.makeTempDir();
const isEmpty = await isDirectoryEmpty(tempDir);
expect(isEmpty).toBe(true);
await Deno.remove(tempDir);
});
Deno.test("isDirectoryEmpty - returns true for directory with only .git", async () => {
const tempDir = await Deno.makeTempDir();
await Deno.mkdir(`${tempDir}/.git`);
const isEmpty = await isDirectoryEmpty(tempDir);
expect(isEmpty).toBe(true);
await Deno.remove(tempDir, { recursive: true });
});
Deno.test("getLatestVersion - returns fallback on error", async () => {
const version = await getLatestVersion("@nonexistent/package", "1.0.0");
expect(version).toBe("1.0.0");
});
Deno.test("getLatestVersion - fetches real version", async () => {
// This test requires network access
const version = await getLatestVersion("@std/assert", "0.0.1");
expect(version).toBeTruthy();
// Should return something other than fallback
// (unless there's a network error, in which case it returns fallback)
});