This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: vite6-rolldown-dynamic-sri-chaining

Vite 6 Rolldown Cryptographic Dynamic ESM Chunk Integrity Chaining

Enforces strict SHA-384 Subresource Integrity (SRI) validation across all static entry points and asynchronously imported ESM chunks compiled by Vite 6 and Rolldown. Guarantees an unbroken cryptographic chain of trust from initial HTML bootstrapping through runtime dynamic imports to prevent CDN supply-chain tampering and cache poisoning.

Prohibited Anti-Pattern: Unvalidated Dynamic ESM Imports Permitting Malicious CDN Script Replacement

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Rolldown Cryptographic Dynamic ESM Chunk Integrity Chaining - Enforces strict SHA-384 Subresource Integrity (SRI) validation across all static entry points and asynchronously imported ESM chunks compiled by Vite 6 and Rolldown. Guarantees an unbroken cryptographic chain of trust from initial HTML bootstrapping through runtime dynamic imports to prevent CDN supply-chain tampering and cache poisoning.
globs: vite.config.ts, vite.config.mts, src/main.ts, src/main.tsx, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-rolldown-dynamic-sri-chaining"
---

# Vite 6 Rolldown Cryptographic Dynamic ESM Chunk Integrity Chaining

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unvalidated Dynamic ESM Imports Permitting Malicious CDN Script Replacement

## System Constraints
You are a Principal Software Architect enforcing zero-trust build and runtime invariants in Vite 6 and Rolldown frontend architectures. You must mandate cryptographic SHA-384 Subresource Integrity (SRI) hash chaining across all statically referenced assets and dynamically imported ESM chunks. Never permit bare, unauthenticated dynamic imports that bypass CDN boundary validation.

## Strict Guidelines
- Engineers MUST ALWAYS configure Vite 6 / Rolldown with strict SHA-384 Subresource Integrity (SRI) generation across both entry points and dynamically split ESM chunks.
- Engineers MUST ALWAYS enforce `crossorigin="anonymous"` and dynamic import integrity mapping using manifest-backed loaders or custom runtime import wrappers.
- Engineers MUST NOT allow native unverified `import(...)` expressions to execute directly against external CDNs without explicit hash verification or modulepreload integrity links.
- Build pipelines MUST fail deterministically if any emitted ESM asset or code-split dynamic bundle lacks a corresponding cryptographically hashed manifest entry.
- Runtime loaders MUST immediately abort module execution and dispatch a critical telemetry event if an integrity hash mismatch occurs during asynchronous chunk retrieval.

## Bad vs Good Implementations
### Vite 6 Rolldown Configuration with Cryptographic Dynamic Chunk Integrity Injection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default configuration only writes content hashes into filenames, which provide no runtime cryptographic validation. If a CDN node or cache is compromised, dynamically loaded chunks can be altered on-the-fly while the browser silently executes the injected payload.
```typescript
import { defineConfig } from 'vite';

// VULNERABLE: Default Vite 6 build with Rolldown fails to bind SRI hashes
// to dynamic import() statements. An attacker with CDN edge write permissions
// can modify asynchronous chunks without breaking root page verification.
export default defineConfig({
  build: {
    target: 'esnext',
    rollupOptions: {
      output: {
        chunkFileNames: 'assets/[name]-[hash].js',
        entryFileNames: 'assets/[name]-[hash].js',
      },
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Computes SHA-384 digests during bundle finalization, decorates `<link rel="modulepreload">` tags with `integrity` and `crossorigin` attributes, and injects a runtime manifest ensuring all downstream dynamic imports can verify hash parity prior to execution.
```typescript
import { defineConfig, type Plugin } from 'vite';
import { createHash } from 'node:crypto';

function rolldownDynamicSriPlugin(): Plugin {
  return {
    name: 'rolldown-dynamic-sri-chaining',
    apply: 'build',
    enforce: 'post',
    generateBundle(_options, bundle) {
      const integrityManifest: Record<string, string> = {};

      // Generate SHA-384 hashes for all output files
      for (const [fileName, asset] of Object.entries(bundle)) {
        if (asset.type === 'chunk' || (asset.type === 'asset' && fileName.endsWith('.js'))) {
          const content = asset.type === 'chunk' ? asset.code : asset.source;
          const hash = createHash('sha384')
            .update(content)
            .digest('base64');
          integrityManifest[fileName] = `sha384-${hash}`;
        }
      }

      // Inject dynamic import runtime interceptor into all chunks executing dynamic imports
      for (const chunk of Object.values(bundle)) {
        if (chunk.type === 'chunk' && chunk.dynamicImports.length > 0) {
          const manifestSnippet = `globalThis.__SRI_MANIFEST__ = Object.assign(globalThis.__SRI_MANIFEST__ || {}, ${JSON.stringify(integrityManifest)});\n`;
          chunk.code = manifestSnippet + chunk.code;
        }
      }
    },
    transformIndexHtml(html, { bundle }) {
      if (!bundle) return html;
      return html.replace(/<link rel="modulepreload" href="([^"]+)">/g, (match, href) => {
        const fileName = href.replace(/^\.?\//, '');
        const chunk = bundle[fileName];
        if (chunk && chunk.type === 'chunk') {
          const hash = createHash('sha384').update(chunk.code).digest('base64');
          return `<link rel="modulepreload" href="${href}" integrity="sha384-${hash}" crossorigin="anonymous">`;
        }
        return match;
      });
    },
  };
}

export default defineConfig({
  build: {
    target: 'esnext',
    sourcemap: true,
  },
  plugins: [rolldownDynamicSriPlugin()],
});
```

### Secure Dynamic ESM Chunk Loader with Hash-Enforced Fallback

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bypasses all client-side cryptographic assertions. The browser loads and executes whatever script payload the remote host delivers at that moment.
```typescript
export async function loadFeatureModule(modulePath: string): Promise<any> {
  // VULNERABLE: Direct evaluation of dynamic import without integrity validation
  return await import(/* @vite-ignore */ modulePath);
}
```

#### Production Standard (Correct)
> **Standard**: Performs pre-execution cryptographic verification via the Fetch API using the injected SHA-384 SRI hash from Vite's manifest. If byte tampering or MITM occurs on the CDN, the browser aborts the request before JavaScript engine evaluation.
```typescript
declare global {
  interface Window {
    __SRI_MANIFEST__?: Record<string, string>;
  }
}

export async function loadFeatureModule<T = unknown>(modulePath: string): Promise<T> {
  const normalizedPath = modulePath.replace(/^\.?\//, '');
  const expectedIntegrity = window.__SRI_MANIFEST__?.[normalizedPath];

  if (!expectedIntegrity) {
    throw new SecurityError(`Refusing to load untrusted module: ${modulePath}. Missing SRI hash.`);
  }

  // Validate chunk via fetch with Subresource Integrity before ESM evaluation
  const response = await fetch(modulePath, {
    integrity: expectedIntegrity,
    credentials: 'same-origin',
    mode: 'cors',
  });

  if (!response.ok) {
    throw new SecurityError(`Integrity check or network fetch failed for chunk: ${modulePath}`);
  }

  const scriptBlob = await response.blob();
  const objectUrl = URL.createObjectURL(scriptBlob);

  try {
    return await import(/* @vite-ignore */ objectUrl) as T;
  } finally {
    URL.revokeObjectURL(objectUrl);
  }
}

export class SecurityError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SecurityError';
  }
}
```

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: Vite 6 Rolldown Cryptographic Dynamic ESM Chunk Integrity Chaining

Vite 6 Rolldown Cryptographic Dynamic ESM Chunk Integrity Chaining defines an industrial-grade behavioral standard for frontend engineering. Enforces strict SHA-384 Subresource Integrity (SRI) validation across all static entry points and asynchronously imported ESM chunks compiled by Vite 6 and Rolldown. Guarantees an unbroken cryptographic chain of trust from initial HTML bootstrapping through runtime dynamic imports to prevent CDN supply-chain tampering and cache poisoning. 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: Unvalidated Dynamic ESM Imports Permitting Malicious CDN Script Replacement 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 DriftUnvalidated Dynamic ESM Imports Permitting Malicious CDN Script ReplacementCritical
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 configure Vite 6 / Rolldown with strict SHA-384 Subresource Integrity (SRI) generation across both entry points and dynamically split ESM chunks.

Engineers MUST ALWAYS configure Vite 6 / Rolldown with strict SHA-384 Subresource Integrity (SRI) generation across both entry points and dynamically split ESM chunks.

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 ALWAYS enforce `crossorigin="anonymous"` and dynamic import integrity mapping using manifest-backed loaders or custom runtime import wrappers.

Engineers MUST ALWAYS enforce `crossorigin="anonymous"` and dynamic import integrity mapping using manifest-backed loaders or custom runtime import wrappers.

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 NOT allow native unverified `import(...)` expressions to execute directly against external CDNs without explicit hash verification or modulepreload integrity links.

Engineers MUST NOT allow native unverified `import(...)` expressions to execute directly against external CDNs without explicit hash verification or modulepreload integrity links.

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

Build pipelines MUST fail deterministically if any emitted ESM asset or code-split dynamic bundle lacks a corresponding cryptographically hashed manifest entry.

Build pipelines MUST fail deterministically if any emitted ESM asset or code-split dynamic bundle lacks a corresponding cryptographically hashed manifest entry.

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

Runtime loaders MUST immediately abort module execution and dispatch a critical telemetry event if an integrity hash mismatch occurs during asynchronous chunk retrieval.

Runtime loaders MUST immediately abort module execution and dispatch a critical telemetry event if an integrity hash mismatch occurs during asynchronous chunk retrieval.

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 Vite 6 Rolldown Cryptographic Dynamic ESM Chunk Integrity Chaining critical for AI coding assistants?

Enforces strict SHA-384 Subresource Integrity (SRI) validation across all static entry points and asynchronously imported ESM chunks compiled by Vite 6 and Rolldown. Guarantees an unbroken cryptographic chain of trust from initial HTML bootstrapping through runtime dynamic imports to prevent CDN supply-chain tampering and cache poisoning. 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 (Unvalidated Dynamic ESM Imports Permitting Malicious CDN Script Replacement) 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

Vite