isr-engine 0.0.0-stage → 1.0.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 (452) hide show
  1. package/CHANGELOG.md +755 -0
  2. package/README.md +694 -2
  3. package/dist/RequestContext-BVQ-rOmV.js +58 -0
  4. package/dist/RequestContext-BVQ-rOmV.js.map +1 -0
  5. package/dist/RequestContext-DgGEAxcW.cjs +105 -0
  6. package/dist/RequestContext-DgGEAxcW.cjs.map +1 -0
  7. package/dist/abVariantContext-CWCdRSdG.js +549 -0
  8. package/dist/abVariantContext-CWCdRSdG.js.map +1 -0
  9. package/dist/abVariantContext-Cqp-uxtd.cjs +678 -0
  10. package/dist/abVariantContext-Cqp-uxtd.cjs.map +1 -0
  11. package/dist/adapters/observability/client/sentry.d.ts +42 -0
  12. package/dist/adapters/observability/client/sentry.d.ts.map +1 -0
  13. package/dist/adapters/observability/index.cjs +152 -0
  14. package/dist/adapters/observability/index.cjs.map +1 -0
  15. package/dist/adapters/observability/index.d.ts +17 -0
  16. package/dist/adapters/observability/index.d.ts.map +1 -0
  17. package/dist/adapters/observability/index.js +148 -0
  18. package/dist/adapters/observability/index.js.map +1 -0
  19. package/dist/adapters/observability/server/datadog.d.ts +45 -0
  20. package/dist/adapters/observability/server/datadog.d.ts.map +1 -0
  21. package/dist/adapters/observability/server/otel.d.ts +51 -0
  22. package/dist/adapters/observability/server/otel.d.ts.map +1 -0
  23. package/dist/adapters/observability/server/sentry.d.ts +67 -0
  24. package/dist/adapters/observability/server/sentry.d.ts.map +1 -0
  25. package/dist/adapters/observability/types.d.ts +39 -0
  26. package/dist/adapters/observability/types.d.ts.map +1 -0
  27. package/dist/adapters/runtime/cloudflare.d.ts +33 -0
  28. package/dist/adapters/runtime/cloudflare.d.ts.map +1 -0
  29. package/dist/adapters/runtime/errorResponse.d.ts +3 -0
  30. package/dist/adapters/runtime/errorResponse.d.ts.map +1 -0
  31. package/dist/adapters/runtime/index.cjs +100 -0
  32. package/dist/adapters/runtime/index.cjs.map +1 -0
  33. package/dist/adapters/runtime/index.d.ts +10 -0
  34. package/dist/adapters/runtime/index.d.ts.map +1 -0
  35. package/dist/adapters/runtime/index.js +97 -0
  36. package/dist/adapters/runtime/index.js.map +1 -0
  37. package/dist/adapters/runtime/types.d.ts +24 -0
  38. package/dist/adapters/runtime/types.d.ts.map +1 -0
  39. package/dist/adapters/runtime/vercel-edge.d.ts +59 -0
  40. package/dist/adapters/runtime/vercel-edge.d.ts.map +1 -0
  41. package/dist/app/createISRApp.d.ts +19 -0
  42. package/dist/app/createISRApp.d.ts.map +1 -0
  43. package/dist/cache/CacheManager.d.ts +81 -0
  44. package/dist/cache/CacheManager.d.ts.map +1 -0
  45. package/dist/cache/ICacheAdapter.d.ts +84 -0
  46. package/dist/cache/ICacheAdapter.d.ts.map +1 -0
  47. package/dist/cache/MemoryCacheAdapter.d.ts +50 -0
  48. package/dist/cache/MemoryCacheAdapter.d.ts.map +1 -0
  49. package/dist/cache/RedisCacheAdapter.d.ts +111 -0
  50. package/dist/cache/RedisCacheAdapter.d.ts.map +1 -0
  51. package/dist/cache/RedisInvalidationBus.d.ts +59 -0
  52. package/dist/cache/RedisInvalidationBus.d.ts.map +1 -0
  53. package/dist/cache/RedisResponseCacheBackend.d.ts +30 -0
  54. package/dist/cache/RedisResponseCacheBackend.d.ts.map +1 -0
  55. package/dist/cache/ResponseCacheBackend.d.ts +28 -0
  56. package/dist/cache/ResponseCacheBackend.d.ts.map +1 -0
  57. package/dist/cache/createAutoCacheStore.d.ts +26 -0
  58. package/dist/cache/createAutoCacheStore.d.ts.map +1 -0
  59. package/dist/cache/index.d.ts +18 -0
  60. package/dist/cache/index.d.ts.map +1 -0
  61. package/dist/cli/cli.cjs +372 -0
  62. package/dist/cli/cli.cjs.map +1 -0
  63. package/dist/cli/cli.d.ts +8 -0
  64. package/dist/cli/cli.d.ts.map +1 -0
  65. package/dist/cli/cli.js +370 -0
  66. package/dist/cli/cli.js.map +1 -0
  67. package/dist/cli/dev.d.ts +11 -0
  68. package/dist/cli/dev.d.ts.map +1 -0
  69. package/dist/cli/fallback.d.ts +42 -0
  70. package/dist/cli/fallback.d.ts.map +1 -0
  71. package/dist/cli/serverOptions.d.ts +7 -0
  72. package/dist/cli/serverOptions.d.ts.map +1 -0
  73. package/dist/cli/start.d.ts +7 -0
  74. package/dist/cli/start.d.ts.map +1 -0
  75. package/dist/config/defaults.d.ts +11 -0
  76. package/dist/config/defaults.d.ts.map +1 -0
  77. package/dist/config/defineConfig.cjs +26 -0
  78. package/dist/config/defineConfig.cjs.map +1 -0
  79. package/dist/config/defineConfig.d.ts +44 -0
  80. package/dist/config/defineConfig.d.ts.map +1 -0
  81. package/dist/config/defineConfig.js +24 -0
  82. package/dist/config/defineConfig.js.map +1 -0
  83. package/dist/config/getEnv.d.ts +9 -0
  84. package/dist/config/getEnv.d.ts.map +1 -0
  85. package/dist/config/getStatus.d.ts +3 -0
  86. package/dist/config/getStatus.d.ts.map +1 -0
  87. package/dist/config/loadConfig.d.ts +18 -0
  88. package/dist/config/loadConfig.d.ts.map +1 -0
  89. package/dist/config/normalizeEngineConfig.d.ts +10 -0
  90. package/dist/config/normalizeEngineConfig.d.ts.map +1 -0
  91. package/dist/config/resolveImageOptions.d.ts +5 -0
  92. package/dist/config/resolveImageOptions.d.ts.map +1 -0
  93. package/dist/config/resolveRuntimeRedis.d.ts +11 -0
  94. package/dist/config/resolveRuntimeRedis.d.ts.map +1 -0
  95. package/dist/context/RequestContext.d.ts +28 -0
  96. package/dist/context/RequestContext.d.ts.map +1 -0
  97. package/dist/context/createServerRequestContext.d.ts +42 -0
  98. package/dist/context/createServerRequestContext.d.ts.map +1 -0
  99. package/dist/createCacheInspectorMiddleware-B32Suct_.js +105 -0
  100. package/dist/createCacheInspectorMiddleware-B32Suct_.js.map +1 -0
  101. package/dist/createCacheInspectorMiddleware-CAzxgGNh.cjs +105 -0
  102. package/dist/createCacheInspectorMiddleware-CAzxgGNh.cjs.map +1 -0
  103. package/dist/createISRApp-Bvs5_63N.cjs +7663 -0
  104. package/dist/createISRApp-Bvs5_63N.cjs.map +1 -0
  105. package/dist/createISRApp-CfGFTcw-.js +7322 -0
  106. package/dist/createISRApp-CfGFTcw-.js.map +1 -0
  107. package/dist/createImagePlugin-BHVUkFBd.js +416 -0
  108. package/dist/createImagePlugin-BHVUkFBd.js.map +1 -0
  109. package/dist/createImagePlugin-C-hHZCqj.cjs +435 -0
  110. package/dist/createImagePlugin-C-hHZCqj.cjs.map +1 -0
  111. package/dist/defaults/auto-observability.cjs +147 -0
  112. package/dist/defaults/auto-observability.cjs.map +1 -0
  113. package/dist/defaults/auto-observability.d.ts +21 -0
  114. package/dist/defaults/auto-observability.d.ts.map +1 -0
  115. package/dist/defaults/auto-observability.js +144 -0
  116. package/dist/defaults/auto-observability.js.map +1 -0
  117. package/dist/defaults/runtime/browserObservability.d.ts +73 -0
  118. package/dist/defaults/runtime/browserObservability.d.ts.map +1 -0
  119. package/dist/defaults/runtime/client-navigation-policy.d.ts +10 -0
  120. package/dist/defaults/runtime/client-navigation-policy.d.ts.map +1 -0
  121. package/dist/defaults/runtime/createCachedFetcher.d.ts +17 -0
  122. package/dist/defaults/runtime/createCachedFetcher.d.ts.map +1 -0
  123. package/dist/defaults/runtime/defineSiteHooks.cjs +11 -0
  124. package/dist/defaults/runtime/defineSiteHooks.d.ts +197 -0
  125. package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -0
  126. package/dist/defaults/runtime/defineSiteHooks.js +3 -0
  127. package/dist/defaults/runtime/dev-css-handoff.client.d.ts +2 -0
  128. package/dist/defaults/runtime/dev-css-handoff.client.d.ts.map +1 -0
  129. package/dist/defaults/runtime/dev-render-inspector.d.ts +57 -0
  130. package/dist/defaults/runtime/dev-render-inspector.d.ts.map +1 -0
  131. package/dist/defaults/runtime/dev-rsc-response.client.d.ts +7 -0
  132. package/dist/defaults/runtime/dev-rsc-response.client.d.ts.map +1 -0
  133. package/dist/defaults/runtime/dev-style-commit-boundary.client.d.ts +9 -0
  134. package/dist/defaults/runtime/dev-style-commit-boundary.client.d.ts.map +1 -0
  135. package/dist/defaults/runtime/dev-style-declarations.server.d.ts +15 -0
  136. package/dist/defaults/runtime/dev-style-declarations.server.d.ts.map +1 -0
  137. package/dist/defaults/runtime/dev-style-id.d.ts +9 -0
  138. package/dist/defaults/runtime/dev-style-id.d.ts.map +1 -0
  139. package/dist/defaults/runtime/dev-style-navigation.client.d.ts +26 -0
  140. package/dist/defaults/runtime/dev-style-navigation.client.d.ts.map +1 -0
  141. package/dist/defaults/runtime/dev-style-registry.client.d.ts +19 -0
  142. package/dist/defaults/runtime/dev-style-registry.client.d.ts.map +1 -0
  143. package/dist/defaults/runtime/dev-style-resource-dispatcher.server.d.ts +4 -0
  144. package/dist/defaults/runtime/dev-style-resource-dispatcher.server.d.ts.map +1 -0
  145. package/dist/defaults/runtime/empty-routes.d.ts +3 -0
  146. package/dist/defaults/runtime/empty-routes.d.ts.map +1 -0
  147. package/dist/defaults/runtime/error-boundary.d.ts +9 -0
  148. package/dist/defaults/runtime/error-boundary.d.ts.map +1 -0
  149. package/dist/defaults/runtime/error500-template.d.ts +21 -0
  150. package/dist/defaults/runtime/error500-template.d.ts.map +1 -0
  151. package/dist/defaults/runtime/head-extras-runtime.d.ts +17 -0
  152. package/dist/defaults/runtime/head-extras-runtime.d.ts.map +1 -0
  153. package/dist/defaults/runtime/hydration-shell.d.ts +12 -0
  154. package/dist/defaults/runtime/hydration-shell.d.ts.map +1 -0
  155. package/dist/defaults/runtime/i18n-server.d.ts +7 -0
  156. package/dist/defaults/runtime/i18n-server.d.ts.map +1 -0
  157. package/dist/defaults/runtime/navigation-history.client.d.ts +16 -0
  158. package/dist/defaults/runtime/navigation-history.client.d.ts.map +1 -0
  159. package/dist/defaults/runtime/navigation-request.client.d.ts +5 -0
  160. package/dist/defaults/runtime/navigation-request.client.d.ts.map +1 -0
  161. package/dist/defaults/runtime/seo-runtime.d.ts +41 -0
  162. package/dist/defaults/runtime/seo-runtime.d.ts.map +1 -0
  163. package/dist/defineSiteHooks-BeVy-qPH.js +720 -0
  164. package/dist/defineSiteHooks-BeVy-qPH.js.map +1 -0
  165. package/dist/defineSiteHooks-C3v3WLS8.cjs +755 -0
  166. package/dist/defineSiteHooks-C3v3WLS8.cjs.map +1 -0
  167. package/dist/discovery/componentDiscovery.d.ts +71 -0
  168. package/dist/discovery/componentDiscovery.d.ts.map +1 -0
  169. package/dist/discovery/directiveParser.d.ts +197 -0
  170. package/dist/discovery/directiveParser.d.ts.map +1 -0
  171. package/dist/discovery/exportParser.d.ts +45 -0
  172. package/dist/discovery/exportParser.d.ts.map +1 -0
  173. package/dist/discovery/fileSystem.d.ts +33 -0
  174. package/dist/discovery/fileSystem.d.ts.map +1 -0
  175. package/dist/discovery/index.d.ts +18 -0
  176. package/dist/discovery/index.d.ts.map +1 -0
  177. package/dist/discovery/routeDiscovery.d.ts +121 -0
  178. package/dist/discovery/routeDiscovery.d.ts.map +1 -0
  179. package/dist/discovery/scan.d.ts +54 -0
  180. package/dist/discovery/scan.d.ts.map +1 -0
  181. package/dist/discovery/types.d.ts +61 -0
  182. package/dist/discovery/types.d.ts.map +1 -0
  183. package/dist/engine/ISREngine.d.ts +54 -0
  184. package/dist/engine/ISREngine.d.ts.map +1 -0
  185. package/dist/engine/RenderMode.d.ts +23 -0
  186. package/dist/engine/RenderMode.d.ts.map +1 -0
  187. package/dist/engine/i18n/types.d.ts +6 -0
  188. package/dist/engine/i18n/types.d.ts.map +1 -0
  189. package/dist/engine/seo/PageSeoMeta.d.ts +9 -0
  190. package/dist/engine/seo/PageSeoMeta.d.ts.map +1 -0
  191. package/dist/engine/seo/SEOEngine.d.ts +61 -0
  192. package/dist/engine/seo/SEOEngine.d.ts.map +1 -0
  193. package/dist/engine/seo/config.d.ts +9 -0
  194. package/dist/engine/seo/config.d.ts.map +1 -0
  195. package/dist/engine/seo/index.d.ts +10 -0
  196. package/dist/engine/seo/index.d.ts.map +1 -0
  197. package/dist/engine/seo/injectSeoMeta.d.ts +5 -0
  198. package/dist/engine/seo/injectSeoMeta.d.ts.map +1 -0
  199. package/dist/engine/seo/resolveSeoConfig.d.ts +15 -0
  200. package/dist/engine/seo/resolveSeoConfig.d.ts.map +1 -0
  201. package/dist/engine/seo/types.d.ts +75 -0
  202. package/dist/engine/seo/types.d.ts.map +1 -0
  203. package/dist/error500-template-BvZmvKoa.cjs +63 -0
  204. package/dist/error500-template-BvZmvKoa.cjs.map +1 -0
  205. package/dist/error500-template-DhaZzLOB.js +63 -0
  206. package/dist/error500-template-DhaZzLOB.js.map +1 -0
  207. package/dist/experiments/ExposureQueue.d.ts +54 -0
  208. package/dist/experiments/ExposureQueue.d.ts.map +1 -0
  209. package/dist/experiments/ManifestLoader.d.ts +57 -0
  210. package/dist/experiments/ManifestLoader.d.ts.map +1 -0
  211. package/dist/i18n-CyJIoYJT.cjs +244 -0
  212. package/dist/i18n-CyJIoYJT.cjs.map +1 -0
  213. package/dist/i18n-Dobe0Wxn.js +191 -0
  214. package/dist/i18n-Dobe0Wxn.js.map +1 -0
  215. package/dist/image/index.cjs +93 -0
  216. package/dist/image/index.cjs.map +1 -0
  217. package/dist/image/index.js +67 -0
  218. package/dist/image/index.js.map +1 -0
  219. package/dist/index.d.ts +59 -0
  220. package/dist/index.d.ts.map +1 -0
  221. package/dist/isr/ISRRoutes.d.ts +25 -0
  222. package/dist/isr/ISRRoutes.d.ts.map +1 -0
  223. package/dist/isr-engine.cjs +2830 -0
  224. package/dist/isr-engine.cjs.map +1 -0
  225. package/dist/isr-engine.js +2740 -0
  226. package/dist/isr-engine.js.map +1 -0
  227. package/dist/logger/Logger.d.ts +33 -0
  228. package/dist/logger/Logger.d.ts.map +1 -0
  229. package/dist/logger/index.d.ts +3 -0
  230. package/dist/logger/index.d.ts.map +1 -0
  231. package/dist/manifest/ManifestLoader.d.ts +98 -0
  232. package/dist/manifest/ManifestLoader.d.ts.map +1 -0
  233. package/dist/manifest/index.d.ts +8 -0
  234. package/dist/manifest/index.d.ts.map +1 -0
  235. package/dist/manifest/types.d.ts +76 -0
  236. package/dist/manifest/types.d.ts.map +1 -0
  237. package/dist/metrics/MetricsCollector.d.ts +90 -0
  238. package/dist/metrics/MetricsCollector.d.ts.map +1 -0
  239. package/dist/metrics/PromMetrics.d.ts +59 -0
  240. package/dist/metrics/PromMetrics.d.ts.map +1 -0
  241. package/dist/metrics/index.d.ts +7 -0
  242. package/dist/metrics/index.d.ts.map +1 -0
  243. package/dist/middlewares/ABVariantMiddleware.d.ts +74 -0
  244. package/dist/middlewares/ABVariantMiddleware.d.ts.map +1 -0
  245. package/dist/middlewares/LocaleRedirect.d.ts +27 -0
  246. package/dist/middlewares/LocaleRedirect.d.ts.map +1 -0
  247. package/dist/middlewares/MiddlewareComposer.d.ts +20 -0
  248. package/dist/middlewares/MiddlewareComposer.d.ts.map +1 -0
  249. package/dist/middlewares/PerformanceMiddleware.d.ts +14 -0
  250. package/dist/middlewares/PerformanceMiddleware.d.ts.map +1 -0
  251. package/dist/middlewares/TraceMiddleware.d.ts +24 -0
  252. package/dist/middlewares/TraceMiddleware.d.ts.map +1 -0
  253. package/dist/middlewares/abVariantContext.d.ts +7 -0
  254. package/dist/middlewares/abVariantContext.d.ts.map +1 -0
  255. package/dist/middlewares/index.d.ts +5 -0
  256. package/dist/middlewares/index.d.ts.map +1 -0
  257. package/dist/middlewares/types.d.ts +4 -0
  258. package/dist/middlewares/types.d.ts.map +1 -0
  259. package/dist/plugin/clientObservabilityConfig.d.ts +16 -0
  260. package/dist/plugin/clientObservabilityConfig.d.ts.map +1 -0
  261. package/dist/plugin/coherentCacheStore.d.ts +11 -0
  262. package/dist/plugin/coherentCacheStore.d.ts.map +1 -0
  263. package/dist/plugin/createAutomaticImagePlugin.d.ts +4 -0
  264. package/dist/plugin/createAutomaticImagePlugin.d.ts.map +1 -0
  265. package/dist/plugin/createCacheInspectorMiddleware.d.ts +16 -0
  266. package/dist/plugin/createCacheInspectorMiddleware.d.ts.map +1 -0
  267. package/dist/plugin/createDevCssHandoffPlugin.d.ts +25 -0
  268. package/dist/plugin/createDevCssHandoffPlugin.d.ts.map +1 -0
  269. package/dist/plugin/createFontPlugin.d.ts +15 -0
  270. package/dist/plugin/createFontPlugin.d.ts.map +1 -0
  271. package/dist/plugin/createImagePlugin.d.ts +46 -0
  272. package/dist/plugin/createImagePlugin.d.ts.map +1 -0
  273. package/dist/plugin/createIsrPlugin.d.ts +43 -0
  274. package/dist/plugin/createIsrPlugin.d.ts.map +1 -0
  275. package/dist/plugin/createSsgPostBuildPlugin.d.ts +4 -0
  276. package/dist/plugin/createSsgPostBuildPlugin.d.ts.map +1 -0
  277. package/dist/plugin/devAssetRequestMiddleware.d.ts +10 -0
  278. package/dist/plugin/devAssetRequestMiddleware.d.ts.map +1 -0
  279. package/dist/plugin/index.d.ts +11 -0
  280. package/dist/plugin/index.d.ts.map +1 -0
  281. package/dist/plugin/isrCacheMiddleware.d.ts +223 -0
  282. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -0
  283. package/dist/plugin/isrCacheStore.d.ts +88 -0
  284. package/dist/plugin/isrCacheStore.d.ts.map +1 -0
  285. package/dist/plugin/remoteImageSource.d.ts +19 -0
  286. package/dist/plugin/remoteImageSource.d.ts.map +1 -0
  287. package/dist/plugin/transformDevCssModule.d.ts +3 -0
  288. package/dist/plugin/transformDevCssModule.d.ts.map +1 -0
  289. package/dist/renderer/RenderHeaders.d.ts +28 -0
  290. package/dist/renderer/RenderHeaders.d.ts.map +1 -0
  291. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  292. package/dist/rolldown-runtime-DakpK96I.cjs +43 -0
  293. package/dist/route/RouteManager.d.ts +22 -0
  294. package/dist/route/RouteManager.d.ts.map +1 -0
  295. package/dist/route/index.d.ts +2 -0
  296. package/dist/route/index.d.ts.map +1 -0
  297. package/dist/rsc/ServerActions.d.ts +65 -0
  298. package/dist/rsc/ServerActions.d.ts.map +1 -0
  299. package/dist/rsc/browser.cjs +109 -0
  300. package/dist/rsc/browser.cjs.map +1 -0
  301. package/dist/rsc/browser.d.ts +59 -0
  302. package/dist/rsc/browser.d.ts.map +1 -0
  303. package/dist/rsc/browser.js +85 -0
  304. package/dist/rsc/browser.js.map +1 -0
  305. package/dist/rsc/cacheTag.d.ts +52 -0
  306. package/dist/rsc/cacheTag.d.ts.map +1 -0
  307. package/dist/rsc/constants.d.ts +10 -0
  308. package/dist/rsc/constants.d.ts.map +1 -0
  309. package/dist/rsc/i18n.d.ts +3 -0
  310. package/dist/rsc/i18n.d.ts.map +1 -0
  311. package/dist/rsc/index.cjs +33 -0
  312. package/dist/rsc/index.d.ts +20 -0
  313. package/dist/rsc/index.d.ts.map +1 -0
  314. package/dist/rsc/index.js +4 -0
  315. package/dist/rsc/revalidate.d.ts +77 -0
  316. package/dist/rsc/revalidate.d.ts.map +1 -0
  317. package/dist/rsc-H7D_meHu.cjs +239 -0
  318. package/dist/rsc-H7D_meHu.cjs.map +1 -0
  319. package/dist/rsc-lvWPTuVD.js +168 -0
  320. package/dist/rsc-lvWPTuVD.js.map +1 -0
  321. package/dist/runtime/Image.d.ts +48 -0
  322. package/dist/runtime/Image.d.ts.map +1 -0
  323. package/dist/runtime/LocaleContext.d.ts +14 -0
  324. package/dist/runtime/LocaleContext.d.ts.map +1 -0
  325. package/dist/runtime/boundary.d.ts +27 -0
  326. package/dist/runtime/boundary.d.ts.map +1 -0
  327. package/dist/runtime/edge-context.d.ts +17 -0
  328. package/dist/runtime/edge-context.d.ts.map +1 -0
  329. package/dist/runtime/i18n-store.d.ts +11 -0
  330. package/dist/runtime/i18n-store.d.ts.map +1 -0
  331. package/dist/runtime/i18n.d.ts +115 -0
  332. package/dist/runtime/i18n.d.ts.map +1 -0
  333. package/dist/runtime/index.d.ts +16 -0
  334. package/dist/runtime/index.d.ts.map +1 -0
  335. package/dist/runtime/routes.d.ts +88 -0
  336. package/dist/runtime/routes.d.ts.map +1 -0
  337. package/dist/runtime/telemetry.d.ts +48 -0
  338. package/dist/runtime/telemetry.d.ts.map +1 -0
  339. package/dist/security/cspNonceTemplate.d.ts +10 -0
  340. package/dist/security/cspNonceTemplate.d.ts.map +1 -0
  341. package/dist/security/staticCspManifest.d.ts +37 -0
  342. package/dist/security/staticCspManifest.d.ts.map +1 -0
  343. package/dist/server/httpServer.d.ts +17 -0
  344. package/dist/server/httpServer.d.ts.map +1 -0
  345. package/dist/server/index.d.ts +3 -0
  346. package/dist/server/index.d.ts.map +1 -0
  347. package/dist/server/manager.d.ts +17 -0
  348. package/dist/server/manager.d.ts.map +1 -0
  349. package/dist/server/middleware.d.ts +87 -0
  350. package/dist/server/middleware.d.ts.map +1 -0
  351. package/dist/server/opsConfig.d.ts +17 -0
  352. package/dist/server/opsConfig.d.ts.map +1 -0
  353. package/dist/server/productionRuntime.d.ts +41 -0
  354. package/dist/server/productionRuntime.d.ts.map +1 -0
  355. package/dist/server/types.d.ts +41 -0
  356. package/dist/server/types.d.ts.map +1 -0
  357. package/dist/server/viteDevServer.d.ts +21 -0
  358. package/dist/server/viteDevServer.d.ts.map +1 -0
  359. package/dist/ssg/spider.d.ts +142 -0
  360. package/dist/ssg/spider.d.ts.map +1 -0
  361. package/dist/types/IFlightData.d.ts +23 -0
  362. package/dist/types/IFlightData.d.ts.map +1 -0
  363. package/dist/types/IHelmetData.d.ts +24 -0
  364. package/dist/types/IHelmetData.d.ts.map +1 -0
  365. package/dist/types/IRenderMetadata.d.ts +46 -0
  366. package/dist/types/IRenderMetadata.d.ts.map +1 -0
  367. package/dist/types/IRenderResult.d.ts +16 -0
  368. package/dist/types/IRenderResult.d.ts.map +1 -0
  369. package/dist/types/ISRConfig.d.ts +463 -0
  370. package/dist/types/ISRConfig.d.ts.map +1 -0
  371. package/dist/types/ISRContext.d.ts +104 -0
  372. package/dist/types/ISRContext.d.ts.map +1 -0
  373. package/dist/types/index.d.ts +7 -0
  374. package/dist/types/index.d.ts.map +1 -0
  375. package/dist/utils/CacheCleanup.d.ts +32 -0
  376. package/dist/utils/CacheCleanup.d.ts.map +1 -0
  377. package/dist/utils/cacheDuration.d.ts +12 -0
  378. package/dist/utils/cacheDuration.d.ts.map +1 -0
  379. package/dist/utils/cookie.d.ts +7 -0
  380. package/dist/utils/cookie.d.ts.map +1 -0
  381. package/dist/utils/hash.d.ts +22 -0
  382. package/dist/utils/hash.d.ts.map +1 -0
  383. package/dist/utils/htmlPathname.d.ts +12 -0
  384. package/dist/utils/htmlPathname.d.ts.map +1 -0
  385. package/dist/utils/index.d.ts +9 -0
  386. package/dist/utils/index.d.ts.map +1 -0
  387. package/dist/utils/resolveFetchHandler.d.ts +4 -0
  388. package/dist/utils/resolveFetchHandler.d.ts.map +1 -0
  389. package/dist/utils/trimTrailingSlashes.d.ts +3 -0
  390. package/dist/utils/trimTrailingSlashes.d.ts.map +1 -0
  391. package/package.json +200 -4
  392. package/src/context/RequestContext.ts +68 -0
  393. package/src/context/createServerRequestContext.ts +104 -0
  394. package/src/defaults/auto-observability.ts +195 -0
  395. package/src/defaults/entry.server.ssr.tsx +257 -0
  396. package/src/defaults/entry.server.tsx +117 -0
  397. package/src/defaults/entry.tsx +23 -0
  398. package/src/defaults/runtime/browserObservability.ts +839 -0
  399. package/src/defaults/runtime/client-navigation-policy.ts +67 -0
  400. package/src/defaults/runtime/createCachedFetcher.ts +121 -0
  401. package/src/defaults/runtime/defineClientEntry.tsx +773 -0
  402. package/src/defaults/runtime/defineServerEntry.tsx +421 -0
  403. package/src/defaults/runtime/defineSiteHooks.ts +1073 -0
  404. package/src/defaults/runtime/dev-css-handoff.client.ts +5 -0
  405. package/src/defaults/runtime/dev-render-inspector.ts +597 -0
  406. package/src/defaults/runtime/dev-rsc-response.client.ts +48 -0
  407. package/src/defaults/runtime/dev-style-commit-boundary.client.tsx +20 -0
  408. package/src/defaults/runtime/dev-style-declarations.server.ts +158 -0
  409. package/src/defaults/runtime/dev-style-id.ts +91 -0
  410. package/src/defaults/runtime/dev-style-navigation.client.ts +152 -0
  411. package/src/defaults/runtime/dev-style-registry.client.ts +744 -0
  412. package/src/defaults/runtime/dev-style-resource-dispatcher.server.ts +42 -0
  413. package/src/defaults/runtime/empty-config.ts +5 -0
  414. package/src/defaults/runtime/empty-routes.ts +2 -0
  415. package/src/defaults/runtime/error-boundary.style.css +35 -0
  416. package/src/defaults/runtime/error-boundary.tsx +65 -0
  417. package/src/defaults/runtime/error500-template.ts +66 -0
  418. package/src/defaults/runtime/head-extras-runtime.ts +64 -0
  419. package/src/defaults/runtime/hydration-shell.tsx +20 -0
  420. package/src/defaults/runtime/i18n-server.ts +27 -0
  421. package/src/defaults/runtime/navigation-history.client.ts +80 -0
  422. package/src/defaults/runtime/navigation-request.client.ts +21 -0
  423. package/src/defaults/runtime/request.tsx +100 -0
  424. package/src/defaults/runtime/seo-runtime.ts +257 -0
  425. package/src/defaults/tsconfig.json +10 -0
  426. package/src/defaults/types.d.ts +23 -0
  427. package/src/runtime/Image.tsx +124 -0
  428. package/src/runtime/LocaleContext.tsx +38 -0
  429. package/src/runtime/boundary.module.css +46 -0
  430. package/src/runtime/boundary.tsx +136 -0
  431. package/src/runtime/edge-context.ts +32 -0
  432. package/src/runtime/i18n-store.ts +76 -0
  433. package/src/runtime/i18n.ts +189 -0
  434. package/src/runtime/index.ts +61 -0
  435. package/src/runtime/routes.tsx +247 -0
  436. package/src/runtime/scss.d.ts +13 -0
  437. package/src/runtime/telemetry.ts +116 -0
  438. package/src/types/IFlightData.ts +27 -0
  439. package/src/types/IHelmetData.ts +9 -0
  440. package/src/types/IRenderMetadata.ts +52 -0
  441. package/src/types/IRenderResult.ts +16 -0
  442. package/src/types/ISRConfig.ts +512 -0
  443. package/src/types/ISRContext.ts +106 -0
  444. package/src/types/index.ts +6 -0
  445. package/src/utils/CacheCleanup.ts +74 -0
  446. package/src/utils/cacheDuration.ts +37 -0
  447. package/src/utils/cookie.ts +59 -0
  448. package/src/utils/hash.ts +32 -0
  449. package/src/utils/htmlPathname.ts +75 -0
  450. package/src/utils/index.ts +9 -0
  451. package/src/utils/resolveFetchHandler.ts +19 -0
  452. package/src/utils/trimTrailingSlashes.ts +6 -0
@@ -0,0 +1,2740 @@
1
+ import { $ as CacheCleanup, A as FallbackChain, B as scanComponents, C as loadConfig, D as getRouteFallbackChain, E as getFallbackChain, F as logger$1, G as parseRouteFromFile, H as scanRoutes, J as isTestFile, K as parseRoutes, M as RenderModes, N as extractSsgRoutes, O as matchRoutePattern, P as spiderSsgRoutes, Q as getEnv, R as resolveFetchHandler, T as createMemoryCacheStore, U as parseComponentFromFile, V as scanProject, W as parseComponents, X as isDev, Y as readDirRecursive, Z as isProd, _ as RedisInvalidationBus, a as DEFAULT_SEO_CONFIG, b as createCoherentCacheStore, c as startAppServer, et as assertDistinctHtmlRouteIdentities, g as createIsrCacheMiddleware, h as createIsrCacheHandler, i as createSEOEngine, j as InternalStrategies, k as resolveRenderMode, l as createABVariantMiddleware, m as generateStaticCspManifest, n as ISREngine, o as mergeSEOConfig, q as isCodeFile, r as SEOEngine, s as shutdownServer, t as createISRApp, tt as resolveImageOptions, v as RedisCacheAdapter, w as createHybridCacheStore, x as createDevAssetRequestMiddleware, y as MemoryCacheAdapter, z as DEFAULT_SCAN_CONFIG } from "./createISRApp-CfGFTcw-.js";
2
+ import { c as requestContext, i as getRequestContext } from "./RequestContext-BVQ-rOmV.js";
3
+ import { _ as invalidatorRunsTotal, b as recordHttpRequest, c as RevalidationError, d as revalidateTag, g as invalidatorFailuresTotal, h as createPrometheusMetricsMiddleware, l as registerInvalidator, n as cacheTag, r as collectTags, s as runWithTagStore, t as getVariant, u as revalidatePath, x as Logger, y as promRegistry } from "./abVariantContext-CWCdRSdG.js";
4
+ import { c as parseCookieHeader, l as readCookie, o as trimTrailingSlashes, s as getCookieHeader } from "./i18n-Dobe0Wxn.js";
5
+ import { defineIsrConfig, defineRuntimeConfig } from "./config/defineConfig.js";
6
+ import { n as createImagePlugin, t as createImageMiddleware } from "./createImagePlugin-BHVUkFBd.js";
7
+ import { a as defineSiteHooks, i as defineAdminSiteHooks, n as createAdminIntlLoader, o as createCachedFetcher, r as createAdminSeoLoader, t as applyRuntimeToServerHooks } from "./defineSiteHooks-BeVy-qPH.js";
8
+ import { a as LEGACY_SERVER_ACTION_ENDPOINT, d as createServerAction, f as serverActionsRegistry, i as getI18nLocale, o as SERVER_ACTION_ENDPOINT, r as getI18n, u as ServerActionUtils } from "./rsc-lvWPTuVD.js";
9
+ import fs, { existsSync, promises, readFileSync, realpathSync } from "node:fs";
10
+ import path from "node:path";
11
+ import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "fs";
12
+ import { resolve as resolve$1 } from "path";
13
+ import ts from "typescript";
14
+ import { normalizePath, version } from "vite";
15
+ import { createHash } from "node:crypto";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import { parse, walk } from "css-tree";
18
+ import { createRequire } from "node:module";
19
+ import vitePluginRsc from "@vitejs/plugin-rsc";
20
+ import * as ReactDOM from "react-dom";
21
+ //#region src/defaults/runtime/seo-runtime.ts
22
+ /**
23
+ * 把相对 URL 用 baseUrl 解析成绝对 URL
24
+ * og:image / canonical / twitter:image / alternates.href 必须是绝对 URL
25
+ * —— 社交爬虫(Facebook/Twitter/微信/LinkedIn)不会基于页面 URL resolve 相对路径
26
+ */
27
+ function toAbsolute(href, baseUrl) {
28
+ if (!href) return href;
29
+ if (/^(https?:)?\/\//i.test(href)) return href;
30
+ if (!baseUrl) return href;
31
+ try {
32
+ return new URL(href, baseUrl).toString();
33
+ } catch {
34
+ return href;
35
+ }
36
+ }
37
+ function renderPageSeoMeta(meta, baseUrl) {
38
+ const tags = [];
39
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
40
+ if (meta.title) tags.push(`<title>${esc(meta.title)}</title>`);
41
+ if (meta.description) tags.push(`<meta data-isr-seo name="description" content="${esc(meta.description)}">`);
42
+ if (meta.keywords?.length) tags.push(`<meta data-isr-seo name="keywords" content="${esc(meta.keywords.join(", "))}">`);
43
+ if (meta.noindex) tags.push(`<meta data-isr-seo name="robots" content="noindex, nofollow">`);
44
+ if (meta.canonical || baseUrl) {
45
+ const href = toAbsolute(meta.canonical || "", baseUrl) || baseUrl || "";
46
+ if (href) tags.push(`<link data-isr-seo rel="canonical" href="${esc(href)}">`);
47
+ }
48
+ if (meta.alternates?.length) for (const a of meta.alternates) tags.push(`<link data-isr-seo rel="alternate" hreflang="${esc(a.hreflang)}" href="${esc(toAbsolute(a.href, baseUrl))}">`);
49
+ if (meta.title) tags.push(`<meta data-isr-seo property="og:title" content="${esc(meta.title)}">`);
50
+ if (meta.description) tags.push(`<meta data-isr-seo property="og:description" content="${esc(meta.description)}">`);
51
+ tags.push(`<meta data-isr-seo property="og:type" content="${meta.ogType ?? "website"}">`);
52
+ if (meta.image) {
53
+ const abs = toAbsolute(meta.image, baseUrl);
54
+ tags.push(`<meta data-isr-seo property="og:image" content="${esc(abs)}">`);
55
+ tags.push(`<meta data-isr-seo name="twitter:image" content="${esc(abs)}">`);
56
+ }
57
+ if (meta.jsonLd) {
58
+ const arr = Array.isArray(meta.jsonLd) ? meta.jsonLd : [meta.jsonLd];
59
+ for (const obj of arr) {
60
+ const json = JSON.stringify(obj).replace(/<\/script/gi, "<\\/script");
61
+ tags.push(`<script data-isr-seo="jsonld" type="application/ld+json">${json}<\/script>`);
62
+ }
63
+ }
64
+ return tags.join("\n ");
65
+ }
66
+ var HEAD_OPEN_RE = /<head\b[^>]*>/i;
67
+ function injectSeoMeta(source, meta, baseUrl) {
68
+ const encoder = new TextEncoder();
69
+ const decoder = new TextDecoder("utf-8", { fatal: false });
70
+ const injection = "\n " + renderPageSeoMeta(meta, baseUrl) + "\n";
71
+ let buffer = "";
72
+ let injected = false;
73
+ const SAFE_KEEP = 256;
74
+ const transform = new TransformStream({
75
+ transform(chunk, controller) {
76
+ if (injected) {
77
+ controller.enqueue(chunk);
78
+ return;
79
+ }
80
+ buffer += decoder.decode(chunk, { stream: true });
81
+ const m = HEAD_OPEN_RE.exec(buffer);
82
+ if (m) {
83
+ const cutAt = m.index + m[0].length;
84
+ const before = buffer.slice(0, cutAt);
85
+ const after = buffer.slice(cutAt);
86
+ controller.enqueue(encoder.encode(before + injection + after));
87
+ buffer = "";
88
+ injected = true;
89
+ return;
90
+ }
91
+ if (buffer.length > SAFE_KEEP) {
92
+ const emit = buffer.slice(0, buffer.length - SAFE_KEEP);
93
+ buffer = buffer.slice(buffer.length - SAFE_KEEP);
94
+ controller.enqueue(encoder.encode(emit));
95
+ }
96
+ },
97
+ flush(controller) {
98
+ const tail = buffer + decoder.decode();
99
+ if (tail) controller.enqueue(encoder.encode(tail));
100
+ }
101
+ });
102
+ return source.pipeThrough(transform);
103
+ }
104
+ //#endregion
105
+ //#region src/manifest/ManifestLoader.ts
106
+ /**
107
+ * Vite Manifest 加载器
108
+ *
109
+ * @description 加载 Vite 构建产出的 Manifest 文件,用于生产环境 SSR 资源注入
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * const manifest = ManifestLoader.load({ rootDir: process.cwd() });
114
+ * if (manifest) {
115
+ * const assets = ManifestLoader.getEntryAssets('src/entry.tsx');
116
+ * console.log(assets.js); // '/assets/entry.a1b2c3.js'
117
+ * }
118
+ * ```
119
+ */
120
+ /** Vite Manifest 默认路径 (按优先级排列) */
121
+ var MANIFEST_PATHS = [
122
+ "dist/.vite/manifest.json",
123
+ "dist/client/.vite/manifest.json",
124
+ "dist/manifest.json"
125
+ ];
126
+ var MANIFEST_ENTRY_CANDIDATES = [
127
+ "src/entry.tsx",
128
+ "src/entry.ts",
129
+ "src/main.tsx",
130
+ "src/main.ts",
131
+ "src/index.tsx",
132
+ "src/index.ts",
133
+ "src/App.tsx",
134
+ "src/App.ts"
135
+ ];
136
+ /**
137
+ * Vite Manifest 加载器
138
+ */
139
+ var ManifestLoader = class {
140
+ static logger = Logger.getInstance();
141
+ static manifest = null;
142
+ static publicPath = "/";
143
+ constructor() {}
144
+ /**
145
+ * 加载 Manifest
146
+ * @returns 解析后的 Manifest,失败返回 null
147
+ */
148
+ static load(config) {
149
+ const { rootDir, manifestPath, publicPath = "/" } = config;
150
+ this.publicPath = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
151
+ const absolutePath = manifestPath ? resolve$1(rootDir, manifestPath) : this.detectManifestPath(rootDir);
152
+ if (!absolutePath) return null;
153
+ return this.loadFromPath(absolutePath);
154
+ }
155
+ /**
156
+ * 检测 Manifest 路径
157
+ */
158
+ static detectManifestPath(rootDir) {
159
+ for (const relativePath of MANIFEST_PATHS) {
160
+ const absolutePath = resolve$1(rootDir, relativePath);
161
+ if (existsSync$1(absolutePath)) {
162
+ this.logger.info(`📦 检测到 Manifest: ${relativePath}`);
163
+ return absolutePath;
164
+ }
165
+ }
166
+ this.logger.warn(`⚠️ 未找到 Manifest 文件,请确保已执行 vite build 并设置 build.manifest: true`);
167
+ return null;
168
+ }
169
+ /**
170
+ * 从路径加载 Manifest
171
+ */
172
+ static loadFromPath(absolutePath) {
173
+ if (!existsSync$1(absolutePath)) {
174
+ this.logger.error(`Manifest 文件不存在: ${absolutePath}`);
175
+ return null;
176
+ }
177
+ try {
178
+ const content = readFileSync$1(absolutePath, "utf-8");
179
+ const raw = JSON.parse(content);
180
+ const parsed = this.parse(raw, absolutePath);
181
+ this.manifest = parsed;
182
+ this.logger.info(`✅ Manifest 加载成功: ${parsed.entries.size} 个入口,${parsed.modules.size} 个模块`);
183
+ return parsed;
184
+ } catch (error) {
185
+ this.logger.error(`Manifest 解析失败: ${error instanceof Error ? error.message : String(error)}`);
186
+ return null;
187
+ }
188
+ }
189
+ /**
190
+ * 解析 Vite Manifest
191
+ */
192
+ static parse(raw, filePath) {
193
+ const entries = /* @__PURE__ */ new Map();
194
+ const modules = /* @__PURE__ */ new Map();
195
+ for (const [modulePath, chunk] of Object.entries(raw)) {
196
+ const assetInfo = this.toAssetInfo(chunk);
197
+ modules.set(modulePath, assetInfo);
198
+ if (chunk.isEntry) entries.set(modulePath, assetInfo);
199
+ }
200
+ return {
201
+ filePath,
202
+ entries,
203
+ modules,
204
+ raw
205
+ };
206
+ }
207
+ /**
208
+ * 转换为 AssetInfo
209
+ */
210
+ static toAssetInfo(chunk) {
211
+ const preloadModules = this.collectPreloadModules(chunk);
212
+ return {
213
+ js: this.normalizePath(chunk.file),
214
+ css: this.uniqueValues((chunk.css ?? []).map((css) => this.normalizePath(css))),
215
+ preloadModules: this.uniqueValues(preloadModules),
216
+ assets: this.uniqueValues((chunk.assets ?? []).map((asset) => this.normalizePath(asset))),
217
+ isEntry: chunk.isEntry ?? false
218
+ };
219
+ }
220
+ /**
221
+ * 收集预加载模块(包含静态与动态导入),并统一为 manifest key 风格
222
+ */
223
+ static collectPreloadModules(chunk) {
224
+ const imports = chunk.imports ?? [];
225
+ const dynamicImports = chunk.dynamicImports ?? [];
226
+ return [...imports, ...dynamicImports].map((entry) => this.normalizeManifestPath(entry)).filter((entry) => Boolean(entry));
227
+ }
228
+ static uniqueValues(values) {
229
+ return Array.from(new Set(values.filter(Boolean)));
230
+ }
231
+ /**
232
+ * 标准化 manifest 路径(便于跨环境匹配)
233
+ */
234
+ static normalizeManifestPath(path) {
235
+ return path.split("?")[0].split("#")[0].replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
236
+ }
237
+ /**
238
+ * 构建匹配候选(含带/不带前导斜杠、去扩展名)
239
+ */
240
+ static buildMatchVariants(raw) {
241
+ const normalized = this.normalizeManifestPath(raw);
242
+ if (!normalized) return [];
243
+ const noExt = normalized.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/i, "");
244
+ return Array.from(/* @__PURE__ */ new Set([
245
+ normalized,
246
+ `/${normalized}`,
247
+ noExt,
248
+ `/${noExt}`
249
+ ]));
250
+ }
251
+ /**
252
+ * 在 manifest 映射中查找候选匹配 key
253
+ */
254
+ static findModuleKeyByCandidates(source, candidates) {
255
+ const normalizedCandidates = /* @__PURE__ */ new Set();
256
+ for (const candidate of candidates) for (const variant of this.buildMatchVariants(candidate)) normalizedCandidates.add(variant);
257
+ for (const key of source.keys()) for (const variant of this.buildMatchVariants(key)) if (normalizedCandidates.has(variant)) return key;
258
+ }
259
+ /**
260
+ * 解析依赖 key(imports)
261
+ */
262
+ static normalizeImportId(importId) {
263
+ return this.normalizeManifestPath(importId);
264
+ }
265
+ /**
266
+ * 规范化路径
267
+ */
268
+ static normalizePath(path) {
269
+ if (path.startsWith("/") || path.startsWith("http")) return path;
270
+ return `${this.publicPath}${path}`;
271
+ }
272
+ /**
273
+ * 获取已加载的 Manifest
274
+ */
275
+ static getManifest() {
276
+ return this.manifest;
277
+ }
278
+ /**
279
+ * 获取入口资源信息
280
+ */
281
+ static getEntryAssets(entryPath) {
282
+ if (!this.manifest) return null;
283
+ const directKey = this.findModuleKeyByCandidates(this.manifest.entries, [entryPath]);
284
+ if (directKey) return this.manifest.entries.get(directKey) ?? null;
285
+ const normalizedPath = this.normalizeManifestPath(entryPath);
286
+ if (normalizedPath) {
287
+ const normalizedKey = this.findModuleKeyByCandidates(this.manifest.entries, [normalizedPath]);
288
+ if (normalizedKey) return this.manifest.entries.get(normalizedKey) ?? null;
289
+ }
290
+ return null;
291
+ }
292
+ /**
293
+ * 生成入口候选 key(兼容 build 产物和路径写法差异)
294
+ */
295
+ static buildEntryCandidates(entryPath) {
296
+ const candidates = /* @__PURE__ */ new Set();
297
+ const collect = (rawPath) => {
298
+ const normalized = rawPath.replace(/^\/+/, "").trim();
299
+ if (!normalized) return;
300
+ candidates.add(normalized);
301
+ candidates.add(`/${normalized}`);
302
+ const noExt = normalized.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/i, "");
303
+ candidates.add(noExt);
304
+ candidates.add(`/${noExt}`);
305
+ if (noExt.includes(".")) candidates.add(noExt.replace(/\.([^.]+)$/, ""));
306
+ };
307
+ if (entryPath) collect(entryPath);
308
+ else for (const candidate of MANIFEST_ENTRY_CANDIDATES) collect(candidate);
309
+ return Array.from(candidates);
310
+ }
311
+ /**
312
+ * 按候选路径解析入口资源,找不到时回退到最接近入口的 chunk
313
+ */
314
+ static resolveEntryAssets(entryPath) {
315
+ if (!this.manifest) return null;
316
+ for (const candidate of this.buildEntryCandidates(entryPath)) {
317
+ const matched = this.getEntryAssets(candidate);
318
+ if (matched) return matched;
319
+ }
320
+ for (const [key, asset] of this.manifest.entries) if (asset.js && !/vendor|router|polyfill/i.test(key)) return asset;
321
+ for (const [, asset] of this.manifest.entries) if (asset.js) return asset;
322
+ return null;
323
+ }
324
+ /**
325
+ * 获取模块资源信息
326
+ */
327
+ static getModuleAssets(modulePath) {
328
+ if (!this.manifest) return null;
329
+ const candidates = this.buildMatchVariants(modulePath);
330
+ const direct = this.findModuleKeyByCandidates(this.manifest.modules, candidates);
331
+ if (direct) return this.manifest.modules.get(direct) ?? null;
332
+ return this.manifest.modules.get(this.normalizeManifestPath(modulePath)) ?? null;
333
+ }
334
+ /**
335
+ * 生成 HTML 资源标签
336
+ */
337
+ static generateHtmlTags(entryPath) {
338
+ if (!this.manifest) return {
339
+ head: "",
340
+ scripts: ""
341
+ };
342
+ const headTagSet = /* @__PURE__ */ new Set();
343
+ const scriptTagSet = /* @__PURE__ */ new Set();
344
+ const { modules, entries } = this.manifest;
345
+ const processAsset = (asset) => {
346
+ for (const css of asset.css) headTagSet.add(`<link rel="stylesheet" href="${css}" />`);
347
+ for (const preload of asset.preloadModules) {
348
+ const preloadModuleKey = this.findModuleKeyByCandidates(modules, [preload]);
349
+ const module = preloadModuleKey ? modules.get(preloadModuleKey) : null;
350
+ if (module?.js) headTagSet.add(`<link rel="modulepreload" href="${module.js}" />`);
351
+ }
352
+ if (asset.isEntry) scriptTagSet.add(`<script type="module" src="${asset.js}"><\/script>`);
353
+ };
354
+ const entryAsset = this.resolveEntryAssets(entryPath);
355
+ if (entryAsset) processAsset(entryAsset);
356
+ else for (const asset of entries.values()) processAsset(asset);
357
+ return {
358
+ head: Array.from(headTagSet).join("\n "),
359
+ scripts: Array.from(scriptTagSet).join("\n ")
360
+ };
361
+ }
362
+ };
363
+ //#endregion
364
+ //#region src/route/RouteManager.ts
365
+ /** 统一提取 RouteRule 的 mode */
366
+ function toMode(rule) {
367
+ return typeof rule === "string" ? rule : rule.mode;
368
+ }
369
+ var RouteManager = class {
370
+ globalMode;
371
+ overrides;
372
+ defaultRevalidate;
373
+ constructor(config) {
374
+ this.globalMode = config.renderMode;
375
+ this.overrides = config.routes || {};
376
+ this.defaultRevalidate = config.revalidate;
377
+ }
378
+ getRenderMode(path) {
379
+ return resolveRenderMode(path, this.globalMode, this.overrides);
380
+ }
381
+ hasOverride(path) {
382
+ if (this.overrides[path] !== void 0) return true;
383
+ for (const pattern of Object.keys(this.overrides)) if (matchRoutePattern(path, pattern)) return true;
384
+ return false;
385
+ }
386
+ getSSGRoutes() {
387
+ return Object.entries(this.overrides).filter(([pattern, rule]) => toMode(rule) === "ssg" && !pattern.includes("*") && !pattern.includes(":")).map(([pattern]) => pattern);
388
+ }
389
+ getISRRoutes() {
390
+ const result = {};
391
+ for (const [pattern, rule] of Object.entries(this.overrides)) if (toMode(rule) === "isr") result[pattern] = {
392
+ revalidate: typeof rule === "object" && typeof rule.ttl === "number" ? rule.ttl : this.defaultRevalidate,
393
+ priority: .5
394
+ };
395
+ return result;
396
+ }
397
+ shouldCache(path) {
398
+ return this.getRenderMode(path) !== "ssr";
399
+ }
400
+ getPriority(path) {
401
+ if (path === "/") return 1;
402
+ switch (this.getRenderMode(path)) {
403
+ case "ssg": return .8;
404
+ case "isr": return .6;
405
+ case "ssr": return .4;
406
+ default: return .5;
407
+ }
408
+ }
409
+ getChangeFreq(path) {
410
+ switch (this.getRenderMode(path)) {
411
+ case "ssg": return "monthly";
412
+ case "isr": return "daily";
413
+ case "ssr": return "hourly";
414
+ default: return "weekly";
415
+ }
416
+ }
417
+ };
418
+ //#endregion
419
+ //#region src/cache/CacheManager.ts
420
+ var DEFAULT_CONFIG = { strategy: "memory" };
421
+ /**
422
+ * 缓存管理器
423
+ * 统一管理缓存后端,支持 Memory / Redis 策略切换
424
+ *
425
+ * 使用工厂模式创建缓存适配器:
426
+ * - memory: 基于 LRU + TTL 的高性能内存缓存
427
+ * - redis: 基于 ioredis 的分布式缓存,自动降级到内存
428
+ */
429
+ var CacheManager = class {
430
+ adapter;
431
+ logger;
432
+ config;
433
+ constructor(config = {}) {
434
+ this.config = {
435
+ ...DEFAULT_CONFIG,
436
+ ...config
437
+ };
438
+ this.logger = Logger.getInstance();
439
+ this.adapter = this.createAdapter();
440
+ this.logger.info(`缓存后端已初始化: ${this.adapter.name}`);
441
+ }
442
+ /**
443
+ * 工厂方法:根据策略创建适配器
444
+ */
445
+ createAdapter() {
446
+ switch (this.config.strategy) {
447
+ case "redis": return new RedisCacheAdapter(this.config.redis);
448
+ default: return new MemoryCacheAdapter(this.config.memory);
449
+ }
450
+ }
451
+ /**
452
+ * 获取底层适配器
453
+ */
454
+ getAdapter() {
455
+ return this.adapter;
456
+ }
457
+ /**
458
+ * 获取缓存内容
459
+ */
460
+ async get(key) {
461
+ return this.adapter.get(key);
462
+ }
463
+ /**
464
+ * 设置缓存内容
465
+ */
466
+ async set(key, value, options) {
467
+ return this.adapter.set(key, value, options);
468
+ }
469
+ /**
470
+ * 检查是否存在
471
+ */
472
+ async has(key) {
473
+ return this.adapter.has(key);
474
+ }
475
+ /**
476
+ * 删除缓存
477
+ */
478
+ async delete(key) {
479
+ return this.adapter.delete(key);
480
+ }
481
+ /**
482
+ * 清空缓存
483
+ */
484
+ async clear() {
485
+ await this.adapter.clear();
486
+ this.logger.debug("缓存已清空");
487
+ }
488
+ /**
489
+ * 批量获取
490
+ */
491
+ async getMany(keys) {
492
+ return this.adapter.getMany(keys);
493
+ }
494
+ /**
495
+ * 批量设置
496
+ */
497
+ async setMany(entries) {
498
+ return this.adapter.setMany(entries);
499
+ }
500
+ /**
501
+ * 按标签批量失效
502
+ */
503
+ async invalidateByTag(tag) {
504
+ return this.adapter.invalidateByTag(tag);
505
+ }
506
+ /**
507
+ * 连接状态
508
+ */
509
+ isConnected() {
510
+ return this.adapter.isConnected();
511
+ }
512
+ /**
513
+ * 销毁缓存管理器
514
+ */
515
+ async destroy() {
516
+ await this.adapter.destroy();
517
+ this.logger.debug("缓存管理器已销毁");
518
+ }
519
+ };
520
+ //#endregion
521
+ //#region src/plugin/createFontPlugin.ts
522
+ /**
523
+ * createFontPlugin —— 字体优化 Vite 插件(构建时 + dev)
524
+ *
525
+ * 解决三个真实问题:
526
+ * 1. **FOUT/FOIT**:所有 @font-face 强制注入 `font-display: swap`
527
+ * (没设的浏览器会 block ~3s 不渲染文本,严重伤 LCP)
528
+ * 2. **CLS**:自上而下扫 CSS 的 @font-face 链接,注入 <link rel="preload">
529
+ * 到 transformIndexHtml(让浏览器在 HTML parse 时就拉字体)
530
+ * 3. **Google Fonts → 自托管**:可选 `google: ['Inter', 'Noto Sans SC']`
531
+ * 构建时下载到 `public/_/fonts/`,避免运行时第三方阻塞 + GDPR 问题
532
+ *
533
+ * 业界对标:next/font 的子集(不做 size-adjust 推算 fallback metrics —— 那是
534
+ * Capsize 的活,可作为后续增强;当前覆盖 80% 收益场景)。
535
+ */
536
+ function escapeHtmlAttribute(value) {
537
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
538
+ }
539
+ /** 字体格式 → preload 的 type 属性 */
540
+ function fontTypeFromUrl(url) {
541
+ const ext = url.split("?")[0].split("#")[0].split(".").pop()?.toLowerCase();
542
+ return ext ? {
543
+ woff2: "font/woff2",
544
+ woff: "font/woff",
545
+ ttf: "font/ttf",
546
+ otf: "font/otf"
547
+ }[ext] : void 0;
548
+ }
549
+ function createFontPlugin(options = {}) {
550
+ const injectSwap = options.injectSwap !== false;
551
+ const injectPreload = options.injectPreload !== false;
552
+ const weights = options.weights ?? ["400", "700"];
553
+ const outRel = options.outDir ?? "_/fonts";
554
+ let resolved;
555
+ /** 跨文件聚合 —— transform 阶段抓取,transformIndexHtml 注入 preload */
556
+ const preloadUrls = /* @__PURE__ */ new Set();
557
+ const generatedCss = [];
558
+ return {
559
+ name: "isr-engine:font-optimization",
560
+ enforce: "post",
561
+ configResolved(c) {
562
+ resolved = c;
563
+ },
564
+ /** 构建启动前:下载 Google Fonts 到 public/<outDir>/ + 生成本地 @font-face CSS */
565
+ async buildStart() {
566
+ if (!options.google || options.google.length === 0) return;
567
+ const publicDir = resolved.publicDir || path.resolve(resolved.root, "public");
568
+ const fontsDir = path.join(publicDir, outRel);
569
+ await promises.mkdir(fontsDir, { recursive: true });
570
+ for (const family of options.google) {
571
+ const css = await downloadGoogleFontFamily(family, weights, fontsDir, outRel);
572
+ if (css) generatedCss.push(css);
573
+ }
574
+ },
575
+ /** 任何 CSS 文件经过 transform:注入 swap + 收集 preload url */
576
+ transform(code, id) {
577
+ if (!/\.(css|scss|less|sass|styl)(\?|$)/.test(id)) return null;
578
+ let stylesheet;
579
+ try {
580
+ stylesheet = parse(code, { positions: true });
581
+ } catch {
582
+ return null;
583
+ }
584
+ const insertions = [];
585
+ walk(stylesheet, {
586
+ visit: "Atrule",
587
+ enter(rule) {
588
+ if (rule.name.toLowerCase() !== "font-face" || !rule.block) return;
589
+ let hasDisplay = false;
590
+ let firstUrl;
591
+ rule.block.children.forEach((declaration) => {
592
+ if (declaration.type !== "Declaration") return;
593
+ const property = declaration.property.toLowerCase();
594
+ if (property === "font-display") hasDisplay = true;
595
+ if (property === "src" && firstUrl === void 0) walk(declaration.value, {
596
+ visit: "Url",
597
+ enter(url) {
598
+ firstUrl ??= url.value;
599
+ }
600
+ });
601
+ });
602
+ if (firstUrl && injectPreload) preloadUrls.add(firstUrl);
603
+ const close = rule.block.loc ? rule.block.loc.end.offset - 1 : -1;
604
+ if (injectSwap && !hasDisplay && code[close] === "}") insertions.push(close);
605
+ }
606
+ });
607
+ if (insertions.length === 0) return null;
608
+ const parts = [];
609
+ let cursor = 0;
610
+ for (const offset of insertions.sort((a, b) => a - b)) {
611
+ parts.push(code.slice(cursor, offset), "; font-display: swap;\n");
612
+ cursor = offset;
613
+ }
614
+ parts.push(code.slice(cursor));
615
+ return {
616
+ code: parts.join(""),
617
+ map: null
618
+ };
619
+ },
620
+ /** HTML 注入:preload 标签 + 自托管 google fonts 的 @font-face 块 */
621
+ transformIndexHtml(html) {
622
+ const tags = [];
623
+ if (generatedCss.length > 0) tags.push({
624
+ tag: "style",
625
+ attrs: { "data-isr-engine-font": "google" },
626
+ injectTo: "head"
627
+ });
628
+ for (const url of preloadUrls) tags.push({
629
+ tag: "link",
630
+ attrs: {
631
+ rel: "preload",
632
+ href: url,
633
+ as: "font",
634
+ type: fontTypeFromUrl(url) ?? "font/woff2",
635
+ crossorigin: "anonymous"
636
+ },
637
+ injectTo: "head"
638
+ });
639
+ if (tags.length === 0) return html;
640
+ const inject = `${tags.filter((t) => t.tag === "link").map((t) => `<link ${Object.entries(t.attrs ?? {}).map(([k, v]) => `${k}="${escapeHtmlAttribute(v)}"`).join(" ")}>`).join("\n ")}\n ${generatedCss.length > 0 ? `<style data-isr-engine-font="google">${generatedCss.join("\n")}</style>` : ""}\n`;
641
+ return html.replace("</head>", ` ${inject}</head>`);
642
+ }
643
+ };
644
+ }
645
+ /**
646
+ * Google Fonts 家族下载 —— 通过 css2 API 拉 CSS,再下载里面所有 url(.woff2)
647
+ *
648
+ * 不用第三方 SDK:直接 HTTP,避开 GDPR + 锁版本风险
649
+ */
650
+ async function downloadGoogleFontFamily(family, weights, outDir, publicRel) {
651
+ const cssUrl = "https://fonts.googleapis.com/css2?family=" + encodeURIComponent(family).replace(/%20/g, "+") + `:wght@${weights.join(";")}&display=swap`;
652
+ try {
653
+ const cssRes = await fetch(cssUrl, { headers: { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36" } });
654
+ if (!cssRes.ok) {
655
+ console.warn(`[font-plugin] Google Fonts ${family} 拉取失败: ${cssRes.status}`);
656
+ return null;
657
+ }
658
+ let css = await cssRes.text();
659
+ const urls = Array.from(css.matchAll(/url\((https:\/\/[^)]+)\)/g)).map((m) => m[1]);
660
+ for (const u of urls) {
661
+ const r = await fetch(u);
662
+ if (!r.ok) continue;
663
+ const ab = await r.arrayBuffer();
664
+ const buf = Buffer.from(ab);
665
+ const ext = u.split(".").pop()?.split("?")[0] || "woff2";
666
+ const hash = createHash("sha1").update(buf).digest("hex").slice(0, 10);
667
+ const fname = `${family.replace(/\s+/g, "-")}-${hash}.${ext}`;
668
+ const localPath = path.join(outDir, fname);
669
+ await promises.writeFile(localPath, buf);
670
+ const publicUrl = `/${publicRel}/${fname}`;
671
+ css = css.replace(u, publicUrl);
672
+ }
673
+ return css;
674
+ } catch (err) {
675
+ console.warn(`[font-plugin] ${family} 下载异常`, err);
676
+ return null;
677
+ }
678
+ }
679
+ //#endregion
680
+ //#region src/runtime/telemetry.ts
681
+ var currentHandle = null;
682
+ var pendingCalls = [];
683
+ function __setBrowserTelemetryHandle(handle) {
684
+ currentHandle = handle;
685
+ const calls = pendingCalls;
686
+ pendingCalls = [];
687
+ for (const call of calls) try {
688
+ call(handle);
689
+ } catch {}
690
+ }
691
+ function __clearBrowserTelemetryHandle(handle) {
692
+ if (currentHandle === handle) currentHandle = null;
693
+ }
694
+ //#endregion
695
+ //#region src/defaults/runtime/browserObservability.ts
696
+ /**
697
+ * Browser observability bridge.
698
+ *
699
+ * isr-engine owns the browser lifecycle points: app boot, page navigation,
700
+ * Web Vitals, global browser errors and Server Action failures. It deliberately
701
+ * does not import a vendor SDK or a project-specific SDK. The only integration
702
+ * contract is HTTP endpoints resolved from ssr.config.ts runtime.telemetry.
703
+ * Rendering, hydration and navigation must never depend on observability.
704
+ */
705
+ /** Dev-runtime 噪声 —— 由开发工具链自身产生的错误,并非业务问题。
706
+ * Sentry 风格 inbound filter,industry-standard。 */
707
+ var DEFAULT_IGNORE_SOURCE_PATTERNS = [
708
+ /@vite\/client/,
709
+ /@react-refresh/,
710
+ /__vite_ping/,
711
+ /webpack-internal:\/\//,
712
+ /webpack-hmr/,
713
+ /^chrome-extension:\/\//,
714
+ /^moz-extension:\/\//,
715
+ /^safari-extension:\/\//
716
+ ];
717
+ async function installBrowserObservability(options) {
718
+ const cleanups = [];
719
+ let currentUser = options.user;
720
+ const getUser = () => currentUser;
721
+ const analytics = options.analytics === false ? null : createEndpointAnalyticsClient(options, getUser);
722
+ const errorReporter = options.errorReporting === false ? null : createEndpointErrorReporter(options, getUser);
723
+ if (analytics && options.analytics !== false && options.analytics?.webVitals && typeof analytics.installWebVitals === "function") cleanups.push(analytics.installWebVitals());
724
+ if (analytics && options.analytics !== false && options.analytics?.trackInitialPage !== false) analytics.page();
725
+ const globalCleanup = errorReporter?.installGlobalHandlers?.({ captureResourceErrors: options.errorReporting !== false ? options.errorReporting?.captureResourceErrors : void 0 });
726
+ if (globalCleanup) cleanups.push(globalCleanup);
727
+ const handle = {
728
+ track(name, properties, trackOptions) {
729
+ analytics?.track(name, properties, trackOptions);
730
+ },
731
+ capture(error, context) {
732
+ errorReporter?.captureException(error, context);
733
+ },
734
+ measure(name, value, measureOptions) {
735
+ analytics?.measure(name, value, measureOptions);
736
+ },
737
+ page(url) {
738
+ if (!analytics) return;
739
+ analytics.page(typeof url === "string" ? sanitizeUrl(url, options.includeQueryString) : url ? toPagePath(url, options.includeQueryString) : void 0);
740
+ },
741
+ captureActionError(error, actionId) {
742
+ errorReporter?.captureException(error, {
743
+ source: "server-action",
744
+ tags: { actionId }
745
+ });
746
+ },
747
+ setUser(user) {
748
+ currentUser = user ?? void 0;
749
+ },
750
+ flush() {
751
+ return Promise.all([analytics?.flush?.(), errorReporter?.flush?.()]).then(() => void 0);
752
+ },
753
+ shutdown() {
754
+ __clearBrowserTelemetryHandle(handle);
755
+ for (const cleanup of cleanups.splice(0)) cleanup();
756
+ analytics?.shutdown?.();
757
+ errorReporter?.shutdown?.();
758
+ }
759
+ };
760
+ __setBrowserTelemetryHandle(handle);
761
+ return handle;
762
+ }
763
+ function toPagePath(url, includeQueryString) {
764
+ return includeQueryString ? `${url.pathname}${url.search}` : url.pathname;
765
+ }
766
+ function createEndpointAnalyticsClient(options, getUser) {
767
+ const analyticsOptions = options.analytics === false ? void 0 : options.analytics;
768
+ const endpoint = analyticsOptions?.endpoint;
769
+ if (!endpoint) return null;
770
+ const base = createEndpointQueue(options, {
771
+ endpoint,
772
+ batchSize: analyticsOptions?.batchSize ?? 20,
773
+ flushIntervalMs: analyticsOptions?.flushIntervalMs ?? 3e3,
774
+ maxQueueSize: analyticsOptions?.maxQueueSize ?? 500,
775
+ retryBaseDelayMs: analyticsOptions?.retryBaseDelayMs ?? 1e3,
776
+ retryMaxDelayMs: analyticsOptions?.retryMaxDelayMs ?? 3e4,
777
+ sampleRate: analyticsOptions?.sampleRate ?? 1,
778
+ key: "isr_engine_builtin_analytics"
779
+ }, getUser);
780
+ return {
781
+ track(name, properties, trackOptions) {
782
+ base.enqueue({
783
+ name,
784
+ properties: properties ?? {},
785
+ tags: normalizeTags(trackOptions?.tags)
786
+ });
787
+ },
788
+ page(path) {
789
+ base.enqueue({
790
+ name: "page_view",
791
+ properties: {
792
+ path: path ?? currentPath(options.includeQueryString),
793
+ title: isBrowser() && typeof document.title === "string" ? document.title : void 0,
794
+ referrer: isBrowser() && typeof document.referrer === "string" ? document.referrer : void 0
795
+ }
796
+ });
797
+ },
798
+ measure(name, value, measureOptions) {
799
+ if (!Number.isFinite(value)) return;
800
+ base.enqueue({
801
+ name: "metric",
802
+ properties: {
803
+ metric: name,
804
+ value,
805
+ unit: measureOptions?.unit,
806
+ ...measureOptions?.properties ?? {}
807
+ },
808
+ tags: normalizeTags(measureOptions?.tags)
809
+ });
810
+ },
811
+ installWebVitals() {
812
+ return installFallbackWebVitals(base, options.includeQueryString);
813
+ },
814
+ flush() {
815
+ return base.flush();
816
+ },
817
+ shutdown() {
818
+ base.shutdown();
819
+ }
820
+ };
821
+ }
822
+ function createEndpointErrorReporter(options, getUser) {
823
+ const errorOptions = options.errorReporting === false ? void 0 : options.errorReporting;
824
+ const endpoint = errorOptions?.endpoint;
825
+ if (!endpoint) return null;
826
+ const base = createEndpointQueue(options, {
827
+ endpoint,
828
+ batchSize: errorOptions?.batchSize ?? 10,
829
+ flushIntervalMs: errorOptions?.flushIntervalMs ?? 3e3,
830
+ maxQueueSize: errorOptions?.maxQueueSize ?? 200,
831
+ retryBaseDelayMs: errorOptions?.retryBaseDelayMs ?? 1e3,
832
+ retryMaxDelayMs: errorOptions?.retryMaxDelayMs ?? 3e4,
833
+ sampleRate: errorOptions?.sampleRate ?? 1,
834
+ key: "isr_engine_builtin_errors"
835
+ }, getUser);
836
+ const captureException = (error, context = {}) => {
837
+ const normalized = normalizeError(error);
838
+ base.enqueue({
839
+ message: normalized.message,
840
+ name: normalized.name,
841
+ stack: normalized.stack,
842
+ level: typeof context.level === "string" ? context.level : "error",
843
+ source: typeof context.source === "string" ? context.source : void 0,
844
+ tags: normalizeTags(context.tags),
845
+ extra: isRecord(context.extra) ? context.extra : void 0,
846
+ fingerprint: Array.isArray(context.fingerprint) ? context.fingerprint : void 0
847
+ });
848
+ };
849
+ const ignorePatterns = resolveIgnorePatterns(errorOptions?.ignoreSourcePatterns);
850
+ return {
851
+ captureException,
852
+ installGlobalHandlers(globalOptions = {}) {
853
+ if (!isBrowser()) return () => {};
854
+ const captureResourceErrors = globalOptions.captureResourceErrors !== false;
855
+ const onError = (event) => {
856
+ if (event instanceof ErrorEvent) {
857
+ if (shouldIgnore(ignorePatterns, event.filename, event.error)) return;
858
+ captureException(event.error ?? event.message, {
859
+ source: event.filename,
860
+ extra: {
861
+ lineno: event.lineno,
862
+ colno: event.colno
863
+ }
864
+ });
865
+ return;
866
+ }
867
+ if (!captureResourceErrors) return;
868
+ const target = event.target;
869
+ if (target instanceof HTMLElement) {
870
+ const url = target instanceof HTMLImageElement || target instanceof HTMLScriptElement ? target.src : target instanceof HTMLLinkElement ? target.href : void 0;
871
+ if (shouldIgnore(ignorePatterns, url, void 0)) return;
872
+ captureException("Resource load failed", {
873
+ level: "warning",
874
+ source: target.tagName.toLowerCase(),
875
+ extra: { url: sanitizeUrl(url, options.includeQueryString) }
876
+ });
877
+ }
878
+ };
879
+ const onRejection = (event) => {
880
+ if (shouldIgnore(ignorePatterns, void 0, event.reason)) return;
881
+ captureException(event.reason, { source: "unhandledrejection" });
882
+ };
883
+ window.addEventListener("error", onError, true);
884
+ window.addEventListener("unhandledrejection", onRejection);
885
+ return () => {
886
+ window.removeEventListener("error", onError, true);
887
+ window.removeEventListener("unhandledrejection", onRejection);
888
+ };
889
+ },
890
+ flush() {
891
+ return base.flush();
892
+ },
893
+ shutdown() {
894
+ base.shutdown();
895
+ }
896
+ };
897
+ }
898
+ function createEndpointQueue(options, baseOptions, getUser) {
899
+ const queue = [];
900
+ const sessionId = readOrCreateBrowserId(`${baseOptions.key}_session`);
901
+ const anonymousId = readOrCreateBrowserId(`${baseOptions.key}_anonymous`);
902
+ let timer = null;
903
+ let retryTimer = null;
904
+ let inFlight = false;
905
+ let consecutiveFailures = 0;
906
+ let disposeLifecycleListeners = null;
907
+ const flush = async (flushOptions = {}) => {
908
+ if (queue.length === 0) return;
909
+ if (!flushOptions.beacon && (inFlight || retryTimer !== null)) return;
910
+ const payloads = queue.splice(0);
911
+ const isError = baseOptions.key.includes("errors");
912
+ const body = JSON.stringify({
913
+ app: options.app,
914
+ sentAt: Date.now(),
915
+ [isError ? "reports" : "events"]: payloads
916
+ });
917
+ let shouldDrainAfterSuccess = false;
918
+ inFlight = true;
919
+ try {
920
+ await postJson(baseOptions.endpoint, body, flushOptions.beacon);
921
+ consecutiveFailures = 0;
922
+ shouldDrainAfterSuccess = !flushOptions.beacon && queue.length >= baseOptions.batchSize;
923
+ if (queue.length === 0) clearRetryTimer();
924
+ } catch {
925
+ queue.unshift(...payloads);
926
+ queue.splice(baseOptions.maxQueueSize);
927
+ consecutiveFailures += 1;
928
+ scheduleRetry();
929
+ } finally {
930
+ inFlight = false;
931
+ if (shouldDrainAfterSuccess) flush();
932
+ }
933
+ };
934
+ const enqueue = (payload) => {
935
+ if (baseOptions.sampleRate <= 0) return;
936
+ if (baseOptions.sampleRate < 1 && Math.random() > baseOptions.sampleRate) return;
937
+ queue.push({
938
+ id: createId(baseOptions.key.includes("errors") ? "err" : "evt"),
939
+ app: options.app,
940
+ ts: Date.now(),
941
+ release: options.release,
942
+ environment: options.environment,
943
+ sessionId,
944
+ anonymousId,
945
+ user: getUser(),
946
+ url: currentPath(options.includeQueryString),
947
+ ...payload
948
+ });
949
+ if (queue.length > baseOptions.maxQueueSize) queue.splice(0, queue.length - baseOptions.maxQueueSize);
950
+ if (queue.length >= baseOptions.batchSize) flush();
951
+ };
952
+ const shutdown = () => {
953
+ if (timer !== null) {
954
+ clearInterval(timer);
955
+ timer = null;
956
+ }
957
+ clearRetryTimer();
958
+ disposeLifecycleListeners?.();
959
+ disposeLifecycleListeners = null;
960
+ flush({ beacon: true });
961
+ };
962
+ const scheduleRetry = () => {
963
+ if (!isBrowser() || retryTimer !== null || queue.length === 0) return;
964
+ const base = Math.max(100, baseOptions.retryBaseDelayMs);
965
+ const max = Math.max(base, baseOptions.retryMaxDelayMs);
966
+ const backoff = Math.min(max, base * 2 ** Math.max(0, consecutiveFailures - 1));
967
+ const jitter = Math.floor(backoff * .2 * Math.random());
968
+ retryTimer = window.setTimeout(() => {
969
+ retryTimer = null;
970
+ flush();
971
+ }, backoff + jitter);
972
+ };
973
+ const clearRetryTimer = () => {
974
+ if (retryTimer !== null && isBrowser()) window.clearTimeout(retryTimer);
975
+ retryTimer = null;
976
+ };
977
+ if (isBrowser()) {
978
+ if (baseOptions.flushIntervalMs > 0) timer = window.setInterval(() => void flush(), baseOptions.flushIntervalMs);
979
+ const flushOnPageHide = () => void flush({ beacon: true });
980
+ const onHidden = () => {
981
+ if (document.visibilityState === "hidden") flush({ beacon: true });
982
+ };
983
+ const onOnline = () => void flush();
984
+ window.addEventListener("pagehide", flushOnPageHide);
985
+ window.addEventListener("online", onOnline);
986
+ document.addEventListener("visibilitychange", onHidden);
987
+ disposeLifecycleListeners = () => {
988
+ window.removeEventListener("pagehide", flushOnPageHide);
989
+ window.removeEventListener("online", onOnline);
990
+ document.removeEventListener("visibilitychange", onHidden);
991
+ };
992
+ }
993
+ return {
994
+ enqueue,
995
+ flush,
996
+ shutdown
997
+ };
998
+ }
999
+ function installFallbackWebVitals(base, includeQueryString) {
1000
+ if (!isBrowser() || typeof PerformanceObserver === "undefined") return () => {};
1001
+ const cleanups = [];
1002
+ let cls = 0;
1003
+ let lcp = 0;
1004
+ let inp = 0;
1005
+ let inpEntry;
1006
+ const observe = (type, callback, options = {}) => {
1007
+ try {
1008
+ const observer = new PerformanceObserver((list) => {
1009
+ for (const entry of list.getEntries()) callback(entry);
1010
+ });
1011
+ observer.observe({
1012
+ type,
1013
+ buffered: true,
1014
+ ...options
1015
+ });
1016
+ cleanups.push(() => observer.disconnect());
1017
+ } catch {}
1018
+ };
1019
+ observe("paint", (entry) => {
1020
+ if (entry.name === "first-contentful-paint") base.enqueue({
1021
+ name: "web_vital",
1022
+ properties: createWebVitalPayload("FCP", entry.startTime, includeQueryString, entry)
1023
+ });
1024
+ });
1025
+ observe("largest-contentful-paint", (entry) => {
1026
+ lcp = entry.startTime;
1027
+ });
1028
+ observe("layout-shift", (entry) => {
1029
+ if (entry.hadRecentInput !== true && typeof entry.value === "number") cls += entry.value;
1030
+ });
1031
+ observe("event", (entry) => {
1032
+ if (typeof entry.duration === "number" && typeof entry.interactionId === "number" && entry.interactionId > 0) {
1033
+ if (entry.duration >= inp) {
1034
+ inp = entry.duration;
1035
+ inpEntry = entry;
1036
+ }
1037
+ }
1038
+ }, { durationThreshold: 40 });
1039
+ const flushFinalVitals = () => {
1040
+ if (lcp > 0) base.enqueue({
1041
+ name: "web_vital",
1042
+ properties: createWebVitalPayload("LCP", lcp, includeQueryString)
1043
+ });
1044
+ if (inp > 0) base.enqueue({
1045
+ name: "web_vital",
1046
+ properties: createWebVitalPayload("INP", inp, includeQueryString, inpEntry)
1047
+ });
1048
+ if (cls > 0) base.enqueue({
1049
+ name: "web_vital",
1050
+ properties: createWebVitalPayload("CLS", cls, includeQueryString)
1051
+ });
1052
+ };
1053
+ const nav = performance.getEntriesByType("navigation")[0];
1054
+ if (nav) base.enqueue({
1055
+ name: "web_vital",
1056
+ properties: createWebVitalPayload("TTFB", nav.responseStart, includeQueryString, nav)
1057
+ });
1058
+ const flushIfHidden = () => {
1059
+ if (document.visibilityState === "hidden") flushFinalVitals();
1060
+ };
1061
+ window.addEventListener("pagehide", flushFinalVitals);
1062
+ document.addEventListener("visibilitychange", flushIfHidden);
1063
+ cleanups.push(() => {
1064
+ window.removeEventListener("pagehide", flushFinalVitals);
1065
+ document.removeEventListener("visibilitychange", flushIfHidden);
1066
+ });
1067
+ return () => cleanups.splice(0).forEach((cleanup) => cleanup());
1068
+ }
1069
+ function createWebVitalPayload(name, value, includeQueryString, entry) {
1070
+ const payload = {
1071
+ name,
1072
+ value,
1073
+ href: currentHref(includeQueryString),
1074
+ path: currentPath(includeQueryString),
1075
+ route: currentRoute(),
1076
+ title: isBrowser() && typeof document.title === "string" ? document.title : void 0,
1077
+ navigationType: currentNavigationType(),
1078
+ visibilityState: isBrowser() && typeof document.visibilityState === "string" ? document.visibilityState : void 0,
1079
+ device: currentDevice(),
1080
+ viewport: currentViewport(),
1081
+ connection: currentConnection(),
1082
+ entryType: entry?.entryType,
1083
+ startTime: typeof entry?.startTime === "number" ? entry.startTime : void 0
1084
+ };
1085
+ const target = pickPerformanceTarget(entry);
1086
+ if (target) payload.target = target;
1087
+ if (typeof entry?.interactionId === "number") payload.interactionId = entry.interactionId;
1088
+ return payload;
1089
+ }
1090
+ async function postJson(endpoint, body, beacon) {
1091
+ if (beacon && isBrowser() && typeof navigator.sendBeacon === "function") {
1092
+ const payload = typeof Blob !== "undefined" ? new Blob([body], { type: "application/json" }) : body;
1093
+ if (navigator.sendBeacon(endpoint, payload)) return;
1094
+ }
1095
+ if (typeof fetch !== "function") return;
1096
+ const response = await fetch(endpoint, {
1097
+ method: "POST",
1098
+ headers: { "content-type": "application/json" },
1099
+ body,
1100
+ keepalive: beacon
1101
+ });
1102
+ if (!response.ok) throw new Error(`observability upload failed: ${response.status}`);
1103
+ }
1104
+ function currentPath(includeQueryString) {
1105
+ if (!isBrowser()) return "/";
1106
+ const { pathname, search } = window.location;
1107
+ return includeQueryString ? `${pathname}${search}` : pathname;
1108
+ }
1109
+ function currentHref(includeQueryString) {
1110
+ if (!isBrowser()) return void 0;
1111
+ try {
1112
+ const url = new URL(window.location.href);
1113
+ return includeQueryString ? `${url.origin}${url.pathname}${url.search}` : `${url.origin}${url.pathname}`;
1114
+ } catch {
1115
+ return;
1116
+ }
1117
+ }
1118
+ function currentRoute() {
1119
+ if (!isBrowser()) return void 0;
1120
+ const explicit = document.documentElement?.getAttribute("data-route") ?? document.body?.getAttribute("data-route") ?? void 0;
1121
+ if (explicit) return explicit;
1122
+ const globalRoute = window.__ISR_ENGINE_ROUTE__;
1123
+ return typeof globalRoute === "string" && globalRoute.trim() ? globalRoute : void 0;
1124
+ }
1125
+ function currentNavigationType() {
1126
+ if (!isBrowser() || typeof performance.getEntriesByType !== "function") return void 0;
1127
+ const nav = performance.getEntriesByType("navigation")[0];
1128
+ return typeof nav?.type === "string" ? nav.type : void 0;
1129
+ }
1130
+ function currentDevice() {
1131
+ if (!isBrowser()) return void 0;
1132
+ const uaData = navigator.userAgentData;
1133
+ if (typeof uaData?.mobile === "boolean") return uaData.mobile ? "mobile" : "desktop";
1134
+ const width = window.innerWidth;
1135
+ if (width < 768) return "mobile";
1136
+ if (width < 1180) return "tablet";
1137
+ return "desktop";
1138
+ }
1139
+ function currentViewport() {
1140
+ if (!isBrowser()) return void 0;
1141
+ if (!Number.isFinite(window.innerWidth) || !Number.isFinite(window.innerHeight)) return;
1142
+ return `${window.innerWidth}x${window.innerHeight}`;
1143
+ }
1144
+ function currentConnection() {
1145
+ if (!isBrowser()) return void 0;
1146
+ const connection = navigator.connection;
1147
+ if (!connection?.effectiveType) return void 0;
1148
+ return connection.saveData ? `${connection.effectiveType}:save-data` : connection.effectiveType;
1149
+ }
1150
+ function pickPerformanceTarget(entry) {
1151
+ if (typeof Element === "undefined") return void 0;
1152
+ const target = entry?.target;
1153
+ if (!(target instanceof Element)) return void 0;
1154
+ return toElementSelector(target);
1155
+ }
1156
+ function toElementSelector(element) {
1157
+ const tag = element.tagName.toLowerCase();
1158
+ const id = element.id ? `#${cssEscape(element.id)}` : "";
1159
+ const testId = element.getAttribute("data-testid");
1160
+ if (testId) return `${tag}[data-testid="${cssEscape(testId)}"]`;
1161
+ return `${tag}${id}${typeof element.className === "string" ? element.className.split(/\s+/).filter(Boolean).slice(0, 2).map((item) => `.${cssEscape(item)}`).join("") : ""}` || tag;
1162
+ }
1163
+ function cssEscape(value) {
1164
+ if (typeof CSS !== "undefined" && typeof CSS.escape === "function") return CSS.escape(value);
1165
+ return value.replace(/["\\]/g, "\\$&");
1166
+ }
1167
+ function sanitizeUrl(url, includeQueryString) {
1168
+ if (!url) return void 0;
1169
+ if (includeQueryString) return url;
1170
+ try {
1171
+ const parsed = new URL(url, isBrowser() ? window.location.origin : "http://localhost");
1172
+ return parsed.origin === "http://localhost" && !/^https?:\/\//i.test(url) ? parsed.pathname : `${parsed.origin}${parsed.pathname}`;
1173
+ } catch {
1174
+ return url.split("?")[0]?.split("#")[0];
1175
+ }
1176
+ }
1177
+ function isBrowser() {
1178
+ return typeof window !== "undefined" && typeof document !== "undefined";
1179
+ }
1180
+ function createId(prefix) {
1181
+ return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1182
+ }
1183
+ function readOrCreateBrowserId(key) {
1184
+ if (!isBrowser()) return createId("runtime");
1185
+ try {
1186
+ const existing = window.localStorage.getItem(key);
1187
+ if (existing) return existing;
1188
+ const next = createId("runtime");
1189
+ window.localStorage.setItem(key, next);
1190
+ return next;
1191
+ } catch {
1192
+ return createId("runtime");
1193
+ }
1194
+ }
1195
+ /** 解析 ignoreSourcePatterns 选项 —— false 关闭过滤;数组与默认合并;缺省走默认。 */
1196
+ function resolveIgnorePatterns(custom) {
1197
+ if (custom === false) return [];
1198
+ if (Array.isArray(custom)) return [...DEFAULT_IGNORE_SOURCE_PATTERNS, ...custom];
1199
+ return DEFAULT_IGNORE_SOURCE_PATTERNS;
1200
+ }
1201
+ /** 判断错误是否来自 dev-runtime 等噪声源。
1202
+ * 命中 ignorePatterns 任一 → 丢弃。检查 source URL + error.stack 两条。 */
1203
+ function shouldIgnore(ignorePatterns, source, reason) {
1204
+ if (ignorePatterns.length === 0) return false;
1205
+ if (typeof source === "string") {
1206
+ for (const re of ignorePatterns) if (re.test(source)) return true;
1207
+ }
1208
+ if (reason && typeof reason === "object" && "stack" in reason) {
1209
+ const stack = reason.stack;
1210
+ if (typeof stack === "string") {
1211
+ for (const re of ignorePatterns) if (re.test(stack)) return true;
1212
+ }
1213
+ }
1214
+ if (typeof reason === "string") {
1215
+ for (const re of ignorePatterns) if (re.test(reason)) return true;
1216
+ }
1217
+ return false;
1218
+ }
1219
+ function normalizeError(error) {
1220
+ if (error instanceof Error) return {
1221
+ message: error.message,
1222
+ name: error.name,
1223
+ stack: error.stack
1224
+ };
1225
+ if (typeof error === "string") return { message: error };
1226
+ try {
1227
+ return { message: JSON.stringify(error) };
1228
+ } catch {
1229
+ return { message: String(error) };
1230
+ }
1231
+ }
1232
+ function isRecord(value) {
1233
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1234
+ }
1235
+ function normalizeTags(tags) {
1236
+ if (!tags) return void 0;
1237
+ const normalized = {};
1238
+ for (const [key, value] of Object.entries(tags)) {
1239
+ if (value === void 0 || value === null) continue;
1240
+ normalized[key] = String(value);
1241
+ }
1242
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
1243
+ }
1244
+ //#endregion
1245
+ //#region src/metrics/MetricsCollector.ts
1246
+ /** 滑动窗口大小 (保留最近 N 条请求记录用于百分位计算) */
1247
+ var WINDOW_SIZE = 1e4;
1248
+ var MetricsCollector = class MetricsCollector {
1249
+ static instance;
1250
+ startedAt = Date.now();
1251
+ totalRequests = 0;
1252
+ successRequests = 0;
1253
+ errorRequests = 0;
1254
+ cacheHits = 0;
1255
+ cacheMisses = 0;
1256
+ totalResponseTime = 0;
1257
+ renderModeBreakdown = {};
1258
+ /** 滑动窗口:用于计算百分位 */
1259
+ recentResponseTimes = [];
1260
+ constructor() {}
1261
+ static getInstance() {
1262
+ if (!MetricsCollector.instance) MetricsCollector.instance = new MetricsCollector();
1263
+ return MetricsCollector.instance;
1264
+ }
1265
+ /**
1266
+ * 重置所有指标 (用于测试)
1267
+ */
1268
+ reset() {
1269
+ this.startedAt = Date.now();
1270
+ this.totalRequests = 0;
1271
+ this.successRequests = 0;
1272
+ this.errorRequests = 0;
1273
+ this.cacheHits = 0;
1274
+ this.cacheMisses = 0;
1275
+ this.totalResponseTime = 0;
1276
+ this.renderModeBreakdown = {};
1277
+ this.recentResponseTimes = [];
1278
+ }
1279
+ /**
1280
+ * 记录一次请求
1281
+ */
1282
+ record(record) {
1283
+ this.totalRequests++;
1284
+ this.totalResponseTime += record.responseTime;
1285
+ if (record.statusCode >= 200 && record.statusCode < 400) this.successRequests++;
1286
+ else this.errorRequests++;
1287
+ if (record.cacheHit) this.cacheHits++;
1288
+ else this.cacheMisses++;
1289
+ const mode = record.renderMode || "unknown";
1290
+ this.renderModeBreakdown[mode] = (this.renderModeBreakdown[mode] || 0) + 1;
1291
+ this.recentResponseTimes.push(record.responseTime);
1292
+ if (this.recentResponseTimes.length > WINDOW_SIZE) this.recentResponseTimes.shift();
1293
+ }
1294
+ /**
1295
+ * 获取当前指标快照
1296
+ */
1297
+ getSnapshot() {
1298
+ const now = Date.now();
1299
+ const memUsage = process.memoryUsage();
1300
+ const sorted = [...this.recentResponseTimes].sort((a, b) => a - b);
1301
+ return {
1302
+ startedAt: this.startedAt,
1303
+ uptime: now - this.startedAt,
1304
+ totalRequests: this.totalRequests,
1305
+ successRequests: this.successRequests,
1306
+ errorRequests: this.errorRequests,
1307
+ successRate: this.totalRequests > 0 ? Number((this.successRequests / this.totalRequests * 100).toFixed(1)) : 0,
1308
+ avgResponseTime: this.totalRequests > 0 ? Math.round(this.totalResponseTime / this.totalRequests) : 0,
1309
+ p50ResponseTime: this.percentile(sorted, .5),
1310
+ p95ResponseTime: this.percentile(sorted, .95),
1311
+ p99ResponseTime: this.percentile(sorted, .99),
1312
+ cacheHitRate: this.cacheHits + this.cacheMisses > 0 ? Number((this.cacheHits / (this.cacheHits + this.cacheMisses) * 100).toFixed(1)) : 0,
1313
+ renderModeBreakdown: { ...this.renderModeBreakdown },
1314
+ memoryUsageMB: Number((memUsage.rss / (1024 * 1024)).toFixed(1)),
1315
+ heapUsedMB: Number((memUsage.heapUsed / (1024 * 1024)).toFixed(1))
1316
+ };
1317
+ }
1318
+ /**
1319
+ * 计算百分位值
1320
+ */
1321
+ percentile(sorted, p) {
1322
+ if (sorted.length === 0) return 0;
1323
+ const index = Math.ceil(sorted.length * p) - 1;
1324
+ return sorted[Math.max(0, index)];
1325
+ }
1326
+ /**
1327
+ * 返回 JSON 格式的指标 (可用于 /metrics API 端点)
1328
+ */
1329
+ toJSON() {
1330
+ return this.getSnapshot();
1331
+ }
1332
+ };
1333
+ //#endregion
1334
+ //#region src/plugin/createAutomaticImagePlugin.ts
1335
+ function createAutomaticImagePlugin(root, inlineConfig) {
1336
+ let image;
1337
+ return {
1338
+ name: "isr-engine:automatic-images",
1339
+ async configResolved(config) {
1340
+ if (config.plugins.some((plugin) => plugin.name === "isr-engine:image-optimization")) return;
1341
+ image = createImagePlugin(resolveImageOptions((Object.keys(inlineConfig).length ? inlineConfig : await loadConfig({ cwd: root })).runtime?.images));
1342
+ const hook = image.configResolved;
1343
+ if (typeof hook === "function") await hook.call(this, config);
1344
+ },
1345
+ configureServer(server) {
1346
+ const hook = image?.configureServer;
1347
+ if (typeof hook === "function") return hook.call(this, server);
1348
+ },
1349
+ configurePreviewServer(server) {
1350
+ const hook = image?.configurePreviewServer;
1351
+ if (typeof hook === "function") return hook.call(this, server);
1352
+ }
1353
+ };
1354
+ }
1355
+ var TRANSPORT_QUERY_KEYS = /* @__PURE__ */ new Set([
1356
+ "direct",
1357
+ "t",
1358
+ "v",
1359
+ "import",
1360
+ "__isr_engine_style_generation"
1361
+ ]);
1362
+ var UNRESERVED_PATH_BYTE$1 = /^[A-Za-z\d._~-]$/;
1363
+ function canonicalizePathname(pathname) {
1364
+ return pathname.replace(/%([\da-f]{2})/gi, (_encoded, hex) => {
1365
+ const decoded = String.fromCharCode(Number.parseInt(hex, 16));
1366
+ return UNRESERVED_PATH_BYTE$1.test(decoded) ? decoded : `%${hex.toUpperCase()}`;
1367
+ });
1368
+ }
1369
+ function canonicalUrl(value, baseUrl) {
1370
+ const url = new URL(value, baseUrl);
1371
+ for (const key of TRANSPORT_QUERY_KEYS) url.searchParams.delete(key);
1372
+ url.searchParams.sort();
1373
+ return url;
1374
+ }
1375
+ function canonicalizeDevStyleSemanticQuery(value, baseUrl = "http://isr-engine.local/") {
1376
+ return canonicalUrl(value, baseUrl).search;
1377
+ }
1378
+ function canonicalizeDevStyleId(value, baseUrl = "http://isr-engine.local/") {
1379
+ const url = canonicalUrl(value, baseUrl);
1380
+ return `${canonicalizePathname(url.pathname)}${url.search}`;
1381
+ }
1382
+ //#endregion
1383
+ //#region src/plugin/transformDevCssModule.ts
1384
+ var STYLESHEET_URL$1 = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:[?#]|$)/i;
1385
+ function hasDirectQuery$1(value) {
1386
+ const queryStart = value.indexOf("?");
1387
+ if (queryStart === -1) return false;
1388
+ const hashStart = value.indexOf("#", queryStart);
1389
+ return new URLSearchParams(value.slice(queryStart + 1, hashStart === -1 ? void 0 : hashStart)).has("direct");
1390
+ }
1391
+ function isViteClientSpecifier(value) {
1392
+ return /(?:^|\/)@vite\/client(?:[?#]|$)/.test(value);
1393
+ }
1394
+ function isCallToBinding(node, binding) {
1395
+ return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === binding;
1396
+ }
1397
+ function isImportMetaHot(node) {
1398
+ return ts.isPropertyAccessExpression(node) && node.name.text === "hot" && ts.isMetaProperty(node.expression) && node.expression.keywordToken === ts.SyntaxKind.ImportKeyword && node.expression.name.text === "meta";
1399
+ }
1400
+ function isImportMetaHotInternalAccess(node) {
1401
+ if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node) || !isImportMetaHot(node.expression)) return false;
1402
+ return ts.isPropertyAccessExpression(node) ? node.name.text === "_internal" : node.argumentExpression !== void 0 && ts.isStringLiteral(node.argumentExpression) && node.argumentExpression.text === "_internal";
1403
+ }
1404
+ function isCanonicalImportMetaHotInternal(node) {
1405
+ return ts.isPropertyAccessExpression(node) && isImportMetaHotInternalAccess(node);
1406
+ }
1407
+ function isNamespaceMutatorAccess(node, namespaceBindings) {
1408
+ if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node) || !ts.isIdentifier(node.expression) || !namespaceBindings.has(node.expression.text)) return false;
1409
+ const propertyName = ts.isPropertyAccessExpression(node) ? node.name.text : ts.isStringLiteral(node.argumentExpression) ? node.argumentExpression.text : void 0;
1410
+ return propertyName === "updateStyle" || propertyName === "removeStyle";
1411
+ }
1412
+ function collectViteStyleBindings(source) {
1413
+ const bindings = {
1414
+ hasEvidence: false,
1415
+ updateStyleBindings: [],
1416
+ removeStyleBindings: [],
1417
+ supportedInternalAccesses: /* @__PURE__ */ new Set(),
1418
+ unsupportedMutatorAccesses: []
1419
+ };
1420
+ const addBinding = (name, declaration) => {
1421
+ bindings.hasEvidence = true;
1422
+ bindings[`${name}Bindings`].push({
1423
+ name: declaration.text,
1424
+ declaration
1425
+ });
1426
+ };
1427
+ const namespaceBindings = /* @__PURE__ */ new Set();
1428
+ for (const statement of source.statements) {
1429
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && isViteClientSpecifier(statement.moduleSpecifier.text)) {
1430
+ const namedBindings = statement.importClause?.namedBindings;
1431
+ if (namedBindings !== void 0 && ts.isNamespaceImport(namedBindings)) {
1432
+ namespaceBindings.add(namedBindings.name.text);
1433
+ continue;
1434
+ }
1435
+ if (namedBindings === void 0 || !ts.isNamedImports(namedBindings)) continue;
1436
+ for (const specifier of namedBindings.elements) {
1437
+ const importedName = specifier.propertyName?.text ?? specifier.name.text;
1438
+ if (importedName === "updateStyle" || importedName === "removeStyle") addBinding(importedName, specifier.name);
1439
+ }
1440
+ continue;
1441
+ }
1442
+ if (!ts.isVariableStatement(statement) || (statement.declarationList.flags & ts.NodeFlags.Const) === 0 || statement.declarationList.declarations.length !== 1) continue;
1443
+ const declaration = statement.declarationList.declarations[0];
1444
+ if (declaration === void 0) continue;
1445
+ const internalAccess = declaration.initializer;
1446
+ if (internalAccess === void 0 || !isCanonicalImportMetaHotInternal(internalAccess)) continue;
1447
+ if (!ts.isObjectBindingPattern(declaration.name) || declaration.name.elements.length !== 2) continue;
1448
+ const extracted = [];
1449
+ for (const element of declaration.name.elements) {
1450
+ if (element.dotDotDotToken !== void 0 || !ts.isIdentifier(element.name)) {
1451
+ extracted.length = 0;
1452
+ break;
1453
+ }
1454
+ extracted.push({
1455
+ importedName: element.propertyName?.getText(source) ?? element.name.text,
1456
+ declaration: element.name
1457
+ });
1458
+ }
1459
+ if (extracted.length !== 2) continue;
1460
+ if (!extracted.some((element) => element.importedName === "updateStyle") || !extracted.some((element) => element.importedName === "removeStyle")) continue;
1461
+ for (const element of extracted) if (element.importedName === "updateStyle" || element.importedName === "removeStyle") addBinding(element.importedName, element.declaration);
1462
+ bindings.supportedInternalAccesses.add(internalAccess);
1463
+ }
1464
+ const visit = (node) => {
1465
+ if (isImportMetaHotInternalAccess(node)) {
1466
+ bindings.hasEvidence = true;
1467
+ if (!bindings.supportedInternalAccesses.has(node)) bindings.unsupportedMutatorAccesses.push(node);
1468
+ }
1469
+ if (isNamespaceMutatorAccess(node, namespaceBindings)) {
1470
+ bindings.hasEvidence = true;
1471
+ bindings.unsupportedMutatorAccesses.push(node);
1472
+ }
1473
+ ts.forEachChild(node, visit);
1474
+ };
1475
+ visit(source);
1476
+ return bindings;
1477
+ }
1478
+ function findPruneCall(statement, removeStyleBinding) {
1479
+ if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) return void 0;
1480
+ const prune = statement.expression;
1481
+ if (!ts.isPropertyAccessExpression(prune.expression) || prune.expression.name.text !== "prune" || !isImportMetaHot(prune.expression.expression) || prune.arguments.length !== 1) return;
1482
+ const callback = prune.arguments[0];
1483
+ if (!ts.isArrowFunction(callback) || !ts.isCallExpression(callback.body)) return void 0;
1484
+ return isCallToBinding(callback.body, removeStyleBinding) && callback.body.arguments.length === 1 ? callback.body : void 0;
1485
+ }
1486
+ function findUpdateStyleCall(statement, updateStyleBinding) {
1487
+ if (!ts.isExpressionStatement(statement)) return void 0;
1488
+ return isCallToBinding(statement.expression, updateStyleBinding) && statement.expression.arguments.length === 2 ? statement.expression : void 0;
1489
+ }
1490
+ function isNonReferenceIdentifier(node) {
1491
+ const parent = node.parent;
1492
+ return ts.isPropertyAccessExpression(parent) && parent.name === node || ts.isPropertyAssignment(parent) && parent.name === node || ts.isBindingElement(parent) && parent.propertyName === node || ts.isImportSpecifier(parent);
1493
+ }
1494
+ function collectMutatorReferences(source, bindings) {
1495
+ const bindingNames = new Set(bindings.map((binding) => binding.name));
1496
+ const declarations = new Set(bindings.map((binding) => binding.declaration));
1497
+ const references = [];
1498
+ const visit = (node) => {
1499
+ if (ts.isIdentifier(node) && bindingNames.has(node.text) && !declarations.has(node) && !isNonReferenceIdentifier(node)) references.push(node);
1500
+ ts.forEachChild(node, visit);
1501
+ };
1502
+ visit(source);
1503
+ return references;
1504
+ }
1505
+ function compatibilityError(id, detail) {
1506
+ return /* @__PURE__ */ new Error(`Vite development CSS wrapper compatibility error for ${id}: ${detail}`);
1507
+ }
1508
+ function staticStringValue(source, expression) {
1509
+ if (ts.isStringLiteral(expression)) return expression.text;
1510
+ if (!ts.isIdentifier(expression)) return void 0;
1511
+ const matches = [];
1512
+ for (const statement of source.statements) {
1513
+ if (!ts.isVariableStatement(statement) || (statement.declarationList.flags & ts.NodeFlags.Const) === 0) continue;
1514
+ for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === expression.text) matches.push(declaration);
1515
+ }
1516
+ const declaration = matches.length === 1 ? matches[0] : void 0;
1517
+ return declaration?.initializer && ts.isStringLiteral(declaration.initializer) ? declaration.initializer.text : void 0;
1518
+ }
1519
+ function transformDevCssModule(code, id, registryId, browserStyleId) {
1520
+ if (!STYLESHEET_URL$1.test(id) || hasDirectQuery$1(id)) return void 0;
1521
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
1522
+ const bindings = collectViteStyleBindings(source);
1523
+ if (!bindings.hasEvidence) return void 0;
1524
+ const exactStyleId = browserStyleId ?? (/^\/(?:src|@fs)\//.test(id) ? id : void 0);
1525
+ if (exactStyleId === void 0) throw compatibilityError(id, "missing an exact browser module URL from the Vite module graph.");
1526
+ if (bindings.unsupportedMutatorAccesses.length > 0) throw compatibilityError(id, "contains unsupported Vite DOM-mutator access.");
1527
+ if (bindings.updateStyleBindings.length !== 1 || bindings.removeStyleBindings.length !== 1) throw compatibilityError(id, "expected one updateStyle and one removeStyle binding.");
1528
+ const updateStyleBinding = bindings.updateStyleBindings[0];
1529
+ const removeStyleBinding = bindings.removeStyleBindings[0];
1530
+ if (updateStyleBinding === void 0 || removeStyleBinding === void 0) throw compatibilityError(id, "expected one updateStyle and one removeStyle binding.");
1531
+ if (updateStyleBinding.name === removeStyleBinding.name) throw compatibilityError(id, "updateStyle and removeStyle must use distinct local bindings.");
1532
+ const updateStyleCalls = source.statements.map((statement) => findUpdateStyleCall(statement, updateStyleBinding.name)).filter((call) => call !== void 0);
1533
+ const removeStyleCalls = source.statements.map((statement) => findPruneCall(statement, removeStyleBinding.name)).filter((call) => call !== void 0);
1534
+ if (updateStyleCalls.length !== 1 || removeStyleCalls.length !== 1) throw compatibilityError(id, "expected exactly one top-level updateStyle call and one import.meta.hot.prune removeStyle callback.");
1535
+ const updateStyleCall = updateStyleCalls[0];
1536
+ const removeStyleCall = removeStyleCalls[0];
1537
+ if (updateStyleCall === void 0 || removeStyleCall === void 0) throw compatibilityError(id, "expected exactly one top-level updateStyle call and one import.meta.hot.prune removeStyle callback.");
1538
+ const removeStyleArgument = removeStyleCall.arguments[0];
1539
+ const updateStyleArgument = updateStyleCall.arguments[0];
1540
+ if (removeStyleArgument === void 0 || updateStyleArgument === void 0) throw compatibilityError(id, "expected the removeStyle callback to receive one stylesheet id.");
1541
+ const updateStyleId = staticStringValue(source, updateStyleArgument);
1542
+ const removeStyleId = staticStringValue(source, removeStyleArgument);
1543
+ if (updateStyleId === void 0 || removeStyleId === void 0 || updateStyleId !== removeStyleId) throw compatibilityError(id, "could not prove one exact stylesheet identity in the wrapper.");
1544
+ const wrapperStyleId = canonicalizeDevStyleId(updateStyleId);
1545
+ const transformedStyleId = canonicalizeDevStyleId(id);
1546
+ const canonicalBrowserStyleId = canonicalizeDevStyleId(exactStyleId);
1547
+ const semanticQueries = [
1548
+ updateStyleId,
1549
+ id,
1550
+ exactStyleId
1551
+ ].map((value) => canonicalizeDevStyleSemanticQuery(value));
1552
+ if (!semanticQueries.every((query) => query === semanticQueries[0])) throw compatibilityError(id, "stylesheet semantic query does not match across identities.");
1553
+ if (wrapperStyleId !== transformedStyleId && wrapperStyleId !== canonicalBrowserStyleId) throw compatibilityError(id, "stylesheet identity in the wrapper does not match the module.");
1554
+ const expectedReferences = /* @__PURE__ */ new Set([updateStyleCall.expression, removeStyleCall.expression]);
1555
+ const references = collectMutatorReferences(source, [updateStyleBinding, removeStyleBinding]);
1556
+ if (references.length !== expectedReferences.size || references.some((reference) => !expectedReferences.has(reference))) throw compatibilityError(id, "contains unsupported additional Vite DOM-mutator references.");
1557
+ const replacements = [{
1558
+ start: updateStyleCall.getStart(source),
1559
+ end: updateStyleCall.getEnd(),
1560
+ value: `__isr_engine_dev_styles.publish(${JSON.stringify(canonicalBrowserStyleId)}, ${updateStyleCall.arguments[1]?.getText(source)})`
1561
+ }, {
1562
+ start: removeStyleCall.getStart(source),
1563
+ end: removeStyleCall.getEnd(),
1564
+ value: `__isr_engine_dev_styles.prune(${JSON.stringify(canonicalBrowserStyleId)})`
1565
+ }];
1566
+ let transformed = code;
1567
+ for (const replacement of replacements.sort((left, right) => right.start - left.start)) transformed = transformed.slice(0, replacement.start) + replacement.value + transformed.slice(replacement.end);
1568
+ return {
1569
+ code: `import { devStyleRegistry as __isr_engine_dev_styles } from ${JSON.stringify(registryId)};\n${transformed}`,
1570
+ map: null
1571
+ };
1572
+ }
1573
+ //#endregion
1574
+ //#region src/defaults/runtime/dev-style-resource-dispatcher.server.ts
1575
+ var PINNED_REACT_DOM_VERSION = "19.3.0-canary-bd6ea412-20260824";
1576
+ function pinnedResourceDispatcher() {
1577
+ const module = ReactDOM;
1578
+ const dispatcher = module.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE?.d;
1579
+ if (module.version !== PINNED_REACT_DOM_VERSION || typeof dispatcher?.S !== "function") throw new Error(`[isr-engine] Development CSS transport requires react-dom ${PINNED_REACT_DOM_VERSION} with the pinned stylesheet resource dispatcher shape.`);
1580
+ return dispatcher;
1581
+ }
1582
+ function assertPinnedDevStyleResourceDispatcher() {
1583
+ pinnedResourceDispatcher();
1584
+ }
1585
+ //#endregion
1586
+ //#region src/plugin/createDevCssHandoffPlugin.ts
1587
+ var VITE_RSC_REMOVE_DUPLICATE_CSS_ID = "virtual:vite-rsc/remove-duplicate-server-css";
1588
+ var DEV_CSS_HANDOFF_RESOLVED_ID = "\0virtual:isr-engine/dev-css-handoff";
1589
+ var DEV_STYLE_REGISTRY_ID = "virtual:isr-engine/dev-style-registry";
1590
+ var DEV_STYLE_REGISTRY_RESOLVED_ID = "\0virtual:isr-engine/dev-style-registry";
1591
+ var VITE_RSC_CSS_RESOLVED_PREFIX = "\0virtual:vite-rsc/css?";
1592
+ var STYLESHEET_URL = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:[?#]|$)/i;
1593
+ var SPECIAL_STYLESHEET_QUERY = /[?&](?:direct|inline|raw|url)(?:[=&]|$)/;
1594
+ var TERMINAL_CLIENT_RESOURCE_QUERY = /[?&](?:worker|sharedworker|raw|url)\b/;
1595
+ var pinnedRscServerRuntimePath;
1596
+ function getPinnedRscServerRuntimePath() {
1597
+ if (pinnedRscServerRuntimePath) return pinnedRscServerRuntimePath;
1598
+ pinnedRscServerRuntimePath = realpathSync(createRequire(typeof import.meta.url === "string" ? import.meta.url : __filename).resolve("@vitejs/plugin-rsc/react/rsc/server"));
1599
+ return pinnedRscServerRuntimePath;
1600
+ }
1601
+ var VITE_HMR_TIMESTAMP_VALUE = /^\d{13}$/;
1602
+ var VITE_DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
1603
+ var DEV_STYLE_GENERATION_VALUE = /^(?:0|[1-9]\d*)$/;
1604
+ var PINNED_VITE_VERSION = "8.1.6";
1605
+ function assertPinnedViteVersion(actualVersion) {
1606
+ if (actualVersion !== PINNED_VITE_VERSION) throw new Error(`[isr-engine] Development CSS lifecycle requires Vite ${PINNED_VITE_VERSION}; detected ${actualVersion}. Install the engine's exact Vite peer version.`);
1607
+ }
1608
+ function applyDevCssLifecycle(_config, environment) {
1609
+ return environment.command === "serve" && environment.isPreview !== true;
1610
+ }
1611
+ function isModuleTransportQueryParameter(parameter) {
1612
+ const separator = parameter.indexOf("=");
1613
+ const key = separator === -1 ? parameter : parameter.slice(0, separator);
1614
+ const value = separator === -1 ? "" : parameter.slice(separator + 1);
1615
+ if (key === "direct" || key === "import") return value === "";
1616
+ if (key === "t") return VITE_HMR_TIMESTAMP_VALUE.test(value);
1617
+ if (key === "v") return VITE_DEP_VERSION_RE.test(`?${parameter}`);
1618
+ if (key !== "__isr_engine_style_generation") return false;
1619
+ if (!DEV_STYLE_GENERATION_VALUE.test(value)) return false;
1620
+ return Number.isSafeInteger(Number(value));
1621
+ }
1622
+ function semanticModuleIdentity(id) {
1623
+ const hashStart = id.indexOf("#");
1624
+ const resource = hashStart === -1 ? id : id.slice(0, hashStart);
1625
+ const hash = hashStart === -1 ? "" : id.slice(hashStart);
1626
+ const queryStart = resource.indexOf("?");
1627
+ if (queryStart === -1) return id;
1628
+ const pathname = resource.slice(0, queryStart);
1629
+ const semanticQuery = resource.slice(queryStart + 1).split("&").filter((parameter) => !isModuleTransportQueryParameter(parameter)).join("&");
1630
+ return `${pathname}${semanticQuery ? `?${semanticQuery}` : ""}${hash}`;
1631
+ }
1632
+ function modulePathname(id) {
1633
+ return id.replace(/[?#].*$/, "");
1634
+ }
1635
+ function moduleSemanticQuery(id) {
1636
+ const semanticId = semanticModuleIdentity(id);
1637
+ const queryStart = semanticId.indexOf("?");
1638
+ if (queryStart === -1) return "";
1639
+ const hashStart = semanticId.indexOf("#", queryStart);
1640
+ return semanticId.slice(queryStart, hashStart === -1 ? void 0 : hashStart);
1641
+ }
1642
+ function browserStyleIdForResolvedModule(server, id) {
1643
+ const moduleGraph = server?.environments.client.moduleGraph;
1644
+ const queryStart = id.indexOf("?");
1645
+ const resolvedPath = queryStart === -1 ? id : id.slice(0, queryStart);
1646
+ const query = queryStart === -1 ? "" : id.slice(queryStart);
1647
+ let mappedId;
1648
+ if (resolvedPath.startsWith("/@fs/") || !server && resolvedPath.startsWith("/src/")) mappedId = canonicalizeDevStyleId(id);
1649
+ else if (server && path.isAbsolute(resolvedPath)) {
1650
+ const normalizedRoot = normalizePath(path.resolve(server.config.root));
1651
+ const normalizedPath = normalizePath(path.resolve(resolvedPath));
1652
+ const relative = normalizePath(path.relative(normalizedRoot, normalizedPath));
1653
+ mappedId = canonicalizeDevStyleId(`${relative !== ".." && !relative.startsWith("../") ? `/${relative}` : `/@fs/${normalizedPath}`}${query}`);
1654
+ }
1655
+ const exactNode = moduleGraph?.getModuleById(id);
1656
+ if (exactNode?.url && !exactNode.url.startsWith("\0")) return canonicalizeDevStyleId(exactNode.url);
1657
+ if (mappedId === void 0) return void 0;
1658
+ const cleanNode = moduleGraph?.getModuleById(modulePathname(id));
1659
+ if (cleanNode?.url && !cleanNode.url.startsWith("\0")) {
1660
+ if (new URL(canonicalizeDevStyleId(cleanNode.url), "http://isr-engine.local/").pathname !== new URL(mappedId, "http://isr-engine.local/").pathname) return void 0;
1661
+ }
1662
+ return mappedId;
1663
+ }
1664
+ function hasUseClientDirective$1(code, id) {
1665
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
1666
+ for (const statement of source.statements) {
1667
+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) return false;
1668
+ if (statement.expression.text === "use client") return true;
1669
+ }
1670
+ return false;
1671
+ }
1672
+ function unsupportedClientProxy(id) {
1673
+ return /* @__PURE__ */ new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc client reference proxy shape in ${id}. Expected the pinned 0.5.34 registerClientReference wrapper.`);
1674
+ }
1675
+ function isPinnedRscServerRuntime(value) {
1676
+ try {
1677
+ const url = new URL(value);
1678
+ if (url.protocol !== "file:") return false;
1679
+ url.search = "";
1680
+ url.hash = "";
1681
+ return realpathSync(fileURLToPath(url)) === getPinnedRscServerRuntimePath();
1682
+ } catch {
1683
+ return false;
1684
+ }
1685
+ }
1686
+ function decodePackageProxyTarget(value) {
1687
+ try {
1688
+ return decodeURIComponent(value).replaceAll("\\", "/");
1689
+ } catch {
1690
+ return;
1691
+ }
1692
+ }
1693
+ var UNRESERVED_PATH_BYTE = /^[A-Za-z\d._~-]$/;
1694
+ var WINDOWS_DRIVE_PATH = /^[A-Za-z]:\//;
1695
+ function canonicalPathSegment(segment) {
1696
+ let result = "";
1697
+ for (let index = 0; index < segment.length;) {
1698
+ const codePoint = segment.codePointAt(index);
1699
+ if (codePoint === void 0) return void 0;
1700
+ const character = String.fromCodePoint(codePoint);
1701
+ if (character === "%") {
1702
+ const hex = segment.slice(index + 1, index + 3);
1703
+ if (!/^[\da-f]{2}$/i.test(hex)) return void 0;
1704
+ const decoded = String.fromCharCode(Number.parseInt(hex, 16));
1705
+ result += UNRESERVED_PATH_BYTE.test(decoded) ? decoded : `%${hex.toUpperCase()}`;
1706
+ index += 3;
1707
+ continue;
1708
+ }
1709
+ if (/^[A-Za-z\d._~:@+-]$/.test(character)) result += character;
1710
+ else result += encodeURIComponent(character).replace(/[!'()*]/g, (value) => `%${value.charCodeAt(0).toString(16).toUpperCase()}`);
1711
+ index += character.length;
1712
+ }
1713
+ return result;
1714
+ }
1715
+ function canonicalFilePath(value) {
1716
+ const normalized = value.replaceAll("\\", "/");
1717
+ const hasDrive = WINDOWS_DRIVE_PATH.test(normalized);
1718
+ if (!(normalized.startsWith("/") || hasDrive)) return void 0;
1719
+ const segments = [];
1720
+ for (const rawSegment of normalized.split("/")) {
1721
+ if (rawSegment === "") continue;
1722
+ const segment = canonicalPathSegment(rawSegment);
1723
+ if (segment === void 0) return void 0;
1724
+ if (segment === ".") continue;
1725
+ if (segment === "..") {
1726
+ if (segments.length === 0 || hasDrive && segments.length === 1) return void 0;
1727
+ segments.pop();
1728
+ continue;
1729
+ }
1730
+ segments.push(segment);
1731
+ }
1732
+ const drive = segments[0];
1733
+ if (hasDrive && drive) {
1734
+ segments[0] = `${drive.charAt(0).toLowerCase()}${drive.slice(1)}`;
1735
+ return segments.join("/");
1736
+ }
1737
+ return `/${segments.join("/")}`;
1738
+ }
1739
+ function filePathFromFsUrl(value) {
1740
+ if (!value.startsWith("/@fs/")) return void 0;
1741
+ const filePath = value.slice(5);
1742
+ return canonicalFilePath(WINDOWS_DRIVE_PATH.test(filePath) ? filePath : `/${filePath}`);
1743
+ }
1744
+ function canonicalModuleFilePath(moduleId) {
1745
+ const cleanId = modulePathname(moduleId);
1746
+ return filePathFromFsUrl(cleanId) ?? canonicalFilePath(cleanId);
1747
+ }
1748
+ function rootRelativeFilePath(root, referenceId) {
1749
+ if (!referenceId.startsWith("/") || referenceId.startsWith("//") || referenceId.includes("\\") || referenceId.startsWith("/@")) return;
1750
+ const canonicalRoot = canonicalFilePath(root);
1751
+ const canonicalReference = canonicalFilePath(referenceId);
1752
+ if (!canonicalRoot || !canonicalReference || referenceId.startsWith("/@fs/")) return void 0;
1753
+ return canonicalFilePath(`${canonicalRoot}/${canonicalReference.slice(1)}`);
1754
+ }
1755
+ function referenceMatchesModule(referenceId, moduleId, root) {
1756
+ const normalizedModuleId = semanticModuleIdentity(moduleId.replaceAll("\\", "/"));
1757
+ const normalizedReferenceId = semanticModuleIdentity(referenceId);
1758
+ if (normalizedModuleId.startsWith("\0")) return normalizedReferenceId === `/@id/__x00__${normalizedModuleId.slice(1)}`;
1759
+ const cleanId = modulePathname(normalizedModuleId);
1760
+ if (normalizedReferenceId.startsWith("/@id/__x00__virtual:vite-rsc/client-in-server-package-proxy/")) {
1761
+ const target = decodePackageProxyTarget(normalizedReferenceId.slice(60));
1762
+ const targetPath = target === void 0 ? void 0 : canonicalModuleFilePath(target);
1763
+ const modulePath = canonicalModuleFilePath(cleanId);
1764
+ return targetPath !== void 0 && modulePath !== void 0 && targetPath === modulePath;
1765
+ }
1766
+ if (moduleSemanticQuery(normalizedReferenceId) !== moduleSemanticQuery(normalizedModuleId)) return false;
1767
+ const moduleFilePath = canonicalModuleFilePath(cleanId);
1768
+ if (!moduleFilePath) return false;
1769
+ const cleanReferenceId = modulePathname(normalizedReferenceId);
1770
+ const fsReference = filePathFromFsUrl(cleanReferenceId);
1771
+ if (fsReference) return moduleFilePath === fsReference;
1772
+ const browserReference = rootRelativeFilePath(root, cleanReferenceId);
1773
+ if (!browserReference) return false;
1774
+ if (cleanId.startsWith("/") && !cleanId.startsWith("/@fs/")) {
1775
+ if (canonicalFilePath(cleanId) === canonicalFilePath(cleanReferenceId)) return true;
1776
+ }
1777
+ return moduleFilePath === browserReference;
1778
+ }
1779
+ function registerClientReferenceCall(expression, runtimeBinding, exportName, moduleId, root) {
1780
+ if (!ts.isCallExpression(expression) || expression.questionDotToken !== void 0 || expression.typeArguments !== void 0 || expression.arguments.length !== 3 || !ts.isPropertyAccessExpression(expression.expression) || expression.expression.questionDotToken !== void 0 || !ts.isIdentifier(expression.expression.expression) || expression.expression.expression.text !== runtimeBinding || expression.expression.name.text !== "registerClientReference" || !isPinnedClientReferenceProxy(expression.arguments[0], exportName) || !ts.isStringLiteral(expression.arguments[1]) || !ts.isStringLiteral(expression.arguments[2]) || expression.arguments[2].text !== exportName || !referenceMatchesModule(expression.arguments[1].text, moduleId, root)) return;
1781
+ return expression.arguments[1].text;
1782
+ }
1783
+ function isPinnedClientReferenceError(node, exportName) {
1784
+ if (!ts.isBinaryExpression(node) || node.operatorToken.kind !== ts.SyntaxKind.PlusToken || !ts.isBinaryExpression(node.left) || node.left.operatorToken.kind !== ts.SyntaxKind.PlusToken) return false;
1785
+ return ts.isStringLiteral(node.left.left) && node.left.left.text === "Unexpectedly client reference export '" && ts.isStringLiteral(node.left.right) && node.left.right.text === exportName && ts.isStringLiteral(node.right) && node.right.text === "' is called on server";
1786
+ }
1787
+ function isPinnedClientReferenceProxy(expression, exportName) {
1788
+ if (!expression || !ts.isArrowFunction(expression) || expression.modifiers !== void 0 || expression.typeParameters !== void 0 || expression.parameters.length !== 0 || expression.type !== void 0 || !ts.isBlock(expression.body) || expression.body.statements.length !== 1) return false;
1789
+ const statement = expression.body.statements[0];
1790
+ if (!statement || !ts.isThrowStatement(statement) || !statement.expression) return false;
1791
+ const error = statement.expression;
1792
+ const message = ts.isNewExpression(error) ? error.arguments?.[0] : void 0;
1793
+ return ts.isNewExpression(error) && ts.isIdentifier(error.expression) && error.expression.text === "Error" && error.typeArguments === void 0 && error.arguments?.length === 1 && message !== void 0 && isPinnedClientReferenceError(message, exportName);
1794
+ }
1795
+ function clientReferenceIdFromProxy(code, id, root) {
1796
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
1797
+ if (source.parseDiagnostics.length > 0) throw unsupportedClientProxy(id);
1798
+ const runtimeImports = source.statements.filter((statement) => ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && isPinnedRscServerRuntime(statement.moduleSpecifier.text) && statement.modifiers === void 0 && statement.importClause?.name === void 0 && statement.importClause?.isTypeOnly === false && statement.importClause?.namedBindings !== void 0 && ts.isNamespaceImport(statement.importClause.namedBindings) && statement.importClause.namedBindings.name.text === "$$ReactServer" && statement.attributes === void 0);
1799
+ if (runtimeImports.length !== 1) throw unsupportedClientProxy(id);
1800
+ const runtimeImport = runtimeImports[0];
1801
+ const runtimeBindings = runtimeImport?.importClause?.namedBindings;
1802
+ if (!runtimeImport || !runtimeBindings || !ts.isNamespaceImport(runtimeBindings)) throw unsupportedClientProxy(id);
1803
+ const runtimeBinding = runtimeBindings.name.text;
1804
+ const referenceIds = /* @__PURE__ */ new Set();
1805
+ const exportNames = /* @__PURE__ */ new Set();
1806
+ for (const statement of source.statements) {
1807
+ if (statement === runtimeImport) continue;
1808
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
1809
+ if (exportNames.has("default")) throw unsupportedClientProxy(id);
1810
+ const referenceId = registerClientReferenceCall(statement.expression, runtimeBinding, "default", id, root);
1811
+ if (!referenceId) throw unsupportedClientProxy(id);
1812
+ referenceIds.add(referenceId);
1813
+ exportNames.add("default");
1814
+ continue;
1815
+ }
1816
+ if (ts.isVariableStatement(statement) && statement.modifiers?.length === 1 && statement.modifiers[0]?.kind === ts.SyntaxKind.ExportKeyword && (statement.declarationList.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === ts.NodeFlags.Const && statement.declarationList.declarations.length === 1) {
1817
+ for (const declaration of statement.declarationList.declarations) {
1818
+ if (!ts.isIdentifier(declaration.name) || exportNames.has(declaration.name.text) || declaration.exclamationToken !== void 0 || declaration.type !== void 0 || !declaration.initializer) throw unsupportedClientProxy(id);
1819
+ const referenceId = registerClientReferenceCall(declaration.initializer, runtimeBinding, declaration.name.text, id, root);
1820
+ if (!referenceId) throw unsupportedClientProxy(id);
1821
+ referenceIds.add(referenceId);
1822
+ exportNames.add(declaration.name.text);
1823
+ }
1824
+ continue;
1825
+ }
1826
+ throw unsupportedClientProxy(id);
1827
+ }
1828
+ const [referenceId] = referenceIds;
1829
+ if (referenceIds.size !== 1 || referenceId === void 0) throw unsupportedClientProxy(id);
1830
+ return referenceId;
1831
+ }
1832
+ async function collectClientReferenceStyles(server, id) {
1833
+ const environment = server.environments.client;
1834
+ const moduleId = semanticModuleIdentity(id);
1835
+ const requestUrl = moduleId.startsWith("\0") ? `/@id/__x00__${moduleId.slice(1)}` : moduleId.startsWith(server.config.root) ? moduleId.slice(server.config.root.length) || "/" : moduleId;
1836
+ await environment.transformRequest(moduleId.startsWith("\0") ? moduleId : requestUrl);
1837
+ const entry = await environment.moduleGraph.getModuleByUrl(requestUrl) ?? environment.moduleGraph.getModuleById(moduleId);
1838
+ if (!entry) throw new Error(`[isr-engine] Could not inspect the client dependency graph for ${id}.`);
1839
+ const visited = /* @__PURE__ */ new Set();
1840
+ const styleIds = /* @__PURE__ */ new Set();
1841
+ const visit = async (module) => {
1842
+ if (visited.has(module)) return;
1843
+ visited.add(module);
1844
+ const transformId = module.id || module.url;
1845
+ if (!transformId) return;
1846
+ await environment.transformRequest(transformId);
1847
+ const transformed = (module.id ? environment.moduleGraph.getModuleById(module.id) : void 0) ?? (module.url ? await environment.moduleGraph.getModuleByUrl(module.url) : void 0) ?? module;
1848
+ for (const dependency of transformed.importedModules) {
1849
+ const dependencyId = dependency.url || dependency.id;
1850
+ if (dependencyId && TERMINAL_CLIENT_RESOURCE_QUERY.test(dependencyId)) continue;
1851
+ if (dependencyId && STYLESHEET_URL.test(dependencyId)) {
1852
+ if (!SPECIAL_STYLESHEET_QUERY.test(dependencyId)) styleIds.add(dependencyId);
1853
+ } else await visit(dependency);
1854
+ }
1855
+ };
1856
+ await visit(entry);
1857
+ return Array.from(styleIds).sort();
1858
+ }
1859
+ function hasDirectQuery(value) {
1860
+ const queryStart = value.indexOf("?");
1861
+ if (queryStart === -1) return false;
1862
+ const hashStart = value.indexOf("#", queryStart);
1863
+ const query = value.slice(queryStart + 1, hashStart === -1 ? void 0 : hashStart);
1864
+ return new URLSearchParams(query).has("direct");
1865
+ }
1866
+ function withDirectQuery(value) {
1867
+ if (!STYLESHEET_URL.test(value) || hasDirectQuery(value)) return value;
1868
+ const hashStart = value.indexOf("#");
1869
+ const resource = hashStart === -1 ? value : value.slice(0, hashStart);
1870
+ const hash = hashStart === -1 ? "" : value.slice(hashStart);
1871
+ return `${resource}${resource.includes("?") ? /[?&]$/.test(resource) ? "" : "&" : "?"}direct${hash}`;
1872
+ }
1873
+ function canonicalizeDevRscStylesheetModule(code, id) {
1874
+ if (!id.startsWith(VITE_RSC_CSS_RESOLVED_PREFIX)) return void 0;
1875
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
1876
+ const replacements = [];
1877
+ const visit = (node) => {
1878
+ if (ts.isStringLiteral(node)) {
1879
+ const value = withDirectQuery(node.text);
1880
+ if (value !== node.text) replacements.push({
1881
+ start: node.getStart(source),
1882
+ end: node.getEnd(),
1883
+ value
1884
+ });
1885
+ }
1886
+ ts.forEachChild(node, visit);
1887
+ };
1888
+ visit(source);
1889
+ if (replacements.length === 0) return void 0;
1890
+ let transformed = code;
1891
+ for (const replacement of replacements.reverse()) transformed = transformed.slice(0, replacement.start) + JSON.stringify(replacement.value) + transformed.slice(replacement.end);
1892
+ return {
1893
+ code: transformed,
1894
+ map: null
1895
+ };
1896
+ }
1897
+ function identifierIs(node, value) {
1898
+ return node !== void 0 && ts.isIdentifier(node) && node.text === value;
1899
+ }
1900
+ function stringIs(node, value) {
1901
+ return node !== void 0 && ts.isStringLiteral(node) && node.text === value;
1902
+ }
1903
+ function propertyName(node) {
1904
+ if (!node) return void 0;
1905
+ return ts.isIdentifier(node) || ts.isStringLiteral(node) ? node.text : void 0;
1906
+ }
1907
+ function isPropertyPath(node, root, ...properties) {
1908
+ let current = node;
1909
+ for (const property of [...properties].reverse()) {
1910
+ if (!ts.isPropertyAccessExpression(current) || current.name.text !== property) return false;
1911
+ current = current.expression;
1912
+ }
1913
+ return identifierIs(current, root);
1914
+ }
1915
+ function isCreateElementCall(node, reactBinding, argumentCount) {
1916
+ return ts.isCallExpression(node) && node.arguments.length === argumentCount && isPropertyPath(node.expression, reactBinding, "createElement");
1917
+ }
1918
+ function isPinnedLinkProps(node, hrefBinding, precedenceBinding) {
1919
+ if (!ts.isObjectLiteralExpression(node) || node.properties.length !== 5) return false;
1920
+ const [key, rel, precedence, href, dataHref] = node.properties;
1921
+ if (!key || !ts.isPropertyAssignment(key) || propertyName(key.name) !== "key" || !ts.isBinaryExpression(key.initializer) || key.initializer.operatorToken.kind !== ts.SyntaxKind.PlusToken || !stringIs(key.initializer.left, "css:") || !identifierIs(key.initializer.right, hrefBinding)) return false;
1922
+ if (!rel || !ts.isPropertyAssignment(rel) || propertyName(rel.name) !== "rel" || !stringIs(rel.initializer, "stylesheet")) return false;
1923
+ if (!precedence || !ts.isSpreadAssignment(precedence)) return false;
1924
+ const condition = precedence.expression;
1925
+ if (!ts.isConditionalExpression(condition) || !identifierIs(condition.condition, precedenceBinding) || !ts.isObjectLiteralExpression(condition.whenTrue) || condition.whenTrue.properties.length !== 1 || !ts.isShorthandPropertyAssignment(condition.whenTrue.properties[0]) || condition.whenTrue.properties[0].name.text !== precedenceBinding || !ts.isObjectLiteralExpression(condition.whenFalse) || condition.whenFalse.properties.length !== 0) return false;
1926
+ if (!href || !ts.isShorthandPropertyAssignment(href) || href.name.text !== hrefBinding || !dataHref || !ts.isPropertyAssignment(dataHref) || propertyName(dataHref.name) !== "data-rsc-css-href" || !identifierIs(dataHref.initializer, hrefBinding)) return false;
1927
+ return true;
1928
+ }
1929
+ function isPinnedResourcesFactory(factory) {
1930
+ const parameterNames = [
1931
+ "React",
1932
+ "deps",
1933
+ "RemoveDuplicateServerCss",
1934
+ "precedence"
1935
+ ];
1936
+ if (factory.parameters.length !== parameterNames.length || !factory.parameters.every((parameter, index) => {
1937
+ const expected = parameterNames[index];
1938
+ return expected !== void 0 && identifierIs(parameter.name, expected);
1939
+ }) || !ts.isBlock(factory.body) || factory.body.statements.length !== 1) return false;
1940
+ const factoryReturn = factory.body.statements[0];
1941
+ if (!factoryReturn || !ts.isReturnStatement(factoryReturn) || !factoryReturn.expression || !ts.isFunctionExpression(factoryReturn.expression) || !identifierIs(factoryReturn.expression.name, "Resources") || factoryReturn.expression.parameters.length !== 0 || factoryReturn.expression.body.statements.length !== 1) return false;
1942
+ const resourcesReturn = factoryReturn.expression.body.statements[0];
1943
+ const resourcesCall = resourcesReturn && ts.isReturnStatement(resourcesReturn) && resourcesReturn.expression && isCreateElementCall(resourcesReturn.expression, "React", 3) ? resourcesReturn.expression : void 0;
1944
+ const [fragment, nullValue, children] = resourcesCall?.arguments ?? [];
1945
+ if (!resourcesCall || !fragment || !isPropertyPath(fragment, "React", "Fragment") || nullValue?.kind !== ts.SyntaxKind.NullKeyword || !children || !ts.isArrayLiteralExpression(children) || children.elements.length !== 2) return false;
1946
+ const [linksSpread, cleanup] = children.elements;
1947
+ if (!linksSpread || !ts.isSpreadElement(linksSpread) || !ts.isCallExpression(linksSpread.expression)) return false;
1948
+ const mapCall = linksSpread.expression;
1949
+ const mapCallback = mapCall.arguments[0];
1950
+ const linkCall = mapCallback && ts.isArrowFunction(mapCallback) && isCreateElementCall(mapCallback.body, "React", 2) ? mapCallback.body : void 0;
1951
+ if (!isPropertyPath(mapCall.expression, "deps", "css", "map") || mapCall.arguments.length !== 1 || !mapCallback || !ts.isArrowFunction(mapCallback) || mapCallback.parameters.length !== 1 || !identifierIs(mapCallback.parameters[0]?.name, "href") || !linkCall || !stringIs(linkCall.arguments[0], "link") || !linkCall.arguments[1] || !isPinnedLinkProps(linkCall.arguments[1], "href", "precedence")) return false;
1952
+ if (!cleanup || !ts.isBinaryExpression(cleanup) || cleanup.operatorToken.kind !== ts.SyntaxKind.AmpersandAmpersandToken || !identifierIs(cleanup.left, "RemoveDuplicateServerCss") || !isCreateElementCall(cleanup.right, "React", 2) || !identifierIs(cleanup.right.arguments[0], "RemoveDuplicateServerCss") || !ts.isObjectLiteralExpression(cleanup.right.arguments[1]) || cleanup.right.arguments[1].properties.length !== 1) return false;
1953
+ const cleanupKey = cleanup.right.arguments[1].properties[0];
1954
+ return cleanupKey !== void 0 && ts.isPropertyAssignment(cleanupKey) && propertyName(cleanupKey.name) === "key" && stringIs(cleanupKey.initializer, "remove-duplicate-css");
1955
+ }
1956
+ function addTransportMediaToPinnedFactory(source, code, factory) {
1957
+ let linkProps;
1958
+ const visit = (node) => {
1959
+ if (ts.isObjectLiteralExpression(node) && isPinnedLinkProps(node, "href", "precedence")) linkProps = node;
1960
+ ts.forEachChild(node, visit);
1961
+ };
1962
+ visit(factory);
1963
+ const lastParameter = factory.parameters[factory.parameters.length - 1];
1964
+ if (!linkProps || !lastParameter) throw new Error("Pinned Resources factory lost its stylesheet transport binding.");
1965
+ const factoryStart = factory.getStart(source);
1966
+ const replacements = [{
1967
+ position: lastParameter.getEnd() - factoryStart,
1968
+ value: ", __isr_engine_transport_media"
1969
+ }, {
1970
+ position: linkProps.getEnd() - factoryStart - 1,
1971
+ value: ",\n media: __isr_engine_transport_media"
1972
+ }].sort((left, right) => right.position - left.position);
1973
+ let factoryCode = code.slice(factoryStart, factory.getEnd());
1974
+ for (const replacement of replacements) factoryCode = factoryCode.slice(0, replacement.position) + replacement.value + factoryCode.slice(replacement.position);
1975
+ return factoryCode;
1976
+ }
1977
+ function isPinnedDependencies(node) {
1978
+ if (!ts.isObjectLiteralExpression(node) || node.properties.length !== 2) return false;
1979
+ const properties = new Map(node.properties.map((property) => [propertyName(property.name), ts.isPropertyAssignment(property) ? property.initializer : void 0]));
1980
+ const js = properties.get("js");
1981
+ const css = properties.get("css");
1982
+ return properties.size === 2 && js !== void 0 && ts.isArrayLiteralExpression(js) && js.elements.every(ts.isStringLiteral) && css !== void 0 && ts.isArrayLiteralExpression(css) && css.elements.every(ts.isStringLiteral);
1983
+ }
1984
+ function defaultImportBinding(statement, source) {
1985
+ if (statement === void 0 || !ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== source || !statement.importClause?.name || statement.importClause.namedBindings) return;
1986
+ return statement.importClause.name.text;
1987
+ }
1988
+ function instrumentDevRscStylesheetModule(code, id, declarationsUrl) {
1989
+ if (!id.startsWith(VITE_RSC_CSS_RESOLVED_PREFIX)) return void 0;
1990
+ if (new URLSearchParams(id.slice(id.indexOf("?") + 1)).get("type") !== "rsc") return void 0;
1991
+ const source = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
1992
+ const resourcesStatement = source.statements.find((statement) => ts.isVariableStatement(statement) && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) === true && statement.declarationList.declarations.some((declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === "Resources"));
1993
+ const initializer = (resourcesStatement?.declarationList.declarations.find((declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === "Resources"))?.initializer;
1994
+ const factory = initializer && ts.isCallExpression(initializer) ? ts.isParenthesizedExpression(initializer.expression) ? initializer.expression.expression : initializer.expression : void 0;
1995
+ const reactBinding = defaultImportBinding(source.statements[0], "react");
1996
+ const cleanupBinding = defaultImportBinding(source.statements[1], VITE_RSC_REMOVE_DUPLICATE_CSS_ID);
1997
+ const depsArgument = initializer && ts.isCallExpression(initializer) ? initializer.arguments[1] : void 0;
1998
+ if (source.statements.length !== 3 || reactBinding === void 0 || cleanupBinding === void 0 || source.statements[2] !== resourcesStatement || !resourcesStatement || resourcesStatement.modifiers?.length !== 1 || resourcesStatement.modifiers[0]?.kind !== ts.SyntaxKind.ExportKeyword || (resourcesStatement.declarationList.flags & ts.NodeFlags.Const) === 0 || resourcesStatement.declarationList.declarations.length !== 1 || !initializer || !ts.isCallExpression(initializer) || initializer.arguments.length !== 4 || factory === void 0 || !ts.isArrowFunction(factory) && !ts.isFunctionExpression(factory) || !isPinnedResourcesFactory(factory) || !identifierIs(initializer.arguments[0], reactBinding) || !depsArgument || !isPinnedDependencies(depsArgument) || !identifierIs(initializer.arguments[2], cleanupBinding) || !(stringIs(initializer.arguments[3], "vite-rsc/importer-resources") || identifierIs(initializer.arguments[3], "undefined"))) throw new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc server stylesheet resource shape in ${id}. Expected the pinned 0.5.34 Resources factory.`);
1999
+ const reactCode = code.slice(initializer.arguments[0].getStart(source), initializer.arguments[0].getEnd());
2000
+ const depsCode = code.slice(initializer.arguments[1].getStart(source), initializer.arguments[1].getEnd());
2001
+ const replacement = `
2002
+ const __isr_engine_create_RscResources = ${addTransportMediaToPinnedFactory(source, code, factory)};
2003
+ export function Resources() {
2004
+ const __isr_engine_RscResources = __isr_engine_create_RscResources(
2005
+ ${reactCode},
2006
+ __isr_engine_prepare_styles(${depsCode}),
2007
+ ${code.slice(initializer.arguments[2].getStart(source), initializer.arguments[2].getEnd())},
2008
+ ${code.slice(initializer.arguments[3].getStart(source), initializer.arguments[3].getEnd())},
2009
+ __isr_engine_get_transport_media(),
2010
+ );
2011
+ return ${reactCode}.createElement(__isr_engine_RscResources);
2012
+ }`;
2013
+ return {
2014
+ code: `import { getDevStyleTransportMedia as __isr_engine_get_transport_media, prepareDevStyleDependencies as __isr_engine_prepare_styles } from ${JSON.stringify(declarationsUrl)};\n` + code.slice(0, resourcesStatement.getStart(source)) + replacement + code.slice(resourcesStatement.getEnd()),
2015
+ map: null
2016
+ };
2017
+ }
2018
+ function createDevCssLifecyclePluginPhases(defaultsDir) {
2019
+ const lifecycleBoundaryPath = path.resolve(defaultsDir, "runtime/dev-css-handoff.client.ts");
2020
+ const registryUrl = pathToFileURL(path.resolve(defaultsDir, "runtime/dev-style-registry.client.ts")).href;
2021
+ const navigationLifecycleUrl = pathToFileURL(path.resolve(defaultsDir, "runtime/dev-style-navigation.client.ts")).href;
2022
+ const declarationsUrl = pathToFileURL(path.resolve(defaultsDir, "runtime/dev-style-declarations.server.ts")).href;
2023
+ const clientReferenceModuleIds = /* @__PURE__ */ new Set();
2024
+ let devServer;
2025
+ const plugins = [
2026
+ {
2027
+ name: "isr:dev-css-handoff",
2028
+ apply: applyDevCssLifecycle,
2029
+ enforce: "pre",
2030
+ configResolved() {
2031
+ assertPinnedViteVersion(version);
2032
+ assertPinnedDevStyleResourceDispatcher();
2033
+ },
2034
+ configureServer(server) {
2035
+ devServer = server;
2036
+ },
2037
+ resolveId(id) {
2038
+ if (id === "virtual:vite-rsc/remove-duplicate-server-css") return DEV_CSS_HANDOFF_RESOLVED_ID;
2039
+ },
2040
+ load(id) {
2041
+ if (id !== "\0virtual:isr-engine/dev-css-handoff") return void 0;
2042
+ const boundary = readFileSync(lifecycleBoundaryPath, "utf8");
2043
+ const directive = "'use client';";
2044
+ if (!boundary.startsWith(directive)) throw new Error("[isr-engine] Development CSS boundary lost its client directive.");
2045
+ if (this.environment.name !== "client") return boundary;
2046
+ return boundary.replace(directive, `${directive}\n\nimport ${JSON.stringify(DEV_STYLE_REGISTRY_ID)};`);
2047
+ },
2048
+ transform(code, id) {
2049
+ if (this?.environment.name === "rsc") {
2050
+ const moduleId = semanticModuleIdentity(id);
2051
+ if (hasUseClientDirective$1(code, id)) clientReferenceModuleIds.add(moduleId);
2052
+ else clientReferenceModuleIds.delete(moduleId);
2053
+ }
2054
+ const canonicalized = canonicalizeDevRscStylesheetModule(code, id);
2055
+ return instrumentDevRscStylesheetModule(canonicalized?.code ?? code, id, declarationsUrl) ?? canonicalized;
2056
+ }
2057
+ },
2058
+ {
2059
+ name: "isr:dev-client-reference-styles",
2060
+ apply: applyDevCssLifecycle,
2061
+ enforce: "post",
2062
+ async transform(code, id) {
2063
+ const moduleId = semanticModuleIdentity(id);
2064
+ if (this.environment.name !== "rsc" || !clientReferenceModuleIds.has(moduleId)) return;
2065
+ if (!devServer) throw new Error("[isr-engine] Development server is unavailable for CSS dependency mapping.");
2066
+ const referenceId = clientReferenceIdFromProxy(code, moduleId, devServer.config.root);
2067
+ const styleIds = await collectClientReferenceStyles(devServer, moduleId);
2068
+ return {
2069
+ code: `import { registerDevClientReferenceStyles as __isr_engine_register_client_styles } from ${JSON.stringify(declarationsUrl)};\n__isr_engine_register_client_styles(${JSON.stringify(referenceId)}, ${JSON.stringify(styleIds)});\n` + code,
2070
+ map: null
2071
+ };
2072
+ }
2073
+ },
2074
+ {
2075
+ name: "isr:dev-style-registry",
2076
+ apply: applyDevCssLifecycle,
2077
+ enforce: "post",
2078
+ resolveId(id) {
2079
+ return id === "virtual:isr-engine/dev-style-registry" ? DEV_STYLE_REGISTRY_RESOLVED_ID : void 0;
2080
+ },
2081
+ load(id) {
2082
+ if (id !== "\0virtual:isr-engine/dev-style-registry") return void 0;
2083
+ if (this.environment.name !== "client") return `
2084
+ export const devStyleRegistry = {
2085
+ publish() {},
2086
+ prune() {},
2087
+ };
2088
+ `;
2089
+ return `
2090
+ "use client";
2091
+ import { getOrCreateDevStyleRegistry } from ${JSON.stringify(registryUrl)};
2092
+ import {
2093
+ completeDevStyleNavigation,
2094
+ registerDevStyleRegistry,
2095
+ } from ${JSON.stringify(navigationLifecycleUrl)};
2096
+
2097
+ export const devStyleRegistry = getOrCreateDevStyleRegistry(document, {
2098
+ onRscCommit: completeDevStyleNavigation,
2099
+ });
2100
+ registerDevStyleRegistry(devStyleRegistry);
2101
+ import.meta.hot?.on('vite:beforeUpdate', () => devStyleRegistry.beginUpdate());
2102
+ import.meta.hot?.on('vite:afterUpdate', () => devStyleRegistry.commitUpdate());
2103
+ import.meta.hot?.on('vite:error', () => devStyleRegistry.abortUpdate());
2104
+ `;
2105
+ },
2106
+ transform(code, id) {
2107
+ return transformDevCssModule(code, id, DEV_STYLE_REGISTRY_ID, browserStyleIdForResolvedModule(devServer, id));
2108
+ }
2109
+ }
2110
+ ];
2111
+ return {
2112
+ beforeRsc: [plugins[0]],
2113
+ afterRsc: [plugins[1], plugins[2]]
2114
+ };
2115
+ }
2116
+ //#endregion
2117
+ //#region src/plugin/createSsgPostBuildPlugin.ts
2118
+ /**
2119
+ * createSsgPostBuildPlugin —— vite 构建结束后自动跑 SSG 预渲染
2120
+ *
2121
+ * 让 `vite build` 成为唯一的构建入口(用户只需在 vite.config.ts 用 createIsrPlugin),
2122
+ * 不再需要 `isr-engine build` 这种 CLI 包一层。
2123
+ *
2124
+ * 实现要点:
2125
+ * - 在 plugin-rsc 的多 pass 构建里,client environment 是最后一轮
2126
+ * - 仅在 client 那一轮的 closeBundle 里跑 SSG(避免重复触发)
2127
+ * - 跑 SSG 需要 dist/rsc/index.js 已就绪 —— plugin-rsc 保证 client 是最后一环
2128
+ */
2129
+ function createSsgPostBuildPlugin(explicitConfig) {
2130
+ let root = process.cwd();
2131
+ async function runSsg() {
2132
+ let userConfig = explicitConfig;
2133
+ if (!userConfig || Object.keys(userConfig).length === 0) userConfig = await loadConfig({ cwd: root });
2134
+ const ssgRoutes = await extractSsgRoutes(userConfig);
2135
+ assertDistinctHtmlRouteIdentities([...ssgRoutes, ...Object.keys(userConfig.routes ?? {})], { allowPatterns: true });
2136
+ if (ssgRoutes.length === 0) return [];
2137
+ const rscDistEntry = path.resolve(root, "dist/rsc/index.js");
2138
+ const clientDir = path.resolve(root, "dist/client");
2139
+ if (!existsSync(rscDistEntry)) {
2140
+ logger$1.warn("[SSG] 未找到 dist/rsc/index.js,跳过 SSG 预生成");
2141
+ return [];
2142
+ }
2143
+ logger$1.info(`[SSG] 预生成 ${ssgRoutes.length} 个路由(${ssgRoutes.join(", ")})...`);
2144
+ const handler = resolveFetchHandler(await import(
2145
+ /* @vite-ignore */
2146
+ pathToFileURL(rscDistEntry).href
2147
+ ));
2148
+ const ssgCfg = userConfig.ssg ?? {};
2149
+ const result = await spiderSsgRoutes({
2150
+ handler,
2151
+ routes: ssgRoutes,
2152
+ outDir: clientDir,
2153
+ options: {
2154
+ concurrency: ssgCfg.concurrent ?? 3,
2155
+ continueOnError: true,
2156
+ requestTimeoutMs: ssgCfg.requestTimeoutMs,
2157
+ maxRetries: ssgCfg.maxRetries,
2158
+ retryBaseDelayMs: ssgCfg.retryBaseDelayMs,
2159
+ failBuildThreshold: ssgCfg.failBuildThreshold
2160
+ }
2161
+ });
2162
+ logger$1.info(`[SSG] 预生成完成: ${result.successful} 成功, ${result.failed} 失败, 共 ${result.total} (失败率 ${(result.failureRate * 100).toFixed(1)}%)`);
2163
+ return ssgRoutes;
2164
+ }
2165
+ /**
2166
+ * 同 build 一并产 dist/spa/index.html ——
2167
+ * 复用 dist/client/ 已有的 client bundle + CSS chunks,触发 entry.tsx 的 SPA 路径
2168
+ * 部署:Nginx error_page 指向此文件,origin 5xx 时浏览器加载即启动 SPA fallback
2169
+ */
2170
+ async function generateSpaShell() {
2171
+ const ssrManifest = path.resolve(root, "dist/ssr/__vite_rsc_assets_manifest.js");
2172
+ const spaDir = path.resolve(root, "dist/spa");
2173
+ if (!existsSync(ssrManifest)) {
2174
+ logger$1.warn("[SPA] 未找到 dist/ssr/__vite_rsc_assets_manifest.js,跳过 SPA shell 生成");
2175
+ return;
2176
+ }
2177
+ const manifest = (await import(
2178
+ /* @vite-ignore */
2179
+ pathToFileURL(ssrManifest).href
2180
+ )).default;
2181
+ const bootstrap = manifest.bootstrapScriptContent ?? "";
2182
+ const cssSet = /* @__PURE__ */ new Set();
2183
+ for (const group of [manifest.clientReferenceDeps, manifest.serverResources]) {
2184
+ if (!group) continue;
2185
+ for (const id of Object.keys(group)) for (const href of group[id].css ?? []) cssSet.add(href);
2186
+ }
2187
+ const html = `<!DOCTYPE html>
2188
+ <html lang="zh-CN">
2189
+ <head>
2190
+ <meta charset="utf-8" />
2191
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2192
+ <title>正在加载…</title>
2193
+ <link rel="icon" type="image/svg+xml" href="/logo.svg" />
2194
+ ${Array.from(cssSet).map((h) => `<link rel="stylesheet" href="${h}" />`).join("\n ")}
2195
+ </head>
2196
+ <body>
2197
+ <script>self.__SPA_MODE__=1;${bootstrap}<\/script>
2198
+ </body>
2199
+ </html>
2200
+ `;
2201
+ await promises.mkdir(spaDir, { recursive: true });
2202
+ await promises.writeFile(path.join(spaDir, "index.html"), html, "utf-8");
2203
+ logger$1.info(`[SPA] dist/spa/index.html 已生成 (${cssSet.size} 个 CSS chunks 注入)`);
2204
+ }
2205
+ return {
2206
+ name: "isr-engine:ssg-post-build",
2207
+ apply: "build",
2208
+ configResolved(resolved) {
2209
+ root = resolved.root;
2210
+ },
2211
+ /**
2212
+ * vite 8 的 buildApp hook —— 在 builder.buildApp() 完成所有环境后调用一次。
2213
+ * 这是跑 SSG 的最佳时机:dist/{rsc,client,ssr}/* 全部就绪,manifest 也已生成。
2214
+ * 比挂在 closeBundle 里要稳定(closeBundle 在每个环境单独触发,且 manifest 不一定 ready)
2215
+ */
2216
+ buildApp: {
2217
+ order: "post",
2218
+ async handler() {
2219
+ const ssgRoutes = await runSsg();
2220
+ await generateSpaShell();
2221
+ await generateStaticCspManifest(path.resolve(root, "dist"), { ssgRoutes });
2222
+ }
2223
+ }
2224
+ };
2225
+ }
2226
+ //#endregion
2227
+ //#region src/plugin/clientObservabilityConfig.ts
2228
+ var DEFAULT_ANALYTICS_PATH = "/api/observability/analytics";
2229
+ var DEFAULT_ERRORS_PATH = "/api/observability/errors";
2230
+ var ANALYTICS_BATCH_SIZE = 20;
2231
+ var ERRORS_BATCH_SIZE = 10;
2232
+ var FLUSH_INTERVAL_MS = 3e3;
2233
+ var ANALYTICS_MAX_QUEUE = 500;
2234
+ var ERRORS_MAX_QUEUE = 200;
2235
+ var RETRY_BASE_DELAY_MS = 1e3;
2236
+ var RETRY_MAX_DELAY_MS = 3e4;
2237
+ /**
2238
+ * Resolve the public browser telemetry config from ssr.config.ts runtime.
2239
+ *
2240
+ * Only this whitelisted shape may be serialized into the client bundle. Never
2241
+ * pass the whole runtime object to the browser because it can contain Redis,
2242
+ * Sentry DSN, private service URLs, and other server-only integration settings.
2243
+ */
2244
+ function resolveClientObservabilityOptions({ runtime, root = process.cwd(), env = process.env }) {
2245
+ const config = runtime?.telemetry;
2246
+ if (config === false) return false;
2247
+ if (!config) return null;
2248
+ const serviceOrigin = runtime?.services?.telemetry ?? runtime?.services?.api ?? "";
2249
+ return {
2250
+ app: config.app ?? readPackageName(root) ?? "isr-engine-app",
2251
+ release: config.release ?? env.VITE_APP_VERSION ?? env.APP_VERSION ?? env.npm_package_version,
2252
+ environment: config.environment ?? env.NODE_ENV ?? env.MODE,
2253
+ includeQueryString: config.includeQueryString,
2254
+ analytics: resolveAnalyticsConfig(config, serviceOrigin),
2255
+ errorReporting: resolveErrorReportingConfig(config, serviceOrigin)
2256
+ };
2257
+ }
2258
+ function resolveAnalyticsConfig(config, serviceOrigin) {
2259
+ if (config.events === false) return false;
2260
+ const events = config.events;
2261
+ return {
2262
+ endpoint: resolveEndpoint(events, serviceOrigin, DEFAULT_ANALYTICS_PATH),
2263
+ sampleRate: events.sampleRate,
2264
+ batchSize: ANALYTICS_BATCH_SIZE,
2265
+ flushIntervalMs: FLUSH_INTERVAL_MS,
2266
+ maxQueueSize: ANALYTICS_MAX_QUEUE,
2267
+ retryBaseDelayMs: RETRY_BASE_DELAY_MS,
2268
+ retryMaxDelayMs: RETRY_MAX_DELAY_MS,
2269
+ webVitals: config.webVitals === false ? false : config.webVitals?.enabled ?? true,
2270
+ trackInitialPage: events.trackInitialPage
2271
+ };
2272
+ }
2273
+ function resolveErrorReportingConfig(config, serviceOrigin) {
2274
+ if (config.errors === false) return false;
2275
+ const errors = config.errors;
2276
+ return {
2277
+ endpoint: resolveEndpoint(errors, serviceOrigin, DEFAULT_ERRORS_PATH),
2278
+ sampleRate: errors.sampleRate,
2279
+ batchSize: ERRORS_BATCH_SIZE,
2280
+ flushIntervalMs: FLUSH_INTERVAL_MS,
2281
+ maxQueueSize: ERRORS_MAX_QUEUE,
2282
+ retryBaseDelayMs: RETRY_BASE_DELAY_MS,
2283
+ retryMaxDelayMs: RETRY_MAX_DELAY_MS,
2284
+ captureResourceErrors: errors.captureResourceErrors
2285
+ };
2286
+ }
2287
+ function resolveEndpoint(options, serviceOrigin, defaultPath) {
2288
+ return joinEndpoint(serviceOrigin, options.endpoint ?? defaultPath);
2289
+ }
2290
+ function joinEndpoint(origin, endpoint) {
2291
+ if (/^https?:\/\//i.test(endpoint)) return endpoint;
2292
+ if (!origin) return endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
2293
+ return `${trimTrailingSlashes(origin)}/${endpoint.replace(/^\/+/, "")}`;
2294
+ }
2295
+ function readPackageName(root) {
2296
+ try {
2297
+ const pkg = JSON.parse(fs.readFileSync(path.resolve(root, "package.json"), "utf8"));
2298
+ return typeof pkg.name === "string" && pkg.name.trim() ? pkg.name : void 0;
2299
+ } catch {
2300
+ return;
2301
+ }
2302
+ }
2303
+ //#endregion
2304
+ //#region src/plugin/createIsrPlugin.ts
2305
+ /**
2306
+ * ISR 插件工厂 —— 组合 @vitejs/plugin-rsc + ISR 缓存中间件
2307
+ *
2308
+ * 真·开箱即用:
2309
+ * import { createIsrPlugin } from './isr-engine';
2310
+ * export default defineConfig({ plugins: [...createIsrPlugin()] });
2311
+ *
2312
+ * 用户**唯一必需的应用代码**:`<root>/src/root.tsx`
2313
+ * - 必须 export `Root({ url: URL })` —— 即应用根 Server Component
2314
+ *
2315
+ * 三个 Vite environment 的入口(client / rsc / ssr)engine 全部内置默认实现:
2316
+ * - 用户不写任何入口文件即可跑起来
2317
+ * - 想覆盖任一个,把同名文件放到 `<root>/src/` 即可(约定优于配置)
2318
+ *
2319
+ * 入口约定(覆盖文件名):
2320
+ * src/entry.tsx —— 客户端水合入口(覆盖默认)
2321
+ * src/entry.server.tsx —— 服务端 RSC handler(覆盖默认)
2322
+ * src/entry.server.ssr.tsx —— SSR 转 HTML 入口(覆盖默认)
2323
+ *
2324
+ * 注:不要再额外注册 @vitejs/plugin-react —— @vitejs/plugin-rsc 已为客户端环境
2325
+ * 内置了 react-refresh 运行时注入与 JSX 处理;重复注册会触发
2326
+ * `Identifier 'RefreshRuntime' has already been declared` 错误。
2327
+ */
2328
+ var logger = Logger.getInstance();
2329
+ var VIRTUAL_ENTRY_IDS = {
2330
+ client: "virtual:isr-engine/client-entry",
2331
+ rsc: "virtual:isr-engine/rsc-entry",
2332
+ runtime: "virtual:isr-engine/runtime-config",
2333
+ clientRuntime: "virtual:isr-engine/client-runtime-config"
2334
+ };
2335
+ var RESOLVED_VIRTUAL_PREFIX = "\0";
2336
+ /**
2337
+ * 三个 environment 的入口文件名约定 —— 用户在 src/ 下放同名文件即覆盖
2338
+ * engine 默认实现
2339
+ */
2340
+ var ENTRY_CONVENTION = {
2341
+ client: "src/entry.tsx",
2342
+ rsc: "src/entry.server.tsx",
2343
+ ssr: "src/entry.server.ssr.tsx"
2344
+ };
2345
+ /** engine 内置默认入口文件名(位于 isr-engine/src/defaults/)*/
2346
+ var ENGINE_DEFAULTS = {
2347
+ client: "entry.tsx",
2348
+ rsc: "entry.server.tsx",
2349
+ ssr: "entry.server.ssr.tsx"
2350
+ };
2351
+ /** 解析 engine defaults 目录的绝对路径(兼容构建产物 dist/ 与源码) */
2352
+ function resolveEngineDefaultsDir() {
2353
+ const here = typeof __dirname === "string" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
2354
+ const candidates = [
2355
+ path.resolve(here, "../src/defaults"),
2356
+ path.resolve(here, "../defaults"),
2357
+ path.resolve(here, "./defaults")
2358
+ ];
2359
+ for (const c of candidates) if (fs.existsSync(c)) return c;
2360
+ throw new Error(`[isr-engine] 找不到 engine defaults 目录(候选:${candidates.join(" / ")})`);
2361
+ }
2362
+ /**
2363
+ * Entry 解析策略:
2364
+ * - client / rsc:永远指向 engine 内置 wrapper;
2365
+ * 用户的可选 src/entry.tsx / src/entry.server.tsx 通过 @app/_*-config 别名
2366
+ * 注入到 wrapper,wrapper 按形状分派(FaaS hooks 或完整 fetch handler)
2367
+ * - ssr:用户提供 src/entry.server.ssr.tsx 时直接用,否则 engine 默认(极少需要覆盖)
2368
+ *
2369
+ * 用户唯一必须提供的应用代码:`<root>/src/app.tsx`(导出 App({url}))
2370
+ */
2371
+ function resolveEntries(root) {
2372
+ const defaultsDir = resolveEngineDefaultsDir();
2373
+ const wrapperPath = (file) => {
2374
+ const abs = path.resolve(defaultsDir, file);
2375
+ if (!fs.existsSync(abs)) throw new Error(`[isr-engine] engine 内置 wrapper 缺失:${abs}(请检查 engine 安装是否完整)`);
2376
+ return abs;
2377
+ };
2378
+ const appPath = path.resolve(root, "src/app.tsx");
2379
+ if (!fs.existsSync(appPath)) throw new Error(`[isr-engine] 找不到应用根组件 src/app.tsx,这是 engine 唯一要求的用户文件。\n请创建 ${appPath} 并 export function App({ url }: { url: URL }) {...}`);
2380
+ const hasUserConfig = (env) => fs.existsSync(path.resolve(root, ENTRY_CONVENTION[env]));
2381
+ const userSsr = path.resolve(root, ENTRY_CONVENTION.ssr);
2382
+ const ssrEntry = fs.existsSync(userSsr) ? userSsr : wrapperPath(ENGINE_DEFAULTS.ssr);
2383
+ return {
2384
+ client: wrapperPath(ENGINE_DEFAULTS.client),
2385
+ rsc: wrapperPath(ENGINE_DEFAULTS.rsc),
2386
+ ssr: ssrEntry,
2387
+ source: {
2388
+ client: hasUserConfig("client") ? "user" : "engine",
2389
+ rsc: hasUserConfig("rsc") ? "user" : "engine",
2390
+ ssr: hasUserConfig("ssr") ? "user" : "engine"
2391
+ }
2392
+ };
2393
+ }
2394
+ /**
2395
+ * 注入两件事:
2396
+ * 1. `@app/*` Vite alias
2397
+ * - `@app/_entry` 特殊指向用户的应用根组件文件(app.tsx 优先 / root.tsx 兼容)
2398
+ * - `@app/<x>` 通用指向 `<root>/src/<x>` —— 给用户自定义文件用
2399
+ *
2400
+ * 2. resolve.dedupe react / react-dom —— engine 默认入口被 plugin-rsc bundle 时,
2401
+ * 可能从 engine 的 node_modules 解析 react,导致用户项目里出现两份 React 实例,
2402
+ * 水合失败(Cannot read properties of null (reading 'useState'))。
2403
+ * 强制 dedupe 让 react 始终从用户项目根解析
2404
+ */
2405
+ /**
2406
+ * 给 client environment 注入 process.* 兜底
2407
+ *
2408
+ * 原因:CJS 库(chalk / signal-exit / supports-color 等)一旦被打包进 client bundle
2409
+ * 会在浏览器报 ReferenceError: process is not defined。
2410
+ * 哪怕这些库是死代码(CSR fallback 路径不实际执行),rolldown 仍会保留它们的 top-level
2411
+ * statement,所以浏览器加载即崩。
2412
+ *
2413
+ * 兜底:仅对 client environment 注入 vite define,把 `process.platform` / `process.env`
2414
+ * 替换为浏览器友好的常量,避免 ReferenceError;不影响 server / rsc / ssr 环境的真实 Node 行为。
2415
+ */
2416
+ /**
2417
+ * engine 拥有的 Vite build/define 默认值与硬约束 —— 消费侧 vite.config.ts 无权覆盖。
2418
+ *
2419
+ * 第一性原理:SSR/ISR 渲染正确性是 engine 的契约(开箱即用),消费侧不该有能力
2420
+ * 通过 vite 配置打破。两类职责合并:
2421
+ *
2422
+ * 1. `config()` 阶段注入 browser-friendly define
2423
+ * CJS 库(chalk / signal-exit / supports-color 等)一旦打进 client bundle
2424
+ * 会在浏览器报 ReferenceError: process is not defined。哪怕是死代码,
2425
+ * rolldown 也保留 top-level statement,浏览器加载即崩。把 process.*
2426
+ * 替换成浏览器友好的常量。
2427
+ *
2428
+ * 2. `configResolved()` 阶段静默 mutate 最终合并后的关键 build 项
2429
+ * configResolved 是 Vite 标准生命周期最后一步,跑在所有用户/插件 config
2430
+ * 合并之后。这里直接改 resolved config —— 消费侧任何 vite.config.ts 写法
2431
+ * 都被无视,构建不报错不警告,engine 静默接管。
2432
+ *
2433
+ * build.cssCodeSplit = true
2434
+ * plugin-rsc 依赖 chunk 级 CSS split 追踪每个 'use client' 组件的 CSS
2435
+ * chunk 依赖。关闭后 clientReferenceDeps[*].css 全空,plugin-rsc native
2436
+ * 自动注入失效,Header / Footer / Logo / Nav 等组件 .module.scss 样式
2437
+ * 丢失。消费侧无权决定此项。
2438
+ */
2439
+ function createBrowserShimPlugin() {
2440
+ return {
2441
+ name: "isr:engine-build-overrides",
2442
+ config(_, { command }) {
2443
+ if (command !== "build") return;
2444
+ const stdMock = "({isTTY:false,write:()=>{},end:()=>{},on:()=>{},getColorDepth:()=>1})";
2445
+ return { define: {
2446
+ "process.platform": "\"browser\"",
2447
+ "process.arch": "\"unknown\"",
2448
+ "process.versions": "({})",
2449
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "production"),
2450
+ "process.stdout": stdMock,
2451
+ "process.stderr": stdMock,
2452
+ "process.argv": "[]"
2453
+ } };
2454
+ },
2455
+ configResolved(config) {
2456
+ const force = (b) => {
2457
+ if (b) b.cssCodeSplit = true;
2458
+ };
2459
+ force(config.build);
2460
+ const envs = config.environments;
2461
+ if (envs) for (const name of Object.keys(envs)) force(envs[name]?.build);
2462
+ }
2463
+ };
2464
+ }
2465
+ function readPackageDependencies(root) {
2466
+ const packageJsonPath = path.resolve(root, "package.json");
2467
+ if (!fs.existsSync(packageJsonPath)) return [];
2468
+ try {
2469
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
2470
+ return Array.from(/* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]));
2471
+ } catch {
2472
+ return [];
2473
+ }
2474
+ }
2475
+ function hasUseClientDirective(filePath) {
2476
+ try {
2477
+ const source = fs.readFileSync(filePath, "utf8").slice(0, 2048);
2478
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, source);
2479
+ return scanner.scan() === ts.SyntaxKind.StringLiteral && (scanner.getTokenText() === "'use client'" || scanner.getTokenText() === "\"use client\"");
2480
+ } catch {
2481
+ return false;
2482
+ }
2483
+ }
2484
+ function detectClientReferenceDependencies(root) {
2485
+ const requireFromRoot = createRequire(path.resolve(root, "package.json"));
2486
+ const result = [];
2487
+ for (const dep of readPackageDependencies(root)) try {
2488
+ if (hasUseClientDirective(requireFromRoot.resolve(dep))) result.push(dep);
2489
+ } catch {}
2490
+ return result;
2491
+ }
2492
+ function createEngineDefaultEntriesPlugin(root, inlineConfig) {
2493
+ const virtualEntryIds = new Set(Object.values(VIRTUAL_ENTRY_IDS));
2494
+ const resolvedVirtualEntryIds = new Set(Object.values(VIRTUAL_ENTRY_IDS).map((id) => `${RESOLVED_VIRTUAL_PREFIX}${id}`));
2495
+ const defaultsDir = resolveEngineDefaultsDir();
2496
+ const fileImport = (relativePath) => JSON.stringify(pathToFileURL(path.resolve(defaultsDir, relativePath)).href);
2497
+ return {
2498
+ name: "isr:engine-default-entries",
2499
+ enforce: "pre",
2500
+ resolveId(id) {
2501
+ if (resolvedVirtualEntryIds.has(id)) return id;
2502
+ if (virtualEntryIds.has(id)) return `${RESOLVED_VIRTUAL_PREFIX}${id}`;
2503
+ return null;
2504
+ },
2505
+ load(id) {
2506
+ if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.client}`) return `
2507
+ import { defineClientEntry } from ${fileImport("runtime/defineClientEntry.tsx")};
2508
+ import userConfig from '@app/_client-config';
2509
+ import runtimeClientConfig from '${VIRTUAL_ENTRY_IDS.clientRuntime}';
2510
+
2511
+ defineClientEntry(mergeClientConfig(runtimeClientConfig ?? {}, userConfig ?? {}));
2512
+
2513
+ function mergeClientConfig(runtimeConfig, userConfig) {
2514
+ return {
2515
+ ...runtimeConfig,
2516
+ ...userConfig,
2517
+ telemetry:
2518
+ Object.prototype.hasOwnProperty.call(userConfig, 'telemetry')
2519
+ ? userConfig.telemetry
2520
+ : runtimeConfig.telemetry,
2521
+ devInspector:
2522
+ Object.prototype.hasOwnProperty.call(userConfig, 'devInspector')
2523
+ ? userConfig.devInspector
2524
+ : runtimeConfig.devInspector,
2525
+ };
2526
+ }
2527
+ `;
2528
+ if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.rsc}`) return `
2529
+ import { defineServerEntry } from ${fileImport("runtime/defineServerEntry.tsx")};
2530
+ import { applyRuntimeToServerHooks } from ${fileImport("runtime/defineSiteHooks.ts")};
2531
+ import { createAutoServerHooks } from 'isr-engine/auto-observability';
2532
+ import userConfig from '@app/_server-config';
2533
+ import runtimeConfig from '${VIRTUAL_ENTRY_IDS.runtime}';
2534
+
2535
+ function hasFetchHandler(x) {
2536
+ return !!x && typeof x.fetch === 'function';
2537
+ }
2538
+
2539
+ const autoHooksPromise = createAutoServerHooks();
2540
+
2541
+ const resolved = hasFetchHandler(userConfig)
2542
+ ? userConfig
2543
+ : (() => {
2544
+ let realHandler = null;
2545
+ let initPromise = null;
2546
+
2547
+ return {
2548
+ async fetch(request) {
2549
+ if (!realHandler) {
2550
+ initPromise ??= (async () => {
2551
+ const auto = await autoHooksPromise;
2552
+ const user = applyRuntimeToServerHooks(userConfig ?? {}, runtimeConfig ?? {});
2553
+ const merged = {
2554
+ ...auto,
2555
+ ...user,
2556
+ beforeRequest: chainBefore(auto.beforeRequest, user.beforeRequest),
2557
+ onResponse: chainResponse(auto.onResponse, user.onResponse),
2558
+ onError: chainError(auto.onError, user.onError),
2559
+ };
2560
+ return defineServerEntry(merged);
2561
+ })();
2562
+ realHandler = await initPromise;
2563
+ }
2564
+ return realHandler.fetch(request);
2565
+ },
2566
+ };
2567
+ })();
2568
+
2569
+ function chainBefore(a, b) {
2570
+ if (!a) return b;
2571
+ if (!b) return a;
2572
+ return async (req, baseline) => {
2573
+ const ax = (await a(req, baseline)) ?? {};
2574
+ const bx = (await b(req, baseline)) ?? {};
2575
+ return { ...ax, ...bx };
2576
+ };
2577
+ }
2578
+
2579
+ function chainResponse(a, b) {
2580
+ if (!a) return b;
2581
+ if (!b) return a;
2582
+ return async (res, ctx) => {
2583
+ await a(res, ctx);
2584
+ await b(res, ctx);
2585
+ };
2586
+ }
2587
+
2588
+ function chainError(a, b) {
2589
+ if (!a) return b;
2590
+ if (!b) return a;
2591
+ return async (err, req, ctx) => {
2592
+ await a(err, req, ctx);
2593
+ await b(err, req, ctx);
2594
+ };
2595
+ }
2596
+
2597
+ export default resolved;
2598
+
2599
+ if (import.meta.hot) {
2600
+ import.meta.hot.accept();
2601
+ }
2602
+ `;
2603
+ if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.runtime}`) {
2604
+ const configPath = path.resolve(root, "ssr.config.ts");
2605
+ if (!fs.existsSync(configPath)) return `export default {};`;
2606
+ return `
2607
+ const configModule = await import(${JSON.stringify(pathToFileURL(configPath).href)});
2608
+ const defaultConfig = configModule.default ?? {};
2609
+ const namedRuntime = configModule['runtime'];
2610
+ export default defaultConfig.runtime ?? namedRuntime ?? {};
2611
+ `;
2612
+ }
2613
+ if (id === `${RESOLVED_VIRTUAL_PREFIX}${VIRTUAL_ENTRY_IDS.clientRuntime}`) return resolveClientRuntimeConfigModule(root, inlineConfig);
2614
+ return null;
2615
+ }
2616
+ };
2617
+ }
2618
+ async function resolveClientRuntimeConfigModule(root, inlineConfig) {
2619
+ const telemetry = resolveClientObservabilityOptions({
2620
+ runtime: (Object.keys(inlineConfig).length > 0 ? inlineConfig : await loadConfig({ cwd: root })).runtime,
2621
+ root
2622
+ });
2623
+ return `export default ${JSON.stringify({ ...telemetry === null ? {} : { telemetry } })};`;
2624
+ }
2625
+ function createAppAliasPlugin(root) {
2626
+ const userSrc = path.resolve(root, "src");
2627
+ const defaultsDir = resolveEngineDefaultsDir();
2628
+ const emptyConfig = path.resolve(defaultsDir, "runtime/empty-config.ts");
2629
+ const emptyRoutes = path.resolve(defaultsDir, "runtime/empty-routes.ts");
2630
+ const appEntry = path.resolve(userSrc, "app.tsx");
2631
+ const appRoutes = path.resolve(userSrc, "routes.tsx");
2632
+ const userOrEmpty = (rel) => {
2633
+ const abs = path.resolve(root, rel);
2634
+ return fs.existsSync(abs) ? abs : emptyConfig;
2635
+ };
2636
+ return {
2637
+ name: "isr:app-alias",
2638
+ enforce: "pre",
2639
+ config() {
2640
+ const clientReferenceDeps = detectClientReferenceDependencies(root);
2641
+ return {
2642
+ resolve: {
2643
+ alias: [
2644
+ {
2645
+ find: "@app/_entry",
2646
+ replacement: appEntry
2647
+ },
2648
+ {
2649
+ find: "@app/_routes",
2650
+ replacement: fs.existsSync(appRoutes) ? appRoutes : emptyRoutes
2651
+ },
2652
+ {
2653
+ find: "@app/_client-config",
2654
+ replacement: userOrEmpty(ENTRY_CONVENTION.client)
2655
+ },
2656
+ {
2657
+ find: "@app/_server-config",
2658
+ replacement: userOrEmpty(ENTRY_CONVENTION.rsc)
2659
+ },
2660
+ {
2661
+ find: "@app/_ssr-config",
2662
+ replacement: userOrEmpty(ENTRY_CONVENTION.ssr)
2663
+ },
2664
+ {
2665
+ find: /^@app\/(.*)$/,
2666
+ replacement: `${userSrc}/$1`
2667
+ }
2668
+ ],
2669
+ dedupe: [
2670
+ "react",
2671
+ "react-dom",
2672
+ "react-server-dom-webpack",
2673
+ "rsc-html-stream"
2674
+ ]
2675
+ },
2676
+ optimizeDeps: {
2677
+ entries: ["src/**/*.{js,jsx,ts,tsx}"],
2678
+ include: [
2679
+ "react",
2680
+ "react/jsx-runtime",
2681
+ "react/jsx-dev-runtime",
2682
+ "react-dom",
2683
+ "react-dom/client",
2684
+ "rsc-html-stream/client"
2685
+ ],
2686
+ exclude: [
2687
+ ...clientReferenceDeps,
2688
+ "isr-engine",
2689
+ "isr-engine/runtime",
2690
+ "@app/_entry",
2691
+ "@app/_routes",
2692
+ "@app/_client-config",
2693
+ "@app/_server-config",
2694
+ "@app/_ssr-config"
2695
+ ]
2696
+ }
2697
+ };
2698
+ }
2699
+ };
2700
+ }
2701
+ function createIsrPlugin(options = {}) {
2702
+ const { config: userConfig = {}, root = process.cwd(), rsc: rscOptions, isrCache: isrCacheOptions } = options;
2703
+ const entries = resolveEntries(root);
2704
+ const fmt = (env) => {
2705
+ if (env === "ssr") return entries.source.ssr === "user" ? `${path.relative(root, entries.ssr)}(用户覆盖)` : "<engine 默认>";
2706
+ return entries.source[env] === "user" ? `<engine wrapper> + ${ENTRY_CONVENTION[env]}(FaaS hooks 已挂载)` : "<engine 默认(无 hooks)>";
2707
+ };
2708
+ logger.info(`🧭 ISR entries:`);
2709
+ logger.info(` client = ${fmt("client")}`);
2710
+ logger.info(` server = ${fmt("rsc")}`);
2711
+ logger.info(` ssr = ${fmt("ssr")}`);
2712
+ const devCssLifecycle = createDevCssLifecyclePluginPhases(resolveEngineDefaultsDir());
2713
+ const plugins = [
2714
+ createEngineDefaultEntriesPlugin(root, userConfig),
2715
+ createAppAliasPlugin(root),
2716
+ createAutomaticImagePlugin(root, userConfig),
2717
+ createDevAssetRequestMiddleware(root),
2718
+ ...devCssLifecycle.beforeRsc,
2719
+ createBrowserShimPlugin()
2720
+ ];
2721
+ if (isrCacheOptions?.enabled !== false) plugins.push(createIsrCacheMiddleware(userConfig, {
2722
+ max: isrCacheOptions?.max,
2723
+ defaultTtlSeconds: isrCacheOptions?.defaultTtlSeconds
2724
+ }));
2725
+ plugins.push(vitePluginRsc({
2726
+ ...rscOptions,
2727
+ entries: {
2728
+ client: VIRTUAL_ENTRY_IDS.client,
2729
+ rsc: VIRTUAL_ENTRY_IDS.rsc,
2730
+ ssr: entries.ssr
2731
+ }
2732
+ }));
2733
+ plugins.push(...devCssLifecycle.afterRsc);
2734
+ plugins.push(createSsgPostBuildPlugin(userConfig));
2735
+ return plugins;
2736
+ }
2737
+ //#endregion
2738
+ export { CacheCleanup, CacheManager, DEFAULT_SCAN_CONFIG, DEFAULT_SEO_CONFIG, FallbackChain, ISREngine, InternalStrategies, LEGACY_SERVER_ACTION_ENDPOINT, Logger, ManifestLoader, MetricsCollector, RedisCacheAdapter, RedisInvalidationBus, RenderModes, RevalidationError, RouteManager, SEOEngine, SERVER_ACTION_ENDPOINT, ServerActionUtils, applyRuntimeToServerHooks, cacheTag, collectTags, createABVariantMiddleware, createAdminIntlLoader, createAdminSeoLoader, createCachedFetcher, createCoherentCacheStore, createFontPlugin, createHybridCacheStore, createISRApp, createImageMiddleware, createImagePlugin, createIsrCacheHandler, createIsrCacheMiddleware, createIsrPlugin, createMemoryCacheStore, createPrometheusMetricsMiddleware, createSEOEngine, createServerAction, defineAdminSiteHooks, defineIsrConfig, defineRuntimeConfig, defineSiteHooks, getCookieHeader, getEnv, getFallbackChain, getI18n, getI18nLocale, getRequestContext, getRouteFallbackChain, getVariant, injectSeoMeta, installBrowserObservability, invalidatorFailuresTotal, invalidatorRunsTotal, isCodeFile, isDev, isProd, isTestFile, loadConfig, matchRoutePattern, mergeSEOConfig, parseComponentFromFile, parseComponents, parseCookieHeader, parseRouteFromFile, parseRoutes, promRegistry, readCookie, readDirRecursive, recordHttpRequest, registerInvalidator, renderPageSeoMeta, requestContext, resolveRenderMode, revalidatePath, revalidateTag, runWithTagStore, scanComponents, scanProject, scanRoutes, serverActionsRegistry, shutdownServer, startAppServer };
2739
+
2740
+ //# sourceMappingURL=isr-engine.js.map