@octanejs/tanstack-start 0.1.0

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 (266) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +52 -0
  3. package/THIRD_PARTY_NOTICES.md +11 -0
  4. package/package.json +149 -0
  5. package/src/client-only.d.ts +1 -0
  6. package/src/client-only.js +0 -0
  7. package/src/client-rpc.d.ts +1 -0
  8. package/src/client-rpc.js +1 -0
  9. package/src/client.d.ts +3 -0
  10. package/src/client.js +2 -0
  11. package/src/default-entry/client.js +12 -0
  12. package/src/default-entry/server.js +13 -0
  13. package/src/default-entry/start.js +1 -0
  14. package/src/default-entry-paths.d.ts +5 -0
  15. package/src/default-entry-paths.js +11 -0
  16. package/src/index.d.ts +11 -0
  17. package/src/index.js +22 -0
  18. package/src/internal/README.md +15 -0
  19. package/src/internal/router-generator/config.d.ts +255 -0
  20. package/src/internal/router-generator/config.js +134 -0
  21. package/src/internal/router-generator/filesystem/physical/getRouteNodes.d.ts +53 -0
  22. package/src/internal/router-generator/filesystem/physical/getRouteNodes.js +335 -0
  23. package/src/internal/router-generator/filesystem/physical/rootPathId.d.ts +1 -0
  24. package/src/internal/router-generator/filesystem/physical/rootPathId.js +4 -0
  25. package/src/internal/router-generator/filesystem/virtual/config.d.ts +3 -0
  26. package/src/internal/router-generator/filesystem/virtual/config.js +36 -0
  27. package/src/internal/router-generator/filesystem/virtual/getRouteNodes.d.ts +31 -0
  28. package/src/internal/router-generator/filesystem/virtual/getRouteNodes.js +272 -0
  29. package/src/internal/router-generator/filesystem/virtual/loadConfigFile.d.ts +1 -0
  30. package/src/internal/router-generator/filesystem/virtual/loadConfigFile.js +10 -0
  31. package/src/internal/router-generator/generator.d.ts +119 -0
  32. package/src/internal/router-generator/generator.js +1080 -0
  33. package/src/internal/router-generator/index.d.ts +40 -0
  34. package/src/internal/router-generator/index.js +49 -0
  35. package/src/internal/router-generator/logger.d.ts +8 -0
  36. package/src/internal/router-generator/logger.js +30 -0
  37. package/src/internal/router-generator/plugin/types.d.ts +37 -0
  38. package/src/internal/router-generator/template.d.ts +38 -0
  39. package/src/internal/router-generator/template.js +220 -0
  40. package/src/internal/router-generator/transform/transform.d.ts +8 -0
  41. package/src/internal/router-generator/transform/transform.js +385 -0
  42. package/src/internal/router-generator/transform/types.d.ts +34 -0
  43. package/src/internal/router-generator/types.d.ts +73 -0
  44. package/src/internal/router-generator/utils.d.ts +270 -0
  45. package/src/internal/router-generator/utils.js +864 -0
  46. package/src/internal/router-generator/validate-route-params.d.ts +13 -0
  47. package/src/internal/router-generator/validate-route-params.js +75 -0
  48. package/src/internal/router-plugin/context.d.ts +2 -0
  49. package/src/internal/router-plugin/context.js +2 -0
  50. package/src/internal/router-plugin/core/code-splitter/compilers.d.ts +69 -0
  51. package/src/internal/router-plugin/core/code-splitter/compilers.js +1042 -0
  52. package/src/internal/router-plugin/core/code-splitter/framework-options.d.ts +11 -0
  53. package/src/internal/router-plugin/core/code-splitter/framework-options.js +41 -0
  54. package/src/internal/router-plugin/core/code-splitter/plugins/framework-plugins.d.ts +12 -0
  55. package/src/internal/router-plugin/core/code-splitter/plugins/framework-plugins.js +35 -0
  56. package/src/internal/router-plugin/core/code-splitter/plugins/octane-hmr-split-route-components.d.ts +5 -0
  57. package/src/internal/router-plugin/core/code-splitter/plugins/octane-hmr-split-route-components.js +106 -0
  58. package/src/internal/router-plugin/core/code-splitter/plugins/octane-split-route-components.d.ts +8 -0
  59. package/src/internal/router-plugin/core/code-splitter/plugins/octane-split-route-components.js +85 -0
  60. package/src/internal/router-plugin/core/code-splitter/plugins/react-refresh-ignored-route-exports.d.ts +2 -0
  61. package/src/internal/router-plugin/core/code-splitter/plugins/react-refresh-ignored-route-exports.js +55 -0
  62. package/src/internal/router-plugin/core/code-splitter/plugins/react-refresh-route-components.d.ts +2 -0
  63. package/src/internal/router-plugin/core/code-splitter/plugins/react-refresh-route-components.js +50 -0
  64. package/src/internal/router-plugin/core/code-splitter/plugins/react-stable-hmr-split-route-components.d.ts +5 -0
  65. package/src/internal/router-plugin/core/code-splitter/plugins/react-stable-hmr-split-route-components.js +54 -0
  66. package/src/internal/router-plugin/core/code-splitter/plugins.d.ts +62 -0
  67. package/src/internal/router-plugin/core/code-splitter/types.d.ts +9 -0
  68. package/src/internal/router-plugin/core/config.d.ts +294 -0
  69. package/src/internal/router-plugin/core/config.js +56 -0
  70. package/src/internal/router-plugin/core/constants.d.ts +12 -0
  71. package/src/internal/router-plugin/core/constants.js +13 -0
  72. package/src/internal/router-plugin/core/framework-plugin-order.d.ts +8 -0
  73. package/src/internal/router-plugin/core/framework-plugin-order.js +78 -0
  74. package/src/internal/router-plugin/core/hmr/handle-route-update.d.ts +1 -0
  75. package/src/internal/router-plugin/core/hmr/handle-route-update.js +126 -0
  76. package/src/internal/router-plugin/core/hmr/index.d.ts +5 -0
  77. package/src/internal/router-plugin/core/hmr/select-adapter.d.ts +17 -0
  78. package/src/internal/router-plugin/core/hmr/select-adapter.js +24 -0
  79. package/src/internal/router-plugin/core/hmr/vite-adapter.d.ts +18 -0
  80. package/src/internal/router-plugin/core/hmr/vite-adapter.js +73 -0
  81. package/src/internal/router-plugin/core/hmr/webpack-adapter.d.ts +22 -0
  82. package/src/internal/router-plugin/core/hmr/webpack-adapter.js +78 -0
  83. package/src/internal/router-plugin/core/router-code-splitter-plugin.d.ts +10 -0
  84. package/src/internal/router-plugin/core/router-code-splitter-plugin.js +244 -0
  85. package/src/internal/router-plugin/core/router-composed-plugin.d.ts +5 -0
  86. package/src/internal/router-plugin/core/router-composed-plugin.js +62 -0
  87. package/src/internal/router-plugin/core/router-generator-plugin.d.ts +10 -0
  88. package/src/internal/router-plugin/core/router-generator-plugin.js +125 -0
  89. package/src/internal/router-plugin/core/router-hmr-plugin.d.ts +13 -0
  90. package/src/internal/router-plugin/core/router-hmr-plugin.js +101 -0
  91. package/src/internal/router-plugin/core/router-plugin-context.d.ts +5 -0
  92. package/src/internal/router-plugin/core/router-plugin-context.js +6 -0
  93. package/src/internal/router-plugin/core/utils.d.ts +17 -0
  94. package/src/internal/router-plugin/core/utils.js +47 -0
  95. package/src/internal/router-plugin/esbuild.d.ts +197 -0
  96. package/src/internal/router-plugin/esbuild.js +58 -0
  97. package/src/internal/router-plugin/index.d.ts +19 -0
  98. package/src/internal/router-plugin/index.js +17 -0
  99. package/src/internal/router-plugin/rspack.d.ts +61 -0
  100. package/src/internal/router-plugin/rspack.js +92 -0
  101. package/src/internal/router-plugin/vite.d.ts +201 -0
  102. package/src/internal/router-plugin/vite.js +62 -0
  103. package/src/internal/router-plugin/webpack.d.ts +50 -0
  104. package/src/internal/router-plugin/webpack.js +77 -0
  105. package/src/internal/start-plugin-core/build-sitemap.d.ts +34 -0
  106. package/src/internal/start-plugin-core/build-sitemap.js +125 -0
  107. package/src/internal/start-plugin-core/config-context.d.ts +30 -0
  108. package/src/internal/start-plugin-core/config-context.js +89 -0
  109. package/src/internal/start-plugin-core/constants.d.ts +20 -0
  110. package/src/internal/start-plugin-core/constants.js +24 -0
  111. package/src/internal/start-plugin-core/debug.d.ts +1 -0
  112. package/src/internal/start-plugin-core/hydrate-when-transform.d.ts +5 -0
  113. package/src/internal/start-plugin-core/hydrate-when-transform.js +661 -0
  114. package/src/internal/start-plugin-core/hydration-constants.d.ts +1 -0
  115. package/src/internal/start-plugin-core/hydration-constants.js +4 -0
  116. package/src/internal/start-plugin-core/import-protection/adapterUtils.d.ts +40 -0
  117. package/src/internal/start-plugin-core/import-protection/adapterUtils.js +42 -0
  118. package/src/internal/start-plugin-core/import-protection/analysis.d.ts +63 -0
  119. package/src/internal/start-plugin-core/import-protection/analysis.js +533 -0
  120. package/src/internal/start-plugin-core/import-protection/constants.d.ts +11 -0
  121. package/src/internal/start-plugin-core/import-protection/constants.js +39 -0
  122. package/src/internal/start-plugin-core/import-protection/defaults.d.ts +19 -0
  123. package/src/internal/start-plugin-core/import-protection/defaults.js +34 -0
  124. package/src/internal/start-plugin-core/import-protection/extensionlessAbsoluteIdResolver.d.ts +22 -0
  125. package/src/internal/start-plugin-core/import-protection/extensionlessAbsoluteIdResolver.js +94 -0
  126. package/src/internal/start-plugin-core/import-protection/matchers.d.ts +18 -0
  127. package/src/internal/start-plugin-core/import-protection/matchers.js +39 -0
  128. package/src/internal/start-plugin-core/import-protection/rewrite.d.ts +29 -0
  129. package/src/internal/start-plugin-core/import-protection/rewrite.js +184 -0
  130. package/src/internal/start-plugin-core/import-protection/sourceLocation.d.ts +170 -0
  131. package/src/internal/start-plugin-core/import-protection/sourceLocation.js +376 -0
  132. package/src/internal/start-plugin-core/import-protection/trace.d.ts +89 -0
  133. package/src/internal/start-plugin-core/import-protection/trace.js +186 -0
  134. package/src/internal/start-plugin-core/import-protection/utils.d.ts +78 -0
  135. package/src/internal/start-plugin-core/import-protection/utils.js +171 -0
  136. package/src/internal/start-plugin-core/import-protection/virtualModules.d.ts +38 -0
  137. package/src/internal/start-plugin-core/import-protection/virtualModules.js +241 -0
  138. package/src/internal/start-plugin-core/index.d.ts +8 -0
  139. package/src/internal/start-plugin-core/index.js +2 -0
  140. package/src/internal/start-plugin-core/planning.d.ts +44 -0
  141. package/src/internal/start-plugin-core/planning.js +98 -0
  142. package/src/internal/start-plugin-core/post-build.d.ts +12 -0
  143. package/src/internal/start-plugin-core/post-build.js +40 -0
  144. package/src/internal/start-plugin-core/prerender.d.ts +17 -0
  145. package/src/internal/start-plugin-core/prerender.js +172 -0
  146. package/src/internal/start-plugin-core/queue.d.ts +37 -0
  147. package/src/internal/start-plugin-core/queue.js +118 -0
  148. package/src/internal/start-plugin-core/resolve-entries.d.ts +10 -0
  149. package/src/internal/start-plugin-core/resolve-entries.js +32 -0
  150. package/src/internal/start-plugin-core/schema.d.ts +1799 -0
  151. package/src/internal/start-plugin-core/schema.js +252 -0
  152. package/src/internal/start-plugin-core/serialization-adapters-module.d.ts +18 -0
  153. package/src/internal/start-plugin-core/serialization-adapters-module.js +37 -0
  154. package/src/internal/start-plugin-core/start-compiler/compiler.d.ts +181 -0
  155. package/src/internal/start-plugin-core/start-compiler/compiler.js +1078 -0
  156. package/src/internal/start-plugin-core/start-compiler/config.d.ts +20 -0
  157. package/src/internal/start-plugin-core/start-compiler/config.js +84 -0
  158. package/src/internal/start-plugin-core/start-compiler/handleClientOnlyJSX.d.ts +24 -0
  159. package/src/internal/start-plugin-core/start-compiler/handleClientOnlyJSX.js +25 -0
  160. package/src/internal/start-plugin-core/start-compiler/handleCreateIsomorphicFn.d.ts +11 -0
  161. package/src/internal/start-plugin-core/start-compiler/handleCreateIsomorphicFn.js +24 -0
  162. package/src/internal/start-plugin-core/start-compiler/handleCreateMiddleware.d.ts +11 -0
  163. package/src/internal/start-plugin-core/start-compiler/handleCreateMiddleware.js +35 -0
  164. package/src/internal/start-plugin-core/start-compiler/handleCreateServerFn.d.ts +22 -0
  165. package/src/internal/start-plugin-core/start-compiler/handleCreateServerFn.js +292 -0
  166. package/src/internal/start-plugin-core/start-compiler/handleEnvOnly.d.ts +14 -0
  167. package/src/internal/start-plugin-core/start-compiler/handleEnvOnly.js +41 -0
  168. package/src/internal/start-plugin-core/start-compiler/host.d.ts +44 -0
  169. package/src/internal/start-plugin-core/start-compiler/host.js +75 -0
  170. package/src/internal/start-plugin-core/start-compiler/server-fn-resolver-module.d.ts +10 -0
  171. package/src/internal/start-plugin-core/start-compiler/server-fn-resolver-module.js +87 -0
  172. package/src/internal/start-plugin-core/start-compiler/types.d.ts +119 -0
  173. package/src/internal/start-plugin-core/start-compiler/utils.d.ts +27 -0
  174. package/src/internal/start-plugin-core/start-compiler/utils.js +36 -0
  175. package/src/internal/start-plugin-core/start-manifest-plugin/inlineCss.d.ts +16 -0
  176. package/src/internal/start-plugin-core/start-manifest-plugin/inlineCss.js +131 -0
  177. package/src/internal/start-plugin-core/start-manifest-plugin/manifestBuilder.d.ts +64 -0
  178. package/src/internal/start-plugin-core/start-manifest-plugin/manifestBuilder.js +441 -0
  179. package/src/internal/start-plugin-core/start-router-plugin/constants.d.ts +1 -0
  180. package/src/internal/start-plugin-core/start-router-plugin/constants.js +4 -0
  181. package/src/internal/start-plugin-core/start-router-plugin/generator-plugins/compose-generator-plugins.d.ts +6 -0
  182. package/src/internal/start-plugin-core/start-router-plugin/generator-plugins/compose-generator-plugins.js +6 -0
  183. package/src/internal/start-plugin-core/start-router-plugin/generator-plugins/prerender-routes-plugin.d.ts +6 -0
  184. package/src/internal/start-plugin-core/start-router-plugin/generator-plugins/prerender-routes-plugin.js +27 -0
  185. package/src/internal/start-plugin-core/start-router-plugin/generator-plugins/routes-manifest-plugin.d.ts +6 -0
  186. package/src/internal/start-plugin-core/start-router-plugin/generator-plugins/routes-manifest-plugin.js +34 -0
  187. package/src/internal/start-plugin-core/start-router-plugin/pruneServerOnlySubtrees.d.ts +11 -0
  188. package/src/internal/start-plugin-core/start-router-plugin/pruneServerOnlySubtrees.js +42 -0
  189. package/src/internal/start-plugin-core/start-router-plugin/route-tree-footer.d.ts +6 -0
  190. package/src/internal/start-plugin-core/start-router-plugin/route-tree-footer.js +59 -0
  191. package/src/internal/start-plugin-core/types.d.ts +135 -0
  192. package/src/internal/start-plugin-core/types.js +4 -0
  193. package/src/internal/start-plugin-core/utils.d.ts +13 -0
  194. package/src/internal/start-plugin-core/utils.js +42 -0
  195. package/src/internal/start-plugin-core/vite/createVirtualModule.d.ts +15 -0
  196. package/src/internal/start-plugin-core/vite/createVirtualModule.js +27 -0
  197. package/src/internal/start-plugin-core/vite/dev-server-plugin/dev-styles.d.ts +26 -0
  198. package/src/internal/start-plugin-core/vite/dev-server-plugin/dev-styles.js +165 -0
  199. package/src/internal/start-plugin-core/vite/dev-server-plugin/plugin.d.ts +11 -0
  200. package/src/internal/start-plugin-core/vite/dev-server-plugin/plugin.js +170 -0
  201. package/src/internal/start-plugin-core/vite/import-protection-plugin/plugin.d.ts +4 -0
  202. package/src/internal/start-plugin-core/vite/import-protection-plugin/plugin.js +1553 -0
  203. package/src/internal/start-plugin-core/vite/import-protection-plugin/types.d.ts +103 -0
  204. package/src/internal/start-plugin-core/vite/import-protection-plugin/virtualModules.d.ts +40 -0
  205. package/src/internal/start-plugin-core/vite/import-protection-plugin/virtualModules.js +68 -0
  206. package/src/internal/start-plugin-core/vite/index.d.ts +13 -0
  207. package/src/internal/start-plugin-core/vite/index.js +4 -0
  208. package/src/internal/start-plugin-core/vite/load-env-plugin/plugin.d.ts +2 -0
  209. package/src/internal/start-plugin-core/vite/load-env-plugin/plugin.js +13 -0
  210. package/src/internal/start-plugin-core/vite/output-directory.d.ts +7 -0
  211. package/src/internal/start-plugin-core/vite/output-directory.js +18 -0
  212. package/src/internal/start-plugin-core/vite/planning.d.ts +112 -0
  213. package/src/internal/start-plugin-core/vite/planning.js +152 -0
  214. package/src/internal/start-plugin-core/vite/plugin.d.ts +7 -0
  215. package/src/internal/start-plugin-core/vite/plugin.js +208 -0
  216. package/src/internal/start-plugin-core/vite/plugins.d.ts +17 -0
  217. package/src/internal/start-plugin-core/vite/plugins.js +72 -0
  218. package/src/internal/start-plugin-core/vite/post-server-build.d.ts +9 -0
  219. package/src/internal/start-plugin-core/vite/post-server-build.js +22 -0
  220. package/src/internal/start-plugin-core/vite/prerender.d.ts +9 -0
  221. package/src/internal/start-plugin-core/vite/prerender.js +52 -0
  222. package/src/internal/start-plugin-core/vite/preview-server-plugin/plugin.d.ts +2 -0
  223. package/src/internal/start-plugin-core/vite/preview-server-plugin/plugin.js +54 -0
  224. package/src/internal/start-plugin-core/vite/schema.d.ts +2423 -0
  225. package/src/internal/start-plugin-core/vite/schema.js +17 -0
  226. package/src/internal/start-plugin-core/vite/serialization-adapters-plugin.d.ts +5 -0
  227. package/src/internal/start-plugin-core/vite/serialization-adapters-plugin.js +63 -0
  228. package/src/internal/start-plugin-core/vite/start-compiler-plugin/hot-update.d.ts +5 -0
  229. package/src/internal/start-plugin-core/vite/start-compiler-plugin/hot-update.js +14 -0
  230. package/src/internal/start-plugin-core/vite/start-compiler-plugin/module-specifier.d.ts +5 -0
  231. package/src/internal/start-plugin-core/vite/start-compiler-plugin/module-specifier.js +25 -0
  232. package/src/internal/start-plugin-core/vite/start-compiler-plugin/plugin.d.ts +29 -0
  233. package/src/internal/start-plugin-core/vite/start-compiler-plugin/plugin.js +380 -0
  234. package/src/internal/start-plugin-core/vite/start-manifest-plugin/normalized-client-build.d.ts +11 -0
  235. package/src/internal/start-plugin-core/vite/start-manifest-plugin/normalized-client-build.js +114 -0
  236. package/src/internal/start-plugin-core/vite/start-manifest-plugin/plugin.d.ts +3 -0
  237. package/src/internal/start-plugin-core/vite/start-manifest-plugin/plugin.js +103 -0
  238. package/src/internal/start-plugin-core/vite/start-router-plugin/plugin.d.ts +9 -0
  239. package/src/internal/start-plugin-core/vite/start-router-plugin/plugin.js +143 -0
  240. package/src/internal/start-plugin-core/vite/types.d.ts +17 -0
  241. package/src/package-names.js +10 -0
  242. package/src/plugin-vite.d.ts +23 -0
  243. package/src/plugin-vite.js +62 -0
  244. package/src/runtime/client/StartClient.d.ts +11 -0
  245. package/src/runtime/client/StartClient.js +16 -0
  246. package/src/runtime/client/hydrateStart.d.ts +4 -0
  247. package/src/runtime/client/hydrateStart.js +30 -0
  248. package/src/runtime/server/StartServer.d.ts +10 -0
  249. package/src/runtime/server/StartServer.js +6 -0
  250. package/src/runtime/server/defaultRenderHandler.d.ts +3 -0
  251. package/src/runtime/server/defaultRenderHandler.js +11 -0
  252. package/src/runtime/server/defaultStreamHandler.d.ts +3 -0
  253. package/src/runtime/server/defaultStreamHandler.js +13 -0
  254. package/src/server-entry.d.ts +11 -0
  255. package/src/server-entry.js +13 -0
  256. package/src/server-only.d.ts +1 -0
  257. package/src/server-only.js +0 -0
  258. package/src/server-rpc.d.ts +1 -0
  259. package/src/server-rpc.js +1 -0
  260. package/src/server.d.ts +6 -0
  261. package/src/server.js +4 -0
  262. package/src/ssr-rpc.d.ts +1 -0
  263. package/src/ssr-rpc.js +1 -0
  264. package/src/use-server-fn.d.ts +3 -0
  265. package/src/use-server-fn.js +18 -0
  266. package/src/validate-options.js +7 -0
@@ -0,0 +1,1553 @@
1
+ import { VITE_ENVIRONMENT_NAMES } from '../../constants.js';
2
+ import { escapeRegExp, resolveViteId } from '../../utils.js';
3
+ import {
4
+ IMPORT_PROTECTION_DEBUG,
5
+ MOCK_BUILD_PREFIX,
6
+ SERVER_FN_LOOKUP_QUERY,
7
+ VITE_BROWSER_VIRTUAL_PREFIX,
8
+ } from '../../import-protection/constants.js';
9
+ import {
10
+ buildResolutionCandidates,
11
+ buildSourceCandidates,
12
+ canonicalizeResolvedId,
13
+ checkFileDenial,
14
+ clearNormalizeFilePathCache,
15
+ debugLog,
16
+ dedupePatterns,
17
+ dedupeViolationKey,
18
+ getOrCreate,
19
+ isFileExcluded,
20
+ isInsideDirectory,
21
+ matchesDebugFilter,
22
+ normalizeFilePath,
23
+ relativizePath,
24
+ shouldDeferViolation,
25
+ } from '../../import-protection/utils.js';
26
+ import { ImportGraph, buildTrace, formatViolation } from '../../import-protection/trace.js';
27
+ import {
28
+ getDefaultImportProtectionRules,
29
+ getMarkerSpecifiers,
30
+ } from '../../import-protection/defaults.js';
31
+ import { compileMatchers, matchesAny } from '../../import-protection/matchers.js';
32
+ import {
33
+ getImportProtectionEnvType,
34
+ getImportProtectionRelativePath,
35
+ getImportProtectionRulesForEnvironment,
36
+ shouldCheckImportProtectionImporter,
37
+ } from '../../import-protection/adapterUtils.js';
38
+ import {
39
+ ImportLocCache,
40
+ addTraceImportLocations,
41
+ buildCodeSnippet,
42
+ createImportSpecifierLocationIndex,
43
+ findImportStatementLocationFromTransformed,
44
+ findOriginalUsageLocation,
45
+ findPostCompileUsageLocation,
46
+ normalizeSourceMap,
47
+ } from '../../import-protection/sourceLocation.js';
48
+ import {
49
+ getImportSourcesFromResult,
50
+ getMockExportNamesBySource,
51
+ getNamedExports,
52
+ } from '../../import-protection/analysis.js';
53
+ import { rewriteDeniedImports } from '../../import-protection/rewrite.js';
54
+ import { ExtensionlessAbsoluteIdResolver } from '../../import-protection/extensionlessAbsoluteIdResolver.js';
55
+ import {
56
+ generateDevSelfDenialModule,
57
+ generateSelfContainedMockModule,
58
+ makeMockEdgeModuleId,
59
+ mockRuntimeModuleIdFromViolation,
60
+ } from '../../import-protection/virtualModules.js';
61
+ import {
62
+ getResolvedVirtualModuleMatchers,
63
+ loadResolvedVirtualModule,
64
+ resolveInternalVirtualModuleId,
65
+ resolvedMarkerVirtualModuleId,
66
+ } from './virtualModules.js';
67
+ import { dirname, relative } from 'pathe';
68
+ import { writeFileSync } from 'node:fs';
69
+ import { normalizePath } from 'vite';
70
+ //#region src/vite/import-protection-plugin/plugin.ts
71
+ function isPerfEnabled() {
72
+ return (
73
+ process.env.TSR_IMPORT_PROTECTION_PERF === '1' ||
74
+ process.env.TSR_IMPORT_PROTECTION_PERF === 'true'
75
+ );
76
+ }
77
+ function createPerfCollector() {
78
+ const counters = /* @__PURE__ */ new Map();
79
+ const timings = /* @__PURE__ */ new Map();
80
+ const flushEnvironments = /* @__PURE__ */ new Set();
81
+ let flushCount = 0;
82
+ return {
83
+ count(name, value = 1) {
84
+ counters.set(name, (counters.get(name) ?? 0) + value);
85
+ },
86
+ time(name, startedAt) {
87
+ const duration = performance.now() - startedAt;
88
+ const timing = timings.get(name);
89
+ if (timing) {
90
+ timing.count++;
91
+ timing.totalMs += duration;
92
+ timing.maxMs = Math.max(timing.maxMs, duration);
93
+ } else
94
+ timings.set(name, {
95
+ count: 1,
96
+ totalMs: duration,
97
+ maxMs: duration,
98
+ });
99
+ },
100
+ flush(root, envName) {
101
+ flushCount++;
102
+ flushEnvironments.add(envName);
103
+ const payload = {
104
+ root,
105
+ flushCount,
106
+ flushEnvironments: Array.from(flushEnvironments).sort(),
107
+ counters: Object.fromEntries(counters),
108
+ timings: Object.fromEntries(
109
+ Array.from(timings, ([name, timing]) => [
110
+ name,
111
+ {
112
+ count: timing.count,
113
+ totalMs: Number(timing.totalMs.toFixed(3)),
114
+ avgMs: Number((timing.totalMs / timing.count).toFixed(3)),
115
+ maxMs: Number(timing.maxMs.toFixed(3)),
116
+ },
117
+ ]),
118
+ ),
119
+ };
120
+ const file = process.env.TSR_IMPORT_PROTECTION_PERF_FILE;
121
+ if (file) writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`);
122
+ else console.warn(`[import-protection:perf] ${JSON.stringify(payload, null, 2)}`);
123
+ },
124
+ };
125
+ }
126
+ function importProtectionPlugin(opts) {
127
+ let devServer = null;
128
+ const perf = isPerfEnabled() ? createPerfCollector() : void 0;
129
+ const extensionlessIdResolver = new ExtensionlessAbsoluteIdResolver();
130
+ const resolveExtensionlessAbsoluteId = (id) => extensionlessIdResolver.resolve(id);
131
+ const importSpecifierLocationIndex = createImportSpecifierLocationIndex();
132
+ /**
133
+ * Build an import trace using Vite's per-environment module graph, which
134
+ * is authoritative even on warm starts when the plugin's own ImportGraph
135
+ * may be incomplete (Vite skips resolveId for cached modules).
136
+ */
137
+ function buildTraceFromModuleGraph(envName, env, targetFile) {
138
+ if (!devServer) return null;
139
+ const environment = devServer.environments[envName];
140
+ if (!environment) return null;
141
+ const file = normalizeFilePath(targetFile);
142
+ const start = environment.moduleGraph.getModuleById(file);
143
+ if (!start) return null;
144
+ const nodeIds = /* @__PURE__ */ new Map();
145
+ function nodeId(n) {
146
+ let cached = nodeIds.get(n);
147
+ if (cached === void 0) {
148
+ cached = n.id ? normalizeFilePath(n.id) : n.url ? normalizeFilePath(n.url) : '';
149
+ nodeIds.set(n, cached);
150
+ }
151
+ return cached;
152
+ }
153
+ const queue = [start];
154
+ const visited = new Set([start]);
155
+ const parent = /* @__PURE__ */ new Map();
156
+ let entryRoot = null;
157
+ let fallbackRoot = null;
158
+ let qi = 0;
159
+ while (qi < queue.length) {
160
+ const node = queue[qi++];
161
+ const id = nodeId(node);
162
+ if (id && env.graph.entries.has(id)) {
163
+ entryRoot = node;
164
+ break;
165
+ }
166
+ const importers = node.importers;
167
+ if (importers.size === 0) {
168
+ if (!fallbackRoot) fallbackRoot = node;
169
+ continue;
170
+ }
171
+ for (const imp of importers) {
172
+ if (visited.has(imp)) continue;
173
+ visited.add(imp);
174
+ parent.set(imp, node);
175
+ queue.push(imp);
176
+ }
177
+ }
178
+ const root = entryRoot ?? fallbackRoot;
179
+ if (!root) return null;
180
+ const chain = [];
181
+ let cur = root;
182
+ for (let i = 0; i < config.maxTraceDepth + 2 && cur; i++) {
183
+ chain.push(cur);
184
+ if (cur === start) break;
185
+ cur = parent.get(cur);
186
+ }
187
+ const steps = [];
188
+ for (let i = 0; i < chain.length; i++) {
189
+ const id = nodeId(chain[i]);
190
+ if (!id) continue;
191
+ let specifier;
192
+ if (i + 1 < chain.length) {
193
+ const nextId = nodeId(chain[i + 1]);
194
+ if (nextId) specifier = env.graph.reverseEdges.get(nextId)?.get(id);
195
+ }
196
+ steps.push(
197
+ specifier
198
+ ? {
199
+ file: id,
200
+ specifier,
201
+ }
202
+ : { file: id },
203
+ );
204
+ }
205
+ return steps.length ? steps : null;
206
+ }
207
+ const config = {
208
+ enabled: true,
209
+ root: '',
210
+ command: 'build',
211
+ bundledDev: false,
212
+ srcDirectory: '',
213
+ framework: opts.framework,
214
+ effectiveBehavior: 'error',
215
+ mockAccess: 'error',
216
+ logMode: 'once',
217
+ maxTraceDepth: 20,
218
+ compiledRules: {
219
+ client: {
220
+ specifiers: [],
221
+ files: [],
222
+ excludeFiles: [],
223
+ },
224
+ server: {
225
+ specifiers: [],
226
+ files: [],
227
+ excludeFiles: [],
228
+ },
229
+ },
230
+ includeMatchers: [],
231
+ excludeMatchers: [],
232
+ ignoreImporterMatchers: [],
233
+ markerSpecifiers: {
234
+ serverOnly: /* @__PURE__ */ new Set(),
235
+ clientOnly: /* @__PURE__ */ new Set(),
236
+ },
237
+ envTypeMap: new Map(opts.environments.map((e) => [e.name, e.type])),
238
+ onViolation: void 0,
239
+ };
240
+ const envStates = /* @__PURE__ */ new Map();
241
+ const shared = { fileMarkerKind: /* @__PURE__ */ new Map() };
242
+ function shouldCaptureDiagnosticSourceMap(code, envType, matchers) {
243
+ if (!(code.includes('import') || code.includes('export'))) return false;
244
+ const boundaryToken = envType === 'client' ? '.server' : '.client';
245
+ if (code.includes(boundaryToken)) return true;
246
+ for (const marker of config.markerSpecifiers.serverOnly) if (code.includes(marker)) return true;
247
+ for (const marker of config.markerSpecifiers.clientOnly) if (code.includes(marker)) return true;
248
+ let needsSourceScan = false;
249
+ for (const matcher of matchers.specifiers) {
250
+ if (matcher.literal !== void 0) {
251
+ if (code.includes(matcher.literal)) return true;
252
+ continue;
253
+ }
254
+ needsSourceScan = true;
255
+ }
256
+ for (const matcher of matchers.files)
257
+ if (matcher.pattern instanceof RegExp || !matcher.pattern.includes(boundaryToken)) {
258
+ needsSourceScan = true;
259
+ break;
260
+ }
261
+ return needsSourceScan;
262
+ }
263
+ function captureDiagnosticSourceMap(result, getCombinedSourcemap, reason) {
264
+ if (result.map) return;
265
+ const startedAt = perf ? performance.now() : 0;
266
+ try {
267
+ const map = getCombinedSourcemap();
268
+ if (map) {
269
+ result.map = map;
270
+ perf?.count(`sourcemap.captured.${reason}`);
271
+ }
272
+ } catch {
273
+ perf?.count(`sourcemap.captureFailed.${reason}`);
274
+ } finally {
275
+ if (perf) perf.time('sourcemap.capture', startedAt);
276
+ }
277
+ }
278
+ /**
279
+ * Build the best available source trace for a module and enrich each step
280
+ * with line/column locations. The plugin's own ImportGraph is preferred;
281
+ * Vite's moduleGraph is only a dev fallback for warm starts where Vite may
282
+ * skip resolveId for cached modules.
283
+ *
284
+ * Shared by {@link buildViolationInfo} and {@link processPendingViolations}.
285
+ */
286
+ async function rebuildAndAnnotateTrace(
287
+ provider,
288
+ env,
289
+ envName,
290
+ normalizedImporter,
291
+ specifier,
292
+ importerLoc,
293
+ traceOverride,
294
+ ) {
295
+ let trace = traceOverride ?? buildTrace(env.graph, normalizedImporter, config.maxTraceDepth);
296
+ if (config.command === 'serve') {
297
+ const mgTrace = buildTraceFromModuleGraph(envName, env, normalizedImporter);
298
+ if (mgTrace && mgTrace.length > trace.length) trace = mgTrace;
299
+ }
300
+ await addTraceImportLocations(
301
+ provider,
302
+ trace,
303
+ env.importLocCache,
304
+ importSpecifierLocationIndex.find,
305
+ );
306
+ if (trace.length > 0) {
307
+ const last = trace[trace.length - 1];
308
+ if (!last.specifier) last.specifier = specifier;
309
+ if (importerLoc && last.line == null) {
310
+ last.line = importerLoc.line;
311
+ last.column = importerLoc.column;
312
+ }
313
+ }
314
+ return trace;
315
+ }
316
+ /**
317
+ * Build a lightweight {@link ViolationInfo} record.
318
+ *
319
+ * Diagnostic-only work (trace, source-map lookup, snippets, AST usage
320
+ * analysis) is intentionally deferred until the violation is about to be
321
+ * reported.
322
+ */
323
+ function buildViolationInfo(
324
+ envName,
325
+ envType,
326
+ normalizedImporter,
327
+ source,
328
+ overrides,
329
+ traceOverride,
330
+ ) {
331
+ perf?.count('violations.detected');
332
+ return {
333
+ env: envName,
334
+ envType,
335
+ behavior: config.effectiveBehavior,
336
+ specifier: source,
337
+ importer: normalizedImporter,
338
+ trace: traceOverride ?? [],
339
+ ...overrides,
340
+ };
341
+ }
342
+ async function enrichViolationInfo(
343
+ provider,
344
+ env,
345
+ envName,
346
+ envType,
347
+ importer,
348
+ info,
349
+ traceOverride,
350
+ ) {
351
+ const startedAt = perf ? performance.now() : 0;
352
+ perf?.count('violations.enriched');
353
+ const resolved = info.resolved;
354
+ const sourceCandidates = buildSourceCandidates(info.specifier, resolved, config.root);
355
+ addImporterRelativeSourceCandidates(sourceCandidates, importer, resolved);
356
+ if (!info.importerLoc) {
357
+ const loc = await resolveImporterLocation(provider, env, envType, importer, sourceCandidates);
358
+ if (loc) {
359
+ info.importerLoc = loc;
360
+ info.snippet = buildCodeSnippet(provider, importer, loc, void 0, config.root);
361
+ }
362
+ } else if (!info.snippet)
363
+ info.snippet = buildCodeSnippet(provider, importer, info.importerLoc, void 0, config.root);
364
+ if (traceOverride || info.trace.length === 0)
365
+ info.trace = await rebuildAndAnnotateTrace(
366
+ provider,
367
+ env,
368
+ envName,
369
+ info.importer,
370
+ info.specifier,
371
+ info.importerLoc,
372
+ traceOverride,
373
+ );
374
+ if (perf) perf.time('violation.enrich', startedAt);
375
+ }
376
+ async function resolveImporterLocation(provider, env, envType, importer, sourceCandidates) {
377
+ for (const candidate of sourceCandidates) {
378
+ const loc =
379
+ (await findPostCompileUsageLocation(provider, importer, candidate)) ||
380
+ findOriginalUsageLocation(provider, importer, candidate, envType, config.root) ||
381
+ (await findImportStatementLocationFromTransformed(
382
+ provider,
383
+ importer,
384
+ candidate,
385
+ env.importLocCache,
386
+ importSpecifierLocationIndex.find,
387
+ ));
388
+ if (loc) return loc;
389
+ }
390
+ }
391
+ function addImporterRelativeSourceCandidates(candidates, importer, resolved) {
392
+ if (!resolved) return;
393
+ const importerFile = normalizeFilePath(importer);
394
+ const resolvedFile = normalizeFilePath(resolved);
395
+ const relativeSource = normalizePath(relative(dirname(importerFile), resolvedFile));
396
+ if (!relativeSource) return;
397
+ const importSource = relativeSource.startsWith('.') ? relativeSource : `./${relativeSource}`;
398
+ for (const candidate of buildSourceCandidates(importSource, void 0, config.root))
399
+ candidates.add(candidate);
400
+ }
401
+ /**
402
+ * Check if a resolved import violates marker restrictions (e.g. importing
403
+ * a server-only module in the client env). If so, build and return the
404
+ * {@link ViolationInfo} — the caller is responsible for reporting/deferring.
405
+ *
406
+ * Returns `undefined` when the resolved import has no marker conflict.
407
+ */
408
+ function buildMarkerViolationFromResolvedImport(
409
+ envName,
410
+ envType,
411
+ importer,
412
+ source,
413
+ resolvedId,
414
+ traceOverride,
415
+ ) {
416
+ const normalizedResolvedId = normalizeFilePath(resolvedId);
417
+ const markerKind = shared.fileMarkerKind.get(normalizedResolvedId);
418
+ if (
419
+ !(
420
+ (envType === 'client' && markerKind === 'server') ||
421
+ (envType === 'server' && markerKind === 'client')
422
+ )
423
+ )
424
+ return void 0;
425
+ return buildViolationInfo(
426
+ envName,
427
+ envType,
428
+ normalizeFilePath(importer),
429
+ source,
430
+ {
431
+ type: 'marker',
432
+ resolved: normalizedResolvedId,
433
+ },
434
+ traceOverride,
435
+ );
436
+ }
437
+ function buildFileViolationInfo(
438
+ envName,
439
+ envType,
440
+ normalizedImporter,
441
+ source,
442
+ resolvedPath,
443
+ pattern,
444
+ traceOverride,
445
+ ) {
446
+ return buildViolationInfo(
447
+ envName,
448
+ envType,
449
+ normalizedImporter,
450
+ source,
451
+ {
452
+ type: 'file',
453
+ pattern,
454
+ resolved: resolvedPath,
455
+ },
456
+ traceOverride,
457
+ );
458
+ }
459
+ function getRulesForEnvironment(envName) {
460
+ return getImportProtectionRulesForEnvironment(config, envName);
461
+ }
462
+ const environmentNames = new Set([VITE_ENVIRONMENT_NAMES.client, VITE_ENVIRONMENT_NAMES.server]);
463
+ if (opts.providerEnvName !== VITE_ENVIRONMENT_NAMES.server)
464
+ environmentNames.add(opts.providerEnvName);
465
+ /** Get (or lazily create) the per-env state for the given environment name. */
466
+ function getEnv(envName) {
467
+ let envState = envStates.get(envName);
468
+ if (!envState) {
469
+ const transformResultCache = /* @__PURE__ */ new Map();
470
+ envState = {
471
+ graph: new ImportGraph(),
472
+ mockExportsByImporter: /* @__PURE__ */ new Map(),
473
+ resolveCache: /* @__PURE__ */ new Map(),
474
+ resolveCacheByFile: /* @__PURE__ */ new Map(),
475
+ importLocCache: new ImportLocCache(),
476
+ seenViolations: /* @__PURE__ */ new Set(),
477
+ transformResultCache,
478
+ transformResultKeysByFile: /* @__PURE__ */ new Map(),
479
+ transformResultProvider: {
480
+ getTransformResult(id) {
481
+ const fullKey = normalizePath(id);
482
+ const exact = transformResultCache.get(fullKey);
483
+ if (exact) return exact;
484
+ const strippedKey = normalizeFilePath(id);
485
+ return strippedKey !== fullKey ? transformResultCache.get(strippedKey) : void 0;
486
+ },
487
+ },
488
+ postTransformImports: /* @__PURE__ */ new Map(),
489
+ serverFnLookupModules: /* @__PURE__ */ new Set(),
490
+ pendingViolations: /* @__PURE__ */ new Map(),
491
+ deferredBuildViolations: [],
492
+ };
493
+ envStates.set(envName, envState);
494
+ }
495
+ return envState;
496
+ }
497
+ /**
498
+ * Search a parsed export-names map for an entry matching any of the
499
+ * specifier candidates. Returns matching names or empty array.
500
+ */
501
+ function findExportsInMap(exportMap, candidates) {
502
+ for (const candidate of candidates) {
503
+ const hit = exportMap.get(candidate);
504
+ if (hit && hit.length > 0) return hit;
505
+ }
506
+ return [];
507
+ }
508
+ /**
509
+ * Build deduped resolution candidates for a module ID, including the
510
+ * extensionless absolute path when the ID looks like a file path.
511
+ */
512
+ function buildIdCandidates(id, extra) {
513
+ const set = new Set(buildResolutionCandidates(id));
514
+ if (extra) {
515
+ for (const c of buildResolutionCandidates(extra)) set.add(c);
516
+ set.add(resolveExtensionlessAbsoluteId(extra));
517
+ }
518
+ return Array.from(set);
519
+ }
520
+ /**
521
+ * Resolve which named exports the importer needs from a denied specifier,
522
+ * so mock-edge modules can provide explicit ESM named exports.
523
+ *
524
+ * Tries multiple strategies: cached export maps, AST parsing, and
525
+ * resolver-based comparison.
526
+ */
527
+ async function resolveExportsForDeniedSpecifier(env, ctx, info, importerIdHint) {
528
+ const importerFile = normalizeFilePath(info.importer);
529
+ const specifierCandidates = buildIdCandidates(info.specifier, info.resolved);
530
+ let parsedBySource = env.mockExportsByImporter.get(importerFile);
531
+ if (!parsedBySource) {
532
+ const importerCode =
533
+ env.transformResultProvider.getTransformResult(importerFile)?.code ??
534
+ (importerIdHint && ctx.getModuleInfo
535
+ ? (ctx.getModuleInfo(importerIdHint)?.code ?? void 0)
536
+ : void 0);
537
+ if (typeof importerCode !== 'string' || importerCode.length === 0) return [];
538
+ try {
539
+ parsedBySource = getMockExportNamesBySource(importerCode, importerFile, perf);
540
+ await recordMockExportsForImporter(env, importerFile, parsedBySource, async (src) => {
541
+ const cacheKey = `${importerFile}:${src}`;
542
+ if (env.resolveCache.has(cacheKey)) return env.resolveCache.get(cacheKey) ?? void 0;
543
+ if (!ctx.resolve) return void 0;
544
+ const resolved = await ctx.resolve(src, info.importer, { skipSelf: true });
545
+ if (!resolved || resolved.external) return void 0;
546
+ return resolved.id;
547
+ });
548
+ parsedBySource = env.mockExportsByImporter.get(importerFile) ?? parsedBySource;
549
+ } catch {
550
+ return [];
551
+ }
552
+ }
553
+ const direct = findExportsInMap(parsedBySource, specifierCandidates);
554
+ if (direct.length > 0) return direct;
555
+ const candidateSet = new Set(specifierCandidates);
556
+ for (const [sourceKey, names] of parsedBySource) {
557
+ if (!names.length) continue;
558
+ const resolvedId = await resolveSourceKey(env, ctx, importerFile, sourceKey, info.importer);
559
+ if (!resolvedId) continue;
560
+ const resolvedCandidates = buildIdCandidates(resolvedId);
561
+ resolvedCandidates.push(resolveExtensionlessAbsoluteId(resolvedId));
562
+ if (resolvedCandidates.some((v) => candidateSet.has(v))) return names;
563
+ }
564
+ return [];
565
+ }
566
+ /** Best-effort resolve a source key using the cache or ctx.resolve. */
567
+ async function resolveSourceKey(env, ctx, importerFile, sourceKey, importerId) {
568
+ const cacheKey = `${importerFile}:${sourceKey}`;
569
+ if (env.resolveCache.has(cacheKey)) return env.resolveCache.get(cacheKey) ?? void 0;
570
+ if (!ctx.resolve) return void 0;
571
+ try {
572
+ const resolved = await ctx.resolve(sourceKey, importerId, { skipSelf: true });
573
+ if (!resolved || resolved.external) return void 0;
574
+ return resolved.id;
575
+ } catch {
576
+ return;
577
+ }
578
+ }
579
+ async function recordMockExportsForImporter(env, importerId, namesBySource, resolveSource) {
580
+ const importerFile = normalizeFilePath(importerId);
581
+ if (namesBySource.size === 0) return;
582
+ const resolvedAliases = /* @__PURE__ */ new Map();
583
+ for (const [source, names] of namesBySource)
584
+ try {
585
+ const resolvedId = await resolveSource(source);
586
+ if (!resolvedId) continue;
587
+ resolvedAliases.set(normalizeFilePath(resolvedId), names);
588
+ resolvedAliases.set(resolveExtensionlessAbsoluteId(resolvedId), names);
589
+ } catch {}
590
+ for (const [source, names] of resolvedAliases) namesBySource.set(source, names);
591
+ const existing = env.mockExportsByImporter.get(importerFile);
592
+ if (!existing) {
593
+ env.mockExportsByImporter.set(importerFile, namesBySource);
594
+ return;
595
+ }
596
+ for (const [source, names] of namesBySource) {
597
+ const prev = existing.get(source);
598
+ if (!prev) {
599
+ existing.set(source, names);
600
+ continue;
601
+ }
602
+ const union = new Set([...prev, ...names]);
603
+ existing.set(source, Array.from(union).sort());
604
+ }
605
+ }
606
+ const shouldCheckImporterCache = /* @__PURE__ */ new Map();
607
+ function shouldCheckImporter(importer) {
608
+ return shouldCheckImportProtectionImporter(config, importer, shouldCheckImporterCache);
609
+ }
610
+ function dedupeKey(info) {
611
+ return dedupeViolationKey(info);
612
+ }
613
+ function hasSeen(env, key) {
614
+ if (config.logMode === 'always') return false;
615
+ if (env.seenViolations.has(key)) return true;
616
+ env.seenViolations.add(key);
617
+ return false;
618
+ }
619
+ function getRelativePath(absolutePath) {
620
+ return getImportProtectionRelativePath(config.root, absolutePath);
621
+ }
622
+ /** Reset all caches on an EnvState (called from buildStart). */
623
+ function clearEnvState(envState) {
624
+ envState.resolveCache.clear();
625
+ envState.resolveCacheByFile.clear();
626
+ envState.importLocCache.clear();
627
+ envState.seenViolations.clear();
628
+ envState.transformResultCache.clear();
629
+ envState.transformResultKeysByFile.clear();
630
+ envState.postTransformImports.clear();
631
+ envState.serverFnLookupModules.clear();
632
+ envState.pendingViolations.clear();
633
+ envState.deferredBuildViolations.length = 0;
634
+ envState.graph.clear();
635
+ envState.mockExportsByImporter.clear();
636
+ }
637
+ /** Invalidate all env-level caches that reference a specific file. */
638
+ function invalidateFileFromEnv(envState, file) {
639
+ envState.importLocCache.deleteByFile(file);
640
+ const resolveKeys = envState.resolveCacheByFile.get(file);
641
+ if (resolveKeys) {
642
+ for (const key of resolveKeys) envState.resolveCache.delete(key);
643
+ envState.resolveCacheByFile.delete(file);
644
+ }
645
+ envState.graph.invalidate(file);
646
+ envState.mockExportsByImporter.delete(file);
647
+ envState.serverFnLookupModules.delete(file);
648
+ envState.pendingViolations.delete(file);
649
+ const transformKeys = envState.transformResultKeysByFile.get(file);
650
+ if (transformKeys) {
651
+ for (const key of transformKeys) {
652
+ envState.transformResultCache.delete(key);
653
+ envState.postTransformImports.delete(key);
654
+ }
655
+ envState.transformResultKeysByFile.delete(file);
656
+ } else {
657
+ envState.transformResultCache.delete(file);
658
+ envState.postTransformImports.delete(file);
659
+ }
660
+ }
661
+ /** Store a transform result under both the cacheKey and physical file path. */
662
+ function cacheTransformResult(envState, file, cacheKey, result) {
663
+ envState.transformResultCache.set(cacheKey, result);
664
+ const keySet = getOrCreate(
665
+ envState.transformResultKeysByFile,
666
+ file,
667
+ () => /* @__PURE__ */ new Set(),
668
+ );
669
+ keySet.add(cacheKey);
670
+ if (cacheKey !== file) {
671
+ envState.transformResultCache.set(file, result);
672
+ keySet.add(file);
673
+ }
674
+ }
675
+ /** Register known Start entrypoints as trace roots for all environments. */
676
+ function registerEntries() {
677
+ const { resolvedStartConfig } = opts.getConfig();
678
+ for (const envDef of opts.environments) {
679
+ const envState = getEnv(envDef.name);
680
+ if (resolvedStartConfig.routerFilePath)
681
+ envState.graph.addEntry(normalizePath(resolvedStartConfig.routerFilePath));
682
+ if (resolvedStartConfig.startFilePath)
683
+ envState.graph.addEntry(normalizePath(resolvedStartConfig.startFilePath));
684
+ }
685
+ }
686
+ /**
687
+ * Get the merged set of post-transform imports for a file, checking all
688
+ * code-split variants. Returns `null` if no post-transform data exists
689
+ * yet (transform hasn't run).
690
+ *
691
+ * Skips `SERVER_FN_LOOKUP` variants because they contain untransformed
692
+ * code — the Start compiler excludes them.
693
+ */
694
+ function getPostTransformImports(env, file) {
695
+ const keySet = env.transformResultKeysByFile.get(file);
696
+ let merged = null;
697
+ if (keySet)
698
+ for (const k of keySet) {
699
+ if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue;
700
+ const imports = env.postTransformImports.get(k);
701
+ if (imports)
702
+ if (!merged) merged = new Set(imports);
703
+ else for (const v of imports) merged.add(v);
704
+ }
705
+ if (!merged) {
706
+ const imports = env.postTransformImports.get(file);
707
+ if (imports) merged = new Set(imports);
708
+ }
709
+ return merged;
710
+ }
711
+ /**
712
+ * Check whether an import edge from `parent` to `target` survived
713
+ * post-transform compilation.
714
+ *
715
+ * Returns:
716
+ * - `'live'` — target appears in a non-lookup variant's post-transform imports
717
+ * - `'dead'` — post-transform data exists but target is absent (compiler stripped it)
718
+ * - `'pending'` — transform ran but import data not yet posted
719
+ * - `'no-data'` — transform never ran (warm-start cached module)
720
+ */
721
+ function checkEdgeLiveness(env, parent, target) {
722
+ const keySet = env.transformResultKeysByFile.get(parent);
723
+ let anyVariantCached = false;
724
+ if (keySet)
725
+ for (const k of keySet) {
726
+ if (k.includes(SERVER_FN_LOOKUP_QUERY)) continue;
727
+ const imports = env.postTransformImports.get(k);
728
+ if (imports) {
729
+ anyVariantCached = true;
730
+ if (imports.has(target)) return 'live';
731
+ }
732
+ }
733
+ if (!anyVariantCached) {
734
+ const imports = env.postTransformImports.get(parent);
735
+ if (imports) return imports.has(target) ? 'live' : 'dead';
736
+ return env.transformResultCache.has(parent) || (keySet ? keySet.size > 0 : false)
737
+ ? 'pending'
738
+ : 'no-data';
739
+ }
740
+ return 'dead';
741
+ }
742
+ function checkPostTransformReachability(env, file) {
743
+ const visited = /* @__PURE__ */ new Set();
744
+ const queue = [file];
745
+ let hasUnknownEdge = false;
746
+ let qi = 0;
747
+ while (qi < queue.length) {
748
+ const current = queue[qi++];
749
+ if (visited.has(current)) continue;
750
+ visited.add(current);
751
+ if (env.graph.entries.has(current)) return 'reachable';
752
+ const importers = env.graph.reverseEdges.get(current);
753
+ if (!importers) continue;
754
+ for (const [parent] of importers) {
755
+ if (visited.has(parent)) continue;
756
+ const liveness = checkEdgeLiveness(env, parent, current);
757
+ if (liveness === 'live' || liveness === 'no-data') queue.push(parent);
758
+ else if (liveness === 'pending') hasUnknownEdge = true;
759
+ }
760
+ }
761
+ return hasUnknownEdge ? 'unknown' : 'unreachable';
762
+ }
763
+ function checkSourceGraphReachability(env, file) {
764
+ const visited = /* @__PURE__ */ new Set();
765
+ const queue = [file];
766
+ let qi = 0;
767
+ while (qi < queue.length) {
768
+ const current = queue[qi++];
769
+ if (visited.has(current)) continue;
770
+ visited.add(current);
771
+ if (env.graph.entries.has(current)) return 'reachable';
772
+ const importers = env.graph.reverseEdges.get(current);
773
+ if (!importers) continue;
774
+ if (importers.size === 0) {
775
+ const routesDirectory = normalizePath(`${config.srcDirectory}/routes`);
776
+ if (current === file || isInsideDirectory(current, routesDirectory)) return 'reachable';
777
+ continue;
778
+ }
779
+ for (const [parent] of importers) if (!visited.has(parent)) queue.push(parent);
780
+ }
781
+ return 'unreachable';
782
+ }
783
+ /**
784
+ * Filter pending violations using edge-survival data. Returns the subset
785
+ * of violations whose resolved import survived the Start compiler (or all
786
+ * violations when no post-transform data is available yet).
787
+ *
788
+ * Returns `undefined` when all violations were stripped or when we must wait
789
+ * for post-transform data before proceeding.
790
+ */
791
+ function filterEdgeSurvival(env, file, violations) {
792
+ const postTransform = getPostTransformImports(env, file);
793
+ if (postTransform) {
794
+ const surviving = violations.filter(
795
+ (pv) => !pv.info.resolved || postTransform.has(pv.info.resolved),
796
+ );
797
+ if (surviving.length === 0) return 'all-stripped';
798
+ env.pendingViolations.set(file, surviving);
799
+ return {
800
+ active: surviving,
801
+ edgeSurvivalApplied: true,
802
+ };
803
+ }
804
+ if (violations.some((pv) => pv.fromPreTransformResolve)) return 'await-transform';
805
+ return {
806
+ active: violations,
807
+ edgeSurvivalApplied: false,
808
+ };
809
+ }
810
+ /**
811
+ * Process pending violations for the given environment. Called from the
812
+ * transform-cache hook after each module transform is cached, because new
813
+ * transform data may allow us to confirm or discard pending violations.
814
+ *
815
+ * @param warnFn - `this.warn` from the transform hook context
816
+ */
817
+ async function processPendingViolations(env, warnFn) {
818
+ if (env.pendingViolations.size === 0) return;
819
+ const toDelete = [];
820
+ for (const [file, violations] of env.pendingViolations) {
821
+ const filtered = filterEdgeSurvival(env, file, violations);
822
+ if (filtered === 'all-stripped') {
823
+ toDelete.push(file);
824
+ continue;
825
+ }
826
+ if (filtered === 'await-transform') continue;
827
+ const { active, edgeSurvivalApplied } = filtered;
828
+ const isBundledClientDev =
829
+ config.command === 'serve' &&
830
+ config.bundledDev &&
831
+ active.some((pv) => pv.info.envType === 'client');
832
+ let status;
833
+ if (isBundledClientDev && edgeSurvivalApplied)
834
+ status = checkSourceGraphReachability(env, file);
835
+ else if (env.graph.entries.size > 0) status = checkPostTransformReachability(env, file);
836
+ else status = 'unknown';
837
+ if (status === 'reachable') {
838
+ for (const pv of active) await emitPendingViolation(env, warnFn, pv);
839
+ toDelete.push(file);
840
+ } else if (status === 'unreachable') {
841
+ if (isBundledClientDev) continue;
842
+ toDelete.push(file);
843
+ } else if (config.command === 'serve') {
844
+ let emittedAny = false;
845
+ for (const pv of active) {
846
+ if (pv.fromPreTransformResolve) continue;
847
+ if (
848
+ edgeSurvivalApplied ||
849
+ (pv.info.type === 'file' &&
850
+ !!pv.info.resolved &&
851
+ isInsideDirectory(pv.info.resolved, config.srcDirectory))
852
+ )
853
+ emittedAny = (await emitPendingViolation(env, warnFn, pv)) || emittedAny;
854
+ }
855
+ if (emittedAny) toDelete.push(file);
856
+ }
857
+ }
858
+ for (const file of toDelete) env.pendingViolations.delete(file);
859
+ }
860
+ async function emitPendingViolation(env, warnFn, pv) {
861
+ if (hasSeen(env, dedupeKey(pv.info))) return false;
862
+ await enrichViolationInfo(
863
+ env.transformResultProvider,
864
+ env,
865
+ pv.info.env,
866
+ pv.info.envType,
867
+ pv.info.importer,
868
+ pv.info,
869
+ );
870
+ if (config.onViolation) {
871
+ if ((await config.onViolation(pv.info)) === false) return false;
872
+ }
873
+ warnFn(formatViolation(pv.info, config.root));
874
+ return true;
875
+ }
876
+ /**
877
+ * Record a violation as pending for later confirmation via graph
878
+ * reachability. Called from `resolveId` when `shouldDefer` is true.
879
+ */
880
+ function deferViolation(env, importerFile, info, isPreTransformResolve) {
881
+ getOrCreate(env.pendingViolations, importerFile, () => []).push({
882
+ info,
883
+ fromPreTransformResolve: isPreTransformResolve,
884
+ });
885
+ }
886
+ /** Counter for generating unique per-violation mock module IDs in build mode. */
887
+ let buildViolationCounter = 0;
888
+ async function handleViolation(ctx, env, info, importerIdHint, violationOpts) {
889
+ if (!violationOpts?.silent) {
890
+ await enrichViolationInfo(
891
+ env.transformResultProvider,
892
+ env,
893
+ info.env,
894
+ info.envType,
895
+ importerIdHint ?? info.importer,
896
+ info,
897
+ );
898
+ if (config.onViolation) {
899
+ if ((await config.onViolation(info)) === false) return void 0;
900
+ }
901
+ if (config.effectiveBehavior === 'error')
902
+ return ctx.error(formatViolation(info, config.root));
903
+ if (!hasSeen(env, dedupeKey(info))) ctx.warn(formatViolation(info, config.root));
904
+ } else if (config.effectiveBehavior === 'error' && config.command !== 'build') return;
905
+ if (info.type === 'file') return info.resolved;
906
+ return resolveViteId(
907
+ makeMockEdgeModuleId(
908
+ await resolveExportsForDeniedSpecifier(env, ctx, info, importerIdHint),
909
+ config.command === 'serve'
910
+ ? mockRuntimeModuleIdFromViolation(info, config.mockAccess, config.root)
911
+ : `${MOCK_BUILD_PREFIX}${buildViolationCounter++}`,
912
+ ),
913
+ );
914
+ }
915
+ /**
916
+ * Unified violation dispatch: either defers or reports immediately.
917
+ *
918
+ * When `shouldDefer` is true (dev mock + build modes), calls
919
+ * `handleViolation` silently to obtain the mock module ID, then stores
920
+ * the violation for later verification:
921
+ * - Dev mock mode: all violations are deferred to `pendingViolations`
922
+ * for edge-survival and graph-reachability checking via
923
+ * `processPendingViolations`.
924
+ * - Build mode (mock + error): defers to `deferredBuildViolations` for
925
+ * tree-shaking verification in `generateBundle`.
926
+ *
927
+ * Otherwise reports immediately (dev error mode). Pre-transform
928
+ * resolves are silenced in error mode because they fire before the
929
+ * compiler runs and there is no deferred verification path.
930
+ *
931
+ * Returns the mock module ID / resolve result from `handleViolation`.
932
+ */
933
+ async function reportOrDeferViolation(
934
+ ctx,
935
+ env,
936
+ importerFile,
937
+ importerIdHint,
938
+ info,
939
+ shouldDefer,
940
+ isPreTransformResolve,
941
+ ) {
942
+ if (shouldDefer) {
943
+ const result = await handleViolation(ctx, env, info, importerIdHint, { silent: true });
944
+ if (config.command === 'build') {
945
+ const mockId = result ?? '';
946
+ env.deferredBuildViolations.push({
947
+ info,
948
+ mockModuleId: mockId,
949
+ checkModuleId: info.type === 'marker' ? info.importer : void 0,
950
+ });
951
+ } else {
952
+ deferViolation(env, importerFile, info, isPreTransformResolve);
953
+ await processPendingViolations(env, ctx.warn.bind(ctx));
954
+ }
955
+ return result;
956
+ }
957
+ return handleViolation(ctx, env, info, importerIdHint, { silent: isPreTransformResolve });
958
+ }
959
+ return [
960
+ {
961
+ name: 'tanstack-start-core:import-protection',
962
+ enforce: 'pre',
963
+ applyToEnvironment(env) {
964
+ if (!config.enabled) return false;
965
+ return environmentNames.has(env.name);
966
+ },
967
+ configResolved(viteConfig) {
968
+ config.root = viteConfig.root;
969
+ config.command = viteConfig.command;
970
+ config.bundledDev = !!viteConfig.experimental.bundledDev;
971
+ const { startConfig, resolvedStartConfig } = opts.getConfig();
972
+ config.srcDirectory = resolvedStartConfig.srcDirectory;
973
+ const userOpts = startConfig.importProtection;
974
+ if (userOpts?.enabled === false) {
975
+ config.enabled = false;
976
+ return;
977
+ }
978
+ config.enabled = true;
979
+ const behavior = userOpts?.behavior;
980
+ if (typeof behavior === 'string') config.effectiveBehavior = behavior;
981
+ else
982
+ config.effectiveBehavior =
983
+ viteConfig.command === 'serve'
984
+ ? (behavior?.dev ?? 'mock')
985
+ : (behavior?.build ?? 'error');
986
+ config.logMode = userOpts?.log ?? 'once';
987
+ config.mockAccess = userOpts?.mockAccess ?? 'error';
988
+ config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20;
989
+ if (userOpts?.onViolation) {
990
+ const fn = userOpts.onViolation;
991
+ config.onViolation = (info) => fn(info);
992
+ }
993
+ const defaults = getDefaultImportProtectionRules();
994
+ const pick = (user, fallback) => (user ? [...user] : [...fallback]);
995
+ const clientSpecifiers = dedupePatterns([
996
+ ...defaults.client.specifiers,
997
+ ...(userOpts?.client?.specifiers ?? []),
998
+ ]);
999
+ config.compiledRules.client = {
1000
+ specifiers: compileMatchers(clientSpecifiers),
1001
+ files: compileMatchers(pick(userOpts?.client?.files, defaults.client.files)),
1002
+ excludeFiles: compileMatchers(
1003
+ pick(userOpts?.client?.excludeFiles, defaults.client.excludeFiles),
1004
+ ),
1005
+ };
1006
+ config.compiledRules.server = {
1007
+ specifiers: compileMatchers(
1008
+ dedupePatterns(pick(userOpts?.server?.specifiers, defaults.server.specifiers)),
1009
+ ),
1010
+ files: compileMatchers(pick(userOpts?.server?.files, defaults.server.files)),
1011
+ excludeFiles: compileMatchers(
1012
+ pick(userOpts?.server?.excludeFiles, defaults.server.excludeFiles),
1013
+ ),
1014
+ };
1015
+ config.includeMatchers = compileMatchers(userOpts?.include ?? []);
1016
+ config.excludeMatchers = compileMatchers(userOpts?.exclude ?? []);
1017
+ config.ignoreImporterMatchers = compileMatchers(userOpts?.ignoreImporters ?? []);
1018
+ const markers = getMarkerSpecifiers();
1019
+ config.markerSpecifiers = {
1020
+ serverOnly: new Set(markers.serverOnly),
1021
+ clientOnly: new Set(markers.clientOnly),
1022
+ };
1023
+ },
1024
+ configureServer(server) {
1025
+ devServer = server;
1026
+ },
1027
+ buildStart() {
1028
+ if (!config.enabled) return;
1029
+ clearNormalizeFilePathCache();
1030
+ extensionlessIdResolver.clear();
1031
+ shouldCheckImporterCache.clear();
1032
+ for (const envState of envStates.values()) clearEnvState(envState);
1033
+ shared.fileMarkerKind.clear();
1034
+ registerEntries();
1035
+ },
1036
+ hotUpdate(ctx) {
1037
+ if (!config.enabled) return;
1038
+ for (const mod of ctx.modules)
1039
+ if (mod.id) {
1040
+ const id = mod.id;
1041
+ const importerFile = normalizeFilePath(id);
1042
+ extensionlessIdResolver.invalidateByFile(importerFile);
1043
+ shared.fileMarkerKind.delete(importerFile);
1044
+ for (const envState of envStates.values())
1045
+ invalidateFileFromEnv(envState, importerFile);
1046
+ }
1047
+ },
1048
+ resolveId: {
1049
+ filter: {
1050
+ id: {
1051
+ exclude: [
1052
+ /^\0(?!tanstack-start-import-protection:)/,
1053
+ /^virtual:(?!tanstack-start-import-protection:)/,
1054
+ ],
1055
+ },
1056
+ },
1057
+ async handler(source, importer, _options) {
1058
+ perf?.count('resolveId.calls');
1059
+ const envName = this.environment.name;
1060
+ const env = getEnv(envName);
1061
+ const envType = getImportProtectionEnvType(config, envName);
1062
+ const isScanResolve = !!_options.scan;
1063
+ if (IMPORT_PROTECTION_DEBUG) {
1064
+ const importerPath = importer ? normalizeFilePath(importer) : '(entry)';
1065
+ const isEntryResolve = !importer;
1066
+ if (
1067
+ process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER === 'entry'
1068
+ ? isEntryResolve
1069
+ : matchesDebugFilter(source, importerPath)
1070
+ )
1071
+ debugLog('resolveId', {
1072
+ env: envName,
1073
+ envType,
1074
+ source,
1075
+ importer: importerPath,
1076
+ isEntryResolve,
1077
+ command: config.command,
1078
+ });
1079
+ }
1080
+ const internalVirtualId = resolveInternalVirtualModuleId(source);
1081
+ if (internalVirtualId) return internalVirtualId;
1082
+ if (!importer) {
1083
+ const normalizedSource = normalizeFilePath(source);
1084
+ if (
1085
+ !(
1086
+ config.command === 'serve' &&
1087
+ config.bundledDev &&
1088
+ envType === 'client' &&
1089
+ isInsideDirectory(normalizedSource, config.srcDirectory)
1090
+ )
1091
+ )
1092
+ env.graph.addEntry(source);
1093
+ await processPendingViolations(env, this.warn.bind(this));
1094
+ return;
1095
+ }
1096
+ if (source.startsWith('\0') || source.startsWith('virtual:')) return;
1097
+ const normalizedImporter = normalizeFilePath(importer);
1098
+ const isDirectLookup = importer.includes(SERVER_FN_LOOKUP_QUERY);
1099
+ if (config.command === 'serve' && config.bundledDev && envType === 'client') {
1100
+ if (
1101
+ isInsideDirectory(normalizedImporter, normalizePath(`${config.srcDirectory}/routes`))
1102
+ )
1103
+ env.graph.addEntry(normalizedImporter);
1104
+ }
1105
+ if (isDirectLookup) env.serverFnLookupModules.add(normalizedImporter);
1106
+ const isServerFnPreTransformResolve =
1107
+ isDirectLookup || env.serverFnLookupModules.has(normalizedImporter);
1108
+ const isPreTransformResolve = isServerFnPreTransformResolve || isScanResolve;
1109
+ const shouldRecordGraphEdge = !isServerFnPreTransformResolve;
1110
+ const isDevMock = config.command === 'serve' && config.effectiveBehavior === 'mock';
1111
+ const isBuild = config.command === 'build';
1112
+ const shouldDefer = shouldDeferViolation({
1113
+ isBuild,
1114
+ isDevMock,
1115
+ });
1116
+ const resolveAgainstImporter = async () => {
1117
+ const startedAt = perf ? performance.now() : 0;
1118
+ perf?.count('thisResolve.calls');
1119
+ let primary = null;
1120
+ try {
1121
+ const resolveOptions = {
1122
+ custom: _options.custom,
1123
+ isEntry: _options.isEntry,
1124
+ skipSelf: true,
1125
+ };
1126
+ if ('attributes' in _options) {
1127
+ const resolveOptionsWithAttributes = resolveOptions;
1128
+ resolveOptionsWithAttributes.attributes = _options.attributes;
1129
+ }
1130
+ primary = await this.resolve(source, importer, resolveOptions);
1131
+ } finally {
1132
+ if (perf) perf.time('thisResolve', startedAt);
1133
+ }
1134
+ if (primary)
1135
+ return {
1136
+ id: canonicalizeResolvedId(primary.id, config.root, resolveExtensionlessAbsoluteId),
1137
+ result: primary,
1138
+ };
1139
+ return null;
1140
+ };
1141
+ const markerKind = config.markerSpecifiers.serverOnly.has(source)
1142
+ ? 'server'
1143
+ : config.markerSpecifiers.clientOnly.has(source)
1144
+ ? 'client'
1145
+ : void 0;
1146
+ if (markerKind) {
1147
+ const existing = shared.fileMarkerKind.get(normalizedImporter);
1148
+ if (existing && existing !== markerKind)
1149
+ this.error(
1150
+ `[import-protection] File "${getRelativePath(normalizedImporter)}" has both server-only and client-only markers. This is not allowed.`,
1151
+ );
1152
+ shared.fileMarkerKind.set(normalizedImporter, markerKind);
1153
+ const violatesEnv =
1154
+ (envType === 'client' && markerKind === 'server') ||
1155
+ (envType === 'server' && markerKind === 'client');
1156
+ if (violatesEnv) {
1157
+ const info = buildViolationInfo(envName, envType, normalizedImporter, source, {
1158
+ type: 'marker',
1159
+ });
1160
+ const markerResult = await reportOrDeferViolation(
1161
+ this,
1162
+ env,
1163
+ normalizedImporter,
1164
+ importer,
1165
+ info,
1166
+ shouldDefer,
1167
+ isPreTransformResolve,
1168
+ );
1169
+ if (isBuild && markerResult != null) return markerResult;
1170
+ }
1171
+ const envRetroKey = `retro-marker:${normalizedImporter}`;
1172
+ if (violatesEnv && !env.seenViolations.has(envRetroKey)) {
1173
+ env.seenViolations.add(envRetroKey);
1174
+ let retroDeferred = false;
1175
+ const importersMap = env.graph.reverseEdges.get(normalizedImporter);
1176
+ if (importersMap && importersMap.size > 0)
1177
+ for (const [importerFile, specifier] of importersMap) {
1178
+ if (!specifier) continue;
1179
+ if (!shouldCheckImporter(importerFile)) continue;
1180
+ const markerInfo = buildMarkerViolationFromResolvedImport(
1181
+ envName,
1182
+ envType,
1183
+ importerFile,
1184
+ specifier,
1185
+ normalizedImporter,
1186
+ );
1187
+ if (markerInfo) {
1188
+ deferViolation(env, importerFile, markerInfo, isPreTransformResolve);
1189
+ retroDeferred = true;
1190
+ }
1191
+ }
1192
+ if (retroDeferred) await processPendingViolations(env, this.warn.bind(this));
1193
+ }
1194
+ return markerKind === 'server'
1195
+ ? resolvedMarkerVirtualModuleId('server')
1196
+ : resolvedMarkerVirtualModuleId('client');
1197
+ }
1198
+ if (!shouldCheckImporter(normalizedImporter)) return;
1199
+ const matchers = getRulesForEnvironment(envName);
1200
+ const specifierMatch = matchesAny(source, matchers.specifiers);
1201
+ if (specifierMatch) {
1202
+ if (shouldRecordGraphEdge) env.graph.addEdge(source, normalizedImporter, source);
1203
+ const info = buildViolationInfo(envName, envType, normalizedImporter, source, {
1204
+ type: 'specifier',
1205
+ pattern: specifierMatch.pattern,
1206
+ });
1207
+ if (shouldDefer && !info.resolved)
1208
+ try {
1209
+ const resolvedForInfo = await resolveAgainstImporter();
1210
+ if (resolvedForInfo) info.resolved = resolvedForInfo.id;
1211
+ } catch {}
1212
+ return reportOrDeferViolation(
1213
+ this,
1214
+ env,
1215
+ normalizedImporter,
1216
+ importer,
1217
+ info,
1218
+ shouldDefer,
1219
+ isPreTransformResolve,
1220
+ );
1221
+ }
1222
+ const cacheKey = `${normalizedImporter}:${source}`;
1223
+ let resolved;
1224
+ let passThroughResult = null;
1225
+ if (env.resolveCache.has(cacheKey)) resolved = env.resolveCache.get(cacheKey) ?? null;
1226
+ else {
1227
+ const resolution = await resolveAgainstImporter();
1228
+ resolved = resolution?.id ?? null;
1229
+ passThroughResult = resolution?.result ?? null;
1230
+ if (resolved !== null) {
1231
+ env.resolveCache.set(cacheKey, resolved);
1232
+ getOrCreate(
1233
+ env.resolveCacheByFile,
1234
+ normalizedImporter,
1235
+ () => /* @__PURE__ */ new Set(),
1236
+ ).add(cacheKey);
1237
+ }
1238
+ }
1239
+ if (resolved) {
1240
+ const relativePath = getRelativePath(resolved);
1241
+ if (isServerFnPreTransformResolve) env.serverFnLookupModules.add(resolved);
1242
+ if (shouldRecordGraphEdge) env.graph.addEdge(resolved, normalizedImporter, source);
1243
+ if (!isFileExcluded(relativePath, matchers)) {
1244
+ const fileMatch = matchers.files.find((matcher) => matcher.test(relativePath));
1245
+ if (fileMatch) {
1246
+ const info = buildFileViolationInfo(
1247
+ envName,
1248
+ envType,
1249
+ normalizedImporter,
1250
+ source,
1251
+ resolved,
1252
+ fileMatch.pattern,
1253
+ );
1254
+ return reportOrDeferViolation(
1255
+ this,
1256
+ env,
1257
+ normalizedImporter,
1258
+ importer,
1259
+ info,
1260
+ shouldDefer,
1261
+ isPreTransformResolve,
1262
+ );
1263
+ }
1264
+ const markerInfo = buildMarkerViolationFromResolvedImport(
1265
+ envName,
1266
+ envType,
1267
+ importer,
1268
+ source,
1269
+ resolved,
1270
+ );
1271
+ if (markerInfo)
1272
+ return reportOrDeferViolation(
1273
+ this,
1274
+ env,
1275
+ normalizedImporter,
1276
+ importer,
1277
+ markerInfo,
1278
+ shouldDefer,
1279
+ isPreTransformResolve,
1280
+ );
1281
+ }
1282
+ if (passThroughResult) return passThroughResult;
1283
+ }
1284
+ },
1285
+ },
1286
+ load: {
1287
+ filter: { id: new RegExp(getResolvedVirtualModuleMatchers().map(escapeRegExp).join('|')) },
1288
+ handler(id) {
1289
+ if (IMPORT_PROTECTION_DEBUG) {
1290
+ if (matchesDebugFilter(id))
1291
+ debugLog('load:handler', {
1292
+ env: this.environment.name,
1293
+ id: normalizePath(id),
1294
+ });
1295
+ }
1296
+ return loadResolvedVirtualModule(id);
1297
+ },
1298
+ },
1299
+ async generateBundle(_options, bundle) {
1300
+ const envName = this.environment.name;
1301
+ const env = envStates.get(envName);
1302
+ if (!env || env.deferredBuildViolations.length === 0) return;
1303
+ const candidateCache = /* @__PURE__ */ new Map();
1304
+ const toModuleIdCandidates = (id) => {
1305
+ let cached = candidateCache.get(id);
1306
+ if (cached) return cached;
1307
+ const out = /* @__PURE__ */ new Set();
1308
+ const normalized = normalizeFilePath(id);
1309
+ out.add(id);
1310
+ out.add(normalized);
1311
+ out.add(relativizePath(normalized, config.root));
1312
+ if (normalized.startsWith('/@id/__x00__')) {
1313
+ const internal = `\0${normalized.slice(VITE_BROWSER_VIRTUAL_PREFIX.length)}`;
1314
+ out.add(internal);
1315
+ out.add(relativizePath(normalizeFilePath(internal), config.root));
1316
+ }
1317
+ if (normalized.startsWith('\0')) {
1318
+ const browser = `${VITE_BROWSER_VIRTUAL_PREFIX}${normalized.slice(1)}`;
1319
+ out.add(browser);
1320
+ out.add(relativizePath(normalizeFilePath(browser), config.root));
1321
+ }
1322
+ cached = Array.from(out);
1323
+ candidateCache.set(id, cached);
1324
+ return cached;
1325
+ };
1326
+ const survivingModules = /* @__PURE__ */ new Set();
1327
+ for (const chunk of Object.values(bundle))
1328
+ if (chunk.type === 'chunk')
1329
+ for (const moduleId of Object.keys(chunk.modules))
1330
+ for (const candidate of toModuleIdCandidates(moduleId))
1331
+ survivingModules.add(candidate);
1332
+ const didModuleSurvive = (moduleId) =>
1333
+ toModuleIdCandidates(moduleId).some((candidate) => survivingModules.has(candidate));
1334
+ const realViolations = [];
1335
+ for (const { info, mockModuleId, checkModuleId } of env.deferredBuildViolations) {
1336
+ let survived;
1337
+ if (checkModuleId != null) {
1338
+ const importerVariantIds = new Set([info.importer]);
1339
+ const importerKeys = env.transformResultKeysByFile.get(
1340
+ normalizeFilePath(info.importer),
1341
+ );
1342
+ if (importerKeys) for (const key of importerKeys) importerVariantIds.add(key);
1343
+ survived = false;
1344
+ for (const importerId of importerVariantIds)
1345
+ if (didModuleSurvive(importerId)) {
1346
+ survived = true;
1347
+ break;
1348
+ }
1349
+ } else survived = didModuleSurvive(mockModuleId);
1350
+ if (!survived) continue;
1351
+ await enrichViolationInfo(
1352
+ env.transformResultProvider,
1353
+ env,
1354
+ info.env,
1355
+ info.envType,
1356
+ info.importer,
1357
+ info,
1358
+ );
1359
+ if (config.onViolation) {
1360
+ if ((await config.onViolation(info)) === false) continue;
1361
+ }
1362
+ realViolations.push(info);
1363
+ }
1364
+ if (realViolations.length === 0) return;
1365
+ if (config.effectiveBehavior === 'error')
1366
+ this.error(formatViolation(realViolations[0], config.root));
1367
+ else {
1368
+ const seen = /* @__PURE__ */ new Set();
1369
+ for (const info of realViolations) {
1370
+ const key = dedupeKey(info);
1371
+ if (!seen.has(key)) {
1372
+ seen.add(key);
1373
+ this.warn(formatViolation(info, config.root));
1374
+ }
1375
+ }
1376
+ }
1377
+ },
1378
+ closeBundle() {
1379
+ const envName = this.environment.name;
1380
+ perf?.count('closeBundle.calls');
1381
+ perf?.count(`closeBundle.env.${envName}`);
1382
+ perf?.flush(config.root, envName);
1383
+ },
1384
+ },
1385
+ {
1386
+ name: 'tanstack-start-core:import-protection-transform-cache',
1387
+ applyToEnvironment(env) {
1388
+ if (!config.enabled) return false;
1389
+ return environmentNames.has(env.name);
1390
+ },
1391
+ transform: {
1392
+ filter: { id: { include: [/\.[cm]?[tj]sx?($|\?)/] } },
1393
+ async handler(code, id) {
1394
+ perf?.count('transform.calls');
1395
+ const envName = this.environment.name;
1396
+ const file = normalizeFilePath(id);
1397
+ const envType = getImportProtectionEnvType(config, envName);
1398
+ const matchers = getRulesForEnvironment(envName);
1399
+ const isBuild = config.command === 'build';
1400
+ if (IMPORT_PROTECTION_DEBUG) {
1401
+ if (matchesDebugFilter(file))
1402
+ debugLog('transform-cache', {
1403
+ env: envName,
1404
+ id: normalizePath(id),
1405
+ file,
1406
+ });
1407
+ }
1408
+ if (!shouldCheckImporter(file)) return;
1409
+ const selfFileMatch = checkFileDenial(getRelativePath(file), matchers);
1410
+ if (selfFileMatch) {
1411
+ let exportNames = [];
1412
+ try {
1413
+ exportNames = getNamedExports(code, file, perf);
1414
+ } catch {}
1415
+ if (isBuild) return generateSelfContainedMockModule(exportNames);
1416
+ const runtimeId = mockRuntimeModuleIdFromViolation(
1417
+ {
1418
+ type: 'file',
1419
+ env: envType,
1420
+ envType,
1421
+ behavior: config.effectiveBehavior === 'error' ? 'error' : 'mock',
1422
+ importer: file,
1423
+ specifier: relativizePath(file, config.root),
1424
+ resolved: file,
1425
+ pattern: selfFileMatch.pattern,
1426
+ trace: [],
1427
+ },
1428
+ config.mockAccess,
1429
+ config.root,
1430
+ );
1431
+ return generateDevSelfDenialModule(exportNames, runtimeId);
1432
+ }
1433
+ const cacheKey = normalizePath(id);
1434
+ const envState = getEnv(envName);
1435
+ const isServerFnLookup = id.includes(SERVER_FN_LOOKUP_QUERY);
1436
+ if (isServerFnLookup) envState.serverFnLookupModules.add(file);
1437
+ const result = {
1438
+ code,
1439
+ filename: file,
1440
+ map: void 0,
1441
+ originalCode: void 0,
1442
+ };
1443
+ if (perf) result.perf = perf;
1444
+ if (shouldCaptureDiagnosticSourceMap(code, envType, matchers))
1445
+ captureDiagnosticSourceMap(result, () => this.getCombinedSourcemap(), 'candidate');
1446
+ cacheTransformResult(envState, file, cacheKey, result);
1447
+ if (isBuild) return void 0;
1448
+ const isDevMock = config.effectiveBehavior === 'mock';
1449
+ const importAnalysisStartedAt = perf ? performance.now() : 0;
1450
+ const importSources = getImportSourcesFromResult(result);
1451
+ if (perf) perf.time('transform.importAnalysis', importAnalysisStartedAt);
1452
+ perf?.count('transform.importSources', importSources.length);
1453
+ const resolvedChildren = /* @__PURE__ */ new Set();
1454
+ const deniedSourceReplacements = /* @__PURE__ */ new Map();
1455
+ for (const src of importSources)
1456
+ try {
1457
+ const startedAt = perf ? performance.now() : 0;
1458
+ perf?.count('transform.thisResolve.calls');
1459
+ const resolved = await this.resolve(src, id, { skipSelf: true });
1460
+ if (perf) perf.time('transform.thisResolve', startedAt);
1461
+ if (resolved && !resolved.external) {
1462
+ const resolvedPath = canonicalizeResolvedId(
1463
+ resolved.id,
1464
+ config.root,
1465
+ resolveExtensionlessAbsoluteId,
1466
+ );
1467
+ resolvedChildren.add(resolvedPath);
1468
+ if (resolved.id.includes('tanstack-start-import-protection:')) {
1469
+ let physicalPath;
1470
+ const pending = envState.pendingViolations.get(file);
1471
+ if (pending) {
1472
+ const match = pending.find(
1473
+ (pv) => pv.info.specifier === src && pv.info.resolved,
1474
+ );
1475
+ if (match) physicalPath = match.info.resolved;
1476
+ }
1477
+ if (physicalPath && physicalPath !== resolvedPath) {
1478
+ resolvedChildren.add(physicalPath);
1479
+ envState.graph.addEdge(physicalPath, file, src);
1480
+ }
1481
+ }
1482
+ envState.graph.addEdge(resolvedPath, file, src);
1483
+ if (isDevMock) {
1484
+ const fileMatch = checkFileDenial(getRelativePath(resolvedPath), matchers);
1485
+ if (fileMatch) {
1486
+ captureDiagnosticSourceMap(
1487
+ result,
1488
+ () => this.getCombinedSourcemap(),
1489
+ 'devViolation',
1490
+ );
1491
+ const info = buildFileViolationInfo(
1492
+ envName,
1493
+ envType,
1494
+ file,
1495
+ src,
1496
+ resolvedPath,
1497
+ fileMatch.pattern,
1498
+ );
1499
+ const replacement = await reportOrDeferViolation(
1500
+ this,
1501
+ envState,
1502
+ file,
1503
+ id,
1504
+ info,
1505
+ isDevMock,
1506
+ isServerFnLookup,
1507
+ );
1508
+ if (replacement)
1509
+ deniedSourceReplacements.set(
1510
+ src,
1511
+ replacement.startsWith('\0')
1512
+ ? VITE_BROWSER_VIRTUAL_PREFIX + replacement.slice(1)
1513
+ : replacement,
1514
+ );
1515
+ }
1516
+ }
1517
+ }
1518
+ } catch {}
1519
+ envState.postTransformImports.set(cacheKey, resolvedChildren);
1520
+ if (cacheKey !== file && !isServerFnLookup)
1521
+ envState.postTransformImports.set(file, resolvedChildren);
1522
+ await processPendingViolations(envState, this.warn.bind(this));
1523
+ if (deniedSourceReplacements.size > 0)
1524
+ try {
1525
+ const rewritten = rewriteDeniedImports(
1526
+ code,
1527
+ id,
1528
+ new Set(deniedSourceReplacements.keys()),
1529
+ (source) => deniedSourceReplacements.get(source) ?? source,
1530
+ );
1531
+ if (!rewritten) return;
1532
+ const normalizedMap = rewritten.map
1533
+ ? normalizeSourceMap(rewritten.map)
1534
+ : {
1535
+ version: 3,
1536
+ file: id,
1537
+ names: [],
1538
+ sources: [id],
1539
+ sourcesContent: [code],
1540
+ mappings: '',
1541
+ };
1542
+ return {
1543
+ code: rewritten.code,
1544
+ map: normalizedMap,
1545
+ };
1546
+ } catch {}
1547
+ },
1548
+ },
1549
+ },
1550
+ ];
1551
+ }
1552
+ //#endregion
1553
+ export { importProtectionPlugin };