vinext 1.0.0-beta.1 → 1.0.0-beta.3

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 (234) hide show
  1. package/README.md +10 -10
  2. package/dist/build/client-build-config.js +8 -1
  3. package/dist/build/report.d.ts +8 -1
  4. package/dist/build/report.js +12 -2
  5. package/dist/check.js +19 -2
  6. package/dist/cli.js +3 -2
  7. package/dist/config/config-matchers.d.ts +13 -37
  8. package/dist/config/config-matchers.js +35 -122
  9. package/dist/config/next-config.d.ts +15 -5
  10. package/dist/config/next-config.js +7 -1
  11. package/dist/config/request-context.d.ts +14 -0
  12. package/dist/config/request-context.js +26 -0
  13. package/dist/entries/app-browser-entry.d.ts +4 -10
  14. package/dist/entries/app-browser-entry.js +20 -4
  15. package/dist/entries/app-rsc-entry.js +30 -9
  16. package/dist/entries/app-rsc-manifest.js +36 -0
  17. package/dist/entries/pages-client-entry.js +0 -1
  18. package/dist/entries/pages-server-entry.js +13 -5
  19. package/dist/index.js +194 -101
  20. package/dist/init-cloudflare.d.ts +3 -1
  21. package/dist/init-cloudflare.js +59 -5
  22. package/dist/init.d.ts +6 -4
  23. package/dist/init.js +20 -22
  24. package/dist/plugins/extensionless-dynamic-import.js +23 -18
  25. package/dist/plugins/ignore-dynamic-requests.js +3 -1
  26. package/dist/plugins/import-meta-url.js +17 -6
  27. package/dist/plugins/og-assets.js +1 -1
  28. package/dist/plugins/require-context.js +20 -15
  29. package/dist/plugins/transform-cache.d.ts +19 -0
  30. package/dist/plugins/transform-cache.js +36 -0
  31. package/dist/routing/app-route-graph.d.ts +27 -11
  32. package/dist/routing/app-route-graph.js +158 -22
  33. package/dist/routing/app-router.js +12 -6
  34. package/dist/routing/file-matcher.d.ts +11 -22
  35. package/dist/routing/file-matcher.js +21 -33
  36. package/dist/routing/pages-router.js +23 -29
  37. package/dist/routing/route-matching.d.ts +14 -1
  38. package/dist/routing/route-matching.js +13 -1
  39. package/dist/routing/route-pattern.d.ts +2 -1
  40. package/dist/routing/route-pattern.js +7 -4
  41. package/dist/routing/route-trie.d.ts +5 -1
  42. package/dist/routing/route-trie.js +5 -2
  43. package/dist/server/api-handler.d.ts +2 -0
  44. package/dist/server/api-handler.js +3 -3
  45. package/dist/server/app-browser-entry.js +110 -37
  46. package/dist/server/app-browser-history-controller.d.ts +1 -1
  47. package/dist/server/app-browser-history-controller.js +3 -3
  48. package/dist/server/app-browser-navigation-controller.d.ts +23 -21
  49. package/dist/server/app-browser-navigation-controller.js +2 -2
  50. package/dist/server/app-browser-state.js +1 -1
  51. package/dist/server/app-browser-visible-commit.js +1 -1
  52. package/dist/server/app-fallback-renderer.d.ts +3 -0
  53. package/dist/server/app-fallback-renderer.js +4 -2
  54. package/dist/server/app-middleware.js +2 -1
  55. package/dist/server/app-page-boundary-render.d.ts +12 -1
  56. package/dist/server/app-page-boundary-render.js +84 -2
  57. package/dist/server/app-page-cache-finalizer.d.ts +1 -1
  58. package/dist/server/app-page-cache-finalizer.js +1 -1
  59. package/dist/server/app-page-cache.d.ts +2 -2
  60. package/dist/server/app-page-cache.js +16 -2
  61. package/dist/server/app-page-dispatch.d.ts +19 -2
  62. package/dist/server/app-page-dispatch.js +45 -23
  63. package/dist/server/app-page-element-builder.d.ts +9 -2
  64. package/dist/server/app-page-element-builder.js +144 -33
  65. package/dist/server/app-page-head.d.ts +56 -4
  66. package/dist/server/app-page-head.js +216 -85
  67. package/dist/server/app-page-http-access-fallback-metadata.d.ts +29 -0
  68. package/dist/server/app-page-http-access-fallback-metadata.js +114 -0
  69. package/dist/server/app-page-probe.d.ts +4 -0
  70. package/dist/server/app-page-probe.js +6 -2
  71. package/dist/server/app-page-render.d.ts +2 -2
  72. package/dist/server/app-page-render.js +1 -1
  73. package/dist/server/app-page-request.d.ts +15 -0
  74. package/dist/server/app-page-request.js +134 -14
  75. package/dist/server/app-page-response.js +1 -1
  76. package/dist/server/app-page-route-wiring.d.ts +16 -0
  77. package/dist/server/app-page-route-wiring.js +254 -52
  78. package/dist/server/app-pages-bridge.d.ts +1 -1
  79. package/dist/server/app-pages-bridge.js +2 -1
  80. package/dist/server/app-post-middleware-context.d.ts +1 -1
  81. package/dist/server/app-post-middleware-context.js +1 -1
  82. package/dist/server/app-route-handler-cache.js +4 -0
  83. package/dist/server/app-route-handler-dispatch.js +40 -20
  84. package/dist/server/app-route-handler-execution.d.ts +6 -1
  85. package/dist/server/app-route-handler-execution.js +42 -16
  86. package/dist/server/app-route-handler-policy.d.ts +2 -0
  87. package/dist/server/app-route-handler-policy.js +3 -3
  88. package/dist/server/app-route-handler-response.js +1 -1
  89. package/dist/server/app-route-module-loader.d.ts +9 -1
  90. package/dist/server/app-route-module-loader.js +4 -0
  91. package/dist/server/app-router-entry.js +6 -3
  92. package/dist/server/app-rsc-cache-busting.d.ts +1 -1
  93. package/dist/server/app-rsc-errors.d.ts +1 -1
  94. package/dist/server/app-rsc-errors.js +22 -2
  95. package/dist/server/app-rsc-handler.d.ts +10 -5
  96. package/dist/server/app-rsc-handler.js +73 -33
  97. package/dist/server/app-rsc-request-normalization.d.ts +3 -2
  98. package/dist/server/app-rsc-request-normalization.js +8 -2
  99. package/dist/server/app-rsc-response-finalizer.d.ts +2 -2
  100. package/dist/server/app-rsc-response-finalizer.js +5 -11
  101. package/dist/server/app-rsc-route-matching.d.ts +29 -0
  102. package/dist/server/app-rsc-route-matching.js +93 -11
  103. package/dist/server/app-segment-config.js +13 -3
  104. package/dist/server/app-server-action-execution.d.ts +3 -1
  105. package/dist/server/app-server-action-execution.js +9 -7
  106. package/dist/server/app-ssr-entry.js +6 -6
  107. package/dist/server/app-ssr-stream.d.ts +1 -7
  108. package/dist/server/app-ssr-stream.js +2 -10
  109. package/dist/server/cache-control.d.ts +2 -2
  110. package/dist/server/cache-control.js +2 -1
  111. package/dist/server/config-headers.d.ts +24 -0
  112. package/dist/server/config-headers.js +52 -0
  113. package/dist/server/dev-initial-server-error.d.ts +1 -1
  114. package/dist/server/dev-server.d.ts +3 -1
  115. package/dist/server/dev-server.js +170 -321
  116. package/dist/server/headers.d.ts +2 -2
  117. package/dist/server/headers.js +4 -3
  118. package/dist/server/isr-cache.d.ts +11 -34
  119. package/dist/server/isr-cache.js +33 -43
  120. package/dist/server/isr-decision.d.ts +2 -2
  121. package/dist/server/middleware-matcher-pattern.d.ts +22 -0
  122. package/dist/server/middleware-matcher-pattern.js +219 -0
  123. package/dist/server/middleware-matcher.d.ts +2 -7
  124. package/dist/server/middleware-matcher.js +13 -60
  125. package/dist/server/middleware-path-to-regexp.d.ts +14 -0
  126. package/dist/server/middleware-path-to-regexp.js +228 -0
  127. package/dist/server/middleware-runtime.js +4 -3
  128. package/dist/server/middleware.d.ts +1 -1
  129. package/dist/server/middleware.js +2 -1
  130. package/dist/server/pages-api-route.d.ts +2 -0
  131. package/dist/server/pages-api-route.js +4 -1
  132. package/dist/server/pages-data-route.d.ts +11 -1
  133. package/dist/server/pages-data-route.js +16 -1
  134. package/dist/server/pages-dev-hydration.js +0 -1
  135. package/dist/server/pages-get-initial-props.d.ts +16 -3
  136. package/dist/server/pages-get-initial-props.js +17 -10
  137. package/dist/server/pages-i18n.js +64 -16
  138. package/dist/server/pages-node-compat.d.ts +2 -0
  139. package/dist/server/pages-node-compat.js +7 -3
  140. package/dist/server/pages-page-data.d.ts +64 -10
  141. package/dist/server/pages-page-data.js +349 -80
  142. package/dist/server/pages-page-handler.d.ts +9 -3
  143. package/dist/server/pages-page-handler.js +131 -36
  144. package/dist/server/pages-page-response.d.ts +5 -3
  145. package/dist/server/pages-page-response.js +24 -27
  146. package/dist/server/pages-readiness.d.ts +3 -3
  147. package/dist/server/pages-request-pipeline.d.ts +8 -0
  148. package/dist/server/pages-request-pipeline.js +30 -12
  149. package/dist/server/pages-revalidate.d.ts +1 -1
  150. package/dist/server/pages-revalidate.js +54 -8
  151. package/dist/server/pages-router-entry.d.ts +1 -0
  152. package/dist/server/pages-router-entry.js +16 -4
  153. package/dist/server/prerender-route-params.js +2 -2
  154. package/dist/server/prod-server.d.ts +3 -5
  155. package/dist/server/prod-server.js +72 -35
  156. package/dist/server/request-pipeline.d.ts +15 -29
  157. package/dist/server/request-pipeline.js +24 -59
  158. package/dist/server/revalidation-host.d.ts +11 -0
  159. package/dist/server/revalidation-host.js +19 -0
  160. package/dist/server/rsc-stream-hints.js +122 -18
  161. package/dist/server/worker-revalidation-context.d.ts +13 -0
  162. package/dist/server/worker-revalidation-context.js +29 -0
  163. package/dist/shims/app.d.ts +1 -1
  164. package/dist/shims/cache-handler.d.ts +1 -1
  165. package/dist/shims/cache-handler.js +10 -7
  166. package/dist/shims/cache-request-state.d.ts +27 -1
  167. package/dist/shims/cache-request-state.js +60 -1
  168. package/dist/shims/cache-runtime.d.ts +18 -1
  169. package/dist/shims/cache-runtime.js +26 -8
  170. package/dist/shims/cache.d.ts +5 -5
  171. package/dist/shims/cache.js +27 -11
  172. package/dist/shims/document.d.ts +42 -83
  173. package/dist/shims/document.js +62 -53
  174. package/dist/shims/dynamic.d.ts +5 -25
  175. package/dist/shims/dynamic.js +29 -8
  176. package/dist/shims/error.d.ts +1 -1
  177. package/dist/shims/error.js +2 -2
  178. package/dist/shims/fetch-cache.js +13 -4
  179. package/dist/shims/font-google-base.d.ts +11 -4
  180. package/dist/shims/font-google-base.js +17 -8
  181. package/dist/shims/font-local.d.ts +10 -3
  182. package/dist/shims/font-local.js +41 -10
  183. package/dist/shims/head.d.ts +13 -2
  184. package/dist/shims/head.js +3 -3
  185. package/dist/shims/headers.d.ts +37 -43
  186. package/dist/shims/headers.js +183 -74
  187. package/dist/shims/image.d.ts +27 -37
  188. package/dist/shims/image.js +21 -14
  189. package/dist/shims/internal/cookie-serialize.d.ts +12 -9
  190. package/dist/shims/internal/cookie-serialize.js +10 -7
  191. package/dist/shims/internal/hybrid-client-route-owner.js +3 -1
  192. package/dist/shims/internal/interpolate-as.d.ts +15 -1
  193. package/dist/shims/internal/interpolate-as.js +27 -2
  194. package/dist/shims/internal/utils.d.ts +3 -3
  195. package/dist/shims/legacy-image.d.ts +3 -37
  196. package/dist/shims/legacy-image.js +6 -16
  197. package/dist/shims/link.d.ts +15 -22
  198. package/dist/shims/link.js +34 -13
  199. package/dist/shims/metadata.d.ts +7 -17
  200. package/dist/shims/metadata.js +74 -24
  201. package/dist/shims/navigation-context-state.d.ts +1 -1
  202. package/dist/shims/navigation.d.ts +7 -3
  203. package/dist/shims/navigation.js +25 -14
  204. package/dist/shims/navigation.react-server.js +1 -1
  205. package/dist/shims/next-shims-augmentations.d.ts +1 -0
  206. package/dist/shims/next-shims-public.d.ts +1 -0
  207. package/dist/shims/public-shim-map.json.js +103 -0
  208. package/dist/shims/readonly-url-search-params.d.ts +3 -3
  209. package/dist/shims/readonly-url-search-params.js +3 -3
  210. package/dist/shims/request-context.d.ts +4 -1
  211. package/dist/shims/request-state-types.d.ts +1 -1
  212. package/dist/shims/router.d.ts +55 -21
  213. package/dist/shims/router.js +180 -44
  214. package/dist/shims/script.d.ts +6 -10
  215. package/dist/shims/script.js +7 -4
  216. package/dist/shims/server.d.ts +50 -26
  217. package/dist/shims/server.js +193 -55
  218. package/dist/shims/unified-request-context.d.ts +22 -3
  219. package/dist/shims/unified-request-context.js +84 -1
  220. package/dist/shims/url-safety.d.ts +1 -1
  221. package/dist/shims/url-safety.js +2 -2
  222. package/dist/typegen.d.ts +8 -2
  223. package/dist/typegen.js +76 -15
  224. package/dist/utils/cache-control-metadata.d.ts +2 -1
  225. package/dist/utils/cache-control-metadata.js +5 -1
  226. package/dist/utils/domain-locale.d.ts +2 -2
  227. package/dist/utils/external-url.d.ts +5 -0
  228. package/dist/utils/external-url.js +7 -0
  229. package/dist/utils/html-limited-bots.js +1 -1
  230. package/dist/utils/protocol-headers.d.ts +7 -1
  231. package/dist/utils/protocol-headers.js +7 -1
  232. package/dist/utils/regex-safety.d.ts +8 -0
  233. package/dist/utils/regex-safety.js +737 -0
  234. package/package.json +13 -2
package/dist/index.js CHANGED
@@ -2,15 +2,17 @@ import path, { toSlash } from "./deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/
2
2
  import { detectPackageManager, formatMissingCloudflarePluginError, hasWranglerConfig } from "./utils/project.js";
3
3
  import { normalizePathnameForRouteMatchStrict } from "./routing/utils.js";
4
4
  import { buildViteResolveExtensions, createValidFileMatcher, findFileWithExts, normalizeViteResolveExtensions } from "./routing/file-matcher.js";
5
+ import { hasBasePath, stripBasePath } from "./utils/base-path.js";
5
6
  import { apiRouter, invalidateRouteCache, matchRoute, pagesRouter } from "./routing/pages-router.js";
6
7
  import { VINEXT_MW_CTX_HEADER } from "./utils/protocol-headers.js";
7
8
  import { INTERNAL_HEADERS, NEXTJS_DEPLOYMENT_ID_HEADER, VINEXT_INTERNAL_HEADERS, VINEXT_TIMING_HEADER } from "./server/headers.js";
8
9
  import { normalizePath as normalizePath$1 } from "./server/normalize-path.js";
9
10
  import { matchesRewriteSource, proxyExternalRequest } from "./config/config-matchers.js";
11
+ import { validateMiddlewareMatcherPatterns } from "./server/middleware-matcher-pattern.js";
10
12
  import { isOpenRedirectShaped } from "./server/open-redirect.js";
11
- import { filterInternalHeaders, normalizeTrailingSlash } from "./server/request-pipeline.js";
13
+ import { canonicalizeRequestUrlPathname, filterInternalHeaders, normalizeTrailingSlash } from "./server/request-pipeline.js";
12
14
  import { findMiddlewareFile, isProxyFile, runMiddleware } from "./server/middleware.js";
13
- import { extractMiddlewareMatcherConfig, hasExportedName } from "./build/report.js";
15
+ import { extractMiddlewareMatcherConfig, extractMiddlewareMatcherConfigValue, hasExportedName } from "./build/report.js";
14
16
  import { generateServerEntry } from "./entries/pages-server-entry.js";
15
17
  import { generateClientEntry } from "./entries/pages-client-entry.js";
16
18
  import { appRouteGraph, appRouter, invalidateAppRouteCache, matchAppRoute } from "./routing/app-router.js";
@@ -18,7 +20,7 @@ import { findInstrumentationClientFile, findInstrumentationFile, runInstrumentat
18
20
  import { isUnknownRecord } from "./utils/record.js";
19
21
  import { logRequest, now } from "./server/request-log.js";
20
22
  import { resolvePagesI18nRequest, stripI18nLocaleForApiRoute } from "./server/pages-i18n.js";
21
- import { isNextDataPathname, normalizeNextDataPagePathname, parseNextDataPathname } from "./server/pages-data-route.js";
23
+ import { encodeUrlParserIgnoredCharacters, isNextDataPathname, normalizeNextDataPagePathname, parseNextDataPathname, urlParserCreatesPagesDataPath } from "./server/pages-data-route.js";
22
24
  import { resolveAssetsDir } from "./utils/asset-prefix.js";
23
25
  import { getPagesPreviewModeId } from "./server/pages-preview.js";
24
26
  import { createSSRHandler } from "./server/dev-server.js";
@@ -33,7 +35,7 @@ import { generateRscEntry } from "./entries/app-rsc-entry.js";
33
35
  import { generateSsrEntry } from "./entries/app-ssr-entry.js";
34
36
  import { VINEXT_CACHE_CONFIG_PLUGIN_PROPERTY, VIRTUAL_CACHE_ADAPTERS, generateCacheAdaptersModule } from "./cache/cache-adapters-virtual.js";
35
37
  import { VIRTUAL_IMAGE_ADAPTERS, generateImageAdaptersModule } from "./image/image-adapters-virtual.js";
36
- import { generateBrowserEntry, isLinkPrefetchRoute, toDocumentOnlyAppRoute, toLinkPrefetchRoute } from "./entries/app-browser-entry.js";
38
+ import { generateBrowserEntry, toLinkPrefetchRoutes } from "./entries/app-browser-entry.js";
37
39
  import { collectRouteClassificationManifest } from "./build/route-classification-manifest.js";
38
40
  import { planRouteClassificationInjection } from "./build/route-classification-injector.js";
39
41
  import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from "./shims/constants.js";
@@ -44,6 +46,7 @@ import { precompressAssets } from "./build/precompress.js";
44
46
  import { ensureAssetsIgnore } from "./build/assets-ignore.js";
45
47
  import { emitNextClientRuntimeManifests } from "./build/next-client-runtime-manifests.js";
46
48
  import { collectInlineCssManifest, injectInlineCssManifestGlobal } from "./build/inline-css.js";
49
+ import { readTrustedRevalidationHostname } from "./server/revalidation-host.js";
47
50
  import { installDevStackSourcemapMiddleware } from "./server/dev-stack-sourcemap.js";
48
51
  import { runPagesRequest } from "./server/pages-request-pipeline.js";
49
52
  import { pagesRouteHasPriorityOverAppRoute, validateHybridRouteConflicts } from "./server/hybrid-route-priority.js";
@@ -68,6 +71,7 @@ import { createOgAssetsPlugin, createOgInlineFetchAssetsPlugin } from "./plugins
68
71
  import { generateRouteTypes } from "./typegen.js";
69
72
  import { SSR_EXTERNAL_REACT_ENTRIES, VINEXT_OPTIMIZE_DEPS_EXCLUDE, mergeOptimizeDepsExclude } from "./plugins/rsc-client-shim-excludes.js";
70
73
  import { createServerExternalsManifestPlugin } from "./plugins/server-externals-manifest.js";
74
+ import public_shim_map_default from "./shims/public-shim-map.json.js";
71
75
  import { VINEXT_CLIENT_ENTRY_MANIFEST } from "./utils/client-entry-manifest.js";
72
76
  import { computeClientRuntimeMetadata } from "./utils/client-runtime-metadata.js";
73
77
  import { PAGES_CLIENT_ASSETS_MODULE, buildPagesClientAssetsModule, setPagesClientAssetsBuildMetadata, takePagesClientAssetsBuildMetadata, writePagesClientAssetsModuleIfMissing } from "./build/pages-client-assets-module.js";
@@ -80,6 +84,7 @@ import { createClientAssetFileNames, createClientCodeSplittingConfig, createClie
80
84
  import { hasExportAllCandidate, stripServerExports, validatePageExports } from "./plugins/strip-server-exports.js";
81
85
  import { removeConsoleCalls } from "./plugins/remove-console.js";
82
86
  import { createImportMetaUrlPlugin } from "./plugins/import-meta-url.js";
87
+ import { createTransformCache } from "./plugins/transform-cache.js";
83
88
  import { createRequireContextPlugin } from "./plugins/require-context.js";
84
89
  import { createExtensionlessDynamicImportPlugin } from "./plugins/extensionless-dynamic-import.js";
85
90
  import { createWasmModuleImportPlugin } from "./plugins/wasm-module-import.js";
@@ -111,6 +116,63 @@ const OPTIONAL_OPTIMIZE_DEPS_WARNING_RE = /Failed to resolve dependency: .*use-s
111
116
  const VINEXT_FILTERED_OPTIMIZE_DEPS_WARN = Symbol.for("vinext.filteredOptimizeDepsWarn");
112
117
  const ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
113
118
  installSocketErrorBackstop();
119
+ function isUseCacheAstNode(value) {
120
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "type") === "string";
121
+ }
122
+ function hasInlineUseCacheDirective(node) {
123
+ const body = isUseCacheAstNode(node.body) && node.body.type === "BlockStatement" ? node.body : null;
124
+ if (!body || !Array.isArray(body.body)) return false;
125
+ return body.body.some((statement) => {
126
+ if (!isUseCacheAstNode(statement) || statement.type !== "ExpressionStatement") return false;
127
+ const expression = isUseCacheAstNode(statement.expression) ? statement.expression : null;
128
+ return expression?.type === "Literal" && typeof expression.value === "string" && /^use cache(:\s*\w+)?$/.test(expression.value);
129
+ });
130
+ }
131
+ function functionAcceptsSecondArgument(node) {
132
+ const params = Array.isArray(node.params) ? node.params : [];
133
+ if (params.length >= 2) return true;
134
+ return params.some((param) => isUseCacheAstNode(param) && param.type === "RestElement");
135
+ }
136
+ function collectInlineUseCacheSecondArgumentUsage(value) {
137
+ const usage = [];
138
+ function walk(node) {
139
+ if (Array.isArray(node)) {
140
+ for (const child of node) walk(child);
141
+ return;
142
+ }
143
+ if (!isUseCacheAstNode(node)) return;
144
+ if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && hasInlineUseCacheDirective(node)) usage.push(functionAcceptsSecondArgument(node));
145
+ for (const [key, child] of Object.entries(node)) {
146
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "parent") continue;
147
+ walk(child);
148
+ }
149
+ }
150
+ walk(value);
151
+ return usage;
152
+ }
153
+ function collectFileUseCacheSecondArgumentUsage(body) {
154
+ const localFunctions = /* @__PURE__ */ new Map();
155
+ function collectDeclaration(value) {
156
+ if (!isUseCacheAstNode(value)) return;
157
+ if (value.type === "FunctionDeclaration") {
158
+ const id = isUseCacheAstNode(value.id) ? value.id : null;
159
+ if (id?.type === "Identifier" && typeof id.name === "string") localFunctions.set(id.name, functionAcceptsSecondArgument(value));
160
+ return;
161
+ }
162
+ if (value.type !== "VariableDeclaration" || !Array.isArray(value.declarations)) return;
163
+ for (const declaration of value.declarations) {
164
+ if (!isUseCacheAstNode(declaration) || declaration.type !== "VariableDeclarator") continue;
165
+ const id = isUseCacheAstNode(declaration.id) ? declaration.id : null;
166
+ const init = isUseCacheAstNode(declaration.init) ? declaration.init : null;
167
+ if (id?.type === "Identifier" && typeof id.name === "string" && init && (init.type === "FunctionExpression" || init.type === "ArrowFunctionExpression")) localFunctions.set(id.name, functionAcceptsSecondArgument(init));
168
+ }
169
+ }
170
+ for (const statement of body) {
171
+ if (!isUseCacheAstNode(statement)) continue;
172
+ collectDeclaration(statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement);
173
+ }
174
+ return localFunctions;
175
+ }
114
176
  function isInsideDirectory(dir, filePath) {
115
177
  const relativePath = path.relative(dir, filePath);
116
178
  return relativePath !== "" && !relativePath.startsWith("..") && !path.isAbsolute(relativePath);
@@ -472,16 +534,17 @@ const _tsconfigAliasCache = /* @__PURE__ */ new Map();
472
534
  function sortTsconfigAliasesBySpecificity(aliases) {
473
535
  return Object.fromEntries(Object.entries(aliases).sort((a, b) => b[0].length - a[0].length));
474
536
  }
475
- function resolveTsconfigAliases(projectRoot) {
476
- if (_tsconfigAliasCache.has(projectRoot)) return _tsconfigAliasCache.get(projectRoot);
537
+ function resolveTsconfigAliases(projectRoot, configuredPath) {
538
+ const configPath = configuredPath ? path.resolve(projectRoot, configuredPath) : void 0;
539
+ const cacheKey = configPath ?? projectRoot;
540
+ if (_tsconfigAliasCache.has(cacheKey)) return _tsconfigAliasCache.get(cacheKey);
477
541
  let aliases = {};
478
- for (const name of TSCONFIG_FILES) {
479
- const candidate = path.join(projectRoot, name);
542
+ for (const candidate of configPath ? [configPath] : TSCONFIG_FILES.map((name) => path.join(projectRoot, name))) {
480
543
  if (!fs.existsSync(candidate)) continue;
481
544
  aliases = sortTsconfigAliasesBySpecificity(loadTsconfigPathAliases(candidate, projectRoot));
482
545
  break;
483
546
  }
484
- _tsconfigAliasCache.set(projectRoot, aliases);
547
+ _tsconfigAliasCache.set(cacheKey, aliases);
485
548
  return aliases;
486
549
  }
487
550
  /**
@@ -667,27 +730,14 @@ function generateRootParamsModule(rootParamNames) {
667
730
  const exports = names.map((name) => `export function ${name}() { return getRootParam(${JSON.stringify(name)}); }`).join("\n");
668
731
  return `import { getRootParam } from ${JSON.stringify(rootParamsShimPath)};\n${exports}\n`;
669
732
  }
670
- /**
671
- * Shims with a `.react-server.ts` variant for the RSC environment.
672
- * Maps import specifier base shim name. In the RSC env, resolveId
673
- * appends `.react-server`; in other envs it resolves to the base.
674
- *
675
- * These MUST NOT appear in `nextShimMap` (resolve.alias) because Vite's
676
- * alias plugin runs before user `enforce:"pre"` plugins — aliases are
677
- * unoverridable. Keeping them out of the alias lets the resolveId hook
678
- * control resolution per-environment.
679
- *
680
- * To add a new react-server shim:
681
- * 1. Create `<name>.react-server.ts` in src/shims/
682
- * 2. Add entries here for each import specifier.
683
- */
684
- const _reactServerShims = /* @__PURE__ */ new Map([
685
- ["next/navigation", "navigation"],
686
- ["next/navigation.js", "navigation"],
687
- ["next/dist/client/components/navigation", "navigation"],
688
- ["next/error", "error"],
689
- ["next/error.js", "error"]
690
- ]);
733
+ const _publicNextShimMap = public_shim_map_default;
734
+ const _reactServerShims = /* @__PURE__ */ new Map();
735
+ for (const [specifier, definition] of Object.entries(_publicNextShimMap)) {
736
+ if (!definition.reactServer) continue;
737
+ _reactServerShims.set(specifier, definition.shim);
738
+ _reactServerShims.set(`${specifier}.js`, definition.shim);
739
+ }
740
+ _reactServerShims.set("next/dist/client/components/navigation", "navigation");
691
741
  const clientCodeSplittingConfig = createClientCodeSplittingConfig(createClientManualChunks(_shimsDir));
692
742
  const appClientCodeSplittingConfig = createClientCodeSplittingConfig(createClientManualChunks(_shimsDir, true));
693
743
  function getClientOutputConfig(assetsDir, preserveAppRouteBoundaries = false) {
@@ -765,7 +815,7 @@ function vinext(options = {}) {
765
815
  * __NEXT_DATA__ to determine which page to hydrate.
766
816
  */
767
817
  async function generateClientEntry$1() {
768
- const appPrefetchRoutes = hasAppDir ? (await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => isLinkPrefetchRoute(route) ? toLinkPrefetchRoute(route) : toDocumentOnlyAppRoute(route)) : [];
818
+ const appPrefetchRoutes = hasAppDir ? toLinkPrefetchRoutes(await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher)) : [];
769
819
  return generateClientEntry(pagesDir, nextConfig, fileMatcher, {
770
820
  appPrefetchRoutes,
771
821
  instrumentationClientPath,
@@ -774,10 +824,9 @@ function vinext(options = {}) {
774
824
  });
775
825
  }
776
826
  async function writeRouteTypes() {
777
- if (!hasAppDir) return;
778
827
  await generateRouteTypes({
779
828
  root,
780
- appDir,
829
+ appDir: hasAppDir ? appDir : null,
781
830
  pageExtensions: nextConfig.pageExtensions
782
831
  });
783
832
  }
@@ -906,6 +955,7 @@ function vinext(options = {}) {
906
955
  return (typeof hook === "function" ? hook : hook.handler).call(this, config, env);
907
956
  }
908
957
  };
958
+ const cachedTypeofWindowTransform = createTransformCache();
909
959
  const plugins = [
910
960
  createStyledJsxPlugin(earlyBaseDir),
911
961
  mdxProxyPlugin,
@@ -978,10 +1028,9 @@ function vinext(options = {}) {
978
1028
  async config(config, env) {
979
1029
  isServeCommand = env.command === "serve";
980
1030
  root = toSlash(config.root ?? process.cwd());
981
- const shouldEnableNativeTsconfigPaths = config.resolve?.tsconfigPaths === void 0;
982
- const tsconfigPathAliases = resolveTsconfigAliases(root);
1031
+ const userResolve = config.resolve;
1032
+ let tsconfigPathAliases = {};
983
1033
  const swcHelpersAlias = resolveSwcHelpersAlias(root);
984
- if (Object.keys(tsconfigPathAliases).length > 0) config.customLogger = suppressAliasCustomResolverDeprecationWarning(config.customLogger ?? createLogger(config.logLevel, { allowClearScreen: config.clearScreen }));
985
1034
  const mode = env?.mode ?? "development";
986
1035
  const dotenvVars = loadEnv(mode, config.envDir ?? root, "");
987
1036
  for (const [key, value] of Object.entries(dotenvVars)) if (process.env[key] === void 0) process.env[key] = value;
@@ -989,7 +1038,7 @@ function vinext(options = {}) {
989
1038
  if (mode === "test") resolvedNodeEnv = "test";
990
1039
  else if (env?.command === "build" || env?.isPreview === true) resolvedNodeEnv = "production";
991
1040
  else resolvedNodeEnv = "development";
992
- if (process.env.NODE_ENV !== resolvedNodeEnv) process.env.NODE_ENV = resolvedNodeEnv;
1041
+ if (process.env.NODE_ENV !== resolvedNodeEnv) Reflect.set(process.env, "NODE_ENV", resolvedNodeEnv);
993
1042
  if (env?.command === "build") previewBuildCredentials = getPreviewBuildCredentials() ?? createPreviewBuildCredentials();
994
1043
  draftModeSecret = previewBuildCredentials?.id ?? getPagesPreviewModeId();
995
1044
  let baseDir;
@@ -1008,6 +1057,8 @@ function vinext(options = {}) {
1008
1057
  appDir = path.join(baseDir, "app");
1009
1058
  hasPagesDir = fs.existsSync(pagesDir);
1010
1059
  hasAppDir = !options.disableAppRouter && fs.existsSync(appDir);
1060
+ invalidateRouteCache(pagesDir);
1061
+ invalidateAppRouteCache();
1011
1062
  if (!nextConfig) {
1012
1063
  const phase = env?.command === "build" ? PHASE_PRODUCTION_BUILD : PHASE_DEVELOPMENT_SERVER;
1013
1064
  let rawConfig;
@@ -1026,6 +1077,10 @@ function vinext(options = {}) {
1026
1077
  buildId: sharedBuildId
1027
1078
  };
1028
1079
  }
1080
+ const configuredTsconfigPath = isUnknownRecord(nextConfig.typescript) ? typeof nextConfig.typescript.tsconfigPath === "string" ? nextConfig.typescript.tsconfigPath : void 0 : void 0;
1081
+ tsconfigPathAliases = resolveTsconfigAliases(root, configuredTsconfigPath);
1082
+ const shouldAutoEnableNativeTsconfigPaths = userResolve?.tsconfigPaths === void 0 && configuredTsconfigPath === void 0;
1083
+ if (Object.keys(tsconfigPathAliases).length > 0) config.customLogger = suppressAliasCustomResolverDeprecationWarning(config.customLogger ?? createLogger(config.logLevel, { allowClearScreen: config.clearScreen }));
1029
1084
  if (rscCompatibilityId === void 0) {
1030
1085
  const sharedRscCompatibilityId = process.env.__VINEXT_SHARED_RSC_COMPATIBILITY_ID;
1031
1086
  rscCompatibilityId = sharedRscCompatibilityId && sharedRscCompatibilityId.length > 0 ? sharedRscCompatibilityId : createRscCompatibilityId(nextConfig);
@@ -1036,6 +1091,10 @@ function vinext(options = {}) {
1036
1091
  instrumentationClientPath = findInstrumentationClientFile(root, fileMatcher);
1037
1092
  const middlewareConventionDir = canonicalize(baseDir) === canonicalize(path.join(root, "src")) ? path.join(root, "src") : root;
1038
1093
  middlewarePath = findMiddlewareFile(root, fileMatcher, middlewareConventionDir);
1094
+ if (middlewarePath) {
1095
+ const staticMatcher = extractMiddlewareMatcherConfigValue(middlewarePath);
1096
+ if (staticMatcher !== void 0) validateMiddlewareMatcherPatterns(staticMatcher);
1097
+ }
1039
1098
  const instrumentationClientInjects = nextConfig.instrumentationClientInject.map((spec) => spec.startsWith("./") || spec.startsWith("../") ? path.resolve(root, spec) : spec);
1040
1099
  clientInjectModule = instrumentationClientInjects.length ? generateInstrumentationClientInjectModule(instrumentationClientInjects, instrumentationClientPath, INSTRUMENTATION_CLIENT_EMPTY_MODULE) : null;
1041
1100
  if (env?.command === "build") await writeRouteTypes();
@@ -1050,6 +1109,10 @@ function vinext(options = {}) {
1050
1109
  }
1051
1110
  defines["process.env.__NEXT_ROUTER_BASEPATH"] = JSON.stringify(nextConfig.basePath);
1052
1111
  defines["process.env.__VINEXT_HAS_PAGES_ROUTER"] = JSON.stringify(String(hasPagesDir));
1112
+ defines["process.env.__VINEXT_HAS_CLIENT_REWRITES"] = JSON.stringify(String(nextConfig.rewrites.beforeFiles.length > 0 || nextConfig.rewrites.afterFiles.length > 0 || nextConfig.rewrites.fallback.length > 0));
1113
+ defines["process.env.__VINEXT_HAS_CONFIG_HEADERS"] = JSON.stringify(String(nextConfig.headers.length > 0));
1114
+ defines["process.env.__VINEXT_HAS_CONFIG_REDIRECTS"] = JSON.stringify(String(nextConfig.redirects.length > 0));
1115
+ defines["process.env.__VINEXT_HAS_CONFIG_REWRITES"] = JSON.stringify(String(nextConfig.rewrites.beforeFiles.length > 0 || nextConfig.rewrites.afterFiles.length > 0 || nextConfig.rewrites.fallback.length > 0));
1053
1116
  defines["process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME"] = JSON.stringify(String(nextConfig.staleTimes.dynamic));
1054
1117
  defines["process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME"] = JSON.stringify(String(nextConfig.staleTimes.static));
1055
1118
  defines["process.env.__VINEXT_PREFETCH_INLINING"] = JSON.stringify(nextConfig.prefetchInlining ? "true" : "false");
@@ -1101,28 +1164,7 @@ function vinext(options = {}) {
1101
1164
  }
1102
1165
  for (const key of Object.keys(nextConfig.compilerDefineServer)) if (key in defines) throw new Error(`The \`compiler.defineServer\` option is configured to replace the \`${key}\` variable. This variable is either part of a built-in or is already configured.`);
1103
1166
  nextShimMap = Object.fromEntries(Object.entries({
1104
- "next/link": path.join(shimsDir, "link"),
1105
- "next/head": path.join(shimsDir, "head"),
1106
- "next/router": path.join(shimsDir, "router"),
1107
- "next/compat/router": path.join(shimsDir, "compat-router"),
1108
- "next/image": path.join(shimsDir, "image"),
1109
- "next/legacy/image": path.join(shimsDir, "legacy-image"),
1110
- "next/dynamic": path.join(shimsDir, "dynamic"),
1111
- "next/app": path.join(shimsDir, "app"),
1112
- "next/document": path.join(shimsDir, "document"),
1113
- "next/config": path.join(shimsDir, "config"),
1114
- "next/script": path.join(shimsDir, "script"),
1115
- "next/server": path.join(shimsDir, "server"),
1116
- "next/headers": path.join(shimsDir, "headers"),
1117
- "next/font/google": path.join(shimsDir, "font-google"),
1118
- "next/font/local": path.join(shimsDir, "font-local"),
1119
- "next/cache": path.join(shimsDir, "cache"),
1120
- "next/form": path.join(shimsDir, "form"),
1121
- "next/og": path.join(shimsDir, "og"),
1122
- "next/web-vitals": path.join(shimsDir, "web-vitals"),
1123
- "next/amp": path.join(shimsDir, "amp"),
1124
- "next/offline": path.join(shimsDir, "offline"),
1125
- "next/constants": path.join(shimsDir, "constants"),
1167
+ ...Object.fromEntries(Object.entries(_publicNextShimMap).filter(([, definition]) => !definition.reactServer).map(([specifier, definition]) => [specifier, path.join(shimsDir, definition.shim)])),
1126
1168
  "next/dist/shared/lib/app-router-context.shared-runtime": path.join(shimsDir, "internal", "app-router-context"),
1127
1169
  "next/dist/shared/lib/app-router-context": path.join(shimsDir, "internal", "app-router-context"),
1128
1170
  "next/dist/shared/lib/router-context.shared-runtime": path.join(shimsDir, "internal", "router-context"),
@@ -1244,7 +1286,7 @@ function vinext(options = {}) {
1244
1286
  "react/jsx-runtime",
1245
1287
  "react/jsx-dev-runtime"
1246
1288
  ],
1247
- ...shouldEnableNativeTsconfigPaths ? { tsconfigPaths: true } : {}
1289
+ ...shouldAutoEnableNativeTsconfigPaths ? { tsconfigPaths: true } : {}
1248
1290
  },
1249
1291
  oxc: {
1250
1292
  jsx: { runtime: "automatic" },
@@ -1460,7 +1502,7 @@ function vinext(options = {}) {
1460
1502
  config.optimizeDeps.exclude = mergeOptimizeDepsExclude(config.optimizeDeps.exclude ?? [], VINEXT_OPTIMIZE_DEPS_EXCLUDE, PAGES_CLOUDFLARE_WORKER_OPTIMIZE_DEPS_EXCLUDE);
1461
1503
  }
1462
1504
  const configuredExtensions = name === "client" ? nextConfig.resolveExtensions : nextConfig.serverResolveExtensions;
1463
- const extensions = configuredExtensions === null ? buildViteResolveExtensions(nextConfig.pageExtensions, config.resolve?.extensions) : normalizeViteResolveExtensions(configuredExtensions);
1505
+ const extensions = configuredExtensions === null ? buildViteResolveExtensions(config.resolve?.extensions) : normalizeViteResolveExtensions(configuredExtensions);
1464
1506
  config.resolve ??= {};
1465
1507
  config.resolve.extensions = extensions;
1466
1508
  return null;
@@ -1856,8 +1898,20 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1856
1898
  }
1857
1899
  },
1858
1900
  configureServer(server) {
1901
+ server.middlewares.use((req, _res, next) => {
1902
+ req.__vinextOriginalEncodedUrl ??= req.url;
1903
+ next();
1904
+ });
1859
1905
  const pageExtensions = fileMatcher.extensionRegex;
1860
1906
  let pagesRunner = null;
1907
+ const getTrustedDevRevalidateOrigin = () => {
1908
+ const resolved = server.resolvedUrls?.local[0];
1909
+ if (resolved) try {
1910
+ return new URL(resolved).origin;
1911
+ } catch {}
1912
+ const address = server.httpServer?.address();
1913
+ return `http://localhost:${typeof address === "object" && address ? address.port : server.config.server.port ?? 3e3}`;
1914
+ };
1861
1915
  let cachedSSRHandler = null;
1862
1916
  function getPagesRunner() {
1863
1917
  if (!pagesRunner) pagesRunner = createDirectRunner(server.environments["ssr"] ?? Object.values(server.environments).find((e) => e !== server.environments["rsc"]) ?? Object.values(server.environments)[0]);
@@ -2179,7 +2233,16 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2179
2233
  res.end("Forbidden");
2180
2234
  return;
2181
2235
  }
2182
- const requestHost = (Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) || "localhost";
2236
+ let revalidationHostname = null;
2237
+ if (req.headers["x-vinext-revalidate-host"] !== void 0) {
2238
+ const revalidationHeaders = new Headers();
2239
+ for (const [name, value] of Object.entries(req.headers)) {
2240
+ if (value === void 0 || name.startsWith(":")) continue;
2241
+ revalidationHeaders.set(name, Array.isArray(value) ? value.join(", ") : value);
2242
+ }
2243
+ revalidationHostname = readTrustedRevalidationHostname(revalidationHeaders, nextConfig?.i18n);
2244
+ }
2245
+ const requestHost = revalidationHostname ?? ((Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host) || "localhost");
2183
2246
  const requestOrigin = `http://${requestHost}`;
2184
2247
  const getUrlHostname = (requestUrl) => new URL(requestUrl).hostname;
2185
2248
  if (isImageOptimizationPath(url.split("?")[0])) {
@@ -2193,9 +2256,25 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2193
2256
  res.end();
2194
2257
  return;
2195
2258
  }
2259
+ const originalEncodedUrl = req.__vinextOriginalEncodedUrl ?? url;
2260
+ const originalEncodedPathname = originalEncodedUrl.split("?")[0];
2261
+ if (isOpenRedirectShaped(originalEncodedPathname)) {
2262
+ res.writeHead(404);
2263
+ res.end("This page could not be found");
2264
+ return;
2265
+ }
2266
+ const canonicalOriginalUrl = canonicalizeRequestUrlPathname(originalEncodedUrl);
2267
+ url = canonicalizeRequestUrlPathname(url);
2196
2268
  const rawPathname = url.split("?")[0];
2197
2269
  if (rawPathname.endsWith("/index.html")) url = url.replace("/index.html", "/");
2198
2270
  else if (rawPathname.endsWith(".html")) url = url.replace(/\.html(?=\?|$)/, "");
2271
+ let middlewareUrl = canonicalOriginalUrl;
2272
+ let routeUrl = middlewareUrl;
2273
+ {
2274
+ const routePathname = routeUrl.split("?")[0];
2275
+ if (routePathname.endsWith("/index.html")) routeUrl = routeUrl.replace("/index.html", "/");
2276
+ else if (routePathname.endsWith(".html")) routeUrl = routeUrl.replace(/\.html(?=\?|$)/, "");
2277
+ }
2199
2278
  let pathname = url.split("?")[0];
2200
2279
  if (isOpenRedirectShaped(pathname)) {
2201
2280
  res.writeHead(404);
@@ -2210,20 +2289,42 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2210
2289
  res.end("Bad Request");
2211
2290
  return;
2212
2291
  }
2292
+ if (urlParserCreatesPagesDataPath(pathname)) {
2293
+ res.writeHead(404);
2294
+ res.end("This page could not be found");
2295
+ return;
2296
+ }
2297
+ pathname = encodeUrlParserIgnoredCharacters(pathname);
2213
2298
  {
2214
2299
  const qs = url.includes("?") ? url.slice(url.indexOf("?")) : "";
2215
2300
  url = pathname + qs;
2216
2301
  }
2217
2302
  const capturedMiddlewarePath = middlewarePath;
2218
2303
  const bp = nextConfig?.basePath ?? "";
2219
- if (bp && pathname.startsWith(bp)) {
2220
- const stripped = pathname.slice(bp.length) || "/";
2221
- url = stripped + (url.includes("?") ? url.slice(url.indexOf("?")) : "");
2222
- pathname = stripped;
2304
+ const viteBase = server.config.base;
2305
+ const viteBasePath = viteBase.startsWith("/") && viteBase !== "/" ? viteBase.replace(/\/+$/, "") : "";
2306
+ const routingBasePath = bp || viteBasePath;
2307
+ if (routingBasePath) {
2308
+ if (hasBasePath(pathname, routingBasePath)) {
2309
+ const stripped = stripBasePath(pathname, routingBasePath);
2310
+ url = stripped + (url.includes("?") ? url.slice(url.indexOf("?")) : "");
2311
+ pathname = stripped;
2312
+ }
2313
+ const middlewarePathname = middlewareUrl.split("?")[0];
2314
+ if (hasBasePath(middlewarePathname, routingBasePath)) {
2315
+ const middlewareQs = middlewareUrl.includes("?") ? middlewareUrl.slice(middlewareUrl.indexOf("?")) : "";
2316
+ middlewareUrl = stripBasePath(middlewarePathname, routingBasePath) + middlewareQs;
2317
+ }
2318
+ const routePathname = routeUrl.split("?")[0];
2319
+ if (hasBasePath(routePathname, routingBasePath)) {
2320
+ const routeQs = routeUrl.includes("?") ? routeUrl.slice(routeUrl.indexOf("?")) : "";
2321
+ routeUrl = stripBasePath(routePathname, routingBasePath) + routeQs;
2322
+ }
2223
2323
  }
2324
+ let configMatchPathname = stripBasePath(middlewareUrl.split("?")[0], routingBasePath);
2224
2325
  if (nextConfig) {
2225
2326
  const qs = url.includes("?") ? url.slice(url.indexOf("?")) : "";
2226
- const trailingSlashRedirect = normalizeTrailingSlash(pathname, bp, nextConfig.trailingSlash, qs);
2327
+ const trailingSlashRedirect = normalizeTrailingSlash(routeUrl.split("?")[0], bp, nextConfig.trailingSlash, qs);
2227
2328
  if (trailingSlashRedirect) {
2228
2329
  const location = trailingSlashRedirect.headers.get("Location");
2229
2330
  res.writeHead(trailingSlashRedirect.status, location ? { Location: location } : void 0);
@@ -2241,7 +2342,10 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2241
2342
  const qs = url.includes("?") ? url.slice(url.indexOf("?")) : "";
2242
2343
  const pagePathname = normalizeNextDataPagePathname(dataMatch.pagePathname, capturedMiddlewarePath !== null && nextConfig?.trailingSlash === true);
2243
2344
  url = pagePathname + qs;
2345
+ middlewareUrl = url;
2346
+ routeUrl = url;
2244
2347
  pathname = pagePathname;
2348
+ configMatchPathname = pagePathname;
2245
2349
  req.url = url;
2246
2350
  } else {
2247
2351
  const deploymentId = process.env.__VINEXT_DEPLOYMENT_ID || process.env.NEXT_DEPLOYMENT_ID;
@@ -2273,10 +2377,11 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2273
2377
  const rawHeaders = new Headers(Object.fromEntries(Object.entries(req.headers).filter(([k, v]) => v !== void 0 && !k.startsWith(":")).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : String(v)])));
2274
2378
  const isDataRequest = isDataReq;
2275
2379
  const nodeRequestHeaders = filterInternalHeaders(rawHeaders);
2380
+ if (revalidationHostname) nodeRequestHeaders.set("host", revalidationHostname);
2276
2381
  for (const header of INTERNAL_HEADERS) delete req.headers[header];
2277
2382
  for (const header of VINEXT_INTERNAL_HEADERS) delete req.headers[header];
2278
2383
  const method = req.method ?? "GET";
2279
- const webRequest = new Request(new URL(url, requestOrigin), {
2384
+ const webRequest = new Request(new URL(routeUrl, requestOrigin), {
2280
2385
  method,
2281
2386
  headers: nodeRequestHeaders
2282
2387
  });
@@ -2287,11 +2392,11 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2287
2392
  const devRunMiddlewareAdapter = capturedMiddlewarePath ? async (_request, _ctx, opts) => {
2288
2393
  const rawProto = process.env.VINEXT_TRUST_PROXY === "1" || (process.env.VINEXT_TRUSTED_HOSTS ?? "").split(",").some((h) => h.trim()) ? String(req.headers["x-forwarded-proto"] || "").split(",")[0].trim() : "";
2289
2394
  const mwOrigin = `${rawProto === "https" || rawProto === "http" ? rawProto : "http"}://${requestHost}`;
2290
- const middlewareRequest = new Request(new URL(url, mwOrigin), {
2395
+ const middlewareRequest = new Request(new URL(middlewareUrl, mwOrigin), {
2291
2396
  method: req.method,
2292
2397
  headers: nodeRequestHeaders
2293
2398
  });
2294
- const result = await runMiddleware(getPagesRunner(), capturedMiddlewarePath, middlewareRequest, nextConfig?.i18n, nextConfig?.basePath, nextConfig?.trailingSlash, opts.isDataRequest);
2399
+ const result = await runMiddleware(getPagesRunner(), capturedMiddlewarePath, middlewareRequest, nextConfig?.i18n, nextConfig?.basePath, nextConfig?.trailingSlash, opts.isDataRequest, pathname);
2295
2400
  if (hasAppDir && result.continue) {
2296
2401
  const mwCtxEntries = [];
2297
2402
  if (result.responseHeaders) {
@@ -2335,6 +2440,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2335
2440
  isDataRequest,
2336
2441
  hasMiddleware: capturedMiddlewarePath !== null,
2337
2442
  rawSearch: url.includes("?") ? url.slice(url.indexOf("?")) : "",
2443
+ configMatchPathname,
2338
2444
  runMiddleware: devRunMiddlewareAdapter,
2339
2445
  matchPageRoute: (resolvedPathname, request) => {
2340
2446
  const m = matchRoute(nextConfig?.i18n ? resolvePagesI18nRequest(resolvedPathname, nextConfig.i18n, request.headers, getUrlHostname(request.url), bp, nextConfig.trailingSlash ?? false).url : resolvedPathname, devPageRoutes);
@@ -2392,6 +2498,8 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2392
2498
  if (await handleApiRoute(getPagesRunner(), req, res, pipelineResult.apiUrl, apiRoutes, {
2393
2499
  basePath: nextConfig?.basePath,
2394
2500
  i18n: nextConfig?.i18n,
2501
+ trustedRevalidateOrigin: getTrustedDevRevalidateOrigin(),
2502
+ allowedRevalidateHeaderKeys: nextConfig?.allowedRevalidateHeaderKeys,
2395
2503
  trailingSlash: nextConfig?.trailingSlash
2396
2504
  })) return;
2397
2505
  if (hasAppDir) return next();
@@ -2410,7 +2518,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2410
2518
  }
2411
2519
  if (!cachedSSRHandler || cachedSSRHandler.routes !== routes) cachedSSRHandler = {
2412
2520
  routes,
2413
- handler: createSSRHandler(server, getPagesRunner(), routes, pagesDir, nextConfig?.i18n, fileMatcher, nextConfig?.basePath ?? "", nextConfig?.trailingSlash ?? false, middlewarePath !== null, (nextConfig?.rewrites.beforeFiles.length ?? 0) > 0 || (nextConfig?.rewrites.afterFiles.length ?? 0) > 0 || (nextConfig?.rewrites.fallback.length ?? 0) > 0, nextConfig?.clientTraceMetadata, nextConfig?.htmlLimitedBots, nextConfig?.reactStrictMode === true)
2521
+ handler: createSSRHandler(server, getPagesRunner(), routes, pagesDir, nextConfig?.i18n, fileMatcher, nextConfig?.basePath ?? "", nextConfig?.trailingSlash ?? false, middlewarePath !== null, (nextConfig?.rewrites.beforeFiles.length ?? 0) > 0 || (nextConfig?.rewrites.afterFiles.length ?? 0) > 0 || (nextConfig?.rewrites.fallback.length ?? 0) > 0, nextConfig?.clientTraceMetadata, nextConfig?.htmlLimitedBots, nextConfig?.reactStrictMode === true, nextConfig?.expireTime)
2414
2522
  };
2415
2523
  flushStagedHeaders();
2416
2524
  flushRequestHeaders();
@@ -2537,7 +2645,8 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2537
2645
  if (useNativeTypeofWindowFolding && this.environment.config.build.write !== false) return null;
2538
2646
  const cacheDir = `${toSlash(this.environment.config.cacheDir).replace(/\/$/, "")}/`;
2539
2647
  if (toSlash(id).startsWith(cacheDir)) return null;
2540
- return replaceTypeofWindow(code, getTypeofWindowReplacement(this.environment), id);
2648
+ const replacement = getTypeofWindowReplacement(this.environment);
2649
+ return cachedTypeofWindowTransform(id, code, replacement, () => replaceTypeofWindow(code, replacement, id));
2541
2650
  }
2542
2651
  }
2543
2652
  },
@@ -2716,32 +2825,8 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2716
2825
  async handler(code, id) {
2717
2826
  const ast = parseAst(code);
2718
2827
  const cacheDirective = ast.body.find((node) => node.type === "ExpressionStatement" && node.expression?.type === "Literal" && typeof node.expression.value === "string" && node.expression.value.startsWith("use cache"));
2719
- function nodeHasInlineCacheDirective(node) {
2720
- if (!node || typeof node !== "object") return false;
2721
- const fn = node.type === "MethodDefinition" ? node.value : node;
2722
- const stmts = fn?.body?.type === "BlockStatement" ? fn.body.body : null;
2723
- if (Array.isArray(stmts)) {
2724
- for (const stmt of stmts) if (stmt?.type === "ExpressionStatement" && stmt.expression?.type === "Literal" && typeof stmt.expression?.value === "string" && /^use cache(:\s*\w+)?$/.test(stmt.expression.value)) return true;
2725
- }
2726
- return false;
2727
- }
2728
- function astHasInlineCache(nodes) {
2729
- for (const node of nodes) {
2730
- if (!node || typeof node !== "object") continue;
2731
- if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "MethodDefinition") && nodeHasInlineCacheDirective(node)) return true;
2732
- for (const key of Object.keys(node)) {
2733
- if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
2734
- const child = node[key];
2735
- if (Array.isArray(child) && child.some((c) => c && typeof c === "object")) {
2736
- if (astHasInlineCache(child)) return true;
2737
- } else if (child && typeof child === "object" && child.type) {
2738
- if (astHasInlineCache([child])) return true;
2739
- }
2740
- }
2741
- }
2742
- return false;
2743
- }
2744
- const hasInlineCache = !cacheDirective && astHasInlineCache(ast.body);
2828
+ const inlineCacheSecondArgumentUsage = cacheDirective ? [] : collectInlineUseCacheSecondArgumentUsage(ast.body);
2829
+ const hasInlineCache = inlineCacheSecondArgumentUsage.length > 0;
2745
2830
  if (!cacheDirective && !hasInlineCache) return null;
2746
2831
  if (!resolvedRscTransformsPath) throw new Error("vinext: 'use cache' requires @vitejs/plugin-rsc to be installed.\nRun: " + detectPackageManager(process.cwd()) + " @vitejs/plugin-rsc");
2747
2832
  const { transformWrapExport, transformHoistInlineDirective } = await import(pathToFileURL(resolvedRscTransformsPath).href);
@@ -2753,10 +2838,15 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2753
2838
  const moduleFileName = path.basename(modulePath);
2754
2839
  const isAppPageModule = hasAppDir && isInsideDirectory(appDir, modulePath) && path.parse(moduleFileName).name === "page" && fileMatcher.extensionRegex.test(moduleFileName);
2755
2840
  const runtimeModuleUrl = pathToFileURL(resolveShimModulePath(shimsDir, "cache-runtime")).href;
2841
+ const secondArgumentUsage = collectFileUseCacheSecondArgumentUsage(ast.body);
2756
2842
  const result = transformWrapExport(code, ast, {
2757
2843
  runtime: (value, name) => {
2758
- const pageOptions = name === "default" && isAppPageModule ? `, { appPageDefaultExport: true }` : "";
2759
- return `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + ":" + name)}, ${JSON.stringify(variant)}${pageOptions})`;
2844
+ const runtimeOptions = [];
2845
+ const acceptsSecondArgument = secondArgumentUsage.get(value) ?? true;
2846
+ runtimeOptions.push(`acceptsSecondArgument: ${acceptsSecondArgument}`);
2847
+ if (name === "default" && isAppPageModule) runtimeOptions.push("appPageDefaultExport: true");
2848
+ const optionsArgument = runtimeOptions.length > 0 ? `, { ${runtimeOptions.join(", ")} }` : "";
2849
+ return `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + ":" + name)}, ${JSON.stringify(variant)}${optionsArgument})`;
2760
2850
  },
2761
2851
  rejectNonAsyncFunction: false,
2762
2852
  filter: (name, meta) => {
@@ -2783,12 +2873,15 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2783
2873
  if (hasInlineCache) {
2784
2874
  const runtimeModuleUrl2 = pathToFileURL(resolveShimModulePath(shimsDir, "cache-runtime")).href;
2785
2875
  try {
2876
+ let transformedFunctionIndex = 0;
2786
2877
  const result = transformHoistInlineDirective(code, ast, {
2787
2878
  directive: /^use cache(:\s*\w+)?$/,
2788
2879
  runtime: (value, name, meta) => {
2789
2880
  const directiveMatch = meta.directiveMatch[0];
2790
2881
  const variant = directiveMatch === "use cache" ? "" : directiveMatch.replace("use cache:", "").trim();
2791
- return `(await import(${JSON.stringify(runtimeModuleUrl2)})).registerCachedFunction(${value}, ${JSON.stringify(id + ":" + name)}, ${JSON.stringify(variant)})`;
2882
+ const acceptsSecondArgument = inlineCacheSecondArgumentUsage[transformedFunctionIndex++];
2883
+ const optionsArgument = acceptsSecondArgument === void 0 ? "" : `, { acceptsSecondArgument: ${acceptsSecondArgument} }`;
2884
+ return `(await import(${JSON.stringify(runtimeModuleUrl2)})).registerCachedFunction(${value}, ${JSON.stringify(id + ":" + name)}, ${JSON.stringify(variant)}${optionsArgument})`;
2792
2885
  },
2793
2886
  rejectNonAsyncFunction: false
2794
2887
  });
@@ -25,7 +25,9 @@ type CloudflarePlatformSetupResult = {
25
25
  declare function validateCloudflarePlatformSetup(context: CloudflarePlatformSetupContext, cloudflare: CloudflareInitOptions): void;
26
26
  declare function setupCloudflarePlatform(context: CloudflarePlatformSetupContext, cloudflare: CloudflareInitOptions): CloudflarePlatformSetupResult;
27
27
  declare function generateWranglerConfig(info: CloudflareProjectInfo, options?: CloudflareInitOptions, today?: string): string;
28
- declare function updateWranglerConfigForCloudflare(code: string, options: CloudflareInitOptions): string;
28
+ declare function updateWranglerConfigForCloudflare(code: string, options: CloudflareInitOptions, context?: {
29
+ root?: string;
30
+ }): string;
29
31
  declare function getWranglerImagesBinding(code: string): string;
30
32
  /** Generate vite.config.ts for App Router */
31
33
  declare function generateAppRouterViteConfig(info?: CloudflareProjectInfo, options?: CloudflareInitOptions, imagesBinding?: string, prerender?: boolean): string;