Skip to content

Commit 729af9f

Browse files
fix: Ignore fully type-only imports and re-exports when collecting import-protection sources
1 parent 77b7d10 commit 729af9f

9 files changed

Lines changed: 166 additions & 6 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/start-plugin-core': patch
3+
---
4+
5+
Ignore fully type-only imports and re-exports when collecting import-protection sources so type-only references to protected modules do not trigger violations.

‎docs/start/framework/react/guide/import-protection.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,24 @@ By default, files inside `node_modules` are excluded from resolved-target deny c
4242

4343
These defaults mean you can use the `.server.ts` / `.client.ts` naming convention to restrict files to a single environment without any configuration. To also deny entire directories (e.g. `server/` or `client/`), add them via `files` in your [deny rules configuration](#configuring-deny-rules) — for example `files: ['**/*.server.*', '**/server/**']` for the client environment.
4444

45+
## Type-Only Imports
46+
47+
Type-only imports and re-exports are ignored by import protection because they are erased from the runtime bundle and cannot leak environment-specific code.
48+
49+
```ts
50+
import type { User } from './db.server'
51+
import { type RequestHandler } from '@tanstack/react-start/server'
52+
53+
export type { User } from './db.server'
54+
```
55+
56+
Mixed imports still count when they include at least one runtime value. Split the type and value imports if only the type is safe to cross the environment boundary.
57+
58+
```ts
59+
// This is still checked because `getUsers` is a runtime value.
60+
import { type User, getUsers } from './db.server'
61+
```
62+
4563
## File Markers
4664

4765
You can explicitly mark a module as server-only or client-only by adding a side-effect import at the top of the file:

‎e2e/react-start/import-protection/src/routes/__root.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const navLinks = linkOptions([
3030
{ to: '/noexternal-client-pkg', label: 'noExternal Client Pkg' },
3131
{ to: '/alias-path-leak', label: 'Alias Path Leak' },
3232
{ to: '/non-alias-namespace-leak', label: 'Non-Alias Namespace Leak' },
33+
{ to: '/type-only-protected-import', label: 'Type-Only Protected Import' },
3334
])
3435

3536
function RootComponent() {
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { createFileRoute } from '@tanstack/react-router'
2+
import { type RequestHandler } from '@tanstack/react-start/server'
3+
import type { TypeOnlySecret } from '../violations/type-only.server'
4+
5+
type TypeOnlyStatus = TypeOnlySecret & {
6+
requestHandler?: RequestHandler<Record<string, never>>
7+
}
8+
9+
const status: TypeOnlyStatus = {
10+
message: 'type-only protected imports are safe',
11+
}
12+
13+
function getStatusMessage(): string {
14+
return status.message
15+
}
16+
17+
export const Route = createFileRoute('/type-only-protected-import')({
18+
component: TypeOnlyProtectedImport,
19+
})
20+
21+
function TypeOnlyProtectedImport() {
22+
return (
23+
<div>
24+
<h1 data-testid="type-only-protected-import-heading">
25+
Type-Only Protected Import
26+
</h1>
27+
<p data-testid="type-only-protected-import-status">
28+
{getStatusMessage()}
29+
</p>
30+
</div>
31+
)
32+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export type TypeOnlySecret = {
2+
message: string
3+
}
4+
5+
export const runtimeSecret = 'this value must never be imported by the client'

‎e2e/react-start/import-protection/tests/import-protection.spec.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,24 @@ function findBarrelMarkerHits(violations: Array<Violation>): Array<Violation> {
103103
)
104104
}
105105

106+
function findTypeOnlyProtectedImportHits(
107+
violations: Array<Violation>,
108+
): Array<Violation> {
109+
return violations.filter(
110+
(v) =>
111+
v.envType === 'client' &&
112+
(v.importer.includes('type-only-protected-import') ||
113+
v.importer.includes('type-only.server') ||
114+
v.specifier.includes('type-only.server') ||
115+
v.resolved?.includes('type-only.server') ||
116+
v.trace.some(
117+
(s) =>
118+
s.file.includes('type-only-protected-import') ||
119+
s.file.includes('type-only.server'),
120+
)),
121+
)
122+
}
123+
106124
test.use({
107125
// The mock proxy returns undefined-ish values, which may cause
108126
// React rendering warnings — whitelist those
@@ -883,6 +901,23 @@ test('non-alias-namespace-leak does not expose real secret after hydration', asy
883901
).not.toContainText('super-secret-server-key-12345')
884902
})
885903

904+
test('type-only protected import route loads in mock mode', async ({ page }) => {
905+
await expectRouteHeading(
906+
page,
907+
'/type-only-protected-import',
908+
'type-only-protected-import-heading',
909+
'Type-Only Protected Import',
910+
)
911+
})
912+
913+
for (const mode of ['build', 'dev', 'dev.warm'] as const) {
914+
test(`type-only protected imports do not trigger violations in ${mode}`, async () => {
915+
const violations = await readViolations(mode)
916+
917+
expect(findTypeOnlyProtectedImportHits(violations)).toEqual([])
918+
})
919+
}
920+
886921
for (const mode of ['build', 'dev'] as const) {
887922
test(`no false positive for noExternal react-tweet (.client entry) in ${mode}`, async () => {
888923
const violations = await readViolations(mode)

‎e2e/react-start/import-protection/tests/violations.setup.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ const routeDefinitions = [
9494
['/alias-path-leak', 'alias-path-leak-heading'],
9595
['/alias-path-namespace-leak', 'alias-path-namespace-leak-heading'],
9696
['/non-alias-namespace-leak', 'non-alias-namespace-leak-heading'],
97+
[
98+
'/type-only-protected-import',
99+
'type-only-protected-import-heading',
100+
],
97101
] as const
98102

99103
const routes = routeDefinitions.map(([route]) => route)

‎packages/start-plugin-core/src/import-protection/analysis.ts‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,30 @@ function getStringLiteralValueStart(node: t.StringLiteral): number {
5353
return node.start
5454
}
5555

56+
function isTypeOnlyImportDeclaration(node: t.ImportDeclaration): boolean {
57+
if (node.importKind === 'type') return true
58+
if (node.specifiers.length === 0) return false
59+
60+
return node.specifiers.every(
61+
(specifier) =>
62+
t.isImportSpecifier(specifier) && specifier.importKind === 'type',
63+
)
64+
}
65+
66+
function isTypeOnlyExportNamedDeclaration(
67+
node: t.ExportNamedDeclaration,
68+
): boolean {
69+
if (node.exportKind === 'type') return true
70+
if (!node.source || node.declaration || node.specifiers.length === 0) {
71+
return false
72+
}
73+
74+
return node.specifiers.every(
75+
(specifier) =>
76+
t.isExportSpecifier(specifier) && specifier.exportKind === 'type',
77+
)
78+
}
79+
5680
function collectIdentifiersFromPattern(
5781
pattern: t.LVal,
5882
add: (name: string) => void,
@@ -149,8 +173,9 @@ function buildImportAnalysis(result: TransformResult): ImportAnalysis {
149173

150174
const visit = (node: t.Node): void => {
151175
if (t.isImportDeclaration(node)) {
152-
addSpecifierLocation(node.source)
153-
if (node.importKind !== 'type') {
176+
const isTypeOnly = isTypeOnlyImportDeclaration(node)
177+
if (!isTypeOnly) {
178+
addSpecifierLocation(node.source)
154179
const source = node.source.value
155180
const bindingInfo = getBindingInfo(source)
156181
for (const specifier of node.specifiers) {
@@ -177,11 +202,12 @@ function buildImportAnalysis(result: TransformResult): ImportAnalysis {
177202
}
178203
}
179204
} else if (t.isExportNamedDeclaration(node)) {
180-
if (node.source && t.isStringLiteral(node.source)) {
205+
const isTypeOnly = isTypeOnlyExportNamedDeclaration(node)
206+
if (!isTypeOnly && node.source && t.isStringLiteral(node.source)) {
181207
addSpecifierLocation(node.source)
182208
}
183209

184-
if (node.exportKind !== 'type' && node.source?.value) {
210+
if (!isTypeOnly && node.source?.value) {
185211
const source = node.source.value
186212
for (const specifier of node.specifiers) {
187213
if (!t.isExportSpecifier(specifier)) continue
@@ -190,7 +216,7 @@ function buildImportAnalysis(result: TransformResult): ImportAnalysis {
190216
}
191217
}
192218

193-
if (node.exportKind !== 'type') {
219+
if (!isTypeOnly) {
194220
if (node.declaration) {
195221
const decl = node.declaration
196222
if (t.isFunctionDeclaration(decl) || t.isClassDeclaration(decl)) {
@@ -210,7 +236,9 @@ function buildImportAnalysis(result: TransformResult): ImportAnalysis {
210236
}
211237
}
212238
} else if (t.isExportAllDeclaration(node)) {
213-
addSpecifierLocation(node.source)
239+
if (node.exportKind !== 'type') {
240+
addSpecifierLocation(node.source)
241+
}
214242
} else if (t.isImportExpression(node)) {
215243
if (t.isStringLiteral(node.source)) {
216244
addSpecifierLocation(node.source)

‎packages/start-plugin-core/tests/importProtection/utils.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,11 +257,43 @@ describe('getImportSources', () => {
257257
expect(getImportSources(code)).toEqual(['bar', 'qux'])
258258
})
259259

260+
test('skips type-only static import sources', () => {
261+
const code = [
262+
`import type { Foo } from './foo.server'`,
263+
`import { type Bar } from './bar.server'`,
264+
].join('\n')
265+
expect(getImportSources(code)).toEqual([])
266+
})
267+
268+
test('keeps mixed type and value static import sources', () => {
269+
const code = `import { type Foo, bar } from './mixed.server'`
270+
expect(getImportSources(code)).toEqual(['./mixed.server'])
271+
})
272+
273+
test('keeps side-effect import sources', () => {
274+
const code = `import './setup.server'`
275+
expect(getImportSources(code)).toEqual(['./setup.server'])
276+
})
277+
260278
test('extracts re-export sources', () => {
261279
const code = `export { a } from './mod'\nexport * from "./other"`
262280
expect(getImportSources(code)).toEqual(['./mod', './other'])
263281
})
264282

283+
test('skips type-only re-export sources', () => {
284+
const code = [
285+
`export type { Foo } from './foo.server'`,
286+
`export { type Bar } from './bar.server'`,
287+
`export type * from './baz.server'`,
288+
].join('\n')
289+
expect(getImportSources(code)).toEqual([])
290+
})
291+
292+
test('keeps mixed type and value re-export sources', () => {
293+
const code = `export { type Foo, bar } from './mixed.server'`
294+
expect(getImportSources(code)).toEqual(['./mixed.server'])
295+
})
296+
265297
test('extracts dynamic import sources', () => {
266298
const code = `const m = import('./lazy')\nconst n = import("./lazy2")`
267299
expect(getImportSources(code)).toEqual(['./lazy', './lazy2'])

0 commit comments

Comments
 (0)