This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte5-runes-proxy-boundary-isolation

Svelte 5 Runes Proxy Boundary Isolation across Workers and Micro-Frontends

Svelte 5 wraps deeply reactive state in internal reactive proxies via `$state()` runes. Passing these proxies across thread boundaries (Web Workers) triggers structured clone algorithm failures (DataCloneError), while passing them across micro-frontend boundaries causes cross-runtime signal leaks, retain cycles, and untracked cascade reactivity. Engineers must enforce explicit boundary snapshotting and immutability fences using `$state.snapshot()` before data exits the Svelte reactive context.

Prohibited Anti-Pattern: Leaking Svelte 5 Reactive Proxy References Across Boundary Fences (Web Workers & Micro-Frontends)

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Proxy Boundary Isolation across Workers and Micro-Frontends - Svelte 5 wraps deeply reactive state in internal reactive proxies via `$state()` runes. Passing these proxies across thread boundaries (Web Workers) triggers structured clone algorithm failures (DataCloneError), while passing them across micro-frontend boundaries causes cross-runtime signal leaks, retain cycles, and untracked cascade reactivity. Engineers must enforce explicit boundary snapshotting and immutability fences using `$state.snapshot()` before data exits the Svelte reactive context.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte5-runes-proxy-boundary-isolation"
---

# Svelte 5 Runes Proxy Boundary Isolation across Workers and Micro-Frontends

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Leaking Svelte 5 Reactive Proxy References Across Boundary Fences (Web Workers & Micro-Frontends)

## System Constraints
You are a Principal Engineer enforcing Svelte 5 Runes Proxy Boundary Isolation. Mandate invariants that prevent reactive proxies created by `$state()` from breaching architectural boundaries such as Web Workers (`postMessage`), MessagePorts, CustomEvent payloads in micro-frontends, or non-reactive external SDK caches. Enforce explicit boundary sanitization using `$state.snapshot()` and defensive deep-freezing at inter-boundary gates.

## Strict Guidelines
- Engineers MUST ALWAYS invoke `$state.snapshot(target)` before passing reactive state across `postMessage()`, `BroadcastChannel`, or Web Worker boundaries to prevent `DataCloneError` and detached proxy serialization overhead.
- Engineers MUST NOT expose raw Svelte 5 `$state()` proxies through CustomEvent details, micro-frontend global buses (e.g., single-spa event bus, window-level dispatchers), or shared singleton caches.
- Code MUST sanitize external inputs arriving from Web Workers or Micro-Frontends before hydrating local `$state()` runes, ensuring data ownership remains strictly encapsulated within the local component lifecycle.
- Services MUST apply `Object.freeze()` or structural immutability to bridge payloads exposed across isolated micro-apps to prevent remote un-tracked mutations from inducing state tearing.
- Components NEVER store direct references to foreign runtime proxies; all external state must be deserialized, structurally validated (e.g., via Zod or TypeBox), and re-instantiated into local runes.

## Bad vs Good Implementations
### Dispatching Reactive State to a Web Worker Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing `this.state` directly transmits Svelte 5's internal reactive proxy. This causes browsers executing `structuredClone` inside `postMessage` to throw a `DataCloneError` on proxy traps or clone unexpected internal reactive descriptors, degrading performance and breaking memory isolation.
```typescript
import { workerPool } from './worker-pool';

interface SessionState {
  token: string;
  metrics: number[];
}

export class TelemetryBridge {
  // Reactive state proxy initialized via Svelte 5 rune
  state = $state<SessionState>({
    token: 'auth-123',
    metrics: [10, 20, 30]
  });

  syncMetrics(): void {
    // VIOLATION: Passing raw $state proxy to postMessage
    // Triggers DOMException: DataCloneError or silently leaks reactive internals
    workerPool.postMessage({
      type: 'SYNC_METRICS',
      payload: this.state
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Using `$state.snapshot(this.state)` strips away all Svelte reactive proxy metadata, producing a pure, structured-clone-compliant plain JavaScript object safe for cross-thread serialization.
```typescript
import { workerPool } from './worker-pool';

interface SessionState {
  token: string;
  metrics: number[];
}

export class TelemetryBridge {
  state = $state<SessionState>({
    token: 'auth-123',
    metrics: [10, 20, 30]
  });

  syncMetrics(): void {
    // INVARIANT: Take a non-reactive plain JS snapshot before the boundary transition
    const rawPayload: SessionState = $state.snapshot(this.state);

    workerPool.postMessage({
      type: 'SYNC_METRICS',
      payload: rawPayload
    });
  }
}
```

### Cross Micro-Frontend CustomEvent Communication

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Foreign micro-frontends (React, Vue, or disparate Svelte instances) receiving this proxy will retain references across lifecycles, causing severe memory leaks. Furthermore, direct mutations from foreign scripts bypass Svelte 5's effect-tracking context, causing state desynchronization and tearing.
```typescript
// Micro-frontend A: Svelte 5 Host Module
interface SharedContext {
  theme: string;
  user: { id: string };
}

export class BridgeService {
  appState = $state<SharedContext>({
    theme: 'dark',
    user: { id: 'usr_892' }
  });

  broadcastToForeignMFE(): void {
    // VIOLATION: Leaking active proxy to external non-Svelte MFE
    // Foreign runtime mutation causes untracked cascades and retain cycles
    window.dispatchEvent(new CustomEvent('mfe:state-sync', {
      detail: this.appState
    }));
  }
}
```

#### Production Standard (Correct)
> **Standard**: The snapshot is decoupled from the reactive graph and defensively cloned and frozen. Foreign micro-frontends can read the state without acquiring retain references to Svelte's reactive engine or causing out-of-band proxy mutations.
```typescript
// Micro-frontend A: Svelte 5 Host Module
interface SharedContext {
  theme: string;
  user: { id: string };
}

export class BridgeService {
  appState = $state<SharedContext>({
    theme: 'dark',
    user: { id: 'usr_892' }
  });

  broadcastToForeignMFE(): void {
    // INVARIANT: Extract snapshot and enforce deep immutability fence
    const pristine = $state.snapshot(this.appState);
    const frozenPayload = Object.freeze(structuredClone(pristine));

    window.dispatchEvent(new CustomEvent('mfe:state-sync', {
      detail: frozenPayload
    }));
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Svelte 5 Runes Proxy Boundary Isolation across Workers and Micro-Frontends

Svelte 5 Runes Proxy Boundary Isolation across Workers and Micro-Frontends defines an industrial-grade behavioral standard for frontend engineering. Svelte 5 wraps deeply reactive state in internal reactive proxies via `$state()` runes. Passing these proxies across thread boundaries (Web Workers) triggers structured clone algorithm failures (DataCloneError), while passing them across micro-frontend boundaries causes cross-runtime signal leaks, retain cycles, and untracked cascade reactivity. Engineers must enforce explicit boundary snapshotting and immutability fences using `$state.snapshot()` before data exits the Svelte reactive context. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Leaking Svelte 5 Reactive Proxy References Across Boundary Fences (Web Workers & Micro-Frontends) Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftLeaking Svelte 5 Reactive Proxy References Across Boundary Fences (Web Workers & Micro-Frontends)Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS invoke `$state.snapshot(target)` before passing reactive state across `postMessage()`, `BroadcastChannel`, or Web Worker boundaries to prevent `DataCloneError` and detached proxy serialization overhead.

Engineers MUST ALWAYS invoke `$state.snapshot(target)` before passing reactive state across `postMessage()`, `BroadcastChannel`, or Web Worker boundaries to prevent `DataCloneError` and detached proxy serialization overhead.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT expose raw Svelte 5 `$state()` proxies through CustomEvent details, micro-frontend global buses (e.g., single-spa event bus, window-level dispatchers), or shared singleton caches.

Engineers MUST NOT expose raw Svelte 5 `$state()` proxies through CustomEvent details, micro-frontend global buses (e.g., single-spa event bus, window-level dispatchers), or shared singleton caches.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST sanitize external inputs arriving from Web Workers or Micro-Frontends before hydrating local `$state()` runes, ensuring data ownership remains strictly encapsulated within the local component lifecycle.

Code MUST sanitize external inputs arriving from Web Workers or Micro-Frontends before hydrating local `$state()` runes, ensuring data ownership remains strictly encapsulated within the local component lifecycle.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST apply `Object.freeze()` or structural immutability to bridge payloads exposed across isolated micro-apps to prevent remote un-tracked mutations from inducing state tearing.

Services MUST apply `Object.freeze()` or structural immutability to bridge payloads exposed across isolated micro-apps to prevent remote un-tracked mutations from inducing state tearing.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store direct references to foreign runtime proxies

Components NEVER store direct references to foreign runtime proxies; all external state must be deserialized, structurally validated (e.g., via Zod or TypeBox), and re-instantiated into local runes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Svelte 5 Runes Proxy Boundary Isolation across Workers and Micro-Frontends critical for AI coding assistants?

Svelte 5 wraps deeply reactive state in internal reactive proxies via `$state()` runes. Passing these proxies across thread boundaries (Web Workers) triggers structured clone algorithm failures (DataCloneError), while passing them across micro-frontend boundaries causes cross-runtime signal leaks, retain cycles, and untracked cascade reactivity. Engineers must enforce explicit boundary snapshotting and immutability fences using `$state.snapshot()` before data exits the Svelte reactive context. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Leaking Svelte 5 Reactive Proxy References Across Boundary Fences (Web Workers & Micro-Frontends)) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Svelte