Architecture and Design Guidance
Description
Provides guidance on design decisions, architecture choices, and implementation approaches that align with the project's approved tech stack and patterns.
Trigger
Activated when users ask about design decisions, architecture choices, or implementation approaches.
Response Pattern
- Reference existing codebase patterns and conventions
- Suggest solutions that align with the approved tech stack (vanilla TS, Express, sql.js)
- Consider WSL compatibility requirements for database choices
- Follow established API patterns and frontend structure
- Explain trade-offs and rationale for recommendations
Examples
- "How should I structure this new API endpoint?"
- "What's the best way to handle this frontend state?"
- "Should I use a different database approach?"
Additional Context
This skill ensures architectural decisions maintain consistency with the project's vanilla TypeScript approach and WSL compatibility requirements.
High-Level Architecture Overview
Technology Stack
- Frontend: Vanilla HTML, CSS, and TypeScript (no frameworks)
- Backend: Node.js with Express.js framework
- Database: SQLite with sql.js driver for WSL compatibility
- ORM: TypeORM with DataMapper pattern
- Development Server: http-serve for local development
- Build System: TypeScript compilation with npm scripts
- Testing: Vitest (unit), Playwright (E2E)
Database Schema
The application uses TypeORM entities for data persistence:
Employee: Employee information and authenticationPtoEntry: PTO time-off entries with date ranges and hoursAcknowledgement: Monthly review acknowledgements- Additional entities for admin panel functionality
Core Tables
employees
id(INTEGER PRIMARY KEY): Auto-incrementing employee IDname(TEXT): Employee full nameidentifier(TEXT UNIQUE): Unique employee identifierpto_rate(REAL): PTO accrual rate per hour (default 0.71)carryover_hours(REAL): Carried over PTO hours from previous yearhire_date(DATE): Employee hire daterole(TEXT): Employee role (default 'Employee')hash(TEXT): Password hash for authentication
pto_entries
id(INTEGER PRIMARY KEY): Auto-incrementing entry IDemployee_id(INTEGER): Foreign key to employees tabledate(TEXT): Date of PTO entry (YYYY-MM-DD format)type(TEXT): PTO type ('Sick', 'PTO', 'Bereavement', 'Jury Duty')hours(REAL): Hours usedcreated_at(DATETIME): Entry creation timestamp
monthly_hours
id(INTEGER PRIMARY KEY): Auto-incrementing record IDemployee_id(INTEGER): Foreign key to employees tablemonth(TEXT): Month in YYYY-MM formathours_worked(REAL): Total hours worked in the monthsubmitted_at(DATETIME): Submission timestamp
acknowledgements
id(INTEGER PRIMARY KEY): Auto-incrementing acknowledgement IDemployee_id(INTEGER): Foreign key to employees tablemonth(TEXT): Month in YYYY-MM formatacknowledged_at(DATETIME): Acknowledgement timestamp
admin_acknowledgements
id(INTEGER PRIMARY KEY): Auto-incrementing admin acknowledgement IDemployee_id(INTEGER): Foreign key to employees tablemonth(TEXT): Month in YYYY-MM formatadmin_id(INTEGER): Foreign key to employees table (admin who acknowledged)acknowledged_at(DATETIME): Admin acknowledgement timestamp
sessions
token(TEXT PRIMARY KEY): Session tokenemployee_id(INTEGER): Foreign key to employees tableexpires_at(DATETIME): Session expiration timestamp
Database Constraints and Indexes
- Foreign key constraints enforce referential integrity
- Unique constraints on employee identifiers and session tokens
- Performance indexes on foreign keys and commonly queried fields
- CHECK constraints on PTO entry types
ORM Patterns
TypeORM Configuration
- Driver: sql.js for WSL compatibility
- Synchronization: Disabled (
synchronize: false) - schema managed manually via SQL files - Auto-save: Enabled for automatic database persistence
- Logging: Disabled in production
Entity Design Patterns
- Active Record Pattern: Not used - Data Mapper pattern preferred
- Repository Pattern: Used through TypeORM repositories for data access
- Entity Relationships:
@OneToManyfor parent-child relationships (Employee → PTO entries)@ManyToOnewith@JoinColumnfor foreign key relationships- Lazy loading by default, explicit joins for complex queries
Data Access Layer (DAL)
- Repository Injection: DAL classes receive DataSource and create repositories
- Business Logic Separation: Validation and calculations in dedicated modules
- Transaction Management: Explicit transactions for multi-table operations
- Query Building: TypeORM query builder for complex queries with joins and conditions
Common ORM Usage Patterns
// Repository usage
const employeeRepo = dataSource.getRepository(Employee);
const ptoEntryRepo = dataSource.getRepository(PtoEntry);
// Simple queries
const employee = await employeeRepo.findOne({ where: { id: employeeId } });
// Relations loading
const employeeWithEntries = await employeeRepo.findOne({
where: { id: employeeId },
relations: ["ptoEntries"],
});
// Complex queries with joins
const entries = await ptoEntryRepo.find({
where: { employee: { id: employeeId } },
relations: ["employee"],
});Service Layer Architecture
To maintain separation of concerns and improve testability, components must not directly instantiate or use APIClient. Instead, implement a service layer with dependency injection:
Service Layer Pattern
// Service interface
interface IEmployeeService {
getEmployees(): Promise<Employee[]>;
updateEmployee(id: number, data: Partial<Employee>): Promise<Employee>;
}
// Service implementation
class EmployeeService implements IEmployeeService {
constructor(private apiClient: APIClient) {}
async getEmployees(): Promise<Employee[]> {
return this.apiClient.get("/api/employees");
}
}
// Component with injected service
class AdminEmployeesPage extends BaseComponent {
constructor(private employeeService: IEmployeeService) {
super();
}
async loadData() {
const employees = await this.employeeService.getEmployees();
// render employees
}
}Dependency Injection
- Container: Use a simple DI container for service registration and resolution
- Injection: Services injected into components via constructors
- Mocking: Services easily mockable for unit testing
- Benefits: Loose coupling, improved testability, clear dependencies
Prohibited Patterns
- ❌ Direct APIClient instantiation in components
- ❌ HTTP logic mixed with UI logic
- ❌ Components making API calls directly
- ❌ Imperative DOM manipulation for responsive layouts
- ❌ JavaScript-based media query handling
- ❌ Global singletons and side effects
- ❌ Implicit state sharing through localStorage/globals
- ❌ Overuse of event delegation creating "event soup"
- ❌ UI messages mixed with business logic
- ❌ Hardcoded feature flags in code
Recommended Patterns
- ✅ Service interfaces for abstraction
- ✅ Dependency injection for loose coupling
- ✅ CSS-driven responsive layouts with grid/flexbox
- ✅ Declarative templates with attribute-based mode switching
- ✅ Context providers for scoped state management
- ✅ Component-level state with explicit dependencies
- ✅ Targeted event listeners with proper cleanup
- ✅ Custom events for component communication
- ✅ Pure business rules returning structured data
- ✅ Localization layer for UI messages
- ✅ Runtime configuration for feature flags
- ✅ Build-time flag elimination
- ✅ Event-driven data flow with service injection
- ✅ Pure business logic in services
Automated Systems
- Monthly Reminder Scheduler: Sends reminders for monthly PTO reviews
- Daily Follow-up System: Handles follow-up notifications and automated processes
Key Architectural Principles
- Vanilla Approach: No heavy frameworks, keeping the codebase lightweight and maintainable
- WSL Compatibility: Database and development setup work seamlessly in Windows Subsystem for Linux
- Separation of Concerns: Clear boundaries between frontend components, API endpoints, and business logic
- Service Layer: Components must use injected services instead of direct APIClient usage
- Event-Driven Architecture: Components dispatch custom events for data requests, parent components handle API calls and data injection
- Component Isolation: Web components should be data-agnostic and testable without direct API dependencies
- Type Safety: Full TypeScript coverage for reliability and developer experience
- Testability: Architecture designed to support comprehensive unit and E2E testing with mockable services
- Domain/Presentation Separation: Business rules return structured data (message keys), not UI strings. A dedicated messages module owns all user-facing text.
Business Rules / Messages Separation
Business rules (shared/businessRules.ts) must be pure domain logic — no UI strings, no message formatting. All user-facing text lives in shared/messages.ts.
Three-Layer Architecture
| Layer | Module | Returns | Knows about UI strings? |
|---|---|---|---|
| Domain | shared/businessRules.ts |
Structured error objects: { field, messageKey, params? } |
No — returns keys only |
| Messages | shared/messages.ts |
Formatted English strings | Yes — owns all UI text |
| Consumer | Components / Server | Calls resolveMessage(error.messageKey, error.params) |
Bridges domain → presentation |
Validation Functions
Validation functions return structured error objects with messageKey strings (not formatted messages):
// ✅ Correct — returns messageKey for consumer to resolve
export function validateHours(hours: number): ValidationError | null {
if (typeof hours !== "number" || isNaN(hours) || hours === 0) {
return { field: "hours", messageKey: "hours.invalid" };
}
return null;
}
// ❌ Prohibited — accessing message constants from businessRules.ts
export function checkThreshold(): string | null {
return VALIDATION_MESSAGES["some.key"]; // Don't do this
}Warning/Threshold Functions
Functions that produce warnings return messageKey strings (not formatted text):
// ✅ Returns key — consumer calls resolveMessage()
export function checkSickDayThreshold(
used: number,
requested: number,
): string | null {
if (used + requested > SICK_HOURS_BEFORE_PTO) {
return "sick.pto_required_after_threshold";
}
return null;
}Structured Violations (Import/Overuse)
Functions producing dynamic violation strings return structured objects with messageKey + params:
// ✅ Structured — consumer calls resolveMessage(v.messageKey, v.params)
interface StructuredViolation {
messageKey: string;
params?: Record<string, string | number>;
}
violations.push({
messageKey: "import.exceed_annual_limit",
params: { type: "Sick", projected: 28, limit: 24 },
});Consumer Pattern
// Component / server resolves message at point of display
import { resolveMessage } from "../shared/messages.js";
const msg = resolveMessage(error.messageKey, error.params);
// → "Sick hours would reach 28h, exceeding 24h annual limit"resolveMessage() API
function resolveMessage(
key: string,
params?: Record<string, string | number>,
): string;- Looks up
keyin all message catalogs (validation, success, notification, ui-error) - Substitutes
{placeholder}tokens withparamsvalues - Returns raw
keyas fallback if not found (aids debugging) - Single choke-point for future i18n (swap lookup to locale-specific catalog)
Prohibited Patterns
- ❌ Importing
VALIDATION_MESSAGESor any message constant inbusinessRules.ts - ❌ Business rule functions returning formatted English strings
- ❌ Inline string construction in domain logic (template literals with user text)
- ❌
formatLockedMessage()/formatMonthNotEndedMessage()style helpers in businessRules
Migration Reference
See TASKS/business-rules-separation.md for the full implementation plan including all message keys, affected files, and migration patterns.
Context Protocol
The application uses a lightweight context protocol for dependency injection into web components. Context providers wrap subtrees and intercept bubbling context-request events.
Providing Context
In App.run(), context providers wrap #app-wrapper:
import { createContextProvider, CONTEXT_KEYS } from "./shared/context.js";
const provider = createContextProvider(
CONTEXT_KEYS.NOTIFICATIONS,
notifications,
);
provider.style.display = "contents";
parentElement.insertBefore(provider, appWrapper);
provider.appendChild(appWrapper);Consuming Context
Components consume context in connectedCallback():
import { consumeContext, CONTEXT_KEYS } from "../../shared/context.js";
import type { TraceListener } from "../../controller/TraceListener.js";
class MyPage extends BaseComponent {
private _notifications: TraceListener | null = null;
connectedCallback() {
super.connectedCallback();
consumeContext<TraceListener>(this, CONTEXT_KEYS.NOTIFICATIONS, (svc) => {
this._notifications = svc;
});
}
private handleError(msg: string): void {
this._notifications?.error(msg); // nullable — safe in unit tests without provider
}
}Well-Known Context Keys
| Key | Value Type | Purpose |
|---|---|---|
NOTIFICATIONS |
TraceListener |
Toast notifications |
DEBUG |
DebugConsoleController |
Debug console bridge |
Context vs Constructor Injection
- Context protocol: For web components (DOM elements) that need shared services.
- Constructor injection: For plain classes like
UIManagerthat are not custom elements.
Event Delegation and data-action Convention
Standard Target Resolution
Use BaseComponent.resolveAction(e) to resolve the data-action attribute from a delegated event:
protected handleDelegatedClick(e: Event): void {
const hit = this.resolveAction(e);
if (!hit) return;
switch (hit.action) {
case "approve":
this.handleApprove(hit.target);
break;
case "reject":
this.handleReject(hit.target);
break;
}
}HTML Markup
Actionable elements carry data-action and optional data-* attributes:
<button data-action="approve" data-request-id="42">Approve</button>
<button data-action="reject" data-request-id="42">Reject</button>When to Use Delegation vs Direct Listeners
| Scenario | Pattern |
|---|---|
| Dynamic/repeated content | Delegation via data-action |
| Static buttons/controls | Direct addListener() |
| Cross-component data flow | Custom events |
| External events (window) | addListener() + addCleanup() |
Custom Event Catalog
All custom events are cataloged in client/shared/events.ts with typed detail interfaces.
Naming Conventions
| Pattern | Usage | Example |
|---|---|---|
noun-verb |
Action completed | employee-submit |
noun-data-request |
Component needs data | pto-data-request |
noun-changed |
State change notification | selection-changed |
Typed Dispatch
import { dispatchTypedEvent } from "../../shared/events.js";
dispatchTypedEvent(this, "employee-submit", { employee: { name: "Jane" } });Two-Click Confirmation Pattern
For destructive or important actions, use ConfirmationController from client/shared/confirmation-mixin.ts:
import { ConfirmationController } from "../../shared/confirmation-mixin.js";
class MyComponent extends BaseComponent {
private _confirm = new ConfirmationController();
disconnectedCallback() {
this._confirm.clearAll();
super.disconnectedCallback();
}
protected handleDelegatedClick(e: Event): void {
const hit = this.resolveAction(e);
if (!hit) return;
if (hit.action === "delete") {
this._confirm.handleClick(hit.target as HTMLButtonElement, () => {
this.executeDelete(hit.target);
});
}
}
}For conditional confirmation (only confirm under certain conditions):
this._confirm.handleConditionalClick(
btn,
hasNegativeBalance, // only require confirmation when true
() => this.executeApprove(requestId),
);StorageService Abstraction
Components that persist UI preferences (expanded state, selected month, etc.) use the StorageService interface from client/shared/storage.ts:
import type { StorageService } from "../../shared/storage.js";
import { LocalStorageAdapter } from "../../shared/storage.js";
class MyComponent extends BaseComponent {
private _storage: StorageService = new LocalStorageAdapter();
// Setter for test injection
set storage(svc: StorageService) {
this._storage = svc;
}
}Tests inject InMemoryStorage instead of mocking localStorage globals.
State Management Patterns
The application follows a layered state management approach — no global stores, no raw localStorage access outside the StorageService abstraction.
State Hierarchy (prefer higher over lower)
| Priority | Mechanism | Scope | Use Case |
|---|---|---|---|
| 1 | Context Protocol | Subtree (DOM-scoped) | Shared services: notifications, debug console |
| 2 | Custom Events | Parent ↔ child communication | Data requests, selection changes, action dispatches |
| 3 | Component Properties | Single component | Attributes, setters, internal state |
| 4 | StorageService | Persistent (localStorage) | UI preferences, cached user identity |
| 5 | Prohibited — use context or constructor injection |
Context Protocol (client/shared/context.ts)
Lightweight dependency injection for web components. A ContextProvider<T> element wraps a DOM subtree and intercepts bubbling context-request events from descendants.
Providing context (typically in App.run()):
const provider = createContextProvider(
CONTEXT_KEYS.NOTIFICATIONS,
notificationService,
);
provider.style.display = "contents";
parentElement.insertBefore(provider, appWrapper);
provider.appendChild(appWrapper);Consuming context (in any descendant component):
connectedCallback() {
super.connectedCallback();
consumeContext<TraceListener>(this, CONTEXT_KEYS.NOTIFICATIONS, (svc) => {
this._notifications = svc;
});
}Well-known context keys (CONTEXT_KEYS):
| Key | Type | Purpose |
|---|---|---|
NOTIFICATIONS |
TraceListener |
Toast notifications |
DEBUG |
DebugConsoleController |
Debug console bridge |
Adding a new context: define a key in CONTEXT_KEYS, wrap the subtree with createContextProvider(), and consume with consumeContext().
Event-Based Communication (client/shared/events.ts)
Components communicate through typed custom events — never through shared mutable state.
noun-verb— action completed:employee-submitnoun-data-request— component needs data:pto-data-requestnoun-changed— state notification:selection-changed,auth-state-changed
Use dispatchTypedEvent() for type-safe dispatch. Parent components listen and orchestrate API calls / data injection.
StorageService Injection
All localStorage access must go through StorageService — never call localStorage directly.
Constructor injection (for plain classes like AuthService):
class AuthService {
private storage: StorageService;
constructor(api?: APIClient, storage?: StorageService) {
this.storage = storage ?? new LocalStorageAdapter();
}
}Property injection (for web components):
class MyComponent extends BaseComponent {
private _storage: StorageService = new LocalStorageAdapter();
set storage(svc: StorageService) {
this._storage = svc;
}
}Test isolation: Inject InMemoryStorage — no global mocking required, no cross-test contamination.
Prohibited State Patterns
- ❌ Raw
localStorage/sessionStoragecalls outsideStorageService - ❌ Global singletons (
window.appState, module-level mutable objects) - ❌ Constructor side-effects (fetching data, subscribing to events in constructors)
- ❌ Implicit state sharing between components through DOM globals
- ❌ Mutable shared references passed by identity between components