diff --git a/deno.lock b/deno.lock index e9f2382a..9850a590 100644 --- a/deno.lock +++ b/deno.lock @@ -19,7 +19,6 @@ "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", @@ -30,7 +29,6 @@ "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", @@ -3754,16 +3752,6 @@ "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", diff --git a/packages/init/DESIGN.md b/packages/init/DESIGN.md deleted file mode 100644 index b95fe053..00000000 --- a/packages/init/DESIGN.md +++ /dev/null @@ -1,135 +0,0 @@ -# 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 diff --git a/packages/init/README.md b/packages/init/README.md index c7d0b936..eec288dd 100644 --- a/packages/init/README.md +++ b/packages/init/README.md @@ -1,62 +1,10 @@ -# @fresh/init +# Create a new Fresh project. -Template-based initialization system for Fresh projects. +This is a CLI tool to bootstrap a new Fresh project. To do so, run this command: -## 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 +```sh +deno run -Ar jsr:@fresh/init ``` -**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. +Go to [https://fresh.deno.dev/](https://fresh.deno.dev/) for more information +about Fresh. diff --git a/packages/init/assets/base/builder/README.md b/packages/init/assets/base/builder/README.md deleted file mode 100644 index b2e551fd..00000000 --- a/packages/init/assets/base/builder/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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. diff --git a/packages/init/assets/base/builder/__gitignore b/packages/init/assets/base/builder/__gitignore deleted file mode 100644 index 0735100f..00000000 --- a/packages/init/assets/base/builder/__gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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/ - diff --git a/packages/init/assets/base/builder/components/Button.tsx b/packages/init/assets/base/builder/components/Button.tsx deleted file mode 100644 index 71eaf7f4..00000000 --- a/packages/init/assets/base/builder/components/Button.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -} diff --git a/packages/init/assets/base/builder/main.ts b/packages/init/assets/base/builder/main.ts deleted file mode 100644 index 350d652b..00000000 --- a/packages/init/assets/base/builder/main.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -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(); diff --git a/packages/init/assets/base/builder/routes/_app.tsx b/packages/init/assets/base/builder/routes/_app.tsx deleted file mode 100644 index 5c727303..00000000 --- a/packages/init/assets/base/builder/routes/_app.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { define } from "../utils.ts"; - -export default define.page(function App({ Component }) { - return ( - - - - - __PROJECT_NAME__ - - - - - - - ); -}); diff --git a/packages/init/assets/base/builder/routes/api/[name].tsx b/packages/init/assets/base/builder/routes/api/[name].tsx deleted file mode 100644 index 0c972482..00000000 --- a/packages/init/assets/base/builder/routes/api/[name].tsx +++ /dev/null @@ -1,10 +0,0 @@ -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)}!`, - ); - }, -}); diff --git a/packages/init/assets/base/builder/routes/index.tsx b/packages/init/assets/base/builder/routes/index.tsx deleted file mode 100644 index 74e9ebcc..00000000 --- a/packages/init/assets/base/builder/routes/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 ( -
- - Fresh counter - -
- the Fresh logo: a sliced lemon dripping with juice -

Welcome to Fresh

-

- Try updating this message in the - ./routes/index.tsx file, and refresh. -

- -
-
- ); -}); diff --git a/packages/init/assets/base/builder/static/logo.svg b/packages/init/assets/base/builder/static/logo.svg deleted file mode 100644 index 5b99e0b1..00000000 --- a/packages/init/assets/base/builder/static/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/packages/init/assets/base/builder/utils.ts b/packages/init/assets/base/builder/utils.ts deleted file mode 100644 index f404216e..00000000 --- a/packages/init/assets/base/builder/utils.ts +++ /dev/null @@ -1,9 +0,0 @@ -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(); diff --git a/packages/init/assets/base/vite/README.md b/packages/init/assets/base/vite/README.md deleted file mode 100644 index b2e551fd..00000000 --- a/packages/init/assets/base/vite/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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. diff --git a/packages/init/assets/base/vite/__gitignore b/packages/init/assets/base/vite/__gitignore deleted file mode 100644 index 0735100f..00000000 --- a/packages/init/assets/base/vite/__gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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/ - diff --git a/packages/init/assets/base/vite/components/Button.tsx b/packages/init/assets/base/vite/components/Button.tsx deleted file mode 100644 index 71eaf7f4..00000000 --- a/packages/init/assets/base/vite/components/Button.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -} diff --git a/packages/init/assets/base/vite/main.ts b/packages/init/assets/base/vite/main.ts deleted file mode 100644 index 350d652b..00000000 --- a/packages/init/assets/base/vite/main.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -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(); diff --git a/packages/init/assets/base/vite/routes/_app.tsx b/packages/init/assets/base/vite/routes/_app.tsx deleted file mode 100644 index e527fa36..00000000 --- a/packages/init/assets/base/vite/routes/_app.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { define } from "../utils.ts"; - -export default define.page(function App({ Component }) { - return ( - - - - - __PROJECT_NAME__ - - - - - - ); -}); diff --git a/packages/init/assets/base/vite/routes/api/[name].tsx b/packages/init/assets/base/vite/routes/api/[name].tsx deleted file mode 100644 index 0c972482..00000000 --- a/packages/init/assets/base/vite/routes/api/[name].tsx +++ /dev/null @@ -1,10 +0,0 @@ -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)}!`, - ); - }, -}); diff --git a/packages/init/assets/base/vite/routes/index.tsx b/packages/init/assets/base/vite/routes/index.tsx deleted file mode 100644 index 74e9ebcc..00000000 --- a/packages/init/assets/base/vite/routes/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 ( -
- - Fresh counter - -
- the Fresh logo: a sliced lemon dripping with juice -

Welcome to Fresh

-

- Try updating this message in the - ./routes/index.tsx file, and refresh. -

- -
-
- ); -}); diff --git a/packages/init/assets/base/vite/static/logo.svg b/packages/init/assets/base/vite/static/logo.svg deleted file mode 100644 index 5b99e0b1..00000000 --- a/packages/init/assets/base/vite/static/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/packages/init/assets/base/vite/utils.ts b/packages/init/assets/base/vite/utils.ts deleted file mode 100644 index f404216e..00000000 --- a/packages/init/assets/base/vite/utils.ts +++ /dev/null @@ -1,9 +0,0 @@ -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(); diff --git a/packages/init/assets/template/builder-tailwind/README.md b/packages/init/assets/template/builder-tailwind/README.md deleted file mode 100644 index b2e551fd..00000000 --- a/packages/init/assets/template/builder-tailwind/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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. diff --git a/packages/init/assets/template/builder-tailwind/__gitignore b/packages/init/assets/template/builder-tailwind/__gitignore deleted file mode 100644 index 0735100f..00000000 --- a/packages/init/assets/template/builder-tailwind/__gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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/ - diff --git a/packages/init/assets/template/builder-tailwind/components/Button.tsx b/packages/init/assets/template/builder-tailwind/components/Button.tsx deleted file mode 100644 index 71eaf7f4..00000000 --- a/packages/init/assets/template/builder-tailwind/components/Button.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -} diff --git a/packages/init/assets/template/builder-tailwind/main.ts b/packages/init/assets/template/builder-tailwind/main.ts deleted file mode 100644 index 350d652b..00000000 --- a/packages/init/assets/template/builder-tailwind/main.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -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(); diff --git a/packages/init/assets/template/builder-tailwind/routes/_app.tsx b/packages/init/assets/template/builder-tailwind/routes/_app.tsx deleted file mode 100644 index 5c727303..00000000 --- a/packages/init/assets/template/builder-tailwind/routes/_app.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { define } from "../utils.ts"; - -export default define.page(function App({ Component }) { - return ( - - - - - __PROJECT_NAME__ - - - - - - - ); -}); diff --git a/packages/init/assets/template/builder-tailwind/routes/api/[name].tsx b/packages/init/assets/template/builder-tailwind/routes/api/[name].tsx deleted file mode 100644 index 0c972482..00000000 --- a/packages/init/assets/template/builder-tailwind/routes/api/[name].tsx +++ /dev/null @@ -1,10 +0,0 @@ -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)}!`, - ); - }, -}); diff --git a/packages/init/assets/template/builder-tailwind/routes/index.tsx b/packages/init/assets/template/builder-tailwind/routes/index.tsx deleted file mode 100644 index 74e9ebcc..00000000 --- a/packages/init/assets/template/builder-tailwind/routes/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 ( -
- - Fresh counter - -
- the Fresh logo: a sliced lemon dripping with juice -

Welcome to Fresh

-

- Try updating this message in the - ./routes/index.tsx file, and refresh. -

- -
-
- ); -}); diff --git a/packages/init/assets/template/builder-tailwind/static/logo.svg b/packages/init/assets/template/builder-tailwind/static/logo.svg deleted file mode 100644 index 5b99e0b1..00000000 --- a/packages/init/assets/template/builder-tailwind/static/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/packages/init/assets/template/builder-tailwind/static/styles.css b/packages/init/assets/template/builder-tailwind/static/styles.css deleted file mode 100644 index 5d8109d8..00000000 --- a/packages/init/assets/template/builder-tailwind/static/styles.css +++ /dev/null @@ -1,10 +0,0 @@ -@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) - ); -} diff --git a/packages/init/assets/template/builder-tailwind/utils.ts b/packages/init/assets/template/builder-tailwind/utils.ts deleted file mode 100644 index f404216e..00000000 --- a/packages/init/assets/template/builder-tailwind/utils.ts +++ /dev/null @@ -1,9 +0,0 @@ -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(); diff --git a/packages/init/assets/template/builder/README.md b/packages/init/assets/template/builder/README.md deleted file mode 100644 index b2e551fd..00000000 --- a/packages/init/assets/template/builder/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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. diff --git a/packages/init/assets/template/builder/__gitignore b/packages/init/assets/template/builder/__gitignore deleted file mode 100644 index 0735100f..00000000 --- a/packages/init/assets/template/builder/__gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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/ - diff --git a/packages/init/assets/template/builder/components/Button.tsx b/packages/init/assets/template/builder/components/Button.tsx deleted file mode 100644 index 71eaf7f4..00000000 --- a/packages/init/assets/template/builder/components/Button.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -} diff --git a/packages/init/assets/template/builder/main.ts b/packages/init/assets/template/builder/main.ts deleted file mode 100644 index 350d652b..00000000 --- a/packages/init/assets/template/builder/main.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -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(); diff --git a/packages/init/assets/template/builder/routes/_app.tsx b/packages/init/assets/template/builder/routes/_app.tsx deleted file mode 100644 index 5c727303..00000000 --- a/packages/init/assets/template/builder/routes/_app.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { define } from "../utils.ts"; - -export default define.page(function App({ Component }) { - return ( - - - - - __PROJECT_NAME__ - - - - - - - ); -}); diff --git a/packages/init/assets/template/builder/routes/api/[name].tsx b/packages/init/assets/template/builder/routes/api/[name].tsx deleted file mode 100644 index 0c972482..00000000 --- a/packages/init/assets/template/builder/routes/api/[name].tsx +++ /dev/null @@ -1,10 +0,0 @@ -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)}!`, - ); - }, -}); diff --git a/packages/init/assets/template/builder/routes/index.tsx b/packages/init/assets/template/builder/routes/index.tsx deleted file mode 100644 index 74e9ebcc..00000000 --- a/packages/init/assets/template/builder/routes/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 ( -
- - Fresh counter - -
- the Fresh logo: a sliced lemon dripping with juice -

Welcome to Fresh

-

- Try updating this message in the - ./routes/index.tsx file, and refresh. -

- -
-
- ); -}); diff --git a/packages/init/assets/template/builder/static/logo.svg b/packages/init/assets/template/builder/static/logo.svg deleted file mode 100644 index 5b99e0b1..00000000 --- a/packages/init/assets/template/builder/static/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/packages/init/assets/template/builder/static/styles.css b/packages/init/assets/template/builder/static/styles.css deleted file mode 100644 index 21c911c4..00000000 --- a/packages/init/assets/template/builder/static/styles.css +++ /dev/null @@ -1,144 +0,0 @@ -*, -*::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) - ); -} diff --git a/packages/init/assets/template/builder/utils.ts b/packages/init/assets/template/builder/utils.ts deleted file mode 100644 index f404216e..00000000 --- a/packages/init/assets/template/builder/utils.ts +++ /dev/null @@ -1,9 +0,0 @@ -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(); diff --git a/packages/init/assets/template/vite-tailwind/README.md b/packages/init/assets/template/vite-tailwind/README.md deleted file mode 100644 index b2e551fd..00000000 --- a/packages/init/assets/template/vite-tailwind/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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. diff --git a/packages/init/assets/template/vite-tailwind/__gitignore b/packages/init/assets/template/vite-tailwind/__gitignore deleted file mode 100644 index 0735100f..00000000 --- a/packages/init/assets/template/vite-tailwind/__gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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/ - diff --git a/packages/init/assets/template/vite-tailwind/assets/styles.css b/packages/init/assets/template/vite-tailwind/assets/styles.css deleted file mode 100644 index 5d8109d8..00000000 --- a/packages/init/assets/template/vite-tailwind/assets/styles.css +++ /dev/null @@ -1,10 +0,0 @@ -@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) - ); -} diff --git a/packages/init/assets/template/vite-tailwind/client.ts b/packages/init/assets/template/vite-tailwind/client.ts deleted file mode 100644 index 016cb078..00000000 --- a/packages/init/assets/template/vite-tailwind/client.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Import CSS files here for hot module reloading to work. -import "./assets/styles.css"; diff --git a/packages/init/assets/template/vite-tailwind/components/Button.tsx b/packages/init/assets/template/vite-tailwind/components/Button.tsx deleted file mode 100644 index 71eaf7f4..00000000 --- a/packages/init/assets/template/vite-tailwind/components/Button.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -} diff --git a/packages/init/assets/template/vite-tailwind/main.ts b/packages/init/assets/template/vite-tailwind/main.ts deleted file mode 100644 index 350d652b..00000000 --- a/packages/init/assets/template/vite-tailwind/main.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -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(); diff --git a/packages/init/assets/template/vite-tailwind/routes/_app.tsx b/packages/init/assets/template/vite-tailwind/routes/_app.tsx deleted file mode 100644 index e527fa36..00000000 --- a/packages/init/assets/template/vite-tailwind/routes/_app.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { define } from "../utils.ts"; - -export default define.page(function App({ Component }) { - return ( - - - - - __PROJECT_NAME__ - - - - - - ); -}); diff --git a/packages/init/assets/template/vite-tailwind/routes/api/[name].tsx b/packages/init/assets/template/vite-tailwind/routes/api/[name].tsx deleted file mode 100644 index 0c972482..00000000 --- a/packages/init/assets/template/vite-tailwind/routes/api/[name].tsx +++ /dev/null @@ -1,10 +0,0 @@ -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)}!`, - ); - }, -}); diff --git a/packages/init/assets/template/vite-tailwind/routes/index.tsx b/packages/init/assets/template/vite-tailwind/routes/index.tsx deleted file mode 100644 index 74e9ebcc..00000000 --- a/packages/init/assets/template/vite-tailwind/routes/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 ( -
- - Fresh counter - -
- the Fresh logo: a sliced lemon dripping with juice -

Welcome to Fresh

-

- Try updating this message in the - ./routes/index.tsx file, and refresh. -

- -
-
- ); -}); diff --git a/packages/init/assets/template/vite-tailwind/static/logo.svg b/packages/init/assets/template/vite-tailwind/static/logo.svg deleted file mode 100644 index 5b99e0b1..00000000 --- a/packages/init/assets/template/vite-tailwind/static/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/packages/init/assets/template/vite-tailwind/utils.ts b/packages/init/assets/template/vite-tailwind/utils.ts deleted file mode 100644 index f404216e..00000000 --- a/packages/init/assets/template/vite-tailwind/utils.ts +++ /dev/null @@ -1,9 +0,0 @@ -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(); diff --git a/packages/init/assets/template/vite-tailwind/vite.config.ts b/packages/init/assets/template/vite-tailwind/vite.config.ts deleted file mode 100644 index 67a37d03..00000000 --- a/packages/init/assets/template/vite-tailwind/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from "vite"; -import { fresh } from "@fresh/plugin-vite"; -import tailwindcss from "@tailwindcss/vite"; - -export default defineConfig({ - plugins: [fresh(), tailwindcss()], -}); diff --git a/packages/init/assets/template/vite/README.md b/packages/init/assets/template/vite/README.md deleted file mode 100644 index b2e551fd..00000000 --- a/packages/init/assets/template/vite/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# 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. diff --git a/packages/init/assets/template/vite/__gitignore b/packages/init/assets/template/vite/__gitignore deleted file mode 100644 index 0735100f..00000000 --- a/packages/init/assets/template/vite/__gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# 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/ - diff --git a/packages/init/assets/template/vite/assets/styles.css b/packages/init/assets/template/vite/assets/styles.css deleted file mode 100644 index 21c911c4..00000000 --- a/packages/init/assets/template/vite/assets/styles.css +++ /dev/null @@ -1,144 +0,0 @@ -*, -*::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) - ); -} diff --git a/packages/init/assets/template/vite/client.ts b/packages/init/assets/template/vite/client.ts deleted file mode 100644 index 016cb078..00000000 --- a/packages/init/assets/template/vite/client.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Import CSS files here for hot module reloading to work. -import "./assets/styles.css"; diff --git a/packages/init/assets/template/vite/components/Button.tsx b/packages/init/assets/template/vite/components/Button.tsx deleted file mode 100644 index 71eaf7f4..00000000 --- a/packages/init/assets/template/vite/components/Button.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import type { ComponentChildren } from "preact"; - -export interface ButtonProps { - id?: string; - onClick?: () => void; - children?: ComponentChildren; - disabled?: boolean; -} - -export function Button(props: ButtonProps) { - return ( - -

{props.count}

- - - ); -} diff --git a/packages/init/assets/template/vite/main.ts b/packages/init/assets/template/vite/main.ts deleted file mode 100644 index 350d652b..00000000 --- a/packages/init/assets/template/vite/main.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { App, staticFiles } from "fresh"; -import { define, type State } from "./utils.ts"; - -export const app = new App(); - -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(); diff --git a/packages/init/assets/template/vite/routes/_app.tsx b/packages/init/assets/template/vite/routes/_app.tsx deleted file mode 100644 index e527fa36..00000000 --- a/packages/init/assets/template/vite/routes/_app.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { define } from "../utils.ts"; - -export default define.page(function App({ Component }) { - return ( - - - - - __PROJECT_NAME__ - - - - - - ); -}); diff --git a/packages/init/assets/template/vite/routes/api/[name].tsx b/packages/init/assets/template/vite/routes/api/[name].tsx deleted file mode 100644 index 0c972482..00000000 --- a/packages/init/assets/template/vite/routes/api/[name].tsx +++ /dev/null @@ -1,10 +0,0 @@ -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)}!`, - ); - }, -}); diff --git a/packages/init/assets/template/vite/routes/index.tsx b/packages/init/assets/template/vite/routes/index.tsx deleted file mode 100644 index 74e9ebcc..00000000 --- a/packages/init/assets/template/vite/routes/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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 ( -
- - Fresh counter - -
- the Fresh logo: a sliced lemon dripping with juice -

Welcome to Fresh

-

- Try updating this message in the - ./routes/index.tsx file, and refresh. -

- -
-
- ); -}); diff --git a/packages/init/assets/template/vite/static/logo.svg b/packages/init/assets/template/vite/static/logo.svg deleted file mode 100644 index 5b99e0b1..00000000 --- a/packages/init/assets/template/vite/static/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/packages/init/assets/template/vite/utils.ts b/packages/init/assets/template/vite/utils.ts deleted file mode 100644 index f404216e..00000000 --- a/packages/init/assets/template/vite/utils.ts +++ /dev/null @@ -1,9 +0,0 @@ -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(); diff --git a/packages/init/assets/template/vite/vite.config.ts b/packages/init/assets/template/vite/vite.config.ts deleted file mode 100644 index 727d49a2..00000000 --- a/packages/init/assets/template/vite/vite.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { defineConfig } from "vite"; -import { fresh } from "@fresh/plugin-vite"; - -export default defineConfig({ - plugins: [fresh()], -}); diff --git a/packages/init/assets/variants/docker/Dockerfile b/packages/init/assets/variants/docker/Dockerfile deleted file mode 100644 index f034f630..00000000 --- a/packages/init/assets/variants/docker/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ - -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"] - diff --git a/packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json b/packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json deleted file mode 100644 index 455f9fcd..00000000 --- a/packages/init/assets/variants/vscode-tailwind/__vscode/extensions.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "recommendations": [ - "denoland.vscode-deno", - "bradlc.vscode-tailwindcss" - ] -} diff --git a/packages/init/assets/variants/vscode-tailwind/__vscode/settings.json b/packages/init/assets/variants/vscode-tailwind/__vscode/settings.json deleted file mode 100644 index bedf1ce5..00000000 --- a/packages/init/assets/variants/vscode-tailwind/__vscode/settings.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "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" - ] -} diff --git a/packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json b/packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json deleted file mode 100644 index 96a1f579..00000000 --- a/packages/init/assets/variants/vscode-tailwind/__vscode/tailwind.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "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" - } - ] - } - ] -} diff --git a/packages/init/assets/variants/vscode/__vscode/extensions.json b/packages/init/assets/variants/vscode/__vscode/extensions.json deleted file mode 100644 index 09cf720d..00000000 --- a/packages/init/assets/variants/vscode/__vscode/extensions.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "recommendations": [ - "denoland.vscode-deno" - ] -} diff --git a/packages/init/assets/variants/vscode/__vscode/settings.json b/packages/init/assets/variants/vscode/__vscode/settings.json deleted file mode 100644 index a5f0701f..00000000 --- a/packages/init/assets/variants/vscode/__vscode/settings.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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" - } -} diff --git a/packages/init/deno.json b/packages/init/deno.json index b1aa1828..cd3615df 100644 --- a/packages/init/deno.json +++ b/packages/init/deno.json @@ -4,37 +4,12 @@ "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", - "tests/", - "DESIGN.md", - "src/sync.ts" - ] + "exclude": ["**/*_test.*", "*.todo"] } } diff --git a/packages/init/src/assets/favicon.ico b/packages/init/src/assets/favicon.ico new file mode 100644 index 00000000..1cfaaa21 Binary files /dev/null and b/packages/init/src/assets/favicon.ico differ diff --git a/packages/init/src/init.ts b/packages/init/src/init.ts index 6d5df6d2..a0160dde 100644 --- a/packages/init/src/init.ts +++ b/packages/init/src/init.ts @@ -1,299 +1,880 @@ +// deno-lint-ignore-file no-console +import * as colors from "@std/fmt/colors"; import * as path from "@std/path"; -import * as fs from "@std/fs"; -import type { - InitOptions, - TemplateVariables, - VersionOverrides, -} from "./types.ts"; -import { - getLatestVersion, - getTemplateDir, - getVariantsDir, - processFilename, - substituteVariables, -} from "./utils.ts"; +import * as semver from "@std/semver"; +import initConfig from "../deno.json" with { type: "json" }; -/** - * Default version constants for dependencies. - * These are updated automatically by the release script (tools/release.ts). - */ +// Keep these as is, as we replace these version in our release script const FRESH_VERSION = "2.1.1"; const FRESH_TAILWIND_VERSION = "1.0.0"; +const FRESH_VITE_PLUGIN = "1.0.0"; const PREACT_VERSION = "10.27.2"; const PREACT_SIGNALS_VERSION = "2.3.1"; - -/** - * Other dependency versions (not automatically updated). - * Update these manually when needed. - */ -const FRESH_VITE_PLUGIN_VERSION = "1.0.0"; const TAILWINDCSS_VERSION = "4.1.10"; const TAILWINDCSS_POSTCSS_VERSION = "4.1.10"; -const TAILWINDCSS_VITE_VERSION = "4.1.12"; const POSTCSS_VERSION = "8.5.6"; -const VITE_VERSION = "7.1.3"; -/** - * Initialize a new Fresh project using templates. - * This is a pure template processor - all validation, prompts, and output - * should be handled by the caller (typically CLI). - * - * @example - * ```ts - * import { initProject, resolveVersions } from "./init.ts"; - * - * const options: InitOptions = { - * directory: "./my-app", - * tailwind: true, - * vscode: false, - * docker: false, - * builder: false, - * force: false, - * }; - * - * const versions = await resolveVersions(); - * await initProject(Deno.cwd(), options, versions); - * ``` - * - * @param cwd - Current working directory - * @param options - Initialization options (optional fields will use defaults) - * @param versions - Pre-resolved version strings (without PROJECT_NAME) - */ +function css(strs: TemplateStringsArray, ...exprs: string[]): string { + let out = ""; + + for (let i = 0; i < exprs.length; i++) { + out += strs[i]; + out += String(exprs[i]); + } + out += strs.at(-1) ?? ""; + + return out; +} + +export class InitError extends Error {} + +function error(message: string): never { + console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", ""); + throw new InitError(); +} + +export 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 +`; + +export const CONFIRM_EMPTY_MESSAGE = + "The target directory is not empty (files could get overwritten). Do you want to continue anyway?"; +export const CONFIRM_TAILWIND_MESSAGE = `Set up ${ + colors.cyan("Tailwind CSS") +} for styling?`; +export const CONFIRM_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`; +export const CONFIRM_VITE_MESSAGE = `Set up ${ + colors.cyan("Vite") +} for build tooling?`; + export async function initProject( - cwd: string, - options: Required, - versions: Omit, + cwd = 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 { - const projectDir = path.resolve(cwd, options.directory); - const projectName = path.basename(projectDir); + const freshVersion = await getLatestVersion("@fresh/core", FRESH_VERSION); - // Boolean flags for template/variant selection (not template variables) - const useVite = !options.builder; - const useTailwind = options.tailwind; - const useVSCode = options.vscode; - const useDocker = options.docker; - - // Template substitution variables (includes PROJECT_NAME + all versions) - const variables: TemplateVariables = { - ...versions, - PROJECT_NAME: projectName, - }; - - // Select complete template based on build system and styling choice - let templateName: string; - if (useVite && useTailwind) { - templateName = "vite-tailwind"; - } else if (useVite) { - templateName = "vite"; - } else if (useTailwind) { - templateName = "builder-tailwind"; - } else { - templateName = "builder"; + if (flags.help || flags.h) { + console.log(HELP_TEXT); + return; } - const templateDir = path.join(getTemplateDir(), templateName); + console.log(); + console.log( + colors.bgRgb8( + colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0), + 121, + ), + ); + console.log(` version ${colors.rgb8(freshVersion, 4)}`); + console.log(); - // Collect truly additive variants (docker, vscode, vscode-tailwind) - const variants: string[] = []; - if (useVSCode) { - variants.push("vscode"); - // Add Tailwind-specific VS Code support if both are enabled - if (useTailwind) { - variants.push("vscode-tailwind"); - } - } - if (useDocker) { - variants.push("docker"); - } - - // Process template - await processTemplate(templateDir, variants, projectDir, variables); - - // Fetch and write favicon - await fetchFavicon(projectDir); -} - -/** - * Resolve all version strings for dependencies. - * - * Version resolution strategy: - * - Only Fresh core version is fetched from network (latest from JSR) - * - All other versions use fixed defaults (updated by release script) - * - * @example - * ```ts - * // Resolve with defaults - * const versions = await resolveVersions(); - * console.log(versions.FRESH_VERSION); // "2.1.1" or latest from network - * - * // Override specific versions (useful for testing) - * const testVersions = await resolveVersions({ - * fresh: "2.0.0", - * preact: "10.20.0", - * }); - * ``` - * - * @param overrides - Optional version overrides for testing or pinning - * @returns Template variables (without PROJECT_NAME, which is added later) - */ -export async function resolveVersions( - overrides?: VersionOverrides, -): Promise> { - // Build default versions object - const defaults = { - fresh: FRESH_VERSION, - freshTailwind: FRESH_TAILWIND_VERSION, - freshVitePlugin: FRESH_VITE_PLUGIN_VERSION, - preact: PREACT_VERSION, - preactSignals: PREACT_SIGNALS_VERSION, - tailwindcss: TAILWINDCSS_VERSION, - tailwindcssPostcss: TAILWINDCSS_POSTCSS_VERSION, - tailwindcssVite: TAILWINDCSS_VITE_VERSION, - postcss: POSTCSS_VERSION, - vite: VITE_VERSION, - }; - - const versions = { ...defaults, ...overrides }; - - // Only fetch latest for Fresh core from JSR - const fresh = await getLatestVersion("@fresh/core", versions.fresh); - - return { - FRESH_VERSION: fresh, - FRESH_TAILWIND_VERSION: versions.freshTailwind, - FRESH_VITE_PLUGIN_VERSION: versions.freshVitePlugin, - // Use fixed versions for Preact and Signals (not fetched from network) - PREACT_VERSION: versions.preact, - PREACT_SIGNALS_VERSION: versions.preactSignals, - TAILWINDCSS_VERSION: versions.tailwindcss, - TAILWINDCSS_POSTCSS_VERSION: versions.tailwindcssPostcss, - TAILWINDCSS_VITE_VERSION: versions.tailwindcssVite, - POSTCSS_VERSION: versions.postcss, - VITE_VERSION: versions.vite, - DENO_VERSION: Deno.version.deno, - }; -} - -/** - * Process a template and write to target directory. - */ -async function processTemplate( - templateDir: string, - variants: string[], - targetDir: string, - variables: TemplateVariables, -): Promise { - // Ensure target directory exists - await fs.ensureDir(targetDir); - - // Copy base template - await processDirectory(templateDir, targetDir, variables); - - // Apply variants - const variantsDir = getVariantsDir(); - for (const variant of variants) { - const variantDir = path.join(variantsDir, variant); - try { - await Deno.stat(variantDir); - await applyVariant(variantDir, targetDir, variables); - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - // Variant doesn't exist, skip it - } - } -} - -/** - * Process a directory, copying and transforming files. - */ -async function processDirectory( - srcDir: string, - destDir: string, - variables: TemplateVariables, -): Promise { - for await (const entry of Deno.readDir(srcDir)) { - const srcPath = path.join(srcDir, entry.name); - - if (entry.isDirectory) { - // Process directory name (convert __ to .) - const destName = processFilename(entry.name); - const destPath = path.join(destDir, destName); - await fs.ensureDir(destPath); - await processDirectory(srcPath, destPath, variables); - } else { - // For files, don't process filename here - processFile will handle it - await processFile(srcPath, destDir, entry.name, variables); - } - } -} - -/** - * Process a single file. - */ -async function processFile( - srcPath: string, - destDir: string, - filename: string, - variables: TemplateVariables, -): Promise { - // Process filename: convert __ prefix to . prefix - const finalName = processFilename(filename); - const destPath = path.join(destDir, finalName); - - // Try to read as text and perform substitution on ALL files - // If file is binary, the copy will fail gracefully and we'll copy as binary - try { - const content = await Deno.readTextFile(srcPath); - const transformed = substituteVariables( - content, - variables as unknown as Record, + let unresolvedDirectory; + if (input.length !== 1) { + const userInput = prompt( + "Project Name:", + "fresh-project", ); - await Deno.writeTextFile(destPath, transformed); - } catch { - // File is binary or unreadable as text, copy as-is - await fs.copy(srcPath, destPath, { overwrite: true }); + if (!userInput) { + error(HELP_TEXT); + } + + unresolvedDirectory = userInput; + } else { + unresolvedDirectory = String(input[0]); } -} -/** - * Apply a variant overlay to the target directory. - * Variants are truly additive - they only add files, don't modify existing ones. - */ -async function applyVariant( - variantDir: string, - targetDir: string, - variables: TemplateVariables, -): Promise { - for await (const entry of Deno.readDir(variantDir)) { - const srcPath = path.join(variantDir, entry.name); + const projectDir = path.resolve(cwd, unresolvedDirectory); - if (entry.isDirectory) { - // Process directory name (convert __ to .) - const destName = processFilename(entry.name); - const destPath = path.join(targetDir, destName); - await fs.ensureDir(destPath); - await processDirectory(srcPath, destPath, variables); - } else { - // Regular file - copy/process - await processFile(srcPath, targetDir, entry.name, variables); + try { + const dir = [...Deno.readDirSync(projectDir)]; + const isEmpty = dir.length === 0 || + dir.length === 1 && dir[0].name === ".git"; + if ( + !isEmpty && + !(flags.force === null ? confirm(CONFIRM_EMPTY_MESSAGE) : flags.force) + ) { + error("Directory is not empty."); + } + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; } } + + const useVite = !flags.builder; + + const useDocker = flags.docker; + let useTailwind = flags.tailwind || false; + if (flags.tailwind == null) { + if ( + confirm(CONFIRM_TAILWIND_MESSAGE) + ) { + useTailwind = true; + } + } + + const useVSCode = flags.vscode == null + ? confirm(CONFIRM_VSCODE_MESSAGE) + : flags.vscode; + + const writeFile = async ( + pathname: string, + content: + | string + | Uint8Array + | ReadableStream + | Record, + ) => await writeProjectFile(projectDir, pathname, content); + + const GITIGNORE = `# 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/ +`; + + await writeFile(".gitignore", GITIGNORE); + + if (useDocker) { + const DENO_VERSION = Deno.version.deno; + const DOCKERFILE_TEXT = ` +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"] + +`; + await writeFile("Dockerfile", DOCKERFILE_TEXT); + } + + // deno-fmt-ignore + const GRADIENT_CSS = css`.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) + ); +}`; + // deno-fmt-ignore + const NO_TAILWIND_STYLES = css`*, +*::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; } -/** - * Fetch and write favicon. - */ -async function fetchFavicon(projectDir: string): Promise { +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; +} + +${GRADIENT_CSS}`; + // deno-fmt-ignore + const TAILWIND_CSS = css`@import "tailwindcss"; +${GRADIENT_CSS}`; + + const cssStyles = useTailwind ? TAILWIND_CSS : NO_TAILWIND_STYLES; + + if (useVite) { + await writeFile("assets/styles.css", cssStyles); + await writeFile( + "client.ts", + `// Import CSS files here for hot module reloading to work. +import "./assets/styles.css";`, + ); + } else { + await writeFile("static/styles.css", cssStyles); + } + // deno-fmt-ignore + const STATIC_LOGO = + ` + + + + +`; + await writeFile("static/logo.svg", STATIC_LOGO); + try { const res = await fetch("https://fresh.deno.dev/favicon.ico"); - if (!res.ok) return; - const buf = await res.arrayBuffer(); - const faviconPath = path.join(projectDir, "static", "favicon.ico"); - await Deno.writeFile(faviconPath, new Uint8Array(buf)); + await writeFile("static/favicon.ico", new Uint8Array(buf)); } catch { - // Silent failure - favicon is not critical + // Skip this and be silent if there is a network issue. + } + + const MAIN_TS = `import { App, staticFiles } from "fresh"; +import { define, type State } from "./utils.ts"; + +export const app = new App(); + +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();`; + await writeFile("main.ts", MAIN_TS); + + const COMPONENTS_BUTTON_TSX = + `import type { ComponentChildren } from "preact"; + +export interface ButtonProps { + id?: string; + onClick?: () => void; + children?: ComponentChildren; + disabled?: boolean; +} + +export function Button(props: ButtonProps) { + return ( + +

{props.count}

+ + + ); +}`; + await writeFile("islands/Counter.tsx", ISLANDS_COUNTER_TSX); + + const DEV_TS = `#!/usr/bin/env -S deno run -A --watch=static/,routes/ +${useTailwind ? `import { tailwind } from "@fresh/plugin-tailwind";\n` : ""} +import { Builder } from "fresh/dev"; + +const builder = new Builder(); +${useTailwind ? "tailwind(builder);" : ""} +if (Deno.args.includes("build")) { + await builder.build(); +} else { + await builder.listen(() => import("./main.ts")); +}`; + + if (!useVite) { + await writeFile("dev.ts", DEV_TS); + } + + const denoJson = { + 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@^${freshVersion}`, + "preact": `npm:preact@^${PREACT_VERSION}`, + "@preact/signals": `npm:@preact/signals@^${PREACT_SIGNALS_VERSION}`, + } as Record, + 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", + ], + } as Record, + }; + + if (useVite) { + denoJson.compilerOptions.types = ["vite/client"]; + denoJson.tasks.dev = "vite"; + denoJson.tasks.build = "vite build"; + + const vitePluginVersion = await getLatestVersion( + "@fresh/plugin-vite", + FRESH_VITE_PLUGIN, + ); + + denoJson.imports["@fresh/plugin-vite"] = + `jsr:@fresh/plugin-vite@^${vitePluginVersion}`; + denoJson.imports["vite"] = "npm:vite@^7.1.3"; + + if (useTailwind) { + denoJson.imports["tailwindcss"] = + `npm:tailwindcss@^${TAILWINDCSS_VERSION}`; + denoJson.imports["@tailwindcss/vite"] = `npm:@tailwindcss/vite@^4.1.12`; + } + } else if (useTailwind) { + denoJson.imports["tailwindcss"] = `npm:tailwindcss@^${TAILWINDCSS_VERSION}`; + denoJson.imports["@fresh/plugin-tailwind"] = + `jsr:@fresh/plugin-tailwind@^${FRESH_TAILWIND_VERSION}`; + denoJson.imports["@tailwindcss/postcss"] = + `npm:@tailwindcss/postcss@^${TAILWINDCSS_POSTCSS_VERSION}`; + denoJson.imports["postcss"] = `npm:postcss@^${POSTCSS_VERSION}`; + } + + await writeFile("deno.json", denoJson); + + if (useVite) { + let viteConfig = `import { defineConfig } from "vite"; +import { fresh } from "@fresh/plugin-vite";\n`; + + if (useTailwind) { + viteConfig += `import tailwindcss from "@tailwindcss/vite";\n`; + } + + viteConfig += `\nexport default defineConfig({ + plugins: [fresh()${useTailwind ? ", tailwindcss()" : ""}], +});`; + + await writeFile("vite.config.ts", viteConfig); + } + + const README_MD = `# 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.`; + await writeFile("README.md", README_MD); + + if (useVSCode) { + const vscodeSettings = { + "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": useTailwind ? [".vscode/tailwind.json"] : undefined, + }; + + await writeFile(".vscode/settings.json", vscodeSettings); + + const recommendations = ["denoland.vscode-deno"]; + if (useTailwind) recommendations.push("bradlc.vscode-tailwindcss"); + await writeFile(".vscode/extensions.json", { recommendations }); + + if (useTailwind) { + const tailwindCustomData = { + "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", + }, + ], + }, + ], + }; + + await writeFile(".vscode/tailwind.json", tailwindCustomData); + } + } + + // Specifically print unresolvedDirectory, rather than resolvedDirectory in order to + // not leak personal info (e.g. `/Users/MyName`) + console.log( + "\n%cProject initialized!\n", + "color: green; font-weight: bold", + ); + + if (unresolvedDirectory !== ".") { + console.log( + `Enter your project directory using %ccd ${unresolvedDirectory}%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", + ); +} + +async function writeProjectFile( + projectDir: string, + pathname: string, + content: + | string + | Uint8Array + | ReadableStream + | Record, +) { + const filePath = path.join( + projectDir, + ...pathname.split("/").filter(Boolean), + ); + try { + await Deno.mkdir( + path.dirname(filePath), + { recursive: true }, + ); + if (typeof content === "string") { + let formatted = content; + if (!content.endsWith("\n\n")) { + formatted += "\n"; + } + await Deno.writeTextFile(filePath, formatted); + } else if ( + content instanceof Uint8Array || content instanceof ReadableStream + ) { + await Deno.writeFile(filePath, content); + } else { + await Deno.writeTextFile( + filePath, + JSON.stringify(content, null, 2) + "\n", + ); + } + } catch (err) { + if (!(err instanceof Deno.errors.AlreadyExists)) { + throw err; + } + } +} + +interface JsrMeta { + scope: string; + name: string; + latest: string | null; + versions: Record; +} + +async function getLatestVersion( + pkg: string, + fallback: string, +): Promise { + // deno-lint-ignore no-explicit-any + if ((globalThis as any).INIT_TEST) { + return fallback; + } + + try { + const res = await fetch(`https://jsr.io/${pkg}/meta.json`); + const json = (await res.json()) as JsrMeta; + + if (json.latest !== null) { + return json.latest; + } + + const versions = Object.keys(json.versions); + if (versions.length === 0) throw new Error("No versions"); + + versions.sort((a, b) => { + const s1 = semver.parse(a); + const s2 = semver.parse(b); + return semver.compare(s1, s2); + }); + + return versions.at(-1)!; + } catch { + console.log( + `Could not fetch latest ${pkg} version. Falling back to: ${fallback}`, + ); + return fallback; } } diff --git a/packages/init/src/init_test.ts b/packages/init/src/init_test.ts new file mode 100644 index 00000000..b91a67ae --- /dev/null +++ b/packages/init/src/init_test.ts @@ -0,0 +1,363 @@ +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 = {}) { + 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 { + 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 { + 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"); +}); diff --git a/packages/init/src/mod.ts b/packages/init/src/mod.ts index b7451765..ce6cc9f4 100644 --- a/packages/init/src/mod.ts +++ b/packages/init/src/mod.ts @@ -1,220 +1,26 @@ -#!/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 * 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" }; +import { initProject } from "./init.ts"; +import { InitError } from "./init.ts"; -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 { - // 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 = { - 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; - } +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; } diff --git a/packages/init/src/sync.ts b/packages/init/src/sync.ts deleted file mode 100644 index 86452c68..00000000 --- a/packages/init/src/sync.ts +++ /dev/null @@ -1,211 +0,0 @@ -#!/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 { - 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 { - 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(); -} diff --git a/packages/init/src/types.ts b/packages/init/src/types.ts deleted file mode 100644 index 1cb64f68..00000000 --- a/packages/init/src/types.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * 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; -} diff --git a/packages/init/src/utils.ts b/packages/init/src/utils.ts deleted file mode 100644 index d54265cb..00000000 --- a/packages/init/src/utils.ts +++ /dev/null @@ -1,186 +0,0 @@ -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 { - // 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; - }; - - 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 { - 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 { - 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 { - 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; -} diff --git a/packages/init/tests/cli_test.ts b/packages/init/tests/cli_test.ts deleted file mode 100644 index c979ace7..00000000 --- a/packages/init/tests/cli_test.ts +++ /dev/null @@ -1,131 +0,0 @@ -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, -}); diff --git a/packages/init/tests/integration_test.ts b/packages/init/tests/integration_test.ts deleted file mode 100644 index 069d53d7..00000000 --- a/packages/init/tests/integration_test.ts +++ /dev/null @@ -1,273 +0,0 @@ -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, -}); diff --git a/packages/init/tests/sync_test.ts b/packages/init/tests/sync_test.ts deleted file mode 100644 index da81e0da..00000000 --- a/packages/init/tests/sync_test.ts +++ /dev/null @@ -1,379 +0,0 @@ -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 { - // 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 }); - } -}); diff --git a/packages/init/tests/template_test.ts b/packages/init/tests/template_test.ts deleted file mode 100644 index e6cca3f3..00000000 --- a/packages/init/tests/template_test.ts +++ /dev/null @@ -1,219 +0,0 @@ -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"); -}); diff --git a/packages/init/tests/utils_test.ts b/packages/init/tests/utils_test.ts deleted file mode 100644 index 2ef43f62..00000000 --- a/packages/init/tests/utils_test.ts +++ /dev/null @@ -1,82 +0,0 @@ -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) -});