@tanstack/start-plugin-core 1.166.11 → 1.166.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/build-sitemap.js +94 -123
- package/dist/esm/build-sitemap.js.map +1 -1
- package/dist/esm/constants.js +15 -20
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/dev-server-plugin/dev-styles.js +137 -150
- package/dist/esm/dev-server-plugin/dev-styles.js.map +1 -1
- package/dist/esm/dev-server-plugin/extract-html-scripts.js +16 -15
- package/dist/esm/dev-server-plugin/extract-html-scripts.js.map +1 -1
- package/dist/esm/dev-server-plugin/plugin.js +125 -195
- package/dist/esm/dev-server-plugin/plugin.js.map +1 -1
- package/dist/esm/import-protection-plugin/ast.js +6 -5
- package/dist/esm/import-protection-plugin/ast.js.map +1 -1
- package/dist/esm/import-protection-plugin/constants.js +20 -22
- package/dist/esm/import-protection-plugin/constants.js.map +1 -1
- package/dist/esm/import-protection-plugin/defaults.js +35 -25
- package/dist/esm/import-protection-plugin/defaults.js.map +1 -1
- package/dist/esm/import-protection-plugin/extensionlessAbsoluteIdResolver.js +93 -92
- package/dist/esm/import-protection-plugin/extensionlessAbsoluteIdResolver.js.map +1 -1
- package/dist/esm/import-protection-plugin/matchers.js +23 -24
- package/dist/esm/import-protection-plugin/matchers.js.map +1 -1
- package/dist/esm/import-protection-plugin/plugin.js +1045 -1361
- package/dist/esm/import-protection-plugin/plugin.js.map +1 -1
- package/dist/esm/import-protection-plugin/postCompileUsage.js +58 -55
- package/dist/esm/import-protection-plugin/postCompileUsage.js.map +1 -1
- package/dist/esm/import-protection-plugin/rewriteDeniedImports.js +187 -259
- package/dist/esm/import-protection-plugin/rewriteDeniedImports.js.map +1 -1
- package/dist/esm/import-protection-plugin/sourceLocation.js +238 -248
- package/dist/esm/import-protection-plugin/sourceLocation.js.map +1 -1
- package/dist/esm/import-protection-plugin/trace.js +173 -184
- package/dist/esm/import-protection-plugin/trace.js.map +1 -1
- package/dist/esm/import-protection-plugin/utils.js +132 -111
- package/dist/esm/import-protection-plugin/utils.js.map +1 -1
- package/dist/esm/import-protection-plugin/virtualModules.js +214 -194
- package/dist/esm/import-protection-plugin/virtualModules.js.map +1 -1
- package/dist/esm/index.js +2 -7
- package/dist/esm/load-env-plugin/plugin.js +12 -11
- package/dist/esm/load-env-plugin/plugin.js.map +1 -1
- package/dist/esm/output-directory.js +10 -10
- package/dist/esm/output-directory.js.map +1 -1
- package/dist/esm/plugin.js +275 -355
- package/dist/esm/plugin.js.map +1 -1
- package/dist/esm/post-server-build.js +39 -53
- package/dist/esm/post-server-build.js.map +1 -1
- package/dist/esm/prerender.js +177 -239
- package/dist/esm/prerender.js.map +1 -1
- package/dist/esm/preview-server-plugin/plugin.js +41 -44
- package/dist/esm/preview-server-plugin/plugin.js.map +1 -1
- package/dist/esm/queue.js +115 -126
- package/dist/esm/queue.js.map +1 -1
- package/dist/esm/resolve-entries.js +31 -32
- package/dist/esm/resolve-entries.js.map +1 -1
- package/dist/esm/schema.js +156 -179
- package/dist/esm/schema.js.map +1 -1
- package/dist/esm/start-compiler-plugin/compiler.js +655 -812
- package/dist/esm/start-compiler-plugin/compiler.js.map +1 -1
- package/dist/esm/start-compiler-plugin/handleClientOnlyJSX.js +25 -8
- package/dist/esm/start-compiler-plugin/handleClientOnlyJSX.js.map +1 -1
- package/dist/esm/start-compiler-plugin/handleCreateIsomorphicFn.js +22 -19
- package/dist/esm/start-compiler-plugin/handleCreateIsomorphicFn.js.map +1 -1
- package/dist/esm/start-compiler-plugin/handleCreateMiddleware.js +20 -22
- package/dist/esm/start-compiler-plugin/handleCreateMiddleware.js.map +1 -1
- package/dist/esm/start-compiler-plugin/handleCreateServerFn.js +187 -255
- package/dist/esm/start-compiler-plugin/handleCreateServerFn.js.map +1 -1
- package/dist/esm/start-compiler-plugin/handleEnvOnly.js +23 -33
- package/dist/esm/start-compiler-plugin/handleEnvOnly.js.map +1 -1
- package/dist/esm/start-compiler-plugin/plugin.js +247 -291
- package/dist/esm/start-compiler-plugin/plugin.js.map +1 -1
- package/dist/esm/start-compiler-plugin/utils.js +27 -27
- package/dist/esm/start-compiler-plugin/utils.js.map +1 -1
- package/dist/esm/start-manifest-plugin/manifestBuilder.js +272 -378
- package/dist/esm/start-manifest-plugin/manifestBuilder.js.map +1 -1
- package/dist/esm/start-manifest-plugin/plugin.js +35 -44
- package/dist/esm/start-manifest-plugin/plugin.js.map +1 -1
- package/dist/esm/start-router-plugin/constants.js +6 -5
- package/dist/esm/start-router-plugin/constants.js.map +1 -1
- package/dist/esm/start-router-plugin/generator-plugins/prerender-routes-plugin.js +24 -19
- package/dist/esm/start-router-plugin/generator-plugins/prerender-routes-plugin.js.map +1 -1
- package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.js +28 -29
- package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.js.map +1 -1
- package/dist/esm/start-router-plugin/plugin.js +146 -199
- package/dist/esm/start-router-plugin/plugin.js.map +1 -1
- package/dist/esm/start-router-plugin/pruneServerOnlySubtrees.js +32 -31
- package/dist/esm/start-router-plugin/pruneServerOnlySubtrees.js.map +1 -1
- package/dist/esm/utils.js +14 -14
- package/dist/esm/utils.js.map +1 -1
- package/package.json +7 -7
- package/dist/esm/index.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sources":["../../../src/import-protection-plugin/plugin.ts"],"sourcesContent":["import { normalizePath } from 'vite'\n\nimport { resolveViteId } from '../utils'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { ImportGraph, buildTrace, formatViolation } from './trace'\nimport {\n getDefaultImportProtectionRules,\n getMarkerSpecifiers,\n} from './defaults'\nimport { compileMatchers, matchesAny } from './matchers'\nimport {\n buildResolutionCandidates,\n buildSourceCandidates,\n canonicalizeResolvedId,\n clearNormalizeFilePathCache,\n debugLog,\n dedupePatterns,\n escapeRegExp,\n extractImportSources,\n getOrCreate,\n isInsideDirectory,\n matchesDebugFilter,\n normalizeFilePath,\n relativizePath,\n shouldDeferViolation,\n} from './utils'\nimport {\n collectMockExportNamesBySource,\n collectNamedExports,\n rewriteDeniedImports,\n} from './rewriteDeniedImports'\nimport {\n MOCK_BUILD_PREFIX,\n generateDevSelfDenialModule,\n generateSelfContainedMockModule,\n getResolvedVirtualModuleMatchers,\n loadResolvedVirtualModule,\n makeMockEdgeModuleId,\n mockRuntimeModuleIdFromViolation,\n resolveInternalVirtualModuleId,\n resolvedMarkerVirtualModuleId,\n} from './virtualModules'\nimport { ExtensionlessAbsoluteIdResolver } from './extensionlessAbsoluteIdResolver'\nimport {\n IMPORT_PROTECTION_DEBUG,\n SERVER_FN_LOOKUP_QUERY,\n VITE_BROWSER_VIRTUAL_PREFIX,\n} from './constants'\nimport {\n ImportLocCache,\n addTraceImportLocations,\n buildCodeSnippet,\n buildLineIndex,\n findImportStatementLocationFromTransformed,\n findPostCompileUsageLocation,\n pickOriginalCodeFromSourcesContent,\n} from './sourceLocation'\nimport type { PluginOption, ViteDevServer } from 'vite'\nimport type { CompiledMatcher } from './matchers'\nimport type { Loc, TraceStep, ViolationInfo } from './trace'\nimport type {\n SourceMapLike,\n TransformResult,\n TransformResultProvider,\n} from './sourceLocation'\nimport type { ImportProtectionOptions } from '../schema'\nimport type {\n EnvRules,\n EnvState,\n HandleViolationResult,\n ImportProtectionPluginOptions,\n ModuleGraphNode,\n PendingViolation,\n PluginConfig,\n SharedState,\n ViolationReporter,\n} from './types'\n\nexport type { ImportProtectionPluginOptions } from './types'\n\nexport function importProtectionPlugin(\n opts: ImportProtectionPluginOptions,\n): PluginOption {\n let devServer: ViteDevServer | null = null\n const extensionlessIdResolver = new ExtensionlessAbsoluteIdResolver()\n const resolveExtensionlessAbsoluteId = (id: string) =>\n extensionlessIdResolver.resolve(id)\n\n const importPatternCache = new Map<string, Array<RegExp>>()\n\n function findFirstImportSpecifierIndex(code: string, source: string): number {\n let patterns = importPatternCache.get(source)\n if (!patterns) {\n const escaped = escapeRegExp(source)\n patterns = [\n new RegExp(`\\\\bimport\\\\s+(['\"])${escaped}\\\\1`),\n new RegExp(`\\\\bfrom\\\\s+(['\"])${escaped}\\\\1`),\n new RegExp(`\\\\bimport\\\\s*\\\\(\\\\s*(['\"])${escaped}\\\\1\\\\s*\\\\)`),\n ]\n importPatternCache.set(source, patterns)\n }\n\n let best = -1\n for (const re of patterns) {\n const m = re.exec(code)\n if (!m) continue\n const idx = m.index + m[0].indexOf(source)\n if (idx === -1) continue\n if (best === -1 || idx < best) best = idx\n }\n return best\n }\n\n /**\n * Build an import trace using Vite's per-environment module graph, which\n * is authoritative even on warm starts when the plugin's own ImportGraph\n * may be incomplete (Vite skips resolveId for cached modules).\n */\n function buildTraceFromModuleGraph(\n envName: string,\n env: EnvState,\n targetFile: string,\n ): Array<TraceStep> | null {\n if (!devServer) return null\n const environment = devServer.environments[envName]\n if (!environment) return null\n\n const file = normalizeFilePath(targetFile)\n const start = environment.moduleGraph.getModuleById(file)\n if (!start) return null\n\n // Resolve a module graph node to its normalized file path once and\n // cache the result so BFS + reconstruction don't recompute.\n const nodeIds = new Map<ModuleGraphNode, string>()\n function nodeId(n: ModuleGraphNode): string {\n let cached = nodeIds.get(n)\n if (cached === undefined) {\n cached = n.id\n ? normalizeFilePath(n.id)\n : n.url\n ? normalizeFilePath(n.url)\n : ''\n nodeIds.set(n, cached)\n }\n return cached\n }\n\n const queue: Array<ModuleGraphNode> = [start]\n const visited = new Set<ModuleGraphNode>([start])\n const parent = new Map<ModuleGraphNode, ModuleGraphNode>()\n\n let entryRoot: ModuleGraphNode | null = null\n let fallbackRoot: ModuleGraphNode | null = null\n let qi = 0\n while (qi < queue.length) {\n const node = queue[qi++]!\n const id = nodeId(node)\n\n if (id && env.graph.entries.has(id)) {\n entryRoot = node\n break\n }\n\n const importers = node.importers\n if (importers.size === 0) {\n if (!fallbackRoot) fallbackRoot = node\n continue\n }\n\n for (const imp of importers) {\n if (visited.has(imp)) continue\n visited.add(imp)\n parent.set(imp, node)\n queue.push(imp)\n }\n }\n\n const root = entryRoot ?? fallbackRoot\n\n if (!root) return null\n\n // Reconstruct: root -> ... -> start\n const chain: Array<ModuleGraphNode> = []\n let cur: ModuleGraphNode | undefined = root\n for (let i = 0; i < config.maxTraceDepth + 2 && cur; i++) {\n chain.push(cur)\n if (cur === start) break\n cur = parent.get(cur)\n }\n\n const steps: Array<TraceStep> = []\n for (let i = 0; i < chain.length; i++) {\n const id = nodeId(chain[i]!)\n if (!id) continue\n let specifier: string | undefined\n if (i + 1 < chain.length) {\n const nextId = nodeId(chain[i + 1]!)\n if (nextId) {\n specifier = env.graph.reverseEdges.get(nextId)?.get(id)\n }\n }\n steps.push(specifier ? { file: id, specifier } : { file: id })\n }\n\n return steps.length ? steps : null\n }\n\n const config: PluginConfig = {\n enabled: true,\n root: '',\n command: 'build',\n srcDirectory: '',\n framework: opts.framework,\n effectiveBehavior: 'error',\n mockAccess: 'error',\n logMode: 'once',\n maxTraceDepth: 20,\n compiledRules: {\n client: { specifiers: [], files: [], excludeFiles: [] },\n server: { specifiers: [], files: [], excludeFiles: [] },\n },\n includeMatchers: [],\n excludeMatchers: [],\n ignoreImporterMatchers: [],\n markerSpecifiers: { serverOnly: new Set(), clientOnly: new Set() },\n envTypeMap: new Map(opts.environments.map((e) => [e.name, e.type])),\n onViolation: undefined,\n }\n\n const envStates = new Map<string, EnvState>()\n const shared: SharedState = { fileMarkerKind: new Map() }\n\n /**\n * Build the best available trace for a module and enrich each step with\n * line/column locations. Tries the plugin's own ImportGraph first, then\n * Vite's moduleGraph (authoritative on warm start), keeping whichever is\n * longer. Annotates the last step with the denied specifier + location.\n *\n * Shared by {@link buildViolationInfo} and {@link processPendingViolations}.\n */\n async function rebuildAndAnnotateTrace(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n normalizedImporter: string,\n specifier: string,\n importerLoc: Loc | undefined,\n traceOverride?: Array<TraceStep>,\n ): Promise<Array<TraceStep>> {\n let trace =\n traceOverride ??\n buildTrace(env.graph, normalizedImporter, config.maxTraceDepth)\n\n if (config.command === 'serve') {\n const mgTrace = buildTraceFromModuleGraph(\n envName,\n env,\n normalizedImporter,\n )\n if (mgTrace && mgTrace.length > trace.length) {\n trace = mgTrace\n }\n }\n await addTraceImportLocations(\n provider,\n trace,\n env.importLocCache,\n findFirstImportSpecifierIndex,\n )\n\n if (trace.length > 0) {\n const last = trace[trace.length - 1]!\n if (!last.specifier) last.specifier = specifier\n if (importerLoc && last.line == null) {\n last.line = importerLoc.line\n last.column = importerLoc.column\n }\n }\n\n return trace\n }\n\n /**\n * Build a complete {@link ViolationInfo} with trace, location, and snippet.\n *\n * This is the single path that all violation types go through: specifier,\n * file, and marker.\n */\n async function buildViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n overrides: Omit<\n ViolationInfo,\n | 'env'\n | 'envType'\n | 'behavior'\n | 'specifier'\n | 'importer'\n | 'trace'\n | 'snippet'\n | 'importerLoc'\n >,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const sourceCandidates = buildSourceCandidates(\n source,\n 'resolved' in overrides && typeof overrides.resolved === 'string'\n ? overrides.resolved\n : undefined,\n config.root,\n )\n\n const loc = await resolveImporterLocation(\n provider,\n env,\n importer,\n sourceCandidates,\n )\n\n const trace = await rebuildAndAnnotateTrace(\n provider,\n env,\n envName,\n normalizedImporter,\n source,\n loc,\n traceOverride,\n )\n\n const snippet = loc ? buildCodeSnippet(provider, importer, loc) : undefined\n\n return {\n env: envName,\n envType,\n behavior: config.effectiveBehavior,\n specifier: source,\n importer: normalizedImporter,\n ...(loc ? { importerLoc: loc } : {}),\n trace,\n snippet,\n ...overrides,\n }\n }\n\n async function resolveImporterLocation(\n provider: TransformResultProvider,\n env: EnvState,\n importer: string,\n sourceCandidates: Iterable<string>,\n ): Promise<Loc | undefined> {\n for (const candidate of sourceCandidates) {\n const loc =\n (await findPostCompileUsageLocation(provider, importer, candidate)) ||\n (await findImportStatementLocationFromTransformed(\n provider,\n importer,\n candidate,\n env.importLocCache,\n findFirstImportSpecifierIndex,\n ))\n if (loc) return loc\n }\n return undefined\n }\n\n /**\n * Check if a resolved import violates marker restrictions (e.g. importing\n * a server-only module in the client env). If so, build and return the\n * {@link ViolationInfo} — the caller is responsible for reporting/deferring.\n *\n * Returns `undefined` when the resolved import has no marker conflict.\n */\n async function buildMarkerViolationFromResolvedImport(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n source: string,\n resolvedId: string,\n relativePath: string,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo | undefined> {\n const normalizedResolvedId = normalizeFilePath(resolvedId)\n const markerKind = shared.fileMarkerKind.get(normalizedResolvedId)\n const violates =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n if (!violates) return undefined\n\n const normalizedImporter = normalizeFilePath(importer)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n resolved: normalizedResolvedId,\n message: buildMarkerViolationMessage(relativePath, markerKind),\n },\n traceOverride,\n )\n }\n\n function buildMarkerViolationMessage(\n relativePath: string,\n markerKind: 'server' | 'client' | undefined,\n ): string {\n return markerKind === 'server'\n ? `Module \"${relativePath}\" is marked server-only but is imported in the client environment`\n : `Module \"${relativePath}\" is marked client-only but is imported in the server environment`\n }\n\n async function buildFileViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n resolvedPath: string,\n pattern: string | RegExp,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const relativePath = getRelativePath(resolvedPath)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'file',\n pattern,\n resolved: resolvedPath,\n message: `Import \"${source}\" (resolved to \"${relativePath}\") is denied in the ${envType} environment`,\n },\n traceOverride,\n )\n }\n\n function getEnvType(envName: string): 'client' | 'server' {\n return config.envTypeMap.get(envName) ?? 'server'\n }\n\n function getRulesForEnvironment(envName: string): EnvRules {\n const type = getEnvType(envName)\n return type === 'client'\n ? config.compiledRules.client\n : config.compiledRules.server\n }\n\n /**\n * Check if a relative path matches any denied file pattern for the given\n * environment, respecting `excludeFiles`. Returns the matching pattern\n * or `undefined` if the file is not denied.\n */\n function checkFileDenial(\n relativePath: string,\n matchers: {\n files: Array<CompiledMatcher>\n excludeFiles: Array<CompiledMatcher>\n },\n ): CompiledMatcher | undefined {\n if (\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n ) {\n return undefined\n }\n return matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n }\n\n const environmentNames = new Set<string>([\n VITE_ENVIRONMENT_NAMES.client,\n VITE_ENVIRONMENT_NAMES.server,\n ])\n if (opts.providerEnvName !== VITE_ENVIRONMENT_NAMES.server) {\n environmentNames.add(opts.providerEnvName)\n }\n\n /** Get (or lazily create) the per-env state for the given environment name. */\n function getEnv(envName: string): EnvState {\n let envState = envStates.get(envName)\n if (!envState) {\n const transformResultCache = new Map<string, TransformResult>()\n envState = {\n graph: new ImportGraph(),\n mockExportsByImporter: new Map(),\n resolveCache: new Map(),\n resolveCacheByFile: new Map(),\n importLocCache: new ImportLocCache(),\n seenViolations: new Set(),\n transformResultCache,\n transformResultKeysByFile: new Map(),\n transformResultProvider: {\n getTransformResult(id: string) {\n const fullKey = normalizePath(id)\n const exact = transformResultCache.get(fullKey)\n if (exact) return exact\n const strippedKey = normalizeFilePath(id)\n return strippedKey !== fullKey\n ? transformResultCache.get(strippedKey)\n : undefined\n },\n },\n postTransformImports: new Map(),\n serverFnLookupModules: new Set(),\n pendingViolations: new Map(),\n deferredBuildViolations: [],\n }\n envStates.set(envName, envState)\n }\n return envState\n }\n\n /**\n * Search a parsed export-names map for an entry matching any of the\n * specifier candidates. Returns matching names or empty array.\n */\n function findExportsInMap(\n exportMap: Map<string, Array<string>>,\n candidates: Array<string>,\n ): Array<string> {\n for (const candidate of candidates) {\n const hit = exportMap.get(candidate)\n if (hit && hit.length > 0) return hit\n }\n return []\n }\n\n /**\n * Build deduped resolution candidates for a module ID, including the\n * extensionless absolute path when the ID looks like a file path.\n */\n function buildIdCandidates(id: string, extra?: string): Array<string> {\n const set = new Set(buildResolutionCandidates(id))\n if (extra) {\n for (const c of buildResolutionCandidates(extra)) set.add(c)\n set.add(resolveExtensionlessAbsoluteId(extra))\n }\n return Array.from(set)\n }\n\n /**\n * Resolve which named exports the importer needs from a denied specifier,\n * so mock-edge modules can provide explicit ESM named exports.\n *\n * Tries multiple strategies: cached export maps, AST parsing, and\n * resolver-based comparison.\n */\n async function resolveExportsForDeniedSpecifier(\n env: EnvState,\n ctx: ViolationReporter,\n info: ViolationInfo,\n importerIdHint?: string,\n ): Promise<Array<string>> {\n const importerFile = normalizeFilePath(info.importer)\n const specifierCandidates = buildIdCandidates(info.specifier, info.resolved)\n\n // Only parse AST when a violation occurs (this function is only called\n // while handling a violation). Cache per-importer to avoid repeated parses\n // across multiple violations.\n let parsedBySource = env.mockExportsByImporter.get(importerFile)\n if (!parsedBySource) {\n // Try transform-cache result first, then moduleInfo fallback.\n const importerCode =\n env.transformResultProvider.getTransformResult(importerFile)?.code ??\n (importerIdHint && ctx.getModuleInfo\n ? (ctx.getModuleInfo(importerIdHint)?.code ?? undefined)\n : undefined)\n if (typeof importerCode !== 'string' || importerCode.length === 0)\n return []\n\n try {\n parsedBySource = collectMockExportNamesBySource(importerCode)\n\n // Also index by resolved physical IDs so later lookups match.\n await recordMockExportsForImporter(\n env,\n importerFile,\n parsedBySource,\n async (src) => {\n const cacheKey = `${importerFile}:${src}`\n if (env.resolveCache.has(cacheKey)) {\n return env.resolveCache.get(cacheKey) ?? undefined\n }\n if (!ctx.resolve) return undefined\n const resolved = await ctx.resolve(src, info.importer, {\n skipSelf: true,\n })\n if (!resolved || resolved.external) return undefined\n return resolved.id\n },\n )\n\n // Keep the parsed-by-source map for direct lookups.\n parsedBySource =\n env.mockExportsByImporter.get(importerFile) ?? parsedBySource\n } catch {\n return []\n }\n }\n\n // 1. Direct candidate match\n const direct = findExportsInMap(parsedBySource, specifierCandidates)\n if (direct.length > 0) return direct\n\n // 2. Resolve each source key and compare candidates.\n const candidateSet = new Set(specifierCandidates)\n for (const [sourceKey, names] of parsedBySource) {\n if (!names.length) continue\n\n const resolvedId = await resolveSourceKey(\n env,\n ctx,\n importerFile,\n sourceKey,\n info.importer,\n )\n if (!resolvedId) continue\n\n const resolvedCandidates = buildIdCandidates(resolvedId)\n resolvedCandidates.push(resolveExtensionlessAbsoluteId(resolvedId))\n if (resolvedCandidates.some((v) => candidateSet.has(v))) {\n return names\n }\n }\n\n return []\n }\n\n /** Best-effort resolve a source key using the cache or ctx.resolve. */\n async function resolveSourceKey(\n env: EnvState,\n ctx: ViolationReporter,\n importerFile: string,\n sourceKey: string,\n importerId: string,\n ): Promise<string | undefined> {\n const cacheKey = `${importerFile}:${sourceKey}`\n if (env.resolveCache.has(cacheKey)) {\n return env.resolveCache.get(cacheKey) ?? undefined\n }\n if (!ctx.resolve) return undefined\n try {\n const resolved = await ctx.resolve(sourceKey, importerId, {\n skipSelf: true,\n })\n if (!resolved || resolved.external) return undefined\n return resolved.id\n } catch {\n return undefined\n }\n }\n\n async function recordMockExportsForImporter(\n env: EnvState,\n importerId: string,\n namesBySource: Map<string, Array<string>>,\n resolveSource: (source: string) => Promise<string | undefined>,\n ): Promise<void> {\n const importerFile = normalizeFilePath(importerId)\n\n if (namesBySource.size === 0) return\n\n for (const [source, names] of namesBySource) {\n try {\n const resolvedId = await resolveSource(source)\n if (!resolvedId) continue\n\n namesBySource.set(normalizeFilePath(resolvedId), names)\n namesBySource.set(resolveExtensionlessAbsoluteId(resolvedId), names)\n } catch {\n // Best-effort only\n }\n }\n\n const existing = env.mockExportsByImporter.get(importerFile)\n if (!existing) {\n env.mockExportsByImporter.set(importerFile, namesBySource)\n return\n }\n\n for (const [source, names] of namesBySource) {\n const prev = existing.get(source)\n if (!prev) {\n existing.set(source, names)\n continue\n }\n\n const union = new Set([...prev, ...names])\n existing.set(source, Array.from(union).sort())\n }\n }\n\n const shouldCheckImporterCache = new Map<string, boolean>()\n function shouldCheckImporter(importer: string): boolean {\n let result = shouldCheckImporterCache.get(importer)\n if (result !== undefined) return result\n\n const relativePath = relativizePath(importer, config.root)\n\n // Excluded or ignored importers are never checked.\n const excluded =\n (config.excludeMatchers.length > 0 &&\n matchesAny(relativePath, config.excludeMatchers)) ||\n (config.ignoreImporterMatchers.length > 0 &&\n matchesAny(relativePath, config.ignoreImporterMatchers))\n\n if (excluded) {\n result = false\n } else if (config.includeMatchers.length > 0) {\n result = !!matchesAny(relativePath, config.includeMatchers)\n } else if (config.srcDirectory) {\n result = isInsideDirectory(importer, config.srcDirectory)\n } else {\n result = true\n }\n\n shouldCheckImporterCache.set(importer, result)\n return result\n }\n\n function dedupeKey(info: ViolationInfo): string {\n return `${info.type}:${info.importer}:${info.specifier}:${info.resolved ?? ''}`\n }\n\n function hasSeen(env: EnvState, key: string): boolean {\n if (config.logMode === 'always') return false\n if (env.seenViolations.has(key)) return true\n env.seenViolations.add(key)\n return false\n }\n\n function getRelativePath(absolutePath: string): string {\n return relativizePath(normalizePath(absolutePath), config.root)\n }\n\n /** Reset all caches on an EnvState (called from buildStart). */\n function clearEnvState(envState: EnvState): void {\n envState.resolveCache.clear()\n envState.resolveCacheByFile.clear()\n envState.importLocCache.clear()\n envState.seenViolations.clear()\n envState.transformResultCache.clear()\n envState.transformResultKeysByFile.clear()\n envState.postTransformImports.clear()\n envState.serverFnLookupModules.clear()\n envState.pendingViolations.clear()\n envState.deferredBuildViolations.length = 0\n envState.graph.clear()\n envState.mockExportsByImporter.clear()\n }\n\n /** Invalidate all env-level caches that reference a specific file. */\n function invalidateFileFromEnv(envState: EnvState, file: string): void {\n envState.importLocCache.deleteByFile(file)\n\n // Resolve cache (keyed \"importer:source\")\n const resolveKeys = envState.resolveCacheByFile.get(file)\n if (resolveKeys) {\n for (const key of resolveKeys) envState.resolveCache.delete(key)\n envState.resolveCacheByFile.delete(file)\n }\n\n envState.graph.invalidate(file)\n envState.mockExportsByImporter.delete(file)\n envState.serverFnLookupModules.delete(file)\n envState.pendingViolations.delete(file)\n\n // Transform result cache + post-transform imports\n const transformKeys = envState.transformResultKeysByFile.get(file)\n if (transformKeys) {\n for (const key of transformKeys) {\n envState.transformResultCache.delete(key)\n envState.postTransformImports.delete(key)\n }\n envState.transformResultKeysByFile.delete(file)\n } else {\n envState.transformResultCache.delete(file)\n envState.postTransformImports.delete(file)\n }\n }\n\n /** Store a transform result under both the cacheKey and physical file path. */\n function cacheTransformResult(\n envState: EnvState,\n file: string,\n cacheKey: string,\n result: TransformResult,\n ): void {\n envState.transformResultCache.set(cacheKey, result)\n const keySet = getOrCreate(\n envState.transformResultKeysByFile,\n file,\n () => new Set<string>(),\n )\n keySet.add(cacheKey)\n if (cacheKey !== file) {\n envState.transformResultCache.set(file, result)\n keySet.add(file)\n }\n }\n\n /** Register known Start entrypoints as trace roots for all environments. */\n function registerEntries(): void {\n const { resolvedStartConfig } = opts.getConfig()\n for (const envDef of opts.environments) {\n const envState = getEnv(envDef.name)\n if (resolvedStartConfig.routerFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.routerFilePath),\n )\n }\n if (resolvedStartConfig.startFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.startFilePath),\n )\n }\n }\n }\n\n /**\n * Get the merged set of post-transform imports for a file, checking all\n * code-split variants. Returns `null` if no post-transform data exists\n * yet (transform hasn't run).\n *\n * Skips `SERVER_FN_LOOKUP` variants because they contain untransformed\n * code — the Start compiler excludes them.\n */\n function getPostTransformImports(\n env: EnvState,\n file: string,\n ): Set<string> | null {\n const keySet = env.transformResultKeysByFile.get(file)\n let merged: Set<string> | null = null\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const imports = env.postTransformImports.get(k)\n if (imports) {\n if (!merged) merged = new Set(imports)\n else for (const v of imports) merged.add(v)\n }\n }\n }\n\n // Fallback: direct file-path key\n if (!merged) {\n const imports = env.postTransformImports.get(file)\n if (imports) merged = new Set(imports)\n }\n\n return merged\n }\n\n /**\n * Check whether an import edge from `parent` to `target` survived\n * post-transform compilation.\n *\n * Returns:\n * - `'live'` — target appears in a non-lookup variant's post-transform imports\n * - `'dead'` — post-transform data exists but target is absent (compiler stripped it)\n * - `'pending'` — transform ran but import data not yet posted\n * - `'no-data'` — transform never ran (warm-start cached module)\n */\n function checkEdgeLiveness(\n env: EnvState,\n parent: string,\n target: string,\n ): 'live' | 'dead' | 'pending' | 'no-data' {\n const keySet = env.transformResultKeysByFile.get(parent)\n let anyVariantCached = false\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const imports = env.postTransformImports.get(k)\n if (imports) {\n anyVariantCached = true\n if (imports.has(target)) return 'live'\n }\n }\n }\n\n if (!anyVariantCached) {\n const imports = env.postTransformImports.get(parent)\n if (imports) return imports.has(target) ? 'live' : 'dead'\n const hasTransformResult =\n env.transformResultCache.has(parent) ||\n (keySet ? keySet.size > 0 : false)\n return hasTransformResult ? 'pending' : 'no-data'\n }\n\n return 'dead'\n }\n\n function checkPostTransformReachability(\n env: EnvState,\n file: string,\n ): 'reachable' | 'unreachable' | 'unknown' {\n const visited = new Set<string>()\n const queue: Array<string> = [file]\n let hasUnknownEdge = false\n let qi = 0\n\n while (qi < queue.length) {\n const current = queue[qi++]!\n if (visited.has(current)) continue\n visited.add(current)\n\n if (env.graph.entries.has(current)) {\n return 'reachable'\n }\n\n const importers = env.graph.reverseEdges.get(current)\n if (!importers) continue\n\n for (const [parent] of importers) {\n if (visited.has(parent)) continue\n const liveness = checkEdgeLiveness(env, parent, current)\n if (liveness === 'live' || liveness === 'no-data') {\n // Live edge or warm-start (no transform data) — follow it\n queue.push(parent)\n } else if (liveness === 'pending') {\n hasUnknownEdge = true\n }\n // 'dead' — edge was stripped by compiler, skip\n }\n }\n\n return hasUnknownEdge ? 'unknown' : 'unreachable'\n }\n\n /**\n * Filter pending violations using edge-survival data. Returns the subset\n * of violations whose resolved import survived the Start compiler (or all\n * violations when no post-transform data is available yet).\n *\n * Returns `undefined` when all violations were stripped or when we must wait\n * for post-transform data before proceeding.\n */\n function filterEdgeSurvival(\n env: EnvState,\n file: string,\n violations: Array<PendingViolation>,\n ):\n | { active: Array<PendingViolation>; edgeSurvivalApplied: boolean }\n | 'all-stripped'\n | 'await-transform' {\n const postTransform = getPostTransformImports(env, file)\n\n if (postTransform) {\n const surviving = violations.filter(\n (pv) => !pv.info.resolved || postTransform.has(pv.info.resolved),\n )\n if (surviving.length === 0) return 'all-stripped'\n env.pendingViolations.set(file, surviving)\n return { active: surviving, edgeSurvivalApplied: true }\n }\n\n // Pre-transform violations need edge-survival verification first.\n if (violations.some((pv) => pv.fromPreTransformResolve)) {\n return 'await-transform'\n }\n\n return { active: violations, edgeSurvivalApplied: false }\n }\n\n /**\n * Process pending violations for the given environment. Called from the\n * transform-cache hook after each module transform is cached, because new\n * transform data may allow us to confirm or discard pending violations.\n *\n * @param warnFn - `this.warn` from the transform hook context\n */\n async function processPendingViolations(\n env: EnvState,\n warnFn: (msg: string) => void,\n ): Promise<void> {\n if (env.pendingViolations.size === 0) return\n\n const toDelete: Array<string> = []\n\n for (const [file, violations] of env.pendingViolations) {\n const filtered = filterEdgeSurvival(env, file, violations)\n\n if (filtered === 'all-stripped') {\n toDelete.push(file)\n continue\n }\n if (filtered === 'await-transform') continue\n\n const { active, edgeSurvivalApplied } = filtered\n\n // Wait for entries before running reachability. registerEntries()\n // populates entries at buildStart; resolveId(!importer) may add more.\n const status =\n env.graph.entries.size > 0\n ? checkPostTransformReachability(env, file)\n : 'unknown'\n\n if (status === 'reachable') {\n for (const pv of active) {\n await emitPendingViolation(env, warnFn, pv)\n }\n toDelete.push(file)\n } else if (status === 'unreachable') {\n toDelete.push(file)\n } else if (config.command === 'serve') {\n // 'unknown' reachability — some graph edges lack transform data.\n // When edge-survival was applied, surviving violations are confirmed\n // real. Without it (warm start), emit conservatively.\n let emittedAny = false\n for (const pv of active) {\n if (pv.fromPreTransformResolve) continue\n\n const shouldEmit =\n edgeSurvivalApplied ||\n (pv.info.type === 'file' &&\n !!pv.info.resolved &&\n isInsideDirectory(pv.info.resolved, config.srcDirectory))\n\n if (shouldEmit) {\n emittedAny =\n (await emitPendingViolation(env, warnFn, pv)) || emittedAny\n }\n }\n\n if (emittedAny) {\n toDelete.push(file)\n }\n }\n // 'unknown' — keep pending for next transform-cache invocation.\n }\n\n for (const file of toDelete) {\n env.pendingViolations.delete(file)\n }\n }\n\n async function emitPendingViolation(\n env: EnvState,\n warnFn: (msg: string) => void,\n pv: PendingViolation,\n ): Promise<boolean> {\n if (!pv.info.importerLoc) {\n const sourceCandidates = buildSourceCandidates(\n pv.info.specifier,\n pv.info.resolved,\n config.root,\n )\n const loc = await resolveImporterLocation(\n env.transformResultProvider,\n env,\n pv.info.importer,\n sourceCandidates,\n )\n\n if (loc) {\n pv.info.importerLoc = loc\n pv.info.snippet = buildCodeSnippet(\n env.transformResultProvider,\n pv.info.importer,\n loc,\n )\n }\n }\n\n if (hasSeen(env, dedupeKey(pv.info))) {\n return false\n }\n\n const freshTrace = await rebuildAndAnnotateTrace(\n env.transformResultProvider,\n env,\n pv.info.env,\n pv.info.importer,\n pv.info.specifier,\n pv.info.importerLoc,\n )\n if (freshTrace.length > pv.info.trace.length) {\n pv.info.trace = freshTrace\n }\n\n if (config.onViolation) {\n const result = await config.onViolation(pv.info)\n if (result === false) return false\n }\n\n warnFn(formatViolation(pv.info, config.root))\n return true\n }\n\n /**\n * Record a violation as pending for later confirmation via graph\n * reachability. Called from `resolveId` when `shouldDefer` is true.\n */\n function deferViolation(\n env: EnvState,\n importerFile: string,\n info: ViolationInfo,\n isPreTransformResolve?: boolean,\n ): void {\n getOrCreate(env.pendingViolations, importerFile, () => []).push({\n info,\n fromPreTransformResolve: isPreTransformResolve,\n })\n }\n\n /** Counter for generating unique per-violation mock module IDs in build mode. */\n let buildViolationCounter = 0\n\n async function handleViolation(\n ctx: ViolationReporter,\n env: EnvState,\n info: ViolationInfo,\n importerIdHint?: string,\n violationOpts?: { silent?: boolean },\n ): Promise<HandleViolationResult> {\n if (!violationOpts?.silent) {\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) return undefined\n }\n\n if (config.effectiveBehavior === 'error') {\n // Dev+error: throw immediately.\n // Always throw on error — do NOT deduplicate via hasSeen().\n // Rollup may resolve the same specifier multiple times (e.g.\n // commonjs--resolver's nested this.resolve() fires before\n // getResolveStaticDependencyPromises). If we record the key\n // on the first (nested) throw, the second (real) resolve\n // silently returns undefined and the build succeeds — which\n // is the bug this fixes.\n //\n // Build mode never reaches here — all build violations are\n // deferred via shouldDefer and handled silently.\n return ctx.error(formatViolation(info, config.root))\n }\n\n if (!hasSeen(env, dedupeKey(info))) {\n ctx.warn(formatViolation(info, config.root))\n }\n } else if (\n config.effectiveBehavior === 'error' &&\n config.command !== 'build'\n ) {\n return undefined\n }\n\n // File violations: return resolved path — the self-denial transform\n // will replace the file's content with a mock module. This avoids\n // virtual module IDs that could leak across environments via\n // third-party resolver caches.\n if (info.type === 'file') return info.resolved\n\n // Non-file violations (specifier/marker): create mock-edge module.\n // Dev mode uses a runtime diagnostics ID; build mode uses a unique\n // per-violation ID so generateBundle can check tree-shaking survival.\n const exports = await resolveExportsForDeniedSpecifier(\n env,\n ctx,\n info,\n importerIdHint,\n )\n const baseMockId =\n config.command === 'serve'\n ? mockRuntimeModuleIdFromViolation(info, config.mockAccess, config.root)\n : `${MOCK_BUILD_PREFIX}${buildViolationCounter++}`\n return resolveViteId(makeMockEdgeModuleId(exports, baseMockId))\n }\n\n /**\n * Unified violation dispatch: either defers or reports immediately.\n *\n * When `shouldDefer` is true (dev mock + build modes), calls\n * `handleViolation` silently to obtain the mock module ID, then stores\n * the violation for later verification:\n * - Dev mock mode: all violations are deferred to `pendingViolations`\n * for edge-survival and graph-reachability checking via\n * `processPendingViolations`.\n * - Build mode (mock + error): defers to `deferredBuildViolations` for\n * tree-shaking verification in `generateBundle`.\n *\n * Otherwise reports immediately (dev error mode). Pre-transform\n * resolves are silenced in error mode because they fire before the\n * compiler runs and there is no deferred verification path.\n *\n * Returns the mock module ID / resolve result from `handleViolation`.\n */\n async function reportOrDeferViolation(\n ctx: ViolationReporter,\n env: EnvState,\n importerFile: string,\n importerIdHint: string | undefined,\n info: ViolationInfo,\n shouldDefer: boolean,\n isPreTransformResolve: boolean,\n ): Promise<HandleViolationResult> {\n if (shouldDefer) {\n const result = await handleViolation(ctx, env, info, importerIdHint, {\n silent: true,\n })\n\n if (config.command === 'build') {\n // Build mode: store for generateBundle tree-shaking check.\n // The mock-edge module ID is returned as a plain string.\n const mockId = result ?? ''\n env.deferredBuildViolations.push({\n info,\n mockModuleId: mockId,\n // For marker violations, check importer survival instead of mock.\n checkModuleId: info.type === 'marker' ? info.importer : undefined,\n })\n } else {\n // Dev mock: store for graph-reachability check.\n deferViolation(env, importerFile, info, isPreTransformResolve)\n await processPendingViolations(env, ctx.warn.bind(ctx))\n }\n\n return result\n }\n\n // Non-deferred path: dev error mode only.\n // Pre-transform resolves are silenced because they fire before the\n // compiler runs — imports inside `.server()` callbacks haven't been\n // stripped yet and error mode has no deferred verification.\n return handleViolation(ctx, env, info, importerIdHint, {\n silent: isPreTransformResolve,\n })\n }\n\n return [\n {\n name: 'tanstack-start-core:import-protection',\n enforce: 'pre',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n // Start's environments are named `client` and `ssr` (not `server`), plus\n // an optional serverFn provider environment (eg `rsc`) when configured.\n return environmentNames.has(env.name)\n },\n\n configResolved(viteConfig) {\n config.root = viteConfig.root\n config.command = viteConfig.command\n\n const { startConfig, resolvedStartConfig } = opts.getConfig()\n config.srcDirectory = resolvedStartConfig.srcDirectory\n\n const userOpts: ImportProtectionOptions | undefined =\n startConfig.importProtection\n\n if (userOpts?.enabled === false) {\n config.enabled = false\n return\n }\n\n config.enabled = true\n\n const behavior = userOpts?.behavior\n if (typeof behavior === 'string') {\n config.effectiveBehavior = behavior\n } else {\n config.effectiveBehavior =\n viteConfig.command === 'serve'\n ? (behavior?.dev ?? 'mock')\n : (behavior?.build ?? 'error')\n }\n\n config.logMode = userOpts?.log ?? 'once'\n config.mockAccess = userOpts?.mockAccess ?? 'error'\n config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20\n if (userOpts?.onViolation) {\n const fn = userOpts.onViolation\n config.onViolation = (info) => fn(info)\n }\n\n const defaults = getDefaultImportProtectionRules()\n // Use user-provided patterns when available, otherwise defaults.\n const pick = <T>(user: Array<T> | undefined, fallback: Array<T>) =>\n user ? [...user] : [...fallback]\n\n // Client specifier denies always include framework defaults even\n // when the user provides a custom list.\n const clientSpecifiers = dedupePatterns([\n ...defaults.client.specifiers,\n ...(userOpts?.client?.specifiers ?? []),\n ])\n\n config.compiledRules.client = {\n specifiers: compileMatchers(clientSpecifiers),\n files: compileMatchers(\n pick(userOpts?.client?.files, defaults.client.files),\n ),\n excludeFiles: compileMatchers(\n pick(userOpts?.client?.excludeFiles, defaults.client.excludeFiles),\n ),\n }\n config.compiledRules.server = {\n specifiers: compileMatchers(\n dedupePatterns(\n pick(userOpts?.server?.specifiers, defaults.server.specifiers),\n ),\n ),\n files: compileMatchers(\n pick(userOpts?.server?.files, defaults.server.files),\n ),\n excludeFiles: compileMatchers(\n pick(userOpts?.server?.excludeFiles, defaults.server.excludeFiles),\n ),\n }\n\n config.includeMatchers = compileMatchers(userOpts?.include ?? [])\n config.excludeMatchers = compileMatchers(userOpts?.exclude ?? [])\n config.ignoreImporterMatchers = compileMatchers(\n userOpts?.ignoreImporters ?? [],\n )\n\n // Marker specifiers\n const markers = getMarkerSpecifiers()\n config.markerSpecifiers = {\n serverOnly: new Set(markers.serverOnly),\n clientOnly: new Set(markers.clientOnly),\n }\n },\n\n configureServer(server) {\n devServer = server\n },\n\n buildStart() {\n if (!config.enabled) return\n // Clear memoization caches that grow unboundedly across builds\n clearNormalizeFilePathCache()\n extensionlessIdResolver.clear()\n importPatternCache.clear()\n shouldCheckImporterCache.clear()\n\n // Clear per-env caches\n for (const envState of envStates.values()) {\n clearEnvState(envState)\n }\n\n // Clear shared state\n shared.fileMarkerKind.clear()\n\n registerEntries()\n },\n\n hotUpdate(ctx) {\n if (!config.enabled) return\n // Invalidate caches for updated files\n for (const mod of ctx.modules) {\n if (mod.id) {\n const id = mod.id\n const importerFile = normalizeFilePath(id)\n\n // Invalidate extensionless-resolution cache entries affected by this file.\n extensionlessIdResolver.invalidateByFile(importerFile)\n shared.fileMarkerKind.delete(importerFile)\n\n // Invalidate per-env caches\n for (const envState of envStates.values()) {\n invalidateFileFromEnv(envState, importerFile)\n }\n }\n }\n },\n\n async resolveId(source, importer, _options) {\n const envName = this.environment.name\n const env = getEnv(envName)\n const envType = getEnvType(envName)\n const provider = env.transformResultProvider\n const isScanResolve = !!(_options as Record<string, unknown>).scan\n\n if (IMPORT_PROTECTION_DEBUG) {\n const importerPath = importer\n ? normalizeFilePath(importer)\n : '(entry)'\n const isEntryResolve = !importer\n const filtered =\n process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER === 'entry'\n ? isEntryResolve\n : matchesDebugFilter(source, importerPath)\n if (filtered) {\n debugLog('resolveId', {\n env: envName,\n envType,\n source,\n importer: importerPath,\n isEntryResolve,\n command: config.command,\n })\n }\n }\n\n // Internal virtual modules (mock:build:N, mock-edge, mock-runtime, marker)\n const internalVirtualId = resolveInternalVirtualModuleId(source)\n if (internalVirtualId) return internalVirtualId\n\n if (!importer) {\n env.graph.addEntry(source)\n // Flush pending violations now that an additional entry is known\n // and reachability analysis may have new roots.\n await processPendingViolations(env, this.warn.bind(this))\n return undefined\n }\n\n if (source.startsWith('\\0') || source.startsWith('virtual:')) {\n return undefined\n }\n\n const normalizedImporter = normalizeFilePath(importer)\n const isDirectLookup = importer.includes(SERVER_FN_LOOKUP_QUERY)\n\n if (isDirectLookup) {\n env.serverFnLookupModules.add(normalizedImporter)\n }\n\n const isPreTransformResolve =\n isDirectLookup ||\n env.serverFnLookupModules.has(normalizedImporter) ||\n isScanResolve\n\n // Dev mock mode: defer all violations (including pre-transform\n // resolves) until post-transform data is available, then\n // confirm/discard via graph reachability.\n // Build mode (both mock and error): defer violations until\n // generateBundle so tree-shaking can eliminate false positives.\n const isDevMock =\n config.command === 'serve' && config.effectiveBehavior === 'mock'\n const isBuild = config.command === 'build'\n const shouldDefer = shouldDeferViolation({ isBuild, isDevMock })\n\n const resolveAgainstImporter = async (): Promise<string | null> => {\n const primary = await this.resolve(source, importer, {\n skipSelf: true,\n })\n if (primary) {\n return canonicalizeResolvedId(\n primary.id,\n config.root,\n resolveExtensionlessAbsoluteId,\n )\n }\n\n return null\n }\n\n // Check if this is a marker import\n const markerKind = config.markerSpecifiers.serverOnly.has(source)\n ? ('server' as const)\n : config.markerSpecifiers.clientOnly.has(source)\n ? ('client' as const)\n : undefined\n\n if (markerKind) {\n const existing = shared.fileMarkerKind.get(normalizedImporter)\n if (existing && existing !== markerKind) {\n this.error(\n `[import-protection] File \"${getRelativePath(normalizedImporter)}\" has both server-only and client-only markers. This is not allowed.`,\n )\n }\n shared.fileMarkerKind.set(normalizedImporter, markerKind)\n\n const violatesEnv =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n\n if (violatesEnv) {\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n message: buildMarkerViolationMessage(\n getRelativePath(normalizedImporter),\n markerKind,\n ),\n },\n )\n const markerResult = await reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n\n // In build mode, if the violation was deferred, return the unique\n // build mock ID instead of the marker module. This lets\n // generateBundle check whether the importer (and thus its marker\n // import) survived tree-shaking. The mock is side-effect-free just\n // like the marker module, and the bare import has no bindings, so\n // replacing it is transparent.\n if (isBuild && markerResult != null) {\n return markerResult\n }\n }\n\n // Retroactive marker violation detection: on cold starts, module\n // A may import module B before B's marker is set (because B hasn't\n // been processed yet). When B's marker is set (here),\n // retroactively check all known importers of B in the graph and\n // create deferred marker violations for them. Without this,\n // cold-start ordering can miss marker violations that warm starts\n // detect (warm starts see markers early from cached transforms).\n //\n // Uses lightweight `deferViolation` to avoid heavy side effects\n // (mock module creation, export resolution). Immediately calls\n // `processPendingViolations` to flush the deferred violations,\n // because the marker resolveId fires during Vite's import\n // analysis (after our transform hook) — there may be no\n // subsequent transform invocation to flush them.\n //\n // Guarded by `violatesEnv` (per-environment) plus a per-env\n // seen-set. The marker is shared across environments but each\n // env's graph has its own edges; this ensures the check runs\n // at most once per (env, module) pair.\n const envRetroKey = `retro-marker:${normalizedImporter}`\n if (violatesEnv && !env.seenViolations.has(envRetroKey)) {\n env.seenViolations.add(envRetroKey)\n let retroDeferred = false\n const importersMap = env.graph.reverseEdges.get(normalizedImporter)\n if (importersMap && importersMap.size > 0) {\n for (const [importerFile, specifier] of importersMap) {\n if (!specifier) continue\n if (!shouldCheckImporter(importerFile)) continue\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importerFile,\n specifier,\n normalizedImporter,\n getRelativePath(normalizedImporter),\n )\n if (markerInfo) {\n deferViolation(\n env,\n importerFile,\n markerInfo,\n isPreTransformResolve,\n )\n retroDeferred = true\n }\n }\n }\n if (retroDeferred) {\n await processPendingViolations(env, this.warn.bind(this))\n }\n }\n\n return markerKind === 'server'\n ? resolvedMarkerVirtualModuleId('server')\n : resolvedMarkerVirtualModuleId('client')\n }\n\n // Check if the importer is within our scope\n if (!shouldCheckImporter(normalizedImporter)) {\n return undefined\n }\n\n const matchers = getRulesForEnvironment(envName)\n\n // 1. Specifier-based denial\n const specifierMatch = matchesAny(source, matchers.specifiers)\n if (specifierMatch) {\n if (!isPreTransformResolve) {\n env.graph.addEdge(source, normalizedImporter, source)\n }\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'specifier',\n pattern: specifierMatch.pattern,\n message: `Import \"${source}\" is denied in the ${envType} environment`,\n },\n )\n\n // Resolve the specifier so edge-survival can verify whether\n // the import survives the Start compiler transform (e.g.\n // factory-safe pattern strips imports inside .server() callbacks).\n if (shouldDefer && !info.resolved) {\n try {\n const resolvedForInfo = await resolveAgainstImporter()\n if (resolvedForInfo) info.resolved = resolvedForInfo\n } catch {\n // Non-fatal: edge-survival will skip unresolved specifiers\n }\n }\n\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n // 2. Resolve the import (cached)\n const cacheKey = `${normalizedImporter}:${source}`\n let resolved: string | null\n\n if (env.resolveCache.has(cacheKey)) {\n resolved = env.resolveCache.get(cacheKey) ?? null\n } else {\n resolved = await resolveAgainstImporter()\n\n // Only cache successful resolves. Null resolves can be\n // order-dependent across importer variants (e.g. code-split\n // `?tsr-split=...` ids) and may poison later lookups.\n if (resolved !== null) {\n env.resolveCache.set(cacheKey, resolved)\n getOrCreate(\n env.resolveCacheByFile,\n normalizedImporter,\n () => new Set(),\n ).add(cacheKey)\n }\n }\n\n if (resolved) {\n const relativePath = getRelativePath(resolved)\n\n // Propagate pre-transform status transitively\n if (isPreTransformResolve && !isScanResolve) {\n env.serverFnLookupModules.add(resolved)\n }\n\n if (!isPreTransformResolve) {\n env.graph.addEdge(resolved, normalizedImporter, source)\n }\n\n // Skip file-based and marker-based denial for resolved paths that\n // match the per-environment `excludeFiles` patterns. By default\n // this includes `**/node_modules/**` so that third-party packages\n // using `.client.` / `.server.` in their filenames (e.g. react-tweet\n // exports `index.client.js`) are not treated as user-authored\n // environment boundaries. Users can override `excludeFiles` per\n // environment to narrow or widen this exclusion.\n const isExcludedFile =\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n\n if (!isExcludedFile) {\n const fileMatch =\n matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n\n if (fileMatch) {\n const info = await buildFileViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n resolved,\n fileMatch.pattern,\n )\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importer,\n source,\n resolved,\n relativePath,\n )\n if (markerInfo) {\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n markerInfo,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n }\n }\n\n return undefined\n },\n\n load: {\n filter: {\n id: new RegExp(\n getResolvedVirtualModuleMatchers().map(escapeRegExp).join('|'),\n ),\n },\n handler(id) {\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(id)) {\n debugLog('load:handler', {\n env: this.environment.name,\n id: normalizePath(id),\n })\n }\n }\n\n return loadResolvedVirtualModule(id)\n },\n },\n\n async generateBundle(_options, bundle) {\n const envName = this.environment.name\n const env = envStates.get(envName)\n if (!env || env.deferredBuildViolations.length === 0) return\n\n const candidateCache = new Map<string, Array<string>>()\n const toModuleIdCandidates = (id: string): Array<string> => {\n let cached = candidateCache.get(id)\n if (cached) return cached\n\n const out = new Set<string>()\n const normalized = normalizeFilePath(id)\n out.add(id)\n out.add(normalized)\n out.add(relativizePath(normalized, config.root))\n\n if (normalized.startsWith(VITE_BROWSER_VIRTUAL_PREFIX)) {\n const internal = `\\0${normalized.slice(VITE_BROWSER_VIRTUAL_PREFIX.length)}`\n out.add(internal)\n out.add(relativizePath(normalizeFilePath(internal), config.root))\n }\n\n if (normalized.startsWith('\\0')) {\n const browser = `${VITE_BROWSER_VIRTUAL_PREFIX}${normalized.slice(1)}`\n out.add(browser)\n out.add(relativizePath(normalizeFilePath(browser), config.root))\n }\n\n cached = Array.from(out)\n candidateCache.set(id, cached)\n return cached\n }\n\n // Collect all module IDs that survived tree-shaking in this bundle.\n const survivingModules = new Set<string>()\n for (const chunk of Object.values(bundle)) {\n if (chunk.type === 'chunk') {\n for (const moduleId of Object.keys(chunk.modules)) {\n for (const candidate of toModuleIdCandidates(moduleId)) {\n survivingModules.add(candidate)\n }\n }\n }\n }\n\n const didModuleSurvive = (moduleId: string): boolean =>\n toModuleIdCandidates(moduleId).some((candidate) =>\n survivingModules.has(candidate),\n )\n\n // Check each deferred violation: if its check module survived\n // in the bundle, the import was NOT tree-shaken — real leak.\n const realViolations: Array<ViolationInfo> = []\n for (const {\n info,\n mockModuleId,\n checkModuleId,\n } of env.deferredBuildViolations) {\n let survived: boolean\n if (checkModuleId != null) {\n // Marker violation: check if the importer survived\n // (marker is about the file's directive, not a binding).\n // Include transform-result keys (e.g. code-split variants)\n // to cover all bundle representations of the importer.\n const importerVariantIds = new Set<string>([info.importer])\n const importerKeys = env.transformResultKeysByFile.get(\n normalizeFilePath(info.importer),\n )\n if (importerKeys) {\n for (const key of importerKeys) {\n importerVariantIds.add(key)\n }\n }\n survived = false\n for (const importerId of importerVariantIds) {\n if (didModuleSurvive(importerId)) {\n survived = true\n break\n }\n }\n } else {\n // File/specifier violation: check if the mock module survived.\n survived = didModuleSurvive(mockModuleId)\n }\n\n if (!survived) continue\n\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) continue\n }\n\n realViolations.push(info)\n }\n\n if (realViolations.length === 0) return\n\n if (config.effectiveBehavior === 'error') {\n // Error mode: fail the build on the first real violation.\n this.error(formatViolation(realViolations[0]!, config.root))\n } else {\n // Mock mode: warn for each surviving violation.\n const seen = new Set<string>()\n for (const info of realViolations) {\n const key = dedupeKey(info)\n if (!seen.has(key)) {\n seen.add(key)\n this.warn(formatViolation(info, config.root))\n }\n }\n }\n },\n },\n {\n // Captures transformed code + composed sourcemap for location mapping.\n // Runs after all `enforce: 'pre'` hooks (including the Start compiler).\n // Only files under `srcDirectory` are cached.\n name: 'tanstack-start-core:import-protection-transform-cache',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n return environmentNames.has(env.name)\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[cm]?[tj]sx?($|\\?)/],\n },\n },\n async handler(code, id) {\n const envName = this.environment.name\n const file = normalizeFilePath(id)\n const envType = getEnvType(envName)\n const matchers = getRulesForEnvironment(envName)\n const isBuild = config.command === 'build'\n\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(file)) {\n debugLog('transform-cache', {\n env: envName,\n id: normalizePath(id),\n file,\n })\n }\n }\n\n if (!shouldCheckImporter(file)) {\n return undefined\n }\n\n // Self-denial: if this file is denied in the current environment\n // (e.g. a `.server` file transformed in the client environment),\n // replace its entire content with a mock module.\n //\n // This is the core mechanism for preventing cross-environment\n // cache contamination: resolveId never returns virtual module\n // IDs for file-based violations, so there is nothing for\n // third-party resolver caches (e.g. vite-tsconfig-paths) to\n // leak across environments. Each environment's transform\n // independently decides whether the file is denied.\n //\n // In dev mode, this also solves the cold-start problem where\n // the importer's AST is unavailable for export resolution:\n // the denied file's own source code is always available here,\n // so we parse its exports directly.\n const selfFileMatch = checkFileDenial(getRelativePath(file), matchers)\n if (selfFileMatch) {\n // Parse exports once — shared by build and dev paths.\n // Falls back to empty list on non-standard syntax.\n let exportNames: Array<string> = []\n try {\n exportNames = collectNamedExports(code)\n } catch {\n // Parsing may fail on non-standard syntax\n }\n\n if (isBuild) {\n return generateSelfContainedMockModule(exportNames)\n }\n\n // Dev mode: generate a mock that imports mock-runtime for\n // runtime diagnostics (error/warn on property access).\n const runtimeId = mockRuntimeModuleIdFromViolation(\n {\n type: 'file',\n env: envType,\n envType,\n behavior:\n config.effectiveBehavior === 'error' ? 'error' : 'mock',\n importer: file,\n specifier: relativizePath(file, config.root),\n resolved: file,\n pattern: selfFileMatch.pattern,\n message: `File \"${relativizePath(file, config.root)}\" is denied in the ${envType} environment`,\n trace: [],\n },\n config.mockAccess,\n config.root,\n )\n return generateDevSelfDenialModule(exportNames, runtimeId)\n }\n\n // getCombinedSourcemap() returns the composed sourcemap\n let map: SourceMapLike | undefined\n try {\n map = this.getCombinedSourcemap()\n } catch {\n map = undefined\n }\n\n let originalCode: string | undefined\n if (map?.sourcesContent) {\n originalCode = pickOriginalCodeFromSourcesContent(\n map,\n file,\n config.root,\n )\n }\n\n const lineIndex = buildLineIndex(code)\n const cacheKey = normalizePath(id)\n\n const envState = getEnv(envName)\n const isServerFnLookup = id.includes(SERVER_FN_LOOKUP_QUERY)\n\n // Propagate SERVER_FN_LOOKUP status before import-analysis\n if (isServerFnLookup) {\n envState.serverFnLookupModules.add(file)\n }\n\n const result: TransformResult = {\n code,\n map,\n originalCode,\n lineIndex,\n }\n cacheTransformResult(envState, file, cacheKey, result)\n\n // Build mode: only self-denial (above) and transform caching are\n // needed. All violations are detected and deferred in resolveId;\n // self-denial replaces denied file content; generateBundle checks\n // tree-shaking survival. The import resolution loop below is\n // dev-mode only — it resolves imports for graph reachability,\n // catches violations missed on warm starts (where Vite caches\n // resolveId), and rewrites denied imports to mock modules.\n if (isBuild) return undefined\n\n // Dev mode: resolve imports, populate graph, detect violations,\n // and rewrite denied imports.\n const isDevMock = config.effectiveBehavior === 'mock'\n const importSources = extractImportSources(code)\n const resolvedChildren = new Set<string>()\n const deniedSourceReplacements = new Map<string, string>()\n for (const src of importSources) {\n try {\n const resolved = await this.resolve(src, id, { skipSelf: true })\n if (resolved && !resolved.external) {\n const resolvedPath = canonicalizeResolvedId(\n resolved.id,\n config.root,\n resolveExtensionlessAbsoluteId,\n )\n\n resolvedChildren.add(resolvedPath)\n\n // When the resolved ID is a mock-module (from our\n // resolveId returning a mock-edge ID), postTransformImports\n // would only contain the mock ID. Edge-survival needs the\n // real physical path so pending violations can be matched.\n //\n // For relative specifiers we can compute the physical path\n // directly. For bare/alias specifiers, look up the real\n // resolved path from the pending violations that were\n // already stored by resolveId before this transform ran.\n if (resolved.id.includes('tanstack-start-import-protection:')) {\n let physicalPath: string | undefined\n // Look up real resolved path from pending violations\n const pending = envState.pendingViolations.get(file)\n if (pending) {\n const match = pending.find(\n (pv) => pv.info.specifier === src && pv.info.resolved,\n )\n if (match) physicalPath = match.info.resolved\n }\n if (physicalPath && physicalPath !== resolvedPath) {\n resolvedChildren.add(physicalPath)\n envState.graph.addEdge(physicalPath, file, src)\n }\n }\n\n // Populate import graph edges for warm-start trace accuracy\n envState.graph.addEdge(resolvedPath, file, src)\n\n if (isDevMock) {\n const relativePath = getRelativePath(resolvedPath)\n const fileMatch = checkFileDenial(relativePath, matchers)\n\n if (fileMatch) {\n const info = await buildFileViolationInfo(\n envState.transformResultProvider,\n envState,\n envName,\n envType,\n id,\n file,\n src,\n resolvedPath,\n fileMatch.pattern,\n )\n\n const replacement = await reportOrDeferViolation(\n this,\n envState,\n file,\n id,\n info,\n isDevMock,\n isServerFnLookup,\n )\n\n if (replacement) {\n deniedSourceReplacements.set(\n src,\n replacement.startsWith('\\0')\n ? VITE_BROWSER_VIRTUAL_PREFIX + replacement.slice(1)\n : replacement,\n )\n }\n }\n }\n }\n } catch {\n // Non-fatal\n }\n }\n envState.postTransformImports.set(cacheKey, resolvedChildren)\n if (cacheKey !== file && !isServerFnLookup) {\n envState.postTransformImports.set(file, resolvedChildren)\n }\n\n await processPendingViolations(envState, this.warn.bind(this))\n\n if (deniedSourceReplacements.size > 0) {\n try {\n const rewritten = rewriteDeniedImports(\n code,\n id,\n new Set(deniedSourceReplacements.keys()),\n (source: string) =>\n deniedSourceReplacements.get(source) ?? source,\n )\n\n if (!rewritten) {\n return undefined\n }\n\n const normalizedMap = rewritten.map\n ? {\n ...rewritten.map,\n version: Number(rewritten.map.version),\n sourcesContent:\n rewritten.map.sourcesContent?.map(\n (s: string | null) => s ?? '',\n ) ?? [],\n }\n : {\n version: 3,\n file: id,\n names: [],\n sources: [id],\n sourcesContent: [code],\n mappings: '',\n }\n\n return {\n code: rewritten.code,\n map: normalizedMap,\n }\n } catch {\n // Non-fatal: keep original code when rewrite fails.\n }\n }\n\n return undefined\n },\n },\n },\n ] satisfies Array<PluginOption>\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAgFO,SAAS,uBACd,MACc;AACd,MAAI,YAAkC;AACtC,QAAM,0BAA0B,IAAI,gCAAA;AACpC,QAAM,iCAAiC,CAAC,OACtC,wBAAwB,QAAQ,EAAE;AAEpC,QAAM,yCAAyB,IAAA;AAE/B,WAAS,8BAA8B,MAAc,QAAwB;AAC3E,QAAI,WAAW,mBAAmB,IAAI,MAAM;AAC5C,QAAI,CAAC,UAAU;AACb,YAAM,UAAU,aAAa,MAAM;AACnC,iBAAW;AAAA,QACT,IAAI,OAAO,sBAAsB,OAAO,KAAK;AAAA,QAC7C,IAAI,OAAO,oBAAoB,OAAO,KAAK;AAAA,QAC3C,IAAI,OAAO,6BAA6B,OAAO,YAAY;AAAA,MAAA;AAE7D,yBAAmB,IAAI,QAAQ,QAAQ;AAAA,IACzC;AAEA,QAAI,OAAO;AACX,eAAW,MAAM,UAAU;AACzB,YAAM,IAAI,GAAG,KAAK,IAAI;AACtB,UAAI,CAAC,EAAG;AACR,YAAM,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE,QAAQ,MAAM;AACzC,UAAI,QAAQ,GAAI;AAChB,UAAI,SAAS,MAAM,MAAM,KAAM,QAAO;AAAA,IACxC;AACA,WAAO;AAAA,EACT;AAOA,WAAS,0BACP,SACA,KACA,YACyB;AACzB,QAAI,CAAC,UAAW,QAAO;AACvB,UAAM,cAAc,UAAU,aAAa,OAAO;AAClD,QAAI,CAAC,YAAa,QAAO;AAEzB,UAAM,OAAO,kBAAkB,UAAU;AACzC,UAAM,QAAQ,YAAY,YAAY,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W;AACd,uBAAO;AAAA,cACT;AAEA,oBAAM,gBAAgB,UAAU,MAC5B;AAAA,gBACE,GAAG,UAAU;AAAA,gBACb,SAAS,OAAO,UAAU,IAAI,OAAO;AAAA,gBACrC,gBACE,UAAU,IAAI,gBAAgB;AAAA,kBAC5B,CAAC,MAAqB,KAAK;AAAA,gBAAA,KACxB,CAAA;AAAA,cAAC,IAEV;AAAA,gBACE,SAAS;AAAA,gBACT,MAAM;AAAA,gBACN,OAAO,CAAA;AAAA,gBACP,SAAS,CAAC,EAAE;AAAA,gBACZ,gBAAgB,CAAC,IAAI;AAAA,gBACrB,UAAU;AAAA,cAAA;AAGhB,qBAAO;AAAA,gBACL,MAAM,UAAU;AAAA,gBAChB,KAAK;AAAA,cAAA;AAAA,YAET,QAAQ;AAAA,YAER;AAAA,UACF;AAEA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,IACF;AAAA,EACF;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"plugin.js","names":[],"sources":["../../../src/import-protection-plugin/plugin.ts"],"sourcesContent":["import { normalizePath } from 'vite'\n\nimport { resolveViteId } from '../utils'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { ImportGraph, buildTrace, formatViolation } from './trace'\nimport {\n getDefaultImportProtectionRules,\n getMarkerSpecifiers,\n} from './defaults'\nimport { compileMatchers, matchesAny } from './matchers'\nimport {\n buildResolutionCandidates,\n buildSourceCandidates,\n canonicalizeResolvedId,\n clearNormalizeFilePathCache,\n debugLog,\n dedupePatterns,\n escapeRegExp,\n extractImportSources,\n getOrCreate,\n isInsideDirectory,\n matchesDebugFilter,\n normalizeFilePath,\n relativizePath,\n shouldDeferViolation,\n} from './utils'\nimport {\n collectMockExportNamesBySource,\n collectNamedExports,\n rewriteDeniedImports,\n} from './rewriteDeniedImports'\nimport {\n MOCK_BUILD_PREFIX,\n generateDevSelfDenialModule,\n generateSelfContainedMockModule,\n getResolvedVirtualModuleMatchers,\n loadResolvedVirtualModule,\n makeMockEdgeModuleId,\n mockRuntimeModuleIdFromViolation,\n resolveInternalVirtualModuleId,\n resolvedMarkerVirtualModuleId,\n} from './virtualModules'\nimport { ExtensionlessAbsoluteIdResolver } from './extensionlessAbsoluteIdResolver'\nimport {\n IMPORT_PROTECTION_DEBUG,\n SERVER_FN_LOOKUP_QUERY,\n VITE_BROWSER_VIRTUAL_PREFIX,\n} from './constants'\nimport {\n ImportLocCache,\n addTraceImportLocations,\n buildCodeSnippet,\n buildLineIndex,\n findImportStatementLocationFromTransformed,\n findPostCompileUsageLocation,\n pickOriginalCodeFromSourcesContent,\n} from './sourceLocation'\nimport type { PluginOption, ViteDevServer } from 'vite'\nimport type { CompiledMatcher } from './matchers'\nimport type { Loc, TraceStep, ViolationInfo } from './trace'\nimport type {\n SourceMapLike,\n TransformResult,\n TransformResultProvider,\n} from './sourceLocation'\nimport type { ImportProtectionOptions } from '../schema'\nimport type {\n EnvRules,\n EnvState,\n HandleViolationResult,\n ImportProtectionPluginOptions,\n ModuleGraphNode,\n PendingViolation,\n PluginConfig,\n SharedState,\n ViolationReporter,\n} from './types'\n\nexport type { ImportProtectionPluginOptions } from './types'\n\nexport function importProtectionPlugin(\n opts: ImportProtectionPluginOptions,\n): PluginOption {\n let devServer: ViteDevServer | null = null\n const extensionlessIdResolver = new ExtensionlessAbsoluteIdResolver()\n const resolveExtensionlessAbsoluteId = (id: string) =>\n extensionlessIdResolver.resolve(id)\n\n const importPatternCache = new Map<string, Array<RegExp>>()\n\n function findFirstImportSpecifierIndex(code: string, source: string): number {\n let patterns = importPatternCache.get(source)\n if (!patterns) {\n const escaped = escapeRegExp(source)\n patterns = [\n new RegExp(`\\\\bimport\\\\s+(['\"])${escaped}\\\\1`),\n new RegExp(`\\\\bfrom\\\\s+(['\"])${escaped}\\\\1`),\n new RegExp(`\\\\bimport\\\\s*\\\\(\\\\s*(['\"])${escaped}\\\\1\\\\s*\\\\)`),\n ]\n importPatternCache.set(source, patterns)\n }\n\n let best = -1\n for (const re of patterns) {\n const m = re.exec(code)\n if (!m) continue\n const idx = m.index + m[0].indexOf(source)\n if (idx === -1) continue\n if (best === -1 || idx < best) best = idx\n }\n return best\n }\n\n /**\n * Build an import trace using Vite's per-environment module graph, which\n * is authoritative even on warm starts when the plugin's own ImportGraph\n * may be incomplete (Vite skips resolveId for cached modules).\n */\n function buildTraceFromModuleGraph(\n envName: string,\n env: EnvState,\n targetFile: string,\n ): Array<TraceStep> | null {\n if (!devServer) return null\n const environment = devServer.environments[envName]\n if (!environment) return null\n\n const file = normalizeFilePath(targetFile)\n const start = environment.moduleGraph.getModuleById(file)\n if (!start) return null\n\n // Resolve a module graph node to its normalized file path once and\n // cache the result so BFS + reconstruction don't recompute.\n const nodeIds = new Map<ModuleGraphNode, string>()\n function nodeId(n: ModuleGraphNode): string {\n let cached = nodeIds.get(n)\n if (cached === undefined) {\n cached = n.id\n ? normalizeFilePath(n.id)\n : n.url\n ? normalizeFilePath(n.url)\n : ''\n nodeIds.set(n, cached)\n }\n return cached\n }\n\n const queue: Array<ModuleGraphNode> = [start]\n const visited = new Set<ModuleGraphNode>([start])\n const parent = new Map<ModuleGraphNode, ModuleGraphNode>()\n\n let entryRoot: ModuleGraphNode | null = null\n let fallbackRoot: ModuleGraphNode | null = null\n let qi = 0\n while (qi < queue.length) {\n const node = queue[qi++]!\n const id = nodeId(node)\n\n if (id && env.graph.entries.has(id)) {\n entryRoot = node\n break\n }\n\n const importers = node.importers\n if (importers.size === 0) {\n if (!fallbackRoot) fallbackRoot = node\n continue\n }\n\n for (const imp of importers) {\n if (visited.has(imp)) continue\n visited.add(imp)\n parent.set(imp, node)\n queue.push(imp)\n }\n }\n\n const root = entryRoot ?? fallbackRoot\n\n if (!root) return null\n\n // Reconstruct: root -> ... -> start\n const chain: Array<ModuleGraphNode> = []\n let cur: ModuleGraphNode | undefined = root\n for (let i = 0; i < config.maxTraceDepth + 2 && cur; i++) {\n chain.push(cur)\n if (cur === start) break\n cur = parent.get(cur)\n }\n\n const steps: Array<TraceStep> = []\n for (let i = 0; i < chain.length; i++) {\n const id = nodeId(chain[i]!)\n if (!id) continue\n let specifier: string | undefined\n if (i + 1 < chain.length) {\n const nextId = nodeId(chain[i + 1]!)\n if (nextId) {\n specifier = env.graph.reverseEdges.get(nextId)?.get(id)\n }\n }\n steps.push(specifier ? { file: id, specifier } : { file: id })\n }\n\n return steps.length ? steps : null\n }\n\n const config: PluginConfig = {\n enabled: true,\n root: '',\n command: 'build',\n srcDirectory: '',\n framework: opts.framework,\n effectiveBehavior: 'error',\n mockAccess: 'error',\n logMode: 'once',\n maxTraceDepth: 20,\n compiledRules: {\n client: { specifiers: [], files: [], excludeFiles: [] },\n server: { specifiers: [], files: [], excludeFiles: [] },\n },\n includeMatchers: [],\n excludeMatchers: [],\n ignoreImporterMatchers: [],\n markerSpecifiers: { serverOnly: new Set(), clientOnly: new Set() },\n envTypeMap: new Map(opts.environments.map((e) => [e.name, e.type])),\n onViolation: undefined,\n }\n\n const envStates = new Map<string, EnvState>()\n const shared: SharedState = { fileMarkerKind: new Map() }\n\n /**\n * Build the best available trace for a module and enrich each step with\n * line/column locations. Tries the plugin's own ImportGraph first, then\n * Vite's moduleGraph (authoritative on warm start), keeping whichever is\n * longer. Annotates the last step with the denied specifier + location.\n *\n * Shared by {@link buildViolationInfo} and {@link processPendingViolations}.\n */\n async function rebuildAndAnnotateTrace(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n normalizedImporter: string,\n specifier: string,\n importerLoc: Loc | undefined,\n traceOverride?: Array<TraceStep>,\n ): Promise<Array<TraceStep>> {\n let trace =\n traceOverride ??\n buildTrace(env.graph, normalizedImporter, config.maxTraceDepth)\n\n if (config.command === 'serve') {\n const mgTrace = buildTraceFromModuleGraph(\n envName,\n env,\n normalizedImporter,\n )\n if (mgTrace && mgTrace.length > trace.length) {\n trace = mgTrace\n }\n }\n await addTraceImportLocations(\n provider,\n trace,\n env.importLocCache,\n findFirstImportSpecifierIndex,\n )\n\n if (trace.length > 0) {\n const last = trace[trace.length - 1]!\n if (!last.specifier) last.specifier = specifier\n if (importerLoc && last.line == null) {\n last.line = importerLoc.line\n last.column = importerLoc.column\n }\n }\n\n return trace\n }\n\n /**\n * Build a complete {@link ViolationInfo} with trace, location, and snippet.\n *\n * This is the single path that all violation types go through: specifier,\n * file, and marker.\n */\n async function buildViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n overrides: Omit<\n ViolationInfo,\n | 'env'\n | 'envType'\n | 'behavior'\n | 'specifier'\n | 'importer'\n | 'trace'\n | 'snippet'\n | 'importerLoc'\n >,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const sourceCandidates = buildSourceCandidates(\n source,\n 'resolved' in overrides && typeof overrides.resolved === 'string'\n ? overrides.resolved\n : undefined,\n config.root,\n )\n\n const loc = await resolveImporterLocation(\n provider,\n env,\n importer,\n sourceCandidates,\n )\n\n const trace = await rebuildAndAnnotateTrace(\n provider,\n env,\n envName,\n normalizedImporter,\n source,\n loc,\n traceOverride,\n )\n\n const snippet = loc ? buildCodeSnippet(provider, importer, loc) : undefined\n\n return {\n env: envName,\n envType,\n behavior: config.effectiveBehavior,\n specifier: source,\n importer: normalizedImporter,\n ...(loc ? { importerLoc: loc } : {}),\n trace,\n snippet,\n ...overrides,\n }\n }\n\n async function resolveImporterLocation(\n provider: TransformResultProvider,\n env: EnvState,\n importer: string,\n sourceCandidates: Iterable<string>,\n ): Promise<Loc | undefined> {\n for (const candidate of sourceCandidates) {\n const loc =\n (await findPostCompileUsageLocation(provider, importer, candidate)) ||\n (await findImportStatementLocationFromTransformed(\n provider,\n importer,\n candidate,\n env.importLocCache,\n findFirstImportSpecifierIndex,\n ))\n if (loc) return loc\n }\n return undefined\n }\n\n /**\n * Check if a resolved import violates marker restrictions (e.g. importing\n * a server-only module in the client env). If so, build and return the\n * {@link ViolationInfo} — the caller is responsible for reporting/deferring.\n *\n * Returns `undefined` when the resolved import has no marker conflict.\n */\n async function buildMarkerViolationFromResolvedImport(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n source: string,\n resolvedId: string,\n relativePath: string,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo | undefined> {\n const normalizedResolvedId = normalizeFilePath(resolvedId)\n const markerKind = shared.fileMarkerKind.get(normalizedResolvedId)\n const violates =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n if (!violates) return undefined\n\n const normalizedImporter = normalizeFilePath(importer)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n resolved: normalizedResolvedId,\n message: buildMarkerViolationMessage(relativePath, markerKind),\n },\n traceOverride,\n )\n }\n\n function buildMarkerViolationMessage(\n relativePath: string,\n markerKind: 'server' | 'client' | undefined,\n ): string {\n return markerKind === 'server'\n ? `Module \"${relativePath}\" is marked server-only but is imported in the client environment`\n : `Module \"${relativePath}\" is marked client-only but is imported in the server environment`\n }\n\n async function buildFileViolationInfo(\n provider: TransformResultProvider,\n env: EnvState,\n envName: string,\n envType: 'client' | 'server',\n importer: string,\n normalizedImporter: string,\n source: string,\n resolvedPath: string,\n pattern: string | RegExp,\n traceOverride?: Array<TraceStep>,\n ): Promise<ViolationInfo> {\n const relativePath = getRelativePath(resolvedPath)\n\n return buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'file',\n pattern,\n resolved: resolvedPath,\n message: `Import \"${source}\" (resolved to \"${relativePath}\") is denied in the ${envType} environment`,\n },\n traceOverride,\n )\n }\n\n function getEnvType(envName: string): 'client' | 'server' {\n return config.envTypeMap.get(envName) ?? 'server'\n }\n\n function getRulesForEnvironment(envName: string): EnvRules {\n const type = getEnvType(envName)\n return type === 'client'\n ? config.compiledRules.client\n : config.compiledRules.server\n }\n\n /**\n * Check if a relative path matches any denied file pattern for the given\n * environment, respecting `excludeFiles`. Returns the matching pattern\n * or `undefined` if the file is not denied.\n */\n function checkFileDenial(\n relativePath: string,\n matchers: {\n files: Array<CompiledMatcher>\n excludeFiles: Array<CompiledMatcher>\n },\n ): CompiledMatcher | undefined {\n if (\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n ) {\n return undefined\n }\n return matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n }\n\n const environmentNames = new Set<string>([\n VITE_ENVIRONMENT_NAMES.client,\n VITE_ENVIRONMENT_NAMES.server,\n ])\n if (opts.providerEnvName !== VITE_ENVIRONMENT_NAMES.server) {\n environmentNames.add(opts.providerEnvName)\n }\n\n /** Get (or lazily create) the per-env state for the given environment name. */\n function getEnv(envName: string): EnvState {\n let envState = envStates.get(envName)\n if (!envState) {\n const transformResultCache = new Map<string, TransformResult>()\n envState = {\n graph: new ImportGraph(),\n mockExportsByImporter: new Map(),\n resolveCache: new Map(),\n resolveCacheByFile: new Map(),\n importLocCache: new ImportLocCache(),\n seenViolations: new Set(),\n transformResultCache,\n transformResultKeysByFile: new Map(),\n transformResultProvider: {\n getTransformResult(id: string) {\n const fullKey = normalizePath(id)\n const exact = transformResultCache.get(fullKey)\n if (exact) return exact\n const strippedKey = normalizeFilePath(id)\n return strippedKey !== fullKey\n ? transformResultCache.get(strippedKey)\n : undefined\n },\n },\n postTransformImports: new Map(),\n serverFnLookupModules: new Set(),\n pendingViolations: new Map(),\n deferredBuildViolations: [],\n }\n envStates.set(envName, envState)\n }\n return envState\n }\n\n /**\n * Search a parsed export-names map for an entry matching any of the\n * specifier candidates. Returns matching names or empty array.\n */\n function findExportsInMap(\n exportMap: Map<string, Array<string>>,\n candidates: Array<string>,\n ): Array<string> {\n for (const candidate of candidates) {\n const hit = exportMap.get(candidate)\n if (hit && hit.length > 0) return hit\n }\n return []\n }\n\n /**\n * Build deduped resolution candidates for a module ID, including the\n * extensionless absolute path when the ID looks like a file path.\n */\n function buildIdCandidates(id: string, extra?: string): Array<string> {\n const set = new Set(buildResolutionCandidates(id))\n if (extra) {\n for (const c of buildResolutionCandidates(extra)) set.add(c)\n set.add(resolveExtensionlessAbsoluteId(extra))\n }\n return Array.from(set)\n }\n\n /**\n * Resolve which named exports the importer needs from a denied specifier,\n * so mock-edge modules can provide explicit ESM named exports.\n *\n * Tries multiple strategies: cached export maps, AST parsing, and\n * resolver-based comparison.\n */\n async function resolveExportsForDeniedSpecifier(\n env: EnvState,\n ctx: ViolationReporter,\n info: ViolationInfo,\n importerIdHint?: string,\n ): Promise<Array<string>> {\n const importerFile = normalizeFilePath(info.importer)\n const specifierCandidates = buildIdCandidates(info.specifier, info.resolved)\n\n // Only parse AST when a violation occurs (this function is only called\n // while handling a violation). Cache per-importer to avoid repeated parses\n // across multiple violations.\n let parsedBySource = env.mockExportsByImporter.get(importerFile)\n if (!parsedBySource) {\n // Try transform-cache result first, then moduleInfo fallback.\n const importerCode =\n env.transformResultProvider.getTransformResult(importerFile)?.code ??\n (importerIdHint && ctx.getModuleInfo\n ? (ctx.getModuleInfo(importerIdHint)?.code ?? undefined)\n : undefined)\n if (typeof importerCode !== 'string' || importerCode.length === 0)\n return []\n\n try {\n parsedBySource = collectMockExportNamesBySource(importerCode)\n\n // Also index by resolved physical IDs so later lookups match.\n await recordMockExportsForImporter(\n env,\n importerFile,\n parsedBySource,\n async (src) => {\n const cacheKey = `${importerFile}:${src}`\n if (env.resolveCache.has(cacheKey)) {\n return env.resolveCache.get(cacheKey) ?? undefined\n }\n if (!ctx.resolve) return undefined\n const resolved = await ctx.resolve(src, info.importer, {\n skipSelf: true,\n })\n if (!resolved || resolved.external) return undefined\n return resolved.id\n },\n )\n\n // Keep the parsed-by-source map for direct lookups.\n parsedBySource =\n env.mockExportsByImporter.get(importerFile) ?? parsedBySource\n } catch {\n return []\n }\n }\n\n // 1. Direct candidate match\n const direct = findExportsInMap(parsedBySource, specifierCandidates)\n if (direct.length > 0) return direct\n\n // 2. Resolve each source key and compare candidates.\n const candidateSet = new Set(specifierCandidates)\n for (const [sourceKey, names] of parsedBySource) {\n if (!names.length) continue\n\n const resolvedId = await resolveSourceKey(\n env,\n ctx,\n importerFile,\n sourceKey,\n info.importer,\n )\n if (!resolvedId) continue\n\n const resolvedCandidates = buildIdCandidates(resolvedId)\n resolvedCandidates.push(resolveExtensionlessAbsoluteId(resolvedId))\n if (resolvedCandidates.some((v) => candidateSet.has(v))) {\n return names\n }\n }\n\n return []\n }\n\n /** Best-effort resolve a source key using the cache or ctx.resolve. */\n async function resolveSourceKey(\n env: EnvState,\n ctx: ViolationReporter,\n importerFile: string,\n sourceKey: string,\n importerId: string,\n ): Promise<string | undefined> {\n const cacheKey = `${importerFile}:${sourceKey}`\n if (env.resolveCache.has(cacheKey)) {\n return env.resolveCache.get(cacheKey) ?? undefined\n }\n if (!ctx.resolve) return undefined\n try {\n const resolved = await ctx.resolve(sourceKey, importerId, {\n skipSelf: true,\n })\n if (!resolved || resolved.external) return undefined\n return resolved.id\n } catch {\n return undefined\n }\n }\n\n async function recordMockExportsForImporter(\n env: EnvState,\n importerId: string,\n namesBySource: Map<string, Array<string>>,\n resolveSource: (source: string) => Promise<string | undefined>,\n ): Promise<void> {\n const importerFile = normalizeFilePath(importerId)\n\n if (namesBySource.size === 0) return\n\n for (const [source, names] of namesBySource) {\n try {\n const resolvedId = await resolveSource(source)\n if (!resolvedId) continue\n\n namesBySource.set(normalizeFilePath(resolvedId), names)\n namesBySource.set(resolveExtensionlessAbsoluteId(resolvedId), names)\n } catch {\n // Best-effort only\n }\n }\n\n const existing = env.mockExportsByImporter.get(importerFile)\n if (!existing) {\n env.mockExportsByImporter.set(importerFile, namesBySource)\n return\n }\n\n for (const [source, names] of namesBySource) {\n const prev = existing.get(source)\n if (!prev) {\n existing.set(source, names)\n continue\n }\n\n const union = new Set([...prev, ...names])\n existing.set(source, Array.from(union).sort())\n }\n }\n\n const shouldCheckImporterCache = new Map<string, boolean>()\n function shouldCheckImporter(importer: string): boolean {\n let result = shouldCheckImporterCache.get(importer)\n if (result !== undefined) return result\n\n const relativePath = relativizePath(importer, config.root)\n\n // Excluded or ignored importers are never checked.\n const excluded =\n (config.excludeMatchers.length > 0 &&\n matchesAny(relativePath, config.excludeMatchers)) ||\n (config.ignoreImporterMatchers.length > 0 &&\n matchesAny(relativePath, config.ignoreImporterMatchers))\n\n if (excluded) {\n result = false\n } else if (config.includeMatchers.length > 0) {\n result = !!matchesAny(relativePath, config.includeMatchers)\n } else if (config.srcDirectory) {\n result = isInsideDirectory(importer, config.srcDirectory)\n } else {\n result = true\n }\n\n shouldCheckImporterCache.set(importer, result)\n return result\n }\n\n function dedupeKey(info: ViolationInfo): string {\n return `${info.type}:${info.importer}:${info.specifier}:${info.resolved ?? ''}`\n }\n\n function hasSeen(env: EnvState, key: string): boolean {\n if (config.logMode === 'always') return false\n if (env.seenViolations.has(key)) return true\n env.seenViolations.add(key)\n return false\n }\n\n function getRelativePath(absolutePath: string): string {\n return relativizePath(normalizePath(absolutePath), config.root)\n }\n\n /** Reset all caches on an EnvState (called from buildStart). */\n function clearEnvState(envState: EnvState): void {\n envState.resolveCache.clear()\n envState.resolveCacheByFile.clear()\n envState.importLocCache.clear()\n envState.seenViolations.clear()\n envState.transformResultCache.clear()\n envState.transformResultKeysByFile.clear()\n envState.postTransformImports.clear()\n envState.serverFnLookupModules.clear()\n envState.pendingViolations.clear()\n envState.deferredBuildViolations.length = 0\n envState.graph.clear()\n envState.mockExportsByImporter.clear()\n }\n\n /** Invalidate all env-level caches that reference a specific file. */\n function invalidateFileFromEnv(envState: EnvState, file: string): void {\n envState.importLocCache.deleteByFile(file)\n\n // Resolve cache (keyed \"importer:source\")\n const resolveKeys = envState.resolveCacheByFile.get(file)\n if (resolveKeys) {\n for (const key of resolveKeys) envState.resolveCache.delete(key)\n envState.resolveCacheByFile.delete(file)\n }\n\n envState.graph.invalidate(file)\n envState.mockExportsByImporter.delete(file)\n envState.serverFnLookupModules.delete(file)\n envState.pendingViolations.delete(file)\n\n // Transform result cache + post-transform imports\n const transformKeys = envState.transformResultKeysByFile.get(file)\n if (transformKeys) {\n for (const key of transformKeys) {\n envState.transformResultCache.delete(key)\n envState.postTransformImports.delete(key)\n }\n envState.transformResultKeysByFile.delete(file)\n } else {\n envState.transformResultCache.delete(file)\n envState.postTransformImports.delete(file)\n }\n }\n\n /** Store a transform result under both the cacheKey and physical file path. */\n function cacheTransformResult(\n envState: EnvState,\n file: string,\n cacheKey: string,\n result: TransformResult,\n ): void {\n envState.transformResultCache.set(cacheKey, result)\n const keySet = getOrCreate(\n envState.transformResultKeysByFile,\n file,\n () => new Set<string>(),\n )\n keySet.add(cacheKey)\n if (cacheKey !== file) {\n envState.transformResultCache.set(file, result)\n keySet.add(file)\n }\n }\n\n /** Register known Start entrypoints as trace roots for all environments. */\n function registerEntries(): void {\n const { resolvedStartConfig } = opts.getConfig()\n for (const envDef of opts.environments) {\n const envState = getEnv(envDef.name)\n if (resolvedStartConfig.routerFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.routerFilePath),\n )\n }\n if (resolvedStartConfig.startFilePath) {\n envState.graph.addEntry(\n normalizePath(resolvedStartConfig.startFilePath),\n )\n }\n }\n }\n\n /**\n * Get the merged set of post-transform imports for a file, checking all\n * code-split variants. Returns `null` if no post-transform data exists\n * yet (transform hasn't run).\n *\n * Skips `SERVER_FN_LOOKUP` variants because they contain untransformed\n * code — the Start compiler excludes them.\n */\n function getPostTransformImports(\n env: EnvState,\n file: string,\n ): Set<string> | null {\n const keySet = env.transformResultKeysByFile.get(file)\n let merged: Set<string> | null = null\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const imports = env.postTransformImports.get(k)\n if (imports) {\n if (!merged) merged = new Set(imports)\n else for (const v of imports) merged.add(v)\n }\n }\n }\n\n // Fallback: direct file-path key\n if (!merged) {\n const imports = env.postTransformImports.get(file)\n if (imports) merged = new Set(imports)\n }\n\n return merged\n }\n\n /**\n * Check whether an import edge from `parent` to `target` survived\n * post-transform compilation.\n *\n * Returns:\n * - `'live'` — target appears in a non-lookup variant's post-transform imports\n * - `'dead'` — post-transform data exists but target is absent (compiler stripped it)\n * - `'pending'` — transform ran but import data not yet posted\n * - `'no-data'` — transform never ran (warm-start cached module)\n */\n function checkEdgeLiveness(\n env: EnvState,\n parent: string,\n target: string,\n ): 'live' | 'dead' | 'pending' | 'no-data' {\n const keySet = env.transformResultKeysByFile.get(parent)\n let anyVariantCached = false\n\n if (keySet) {\n for (const k of keySet) {\n if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue\n const imports = env.postTransformImports.get(k)\n if (imports) {\n anyVariantCached = true\n if (imports.has(target)) return 'live'\n }\n }\n }\n\n if (!anyVariantCached) {\n const imports = env.postTransformImports.get(parent)\n if (imports) return imports.has(target) ? 'live' : 'dead'\n const hasTransformResult =\n env.transformResultCache.has(parent) ||\n (keySet ? keySet.size > 0 : false)\n return hasTransformResult ? 'pending' : 'no-data'\n }\n\n return 'dead'\n }\n\n function checkPostTransformReachability(\n env: EnvState,\n file: string,\n ): 'reachable' | 'unreachable' | 'unknown' {\n const visited = new Set<string>()\n const queue: Array<string> = [file]\n let hasUnknownEdge = false\n let qi = 0\n\n while (qi < queue.length) {\n const current = queue[qi++]!\n if (visited.has(current)) continue\n visited.add(current)\n\n if (env.graph.entries.has(current)) {\n return 'reachable'\n }\n\n const importers = env.graph.reverseEdges.get(current)\n if (!importers) continue\n\n for (const [parent] of importers) {\n if (visited.has(parent)) continue\n const liveness = checkEdgeLiveness(env, parent, current)\n if (liveness === 'live' || liveness === 'no-data') {\n // Live edge or warm-start (no transform data) — follow it\n queue.push(parent)\n } else if (liveness === 'pending') {\n hasUnknownEdge = true\n }\n // 'dead' — edge was stripped by compiler, skip\n }\n }\n\n return hasUnknownEdge ? 'unknown' : 'unreachable'\n }\n\n /**\n * Filter pending violations using edge-survival data. Returns the subset\n * of violations whose resolved import survived the Start compiler (or all\n * violations when no post-transform data is available yet).\n *\n * Returns `undefined` when all violations were stripped or when we must wait\n * for post-transform data before proceeding.\n */\n function filterEdgeSurvival(\n env: EnvState,\n file: string,\n violations: Array<PendingViolation>,\n ):\n | { active: Array<PendingViolation>; edgeSurvivalApplied: boolean }\n | 'all-stripped'\n | 'await-transform' {\n const postTransform = getPostTransformImports(env, file)\n\n if (postTransform) {\n const surviving = violations.filter(\n (pv) => !pv.info.resolved || postTransform.has(pv.info.resolved),\n )\n if (surviving.length === 0) return 'all-stripped'\n env.pendingViolations.set(file, surviving)\n return { active: surviving, edgeSurvivalApplied: true }\n }\n\n // Pre-transform violations need edge-survival verification first.\n if (violations.some((pv) => pv.fromPreTransformResolve)) {\n return 'await-transform'\n }\n\n return { active: violations, edgeSurvivalApplied: false }\n }\n\n /**\n * Process pending violations for the given environment. Called from the\n * transform-cache hook after each module transform is cached, because new\n * transform data may allow us to confirm or discard pending violations.\n *\n * @param warnFn - `this.warn` from the transform hook context\n */\n async function processPendingViolations(\n env: EnvState,\n warnFn: (msg: string) => void,\n ): Promise<void> {\n if (env.pendingViolations.size === 0) return\n\n const toDelete: Array<string> = []\n\n for (const [file, violations] of env.pendingViolations) {\n const filtered = filterEdgeSurvival(env, file, violations)\n\n if (filtered === 'all-stripped') {\n toDelete.push(file)\n continue\n }\n if (filtered === 'await-transform') continue\n\n const { active, edgeSurvivalApplied } = filtered\n\n // Wait for entries before running reachability. registerEntries()\n // populates entries at buildStart; resolveId(!importer) may add more.\n const status =\n env.graph.entries.size > 0\n ? checkPostTransformReachability(env, file)\n : 'unknown'\n\n if (status === 'reachable') {\n for (const pv of active) {\n await emitPendingViolation(env, warnFn, pv)\n }\n toDelete.push(file)\n } else if (status === 'unreachable') {\n toDelete.push(file)\n } else if (config.command === 'serve') {\n // 'unknown' reachability — some graph edges lack transform data.\n // When edge-survival was applied, surviving violations are confirmed\n // real. Without it (warm start), emit conservatively.\n let emittedAny = false\n for (const pv of active) {\n if (pv.fromPreTransformResolve) continue\n\n const shouldEmit =\n edgeSurvivalApplied ||\n (pv.info.type === 'file' &&\n !!pv.info.resolved &&\n isInsideDirectory(pv.info.resolved, config.srcDirectory))\n\n if (shouldEmit) {\n emittedAny =\n (await emitPendingViolation(env, warnFn, pv)) || emittedAny\n }\n }\n\n if (emittedAny) {\n toDelete.push(file)\n }\n }\n // 'unknown' — keep pending for next transform-cache invocation.\n }\n\n for (const file of toDelete) {\n env.pendingViolations.delete(file)\n }\n }\n\n async function emitPendingViolation(\n env: EnvState,\n warnFn: (msg: string) => void,\n pv: PendingViolation,\n ): Promise<boolean> {\n if (!pv.info.importerLoc) {\n const sourceCandidates = buildSourceCandidates(\n pv.info.specifier,\n pv.info.resolved,\n config.root,\n )\n const loc = await resolveImporterLocation(\n env.transformResultProvider,\n env,\n pv.info.importer,\n sourceCandidates,\n )\n\n if (loc) {\n pv.info.importerLoc = loc\n pv.info.snippet = buildCodeSnippet(\n env.transformResultProvider,\n pv.info.importer,\n loc,\n )\n }\n }\n\n if (hasSeen(env, dedupeKey(pv.info))) {\n return false\n }\n\n const freshTrace = await rebuildAndAnnotateTrace(\n env.transformResultProvider,\n env,\n pv.info.env,\n pv.info.importer,\n pv.info.specifier,\n pv.info.importerLoc,\n )\n if (freshTrace.length > pv.info.trace.length) {\n pv.info.trace = freshTrace\n }\n\n if (config.onViolation) {\n const result = await config.onViolation(pv.info)\n if (result === false) return false\n }\n\n warnFn(formatViolation(pv.info, config.root))\n return true\n }\n\n /**\n * Record a violation as pending for later confirmation via graph\n * reachability. Called from `resolveId` when `shouldDefer` is true.\n */\n function deferViolation(\n env: EnvState,\n importerFile: string,\n info: ViolationInfo,\n isPreTransformResolve?: boolean,\n ): void {\n getOrCreate(env.pendingViolations, importerFile, () => []).push({\n info,\n fromPreTransformResolve: isPreTransformResolve,\n })\n }\n\n /** Counter for generating unique per-violation mock module IDs in build mode. */\n let buildViolationCounter = 0\n\n async function handleViolation(\n ctx: ViolationReporter,\n env: EnvState,\n info: ViolationInfo,\n importerIdHint?: string,\n violationOpts?: { silent?: boolean },\n ): Promise<HandleViolationResult> {\n if (!violationOpts?.silent) {\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) return undefined\n }\n\n if (config.effectiveBehavior === 'error') {\n // Dev+error: throw immediately.\n // Always throw on error — do NOT deduplicate via hasSeen().\n // Rollup may resolve the same specifier multiple times (e.g.\n // commonjs--resolver's nested this.resolve() fires before\n // getResolveStaticDependencyPromises). If we record the key\n // on the first (nested) throw, the second (real) resolve\n // silently returns undefined and the build succeeds — which\n // is the bug this fixes.\n //\n // Build mode never reaches here — all build violations are\n // deferred via shouldDefer and handled silently.\n return ctx.error(formatViolation(info, config.root))\n }\n\n if (!hasSeen(env, dedupeKey(info))) {\n ctx.warn(formatViolation(info, config.root))\n }\n } else if (\n config.effectiveBehavior === 'error' &&\n config.command !== 'build'\n ) {\n return undefined\n }\n\n // File violations: return resolved path — the self-denial transform\n // will replace the file's content with a mock module. This avoids\n // virtual module IDs that could leak across environments via\n // third-party resolver caches.\n if (info.type === 'file') return info.resolved\n\n // Non-file violations (specifier/marker): create mock-edge module.\n // Dev mode uses a runtime diagnostics ID; build mode uses a unique\n // per-violation ID so generateBundle can check tree-shaking survival.\n const exports = await resolveExportsForDeniedSpecifier(\n env,\n ctx,\n info,\n importerIdHint,\n )\n const baseMockId =\n config.command === 'serve'\n ? mockRuntimeModuleIdFromViolation(info, config.mockAccess, config.root)\n : `${MOCK_BUILD_PREFIX}${buildViolationCounter++}`\n return resolveViteId(makeMockEdgeModuleId(exports, baseMockId))\n }\n\n /**\n * Unified violation dispatch: either defers or reports immediately.\n *\n * When `shouldDefer` is true (dev mock + build modes), calls\n * `handleViolation` silently to obtain the mock module ID, then stores\n * the violation for later verification:\n * - Dev mock mode: all violations are deferred to `pendingViolations`\n * for edge-survival and graph-reachability checking via\n * `processPendingViolations`.\n * - Build mode (mock + error): defers to `deferredBuildViolations` for\n * tree-shaking verification in `generateBundle`.\n *\n * Otherwise reports immediately (dev error mode). Pre-transform\n * resolves are silenced in error mode because they fire before the\n * compiler runs and there is no deferred verification path.\n *\n * Returns the mock module ID / resolve result from `handleViolation`.\n */\n async function reportOrDeferViolation(\n ctx: ViolationReporter,\n env: EnvState,\n importerFile: string,\n importerIdHint: string | undefined,\n info: ViolationInfo,\n shouldDefer: boolean,\n isPreTransformResolve: boolean,\n ): Promise<HandleViolationResult> {\n if (shouldDefer) {\n const result = await handleViolation(ctx, env, info, importerIdHint, {\n silent: true,\n })\n\n if (config.command === 'build') {\n // Build mode: store for generateBundle tree-shaking check.\n // The mock-edge module ID is returned as a plain string.\n const mockId = result ?? ''\n env.deferredBuildViolations.push({\n info,\n mockModuleId: mockId,\n // For marker violations, check importer survival instead of mock.\n checkModuleId: info.type === 'marker' ? info.importer : undefined,\n })\n } else {\n // Dev mock: store for graph-reachability check.\n deferViolation(env, importerFile, info, isPreTransformResolve)\n await processPendingViolations(env, ctx.warn.bind(ctx))\n }\n\n return result\n }\n\n // Non-deferred path: dev error mode only.\n // Pre-transform resolves are silenced because they fire before the\n // compiler runs — imports inside `.server()` callbacks haven't been\n // stripped yet and error mode has no deferred verification.\n return handleViolation(ctx, env, info, importerIdHint, {\n silent: isPreTransformResolve,\n })\n }\n\n return [\n {\n name: 'tanstack-start-core:import-protection',\n enforce: 'pre',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n // Start's environments are named `client` and `ssr` (not `server`), plus\n // an optional serverFn provider environment (eg `rsc`) when configured.\n return environmentNames.has(env.name)\n },\n\n configResolved(viteConfig) {\n config.root = viteConfig.root\n config.command = viteConfig.command\n\n const { startConfig, resolvedStartConfig } = opts.getConfig()\n config.srcDirectory = resolvedStartConfig.srcDirectory\n\n const userOpts: ImportProtectionOptions | undefined =\n startConfig.importProtection\n\n if (userOpts?.enabled === false) {\n config.enabled = false\n return\n }\n\n config.enabled = true\n\n const behavior = userOpts?.behavior\n if (typeof behavior === 'string') {\n config.effectiveBehavior = behavior\n } else {\n config.effectiveBehavior =\n viteConfig.command === 'serve'\n ? (behavior?.dev ?? 'mock')\n : (behavior?.build ?? 'error')\n }\n\n config.logMode = userOpts?.log ?? 'once'\n config.mockAccess = userOpts?.mockAccess ?? 'error'\n config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20\n if (userOpts?.onViolation) {\n const fn = userOpts.onViolation\n config.onViolation = (info) => fn(info)\n }\n\n const defaults = getDefaultImportProtectionRules()\n // Use user-provided patterns when available, otherwise defaults.\n const pick = <T>(user: Array<T> | undefined, fallback: Array<T>) =>\n user ? [...user] : [...fallback]\n\n // Client specifier denies always include framework defaults even\n // when the user provides a custom list.\n const clientSpecifiers = dedupePatterns([\n ...defaults.client.specifiers,\n ...(userOpts?.client?.specifiers ?? []),\n ])\n\n config.compiledRules.client = {\n specifiers: compileMatchers(clientSpecifiers),\n files: compileMatchers(\n pick(userOpts?.client?.files, defaults.client.files),\n ),\n excludeFiles: compileMatchers(\n pick(userOpts?.client?.excludeFiles, defaults.client.excludeFiles),\n ),\n }\n config.compiledRules.server = {\n specifiers: compileMatchers(\n dedupePatterns(\n pick(userOpts?.server?.specifiers, defaults.server.specifiers),\n ),\n ),\n files: compileMatchers(\n pick(userOpts?.server?.files, defaults.server.files),\n ),\n excludeFiles: compileMatchers(\n pick(userOpts?.server?.excludeFiles, defaults.server.excludeFiles),\n ),\n }\n\n config.includeMatchers = compileMatchers(userOpts?.include ?? [])\n config.excludeMatchers = compileMatchers(userOpts?.exclude ?? [])\n config.ignoreImporterMatchers = compileMatchers(\n userOpts?.ignoreImporters ?? [],\n )\n\n // Marker specifiers\n const markers = getMarkerSpecifiers()\n config.markerSpecifiers = {\n serverOnly: new Set(markers.serverOnly),\n clientOnly: new Set(markers.clientOnly),\n }\n },\n\n configureServer(server) {\n devServer = server\n },\n\n buildStart() {\n if (!config.enabled) return\n // Clear memoization caches that grow unboundedly across builds\n clearNormalizeFilePathCache()\n extensionlessIdResolver.clear()\n importPatternCache.clear()\n shouldCheckImporterCache.clear()\n\n // Clear per-env caches\n for (const envState of envStates.values()) {\n clearEnvState(envState)\n }\n\n // Clear shared state\n shared.fileMarkerKind.clear()\n\n registerEntries()\n },\n\n hotUpdate(ctx) {\n if (!config.enabled) return\n // Invalidate caches for updated files\n for (const mod of ctx.modules) {\n if (mod.id) {\n const id = mod.id\n const importerFile = normalizeFilePath(id)\n\n // Invalidate extensionless-resolution cache entries affected by this file.\n extensionlessIdResolver.invalidateByFile(importerFile)\n shared.fileMarkerKind.delete(importerFile)\n\n // Invalidate per-env caches\n for (const envState of envStates.values()) {\n invalidateFileFromEnv(envState, importerFile)\n }\n }\n }\n },\n\n async resolveId(source, importer, _options) {\n const envName = this.environment.name\n const env = getEnv(envName)\n const envType = getEnvType(envName)\n const provider = env.transformResultProvider\n const isScanResolve = !!(_options as Record<string, unknown>).scan\n\n if (IMPORT_PROTECTION_DEBUG) {\n const importerPath = importer\n ? normalizeFilePath(importer)\n : '(entry)'\n const isEntryResolve = !importer\n const filtered =\n process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER === 'entry'\n ? isEntryResolve\n : matchesDebugFilter(source, importerPath)\n if (filtered) {\n debugLog('resolveId', {\n env: envName,\n envType,\n source,\n importer: importerPath,\n isEntryResolve,\n command: config.command,\n })\n }\n }\n\n // Internal virtual modules (mock:build:N, mock-edge, mock-runtime, marker)\n const internalVirtualId = resolveInternalVirtualModuleId(source)\n if (internalVirtualId) return internalVirtualId\n\n if (!importer) {\n env.graph.addEntry(source)\n // Flush pending violations now that an additional entry is known\n // and reachability analysis may have new roots.\n await processPendingViolations(env, this.warn.bind(this))\n return undefined\n }\n\n if (source.startsWith('\\0') || source.startsWith('virtual:')) {\n return undefined\n }\n\n const normalizedImporter = normalizeFilePath(importer)\n const isDirectLookup = importer.includes(SERVER_FN_LOOKUP_QUERY)\n\n if (isDirectLookup) {\n env.serverFnLookupModules.add(normalizedImporter)\n }\n\n const isPreTransformResolve =\n isDirectLookup ||\n env.serverFnLookupModules.has(normalizedImporter) ||\n isScanResolve\n\n // Dev mock mode: defer all violations (including pre-transform\n // resolves) until post-transform data is available, then\n // confirm/discard via graph reachability.\n // Build mode (both mock and error): defer violations until\n // generateBundle so tree-shaking can eliminate false positives.\n const isDevMock =\n config.command === 'serve' && config.effectiveBehavior === 'mock'\n const isBuild = config.command === 'build'\n const shouldDefer = shouldDeferViolation({ isBuild, isDevMock })\n\n const resolveAgainstImporter = async (): Promise<string | null> => {\n const primary = await this.resolve(source, importer, {\n skipSelf: true,\n })\n if (primary) {\n return canonicalizeResolvedId(\n primary.id,\n config.root,\n resolveExtensionlessAbsoluteId,\n )\n }\n\n return null\n }\n\n // Check if this is a marker import\n const markerKind = config.markerSpecifiers.serverOnly.has(source)\n ? ('server' as const)\n : config.markerSpecifiers.clientOnly.has(source)\n ? ('client' as const)\n : undefined\n\n if (markerKind) {\n const existing = shared.fileMarkerKind.get(normalizedImporter)\n if (existing && existing !== markerKind) {\n this.error(\n `[import-protection] File \"${getRelativePath(normalizedImporter)}\" has both server-only and client-only markers. This is not allowed.`,\n )\n }\n shared.fileMarkerKind.set(normalizedImporter, markerKind)\n\n const violatesEnv =\n (envType === 'client' && markerKind === 'server') ||\n (envType === 'server' && markerKind === 'client')\n\n if (violatesEnv) {\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'marker',\n message: buildMarkerViolationMessage(\n getRelativePath(normalizedImporter),\n markerKind,\n ),\n },\n )\n const markerResult = await reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n\n // In build mode, if the violation was deferred, return the unique\n // build mock ID instead of the marker module. This lets\n // generateBundle check whether the importer (and thus its marker\n // import) survived tree-shaking. The mock is side-effect-free just\n // like the marker module, and the bare import has no bindings, so\n // replacing it is transparent.\n if (isBuild && markerResult != null) {\n return markerResult\n }\n }\n\n // Retroactive marker violation detection: on cold starts, module\n // A may import module B before B's marker is set (because B hasn't\n // been processed yet). When B's marker is set (here),\n // retroactively check all known importers of B in the graph and\n // create deferred marker violations for them. Without this,\n // cold-start ordering can miss marker violations that warm starts\n // detect (warm starts see markers early from cached transforms).\n //\n // Uses lightweight `deferViolation` to avoid heavy side effects\n // (mock module creation, export resolution). Immediately calls\n // `processPendingViolations` to flush the deferred violations,\n // because the marker resolveId fires during Vite's import\n // analysis (after our transform hook) — there may be no\n // subsequent transform invocation to flush them.\n //\n // Guarded by `violatesEnv` (per-environment) plus a per-env\n // seen-set. The marker is shared across environments but each\n // env's graph has its own edges; this ensures the check runs\n // at most once per (env, module) pair.\n const envRetroKey = `retro-marker:${normalizedImporter}`\n if (violatesEnv && !env.seenViolations.has(envRetroKey)) {\n env.seenViolations.add(envRetroKey)\n let retroDeferred = false\n const importersMap = env.graph.reverseEdges.get(normalizedImporter)\n if (importersMap && importersMap.size > 0) {\n for (const [importerFile, specifier] of importersMap) {\n if (!specifier) continue\n if (!shouldCheckImporter(importerFile)) continue\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importerFile,\n specifier,\n normalizedImporter,\n getRelativePath(normalizedImporter),\n )\n if (markerInfo) {\n deferViolation(\n env,\n importerFile,\n markerInfo,\n isPreTransformResolve,\n )\n retroDeferred = true\n }\n }\n }\n if (retroDeferred) {\n await processPendingViolations(env, this.warn.bind(this))\n }\n }\n\n return markerKind === 'server'\n ? resolvedMarkerVirtualModuleId('server')\n : resolvedMarkerVirtualModuleId('client')\n }\n\n // Check if the importer is within our scope\n if (!shouldCheckImporter(normalizedImporter)) {\n return undefined\n }\n\n const matchers = getRulesForEnvironment(envName)\n\n // 1. Specifier-based denial\n const specifierMatch = matchesAny(source, matchers.specifiers)\n if (specifierMatch) {\n if (!isPreTransformResolve) {\n env.graph.addEdge(source, normalizedImporter, source)\n }\n const info = await buildViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n {\n type: 'specifier',\n pattern: specifierMatch.pattern,\n message: `Import \"${source}\" is denied in the ${envType} environment`,\n },\n )\n\n // Resolve the specifier so edge-survival can verify whether\n // the import survives the Start compiler transform (e.g.\n // factory-safe pattern strips imports inside .server() callbacks).\n if (shouldDefer && !info.resolved) {\n try {\n const resolvedForInfo = await resolveAgainstImporter()\n if (resolvedForInfo) info.resolved = resolvedForInfo\n } catch {\n // Non-fatal: edge-survival will skip unresolved specifiers\n }\n }\n\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n // 2. Resolve the import (cached)\n const cacheKey = `${normalizedImporter}:${source}`\n let resolved: string | null\n\n if (env.resolveCache.has(cacheKey)) {\n resolved = env.resolveCache.get(cacheKey) ?? null\n } else {\n resolved = await resolveAgainstImporter()\n\n // Only cache successful resolves. Null resolves can be\n // order-dependent across importer variants (e.g. code-split\n // `?tsr-split=...` ids) and may poison later lookups.\n if (resolved !== null) {\n env.resolveCache.set(cacheKey, resolved)\n getOrCreate(\n env.resolveCacheByFile,\n normalizedImporter,\n () => new Set(),\n ).add(cacheKey)\n }\n }\n\n if (resolved) {\n const relativePath = getRelativePath(resolved)\n\n // Propagate pre-transform status transitively\n if (isPreTransformResolve && !isScanResolve) {\n env.serverFnLookupModules.add(resolved)\n }\n\n if (!isPreTransformResolve) {\n env.graph.addEdge(resolved, normalizedImporter, source)\n }\n\n // Skip file-based and marker-based denial for resolved paths that\n // match the per-environment `excludeFiles` patterns. By default\n // this includes `**/node_modules/**` so that third-party packages\n // using `.client.` / `.server.` in their filenames (e.g. react-tweet\n // exports `index.client.js`) are not treated as user-authored\n // environment boundaries. Users can override `excludeFiles` per\n // environment to narrow or widen this exclusion.\n const isExcludedFile =\n matchers.excludeFiles.length > 0 &&\n matchesAny(relativePath, matchers.excludeFiles)\n\n if (!isExcludedFile) {\n const fileMatch =\n matchers.files.length > 0\n ? matchesAny(relativePath, matchers.files)\n : undefined\n\n if (fileMatch) {\n const info = await buildFileViolationInfo(\n provider,\n env,\n envName,\n envType,\n importer,\n normalizedImporter,\n source,\n resolved,\n fileMatch.pattern,\n )\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n info,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n\n const markerInfo = await buildMarkerViolationFromResolvedImport(\n provider,\n env,\n envName,\n envType,\n importer,\n source,\n resolved,\n relativePath,\n )\n if (markerInfo) {\n return reportOrDeferViolation(\n this,\n env,\n normalizedImporter,\n importer,\n markerInfo,\n shouldDefer,\n isPreTransformResolve,\n )\n }\n }\n }\n\n return undefined\n },\n\n load: {\n filter: {\n id: new RegExp(\n getResolvedVirtualModuleMatchers().map(escapeRegExp).join('|'),\n ),\n },\n handler(id) {\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(id)) {\n debugLog('load:handler', {\n env: this.environment.name,\n id: normalizePath(id),\n })\n }\n }\n\n return loadResolvedVirtualModule(id)\n },\n },\n\n async generateBundle(_options, bundle) {\n const envName = this.environment.name\n const env = envStates.get(envName)\n if (!env || env.deferredBuildViolations.length === 0) return\n\n const candidateCache = new Map<string, Array<string>>()\n const toModuleIdCandidates = (id: string): Array<string> => {\n let cached = candidateCache.get(id)\n if (cached) return cached\n\n const out = new Set<string>()\n const normalized = normalizeFilePath(id)\n out.add(id)\n out.add(normalized)\n out.add(relativizePath(normalized, config.root))\n\n if (normalized.startsWith(VITE_BROWSER_VIRTUAL_PREFIX)) {\n const internal = `\\0${normalized.slice(VITE_BROWSER_VIRTUAL_PREFIX.length)}`\n out.add(internal)\n out.add(relativizePath(normalizeFilePath(internal), config.root))\n }\n\n if (normalized.startsWith('\\0')) {\n const browser = `${VITE_BROWSER_VIRTUAL_PREFIX}${normalized.slice(1)}`\n out.add(browser)\n out.add(relativizePath(normalizeFilePath(browser), config.root))\n }\n\n cached = Array.from(out)\n candidateCache.set(id, cached)\n return cached\n }\n\n // Collect all module IDs that survived tree-shaking in this bundle.\n const survivingModules = new Set<string>()\n for (const chunk of Object.values(bundle)) {\n if (chunk.type === 'chunk') {\n for (const moduleId of Object.keys(chunk.modules)) {\n for (const candidate of toModuleIdCandidates(moduleId)) {\n survivingModules.add(candidate)\n }\n }\n }\n }\n\n const didModuleSurvive = (moduleId: string): boolean =>\n toModuleIdCandidates(moduleId).some((candidate) =>\n survivingModules.has(candidate),\n )\n\n // Check each deferred violation: if its check module survived\n // in the bundle, the import was NOT tree-shaken — real leak.\n const realViolations: Array<ViolationInfo> = []\n for (const {\n info,\n mockModuleId,\n checkModuleId,\n } of env.deferredBuildViolations) {\n let survived: boolean\n if (checkModuleId != null) {\n // Marker violation: check if the importer survived\n // (marker is about the file's directive, not a binding).\n // Include transform-result keys (e.g. code-split variants)\n // to cover all bundle representations of the importer.\n const importerVariantIds = new Set<string>([info.importer])\n const importerKeys = env.transformResultKeysByFile.get(\n normalizeFilePath(info.importer),\n )\n if (importerKeys) {\n for (const key of importerKeys) {\n importerVariantIds.add(key)\n }\n }\n survived = false\n for (const importerId of importerVariantIds) {\n if (didModuleSurvive(importerId)) {\n survived = true\n break\n }\n }\n } else {\n // File/specifier violation: check if the mock module survived.\n survived = didModuleSurvive(mockModuleId)\n }\n\n if (!survived) continue\n\n if (config.onViolation) {\n const result = await config.onViolation(info)\n if (result === false) continue\n }\n\n realViolations.push(info)\n }\n\n if (realViolations.length === 0) return\n\n if (config.effectiveBehavior === 'error') {\n // Error mode: fail the build on the first real violation.\n this.error(formatViolation(realViolations[0]!, config.root))\n } else {\n // Mock mode: warn for each surviving violation.\n const seen = new Set<string>()\n for (const info of realViolations) {\n const key = dedupeKey(info)\n if (!seen.has(key)) {\n seen.add(key)\n this.warn(formatViolation(info, config.root))\n }\n }\n }\n },\n },\n {\n // Captures transformed code + composed sourcemap for location mapping.\n // Runs after all `enforce: 'pre'` hooks (including the Start compiler).\n // Only files under `srcDirectory` are cached.\n name: 'tanstack-start-core:import-protection-transform-cache',\n\n applyToEnvironment(env) {\n if (!config.enabled) return false\n return environmentNames.has(env.name)\n },\n\n transform: {\n filter: {\n id: {\n include: [/\\.[cm]?[tj]sx?($|\\?)/],\n },\n },\n async handler(code, id) {\n const envName = this.environment.name\n const file = normalizeFilePath(id)\n const envType = getEnvType(envName)\n const matchers = getRulesForEnvironment(envName)\n const isBuild = config.command === 'build'\n\n if (IMPORT_PROTECTION_DEBUG) {\n if (matchesDebugFilter(file)) {\n debugLog('transform-cache', {\n env: envName,\n id: normalizePath(id),\n file,\n })\n }\n }\n\n if (!shouldCheckImporter(file)) {\n return undefined\n }\n\n // Self-denial: if this file is denied in the current environment\n // (e.g. a `.server` file transformed in the client environment),\n // replace its entire content with a mock module.\n //\n // This is the core mechanism for preventing cross-environment\n // cache contamination: resolveId never returns virtual module\n // IDs for file-based violations, so there is nothing for\n // third-party resolver caches (e.g. vite-tsconfig-paths) to\n // leak across environments. Each environment's transform\n // independently decides whether the file is denied.\n //\n // In dev mode, this also solves the cold-start problem where\n // the importer's AST is unavailable for export resolution:\n // the denied file's own source code is always available here,\n // so we parse its exports directly.\n const selfFileMatch = checkFileDenial(getRelativePath(file), matchers)\n if (selfFileMatch) {\n // Parse exports once — shared by build and dev paths.\n // Falls back to empty list on non-standard syntax.\n let exportNames: Array<string> = []\n try {\n exportNames = collectNamedExports(code)\n } catch {\n // Parsing may fail on non-standard syntax\n }\n\n if (isBuild) {\n return generateSelfContainedMockModule(exportNames)\n }\n\n // Dev mode: generate a mock that imports mock-runtime for\n // runtime diagnostics (error/warn on property access).\n const runtimeId = mockRuntimeModuleIdFromViolation(\n {\n type: 'file',\n env: envType,\n envType,\n behavior:\n config.effectiveBehavior === 'error' ? 'error' : 'mock',\n importer: file,\n specifier: relativizePath(file, config.root),\n resolved: file,\n pattern: selfFileMatch.pattern,\n message: `File \"${relativizePath(file, config.root)}\" is denied in the ${envType} environment`,\n trace: [],\n },\n config.mockAccess,\n config.root,\n )\n return generateDevSelfDenialModule(exportNames, runtimeId)\n }\n\n // getCombinedSourcemap() returns the composed sourcemap\n let map: SourceMapLike | undefined\n try {\n map = this.getCombinedSourcemap()\n } catch {\n map = undefined\n }\n\n let originalCode: string | undefined\n if (map?.sourcesContent) {\n originalCode = pickOriginalCodeFromSourcesContent(\n map,\n file,\n config.root,\n )\n }\n\n const lineIndex = buildLineIndex(code)\n const cacheKey = normalizePath(id)\n\n const envState = getEnv(envName)\n const isServerFnLookup = id.includes(SERVER_FN_LOOKUP_QUERY)\n\n // Propagate SERVER_FN_LOOKUP status before import-analysis\n if (isServerFnLookup) {\n envState.serverFnLookupModules.add(file)\n }\n\n const result: TransformResult = {\n code,\n map,\n originalCode,\n lineIndex,\n }\n cacheTransformResult(envState, file, cacheKey, result)\n\n // Build mode: only self-denial (above) and transform caching are\n // needed. All violations are detected and deferred in resolveId;\n // self-denial replaces denied file content; generateBundle checks\n // tree-shaking survival. The import resolution loop below is\n // dev-mode only — it resolves imports for graph reachability,\n // catches violations missed on warm starts (where Vite caches\n // resolveId), and rewrites denied imports to mock modules.\n if (isBuild) return undefined\n\n // Dev mode: resolve imports, populate graph, detect violations,\n // and rewrite denied imports.\n const isDevMock = config.effectiveBehavior === 'mock'\n const importSources = extractImportSources(code)\n const resolvedChildren = new Set<string>()\n const deniedSourceReplacements = new Map<string, string>()\n for (const src of importSources) {\n try {\n const resolved = await this.resolve(src, id, { skipSelf: true })\n if (resolved && !resolved.external) {\n const resolvedPath = canonicalizeResolvedId(\n resolved.id,\n config.root,\n resolveExtensionlessAbsoluteId,\n )\n\n resolvedChildren.add(resolvedPath)\n\n // When the resolved ID is a mock-module (from our\n // resolveId returning a mock-edge ID), postTransformImports\n // would only contain the mock ID. Edge-survival needs the\n // real physical path so pending violations can be matched.\n //\n // For relative specifiers we can compute the physical path\n // directly. For bare/alias specifiers, look up the real\n // resolved path from the pending violations that were\n // already stored by resolveId before this transform ran.\n if (resolved.id.includes('tanstack-start-import-protection:')) {\n let physicalPath: string | undefined\n // Look up real resolved path from pending violations\n const pending = envState.pendingViolations.get(file)\n if (pending) {\n const match = pending.find(\n (pv) => pv.info.specifier === src && pv.info.resolved,\n )\n if (match) physicalPath = match.info.resolved\n }\n if (physicalPath && physicalPath !== resolvedPath) {\n resolvedChildren.add(physicalPath)\n envState.graph.addEdge(physicalPath, file, src)\n }\n }\n\n // Populate import graph edges for warm-start trace accuracy\n envState.graph.addEdge(resolvedPath, file, src)\n\n if (isDevMock) {\n const relativePath = getRelativePath(resolvedPath)\n const fileMatch = checkFileDenial(relativePath, matchers)\n\n if (fileMatch) {\n const info = await buildFileViolationInfo(\n envState.transformResultProvider,\n envState,\n envName,\n envType,\n id,\n file,\n src,\n resolvedPath,\n fileMatch.pattern,\n )\n\n const replacement = await reportOrDeferViolation(\n this,\n envState,\n file,\n id,\n info,\n isDevMock,\n isServerFnLookup,\n )\n\n if (replacement) {\n deniedSourceReplacements.set(\n src,\n replacement.startsWith('\\0')\n ? VITE_BROWSER_VIRTUAL_PREFIX + replacement.slice(1)\n : replacement,\n )\n }\n }\n }\n }\n } catch {\n // Non-fatal\n }\n }\n envState.postTransformImports.set(cacheKey, resolvedChildren)\n if (cacheKey !== file && !isServerFnLookup) {\n envState.postTransformImports.set(file, resolvedChildren)\n }\n\n await processPendingViolations(envState, this.warn.bind(this))\n\n if (deniedSourceReplacements.size > 0) {\n try {\n const rewritten = rewriteDeniedImports(\n code,\n id,\n new Set(deniedSourceReplacements.keys()),\n (source: string) =>\n deniedSourceReplacements.get(source) ?? source,\n )\n\n if (!rewritten) {\n return undefined\n }\n\n const normalizedMap = rewritten.map\n ? {\n ...rewritten.map,\n version: Number(rewritten.map.version),\n sourcesContent:\n rewritten.map.sourcesContent?.map(\n (s: string | null) => s ?? '',\n ) ?? [],\n }\n : {\n version: 3,\n file: id,\n names: [],\n sources: [id],\n sourcesContent: [code],\n mappings: '',\n }\n\n return {\n code: rewritten.code,\n map: normalizedMap,\n }\n } catch {\n // Non-fatal: keep original code when rewrite fails.\n }\n }\n\n return undefined\n },\n },\n },\n ] satisfies Array<PluginOption>\n}\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AAE,GAClD,YACL;;;;YAKH;AAIV,aAAS,qBAAqB,IAAI,UAAU,iBAAiB;AAC7D,QAAI,aAAa,QAAQ,CAAC,iBACxB,UAAS,qBAAqB,IAAI,MAAM,iBAAiB;AAG3D,UAAM,yBAAyB,UAAU,KAAK,KAAK,KAAK,KAAK,CAAC;AAE9D,QAAI,yBAAyB,OAAO,EAClC,KAAI;KACF,MAAM,YAAY,qBAChB,MACA,IACA,IAAI,IAAI,yBAAyB,MAAM,CAAC,GACvC,WACC,yBAAyB,IAAI,OAAO,IAAI,OAC3C;AAED,SAAI,CAAC,UACH;KAGF,MAAM,gBAAgB,UAAU,MAC5B;MACE,GAAG,UAAU;MACb,SAAS,OAAO,UAAU,IAAI,QAAQ;MACtC,gBACE,UAAU,IAAI,gBAAgB,KAC3B,MAAqB,KAAK,GAC5B,IAAI,EAAE;MACV,GACD;MACE,SAAS;MACT,MAAM;MACN,OAAO,EAAE;MACT,SAAS,CAAC,GAAG;MACb,gBAAgB,CAAC,KAAK;MACtB,UAAU;MACX;AAEL,YAAO;MACL,MAAM,UAAU;MAChB,KAAK;MACN;YACK;;GAOb;EACF,CACF"}
|
|
@@ -1,60 +1,63 @@
|
|
|
1
|
-
import babel from "@babel/core";
|
|
2
|
-
import * as t from "@babel/types";
|
|
3
1
|
import { parseImportProtectionAst } from "./ast.js";
|
|
2
|
+
import * as t from "@babel/types";
|
|
3
|
+
import babel from "@babel/core";
|
|
4
|
+
//#region src/import-protection-plugin/postCompileUsage.ts
|
|
5
|
+
/**
|
|
6
|
+
* Given transformed code, returns the first "meaningful" usage position for an
|
|
7
|
+
* import from `source` that survives compilation.
|
|
8
|
+
*
|
|
9
|
+
* "Preferred" positions (call, new, member-access) take priority over bare
|
|
10
|
+
* identifier references. The returned column is 0-based (Babel loc semantics).
|
|
11
|
+
*/
|
|
4
12
|
function findPostCompileUsagePos(code, source) {
|
|
5
|
-
|
|
13
|
+
return findPostCompileUsagePosFromAst(parseImportProtectionAst(code), source);
|
|
6
14
|
}
|
|
7
15
|
function findPostCompileUsagePosFromAst(ast, source) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
});
|
|
52
|
-
} catch {
|
|
53
|
-
return void 0;
|
|
54
|
-
}
|
|
55
|
-
return preferred ?? anyUsage;
|
|
16
|
+
const imported = /* @__PURE__ */ new Set();
|
|
17
|
+
for (const node of ast.program.body) if (t.isImportDeclaration(node) && node.source.value === source) {
|
|
18
|
+
if (node.importKind === "type") continue;
|
|
19
|
+
for (const s of node.specifiers) {
|
|
20
|
+
if (t.isImportSpecifier(s) && s.importKind === "type") continue;
|
|
21
|
+
imported.add(s.local.name);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (imported.size === 0) return void 0;
|
|
25
|
+
let preferred;
|
|
26
|
+
let anyUsage;
|
|
27
|
+
try {
|
|
28
|
+
babel.traverse(ast, {
|
|
29
|
+
ImportDeclaration(path) {
|
|
30
|
+
path.skip();
|
|
31
|
+
},
|
|
32
|
+
Identifier(path) {
|
|
33
|
+
if (preferred && anyUsage) {
|
|
34
|
+
path.stop();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const { node, parent, scope } = path;
|
|
38
|
+
if (!imported.has(node.name)) return;
|
|
39
|
+
if (path.isBindingIdentifier()) return;
|
|
40
|
+
if (t.isObjectProperty(parent) && parent.key === node && !parent.computed && !parent.shorthand) return;
|
|
41
|
+
if (t.isObjectMethod(parent) && parent.key === node && !parent.computed) return;
|
|
42
|
+
if (t.isExportSpecifier(parent) && parent.exported === node) return;
|
|
43
|
+
const binding = scope.getBinding(node.name);
|
|
44
|
+
if (binding && binding.kind !== "module") return;
|
|
45
|
+
const loc = node.loc?.start;
|
|
46
|
+
if (!loc) return;
|
|
47
|
+
const pos = {
|
|
48
|
+
line: loc.line,
|
|
49
|
+
column0: loc.column
|
|
50
|
+
};
|
|
51
|
+
if (t.isCallExpression(parent) && parent.callee === node || t.isNewExpression(parent) && parent.callee === node || t.isMemberExpression(parent) && parent.object === node) preferred ||= pos;
|
|
52
|
+
else anyUsage ||= pos;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
} catch {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
return preferred ?? anyUsage;
|
|
56
59
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
//# sourceMappingURL=postCompileUsage.js.map
|
|
60
|
+
//#endregion
|
|
61
|
+
export { findPostCompileUsagePos };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=postCompileUsage.js.map
|