diff --git a/.changeset/typed-vite-plugin.md b/.changeset/typed-vite-plugin.md new file mode 100644 index 0000000..df02dd0 --- /dev/null +++ b/.changeset/typed-vite-plugin.md @@ -0,0 +1,5 @@ +--- +'@tanstack/redact': patch +--- + +Return typed Vite plugins from `redact()` instead of `any`. diff --git a/packages/redact/src/vite/index.ts b/packages/redact/src/vite/index.ts index dfb7f6b..2b4f561 100644 --- a/packages/redact/src/vite/index.ts +++ b/packages/redact/src/vite/index.ts @@ -1,6 +1,7 @@ import { readFileSync, realpathSync } from 'node:fs' import { dirname, resolve as resolvePath } from 'node:path' import { fileURLToPath } from 'node:url' +import type { Plugin } from 'vite' import { adaptReact18 } from './react18' import { ALIASES, resolveFeatures, isOwnedRuntimeFeature } from '../bundler-core/selection' @@ -32,7 +33,7 @@ function pruneOptimizeDepsInclude( }) } -export function redact(options: RedactOptions = {}): any { +export function redact(options: RedactOptions = {}) { const skip = new Set(options.skip ?? []) const entries = Object.entries(ALIASES).filter(([k]) => !skip.has(k)) const excludeList = entries.map(([k]) => k) @@ -72,9 +73,11 @@ export function redact(options: RedactOptions = {}): any { done = true } - return [{ + // Check the common Vite contract without erasing newer environment hooks + // or making optional Vite declarations part of the public return type. + const plugins = [{ name: 'redact', - enforce: 'pre', + enforce: 'pre' as const, config() { // Single package — only one name to dedupe / no-external. @@ -188,7 +191,7 @@ export function redact(options: RedactOptions = {}): any { name: 'redact:canonical-imports', applyToEnvironment: (environment: any) => active(environment), resolveId: { - order: 'pre', + order: 'pre' as const, filter: { id: aliasFilter }, handler(this: any, id: string, _importer?: string, opts?: any) { if (!active(this.environment, opts?.ssr)) return null @@ -198,7 +201,7 @@ export function redact(options: RedactOptions = {}): any { }, { name: 'redact:react18', applyToEnvironment: (environment: any) => !!react18Version && !!runtimeRoot && active(environment), - enforce: 'post', + enforce: 'post' as const, transform(this: any, code: string, id: string, opts?: any) { if (!react18Version || !runtimeRoot || !active(this?.environment, opts?.ssr)) return null const path = id.split('?')[0]!.replaceAll('\\', '/') @@ -208,7 +211,7 @@ export function redact(options: RedactOptions = {}): any { }, }, { name: 'redact:optimize-deps-guard', - enforce: 'post', + enforce: 'post' as const, configResolved(config: any) { // `optimizeDeps.exclude` loses when another plugin force-adds the same @@ -223,6 +226,7 @@ export function redact(options: RedactOptions = {}): any { // Leave `environments.rsc` untouched. RSC depends on real React internals. }, }] + return plugins satisfies Array } export default redact diff --git a/tests/fixtures/react-router-framework/vite.config.js b/tests/fixtures/react-router-framework/vite.config.js index eaa80de..b71b86f 100644 --- a/tests/fixtures/react-router-framework/vite.config.js +++ b/tests/fixtures/react-router-framework/vite.config.js @@ -1,7 +1,11 @@ import { reactRouter } from '@react-router/dev/vite' import { redact } from '@tanstack/redact/vite' export default { - server: { host: '127.0.0.1' }, + server: { + host: '127.0.0.1', + // HMR must read a completed module, not a file while it is being rewritten. + watch: { awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 10 } }, + }, cacheDir: process.env.ROUTER_REFERENCE ? '.vite-native' : '.vite-redact', plugins: [ ...(process.env.ROUTER_REFERENCE diff --git a/tests/vite-environments.test.ts b/tests/vite-environments.test.ts index 4d883ec..cd5449d 100644 --- a/tests/vite-environments.test.ts +++ b/tests/vite-environments.test.ts @@ -6,11 +6,19 @@ import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import { execFileSync } from 'node:child_process' import { build } from 'vite' +import type { Plugin } from 'vite' import { redact } from '@tanstack/redact/vite' +// These unit fixtures supply only the Vite context fields used by each hook. +function findPlugin(plugins: Array, name: string): any { + const plugin = plugins.find(item => item.name === name) + expect(plugin).toBeDefined() + return plugin +} + it.each(['client', 'ssr'] as const)('only substitutes React in the selected %s environment', async selected => { const plugins = redact({ environments: [selected], preset: 'nano', packageRoots: { '@tanstack/redact': resolve(import.meta.dirname, '../packages/redact') } }) - const plugin = plugins.find((item: { name: string }) => item.name === 'redact') + const plugin = findPlugin(plugins, 'redact') plugin.configResolved({ root: resolve(import.meta.dirname, '..') }) const config = plugin.config() expect(Object.keys(config.environments)).toEqual([selected]) @@ -26,7 +34,7 @@ it.each(['client', 'ssr'] as const)('only substitutes React in the selected %s e it('keeps native SSR optimizer includes when only the browser uses Redact', () => { const plugins = redact({ environments: ['client'] }) - const guard = plugins.find((item: { name: string }) => item.name === 'redact:optimize-deps-guard') + const guard = findPlugin(plugins, 'redact:optimize-deps-guard') const config = { optimizeDeps: { include: ['react', 'other'] }, environments: { @@ -43,7 +51,7 @@ it('keeps native SSR optimizer includes when only the browser uses Redact', () = }) it('does not swap feature modules in an unselected SSR environment', async () => { - const plugin = redact({ environments: ['client'], preset: 'nano' }).find((item: { name: string }) => item.name === 'redact') + const plugin = findPlugin(redact({ environments: ['client'], preset: 'nano' }), 'redact') const context = { environment: { name: 'ssr' }, resolve() { throw new Error('Native SSR must not be rewritten') } } expect(await plugin.resolveId.handler.call(context, './portal', '/package/src/dom/features/index.ts')).toBeNull() }) @@ -79,8 +87,8 @@ it('leaves the native SSR protocol untouched when adapting a React 18 browser', mkdirSync(resolve(root, 'node_modules/react'), { recursive: true }) writeFileSync(resolve(root, 'node_modules/react/package.json'), JSON.stringify({ version: '18.3.1' })) const plugins = redact({ environments: ['client'], resolveFrom: root, packageRoots: { '@tanstack/redact': resolve(import.meta.dirname, '../packages/redact') } }) - const main = plugins.find((item: { name: string }) => item.name === 'redact') - const compiler = plugins.find((item: { name: string }) => item.name === 'redact:react18') + const main = findPlugin(plugins, 'redact') + const compiler = findPlugin(plugins, 'redact:react18') main.configResolved({ root }) const id = await main.resolveId.handler.call({}, 'react') const code = "export const version = '19.2.3'; export default { version: '19.2.3' };" @@ -94,8 +102,8 @@ it('leaves the native SSR protocol untouched when adapting a React 18 browser', it.each(['client', 'ssr'] as const)('keeps canonical imports in the selected %s environment only', async selected => { const plugins = redact({ environments: [selected], packageRoots: { '@tanstack/redact': resolve(import.meta.dirname, '../packages/redact') } }) - plugins.find((p: any) => p.name === 'redact').configResolved({ root: resolve(import.meta.dirname, '..') }) - const hook = plugins.find((p: any) => p.name === 'redact:canonical-imports').resolveId.handler + findPlugin(plugins, 'redact').configResolved({ root: resolve(import.meta.dirname, '..') }) + const hook = findPlugin(plugins, 'redact:canonical-imports').resolveId.handler for (const name of ['client', 'ssr', 'rsc']) expect((await hook.call({ environment: { name } }, 'react')) !== null).toBe(name === selected) expect(await hook.call({}, 'react', undefined, { ssr: true }) !== null).toBe(selected === 'ssr') }) diff --git a/tests/vite-plugin-types.test.ts b/tests/vite-plugin-types.test.ts new file mode 100644 index 0000000..18c28a3 --- /dev/null +++ b/tests/vite-plugin-types.test.ts @@ -0,0 +1,43 @@ +// @vitest-environment node +import { expect, it } from 'vitest' +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { resolve } from 'node:path' +import ts from 'typescript' + +it('publishes typed Vite plugins for both exports', () => { + const root = mkdtempSync(resolve(tmpdir(), 'redact-vite-types-')) + try { + symlinkSync(resolve(import.meta.dirname, '../node_modules'), resolve(root, 'node_modules'), 'dir') + const declaration = resolve(import.meta.dirname, '../packages/redact/dist/vite/index.js') + const fixture = (entry: string) => ` + import defaultRedact, { redact } from ${JSON.stringify(entry)}; + import { defineConfig, type Plugin } from 'vite'; + type IsAny = 0 extends (1 & T) ? true : false; + type AssertFalse = T; + export type NamedReturn = AssertFalse>>; + export type DefaultReturn = AssertFalse>>; + const plugins: Plugin[] = redact(); + defineConfig({ plugins: [redact(), ...defaultRedact(), ...plugins] }); + ` + const check = (entry: string) => { + const file = resolve(root, 'consumer.mts') + writeFileSync(file, fixture(entry)) + const program = ts.createProgram([file], { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + strict: true, skipLibCheck: true, noEmit: true, types: [], + }) + return ts.getPreEmitDiagnostics(program).map(diagnostic => ({ + code: diagnostic.code, + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), + })) + } + // Prove the same consumer rejects the original public any return type. + const control = resolve(root, 'untyped.d.mts') + writeFileSync(control, 'export declare function redact(): any;\nexport default redact;\n') + expect(check(resolve(root, 'untyped.mjs')).map(diagnostic => diagnostic.code)).toEqual([2344, 2344]) + expect(check(declaration)).toEqual([]) + } finally { rmSync(root, { recursive: true, force: true }) } +})