This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-wasm-cross-origin-isolation-guardrail

Capacitor 7 WebAssembly SharedArrayBuffer & Cross-Origin Isolation Architecture

Mandates native WebView header synthesis (COOP/COEP) and isolated worker contexts for multi-threaded WebAssembly in Capacitor 7. Guarantees zero-copy SharedArrayBuffer stability while preventing UI thread deadlocks and native bridge message queue stalls.

Prohibited Anti-Pattern: Instantiating Multi-Threaded WASM on Main UI Thread Without Native COOP/COEP Header Interception

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 WebAssembly SharedArrayBuffer & Cross-Origin Isolation Architecture - Mandates native WebView header synthesis (COOP/COEP) and isolated worker contexts for multi-threaded WebAssembly in Capacitor 7. Guarantees zero-copy SharedArrayBuffer stability while preventing UI thread deadlocks and native bridge message queue stalls.
globs: src/**/*.{ts,tsx}, capacitor.config.ts, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-wasm-cross-origin-isolation-guardrail"
---

# Capacitor 7 WebAssembly SharedArrayBuffer & Cross-Origin Isolation Architecture

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Instantiating Multi-Threaded WASM on Main UI Thread Without Native COOP/COEP Header Interception

## System Constraints
You are a Principal Software Architect enforcing production-grade WebAssembly, SharedArrayBuffer, and Cross-Origin Isolation architecture inside Capacitor 7 hybrid mobile applications. You strictly prohibit unisolated SAB allocations, main-thread Atomics blocking, and unhandled COOP/COEP WebView asset rejections.

## Strict Guidelines
- Engineers MUST ALWAYS verify `self.crossOriginIsolated === true` before attempting to allocate `SharedArrayBuffer` instances or instantiating multi-threaded WASM compilation pipelines.
- Engineers MUST NEVER execute blocking `Atomics.wait()` or compute-intensive WASM kernels on the main JavaScript thread; all parallel execution MUST occur inside dedicated Web Workers.
- Engineers MUST ensure that local and packaged assets delivered via Capacitor's native asset schemes (`https://localhost` on Android/iOS) return `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (or `credentialless`).
- External cross-origin assets (e.g., CDN images, audio chunks) loaded into an isolated WebView MUST declare explicit CORS attributes or be requested via `@capacitor/http` to circumvent COEP-induced asset blocking.
- Worker instantiations MUST manage graceful degradation paths for non-isolated legacy WebView fallbacks without causing hard uncaught native bridge runtime crashes.

## Bad vs Good Implementations
### WASM Worker Runtime Initialization and Cross-Origin Isolation Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attempting to allocate a shared WebAssembly.Memory or SharedArrayBuffer without confirming `crossOriginIsolated` throws an unhandled TypeError. Furthermore, calling `Atomics.wait` on the main thread will throw a RangeError in modern WebViews and stall the native Capacitor bridge, permanently freezing user input and native plugin communication.
```typescript
import { initWasmKernel } from './wasm-loader';

export async function startAudioProcessing(bufferSize: number): Promise<void> {
  // Anti-pattern: Blindly instantiating SharedArrayBuffer without checking isolation state.
  // In Capacitor 7, this triggers a ReferenceError or silent allocation crash on unconfigured WebViews.
  const memory = new WebAssembly.Memory({
    initial: 256,
    maximum: 512,
    shared: true // Throws TypeError if crossOriginIsolated is false
  });

  const rawBuffer = new SharedArrayBuffer(bufferSize);
  
  // Anti-pattern: Running blocking WASM on the main thread freezes the Capacitor bridge
  const kernel = await initWasmKernel(memory);
  kernel.processAudio(rawBuffer);
  
  // Deadlocks the Capacitor native message dispatch thread
  Atomics.wait(new Int32Array(rawBuffer), 0, 0);
}
```

#### Production Standard (Correct)
> **Standard**: Validates `self.crossOriginIsolated` prior to memory instantiation, handles runtime fallback gracefully, and delegates shared-memory synchronization strictly to a background Web Worker, ensuring zero-copy throughput without stalling the Capacitor native bridge.
```typescript
export interface WasmInitResult {
  success: boolean;
  worker?: Worker;
  error?: string;
}

export async function initializeThreadedWasm(
  workerScriptUrl: URL,
  bufferByteLength: number
): Promise<WasmInitResult> {
  // Invariant 1: Assert crossOriginIsolated is enabled by native COOP/COEP configuration
  if (!self.crossOriginIsolated) {
    return {
      success: false,
      error: 'CRITICAL: Environment is not crossOriginIsolated. Verify Capacitor native COOP/COEP headers.'
    };
  }

  try {
    // Invariant 2: Shared buffers must be orchestrated via Dedicated Workers, never main thread
    const sharedBuffer = new SharedArrayBuffer(bufferByteLength);
    const worker = new Worker(workerScriptUrl, { type: 'module' });

    await new Promise<void>((resolve, reject) => {
      const timeoutId = setTimeout(() => reject(new Error('Worker handshake timed out')), 5000);

      worker.onmessage = (event: MessageEvent<{ type: string }>) => {
        if (event.data.type === 'READY') {
          clearTimeout(timeoutId);
          resolve();
        }
      };

      worker.onerror = (err: ErrorEvent) => {
        clearTimeout(timeoutId);
        reject(new Error(`Worker boot error: ${err.message}`));
      };

      // Send shared buffer reference to worker for background Atomics operations
      worker.postMessage({ type: 'INIT', sharedBuffer });
    });

    return { success: true, worker };
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown WASM initialization error';
    return { success: false, error: message };
  }
}
```

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: Capacitor 7 WebAssembly SharedArrayBuffer & Cross-Origin Isolation Architecture

Capacitor 7 WebAssembly SharedArrayBuffer & Cross-Origin Isolation Architecture defines an industrial-grade behavioral standard for mobile engineering. Mandates native WebView header synthesis (COOP/COEP) and isolated worker contexts for multi-threaded WebAssembly in Capacitor 7. Guarantees zero-copy SharedArrayBuffer stability while preventing UI thread deadlocks and native bridge message queue stalls. 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: Instantiating Multi-Threaded WASM on Main UI Thread Without Native COOP/COEP Header Interception 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 DriftInstantiating Multi-Threaded WASM on Main UI Thread Without Native COOP/COEP Header InterceptionCritical
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 verify `self.crossOriginIsolated === true` before attempting to allocate `SharedArrayBuffer` instances or instantiating multi-threaded WASM compilation pipelines.

Engineers MUST ALWAYS verify `self.crossOriginIsolated === true` before attempting to allocate `SharedArrayBuffer` instances or instantiating multi-threaded WASM compilation pipelines.

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 NEVER execute blocking `Atomics.wait()` or compute-intensive WASM kernels on the main JavaScript thread

Engineers MUST NEVER execute blocking `Atomics.wait()` or compute-intensive WASM kernels on the main JavaScript thread; all parallel execution MUST occur inside dedicated Web Workers.

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

Engineers MUST ensure that local and packaged assets delivered via Capacitor's native asset schemes (`https

Engineers MUST ensure that local and packaged assets delivered via Capacitor's native asset schemes (`https://localhost` on Android/iOS) return `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (or `credentialless`).

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

External cross-origin assets (e.g., CDN images, audio chunks) loaded into an isolated WebView MUST declare explicit CORS attributes or be requested via `@capacitor/http` to circumvent COEP-induced asset blocking.

External cross-origin assets (e.g., CDN images, audio chunks) loaded into an isolated WebView MUST declare explicit CORS attributes or be requested via `@capacitor/http` to circumvent COEP-induced asset blocking.

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

Worker instantiations MUST manage graceful degradation paths for non-isolated legacy WebView fallbacks without causing hard uncaught native bridge runtime crashes.

Worker instantiations MUST manage graceful degradation paths for non-isolated legacy WebView fallbacks without causing hard uncaught native bridge runtime crashes.

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 Capacitor 7 WebAssembly SharedArrayBuffer & Cross-Origin Isolation Architecture critical for AI coding assistants?

Mandates native WebView header synthesis (COOP/COEP) and isolated worker contexts for multi-threaded WebAssembly in Capacitor 7. Guarantees zero-copy SharedArrayBuffer stability while preventing UI thread deadlocks and native bridge message queue stalls. 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 (Instantiating Multi-Threaded WASM on Main UI Thread Without Native COOP/COEP Header Interception) 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 MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor