@bleedingdev/tanstack-redact 0.2.1 → 0.3.2

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.
Files changed (120) hide show
  1. package/dist/bundler-core/resolution.d.ts +31 -0
  2. package/dist/bundler-core/resolution.js +80 -0
  3. package/dist/bundler-core/resolution.js.map +7 -0
  4. package/dist/bundler-core/selection.d.ts +89 -0
  5. package/dist/bundler-core/selection.js +103 -0
  6. package/dist/bundler-core/selection.js.map +7 -0
  7. package/dist/core/devtools.d.ts +1 -1
  8. package/dist/core/devtools.js +1 -0
  9. package/dist/core/devtools.js.map +2 -2
  10. package/dist/core/functions.js +1 -0
  11. package/dist/core/functions.js.map +2 -2
  12. package/dist/core/internal.d.ts +5 -4
  13. package/dist/core/internal.js +4 -3
  14. package/dist/core/internal.js.map +2 -2
  15. package/dist/core/types.d.ts +2 -2
  16. package/dist/core/types.js +1 -0
  17. package/dist/core/types.js.map +1 -1
  18. package/dist/dom/devtools.d.ts +5 -5
  19. package/dist/dom/devtools.js +1 -0
  20. package/dist/dom/devtools.js.map +2 -2
  21. package/dist/dom/dispatcher.d.ts +1 -1
  22. package/dist/dom/dispatcher.js +1 -0
  23. package/dist/dom/dispatcher.js.map +3 -3
  24. package/dist/dom/document-metadata.d.ts +1 -1
  25. package/dist/dom/document-metadata.js +3 -1
  26. package/dist/dom/document-metadata.js.map +2 -2
  27. package/dist/dom/dom.js +1 -1
  28. package/dist/dom/dom.js.map +2 -2
  29. package/dist/dom/features/class/full.js +25 -32
  30. package/dist/dom/features/class/full.js.map +2 -2
  31. package/dist/dom/features/class/stub.js +1 -0
  32. package/dist/dom/features/class/stub.js.map +2 -2
  33. package/dist/dom/features/hydration/full.d.ts +6 -6
  34. package/dist/dom/features/hydration/full.js +20 -29
  35. package/dist/dom/features/hydration/full.js.map +2 -2
  36. package/dist/dom/features/hydration/stub.d.ts +7 -2
  37. package/dist/dom/features/hydration/stub.js +1 -0
  38. package/dist/dom/features/hydration/stub.js.map +2 -2
  39. package/dist/dom/features/lazy/full.js +1 -0
  40. package/dist/dom/features/lazy/full.js.map +2 -2
  41. package/dist/dom/features/suspense/full.d.ts +4 -1
  42. package/dist/dom/features/suspense/full.js +22 -161
  43. package/dist/dom/features/suspense/full.js.map +2 -2
  44. package/dist/dom/features/suspense-hydration/full.d.ts +8 -0
  45. package/dist/dom/features/suspense-hydration/full.js +147 -0
  46. package/dist/dom/features/suspense-hydration/full.js.map +7 -0
  47. package/dist/dom/features/suspense-hydration/index.d.ts +1 -0
  48. package/dist/dom/features/suspense-hydration/index.js +2 -0
  49. package/dist/dom/features/suspense-hydration/index.js.map +7 -0
  50. package/dist/dom/features/suspense-hydration/stub.d.ts +2 -0
  51. package/dist/dom/features/suspense-hydration/stub.js +9 -0
  52. package/dist/dom/features/suspense-hydration/stub.js.map +7 -0
  53. package/dist/dom/features/suspense-runtime/stub.js +1 -0
  54. package/dist/dom/features/suspense-runtime/stub.js.map +2 -2
  55. package/dist/dom/profiling.d.ts +36 -0
  56. package/dist/dom/profiling.js +9 -0
  57. package/dist/dom/profiling.js.map +7 -0
  58. package/dist/dom/react-ids.js +1 -0
  59. package/dist/dom/react-ids.js.map +2 -2
  60. package/dist/dom/reconcile.d.ts +4 -5
  61. package/dist/dom/reconcile.js +102 -144
  62. package/dist/dom/reconcile.js.map +2 -2
  63. package/dist/dom/resources.js +1 -0
  64. package/dist/dom/resources.js.map +2 -2
  65. package/dist/dom/root-internal.d.ts +1 -1
  66. package/dist/dom/root-internal.js +4 -3
  67. package/dist/dom/root-internal.js.map +2 -2
  68. package/dist/dom/root.d.ts +2 -2
  69. package/dist/dom/root.js +1 -0
  70. package/dist/dom/root.js.map +2 -2
  71. package/dist/dom/synthetic-event.js +6 -4
  72. package/dist/dom/synthetic-event.js.map +2 -2
  73. package/dist/dom/transitions.d.ts +1 -1
  74. package/dist/dom/transitions.js +1 -0
  75. package/dist/dom/transitions.js.map +2 -2
  76. package/dist/react/action-scope.d.ts +1 -1
  77. package/dist/react/action-scope.js +1 -0
  78. package/dist/react/action-scope.js.map +2 -2
  79. package/dist/rspack/index.d.ts +2 -0
  80. package/dist/rspack/index.js +6 -0
  81. package/dist/rspack/index.js.map +7 -0
  82. package/dist/server/bootstrap-script.js +1 -0
  83. package/dist/server/bootstrap-script.js.map +2 -2
  84. package/dist/server/dispatcher.js +11 -20
  85. package/dist/server/dispatcher.js.map +2 -2
  86. package/dist/server/insertion-context.js +9 -16
  87. package/dist/server/insertion-context.js.map +7 -0
  88. package/dist/server/stream-ids.js +1 -0
  89. package/dist/server/stream-ids.js.map +7 -0
  90. package/dist/server/stream.d.ts +1 -2
  91. package/dist/server/stream.js +106 -122
  92. package/dist/server/stream.js.map +2 -2
  93. package/dist/server/walk.js +69 -72
  94. package/dist/server/walk.js.map +3 -3
  95. package/dist/vite/index.d.ts +5 -99
  96. package/dist/vite/index.js +56 -179
  97. package/dist/vite/index.js.map +2 -2
  98. package/dist/webpack/index.d.ts +46 -0
  99. package/dist/webpack/index.js +102 -0
  100. package/dist/webpack/index.js.map +7 -0
  101. package/dist/webpack/react18-loader.cjs +25 -0
  102. package/package.json +17 -3
  103. package/src/bundler-core/resolution.ts +131 -0
  104. package/src/bundler-core/selection.ts +192 -0
  105. package/src/core/internal.ts +2 -1
  106. package/src/core/types.ts +3 -2
  107. package/src/dom/dom.ts +1 -1
  108. package/src/dom/features/class/full.ts +26 -34
  109. package/src/dom/features/suspense/full.ts +7 -165
  110. package/src/dom/features/suspense-hydration/full.ts +166 -0
  111. package/src/dom/features/suspense-hydration/index.ts +1 -0
  112. package/src/dom/features/suspense-hydration/stub.ts +2 -0
  113. package/src/dom/profiling.ts +6 -0
  114. package/src/dom/reconcile.ts +16 -6
  115. package/src/dom/synthetic-event.ts +9 -4
  116. package/src/rspack/index.ts +2 -0
  117. package/src/server/stream.ts +15 -14
  118. package/src/vite/index.ts +55 -317
  119. package/src/webpack/index.ts +108 -0
  120. package/src/webpack/react18-loader.cjs +25 -0
package/src/vite/index.ts CHANGED
@@ -1,308 +1,21 @@
1
- import { existsSync, readFileSync, realpathSync } from 'node:fs'
1
+ import { readFileSync, realpathSync } from 'node:fs'
2
2
  import { dirname, resolve as resolvePath } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import { adaptReact18 } from './react18'
5
5
 
6
- export type RedactPreset = 'nano' | 'full'
6
+ import { ALIASES, resolveFeatures, isOwnedRuntimeFeature } from '../bundler-core/selection'
7
+ import type { ResolvedFeatures } from '../bundler-core/selection'
8
+ export type { RedactPreset, RedactFeatures } from '../bundler-core/selection'
7
9
 
8
- /**
9
- * Opt-in feature set. Each flag toggles whether the feature's real
10
- * implementation ships (`true`) or is swapped with a stub module that
11
- * degrades gracefully (`false`). Missing keys fall back to the preset's
12
- * default. Adding a feature to this interface propagates to consumer
13
- * configs as autocompleted options.
14
- */
15
- export interface RedactFeatures {
16
- /** Activity visibility, retained state and disconnected effects. */
17
- activity?: boolean
18
- /** DOM instances, events, focus, layout and observers for Fragment refs. */
19
- fragmentRefs?: boolean
20
- /** Experimental native ViewTransition animations. Opt-in until snapshot parity is complete. */
21
- viewTransitions?: boolean
22
- /**
23
- * `createPortal`. When `false`, portal elements render in place as a
24
- * Fragment (the `container` prop is ignored). `renderPortal` and its
25
- * deps are stripped from the bundle.
26
- */
27
- portal?: boolean
28
- /**
29
- * `createContext` / `useContext` / `<Provider>` / `<Consumer>`. When
30
- * `false`, Providers render as Fragments (value never propagates),
31
- * Consumers invoke their function-children with the context's default
32
- * value, and `useContext` returns the default. Provider-walk logic and
33
- * `renderProvider` are stripped.
34
- */
35
- context?: boolean
36
- /**
37
- * `<Suspense>` boundaries + streaming hydration. When `false`, Suspense
38
- * elements render as Fragments (children mount inline, `fallback` is
39
- * ignored). Thrown thenables still schedule a re-render on settle, so
40
- * eventual consistency works — just no fallback UI during the pending
41
- * window. Boundary-handler stack and hydration integration are stripped.
42
- */
43
- suspense?: boolean
44
- /**
45
- * `React.memo`. When `false`, memoized components still render but without
46
- * the prop-equality gate — every parent rerender passes through.
47
- * `shallowEqual` and the force-rerender bypass are stripped.
48
- */
49
- memo?: boolean
50
- /**
51
- * `React.forwardRef`. When `false`, forwardRef components still render but
52
- * the ref prop isn't forwarded to the inner function. React 19+ treats
53
- * refs as normal props on function components anyway, so most apps can
54
- * drop this. The dispatcher save/restore machinery is stripped.
55
- */
56
- forwardRef?: boolean
57
- /**
58
- * `React.lazy`. When `false`, lazy elements still resolve if their payload
59
- * is already available synchronously (e.g. pre-awaited RSC Flight); async
60
- * resolution throws a clear error. The hydration-deferred-reveal path and
61
- * Suspense coordination are stripped.
62
- */
63
- lazy?: boolean
64
- /**
65
- * Class components (`extends Component`). When `false`, class components
66
- * still render but only honor the core contract: constructor + `render()`
67
- * + `setState`. Dropped: `contextType`, `getDerivedStateFromProps`,
68
- * `shouldComponentUpdate`, `componentDidMount`/`Update`/`WillUnmount`,
69
- * `getDerivedStateFromError`/`componentDidCatch` (error boundaries).
70
- */
71
- classComponents?: boolean
72
- /**
73
- * SSR hydration (`hydrateRoot`). When `false`, `hydrateRoot` throws
74
- * (use `createRoot` for SPAs). The HydrationCursor / DOM adoption /
75
- * streaming-boundary coordination / event-replay / scroll-guard
76
- * machinery is stripped — the biggest single chunk of reducible code.
77
- */
78
- hydration?: boolean
79
- }
80
-
81
- interface ResolvedFeatures {
82
- activity: boolean
83
- fragmentRefs: boolean
84
- viewTransitions: boolean
85
- portal: boolean
86
- context: boolean
87
- suspense: boolean
88
- memo: boolean
89
- forwardRef: boolean
90
- lazy: boolean
91
- classComponents: boolean
92
- hydration: boolean
93
- }
94
-
95
- const PRESET_DEFAULTS: Record<RedactPreset, ResolvedFeatures> = {
96
- // Opt-in: everything off. Turn individual features on via `features`.
97
- nano: {
98
- activity: false, fragmentRefs: false, viewTransitions: false,
99
- portal: false, context: false, suspense: false, memo: false,
100
- forwardRef: false, lazy: false, classComponents: false, hydration: false,
101
- },
102
- // Opt-out: everything on (drop-in React parity). Turn features off via `features`.
103
- full: {
104
- activity: true, fragmentRefs: true, viewTransitions: false,
105
- portal: true, context: true, suspense: true, memo: true,
106
- forwardRef: true, lazy: true, classComponents: true, hydration: true,
107
- },
108
- }
109
-
110
- function resolveFeatures(
111
- preset: RedactPreset,
112
- overrides: RedactFeatures,
113
- ): ResolvedFeatures {
114
- const p = PRESET_DEFAULTS[preset]
115
- return {
116
- activity: overrides.activity ?? p.activity,
117
- fragmentRefs: overrides.fragmentRefs ?? p.fragmentRefs,
118
- viewTransitions: overrides.viewTransitions ?? p.viewTransitions,
119
- portal: overrides.portal ?? p.portal,
120
- context: overrides.context ?? p.context,
121
- suspense: overrides.suspense ?? p.suspense,
122
- memo: overrides.memo ?? p.memo,
123
- forwardRef: overrides.forwardRef ?? p.forwardRef,
124
- lazy: overrides.lazy ?? p.lazy,
125
- classComponents: overrides.classComponents ?? p.classComponents,
126
- hydration: overrides.hydration ?? p.hydration,
127
- }
128
- }
129
-
130
- export interface RedactOptions {
131
- /** Skip aliasing specific specifiers, e.g. if a consumer wants real React somewhere. */
132
- skip?: ReadonlyArray<string>
133
- /**
134
- * Override package resolution root. Defaults to the Vite config root. Useful
135
- * for monorepos where the plugin lives in a different workspace than the
136
- * consumer app.
137
- */
138
- resolveFrom?: string
139
- /**
140
- * Explicit package roots, bypassing node_modules lookup. Keys are package
141
- * names (e.g. `@tanstack/redact`), values are absolute paths to the package
142
- * directory. Handy for cross-workspace testing / bring-your-own-build setups.
143
- */
144
- packageRoots?: Record<string, string>
145
- /**
146
- * Starting point for feature selection. `'full'` (default) turns every
147
- * feature on — drop-in React parity, opt-out individual features via
148
- * `features`. `'nano'` turns everything off — opt in to what you need.
149
- */
150
- preset?: RedactPreset
151
- /**
152
- * Per-feature overrides merged on top of the preset's defaults. Enables
153
- * fine-grained "preset minus X" or "preset plus Y" configurations.
154
- */
155
- features?: RedactFeatures
156
- }
157
-
158
- // Alias map. ORDER MATTERS — Vite's alias matcher uses first-match against
159
- // prefix, so more-specific specifiers MUST come before less-specific ones.
160
- // Without this, `react-dom/server` would prefix-match `react-dom` first and
161
- // resolve to `@tanstack/redact/dom/server` (wrong) instead of
162
- // `@tanstack/redact/server`.
163
- //
164
- // `use-sync-external-store` aliases are here because its CJS-only React 17
165
- // compat shim does `var React = require('react')`. That survives Vite's
166
- // pre-bundling intact and explodes in Cloudflare Workers (no `require`).
167
- // Modern React has `useSyncExternalStore` built-in, and `@tanstack/redact`
168
- // additionally exports `useSyncExternalStoreWithSelector` so this alias
169
- // is safe everywhere.
170
- const ALIASES: Record<string, string> = {
171
- // ---- most-specific first ----
172
- 'use-sync-external-store/shim/with-selector': '@tanstack/redact',
173
- 'use-sync-external-store/shim/with-selector.js': '@tanstack/redact',
174
- 'use-sync-external-store/with-selector': '@tanstack/redact',
175
- 'use-sync-external-store/with-selector.js': '@tanstack/redact',
176
- // Explicit file subpaths (react-aria imports `shim/index.js`). Without these,
177
- // dev resolves the raw CJS shim and its named ESM import fails.
178
- 'use-sync-external-store/shim/index.js': '@tanstack/redact',
179
- 'use-sync-external-store/index.js': '@tanstack/redact',
180
- 'use-sync-external-store/shim': '@tanstack/redact',
181
- 'use-sync-external-store': '@tanstack/redact',
182
-
183
- // React drop-in shim targets. Subpaths first.
184
- 'react/jsx-runtime': '@tanstack/redact/jsx-runtime',
185
- 'react/jsx-dev-runtime': '@tanstack/redact/jsx-dev-runtime',
186
- 'react/compiler-runtime': '@tanstack/redact/compiler-runtime',
187
- 'react-dom/client': '@tanstack/redact/dom-client',
188
- 'react-dom/server.browser': '@tanstack/redact/server',
189
- 'react-dom/server.bun': '@tanstack/redact/server',
190
- 'react-dom/server.edge': '@tanstack/redact/server',
191
- 'react-dom/server.node': '@tanstack/redact/server',
192
- 'react-dom/static.edge': '@tanstack/redact/server',
193
- 'react-dom/server': '@tanstack/redact/server',
194
- 'react-dom/test-utils': '@tanstack/redact/dom-test-utils',
195
- 'react-dom': '@tanstack/redact/dom',
196
- react: '@tanstack/redact',
197
- scheduler: '@tanstack/redact/scheduler',
198
-
199
- // Self-aliases so Vite resolves `@tanstack/redact/*` imports to the same
200
- // canonical file path no matter where they originate (worker bundle vs
201
- // deps_ssr pre-bundle vs source). Without these, Cloudflare's
202
- // `noExternal: true` worker config inlines one copy while Vite's
203
- // optimizeDeps pre-bundles another, ending up with two separate
204
- // ReactSharedInternals instances and a null dispatcher in user hooks.
205
- // Subpaths first here too.
206
- '@tanstack/redact/jsx-runtime': '@tanstack/redact/jsx-runtime',
207
- '@tanstack/redact/jsx-dev-runtime': '@tanstack/redact/jsx-dev-runtime',
208
- '@tanstack/redact/compiler-runtime': '@tanstack/redact/compiler-runtime',
209
- '@tanstack/redact/dom-client': '@tanstack/redact/dom-client',
210
- '@tanstack/redact/dom-test-utils': '@tanstack/redact/dom-test-utils',
211
- '@tanstack/redact/server': '@tanstack/redact/server',
212
- '@tanstack/redact/scheduler': '@tanstack/redact/scheduler',
213
- '@tanstack/redact/dom': '@tanstack/redact/dom',
214
- '@tanstack/redact': '@tanstack/redact',
215
- }
216
-
217
- function splitSpecifier(specifier: string): { pkg: string; sub: string } {
218
- if (specifier.startsWith('@')) {
219
- const slash1 = specifier.indexOf('/')
220
- const slash2 = specifier.indexOf('/', slash1 + 1)
221
- if (slash2 < 0) return { pkg: specifier, sub: '' }
222
- return { pkg: specifier.slice(0, slash2), sub: specifier.slice(slash2 + 1) }
223
- }
224
- const slash = specifier.indexOf('/')
225
- if (slash < 0) return { pkg: specifier, sub: '' }
226
- return { pkg: specifier.slice(0, slash), sub: specifier.slice(slash + 1) }
227
- }
228
-
229
- function findPackageDir(pkg: string, fromDir: string): string | null {
230
- let dir = fromDir
231
- while (true) {
232
- const candidate = resolvePath(dir, 'node_modules', pkg)
233
- if (existsSync(resolvePath(candidate, 'package.json'))) return candidate
234
- const parent = dirname(dir)
235
- if (parent === dir) return null
236
- dir = parent
237
- }
238
- }
10
+ import { findPackageDir, resolveSpecifier, resolvePackageDir } from '../bundler-core/resolution'
11
+ import type { RedactOptions as CommonRedactOptions } from '../bundler-core/resolution'
239
12
 
240
- function resolveExport(packageDir: string, sub: string): string | null {
241
- const pkgJsonPath = resolvePath(packageDir, 'package.json')
242
- let pkg: any
243
- try {
244
- pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8'))
245
- } catch {
246
- return null
247
- }
248
- const key = sub ? './' + sub : '.'
249
- const exp = pkg.exports?.[key]
250
- // Prefer published JavaScript over TypeScript sources. Dist preserves one
251
- // file per module, so subpath imports share state and feature boundaries.
252
- const pick = (v: any): string | null => {
253
- if (typeof v === 'string') return v
254
- if (v && typeof v === 'object') {
255
- return pick(v.import ?? v.module ?? v.source ?? v.default ?? null)
256
- }
257
- return null
258
- }
259
- const target = pick(exp)
260
- if (target) return resolvePath(packageDir, target)
261
- if (!sub) {
262
- const main = pkg.module ?? pkg.main
263
- if (typeof main === 'string') return resolvePath(packageDir, main)
264
- }
265
- return null
13
+ export interface RedactOptions extends CommonRedactOptions {
14
+ /** Select browser and/or SSR replacement. RSC always keeps native React. */
15
+ environments?: ReadonlyArray<'client' | 'ssr'>
266
16
  }
267
-
268
- // When installed from npm, `@tanstack/redact` is declared as a `dependency`
269
- // of consumer apps. Under pnpm's strict mode it ends up nested under the
270
- // plugin's own `.pnpm/@tanstack+redact@.../node_modules/` rather than
271
- // hoisted to the consumer's root, so a `findPackageDir` walk starting at
272
- // the Vite project root won't always find it. Search from the plugin's own
273
- // directory first (which walks into its nested node_modules), then fall
274
- // back to the consumer root for hoisted installs.
275
17
  const pluginDir = dirname(fileURLToPath(import.meta.url))
276
18
 
277
- function resolveSpecifier(
278
- specifier: string,
279
- fromDir: string,
280
- packageRoots: Record<string, string>,
281
- ): string | null {
282
- const { pkg, sub } = splitSpecifier(specifier)
283
- const packageDir =
284
- packageRoots[pkg] ??
285
- findPackageDir(pkg, pluginDir) ??
286
- findPackageDir(pkg, fromDir)
287
- if (!packageDir) return null
288
- const target = resolveExport(packageDir, sub)
289
- if (!target) return null
290
- // Canonicalize through pnpm symlinks. Under strict pnpm, the package may
291
- // live nested under `.pnpm/@tanstack+redact@.../node_modules/*`, but each
292
- // of those is itself a symlink to the flat `.pnpm/@tanstack+redact@.../`
293
- // entry. Vite's `fetchModule` (used by TanStack Start's server-fn
294
- // compiler) follows the realpath, so the id seen by the capture-transform
295
- // differs from the nested id we'd return. That leaves the compiler's
296
- // moduleCache keyed on the realpath while `getModuleInfo` looks up the
297
- // nested path → miss → "could not load module info". Returning the
298
- // canonical realpath here keeps the two sides in agreement.
299
- try {
300
- return realpathSync(target)
301
- } catch {
302
- return target
303
- }
304
- }
305
-
306
19
  interface OptimizeDepsWithInclude {
307
20
  include?: Array<string>
308
21
  }
@@ -327,18 +40,31 @@ export function redact(options: RedactOptions = {}): any {
327
40
  const features = resolveFeatures(options.preset ?? 'full', options.features ?? {})
328
41
 
329
42
  const resolvedMap: Record<string, string> = {}
43
+ const client = !options.environments || options.environments.includes('client')
44
+ const ssr = !options.environments || options.environments.includes('ssr')
45
+ const active = (environment: any, legacySsr?: boolean): boolean => environment?.name !== 'rsc' &&
46
+ (environment?.name === 'ssr' || environment?.config?.consumer === 'server' || legacySsr ? ssr : client)
330
47
  let done = false
331
48
  let react18Version: string | undefined
332
49
  let runtimeRoot: string | undefined
50
+ const featurePackageDir = options.packageRoots?.['@tanstack/redact'] ?? resolvePath(pluginDir, '../..')
51
+ let featurePackageRoot = resolvePath(featurePackageDir)
52
+ try { featurePackageRoot = realpathSync(featurePackageRoot) } catch { /* Package may not be built yet. */ }
53
+ featurePackageRoot = featurePackageRoot.replaceAll('\\', '/').replace(/\/$/, '')
54
+ const isRuntimeFeature = (id: string) => isOwnedRuntimeFeature(id, featurePackageRoot)
333
55
 
334
56
  function resolveAll(root: string): void {
335
57
  if (done) return
336
58
  const fromDir = options.resolveFrom ?? root
337
59
  const packageRoots = options.packageRoots ?? {}
338
60
  for (const [from, to] of entries) {
339
- const resolved = resolveSpecifier(to, fromDir, packageRoots)
61
+ const resolved = resolveSpecifier(to, fromDir, packageRoots, options.resolveFrom !== undefined)
340
62
  if (resolved) resolvedMap[from] = resolved
341
63
  }
64
+ const selectedDir = resolvePackageDir('@tanstack/redact', fromDir, packageRoots, options.resolveFrom !== undefined)
65
+ if (selectedDir) {
66
+ try { featurePackageRoot = realpathSync(selectedDir).replaceAll('\\', '/').replace(/\/$/, '') } catch { /* Keep the unbuilt-package fallback. */ }
67
+ }
342
68
  done = true
343
69
  }
344
70
 
@@ -369,16 +95,16 @@ export function redact(options: RedactOptions = {}): any {
369
95
  // array form is silently ignored by rolldown's worker-runner.
370
96
  return {
371
97
  environments: {
372
- client: {
98
+ ...(client ? { client: {
373
99
  optimizeDeps: { exclude: excludeList },
374
100
  resolve: { alias: aliasMap, dedupe },
375
- },
376
- ssr: {
101
+ } } : {}),
102
+ ...(ssr ? { ssr: {
377
103
  optimizeDeps: { exclude: excludeList },
378
104
  resolve: { alias: aliasMap, dedupe, noExternal: noExt },
379
- },
105
+ } } : {}),
380
106
  },
381
- ssr: { noExternal: noExt },
107
+ ...(ssr ? { ssr: { noExternal: noExt } } : {}),
382
108
  }
383
109
  },
384
110
 
@@ -410,20 +136,21 @@ export function redact(options: RedactOptions = {}): any {
410
136
  // Skip the RSC environment — it relies on real React internals via
411
137
  // @vitejs/plugin-rsc's vendored react-server-dom. Substituting our
412
138
  // shim there breaks Flight serialization. Client + SSR envs still swap.
413
- const envName = this?.environment?.name
414
- if (envName === 'rsc') return null
139
+ if (!active(this?.environment, opts?.ssr)) return null
415
140
 
416
141
  // Feature-flag swap: when the reconciler's `features/index` module
417
142
  // imports a feature by relative path, redirect to that feature's stub
418
143
  // if the flag is off. The stub registers a graceful-degradation
419
144
  // matcher (e.g. Portal → Fragment) so user code keeps working.
420
- if (importer && /[\\/]features[\\/]index\.[jt]sx?$/.test(importer)) {
421
- const m = id.match(/^\.\/([a-z-]+)(\/index\.js)?$/)
145
+ const path = id.split(/[?#]/, 1)[0]!
146
+ const suffix = id.slice(path.length)
147
+ if (importer && isRuntimeFeature(importer) && /[\\/]features[\\/]index\.[jt]sx?$/.test(importer.split(/[?#]/, 1)[0]!)) {
148
+ const m = path.match(/^\.\/([a-z-]+)(\/index\.js)?$/)
422
149
  if (m) {
423
150
  const dir = m[1]!
424
151
  const name = (dir === 'forward-ref' ? 'forwardRef' : dir === 'fragment-refs' ? 'fragmentRefs' : dir === 'view-transition' ? 'viewTransitions' : dir === 'class' ? 'classComponents' : dir) as keyof ResolvedFeatures
425
152
  if (name in features && !features[name]) {
426
- const r = await this.resolve(`./${dir}/stub${m[2] ? '.js' : ''}`, importer, {
153
+ const r = await this.resolve(`./${dir}/stub${m[2] ? '.js' : ''}${suffix}`, importer, {
427
154
  ...opts,
428
155
  skipSelf: true,
429
156
  })
@@ -434,23 +161,32 @@ export function redact(options: RedactOptions = {}): any {
434
161
 
435
162
  // Peer imports must use the same feature selection as the registration
436
163
  // entrypoint, or an enabled feature can bring a disabled one back in.
437
- const peer = id.match(/[\\/](context|hydration|fragment-refs|view-transition|class|suspense-runtime)(?:[\\/]index\.js)?$/)
438
- const peerKey = peer?.[1] === 'suspense-runtime' ? 'suspense' : peer?.[1] === 'fragment-refs' ? 'fragmentRefs' : peer?.[1] === 'view-transition' ? 'viewTransitions' : peer?.[1] === 'class' ? 'classComponents' : peer?.[1] as 'context' | 'hydration' | undefined
164
+ const peer = path.match(/[\\/](context|hydration|fragment-refs|view-transition|class|suspense-runtime|suspense-hydration)(?:[\\/]index\.js)?$/)
165
+ const peerKey = peer?.[1] === 'suspense-hydration' ? 'hydration' : peer?.[1] === 'suspense-runtime' ? 'suspense' : peer?.[1] === 'fragment-refs' ? 'fragmentRefs' : peer?.[1] === 'view-transition' ? 'viewTransitions' : peer?.[1] === 'class' ? 'classComponents' : peer?.[1] as 'context' | 'hydration' | undefined
439
166
  if (importer && peer && peerKey && !features[peerKey]) {
440
167
  const r = await this.resolve(id, importer, { ...opts, skipSelf: true })
441
- const resolvedFeature = r?.id.match(/features[\\/](context|hydration|fragment-refs|view-transition|class|suspense-runtime)[\\/]index\.(ts|js)$/)
442
- if (resolvedFeature?.[1] === peer[1]) {
443
- return r.id.replace(/index\.(ts|js)$/, 'stub.$1')
168
+ const resolvedFeature = r?.id.match(/features[\\/](context|hydration|fragment-refs|view-transition|class|suspense-runtime|suspense-hydration)[\\/]index\.(ts|js)(?=[?#]|$)/)
169
+ if (r && isRuntimeFeature(r.id) && resolvedFeature?.[1] === peer[1]) {
170
+ return r.id.replace(/index\.(ts|js)(?=[?#]|$)/, 'stub.$1')
444
171
  }
445
172
  }
446
173
 
447
174
  return resolvedMap[id] ?? null
448
175
  },
176
+ }, {
177
+ name: 'redact:canonical-imports',
178
+ resolveId: {
179
+ order: 'pre',
180
+ handler(this: any, id: string, _importer?: string, opts?: any) {
181
+ if (!active(this.environment, opts?.ssr)) return null
182
+ return resolvedMap[id] ?? null
183
+ },
184
+ },
449
185
  }, {
450
186
  name: 'redact:react18',
451
187
  enforce: 'post',
452
- transform(this: any, code: string, id: string) {
453
- if (!react18Version || !runtimeRoot || this?.environment?.name === 'rsc') return null
188
+ transform(this: any, code: string, id: string, opts?: any) {
189
+ if (!react18Version || !runtimeRoot || !active(this?.environment, opts?.ssr)) return null
454
190
  const path = id.split('?')[0]!.replaceAll('\\', '/')
455
191
  if (!path.startsWith(runtimeRoot)) return null
456
192
  const module = path.slice(runtimeRoot.length).replace(/\.[jt]s$/, '')
@@ -465,9 +201,11 @@ export function redact(options: RedactOptions = {}): any {
465
201
  // ids to `include`. That lets Vite pre-bundle real React next to Redact,
466
202
  // producing duplicate dispatcher state. Prune after config settles so
467
203
  // Redact's client/SSR shims stay canonical.
468
- pruneOptimizeDepsInclude(config.optimizeDeps, optimizeDepsBlocked)
469
- pruneOptimizeDepsInclude(config.environments?.client?.optimizeDeps, optimizeDepsBlocked)
470
- pruneOptimizeDepsInclude(config.environments?.ssr?.optimizeDeps, optimizeDepsBlocked)
204
+ if (client) {
205
+ pruneOptimizeDepsInclude(config.optimizeDeps, optimizeDepsBlocked)
206
+ pruneOptimizeDepsInclude(config.environments?.client?.optimizeDeps, optimizeDepsBlocked)
207
+ }
208
+ if (ssr) pruneOptimizeDepsInclude(config.environments?.ssr?.optimizeDeps, optimizeDepsBlocked)
471
209
  // Leave `environments.rsc` untouched. RSC depends on real React internals.
472
210
  },
473
211
  }]
@@ -0,0 +1,108 @@
1
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { ALIASES, resolveFeatures, isOwnedRuntimeFeature } from '../bundler-core/selection'
5
+ import { findPackageDir, resolveSpecifier, resolvePackageDir } from '../bundler-core/resolution'
6
+ import type { ResolvedFeatures } from '../bundler-core/selection'
7
+ import type { RedactOptions } from '../bundler-core/resolution'
8
+ export type { RedactOptions } from '../bundler-core/resolution'
9
+ export type { RedactPreset, RedactFeatures } from '../bundler-core/selection'
10
+
11
+ const pluginDir = dirname(fileURLToPath(import.meta.url))
12
+ const directories: Record<string, keyof ResolvedFeatures> = {
13
+ activity: 'activity', 'fragment-refs': 'fragmentRefs', 'view-transition': 'viewTransitions',
14
+ portal: 'portal', context: 'context', suspense: 'suspense', memo: 'memo',
15
+ 'forward-ref': 'forwardRef', lazy: 'lazy', class: 'classComponents', hydration: 'hydration',
16
+ 'suspense-runtime': 'suspense', 'suspense-hydration': 'hydration',
17
+ }
18
+
19
+ // Both compilers expose these hooks. No compiler package is loaded by the plugin.
20
+ interface ResourceData {
21
+ resource?: string
22
+ request?: string
23
+ userRequest?: string
24
+ }
25
+ interface ModuleFactory {
26
+ hooks: { afterResolve: { tap(name: string, callback: (data: { createData?: ResourceData }) => void): void } }
27
+ }
28
+ type AliasValue = string | false | Array<string | false>
29
+
30
+ interface Compiler {
31
+ context: string
32
+ options: {
33
+ target?: string | false | ReadonlyArray<string>
34
+ resolve: { alias?: false | Record<string, AliasValue> | Array<{ name: string; alias: AliasValue; onlyModule?: boolean }> }
35
+ module: { rules: Array<unknown> }
36
+ }
37
+ hooks: { normalModuleFactory: { tap(name: string, callback: (factory: ModuleFactory) => void): void } }
38
+ }
39
+
40
+ export function selectedFeatureResource(resource: string, root: string, features: ResolvedFeatures): string | null {
41
+ const path = resource.split(/[?#]/, 1)[0]!
42
+ if (!existsSync(path)) return null
43
+ const canonical = realpathSync(path)
44
+ if (!isOwnedRuntimeFeature(canonical, root)) return null
45
+ const directory = canonical.replaceAll('\\', '/').match(/\/dom\/features\/([^/]+)\/index\.js$/)?.[1]
46
+ const feature = directory && directories[directory]
47
+ if (!feature || features[feature]) return null
48
+ const stub = resolve(dirname(canonical), 'stub.js')
49
+ if (!existsSync(stub)) throw new Error(`Redact feature stub is missing: ${stub}`)
50
+ return stub + resource.slice(path.length)
51
+ }
52
+
53
+ /** Webpack 5 and Rspack 2 integration for browser SPAs. */
54
+ export function redact(options: RedactOptions = {}) {
55
+ const features = resolveFeatures(options.preset ?? 'full', options.features ?? {})
56
+ return {
57
+ apply(compiler: Compiler): void {
58
+ const target = compiler.options.target
59
+ if (target !== undefined && target !== 'web' && !(Array.isArray(target) && target.includes('web') && target.every(value => value === 'web' || /^es\d+$/.test(value)))) {
60
+ throw new Error('The Redact Webpack/Rspack plugin supports browser SPA targets only. Use target: "web".')
61
+ }
62
+ const from = options.resolveFrom ?? compiler.context
63
+ const roots = options.packageRoots ?? {}
64
+ const packageDir = resolvePackageDir('@tanstack/redact', from, roots, options.resolveFrom !== undefined)
65
+ if (!packageDir) throw new Error('Cannot find the built @tanstack/redact package. Install it before configuring the plugin.')
66
+ const root = realpathSync(packageDir)
67
+ const aliases: Array<{ name: string; alias: string; onlyModule: boolean }> = []
68
+ for (const [name, specifier] of Object.entries(ALIASES)) {
69
+ if (options.skip?.includes(name)) continue
70
+ const alias = resolveSpecifier(specifier, from, roots, options.resolveFrom !== undefined)
71
+ if (!alias) throw new Error(`Cannot resolve Redact alias: ${specifier}`)
72
+ aliases.push({ name, alias, onlyModule: true })
73
+ }
74
+ aliases.push({ name: '@tanstack/redact/features', alias: resolve(root, 'dist/dom/features'), onlyModule: false })
75
+ const aliasKey = ({ name, onlyModule }: { name: string; onlyModule: boolean }) => name + (onlyModule ? '$' : '')
76
+ const previous = compiler.options.resolve.alias || {}
77
+ compiler.options.resolve.alias = Array.isArray(previous)
78
+ ? [...aliases, ...previous]
79
+ : Object.fromEntries([
80
+ ...aliases.map(entry => [aliasKey(entry), entry.alias]),
81
+ ...Object.entries(previous).filter(([name]) => !aliases.some(alias => aliasKey(alias) === name)),
82
+ ])
83
+ const reactDir = findPackageDir('react', from)
84
+ const version = reactDir && JSON.parse(readFileSync(resolve(reactDir, 'package.json'), 'utf8')).version
85
+ if (typeof version === 'string' && /^18\./.test(version)) {
86
+ compiler.options.module.rules.push({
87
+ test: /\.js$/,
88
+ include: (file: string) => existsSync(file) && realpathSync(file).replaceAll('\\', '/').startsWith(root.replaceAll('\\', '/') + '/dist/'),
89
+ use: [{ loader: resolve(pluginDir, 'react18-loader.cjs'), options: { packageRoot: root, version } }],
90
+ })
91
+ }
92
+ compiler.hooks.normalModuleFactory.tap('redact', factory => {
93
+ factory.hooks.afterResolve.tap('redact', data => {
94
+ const created = data.createData
95
+ if (!created?.resource) return
96
+ const old = created.resource
97
+ const next = selectedFeatureResource(old, root, features)
98
+ if (!next) return
99
+ created.resource = next
100
+ if (created.request) created.request = created.request.replace(old, next)
101
+ if (created.userRequest) created.userRequest = created.userRequest.replace(old, next)
102
+ })
103
+ })
104
+ },
105
+ }
106
+ }
107
+
108
+ export default redact
@@ -0,0 +1,25 @@
1
+ const { realpathSync } = require('node:fs')
2
+ const { relative, resolve } = require('node:path')
3
+ const { pathToFileURL } = require('node:url')
4
+ const { parse } = require('acorn')
5
+ const remapping = require('@jridgewell/remapping')
6
+
7
+ module.exports = function(source, inputMap) {
8
+ const done = this.async()
9
+ const { packageRoot, version } = this.getOptions()
10
+ const root = realpathSync(resolve(packageRoot, 'dist'))
11
+ const resource = realpathSync(this.resourcePath)
12
+ const moduleName = relative(root, resource).replaceAll('\\', '/').replace(/\.js$/, '')
13
+ if (!/^18\./.test(version) || moduleName.startsWith('../') || moduleName === '..') {
14
+ done(null, source, inputMap)
15
+ return
16
+ }
17
+ import(pathToFileURL(resolve(root, 'vite/react18.js')).href).then(({ adaptReact18 }) => {
18
+ const result = adaptReact18(source, this.resourcePath, moduleName, version,
19
+ code => parse(code, { ecmaVersion: 'latest', sourceType: 'module' }))
20
+ const map = result && inputMap
21
+ ? remapping([result.map, inputMap], () => null)
22
+ : result ? result.map : inputMap
23
+ done(null, result ? result.code : source, map)
24
+ }).catch(done)
25
+ }