This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-sharedarraybuffer-zero-copy-streaming

Capacitor 7 Native-to-Webview Zero-Copy TypedArray Bridge Invariant

Mandates bounded zero-copy buffer transfers or SharedArrayBuffer ring-buffers via Web Workers for high-frequency native telemetry in Capacitor 7. Eliminates JSON bridge serialization overhead, GC thrashing, and UI main-thread frame drops during sensor, IMU, audio, and biometric data ingest.

Prohibited Anti-Pattern: Serializing Continuous High-Frequency Sensor Telemetry as JSON Across the Capacitor Bridge

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native-to-Webview Zero-Copy TypedArray Bridge Invariant - Mandates bounded zero-copy buffer transfers or SharedArrayBuffer ring-buffers via Web Workers for high-frequency native telemetry in Capacitor 7. Eliminates JSON bridge serialization overhead, GC thrashing, and UI main-thread frame drops during sensor, IMU, audio, and biometric data ingest.
globs: src/**/*.{ts,tsx}, src/workers/**/*.{ts,js}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-sharedarraybuffer-zero-copy-streaming"
---

# Capacitor 7 Native-to-Webview Zero-Copy TypedArray Bridge Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Serializing Continuous High-Frequency Sensor Telemetry as JSON Across the Capacitor Bridge

## System Constraints
You are a Principal Mobile Architect enforcing strict zero-copy streaming invariants between native runtimes (Android/iOS) and Capacitor 7 WebViews. You mandate that high-frequency biometric, IMU, or audio telemetry bypasses JSON-over-bridge serialization entirely. Require pre-allocated TypedArrays, SharedArrayBuffer ring buffers, or Transferable ArrayBuffers executed inside Web Workers with Atomics synchronization to preserve 60/120fps UI rendering.

## Strict Guidelines
- Engineers MUST NEVER emit high-frequency (>30Hz) sensor or biometric samples through standard Capacitor `notifyListeners` using JSON objects.
- Engineers MUST isolate high-frequency telemetry processing inside a dedicated Web Worker, completely off the UI main thread.
- Streaming bridges MUST utilize pre-allocated `SharedArrayBuffer` structures with `Atomics` or binary chunks piped via `Transferable` ArrayBuffers to achieve zero-copy semantics.
- Native plugins (Kotlin/Swift) MUST expose binary byte channels or native memory handles mapped directly into the WebView via custom asset loaders or direct buffer bridge calls.
- UI components MUST NEVER directly subscribe to raw sensor streams; they MUST consume downsampled, RAF-throttled view models published by the worker.

## Bad vs Good Implementations
### High-Frequency Native Telemetry Ingest Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Routing 100Hz+ sensor payloads through standard Capacitor plugin events causes excessive bridge JSON serialization, bridge message queue saturation, heavy GC pressure, and UI main-thread jank.
```typescript
import { Plugins } from '@capacitor/core';
const { BiometricSensorPlugin } = Plugins;

// Anti-pattern: Direct main-thread listener with JSON deserialization at 100Hz
export function setupSensorStream(onData: (val: number) => void) {
  BiometricSensorPlugin.addListener('onSample', (payload: { timestamp: number; ppgValue: number; ecgValue: number }) => {
    // Main thread JSON parse overhead + rapid GC allocation destroys 60/120fps UI render loop
    onData(payload.ppgValue);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Bypasses JSON serialization entirely using native binary transfers via Transferable ArrayBuffers into a Web Worker, updating a pre-allocated SharedArrayBuffer ring-buffer synchronized with Atomics, completely eliminating UI main-thread stutter.
```typescript
// worker.ts: Dedicated Web Worker processing binary stream via SharedArrayBuffer
const BUFFER_SIZE = 4096;
const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE * Float32Array.BYTES_PER_ELEMENT);
const ringBuffer = new Float32Array(sharedBuffer);
const stateBuffer = new Int32Array(new SharedArrayBuffer(4)); // Write pointer

self.onmessage = (event: MessageEvent<{ nativeStreamPort: MessagePort }>) => {
  const port = event.data.nativeStreamPort;
  port.onmessage = (msg: MessageEvent<ArrayBuffer>) => {
    // Zero-copy transfer: binary buffer transferred directly without serialization
    const incomingData = new Float32Array(msg.data);
    const currentHead = Atomics.load(stateBuffer, 0);
    
    for (let i = 0; i < incomingData.length; i++) {
      const targetIndex = (currentHead + i) % BUFFER_SIZE;
      ringBuffer[targetIndex] = incomingData[i];
    }
    
    Atomics.store(stateBuffer, 0, (currentHead + incomingData.length) % BUFFER_SIZE);
  };
};

export { sharedBuffer, stateBuffer };
```

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 Native-to-Webview Zero-Copy TypedArray Bridge Invariant

Capacitor 7 Native-to-Webview Zero-Copy TypedArray Bridge Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates bounded zero-copy buffer transfers or SharedArrayBuffer ring-buffers via Web Workers for high-frequency native telemetry in Capacitor 7. Eliminates JSON bridge serialization overhead, GC thrashing, and UI main-thread frame drops during sensor, IMU, audio, and biometric data ingest. 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: Serializing Continuous High-Frequency Sensor Telemetry as JSON Across the Capacitor Bridge 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 DriftSerializing Continuous High-Frequency Sensor Telemetry as JSON Across the Capacitor BridgeCritical
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 NEVER emit high-frequency (>30Hz) sensor or biometric samples through standard Capacitor `notifyListeners` using JSON objects.

Engineers MUST NEVER emit high-frequency (>30Hz) sensor or biometric samples through standard Capacitor `notifyListeners` using JSON objects.

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 isolate high-frequency telemetry processing inside a dedicated Web Worker, completely off the UI main thread.

Engineers MUST isolate high-frequency telemetry processing inside a dedicated Web Worker, completely off the UI main thread.

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

Streaming bridges MUST utilize pre-allocated `SharedArrayBuffer` structures with `Atomics` or binary chunks piped via `Transferable` ArrayBuffers to achieve zero-copy semantics.

Streaming bridges MUST utilize pre-allocated `SharedArrayBuffer` structures with `Atomics` or binary chunks piped via `Transferable` ArrayBuffers to achieve zero-copy semantics.

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

Native plugins (Kotlin/Swift) MUST expose binary byte channels or native memory handles mapped directly into the WebView via custom asset loaders or direct buffer bridge calls.

Native plugins (Kotlin/Swift) MUST expose binary byte channels or native memory handles mapped directly into the WebView via custom asset loaders or direct buffer bridge calls.

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

UI components MUST NEVER directly subscribe to raw sensor streams

UI components MUST NEVER directly subscribe to raw sensor streams; they MUST consume downsampled, RAF-throttled view models published by the worker.

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 Native-to-Webview Zero-Copy TypedArray Bridge Invariant critical for AI coding assistants?

Mandates bounded zero-copy buffer transfers or SharedArrayBuffer ring-buffers via Web Workers for high-frequency native telemetry in Capacitor 7. Eliminates JSON bridge serialization overhead, GC thrashing, and UI main-thread frame drops during sensor, IMU, audio, and biometric data ingest. 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 (Serializing Continuous High-Frequency Sensor Telemetry as JSON Across the Capacitor Bridge) 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