engineering-patterns

A set of software-organisation patterns for SvelteKit, TypeScript, and Supabase applications. The patterns separate interface components, business services, data repositories, and third-party adapters.

In plain words
What is it for?
Use it when structuring a SvelteKit app, organising data access, wrapping external services, sharing client state, or choosing patterns such as factories and repositories.
Why use it?
Separating these responsibilities makes browser-based application code easier to organise, test, and change when data sources or behaviours change.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/wesselgrift/sveltekit-spa/engineering-patterns
Clone the repo
git clone --depth 1 https://github.com/wesselgrift/sveltekit-spa

Made for: Cursor.

Per session 72 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 3,766 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00072 $0.03766
Opus 5 $0.00036 $0.01883
Sonnet 5 $0.00014 $0.00753
Haiku 4.5 $0.00007 $0.00377

Measured 2d ago against content hash f3e3328a5860, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

engineering-patterns scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/engineering-patterns.mdc · 447 lines

How it starts

The opening of the file, as written. The whole thing — 447 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Engineering Patterns for SvelteKit

This project runs in SPA mode (ssr = false). All code executes in the browser — there are no server routes, server hooks, or server-side rendering.

SPA implications for pattern selection:

  • Module-level singletons are safe (one user per tab, no cross-request leakage).
  • Strategies wrap client-side SDKs or call external APIs/edge functions.
  • Observer patterns use Svelte 5 runes; event buses are client-side only.
  • Services and repositories run entirely in the browser via the Supabase client SDK.
  • If the project ever migrates to SSR, re-evaluate Singleton and Observer patterns for per-request safety.

Composition flow — patterns layer in one direction:

Component → Service → Repository → Adapter (wraps SDK)
                                  ↑
                            Singleton (shared client)

Components call services. Services enforce business rules and call repositories. Repositories abstract data access. Adapters wrap third-party SDKs. Singletons provide shared client instances. Strategies and Factories are cross-cutting — used wherever swappable behavior or complex construction is needed.

============================================================

  1. Factory — centralized object creation ============================================================ Use a factory when constructing objects requires conditional logic, defaults, or async setup that callers should not repeat.
  • Export a plain function (or async function) that returns a fully configured instance.
  • Keep construction details hidden; callers receive a typed result.
  • Prefer a factory over a class constructor when multiple creation paths exist.
  • For costly async setup (remote config, auth token exchange), await the factory once at init time and reuse the result.
// src/lib/api/create-api-client.ts
import type { ApiClient } from './types';

// Async factory — resolves auth headers before returning a ready client.
export async function createApiClient(baseUrl: string): Promise<ApiClient> {
  const token = await fetchServiceToken();
  const headers = { Authorization: `Bearer ${token}` };

  return {
    get: async (path) => fetch(`${baseUrl}${path}`, { headers }).then((r) => r.json()),
    post: async (path, body) =>
      fetch(`${baseUrl}${path}`, {
        method: 'POST',
        headers: { ...headers, 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      }).then((r) => r.json()),
  };
}

Avoid:

  • Scattering construction logic across multiple call sites — centralize it in the factory.
  • Returning partially initialized objects — the factory's output must be ready to use.

============================================================ 2) Repository — data access abstraction

Encapsulate all Supabase table operations behind a repository interface so business logic never depends on Supabase directly.

  • Define an interface describing the data operations (find, create, update, delete).
  • Implement with Supabase queries; export the concrete implementation as the default.
  • For tests, provide a mock factory that satisfies the same interface with in-memory storage.
  • Place repositories in src/lib/database/repositories/.
  • Select only the columns you need — avoid select('*').
  • Let Supabase errors propagate — the service layer is responsible for catching and transforming them.
// src/lib/database/repositories/types.ts
export interface ProjectRepository {
  findById(id: string): Promise<Project | null>;
  findByOwner(ownerId: string): Promise<Project[]>;
  create(data: CreateProjectInput): Promise<Project>;
  update(id: string, data: UpdateProjectInput): Promise<Project>;
  remove(id: string): Promise<void>;
}
// src/lib/database/repositories/project-repository.ts
import { supabase } from '$lib/supabase/client';
import type { ProjectRepository } from './types';

export const projectRepository: ProjectRepository = {
  async findById(id) {
    const { data, error } = await supabase
      .from('projects')
      .select('id, name, owner_id, created_at')
      .eq('id', id)
      .maybeSingle();
    if (error) throw error;
    return data;
  },
  // ... remaining methods follow the same shape
};

Read the full file on GitHub · 447 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 447 lines · 72 tokens per session scan A f3e3328a5860

Subscribe to this mod's changes

engineering-patterns is a cursor rule published in the GitHub repository wesselgrift/sveltekit-spa (37 stars, last pushed 5mo ago), licensed MIT. It adds 72 tokens to every session and 3,766 once invoked, about $0.0004 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.