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

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

This is now ready for review.

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

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

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

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

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

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

Generated PR message below:

---

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

### Architecture

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

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

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

### Maintenance workflow

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

### Version resolution

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

### Testing

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

### Breaking changes

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

### Documentation

- README.md - User-facing usage documentation
- DESIGN.md - Maintainer documentation (architecture, template
maintenance, development setup)
This commit is contained in:
fry69
2025-10-06 09:12:07 +02:00
committed by GitHub
parent 317f1cb95f
commit 198816b042
98 changed files with 4615 additions and 1236 deletions
+131
View File
@@ -0,0 +1,131 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
Deno.test({
name: "cli - shows help text",
async fn() {
const command = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(import.meta.dirname!, "..", "src", "mod.ts"),
"--help",
],
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("@fresh/init");
expect(output).toContain("USAGE:");
expect(output).toContain("OPTIONS:");
expect(output).toContain("--force");
expect(output).toContain("--tailwind");
expect(output).toContain("--vscode");
expect(output).toContain("--docker");
expect(output).toContain("--builder");
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "cli - creates project with flags",
async fn() {
const tmpDir = await Deno.makeTempDir();
const projectName = "test-cli-full";
try {
const command = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(import.meta.dirname!, "..", "src", "mod.ts"),
projectName,
"--force",
"--tailwind",
"--vscode",
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("Project initialized!");
// Verify project structure
const projectDir = path.join(tmpDir, projectName);
const stat = await Deno.stat(projectDir);
expect(stat.isDirectory).toBe(true);
// Verify key files exist
await Deno.stat(path.join(projectDir, "deno.json"));
await Deno.stat(path.join(projectDir, "vite.config.ts"));
await Deno.stat(path.join(projectDir, "assets", "styles.css"));
await Deno.stat(path.join(projectDir, ".vscode", "settings.json"));
await Deno.stat(path.join(projectDir, ".vscode", "tailwind.json"));
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "cli - creates builder project",
async fn() {
const tmpDir = await Deno.makeTempDir();
const projectName = "test-cli-builder";
try {
const command = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(import.meta.dirname!, "..", "src", "mod.ts"),
projectName,
"--force",
"--builder",
"--docker",
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
stdin: "null",
env: {
"NO_COLOR": "1", // Disable prompts in test
},
});
const { code } = await command.output();
expect(code).toBe(0);
// Verify builder project structure
const projectDir = path.join(tmpDir, projectName);
await Deno.stat(path.join(projectDir, "dev.ts"));
await Deno.stat(path.join(projectDir, "Dockerfile"));
// Should NOT have vite files
try {
await Deno.stat(path.join(projectDir, "vite.config.ts"));
throw new Error("Should not have vite.config.ts in builder mode");
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
},
sanitizeOps: false,
sanitizeResources: false,
});
+320
View File
@@ -0,0 +1,320 @@
/**
* Compatibility tests that compare the output of @fresh/init v2.0.9
* (last version before template-based refactor) with the current version
* to ensure 100% identical output for various option combinations.
*/
import { expect } from "@std/expect";
import * as path from "@std/path";
import * as fs from "@std/fs";
import { stub } from "@std/testing/mock";
import { initProject as newInitProject, resolveVersions } from "../src/init.ts";
import { withTmpDir } from "../../fresh/src/test_utils.ts";
/**
* Recursively get all files in a directory with their relative paths
*/
async function getAllFiles(dir: string, baseDir = dir): Promise<string[]> {
const files: string[] = [];
for await (const entry of fs.walk(dir, { includeFiles: true })) {
if (entry.isFile) {
const relativePath = path.relative(baseDir, entry.path);
files.push(relativePath);
}
}
return files.sort();
}
/**
* Compare two directories recursively, ensuring all files and contents match
*/
async function compareDirectories(
dir1: string,
dir2: string,
description: string,
): Promise<void> {
const files1 = await getAllFiles(dir1);
const files2 = await getAllFiles(dir2);
// Compare file lists
expect(files1).toEqual(files2);
// Compare file contents
for (const file of files1) {
const file1Path = path.join(dir1, file);
const file2Path = path.join(dir2, file);
let content1 = await Deno.readTextFile(file1Path);
let content2 = await Deno.readTextFile(file2Path);
// For deno.json, normalize dependency versions to allow minor/patch differences
// The current init fetches latest Fresh version from network, which may differ
// from the version that was current when 2.0.9 was released. This is expected.
if (file === "deno.json") {
content1 = normalizeDependencyVersions(content1);
content2 = normalizeDependencyVersions(content2);
}
if (content1 !== content2) {
console.error(`\nFile mismatch in ${description}: ${file}`);
console.error(`Version 2.0.9: ${file1Path}`);
console.error(`Current version: ${file2Path}`);
console.error("\n--- Expected (v2.0.9) ---");
console.error(content1.slice(0, 500));
console.error("\n--- Actual (current) ---");
console.error(content2.slice(0, 500));
}
expect(content2).toBe(content1);
}
}
/**
* Normalize dependency versions in deno.json to allow minor/patch differences.
* Replaces specific version numbers with major version only for comparison.
*/
function normalizeDependencyVersions(content: string): string {
return content
// Normalize preact signals version (2.3.x -> 2.x)
.replace(
/"npm:@preact\/signals@\^2\.\d+\.\d+"/g,
'"npm:@preact/signals@^2.x"',
)
// Normalize preact version (10.x.x -> 10.x)
.replace(/"npm:preact@\^10\.\d+\.\d+"/g, '"npm:preact@^10.x"')
// Normalize fresh/plugin-vite version (1.0.x -> 1.0)
.replace(
/"jsr:@fresh\/plugin-vite@\^1\.0\.\d+"/g,
'"jsr:@fresh/plugin-vite@^1.0"',
);
}
/**
* Run the reference init script (v2.0.9) from JSR using the CLI.
* This is the last version before the template-based refactor.
*/
async function runReferenceInit(
dir: string,
projectName: string,
flags: {
docker?: boolean;
tailwind?: boolean;
vscode?: boolean;
builder?: boolean;
},
): Promise<void> {
const args = [
"run",
"-A",
"jsr:@fresh/init@2.0.9",
projectName,
"--force",
];
if (flags.builder) args.push("--builder");
if (flags.tailwind) args.push("--tailwind");
if (flags.vscode) args.push("--vscode");
if (flags.docker) args.push("--docker");
const command = new Deno.Command("deno", {
args,
cwd: dir,
stdout: "null",
stderr: "null",
});
const { success } = await command.output();
if (!success) {
throw new Error("Reference init script (v2.0.9) failed");
}
}
/**
* Test helper that runs both v2.0.9 (reference) and current init with the same
* options and compares the output to ensure backward compatibility.
*/
async function testCompatibility(
testName: string,
flags: {
docker?: boolean;
tailwind?: boolean;
vscode?: boolean;
builder?: boolean;
},
): Promise<void> {
// Use temporary directories for both tests
await using tmpOld = await withTmpDir();
await using tmpNew = await withTmpDir();
const projectName = "test-project";
// Stub console.log to suppress init output
using _logs = stub(console, "log", () => undefined);
// Stub prompt and confirm to prevent waiting for user input
using _promptStub = stub(globalThis, "prompt", () => projectName);
using _confirmStub = stub(globalThis, "confirm", () => false);
// Run reference init script (v2.0.9) from JSR using CLI
await runReferenceInit(tmpOld.dir, projectName, flags);
// Resolve versions to match what v2.0.9 would use (fixed versions)
const versions = await resolveVersions({
fresh: "2.1.1",
freshTailwind: "1.0.0",
freshVitePlugin: "1.0.0",
preact: "10.27.2",
preactSignals: "2.3.1",
tailwindcss: "4.1.10",
tailwindcssPostcss: "4.1.10",
tailwindcssVite: "4.1.12",
postcss: "8.5.6",
vite: "7.1.3",
});
// Run current init script
await newInitProject(
tmpNew.dir,
{
directory: projectName,
builder: flags.builder ?? false,
tailwind: flags.tailwind ?? false,
vscode: flags.vscode ?? false,
docker: flags.docker ?? false,
force: true,
},
versions,
);
// Compare the outputs
const oldProjectDir = path.join(tmpOld.dir, projectName);
const newProjectDir = path.join(tmpNew.dir, projectName);
await compareDirectories(oldProjectDir, newProjectDir, testName);
}
// Test suite covering major option combinations
Deno.test({
name: "compatibility - default (builder, no extras)",
async fn() {
await testCompatibility("default", {
builder: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite only",
async fn() {
await testCompatibility("vite", {
builder: false,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + tailwind",
async fn() {
await testCompatibility("vite-tailwind", {
builder: false,
tailwind: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - builder + tailwind",
async fn() {
await testCompatibility("builder-tailwind", {
builder: true,
tailwind: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + vscode",
async fn() {
await testCompatibility("vite-vscode", {
builder: false,
vscode: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + docker",
async fn() {
await testCompatibility("vite-docker", {
builder: false,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + tailwind + vscode",
async fn() {
await testCompatibility("vite-tailwind-vscode", {
builder: false,
tailwind: true,
vscode: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - builder + tailwind + docker",
async fn() {
await testCompatibility("builder-tailwind-docker", {
builder: true,
tailwind: true,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - vite + all extras",
async fn() {
await testCompatibility("vite-all", {
builder: false,
tailwind: true,
vscode: true,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "compatibility - builder + all extras",
async fn() {
await testCompatibility("builder-all", {
builder: true,
tailwind: true,
vscode: true,
docker: true,
});
},
sanitizeResources: false,
sanitizeOps: false,
});
+249
View File
@@ -0,0 +1,249 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { withTmpDir } from "../../fresh/src/test_utils.ts";
import { initProject, resolveVersions } from "../src/init.ts";
Deno.test("initProject - creates vite project with default options", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-project");
const versions = await resolveVersions({
fresh: "2.1.1",
preact: "10.27.2",
});
await initProject(tmp.dir, {
directory: "test-project",
builder: false,
tailwind: false,
vscode: false,
docker: false,
force: true,
}, versions);
// Check that key files exist
const files = [
"deno.json",
"vite.config.ts",
"main.ts",
"client.ts",
"utils.ts",
"README.md",
".gitignore",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"islands/Counter.tsx",
"components/Button.tsx",
"assets/styles.css",
"static/logo.svg",
// favicon.ico might not exist if network fails, so skip checking it
];
for (const file of files) {
const filePath = path.join(projectDir, file);
const stat = await Deno.stat(filePath);
expect(stat.isFile).toBe(true);
}
// Check that deno.json contains correct version
const denoJson = JSON.parse(
await Deno.readTextFile(path.join(projectDir, "deno.json")),
);
expect(denoJson.imports.fresh).toContain("2.1.1");
expect(denoJson.imports.preact).toContain("10.27.2");
// Check that vite.config.ts doesn't include tailwind
const viteConfig = await Deno.readTextFile(
path.join(projectDir, "vite.config.ts"),
);
expect(viteConfig).not.toContain("tailwindcss");
// Check that _app.tsx has project name
const appFile = await Deno.readTextFile(
path.join(projectDir, "routes/_app.tsx"),
);
expect(appFile).toContain("test-project");
});
Deno.test("initProject - creates vite project with tailwind", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-tailwind");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-tailwind",
builder: false,
tailwind: true,
vscode: false,
docker: false,
force: true,
}, versions);
// Check vite.config.ts includes tailwind
const viteConfig = await Deno.readTextFile(
path.join(projectDir, "vite.config.ts"),
);
expect(viteConfig).toContain("tailwindcss");
expect(viteConfig).toContain("@tailwindcss/vite");
// Check deno.json includes tailwind
const denoJson = JSON.parse(
await Deno.readTextFile(path.join(projectDir, "deno.json")),
);
expect(denoJson.imports.tailwindcss).toBeTruthy();
expect(denoJson.imports["@tailwindcss/vite"]).toBeTruthy();
// Check styles.css uses @import
const styles = await Deno.readTextFile(
path.join(projectDir, "assets/styles.css"),
);
expect(styles).toContain("@import");
});
Deno.test("initProject - creates builder project", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-builder",
builder: true,
tailwind: false,
vscode: false,
docker: false,
force: true,
}, versions);
// Check that dev.ts exists (not vite.config.ts)
const devTsPath = path.join(projectDir, "dev.ts");
const vitePath = path.join(projectDir, "vite.config.ts");
const devStat = await Deno.stat(devTsPath);
expect(devStat.isFile).toBe(true);
try {
await Deno.stat(vitePath);
throw new Error("vite.config.ts should not exist in builder mode");
} catch (err) {
expect(err).toBeInstanceOf(Deno.errors.NotFound);
}
// Check that static/styles.css exists (not assets/)
const stylesPath = path.join(projectDir, "static/styles.css");
const stylesStat = await Deno.stat(stylesPath);
expect(stylesStat.isFile).toBe(true);
// Check that _app.tsx has link to styles.css
const appFile = await Deno.readTextFile(
path.join(projectDir, "routes/_app.tsx"),
);
expect(appFile).toContain('href="/styles.css"');
});
Deno.test("initProject - creates project with vscode settings", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vscode");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-vscode",
builder: false,
tailwind: false,
vscode: true,
docker: false,
force: true,
}, versions);
// Check VS Code files exist
const vscodeFiles = [
".vscode/settings.json",
".vscode/extensions.json",
];
for (const file of vscodeFiles) {
const filePath = path.join(projectDir, file);
const stat = await Deno.stat(filePath);
expect(stat.isFile).toBe(true);
}
// Check settings.json content
const settings = JSON.parse(
await Deno.readTextFile(path.join(projectDir, ".vscode/settings.json")),
);
expect(settings["deno.enable"]).toBe(true);
expect(settings["deno.lint"]).toBe(true);
// Check extensions.json content
const extensions = JSON.parse(
await Deno.readTextFile(
path.join(projectDir, ".vscode/extensions.json"),
),
);
expect(extensions.recommendations).toContain("denoland.vscode-deno");
});
Deno.test("initProject - creates project with docker", async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-docker");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-docker",
builder: false,
tailwind: false,
vscode: false,
docker: true,
force: true,
}, versions);
// Check Dockerfile exists
const dockerfilePath = path.join(projectDir, "Dockerfile");
const dockerStat = await Deno.stat(dockerfilePath);
expect(dockerStat.isFile).toBe(true);
// Check Dockerfile content
const dockerfile = await Deno.readTextFile(dockerfilePath);
expect(dockerfile).toContain("FROM denoland/deno");
expect(dockerfile).toContain("EXPOSE 8000");
});
Deno.test(
"initProject - creates tailwind.json when vscode + tailwind",
async () => {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vscode-tailwind");
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(tmp.dir, {
directory: "test-vscode-tailwind",
builder: false,
tailwind: true,
vscode: true,
docker: false,
force: true,
}, versions);
// Check .vscode/tailwind.json exists
const tailwindJsonPath = path.join(
projectDir,
".vscode/tailwind.json",
);
const tailwindStat = await Deno.stat(tailwindJsonPath);
expect(tailwindStat.isFile).toBe(true);
// Check tailwind.json content
const tailwindJson = JSON.parse(
await Deno.readTextFile(tailwindJsonPath),
);
expect(tailwindJson.version).toBe(1.1);
expect(tailwindJson.atDirectives).toBeTruthy();
expect(tailwindJson.atDirectives.length).toBeGreaterThan(0);
expect(tailwindJson.atDirectives[0].name).toBe("@tailwind");
},
);
+273
View File
@@ -0,0 +1,273 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { initProject, resolveVersions } from "../src/init.ts";
import { withTmpDir } from "../../fresh/src/test_utils.ts";
import { withChildProcessServer } from "../../fresh/tests/test_utils.tsx";
/**
* Integration tests for validating generated projects.
*
* These tests generate complete projects and verify they work correctly:
* - Project files are valid and can be checked with `deno task check`
* - Development server starts successfully with `deno task dev`
* - Production build completes with `deno task build`
*
* Note: These tests are more extensive and slower than unit tests.
* They should be run less frequently, perhaps in CI or before releases.
*/
// Helper to run a command in a directory and check its exit code
async function runCommand(
dir: string,
cmd: string[],
): Promise<{ success: boolean; output: string }> {
const command = new Deno.Command(cmd[0], {
args: cmd.slice(1),
cwd: dir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout, stderr } = await command.output();
const output = new TextDecoder().decode(stdout) +
new TextDecoder().decode(stderr);
return { success: code === 0, output };
}
// Helper to initialize a project with resolved versions (for tests)
async function initTestProject(
cwd: string,
directory: string,
builder: boolean,
tailwind: boolean,
) {
const versions = await resolveVersions({ fresh: "2.1.1" });
await initProject(cwd, {
directory,
builder,
tailwind,
vscode: false,
docker: false,
force: true,
}, versions);
}
Deno.test({
name: "integration - vite project passes check",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vite-check");
await initTestProject(tmp.dir, "test-vite-check", false, false);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "check"],
);
expect(success, `Check failed: ${output}`).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - builder project passes check",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder-check");
await initTestProject(tmp.dir, "test-builder-check", true, false);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "check"],
);
expect(success, `Check failed: ${output}`).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - vite with tailwind passes check",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vite-tailwind-check");
await initTestProject(tmp.dir, "test-vite-tailwind-check", false, true);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "check"],
);
expect(success, `Check failed: ${output}`).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - vite project can build",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-vite-build");
await initTestProject(tmp.dir, "test-vite-build", false, false);
// Install dependencies first
await runCommand(projectDir, ["deno", "install"]);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "build"],
);
expect(success, `Build failed: ${output}`).toBe(true);
// Check that _fresh directory was created
const freshDir = path.join(projectDir, "_fresh");
const stat = await Deno.stat(freshDir);
expect(stat.isDirectory).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - builder project can build",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder-build");
await initTestProject(tmp.dir, "test-builder-build", true, false);
const { success, output } = await runCommand(
projectDir,
["deno", "task", "build"],
);
expect(success, `Build failed: ${output}`).toBe(true);
// Check that _fresh directory was created
const freshDir = path.join(projectDir, "_fresh");
const stat = await Deno.stat(freshDir);
expect(stat.isDirectory).toBe(true);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - vite dev server works",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-dev-server");
await initTestProject(tmp.dir, "test-dev-server", false, false);
// Start dev server and verify it works
await withChildProcessServer(
{
cwd: projectDir,
args: ["task", "dev"],
},
async (address) => {
// Verify the home page responds with correct content
const res = await fetch(address);
expect(res.status).toBe(200);
const html = await res.text();
// Check for Fresh welcome message
expect(
html,
"Fresh welcome message should appear",
).toContain("Welcome to Fresh");
// Check for counter buttons (verifies island is rendered)
expect(
html,
"Counter buttons should be present",
).toContain('id="increment"');
expect(
html,
"Counter buttons should be present",
).toContain('id="decrement"');
// Check for logo
expect(
html,
"Fresh logo should be present",
).toContain("logo.svg");
// Test the API route
const apiRes = await fetch(`${address}/api/fresh`);
expect(apiRes.status).toBe(200);
const greeting = await apiRes.text();
expect(greeting, "API should return greeting").toBe("Hello, Fresh!");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "integration - builder dev server works",
ignore: false,
async fn() {
await using tmp = await withTmpDir();
const projectDir = path.join(tmp.dir, "test-builder-dev");
await initTestProject(tmp.dir, "test-builder-dev", true, false);
// Start dev server and verify it works
await withChildProcessServer(
{
cwd: projectDir,
args: ["task", "dev"],
},
async (address) => {
// Verify the home page responds with correct content
const res = await fetch(address);
expect(res.status).toBe(200);
const html = await res.text();
// Check for Fresh welcome message
expect(
html,
"Fresh welcome message should appear",
).toContain("Welcome to Fresh");
// Check for counter buttons (verifies island is rendered)
expect(
html,
"Counter buttons should be present",
).toContain('id="increment"');
expect(
html,
"Counter buttons should be present",
).toContain('id="decrement"');
// Check for logo
expect(
html,
"Fresh logo should be present",
).toContain("logo.svg");
// Test the API route
const apiRes = await fetch(`${address}/api/fresh`);
expect(apiRes.status).toBe(200);
const greeting = await apiRes.text();
expect(greeting, "API should return greeting").toBe("Hello, Fresh!");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
+379
View File
@@ -0,0 +1,379 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import * as fs from "@std/fs";
/**
* Helper to create a temporary directory structure for testing
*/
async function createTestStructure(baseDir: string): Promise<void> {
// Create base template structure
const baseVite = path.join(baseDir, "assets/base/vite");
const baseBuilder = path.join(baseDir, "assets/base/builder");
await fs.ensureDir(path.join(baseVite, "components"));
await fs.ensureDir(path.join(baseVite, "routes"));
await fs.ensureDir(path.join(baseBuilder, "components"));
await fs.ensureDir(path.join(baseBuilder, "static"));
// Create common files
await Deno.writeTextFile(
path.join(baseVite, "main.ts"),
"export const app = new App();",
);
await Deno.writeTextFile(
path.join(baseVite, "components/Button.tsx"),
"export function Button() {}",
);
await Deno.writeTextFile(
path.join(baseVite, "routes/index.tsx"),
"export default function Home() {}",
);
await Deno.writeTextFile(
path.join(baseBuilder, "main.ts"),
"export const app = new App();",
);
await Deno.writeTextFile(
path.join(baseBuilder, "components/Button.tsx"),
"export function Button() {}",
);
// Create template directories
const templateVite = path.join(baseDir, "assets/template/vite");
const templateViteTailwind = path.join(
baseDir,
"assets/template/vite-tailwind",
);
const templateBuilder = path.join(baseDir, "assets/template/builder");
const templateBuilderTailwind = path.join(
baseDir,
"assets/template/builder-tailwind",
);
await fs.ensureDir(templateVite);
await fs.ensureDir(templateViteTailwind);
await fs.ensureDir(templateBuilder);
await fs.ensureDir(templateBuilderTailwind);
// Create template-specific files
await Deno.writeTextFile(
path.join(templateVite, "deno.json.tmpl"),
'{"imports": {"vite": "npm:vite"}}',
);
await Deno.writeTextFile(
path.join(templateViteTailwind, "deno.json.tmpl"),
'{"imports": {"vite": "npm:vite", "tailwind": "npm:tailwindcss"}}',
);
await Deno.writeTextFile(
path.join(templateVite, "vite.config.ts"),
"export default { plugins: [] }",
);
await Deno.writeTextFile(
path.join(templateViteTailwind, "vite.config.ts"),
"export default { plugins: [tailwind()] }",
);
await fs.ensureDir(path.join(templateVite, "assets"));
await fs.ensureDir(path.join(templateViteTailwind, "assets"));
await Deno.writeTextFile(
path.join(templateVite, "assets/styles.css"),
".fresh { color: blue; }",
);
await Deno.writeTextFile(
path.join(templateViteTailwind, "assets/styles.css"),
"@import 'tailwindcss';",
);
await fs.ensureDir(path.join(templateBuilder, "static"));
await fs.ensureDir(path.join(templateBuilderTailwind, "static"));
await Deno.writeTextFile(
path.join(templateBuilder, "static/styles.css"),
".fresh { color: blue; }",
);
await Deno.writeTextFile(
path.join(templateBuilderTailwind, "static/styles.css"),
"@import 'tailwindcss';",
);
}
/**
* Test that isTemplateSpecific correctly identifies template-specific files
*/
Deno.test("isTemplateSpecific - identifies template-specific files", () => {
// Import the function from the script
const TEMPLATE_SPECIFIC_FILES = [
"deno.json.tmpl",
"deno.json",
"vite.config.ts",
"assets/styles.css",
"static/styles.css",
];
function isTemplateSpecific(relPath: string): boolean {
return TEMPLATE_SPECIFIC_FILES.some((specific) =>
relPath === specific || relPath.endsWith(`/${specific}`)
);
}
// Should return true for template-specific files
expect(isTemplateSpecific("deno.json.tmpl")).toBe(true);
expect(isTemplateSpecific("vite.config.ts")).toBe(true);
expect(isTemplateSpecific("assets/styles.css")).toBe(true);
expect(isTemplateSpecific("static/styles.css")).toBe(true);
expect(isTemplateSpecific("path/to/deno.json.tmpl")).toBe(true);
// Should return false for common files
expect(isTemplateSpecific("main.ts")).toBe(false);
expect(isTemplateSpecific("components/Button.tsx")).toBe(false);
expect(isTemplateSpecific("routes/index.tsx")).toBe(false);
expect(isTemplateSpecific("README.md")).toBe(false);
});
/**
* Test sync in dry-run mode
*/
Deno.test("sync_templates - dry run does not modify files", async () => {
const tmpDir = await Deno.makeTempDir();
try {
await createTestStructure(tmpDir);
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run sync in dry-run mode
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
"--dry-run",
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await process.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("DRY RUN MODE");
expect(output).toContain("would be copied");
// Verify templates are still empty (dry run didn't copy)
const viteMain = path.join(tmpDir, "assets/template/vite/main.ts");
const exists = await fs.exists(viteMain);
expect(exists).toBe(false);
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
/**
* Test actual sync operation
*/
Deno.test("sync_templates - syncs common files correctly", async () => {
const tmpDir = await Deno.makeTempDir();
try {
await createTestStructure(tmpDir);
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run actual sync
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await process.output();
const output = new TextDecoder().decode(stdout);
expect(code).toBe(0);
expect(output).toContain("Sync complete");
// Verify common files were copied
const viteMain = path.join(tmpDir, "assets/template/vite/main.ts");
const viteButton = path.join(
tmpDir,
"assets/template/vite/components/Button.tsx",
);
const viteTailwindMain = path.join(
tmpDir,
"assets/template/vite-tailwind/main.ts",
);
expect(await fs.exists(viteMain)).toBe(true);
expect(await fs.exists(viteButton)).toBe(true);
expect(await fs.exists(viteTailwindMain)).toBe(true);
// Verify content is correct
const mainContent = await Deno.readTextFile(viteMain);
expect(mainContent).toBe("export const app = new App();");
// Verify template-specific files were NOT overwritten
const viteDeno = path.join(tmpDir, "assets/template/vite/deno.json.tmpl");
const viteConfig = path.join(tmpDir, "assets/template/vite/vite.config.ts");
const viteStyles = path.join(
tmpDir,
"assets/template/vite/assets/styles.css",
);
const denoContent = await Deno.readTextFile(viteDeno);
const configContent = await Deno.readTextFile(viteConfig);
const stylesContent = await Deno.readTextFile(viteStyles);
expect(denoContent).toBe('{"imports": {"vite": "npm:vite"}}');
expect(configContent).toBe("export default { plugins: [] }");
expect(stylesContent).toBe(".fresh { color: blue; }");
// Verify tailwind variant has different template-specific files
const viteTailwindDeno = path.join(
tmpDir,
"assets/template/vite-tailwind/deno.json.tmpl",
);
const viteTailwindConfig = path.join(
tmpDir,
"assets/template/vite-tailwind/vite.config.ts",
);
const viteTailwindStyles = path.join(
tmpDir,
"assets/template/vite-tailwind/assets/styles.css",
);
const tailwindDenoContent = await Deno.readTextFile(viteTailwindDeno);
const tailwindConfigContent = await Deno.readTextFile(viteTailwindConfig);
const tailwindStylesContent = await Deno.readTextFile(viteTailwindStyles);
expect(tailwindDenoContent).toBe(
'{"imports": {"vite": "npm:vite", "tailwind": "npm:tailwindcss"}}',
);
expect(tailwindConfigContent).toBe(
"export default { plugins: [tailwind()] }",
);
expect(tailwindStylesContent).toBe("@import 'tailwindcss';");
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
/**
* Test that sync handles builder templates correctly
*/
Deno.test("sync_templates - syncs builder templates", async () => {
const tmpDir = await Deno.makeTempDir();
try {
await createTestStructure(tmpDir);
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run sync
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code } = await process.output();
expect(code).toBe(0);
// Verify builder files were copied
const builderMain = path.join(tmpDir, "assets/template/builder/main.ts");
const builderButton = path.join(
tmpDir,
"assets/template/builder/components/Button.tsx",
);
const builderTailwindMain = path.join(
tmpDir,
"assets/template/builder-tailwind/main.ts",
);
expect(await fs.exists(builderMain)).toBe(true);
expect(await fs.exists(builderButton)).toBe(true);
expect(await fs.exists(builderTailwindMain)).toBe(true);
// Verify template-specific files were preserved
const builderStyles = path.join(
tmpDir,
"assets/template/builder/static/styles.css",
);
const builderTailwindStyles = path.join(
tmpDir,
"assets/template/builder-tailwind/static/styles.css",
);
const stylesContent = await Deno.readTextFile(builderStyles);
const tailwindStylesContent = await Deno.readTextFile(
builderTailwindStyles,
);
expect(stylesContent).toBe(".fresh { color: blue; }");
expect(tailwindStylesContent).toBe("@import 'tailwindcss';");
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
/**
* Test error handling when base directory doesn't exist
*/
Deno.test("sync_templates - handles missing base directory", async () => {
const tmpDir = await Deno.makeTempDir();
try {
// Create only template directories, not base
await fs.ensureDir(path.join(tmpDir, "assets/template/vite"));
await fs.ensureDir(path.join(tmpDir, "assets/template/vite-tailwind"));
// Get path to src/sync.ts relative to this test file
const syncScriptPath = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"../src/sync.ts",
);
// Run sync (should handle missing base gracefully)
const process = new Deno.Command("deno", {
args: [
"run",
"-A",
syncScriptPath,
],
cwd: tmpDir,
stdout: "piped",
stderr: "piped",
});
const { code, stdout } = await process.output();
const output = new TextDecoder().decode(stdout);
// Should complete but report errors
expect(code).toBe(0);
expect(output).toContain("error");
} finally {
await Deno.remove(tmpDir, { recursive: true });
}
});
+219
View File
@@ -0,0 +1,219 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { getTemplateDir, getVariantsDir } from "../src/utils.ts";
Deno.test("vite - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "vite");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"vite.config.ts",
"main.ts",
"client.ts",
"utils.ts",
"assets/styles.css",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("vite-tailwind - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"vite.config.ts",
"main.ts",
"client.ts",
"utils.ts",
"assets/styles.css",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("builder - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "builder");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"dev.ts",
"main.ts",
"utils.ts",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/styles.css",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("builder-tailwind - has all required files", async () => {
const templateDir = path.join(getTemplateDir(), "builder-tailwind");
const requiredFiles = [
"__gitignore",
"README.md",
"deno.json",
"dev.ts",
"main.ts",
"utils.ts",
"components/Button.tsx",
"islands/Counter.tsx",
"routes/index.tsx",
"routes/_app.tsx",
"routes/api/[name].tsx",
"static/styles.css",
"static/logo.svg",
];
for (const file of requiredFiles) {
const filePath = path.join(templateDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("vite deno.json - contains template variables", async () => {
const templateDir = path.join(getTemplateDir(), "vite");
const denoJsonPath = path.join(templateDir, "deno.json");
const content = await Deno.readTextFile(denoJsonPath);
expect(content).toContain("__FRESH_VERSION__");
expect(content).toContain("__PREACT_VERSION__");
expect(content).toContain("__PREACT_SIGNALS_VERSION__");
expect(content).toContain("__VITE_VERSION__");
});
Deno.test("vite-tailwind deno.json - contains Tailwind dependencies", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const denoJsonPath = path.join(templateDir, "deno.json");
const content = await Deno.readTextFile(denoJsonPath);
expect(content).toContain("__TAILWINDCSS_VERSION__");
expect(content).toContain("__TAILWINDCSS_VITE_VERSION__");
});
Deno.test("vite-tailwind vite.config.ts - imports Tailwind", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const configPath = path.join(templateDir, "vite.config.ts");
const content = await Deno.readTextFile(configPath);
expect(content).toContain("@tailwindcss/vite");
expect(content).toContain("tailwindcss()");
});
Deno.test("vite-tailwind assets/styles.css - uses Tailwind", async () => {
const templateDir = path.join(getTemplateDir(), "vite-tailwind");
const cssPath = path.join(templateDir, "assets/styles.css");
const content = await Deno.readTextFile(cssPath);
expect(content).toContain('@import "tailwindcss"');
});
Deno.test("builder-tailwind deno.json - contains Tailwind dependencies", async () => {
const templateDir = path.join(getTemplateDir(), "builder-tailwind");
const denoJsonPath = path.join(templateDir, "deno.json");
const content = await Deno.readTextFile(denoJsonPath);
expect(content).toContain("__TAILWINDCSS_VERSION__");
expect(content).toContain("__FRESH_TAILWIND_VERSION__");
});
Deno.test("builder-tailwind static/styles.css - uses Tailwind", async () => {
const templateDir = path.join(getTemplateDir(), "builder-tailwind");
const cssPath = path.join(templateDir, "static/styles.css");
const content = await Deno.readTextFile(cssPath);
expect(content).toContain('@import "tailwindcss"');
});
Deno.test("vite _app.tsx - contains PROJECT_NAME variable", async () => {
const templateDir = path.join(getTemplateDir(), "vite");
const appPath = path.join(templateDir, "routes/_app.tsx");
const content = await Deno.readTextFile(appPath);
expect(content).toContain("__PROJECT_NAME__");
});
Deno.test("variants/docker - has Dockerfile", async () => {
const variantDir = path.join(getVariantsDir(), "docker");
const dockerfilePath = path.join(variantDir, "Dockerfile");
const stat = await Deno.stat(dockerfilePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
const content = await Deno.readTextFile(dockerfilePath);
expect(content).toContain("__DENO_VERSION__");
});
Deno.test("variants/vscode - has required files", async () => {
const variantDir = path.join(getVariantsDir(), "vscode");
const requiredFiles = [
"__vscode/settings.json",
"__vscode/extensions.json",
];
for (const file of requiredFiles) {
const filePath = path.join(variantDir, file);
const stat = await Deno.stat(filePath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
}
});
Deno.test("variants/vscode-tailwind - has tailwind.json", async () => {
const variantDir = path.join(getVariantsDir(), "vscode-tailwind");
const tailwindJsonPath = path.join(variantDir, "__vscode/tailwind.json");
const stat = await Deno.stat(tailwindJsonPath);
expect(stat).toBeTruthy();
expect(stat.isFile).toBe(true);
// Check content
const content = JSON.parse(await Deno.readTextFile(tailwindJsonPath));
expect(content.version).toBe(1.1);
expect(content.atDirectives).toBeTruthy();
expect(content.atDirectives.length).toBeGreaterThan(0);
expect(content.atDirectives[0].name).toBe("@tailwind");
});
+82
View File
@@ -0,0 +1,82 @@
import { expect } from "@std/expect";
import {
getLatestVersion,
isDirectoryEmpty,
processFilename,
substituteVariables,
} from "../src/utils.ts";
Deno.test("processFilename - converts double underscore prefix to dot", () => {
expect(processFilename("__gitignore")).toBe(".gitignore");
expect(processFilename("__vscode")).toBe(".vscode");
expect(processFilename("_app.tsx")).toBe("_app.tsx");
expect(processFilename("regular-file.ts")).toBe("regular-file.ts");
});
Deno.test("substituteVariables - replaces template variables", () => {
const template = "Hello __NAME__, version __VERSION__!";
const variables = { NAME: "Fresh", VERSION: "2.0.0" };
const result = substituteVariables(template, variables);
expect(result).toBe("Hello Fresh, version 2.0.0!");
});
Deno.test("substituteVariables - handles multiple occurrences", () => {
const template = "__X__ + __X__ = __Y__";
const variables = { X: "1", Y: "2" };
const result = substituteVariables(template, variables);
expect(result).toBe("1 + 1 = 2");
});
Deno.test("substituteVariables - handles boolean values", () => {
const template = "Enabled: __ENABLED__";
const variables = { ENABLED: true };
const result = substituteVariables(template, variables);
expect(result).toBe("Enabled: true");
});
Deno.test("isDirectoryEmpty - returns true for non-existent directory", async () => {
const isEmpty = await isDirectoryEmpty("/non/existent/path");
expect(isEmpty).toBe(true);
});
Deno.test("isDirectoryEmpty - returns false for directory with files", async () => {
const tempDir = await Deno.makeTempDir();
await Deno.writeTextFile(`${tempDir}/test.txt`, "test");
const isEmpty = await isDirectoryEmpty(tempDir);
expect(isEmpty).toBe(false);
await Deno.remove(tempDir, { recursive: true });
});
Deno.test("isDirectoryEmpty - returns true for empty directory", async () => {
const tempDir = await Deno.makeTempDir();
const isEmpty = await isDirectoryEmpty(tempDir);
expect(isEmpty).toBe(true);
await Deno.remove(tempDir);
});
Deno.test("isDirectoryEmpty - returns true for directory with only .git", async () => {
const tempDir = await Deno.makeTempDir();
await Deno.mkdir(`${tempDir}/.git`);
const isEmpty = await isDirectoryEmpty(tempDir);
expect(isEmpty).toBe(true);
await Deno.remove(tempDir, { recursive: true });
});
Deno.test("getLatestVersion - returns fallback on error", async () => {
const version = await getLatestVersion("@nonexistent/package", "1.0.0");
expect(version).toBe("1.0.0");
});
Deno.test("getLatestVersion - fetches real version", async () => {
// This test requires network access
const version = await getLatestVersion("@std/assert", "0.0.1");
expect(version).toBeTruthy();
// Should return something other than fallback
// (unless there's a network error, in which case it returns fallback)
});