4 Commits

Author SHA1 Message Date
07c7d424e5 add steering files for M1-M4 foundation and M1-M4 milestones 2026-06-24 23:54:04 +02:00
a9aef7e484 save current changes 2026-06-24 23:53:30 +02:00
cfcc91a670 Merge branch 'feature/m1-setup' - M1 project foundation setup
Some checks failed
CI / test (push) Has been cancelled
2026-06-24 23:47:40 +02:00
9253164fd3 feat(m1): project foundation setup - Next.js 15, Tailwind, tooling, CI
- Configure Next.js 15 (App Router, Node.js runtime, serverExternalPackages for better-sqlite3/bcrypt)

- Add Tailwind CSS, PostCSS, tsconfig with @/* alias

- Create app structure (layout, page, globals.css)

- Create directory structure (lib, repositories, services, components, tests)

- Configure Vitest (alias, coverage), Playwright

- Add dependencies: next, react, better-sqlite3, bcrypt, react-markdown, etc.

- Add .env.example, CI workflow, next-env.d.ts

- Remove boilerplate src/example files
2026-06-24 23:47:27 +02:00
31 changed files with 13398 additions and 133 deletions

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
# SQLite database file path
SQLITE_PATH=./data/app.db
# Session secret for signing session cookies
SESSION_SECRET=change-me-in-production
# Uploads directory path
UPLOADS_PATH=./data/uploads

20
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '24'
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm test
- run: npm run build

3
.gitignore vendored
View File

@ -47,9 +47,6 @@ Thumbs.db
coverage/ coverage/
.nyc_output/ .nyc_output/
# Steering files (task management - temporary)
.steering/*
!.steering/.gitkeep
# Lock files (keep package-lock.json for consistency) # Lock files (keep package-lock.json for consistency)
# yarn.lock # yarn.lock

View File

@ -12,3 +12,7 @@ node_modules/
# ビルド成果物 # ビルド成果物
dist/ dist/
.next/
# Next.js auto-generated
next-env.d.ts

View File

@ -0,0 +1,189 @@
# Design Document
## Architecture Overview
Layered architecture (UI → Service → Repository → Data) per `docs/architecture.md`. Next.js 15 App Router with Node.js Runtime only (no Edge Runtime). SQLite via better-sqlite3 accessed exclusively through a custom SQL wrapper. No Prisma.
```
app/ (UI: Route Handlers / Server Components / SSE)
services/ (business logic, permission checks, transactions)
repositories/ (SQL, parameter binding, logical-delete filter)
lib/db/ (SQLite connection, SQL wrapper, Migration)
```
## Component Design
### 1. SQL Wrapper: `lib/db/sqlite.ts`
**Responsibilities**:
- SQLite connection management (singleton getDb(), WAL, foreign_keys ON)
- query<T> (multi-row), get<T> (single-row), execute (insert/update/delete), transaction<T>, close
- Error handling
**Implementation highlights**:
- dbPath = process.env.SQLITE_PATH ?? "./data/app.db"
- SqlParams = Record<string, unknown> | unknown[]
- All repositories use this wrapper; direct better-sqlite3 access forbidden
### 2. Migrator: `lib/db/migrator.ts`
**Responsibilities**:
- Create schema_migrations table
- Read .sql files from migrations dir in filename order
- Skip already-applied files (tracked in schema_migrations)
- Execute each file in a transaction; rollback on failure
### 3. Initial Schema: `lib/db/migrations/001_initial.sql`
16 tables: users, projects, project_members, board_threads, board_comments, chat_messages, todo_columns, todo_items, file_assets, project_notes, milestones, calendar_events, meetings, meeting_members, notifications, activity_logs + indexes.
### 4. Entity Types: `lib/types/`
PascalCase type files for each entity + union types (UserRole, UserStatus, ProjectStatus, ProjectMemberRole, etc.).
### 5. UserRepository
findById, findByEmail, create (with passwordHash), update (name/avatarUrl/role/status).
### 6. AuthService
register (hash password, create user), login (verify hash, issue session), logout, getCurrentUser, updateProfile. Uses bcrypt.
### 7. Session: `lib/auth/session.ts`, `lib/auth/getCurrentUser.ts`
Cookie-based session. getCurrentUser resolves the user from the request cookie.
### 8. ProjectRepository / ProjectMemberRepository
Project: findById, findByOwner, findByUser (via join), create, update, delete.
ProjectMember: findByProject, findByUser, add, remove, isMember, getRole.
### 9. ProjectService
createProject (owner becomes admin member), updateProject, addMember (permission check + notification hook later), removeMember, archiveProject, getDashboard skeleton.
## Data Flow
### Login
1. POST /api/auth/login → AuthService.login(email, password)
2. AuthService → UserRepository.findByEmail → verify bcrypt hash
3. Issue session cookie → return user
### Project creation
1. POST /api/projects → ProjectService.createProject(actorId, input)
2. ProjectService → permission (any authenticated user) → ProjectRepository.create
3. ProjectMemberRepository.add(projectId, ownerId, 'admin')
4. Return project
## Error Handling Strategy
### Custom Error Classes
- ValidationError (400) - field, value
- ForbiddenError (403)
- NotFoundError (404) - resource, id
- (409 for unique constraint - handled via SQLite error code)
### Error Handling Patterns
Route Handlers catch errors and map to HTTP status. Expected errors use custom classes; unexpected errors propagate + log.
## Test Strategy
### Unit Tests (Vitest)
- lib/db/sqlite.test.ts (query/get/execute/transaction, WAL, foreign keys)
- lib/db/migrator.test.ts (order, skip applied, rollback)
- repositories/UserRepository.test.ts
- services/AuthService.test.ts
- repositories/ProjectRepository.test.ts
- repositories/ProjectMemberRepository.test.ts
- services/ProjectService.test.ts
Tests use a temp SQLite file (in-memory or tmpdir) to avoid touching real data/.
### Integration Tests (Vitest)
- project-member-permission.test.ts (non-member cannot access project data)
### E2E Tests (Playwright)
- auth.spec.ts (login, logout, protected screen)
- project-management.spec.ts (create, edit, member add/remove, archive)
## Dependent Libraries
```json
{
"dependencies": {
"next": "15",
"react": "19",
"react-dom": "19",
"better-sqlite3": "^11",
"bcrypt": "^5",
"react-markdown": "^9",
"remark-gfm": "^4",
"rehype-sanitize": "^6"
},
"devDependencies": {
"tailwindcss": "^3",
"@types/better-sqlite3": "^7",
"@types/bcrypt": "^5",
"@playwright/test": "^1",
"tsx": "^4"
}
}
```
## Directory Structure
```
app/
api/auth/{register,login,logout,me}/route.ts
api/users/me/route.ts
api/projects/route.ts
api/projects/[projectId]/route.ts
api/projects/[projectId]/members/route.ts
api/projects/[projectId]/members/[userId]/route.ts
api/admin/migrations/route.ts
login/page.tsx
profile/page.tsx
dashboard/page.tsx
projects/[projectId]/{page,members,settings}.tsx
layout.tsx, globals.css
lib/
db/{sqlite.ts, migrator.ts, run-migrations.ts, migrations/001_initial.sql}
auth/{session.ts, getCurrentUser.ts}
types/*.ts
validators/{userValidator.ts, projectValidator.ts}
repositories/{UserRepository,ProjectRepository,ProjectMemberRepository}.ts
services/{AuthService,ProjectService}.ts
components/layout/{Header,Sidebar,ProjectNav}.tsx
tests/unit/..., tests/integration/..., tests/e2e/...
```
## Implementation Order
1. M1 (branch feature/m1-setup): Next.js setup, deps, config, dir structure, remove boilerplate → merge to main
2. M2 (branch feature/m2-db-foundation): SQL wrapper, migrator, schema, types, migration API, unit tests → merge to main
3. M3 (branch feature/m3-auth-user): UserRepository, AuthService, session, validators, auth API, login/profile pages, unit + e2e → merge to main
4. M4 (branch feature/m4-project-member): Project/Member repos, ProjectService, project API, dashboard/members/settings pages, unit + integration + e2e → merge to main
## Security Considerations
- Passwords hashed with bcrypt (never plaintext)
- All SQL parameter-bound (no string concatenation)
- Auth required on all protected routes (except /api/auth/register, /api/auth/login)
- Project access requires isMember check
- Admin features require role='system_admin'
- .env not committed; secrets via environment
## Performance Considerations
- SQLite WAL mode for read/write concurrency
- Pagination on list endpoints
- Singleton DB connection
## Future Extensibility
- Repository pattern allows adding tables without changing wrapper
- SseEvent type extensible (M8)
- NotificationService/ActivityLogService hooks prepared for M5 (ProjectService.addMember will call notification in M5)

View File

@ -0,0 +1,102 @@
# Requirements
## Overview
Implement milestones M1-M4 of the Simple Groupware project: project foundation setup (Next.js 15), DB foundation (SQL wrapper + Migration), authentication & user management, and project & member management. Each milestone is developed on a separate branch and merged to main. Unit tests and E2E tests are mandatory.
## Background
The repository is currently a spec-driven-development boilerplate (vitest/eslint/prettier/husky configured, but no Next.js, no react, no SQLite). It must be transformed into the foundation of the Simple Groupware: a Next.js 15 + TypeScript + SQLite(better-sqlite3) application following the layered architecture (UI → Service → Repository → Data) defined in `docs/architecture.md`. M1-M4 establish the base that all subsequent milestones (M5+) depend on.
## Features to Implement
### 1. M1: Project Foundation Setup
- Next.js 15 (App Router, TypeScript) project configuration
- Tailwind CSS setup
- tsconfig with `@/*` path alias, strict mode
- next.config, .env.example
- Directory structure: app/, lib/, repositories/, services/, components/, tests/, data/, backups/
- ESLint (with Next.js plugin), Prettier, Husky, lint-staged, Vitest, Playwright setup
- CI config (GitHub Actions)
- package.json scripts: lint, format, typecheck, test, test:e2e, migrate, dev, build
- Dependencies: next, react, react-dom, better-sqlite3, bcrypt, react-markdown, remark-gfm, rehype-sanitize, tailwindcss, @types/better-sqlite3
- Remove boilerplate src/example.ts and src/example.test.ts
### 2. M2: DB Foundation (SQL Wrapper + Migration)
- `lib/db/sqlite.ts`: SqliteDatabase class (query/get/execute/transaction/close) + getDb() singleton (WAL, foreign_keys ON)
- `lib/db/migrator.ts`: Migrator class (filename-order execution, skip applied, 1-file-1-transaction, rollback on failure)
- `lib/db/migrations/001_initial.sql`: all 16 tables + indexes
- `lib/types/`: all Entity type definitions + enums
- `lib/db/run-migrations.ts`: migration runner script
- API: `GET /api/admin/migrations` (admin-only migration status)
- Unit tests: sqlite.test.ts, migrator.test.ts
### 3. M3: Authentication & User Management
- UserRepository (findById/findByEmail/create/update)
- AuthService (register/login/logout/getCurrentUser/updateProfile) with bcrypt password hashing
- Role management (system_admin/project_admin/member/guest), account enable/disable
- lib/auth/ (session.ts, getCurrentUser.ts)
- lib/validators/userValidator.ts
- API: register, login, logout, me, users/me
- Login page, profile page, root layout
- Auth middleware (redirect unauthenticated to login)
- Unit tests: UserRepository, AuthService; E2E test: auth.spec.ts
### 4. M4: Project & Member Management
- ProjectRepository, ProjectMemberRepository
- ProjectService (createProject/updateProject/addMember/removeMember/archiveProject/getDashboard) with permission checks
- projectValidator.ts
- API: projects CRUD, members CRUD
- Dashboard (project list), project overview, members page, settings page
- Layout components (Header, Sidebar, ProjectNav)
- Unit tests: ProjectRepository, ProjectMemberRepository, ProjectService; Integration test: project-member-permission; E2E test: project-management.spec.ts
## Acceptance Criteria
### M1
- [ ] `npm run dev` starts the Next.js dev server
- [ ] `npm run lint`, `npm run typecheck`, `npm run build` succeed
- [ ] Directory structure matches repository-structure.md
### M2
- [ ] `npm run migrate` creates the initial schema
- [ ] Migrations run in filename order and skip applied ones
- [ ] Failed migration rolls back
- [ ] Unit tests pass
### M3
- [ ] User registration, login, logout work
- [ ] Password is hashed with bcrypt
- [ ] Profile & avatar editable
- [ ] Inactive accounts cannot log in
- [ ] Unauthenticated access to protected screens is blocked
- [ ] Unit & E2E tests pass
### M4
- [ ] Project create/edit/delete/archive work
- [ ] Member add/remove/role work
- [ ] Non-members get 403
- [ ] Unit, Integration & E2E tests pass
## Success Metrics
- All Unit tests pass (`npm test`)
- All E2E tests pass (`npm run test:e2e`)
- Lint and typecheck clean
- Each milestone merged to main on its own branch
## Out of Scope
The following will not be implemented in this phase:
- M5-M15 (notifications, board, chat, SSE, todo, files, calendar, milestones, meetings, search, dashboard completion, backup)
- E2E tests for features beyond M3/M4 scope (board, chat, etc.)
- Full project dashboard content (only skeleton in M4; full content in M13)
## Reference Documents
- `docs/product-requirements.md` - Product Requirements Document
- `docs/functional-design.md` - Functional design document
- `docs/architecture.md` - Architecture design document
- `docs/repository-structure.md` - Repository structure document
- `docs/development-guidelines.md` - Development guidelines
- `docs/milestones.md` - Milestone & task definitions

View File

@ -0,0 +1,150 @@
# Task List
## 🚨 Principle of Fully Completing Tasks
**Keep working until all tasks in this file are complete**
### Mandatory Rules
- **Make every task `[x]`**
- "Planned as a separate task due to time constraints" is forbidden
- "Postponed because the implementation is too complex" is forbidden
- Do not finish work while leaving incomplete tasks (`[ ]`)
### The Only Case Where Skipping a Task Is Permitted
Skipping is possible only when one of the following technical reasons applies:
- A change in the implementation approach made the feature itself unnecessary
- An architecture change replaced it with a different implementation method
- A change in dependencies made the task impossible to execute
When skipping, always state the reason clearly:
```markdown
- [x] ~~task name~~ (unnecessary due to a change in approach: specific technical reason)
```
### If a Task Is Too Large
- Split the task into smaller subtasks
- Add the split subtasks to this file
- Complete the subtasks one by one
---
## Phase 1: M1 - Project Foundation Setup (branch: feature/m1-setup)
- [x] Create branch `feature/m1-setup` from main
- [x] Update package.json: name, scripts (dev/build/lint/format/typecheck/test/test:e2e/migrate), dependencies (next, react, react-dom, better-sqlite3, bcrypt, react-markdown, remark-gfm, rehype-sanitize), devDependencies (tailwindcss, @types/better-sqlite3, @types/bcrypt, @playwright/test, tsx, eslint-config-next)
- [x] Run `npm install` and confirm dependencies install successfully
- [x] Configure Next.js: create next.config.mjs (Node.js runtime), update tsconfig.json for Next.js (@/* path alias, jsx preserve, next plugin types), create app/globals.css (Tailwind directives), create tailwind.config.ts, postcss.config.mjs
- [x] Create Next.js app structure: app/layout.tsx (root layout), app/page.tsx (home redirect), app/globals.css
- [x] Create directory structure: lib/, repositories/, services/, components/, tests/unit, tests/integration, tests/e2e, data/.gitkeep, backups/.gitkeep
- [x] Remove boilerplate: delete src/example.ts, src/example.test.ts
- [x] Update vitest.config.ts (include tests/**, exclude .next), create playwright.config.ts
- [x] Update eslint.config.js (add Next.js plugin/ignores for .next), update .prettierrc if needed
- [x] Create .env.example (SQLITE_PATH, SESSION_SECRET)
- [x] Create CI config .github/workflows/ci.yml (lint, typecheck, test, build)
- [x] Commit M1, merge feature/m1-setup to main, push
## Phase 2: M2 - DB Foundation (branch: feature/m2-db-foundation)
- [ ] Create branch `feature/m2-db-foundation` from main
- [ ] Implement `lib/db/sqlite.ts`: SqliteDatabase class (query/get/execute/transaction/close) + getDb() singleton (WAL, foreign_keys ON)
- [ ] Implement `lib/db/migrator.ts`: Migrator class (schema_migrations table, filename-order, skip applied, 1-file-1-tx, rollback)
- [ ] Create `lib/db/migrations/001_initial.sql`: all 16 tables + indexes
- [ ] Create `lib/types/`: all Entity types + enums (User, Project, ProjectMember, BoardThread, BoardComment, ChatMessage, TodoColumn, TodoItem, FileAsset, ProjectNote, Milestone, CalendarEvent, Meeting, MeetingMember, Notification, ActivityLog, SchemaMigration + union types)
- [ ] Create `lib/db/run-migrations.ts`: migration runner script
- [ ] Implement API `GET /api/admin/migrations` (migration status, admin-only)
- [ ] Create test helper `tests/helpers/db.ts` (temp SQLite DB factory)
- [ ] Write Unit test `tests/unit/lib/db/sqlite.test.ts`
- [ ] Write Unit test `tests/unit/lib/db/migrator.test.ts`
- [ ] Run `npm run migrate` to verify schema creation
- [ ] Commit M2, merge feature/m2-db-foundation to main, push
## Phase 3: M3 - Auth & User Management (branch: feature/m3-auth-user)
- [ ] Create branch `feature/m3-auth-user` from main
- [ ] Create custom error classes `lib/errors.ts` (ValidationError, ForbiddenError, NotFoundError)
- [ ] Implement `lib/auth/session.ts` (session cookie read/write) and `lib/auth/getCurrentUser.ts`
- [ ] Implement `lib/validators/userValidator.ts`
- [ ] Implement `repositories/UserRepository.ts`
- [ ] Implement `services/AuthService.ts` (register/login/logout/getCurrentUser/updateProfile, bcrypt)
- [ ] Implement API routes: register, login, logout, me, users/me
- [ ] Implement auth middleware/guard (protected routes redirect to login)
- [ ] Implement `app/login/page.tsx`, `app/profile/page.tsx`, update `app/layout.tsx`
- [ ] Write Unit test `tests/unit/repositories/UserRepository.test.ts`
- [ ] Write Unit test `tests/unit/services/AuthService.test.ts`
- [ ] Write E2E test `tests/e2e/auth.spec.ts`
- [ ] Commit M3, merge feature/m3-auth-user to main, push
## Phase 4: M4 - Project & Member Management (branch: feature/m4-project-member)
- [ ] Create branch `feature/m4-project-member` from main
- [ ] Implement `lib/validators/projectValidator.ts`
- [ ] Implement `repositories/ProjectRepository.ts`
- [ ] Implement `repositories/ProjectMemberRepository.ts`
- [ ] Implement `services/ProjectService.ts` (createProject/updateProject/addMember/removeMember/archiveProject/getDashboard skeleton, permission checks)
- [ ] Implement API routes: projects (list/create), projects/[projectId] (detail/edit/delete), members (list/add), members/[userId] (remove)
- [ ] Implement `app/dashboard/page.tsx` (project list skeleton)
- [ ] Implement `app/projects/[projectId]/page.tsx` (overview skeleton)
- [ ] Implement `app/projects/[projectId]/members/page.tsx`
- [ ] Implement `app/projects/[projectId]/settings/page.tsx`
- [ ] Implement layout components: components/layout/Header.tsx, Sidebar.tsx, ProjectNav.tsx
- [ ] Write Unit test `tests/unit/repositories/ProjectRepository.test.ts`
- [ ] Write Unit test `tests/unit/repositories/ProjectMemberRepository.test.ts`
- [ ] Write Unit test `tests/unit/services/ProjectService.test.ts`
- [ ] Write Integration test `tests/integration/project-member-permission.test.ts`
- [ ] Write E2E test `tests/e2e/project-management.spec.ts`
- [ ] Commit M4, merge feature/m4-project-member to main, push
## Phase 5: Quality Check and Fixes
- [ ] Confirm that all tests pass
- [ ] `npm test`
- [ ] Confirm that there are no lint errors
- [ ] `npm run lint`
- [ ] Confirm that there are no type errors
- [ ] `npm run typecheck`
- [ ] Confirm that the build succeeds
- [ ] `npm run build`
## Phase 6: Documentation Updates
- [ ] Update README.md (setup instructions, scripts)
- [ ] Post-implementation retrospective (record at the bottom of this file)
---
## Post-Implementation Retrospective
### Implementation Completion Date
{YYYY-MM-DD}
### Differences Between Plan and Actual
**Points that differed from the plan**:
- {Technical changes not anticipated at planning time}
- {Changes in the implementation approach and the reasons}
**Tasks that became newly necessary**:
- {Tasks added during implementation}
- {Why the addition was necessary}
**Tasks skipped for technical reasons** (only when applicable):
- {Task name}
- Reason for skipping: {specific technical reason}
- Alternative implementation: {what it was replaced with}
**⚠️ Note**: Do not list tasks skipped for reasons such as "time constraints" or "difficulty" here. Completing all tasks is the principle.
### Lessons Learned
**Technical insights**:
- {Technical knowledge gained through implementation}
- {New technologies or patterns used}
**Process improvements**:
- {What went well in task management}
- {How the steering files were leveraged}
### Improvement Suggestions for Next Time
- {Things to watch out for in the next feature addition}
- {More efficient implementation methods}
- {Improvements to task planning}

3
app/globals.css Normal file
View File

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

20
app/layout.tsx Normal file
View File

@ -0,0 +1,20 @@
import type { Metadata } from 'next';
import './globals.css';
export const metadata: Metadata = {
title: 'シンプルグループウェア',
description:
'プロジェクト単位で情報共有・タスク管理を行えるチームコラボレーションツール',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ja">
<body>{children}</body>
</html>
);
}

10
app/page.tsx Normal file
View File

@ -0,0 +1,10 @@
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-8">
<h1 className="text-3xl font-bold"></h1>
<p className="mt-4 text-gray-600">
</p>
</main>
);
}

View File

@ -18,6 +18,16 @@ export default tseslint.config(
}, },
}, },
{ {
ignores: ['node_modules/**', 'dist/**', '.steering/**'], ignores: [
'node_modules/**',
'dist/**',
'.next/**',
'.steering/**',
'data/**',
'backups/**',
'playwright-report/**',
'test-results/**',
'next-env.d.ts',
],
} }
); );

View File

@ -0,0 +1,257 @@
-- 001_initial.sql
-- シンプルグループウェア 初期スキーマ
-- 全16テーブル + インデックス
-- 1. users: システム利用ユーザー
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password_hash TEXT,
avatar_url TEXT,
role TEXT NOT NULL DEFAULT 'member',
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
-- 2. projects: プロジェクト
CREATE TABLE projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL DEFAULT 'active',
owner_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (owner_id) REFERENCES users(id)
);
-- 3. project_members: プロジェクトメンバー
CREATE TABLE project_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
joined_at TEXT NOT NULL,
UNIQUE(project_id, user_id),
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
-- 4. board_threads: 掲示板スレッド
CREATE TABLE board_threads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
body_md TEXT NOT NULL,
author_id INTEGER NOT NULL,
category TEXT,
is_pinned INTEGER NOT NULL DEFAULT 0,
is_important INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- 5. board_comments: 掲示板コメント
CREATE TABLE board_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
thread_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
body_md TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (thread_id) REFERENCES board_threads(id) ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- 6. chat_messages: チャットメッセージ
CREATE TABLE chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
body TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- 7. todo_columns: ToDoカラム
CREATE TABLE todo_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
name TEXT NOT NULL,
order_index INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
);
-- 8. todo_items: ToDoタスク
CREATE TABLE todo_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
column_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
assignee_id INTEGER,
creator_id INTEGER NOT NULL,
priority TEXT NOT NULL DEFAULT 'normal',
start_date TEXT,
due_date TEXT,
completed_at TEXT,
order_index INTEGER NOT NULL DEFAULT 0,
milestone_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (column_id) REFERENCES todo_columns(id) ON DELETE CASCADE,
FOREIGN KEY (assignee_id) REFERENCES users(id),
FOREIGN KEY (creator_id) REFERENCES users(id)
);
-- 9. file_assets: ファイルアセット
CREATE TABLE file_assets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
uploader_id INTEGER NOT NULL,
filename TEXT NOT NULL,
original_name TEXT NOT NULL,
mime_type TEXT NOT NULL,
size INTEGER NOT NULL,
path TEXT NOT NULL,
created_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (uploader_id) REFERENCES users(id)
);
-- 10. project_notes: Markdownメモ
CREATE TABLE project_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
body_md TEXT NOT NULL,
tags TEXT,
is_pinned INTEGER NOT NULL DEFAULT 0,
created_by_id INTEGER NOT NULL,
updated_by_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES users(id),
FOREIGN KEY (updated_by_id) REFERENCES users(id)
);
CREATE INDEX idx_project_notes_project_id ON project_notes(project_id);
CREATE INDEX idx_project_notes_updated_at ON project_notes(updated_at);
-- 11. milestones: マイルストーン
CREATE TABLE milestones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
due_date TEXT,
status TEXT NOT NULL DEFAULT 'open',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
);
-- 12. calendar_events: カレンダーイベント
CREATE TABLE calendar_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
type TEXT NOT NULL,
start_at TEXT NOT NULL,
end_at TEXT,
created_by_id INTEGER NOT NULL,
related_todo_id INTEGER,
related_milestone_id INTEGER,
related_meeting_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES users(id)
);
-- 13. meetings: ミーティング
CREATE TABLE meetings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
location TEXT,
meeting_url TEXT,
start_at TEXT NOT NULL,
end_at TEXT NOT NULL,
agenda_md TEXT,
minutes_md TEXT,
created_by_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES users(id)
);
-- 14. meeting_members: ミーティング参加メンバー
CREATE TABLE meeting_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meeting_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'invited',
UNIQUE(meeting_id, user_id),
FOREIGN KEY (meeting_id) REFERENCES meetings(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- 15. notifications: 通知
CREATE TABLE notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
project_id INTEGER,
type TEXT NOT NULL,
title TEXT NOT NULL,
body TEXT,
read_at TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
);
-- 16. activity_logs: アクティビティログ
CREATE TABLE activity_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
actor_id INTEGER NOT NULL,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id INTEGER,
metadata_json TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (actor_id) REFERENCES users(id)
);
CREATE INDEX idx_activity_logs_project_id ON activity_logs(project_id);
CREATE INDEX idx_activity_logs_created_at ON activity_logs(created_at);
CREATE INDEX idx_notifications_user_id ON notifications(user_id);
CREATE INDEX idx_chat_messages_project_id ON chat_messages(project_id);
CREATE INDEX idx_board_threads_project_id ON board_threads(project_id);
CREATE INDEX idx_todo_items_project_id ON todo_items(project_id);
CREATE INDEX idx_meetings_project_id ON meetings(project_id);
CREATE INDEX idx_calendar_events_project_id ON calendar_events(project_id);

68
lib/db/migrator.ts Normal file
View File

@ -0,0 +1,68 @@
import fs from 'node:fs';
import path from 'node:path';
import { SqliteDatabase } from './sqlite';
/**
* SQLファイルベースのMigration機構。
* - Migrationファイルをファイル名順に実行する
* - 実行済みファイルは再実行しない
* - 1ファイルごとにトランザクションを張り、失敗時はロールバックする
*/
export class Migrator {
constructor(
private readonly db: SqliteDatabase,
private readonly migrationsDir: string
) {}
/**
* 未適用のMigrationをファイル名順に実行する
*/
migrate(): void {
this.ensureMigrationsTable();
const applied = this.db.query<{ filename: string }>(
'SELECT filename FROM schema_migrations'
);
const appliedSet = new Set(applied.map((x) => x.filename));
const files = fs
.readdirSync(this.migrationsDir)
.filter((file) => file.endsWith('.sql'))
.sort();
for (const file of files) {
if (appliedSet.has(file)) continue;
const fullPath = path.join(this.migrationsDir, file);
const sql = fs.readFileSync(fullPath, 'utf-8');
this.db.transaction(() => {
this.db.execute(sql);
this.db.execute(
`INSERT INTO schema_migrations (filename, applied_at) VALUES (@filename, @appliedAt)`,
{ filename: file, appliedAt: new Date().toISOString() }
);
});
}
}
/**
* 適用済みMigration一覧を取得する
*/
getAppliedMigrations(): { filename: string; applied_at: string }[] {
this.ensureMigrationsTable();
return this.db.query<{ filename: string; applied_at: string }>(
'SELECT filename, applied_at FROM schema_migrations ORDER BY filename'
);
}
private ensureMigrationsTable(): void {
this.db.execute(`
CREATE TABLE IF NOT EXISTS schema_migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL UNIQUE,
applied_at TEXT NOT NULL
)
`);
}
}

26
lib/db/run-migrations.ts Normal file
View File

@ -0,0 +1,26 @@
import path from 'node:path';
import fs from 'node:fs';
import { getDb, resetDbInstance } from './sqlite';
import { Migrator } from './migrator';
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
const dbDir = path.dirname(dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
const db = getDb();
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
const applied = migrator.getAppliedMigrations();
console.log(`Migrations applied: ${applied.length}`);
for (const m of applied) {
console.log(` - ${m.filename} (applied at ${m.applied_at})`);
}
db.close();
resetDbInstance();

90
lib/db/sqlite.ts Normal file
View File

@ -0,0 +1,90 @@
import Database from 'better-sqlite3';
export type SqlParams = Record<string, unknown> | unknown[];
export interface ExecuteResult {
changes: number;
lastInsertRowid: number | bigint;
}
/**
* SQLiteへのアクセスを一元管理する共通SQLラッパー。
* 各Repositoryは直接better-sqlite3を触らず、必ずこのクラスを通してSQLを実行する。
*/
export class SqliteDatabase {
private db: Database.Database;
constructor(dbPath: string) {
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('foreign_keys = ON');
}
/**
* 複数行を取得するSELECT
*/
query<T>(sql: string, params?: SqlParams): T[] {
return this.db.prepare(sql).all(params ?? {}) as T[];
}
/**
* 単一行を取得するSELECT該当なしの場合はnull
*/
get<T>(sql: string, params?: SqlParams): T | null {
const row = this.db.prepare(sql).get(params ?? {}) as T | undefined;
return row ?? null;
}
/**
* INSERT / UPDATE / DELETEを実行する
*/
execute(sql: string, params?: SqlParams): ExecuteResult {
const result = this.db.prepare(sql).run(params ?? {});
return {
changes: result.changes,
lastInsertRowid: result.lastInsertRowid,
};
}
/**
* トランザクション内でコールバックを実行する
*/
transaction<T>(callback: () => T): T {
const tx = this.db.transaction(callback);
return tx();
}
/**
* DB接続を閉じる
*/
close(): void {
this.db.close();
}
}
let instance: SqliteDatabase | null = null;
/**
* シングルトンのDB接続を取得する。
* dbPathは process.env.SQLITE_PATH ?? "./data/app.db"
*/
export function getDb(): SqliteDatabase {
if (!instance) {
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
instance = new SqliteDatabase(dbPath);
}
return instance;
}
/**
* テスト用途: シングルトンインスタンスをリセットする
*/
export function resetDbInstance(): void {
if (instance) {
instance.close();
instance = null;
}
}

241
lib/types/index.ts Normal file
View File

@ -0,0 +1,241 @@
/**
* 全Entity型定義・共有型
* functional-design.md のデータモデルに対応。
* タイムスタンプはISO8601文字列(TEXT)。真偽値はINTEGER(0/1)。
*/
// ===== 列挙型 =====
export type UserRole = 'system_admin' | 'project_admin' | 'member' | 'guest';
export type UserStatus = 'active' | 'inactive';
export type ProjectStatus = 'active' | 'on_hold' | 'completed' | 'archived';
export type ProjectMemberRole = 'admin' | 'member' | 'guest';
export type BoardCategory =
| 'notice'
| 'spec'
| 'minutes'
| 'question'
| 'decision'
| 'trouble'
| 'memo';
export type TodoPriority = 'low' | 'normal' | 'high';
export type MilestoneStatus = 'open' | 'closed';
export type CalendarEventType =
| 'meeting'
| 'deadline'
| 'milestone'
| 'todo'
| 'reminder'
| 'custom';
export type MeetingMemberStatus = 'invited' | 'accepted' | 'declined';
export type NotificationType =
| 'mention'
| 'todo_assigned'
| 'todo_due_soon'
| 'meeting_invited'
| 'board_commented'
| 'project_added'
| 'file_shared'
| 'note_updated';
// ===== エンティティ =====
export interface User {
id: number;
name: string;
email: string;
passwordHash: string | null;
avatarUrl: string | null;
role: UserRole;
status: UserStatus;
createdAt: string;
updatedAt: string;
}
export interface Project {
id: number;
name: string;
description: string | null;
status: ProjectStatus;
ownerId: number;
createdAt: string;
updatedAt: string;
}
export interface ProjectMember {
id: number;
projectId: number;
userId: number;
role: ProjectMemberRole;
joinedAt: string;
}
export interface BoardThread {
id: number;
projectId: number;
title: string;
bodyMd: string;
authorId: number;
category: BoardCategory | null;
isPinned: number;
isImportant: number;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface BoardComment {
id: number;
threadId: number;
authorId: number;
bodyMd: string;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface ChatMessage {
id: number;
projectId: number;
authorId: number;
body: string;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface TodoColumn {
id: number;
projectId: number;
name: string;
orderIndex: number;
createdAt: string;
updatedAt: string;
}
export interface TodoItem {
id: number;
projectId: number;
columnId: number;
title: string;
description: string | null;
assigneeId: number | null;
creatorId: number;
priority: TodoPriority;
startDate: string | null;
dueDate: string | null;
completedAt: string | null;
orderIndex: number;
milestoneId: number | null;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface FileAsset {
id: number;
projectId: number;
uploaderId: number;
filename: string;
originalName: string;
mimeType: string;
size: number;
path: string;
createdAt: string;
deletedAt: string | null;
}
export interface ProjectNote {
id: number;
projectId: number;
title: string;
bodyMd: string;
tags: string | null;
isPinned: number;
createdById: number;
updatedById: number;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface Milestone {
id: number;
projectId: number;
title: string;
description: string | null;
dueDate: string | null;
status: MilestoneStatus;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface CalendarEvent {
id: number;
projectId: number;
title: string;
description: string | null;
type: CalendarEventType;
startAt: string;
endAt: string | null;
createdById: number;
relatedTodoId: number | null;
relatedMilestoneId: number | null;
relatedMeetingId: number | null;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface Meeting {
id: number;
projectId: number;
title: string;
description: string | null;
location: string | null;
meetingUrl: string | null;
startAt: string;
endAt: string;
agendaMd: string | null;
minutesMd: string | null;
createdById: number;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface MeetingMember {
id: number;
meetingId: number;
userId: number;
status: MeetingMemberStatus;
}
export interface Notification {
id: number;
userId: number;
projectId: number | null;
type: NotificationType;
title: string;
body: string | null;
readAt: string | null;
createdAt: string;
}
export interface ActivityLog {
id: number;
projectId: number;
actorId: number;
action: string;
targetType: string;
targetId: number | null;
metadataJson: string | null;
createdAt: string;
}
export interface SchemaMigration {
id: number;
filename: string;
appliedAt: string;
}

6
next-env.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

6
next.config.mjs Normal file
View File

@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
serverExternalPackages: ['better-sqlite3', 'bcrypt'],
};
export default nextConfig;

12031
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,58 @@
{ {
"name": "opencode-spec-driven-boilerplate", "name": "opengroupware",
"version": "0.1.0", "version": "0.1.0",
"description": "Spec-driven development boilerplate for opencode", "description": "Simple project-based groupware built with Next.js 15, TypeScript, and SQLite",
"type": "module", "type": "module",
"scripts": { "scripts": {
"prepare": "husky", "prepare": "husky",
"build": "tsc", "dev": "next dev",
"dev": "tsc --watch", "build": "next build",
"start": "next start",
"lint": "eslint .", "lint": "eslint .",
"format": "npx prettier --write .", "format": "prettier --write .",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
"test:e2e": "playwright test",
"test:coverage": "vitest run --coverage", "test:coverage": "vitest run --coverage",
"test:ui": "vitest --ui" "migrate": "tsx lib/db/run-migrations.ts"
}, },
"keywords": [ "keywords": [
"spec-driven-development", "groupware",
"opencode", "nextjs",
"template" "sqlite"
], ],
"author": "", "author": "Ken Yasue",
"license": "MIT", "license": "MIT",
"dependencies": {
"bcrypt": "^5.1.1",
"better-sqlite3": "^11.3.0",
"next": "^15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^9.0.1",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0"
},
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.49.0",
"@types/bcrypt": "^5.0.2",
"@types/better-sqlite3": "^7.6.11",
"@types/node": "^20.11.0", "@types/node": "^20.11.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitest/coverage-v8": "^2.0.0", "@vitest/coverage-v8": "^2.0.0",
"@vitest/ui": "^2.0.0", "@vitest/ui": "^2.0.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"eslint-config-next": "^15.1.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"husky": "^9.0.0", "husky": "^9.0.0",
"lint-staged": "^15.2.0", "lint-staged": "^15.2.0",
"postcss": "^8.4.49",
"prettier": "^3.2.0", "prettier": "^3.2.0",
"tailwindcss": "^3.4.15",
"tsx": "^4.19.2",
"typescript": "~5.3.0", "typescript": "~5.3.0",
"typescript-eslint": "^8.0.0", "typescript-eslint": "^8.0.0",
"vitest": "^2.0.0" "vitest": "^2.0.0"

26
playwright.config.ts Normal file
View File

@ -0,0 +1,26 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests/e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
});

9
postcss.config.mjs Normal file
View File

@ -0,0 +1,9 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
export default config;

View File

@ -1,93 +0,0 @@
import { describe, it, expect } from 'vitest';
import { add, subtract, multiply, divide } from './example';
describe('Math operations', () => {
describe('add', () => {
it('正の数を足すと正しい結果が返る', () => {
// Given: 準備
const a = 2;
const b = 3;
// When: 実行
const result = add(a, b);
// Then: 検証
expect(result).toBe(5);
});
it('負の数を足すと正しい結果が返る', () => {
// Given: 準備
const a = -2;
const b = 3;
// When: 実行
const result = add(a, b);
// Then: 検証
expect(result).toBe(1);
});
});
describe('subtract', () => {
it('正の数を引くと正しい結果が返る', () => {
// Given: 準備
const a = 5;
const b = 3;
// When: 実行
const result = subtract(a, b);
// Then: 検証
expect(result).toBe(2);
});
});
describe('multiply', () => {
it('正の数をかけると正しい結果が返る', () => {
// Given: 準備
const a = 2;
const b = 3;
// When: 実行
const result = multiply(a, b);
// Then: 検証
expect(result).toBe(6);
});
it('0をかけると0が返る', () => {
// Given: 準備
const a = 5;
const b = 0;
// When: 実行
const result = multiply(a, b);
// Then: 検証
expect(result).toBe(0);
});
});
describe('divide', () => {
it('正の数で割ると正しい結果が返る', () => {
// Given: 準備
const a = 6;
const b = 3;
// When: 実行
const result = divide(a, b);
// Then: 検証
expect(result).toBe(2);
});
it('0で割るとエラーをスローする', () => {
// Given: 準備
const a = 5;
const b = 0;
// When/Then: 実行と検証
expect(() => divide(a, b)).toThrow('Division by zero is not allowed');
});
});
});

View File

@ -1,18 +0,0 @@
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
export function divide(a: number, b: number): number {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
}

14
tailwind.config.ts Normal file
View File

@ -0,0 +1,14 @@
import type { Config } from 'tailwindcss';
const config: Config = {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
};
export default config;

46
tests/helpers/db.ts Normal file
View File

@ -0,0 +1,46 @@
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { SqliteDatabase } from '@/lib/db/sqlite';
let counter = 0;
/**
* テスト用の一時SQLite DBを作成する。
* 実DB(一時ファイル)を使用し、テスト終了時に自動削除される。
*/
export function createTestDb(): SqliteDatabase {
const tmpDir = os.tmpdir();
const dbPath = path.join(
tmpDir,
`test-${process.pid}-${Date.now()}-${counter++}.db`
);
const db = new SqliteDatabase(dbPath);
const originalClose = db.close.bind(db);
db.close = () => {
originalClose();
if (fs.existsSync(dbPath)) {
fs.unlinkSync(dbPath);
}
const walPath = `${dbPath}-wal`;
const shmPath = `${dbPath}-shm`;
if (fs.existsSync(walPath)) fs.unlinkSync(walPath);
if (fs.existsSync(shmPath)) fs.unlinkSync(shmPath);
};
return db;
}
/**
* マイグレーション済みのテスト用DBを作成する
*/
export function createMigratedTestDb(): SqliteDatabase {
const db = createTestDb();
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { Migrator } = require('@/lib/db/migrator');
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
return db;
}

View File

@ -1,22 +1,33 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2022", "target": "ES2022",
"lib": ["dom", "dom.iterable", "ES2022"],
"module": "ESNext", "module": "ESNext",
"lib": ["ES2022"],
"moduleResolution": "bundler", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"allowJs": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"esModuleInterop": true, "esModuleInterop": true,
"outDir": "./dist", "isolatedModules": true,
"rootDir": "./src", "jsx": "preserve",
"incremental": true,
"noEmit": true,
"strict": true, "strict": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"skipLibCheck": true, "skipLibCheck": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"types": ["vitest/globals"] "plugins": [{ "name": "next" }],
"paths": {
"@/*": ["./*"]
}
}, },
"include": ["src/**/*"], "include": [
"exclude": ["node_modules", "dist"] "next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": ["node_modules", "dist", ".next", "data", "backups"]
} }

View File

@ -1,12 +1,15 @@
import { defineConfig } from 'vitest/config'; import { defineConfig } from 'vitest/config';
import path from 'node:path';
export default defineConfig({ export default defineConfig({
test: { test: {
globals: true, globals: true,
environment: 'node', environment: 'node',
include: [ include: [
'src/**/*.{test,spec}.{ts,tsx}',
'tests/**/*.{test,spec}.{ts,tsx}', 'tests/**/*.{test,spec}.{ts,tsx}',
'lib/**/*.{test,spec}.{ts,tsx}',
'repositories/**/*.{test,spec}.{ts,tsx}',
'services/**/*.{test,spec}.{ts,tsx}',
], ],
coverage: { coverage: {
provider: 'v8', provider: 'v8',
@ -14,9 +17,11 @@ export default defineConfig({
exclude: [ exclude: [
'node_modules/**', 'node_modules/**',
'dist/**', 'dist/**',
'.next/**',
'.steering/**', '.steering/**',
'**/*.config.{ts,js}', '**/*.config.{ts,js,mjs}',
'**/types/**', '**/types/**',
'tests/**',
], ],
thresholds: { thresholds: {
branches: 80, branches: 80,
@ -26,4 +31,9 @@ export default defineConfig({
}, },
}, },
}, },
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
},
},
}); });