vinext 0.0.44 → 0.0.46

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 (323) hide show
  1. package/dist/build/google-fonts/build-url.d.ts +10 -0
  2. package/dist/build/google-fonts/build-url.js +30 -0
  3. package/dist/build/google-fonts/build-url.js.map +1 -0
  4. package/dist/build/google-fonts/font-data.js +24985 -0
  5. package/dist/build/google-fonts/font-data.js.map +1 -0
  6. package/dist/build/google-fonts/font-metadata.d.ts +17 -0
  7. package/dist/build/google-fonts/font-metadata.js +7 -0
  8. package/dist/build/google-fonts/font-metadata.js.map +1 -0
  9. package/dist/build/google-fonts/get-axes.d.ts +7 -0
  10. package/dist/build/google-fonts/get-axes.js +39 -0
  11. package/dist/build/google-fonts/get-axes.js.map +1 -0
  12. package/dist/build/google-fonts/sort-variants.d.ts +5 -0
  13. package/dist/build/google-fonts/sort-variants.js +14 -0
  14. package/dist/build/google-fonts/sort-variants.js.map +1 -0
  15. package/dist/build/google-fonts/validate.d.ts +28 -0
  16. package/dist/build/google-fonts/validate.js +56 -0
  17. package/dist/build/google-fonts/validate.js.map +1 -0
  18. package/dist/build/layout-classification.d.ts +1 -1
  19. package/dist/build/layout-classification.js.map +1 -1
  20. package/dist/build/nitro-route-rules.d.ts +1 -1
  21. package/dist/build/nitro-route-rules.js.map +1 -1
  22. package/dist/build/precompress.d.ts +1 -1
  23. package/dist/build/precompress.js.map +1 -1
  24. package/dist/build/prerender.d.ts +1 -7
  25. package/dist/build/prerender.js +17 -6
  26. package/dist/build/prerender.js.map +1 -1
  27. package/dist/build/run-prerender.d.ts +1 -13
  28. package/dist/build/run-prerender.js +5 -1
  29. package/dist/build/run-prerender.js.map +1 -1
  30. package/dist/build/standalone.d.ts +1 -1
  31. package/dist/build/standalone.js +4 -3
  32. package/dist/build/standalone.js.map +1 -1
  33. package/dist/check.js +30 -18
  34. package/dist/check.js.map +1 -1
  35. package/dist/cli.js +4 -0
  36. package/dist/cli.js.map +1 -1
  37. package/dist/cloudflare/kv-cache-handler.d.ts +5 -0
  38. package/dist/cloudflare/kv-cache-handler.js +56 -35
  39. package/dist/cloudflare/kv-cache-handler.js.map +1 -1
  40. package/dist/cloudflare/tpr.d.ts +1 -16
  41. package/dist/cloudflare/tpr.js +1 -1
  42. package/dist/cloudflare/tpr.js.map +1 -1
  43. package/dist/config/config-matchers.js +1 -0
  44. package/dist/config/config-matchers.js.map +1 -1
  45. package/dist/config/dotenv.d.ts +1 -1
  46. package/dist/config/dotenv.js.map +1 -1
  47. package/dist/config/next-config.d.ts +38 -2
  48. package/dist/config/next-config.js +24 -0
  49. package/dist/config/next-config.js.map +1 -1
  50. package/dist/deploy.d.ts +1 -1
  51. package/dist/deploy.js +18 -23
  52. package/dist/deploy.js.map +1 -1
  53. package/dist/entries/app-rsc-entry.js +387 -1718
  54. package/dist/entries/app-rsc-entry.js.map +1 -1
  55. package/dist/entries/app-rsc-manifest.d.ts +24 -0
  56. package/dist/entries/app-rsc-manifest.js +153 -0
  57. package/dist/entries/app-rsc-manifest.js.map +1 -0
  58. package/dist/entries/pages-server-entry.js +13 -103
  59. package/dist/entries/pages-server-entry.js.map +1 -1
  60. package/dist/index.js +59 -34
  61. package/dist/index.js.map +1 -1
  62. package/dist/init.d.ts +1 -1
  63. package/dist/init.js.map +1 -1
  64. package/dist/plugins/async-hooks-stub.d.ts +1 -2
  65. package/dist/plugins/async-hooks-stub.js +2 -2
  66. package/dist/plugins/async-hooks-stub.js.map +1 -1
  67. package/dist/plugins/fonts.d.ts +1 -20
  68. package/dist/plugins/fonts.js +42 -21
  69. package/dist/plugins/fonts.js.map +1 -1
  70. package/dist/plugins/rsc-client-shim-excludes.d.ts +6 -0
  71. package/dist/plugins/rsc-client-shim-excludes.js +27 -0
  72. package/dist/plugins/rsc-client-shim-excludes.js.map +1 -0
  73. package/dist/plugins/server-externals-manifest.d.ts +1 -11
  74. package/dist/plugins/server-externals-manifest.js +1 -1
  75. package/dist/plugins/server-externals-manifest.js.map +1 -1
  76. package/dist/routing/app-router.d.ts +14 -5
  77. package/dist/routing/app-router.js +82 -5
  78. package/dist/routing/app-router.js.map +1 -1
  79. package/dist/routing/file-matcher.d.ts +1 -3
  80. package/dist/routing/file-matcher.js +1 -1
  81. package/dist/routing/file-matcher.js.map +1 -1
  82. package/dist/routing/route-pattern.d.ts +9 -0
  83. package/dist/routing/route-pattern.js +90 -0
  84. package/dist/routing/route-pattern.js.map +1 -0
  85. package/dist/routing/route-trie.js +10 -11
  86. package/dist/routing/route-trie.js.map +1 -1
  87. package/dist/routing/utils.d.ts +1 -29
  88. package/dist/routing/utils.js +1 -1
  89. package/dist/routing/utils.js.map +1 -1
  90. package/dist/server/app-browser-entry.js +63 -5
  91. package/dist/server/app-browser-entry.js.map +1 -1
  92. package/dist/server/app-browser-state.d.ts +1 -1
  93. package/dist/server/app-browser-state.js.map +1 -1
  94. package/dist/server/app-browser-stream.d.ts +1 -1
  95. package/dist/server/app-browser-stream.js.map +1 -1
  96. package/dist/server/app-elements.d.ts +1 -2
  97. package/dist/server/app-elements.js +1 -1
  98. package/dist/server/app-elements.js.map +1 -1
  99. package/dist/server/app-middleware.d.ts +32 -0
  100. package/dist/server/app-middleware.js +147 -0
  101. package/dist/server/app-middleware.js.map +1 -0
  102. package/dist/server/app-page-boundary-render.d.ts +5 -1
  103. package/dist/server/app-page-boundary-render.js +52 -30
  104. package/dist/server/app-page-boundary-render.js.map +1 -1
  105. package/dist/server/app-page-boundary.d.ts +13 -1
  106. package/dist/server/app-page-boundary.js +37 -17
  107. package/dist/server/app-page-boundary.js.map +1 -1
  108. package/dist/server/app-page-cache.d.ts +4 -1
  109. package/dist/server/app-page-cache.js +38 -2
  110. package/dist/server/app-page-cache.js.map +1 -1
  111. package/dist/server/app-page-dispatch.d.ts +120 -0
  112. package/dist/server/app-page-dispatch.js +332 -0
  113. package/dist/server/app-page-dispatch.js.map +1 -0
  114. package/dist/server/app-page-execution.d.ts +6 -3
  115. package/dist/server/app-page-execution.js +22 -10
  116. package/dist/server/app-page-execution.js.map +1 -1
  117. package/dist/server/app-page-head.d.ts +55 -0
  118. package/dist/server/app-page-head.js +196 -0
  119. package/dist/server/app-page-head.js.map +1 -0
  120. package/dist/server/app-page-method.d.ts +16 -0
  121. package/dist/server/app-page-method.js +30 -0
  122. package/dist/server/app-page-method.js.map +1 -0
  123. package/dist/server/app-page-params.d.ts +7 -0
  124. package/dist/server/app-page-params.js +28 -0
  125. package/dist/server/app-page-params.js.map +1 -0
  126. package/dist/server/app-page-probe.d.ts +1 -1
  127. package/dist/server/app-page-probe.js.map +1 -1
  128. package/dist/server/app-page-render.d.ts +4 -3
  129. package/dist/server/app-page-render.js +54 -8
  130. package/dist/server/app-page-render.js.map +1 -1
  131. package/dist/server/app-page-request.d.ts +5 -5
  132. package/dist/server/app-page-request.js.map +1 -1
  133. package/dist/server/app-page-response.d.ts +1 -1
  134. package/dist/server/app-page-response.js.map +1 -1
  135. package/dist/server/app-page-route-wiring.d.ts +15 -11
  136. package/dist/server/app-page-route-wiring.js +31 -9
  137. package/dist/server/app-page-route-wiring.js.map +1 -1
  138. package/dist/server/app-page-stream.d.ts +12 -1
  139. package/dist/server/app-page-stream.js +10 -4
  140. package/dist/server/app-page-stream.js.map +1 -1
  141. package/dist/server/app-prerender-endpoints.d.ts +19 -0
  142. package/dist/server/app-prerender-endpoints.js +96 -0
  143. package/dist/server/app-prerender-endpoints.js.map +1 -0
  144. package/dist/server/app-prerender-static-params.d.ts +16 -0
  145. package/dist/server/app-prerender-static-params.js +14 -0
  146. package/dist/server/app-prerender-static-params.js.map +1 -0
  147. package/dist/server/app-route-handler-cache.d.ts +4 -1
  148. package/dist/server/app-route-handler-cache.js +6 -2
  149. package/dist/server/app-route-handler-cache.js.map +1 -1
  150. package/dist/server/app-route-handler-dispatch.d.ts +42 -0
  151. package/dist/server/app-route-handler-dispatch.js +147 -0
  152. package/dist/server/app-route-handler-dispatch.js.map +1 -0
  153. package/dist/server/app-route-handler-execution.d.ts +7 -3
  154. package/dist/server/app-route-handler-execution.js +32 -6
  155. package/dist/server/app-route-handler-execution.js.map +1 -1
  156. package/dist/server/app-route-handler-policy.d.ts +6 -2
  157. package/dist/server/app-route-handler-policy.js +8 -3
  158. package/dist/server/app-route-handler-policy.js.map +1 -1
  159. package/dist/server/app-route-handler-response.d.ts +2 -1
  160. package/dist/server/app-route-handler-response.js +44 -4
  161. package/dist/server/app-route-handler-response.js.map +1 -1
  162. package/dist/server/app-route-handler-runtime.d.ts +5 -2
  163. package/dist/server/app-route-handler-runtime.js +108 -2
  164. package/dist/server/app-route-handler-runtime.js.map +1 -1
  165. package/dist/server/app-router-entry.js.map +1 -1
  166. package/dist/server/app-rsc-errors.d.ts +27 -0
  167. package/dist/server/app-rsc-errors.js +42 -0
  168. package/dist/server/app-rsc-errors.js.map +1 -0
  169. package/dist/server/app-rsc-route-matching.d.ts +40 -0
  170. package/dist/server/app-rsc-route-matching.js +66 -0
  171. package/dist/server/app-rsc-route-matching.js.map +1 -0
  172. package/dist/server/app-server-action-execution.d.ts +120 -0
  173. package/dist/server/app-server-action-execution.js +355 -0
  174. package/dist/server/app-server-action-execution.js.map +1 -0
  175. package/dist/server/app-ssr-entry.d.ts +7 -0
  176. package/dist/server/app-ssr-entry.js +30 -9
  177. package/dist/server/app-ssr-entry.js.map +1 -1
  178. package/dist/server/app-ssr-stream.d.ts +5 -3
  179. package/dist/server/app-ssr-stream.js +29 -2
  180. package/dist/server/app-ssr-stream.js.map +1 -1
  181. package/dist/server/app-static-generation.d.ts +15 -0
  182. package/dist/server/app-static-generation.js +20 -0
  183. package/dist/server/app-static-generation.js.map +1 -0
  184. package/dist/server/csp.d.ts +1 -2
  185. package/dist/server/csp.js +1 -1
  186. package/dist/server/csp.js.map +1 -1
  187. package/dist/server/dev-module-runner.d.ts +1 -1
  188. package/dist/server/dev-module-runner.js.map +1 -1
  189. package/dist/server/dev-route-files.d.ts +7 -0
  190. package/dist/server/dev-route-files.js +73 -0
  191. package/dist/server/dev-route-files.js.map +1 -0
  192. package/dist/server/dev-server.js +4 -0
  193. package/dist/server/dev-server.js.map +1 -1
  194. package/dist/server/file-based-metadata.d.ts +17 -0
  195. package/dist/server/file-based-metadata.js +356 -0
  196. package/dist/server/file-based-metadata.js.map +1 -0
  197. package/dist/server/implicit-tags.d.ts +6 -0
  198. package/dist/server/implicit-tags.js +42 -0
  199. package/dist/server/implicit-tags.js.map +1 -0
  200. package/dist/server/instrumentation.js.map +1 -1
  201. package/dist/server/isr-cache.d.ts +20 -2
  202. package/dist/server/isr-cache.js +58 -7
  203. package/dist/server/isr-cache.js.map +1 -1
  204. package/dist/server/metadata-route-build-data.d.ts +25 -0
  205. package/dist/server/metadata-route-build-data.js +150 -0
  206. package/dist/server/metadata-route-build-data.js.map +1 -0
  207. package/dist/server/metadata-route-response.d.ts +17 -0
  208. package/dist/server/metadata-route-response.js +187 -0
  209. package/dist/server/metadata-route-response.js.map +1 -0
  210. package/dist/server/metadata-routes.d.ts +42 -4
  211. package/dist/server/metadata-routes.js +127 -11
  212. package/dist/server/metadata-routes.js.map +1 -1
  213. package/dist/server/middleware-matcher.d.ts +15 -0
  214. package/dist/server/middleware-matcher.js +102 -0
  215. package/dist/server/middleware-matcher.js.map +1 -0
  216. package/dist/server/middleware-request-headers.d.ts +1 -3
  217. package/dist/server/middleware-request-headers.js +5 -4
  218. package/dist/server/middleware-request-headers.js.map +1 -1
  219. package/dist/server/middleware-runtime.d.ts +39 -0
  220. package/dist/server/middleware-runtime.js +159 -0
  221. package/dist/server/middleware-runtime.js.map +1 -0
  222. package/dist/server/middleware.d.ts +5 -37
  223. package/dist/server/middleware.js +18 -228
  224. package/dist/server/middleware.js.map +1 -1
  225. package/dist/server/pages-api-route.d.ts +1 -1
  226. package/dist/server/pages-api-route.js.map +1 -1
  227. package/dist/server/pages-i18n.d.ts +2 -3
  228. package/dist/server/pages-i18n.js +1 -1
  229. package/dist/server/pages-i18n.js.map +1 -1
  230. package/dist/server/pages-node-compat.d.ts +1 -2
  231. package/dist/server/pages-node-compat.js +1 -1
  232. package/dist/server/pages-node-compat.js.map +1 -1
  233. package/dist/server/pages-page-data.d.ts +6 -2
  234. package/dist/server/pages-page-data.js +4 -0
  235. package/dist/server/pages-page-data.js.map +1 -1
  236. package/dist/server/pages-page-response.d.ts +1 -1
  237. package/dist/server/pages-page-response.js +2 -1
  238. package/dist/server/pages-page-response.js.map +1 -1
  239. package/dist/server/prerender-work-unit-setup.d.ts +7 -0
  240. package/dist/server/prerender-work-unit-setup.js +30 -0
  241. package/dist/server/prerender-work-unit-setup.js.map +1 -0
  242. package/dist/server/prod-server.js +12 -14
  243. package/dist/server/prod-server.js.map +1 -1
  244. package/dist/server/request-pipeline.d.ts +46 -5
  245. package/dist/server/request-pipeline.js +84 -5
  246. package/dist/server/request-pipeline.js.map +1 -1
  247. package/dist/server/rsc-stream-hints.d.ts +5 -0
  248. package/dist/server/rsc-stream-hints.js +35 -0
  249. package/dist/server/rsc-stream-hints.js.map +1 -0
  250. package/dist/server/seed-cache.js.map +1 -1
  251. package/dist/server/server-action-not-found.d.ts +9 -0
  252. package/dist/server/server-action-not-found.js +40 -0
  253. package/dist/server/server-action-not-found.js.map +1 -0
  254. package/dist/server/socket-error-backstop.d.ts +17 -0
  255. package/dist/server/socket-error-backstop.js +129 -0
  256. package/dist/server/socket-error-backstop.js.map +1 -0
  257. package/dist/server/static-file-cache.d.ts +1 -1
  258. package/dist/server/static-file-cache.js.map +1 -1
  259. package/dist/shims/cache-runtime.js +16 -3
  260. package/dist/shims/cache-runtime.js.map +1 -1
  261. package/dist/shims/cache.d.ts +27 -2
  262. package/dist/shims/cache.js +135 -24
  263. package/dist/shims/cache.js.map +1 -1
  264. package/dist/shims/error-boundary.d.ts +49 -4
  265. package/dist/shims/error-boundary.js +76 -4
  266. package/dist/shims/error-boundary.js.map +1 -1
  267. package/dist/shims/fetch-cache.d.ts +10 -1
  268. package/dist/shims/fetch-cache.js +24 -4
  269. package/dist/shims/fetch-cache.js.map +1 -1
  270. package/dist/shims/font-google-base.d.ts +21 -22
  271. package/dist/shims/font-google-base.js +86 -29
  272. package/dist/shims/font-google-base.js.map +1 -1
  273. package/dist/shims/form.js +1 -1
  274. package/dist/shims/headers.d.ts +14 -2
  275. package/dist/shims/headers.js +127 -17
  276. package/dist/shims/headers.js.map +1 -1
  277. package/dist/shims/image.js +26 -8
  278. package/dist/shims/image.js.map +1 -1
  279. package/dist/shims/internal/make-hanging-promise.d.ts +16 -0
  280. package/dist/shims/internal/make-hanging-promise.js +46 -0
  281. package/dist/shims/internal/make-hanging-promise.js.map +1 -0
  282. package/dist/shims/internal/work-unit-async-storage.d.ts +26 -3
  283. package/dist/shims/internal/work-unit-async-storage.js +6 -3
  284. package/dist/shims/internal/work-unit-async-storage.js.map +1 -1
  285. package/dist/shims/link.js +1 -1
  286. package/dist/shims/metadata.d.ts +38 -26
  287. package/dist/shims/metadata.js +75 -45
  288. package/dist/shims/metadata.js.map +1 -1
  289. package/dist/shims/navigation.d.ts +17 -4
  290. package/dist/shims/navigation.js +29 -6
  291. package/dist/shims/navigation.js.map +1 -1
  292. package/dist/shims/navigation.react-server.d.ts +2 -2
  293. package/dist/shims/navigation.react-server.js +2 -2
  294. package/dist/shims/navigation.react-server.js.map +1 -1
  295. package/dist/shims/offline.d.ts +5 -0
  296. package/dist/shims/offline.js +17 -0
  297. package/dist/shims/offline.js.map +1 -0
  298. package/dist/shims/request-state-types.d.ts +2 -1
  299. package/dist/shims/root-params.d.ts +11 -0
  300. package/dist/shims/root-params.js +24 -0
  301. package/dist/shims/root-params.js.map +1 -0
  302. package/dist/shims/router.js +1 -1
  303. package/dist/shims/server.d.ts +5 -1
  304. package/dist/shims/server.js +101 -10
  305. package/dist/shims/server.js.map +1 -1
  306. package/dist/shims/thenable-params.d.ts +5 -0
  307. package/dist/shims/thenable-params.js +37 -0
  308. package/dist/shims/thenable-params.js.map +1 -0
  309. package/dist/shims/unified-request-context.d.ts +2 -1
  310. package/dist/shims/unified-request-context.js +4 -0
  311. package/dist/shims/unified-request-context.js.map +1 -1
  312. package/dist/shims/url-safety.d.ts +3 -1
  313. package/dist/shims/url-safety.js +5 -1
  314. package/dist/shims/url-safety.js.map +1 -1
  315. package/dist/utils/error-cause.d.ts +5 -0
  316. package/dist/utils/error-cause.js +97 -0
  317. package/dist/utils/error-cause.js.map +1 -0
  318. package/dist/utils/lazy-chunks.d.ts +1 -1
  319. package/dist/utils/lazy-chunks.js.map +1 -1
  320. package/package.json +6 -1
  321. package/dist/server/middleware-codegen.d.ts +0 -54
  322. package/dist/server/middleware-codegen.js +0 -414
  323. package/dist/server/middleware-codegen.js.map +0 -1
@@ -0,0 +1,97 @@
1
+ //#region src/utils/error-cause.ts
2
+ /**
3
+ * Embed an Error's `.cause` chain into its own `.message` and `.stack` so
4
+ * single-pass formatters (Vite's "Internal server error: ${err.message}\n${err.stack}"
5
+ * dev-server logger, anything that just prints message + stack) reveal the
6
+ * underlying root cause instead of silently dropping it.
7
+ *
8
+ * Without this, a wrapper like `new Error("Failed query", { cause: pgError })`
9
+ * shows up in the Vite dev console as just "Failed query" — the actual
10
+ * ECONNREFUSED / role-missing / socket-error in `.cause` is lost.
11
+ *
12
+ * Intended for **dev-server use only**. Production loggers (Node's
13
+ * `console.error` → `util.inspect`, workerd's runtime logger) already render
14
+ * `.cause` natively, so calling this in prod would double-print the cause —
15
+ * once in the synthesized message, once in util.inspect's `[cause]:` block.
16
+ * Callers should gate on `process.env.NODE_ENV !== "production"` (Vite
17
+ * build-time-replaces this, so the prod bundle gets a no-op).
18
+ *
19
+ * - Best-effort: never throws. Frozen / non-extensible errors are left untouched.
20
+ * - Idempotent (repeat calls are no-ops via a non-enumerable module-private symbol).
21
+ * - Cycle-safe and depth-capped (10) for pathological cause graphs.
22
+ * - Cause stack frames are appended as `at` lines so stack-cleaning regexes
23
+ * like Vite's `/^\s*at/` filter preserve them.
24
+ */
25
+ const FLATTENED_MARKER = Symbol("vinext.errorCausesFlattened");
26
+ const MAX_CAUSE_DEPTH = 10;
27
+ function stringifyNonError(value) {
28
+ if (typeof value === "string") return value;
29
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
30
+ if (value === null || value === void 0) return String(value);
31
+ try {
32
+ return JSON.stringify(value) ?? Object.prototype.toString.call(value);
33
+ } catch {
34
+ return Object.prototype.toString.call(value);
35
+ }
36
+ }
37
+ function flattenErrorCauses(err) {
38
+ if (!(err instanceof Error)) return;
39
+ const marked = err;
40
+ if (marked[FLATTENED_MARKER]) return;
41
+ try {
42
+ Object.defineProperty(marked, FLATTENED_MARKER, {
43
+ value: true,
44
+ enumerable: false,
45
+ configurable: false,
46
+ writable: false
47
+ });
48
+ } catch {
49
+ return;
50
+ }
51
+ const seen = new WeakSet([err]);
52
+ const causes = [];
53
+ let cur = err.cause;
54
+ let depth = 0;
55
+ while (cur != null && depth < MAX_CAUSE_DEPTH) {
56
+ if (typeof cur === "object") {
57
+ if (seen.has(cur)) break;
58
+ seen.add(cur);
59
+ }
60
+ if (cur instanceof Error) {
61
+ causes.push({
62
+ message: cur.message,
63
+ stack: cur.stack
64
+ });
65
+ cur = cur.cause;
66
+ } else {
67
+ causes.push({ message: stringifyNonError(cur) });
68
+ cur = null;
69
+ }
70
+ depth++;
71
+ }
72
+ if (causes.length === 0) return;
73
+ const messageSuffix = causes.map((c) => ` [cause]: ${c.message}`).join("\n");
74
+ try {
75
+ err.message = `${err.message}\n${messageSuffix}`;
76
+ } catch {
77
+ return;
78
+ }
79
+ if (typeof err.stack === "string") {
80
+ let stackSuffix = "";
81
+ for (const c of causes) {
82
+ const headline = c.message.split("\n", 1)[0];
83
+ stackSuffix += `\n at [cause: ${headline}]`;
84
+ if (c.stack) {
85
+ const frames = c.stack.split("\n").filter((l) => /^\s*at\s/.test(l)).join("\n");
86
+ if (frames) stackSuffix += `\n${frames}`;
87
+ }
88
+ }
89
+ try {
90
+ err.stack = `${err.stack}${stackSuffix}`;
91
+ } catch {}
92
+ }
93
+ }
94
+ //#endregion
95
+ export { flattenErrorCauses };
96
+
97
+ //# sourceMappingURL=error-cause.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-cause.js","names":[],"sources":["../../src/utils/error-cause.ts"],"sourcesContent":["/**\n * Embed an Error's `.cause` chain into its own `.message` and `.stack` so\n * single-pass formatters (Vite's \"Internal server error: ${err.message}\\n${err.stack}\"\n * dev-server logger, anything that just prints message + stack) reveal the\n * underlying root cause instead of silently dropping it.\n *\n * Without this, a wrapper like `new Error(\"Failed query\", { cause: pgError })`\n * shows up in the Vite dev console as just \"Failed query\" — the actual\n * ECONNREFUSED / role-missing / socket-error in `.cause` is lost.\n *\n * Intended for **dev-server use only**. Production loggers (Node's\n * `console.error` → `util.inspect`, workerd's runtime logger) already render\n * `.cause` natively, so calling this in prod would double-print the cause —\n * once in the synthesized message, once in util.inspect's `[cause]:` block.\n * Callers should gate on `process.env.NODE_ENV !== \"production\"` (Vite\n * build-time-replaces this, so the prod bundle gets a no-op).\n *\n * - Best-effort: never throws. Frozen / non-extensible errors are left untouched.\n * - Idempotent (repeat calls are no-ops via a non-enumerable module-private symbol).\n * - Cycle-safe and depth-capped (10) for pathological cause graphs.\n * - Cause stack frames are appended as `at` lines so stack-cleaning regexes\n * like Vite's `/^\\s*at/` filter preserve them.\n */\nconst FLATTENED_MARKER = Symbol(\"vinext.errorCausesFlattened\");\nconst MAX_CAUSE_DEPTH = 10;\n\nfunction stringifyNonError(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return String(value);\n }\n if (value === null || value === undefined) return String(value);\n try {\n return JSON.stringify(value) ?? Object.prototype.toString.call(value);\n } catch {\n return Object.prototype.toString.call(value);\n }\n}\n\nexport function flattenErrorCauses(err: unknown): void {\n if (!(err instanceof Error)) return;\n const marked = err as Error & { [FLATTENED_MARKER]?: true };\n if (marked[FLATTENED_MARKER]) return;\n // defineProperty throws on frozen errors; mutations below also throw.\n // Wrap each step so this function honours its \"never throw\" contract —\n // a thrown TypeError here would propagate from the caller's catch block\n // and replace the user's real error with our enrichment failure.\n try {\n Object.defineProperty(marked, FLATTENED_MARKER, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n } catch {\n return;\n }\n\n const seen = new WeakSet<object>([err]);\n const causes: Array<{ message: string; stack?: string }> = [];\n let cur: unknown = (err as { cause?: unknown }).cause;\n let depth = 0;\n while (cur != null && depth < MAX_CAUSE_DEPTH) {\n if (typeof cur === \"object\") {\n if (seen.has(cur as object)) break;\n seen.add(cur as object);\n }\n if (cur instanceof Error) {\n causes.push({ message: cur.message, stack: cur.stack });\n cur = (cur as { cause?: unknown }).cause;\n } else {\n causes.push({ message: stringifyNonError(cur) });\n cur = null;\n }\n depth++;\n }\n if (causes.length === 0) return;\n\n const messageSuffix = causes.map((c) => ` [cause]: ${c.message}`).join(\"\\n\");\n try {\n err.message = `${err.message}\\n${messageSuffix}`;\n } catch {\n // Frozen / non-writable .message — leave the rest untouched too,\n // since a partial write would be misleading.\n return;\n }\n\n if (typeof err.stack === \"string\") {\n let stackSuffix = \"\";\n for (const c of causes) {\n const headline = c.message.split(\"\\n\", 1)[0];\n stackSuffix += `\\n at [cause: ${headline}]`;\n if (c.stack) {\n const frames = c.stack\n .split(\"\\n\")\n .filter((l) => /^\\s*at\\s/.test(l))\n .join(\"\\n\");\n if (frames) stackSuffix += `\\n${frames}`;\n }\n }\n try {\n err.stack = `${err.stack}${stackSuffix}`;\n } catch {\n // Stack is read-only on some hosts; message enrichment still holds.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,mBAAmB,OAAO,8BAA8B;AAC9D,MAAM,kBAAkB;AAExB,SAAS,kBAAkB,OAAwB;AACjD,KAAI,OAAO,UAAU,SAAU,QAAO;AACtC,KAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,SAC9E,QAAO,OAAO,MAAM;AAEtB,KAAI,UAAU,QAAQ,UAAU,KAAA,EAAW,QAAO,OAAO,MAAM;AAC/D,KAAI;AACF,SAAO,KAAK,UAAU,MAAM,IAAI,OAAO,UAAU,SAAS,KAAK,MAAM;SAC/D;AACN,SAAO,OAAO,UAAU,SAAS,KAAK,MAAM;;;AAIhD,SAAgB,mBAAmB,KAAoB;AACrD,KAAI,EAAE,eAAe,OAAQ;CAC7B,MAAM,SAAS;AACf,KAAI,OAAO,kBAAmB;AAK9B,KAAI;AACF,SAAO,eAAe,QAAQ,kBAAkB;GAC9C,OAAO;GACP,YAAY;GACZ,cAAc;GACd,UAAU;GACX,CAAC;SACI;AACN;;CAGF,MAAM,OAAO,IAAI,QAAgB,CAAC,IAAI,CAAC;CACvC,MAAM,SAAqD,EAAE;CAC7D,IAAI,MAAgB,IAA4B;CAChD,IAAI,QAAQ;AACZ,QAAO,OAAO,QAAQ,QAAQ,iBAAiB;AAC7C,MAAI,OAAO,QAAQ,UAAU;AAC3B,OAAI,KAAK,IAAI,IAAc,CAAE;AAC7B,QAAK,IAAI,IAAc;;AAEzB,MAAI,eAAe,OAAO;AACxB,UAAO,KAAK;IAAE,SAAS,IAAI;IAAS,OAAO,IAAI;IAAO,CAAC;AACvD,SAAO,IAA4B;SAC9B;AACL,UAAO,KAAK,EAAE,SAAS,kBAAkB,IAAI,EAAE,CAAC;AAChD,SAAM;;AAER;;AAEF,KAAI,OAAO,WAAW,EAAG;CAEzB,MAAM,gBAAgB,OAAO,KAAK,MAAM,cAAc,EAAE,UAAU,CAAC,KAAK,KAAK;AAC7E,KAAI;AACF,MAAI,UAAU,GAAG,IAAI,QAAQ,IAAI;SAC3B;AAGN;;AAGF,KAAI,OAAO,IAAI,UAAU,UAAU;EACjC,IAAI,cAAc;AAClB,OAAK,MAAM,KAAK,QAAQ;GACtB,MAAM,WAAW,EAAE,QAAQ,MAAM,MAAM,EAAE,CAAC;AAC1C,kBAAe,oBAAoB,SAAS;AAC5C,OAAI,EAAE,OAAO;IACX,MAAM,SAAS,EAAE,MACd,MAAM,KAAK,CACX,QAAQ,MAAM,WAAW,KAAK,EAAE,CAAC,CACjC,KAAK,KAAK;AACb,QAAI,OAAQ,gBAAe,KAAK;;;AAGpC,MAAI;AACF,OAAI,QAAQ,GAAG,IAAI,QAAQ;UACrB"}
@@ -30,5 +30,5 @@ type BuildManifestChunk = {
30
30
  */
31
31
  declare function computeLazyChunks(buildManifest: Record<string, BuildManifestChunk>): string[];
32
32
  //#endregion
33
- export { BuildManifestChunk, computeLazyChunks };
33
+ export { computeLazyChunks };
34
34
  //# sourceMappingURL=lazy-chunks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lazy-chunks.js","names":[],"sources":["../../src/utils/lazy-chunks.ts"],"sourcesContent":["/**\n * Build-manifest chunk metadata used to compute lazy chunks.\n */\nexport type BuildManifestChunk = {\n file: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n imports?: string[];\n dynamicImports?: string[];\n css?: string[];\n assets?: string[];\n};\n\n/**\n * Compute the set of chunk filenames that are ONLY reachable through dynamic\n * imports (i.e. behind React.lazy(), next/dynamic, or manual import()).\n *\n * These chunks should NOT be modulepreloaded in the HTML — they will be\n * fetched on demand when the dynamic import executes.\n *\n * Algorithm: Starting from all entry chunks in the build manifest, walk the\n * static `imports` tree (breadth-first). Any chunk file NOT reached by this\n * walk is only reachable through `dynamicImports` and is therefore \"lazy\".\n *\n * @param buildManifest - Vite's build manifest (manifest.json), which is a\n * Record<string, ManifestChunk> where each chunk has `file`, `imports`,\n * `dynamicImports`, `isEntry`, and `isDynamicEntry` fields.\n * @returns Array of chunk filenames (e.g. \"assets/mermaid-NOHMQCX5.js\") that\n * should be excluded from modulepreload hints.\n */\nexport function computeLazyChunks(buildManifest: Record<string, BuildManifestChunk>): string[] {\n // Collect all chunk files that are statically reachable from entries\n const eagerFiles = new Set<string>();\n const visited = new Set<string>();\n const queue: string[] = [];\n\n // Start BFS from all entry chunks\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.isEntry) {\n queue.push(key);\n }\n }\n\n while (queue.length > 0) {\n const key = queue.shift();\n if (!key || visited.has(key)) continue;\n visited.add(key);\n\n const chunk = buildManifest[key];\n if (!chunk) continue;\n\n // Mark this chunk's file as eager\n eagerFiles.add(chunk.file);\n\n // Also mark its CSS as eager (CSS should always be preloaded to avoid FOUC)\n if (chunk.css) {\n for (const cssFile of chunk.css) {\n eagerFiles.add(cssFile);\n }\n }\n\n // Follow only static imports — NOT dynamicImports\n if (chunk.imports) {\n for (const imp of chunk.imports) {\n if (!visited.has(imp)) {\n queue.push(imp);\n }\n }\n }\n }\n\n // Any JS file in the manifest that's NOT in eagerFiles is a lazy chunk\n const lazyChunks: string[] = [];\n const allFiles = new Set<string>();\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.file && !allFiles.has(chunk.file)) {\n allFiles.add(chunk.file);\n if (!eagerFiles.has(chunk.file) && chunk.file.endsWith(\".js\")) {\n lazyChunks.push(chunk.file);\n }\n }\n }\n\n return lazyChunks;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,SAAgB,kBAAkB,eAA6D;CAE7F,MAAM,6BAAa,IAAI,KAAa;CACpC,MAAM,0BAAU,IAAI,KAAa;CACjC,MAAM,QAAkB,EAAE;AAG1B,MAAK,MAAM,OAAO,OAAO,KAAK,cAAc,CAE1C,KADc,cAAc,KAClB,QACR,OAAM,KAAK,IAAI;AAInB,QAAO,MAAM,SAAS,GAAG;EACvB,MAAM,MAAM,MAAM,OAAO;AACzB,MAAI,CAAC,OAAO,QAAQ,IAAI,IAAI,CAAE;AAC9B,UAAQ,IAAI,IAAI;EAEhB,MAAM,QAAQ,cAAc;AAC5B,MAAI,CAAC,MAAO;AAGZ,aAAW,IAAI,MAAM,KAAK;AAG1B,MAAI,MAAM,IACR,MAAK,MAAM,WAAW,MAAM,IAC1B,YAAW,IAAI,QAAQ;AAK3B,MAAI,MAAM;QACH,MAAM,OAAO,MAAM,QACtB,KAAI,CAAC,QAAQ,IAAI,IAAI,CACnB,OAAM,KAAK,IAAI;;;CAOvB,MAAM,aAAuB,EAAE;CAC/B,MAAM,2BAAW,IAAI,KAAa;AAClC,MAAK,MAAM,OAAO,OAAO,KAAK,cAAc,EAAE;EAC5C,MAAM,QAAQ,cAAc;AAC5B,MAAI,MAAM,QAAQ,CAAC,SAAS,IAAI,MAAM,KAAK,EAAE;AAC3C,YAAS,IAAI,MAAM,KAAK;AACxB,OAAI,CAAC,WAAW,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,SAAS,MAAM,CAC3D,YAAW,KAAK,MAAM,KAAK;;;AAKjC,QAAO"}
1
+ {"version":3,"file":"lazy-chunks.js","names":[],"sources":["../../src/utils/lazy-chunks.ts"],"sourcesContent":["/**\n * Build-manifest chunk metadata used to compute lazy chunks.\n */\ntype BuildManifestChunk = {\n file: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n imports?: string[];\n dynamicImports?: string[];\n css?: string[];\n assets?: string[];\n};\n\n/**\n * Compute the set of chunk filenames that are ONLY reachable through dynamic\n * imports (i.e. behind React.lazy(), next/dynamic, or manual import()).\n *\n * These chunks should NOT be modulepreloaded in the HTML — they will be\n * fetched on demand when the dynamic import executes.\n *\n * Algorithm: Starting from all entry chunks in the build manifest, walk the\n * static `imports` tree (breadth-first). Any chunk file NOT reached by this\n * walk is only reachable through `dynamicImports` and is therefore \"lazy\".\n *\n * @param buildManifest - Vite's build manifest (manifest.json), which is a\n * Record<string, ManifestChunk> where each chunk has `file`, `imports`,\n * `dynamicImports`, `isEntry`, and `isDynamicEntry` fields.\n * @returns Array of chunk filenames (e.g. \"assets/mermaid-NOHMQCX5.js\") that\n * should be excluded from modulepreload hints.\n */\nexport function computeLazyChunks(buildManifest: Record<string, BuildManifestChunk>): string[] {\n // Collect all chunk files that are statically reachable from entries\n const eagerFiles = new Set<string>();\n const visited = new Set<string>();\n const queue: string[] = [];\n\n // Start BFS from all entry chunks\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.isEntry) {\n queue.push(key);\n }\n }\n\n while (queue.length > 0) {\n const key = queue.shift();\n if (!key || visited.has(key)) continue;\n visited.add(key);\n\n const chunk = buildManifest[key];\n if (!chunk) continue;\n\n // Mark this chunk's file as eager\n eagerFiles.add(chunk.file);\n\n // Also mark its CSS as eager (CSS should always be preloaded to avoid FOUC)\n if (chunk.css) {\n for (const cssFile of chunk.css) {\n eagerFiles.add(cssFile);\n }\n }\n\n // Follow only static imports — NOT dynamicImports\n if (chunk.imports) {\n for (const imp of chunk.imports) {\n if (!visited.has(imp)) {\n queue.push(imp);\n }\n }\n }\n }\n\n // Any JS file in the manifest that's NOT in eagerFiles is a lazy chunk\n const lazyChunks: string[] = [];\n const allFiles = new Set<string>();\n for (const key of Object.keys(buildManifest)) {\n const chunk = buildManifest[key];\n if (chunk.file && !allFiles.has(chunk.file)) {\n allFiles.add(chunk.file);\n if (!eagerFiles.has(chunk.file) && chunk.file.endsWith(\".js\")) {\n lazyChunks.push(chunk.file);\n }\n }\n }\n\n return lazyChunks;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,SAAgB,kBAAkB,eAA6D;CAE7F,MAAM,6BAAa,IAAI,KAAa;CACpC,MAAM,0BAAU,IAAI,KAAa;CACjC,MAAM,QAAkB,EAAE;AAG1B,MAAK,MAAM,OAAO,OAAO,KAAK,cAAc,CAE1C,KADc,cAAc,KAClB,QACR,OAAM,KAAK,IAAI;AAInB,QAAO,MAAM,SAAS,GAAG;EACvB,MAAM,MAAM,MAAM,OAAO;AACzB,MAAI,CAAC,OAAO,QAAQ,IAAI,IAAI,CAAE;AAC9B,UAAQ,IAAI,IAAI;EAEhB,MAAM,QAAQ,cAAc;AAC5B,MAAI,CAAC,MAAO;AAGZ,aAAW,IAAI,MAAM,KAAK;AAG1B,MAAI,MAAM,IACR,MAAK,MAAM,WAAW,MAAM,IAC1B,YAAW,IAAI,QAAQ;AAK3B,MAAI,MAAM;QACH,MAAM,OAAO,MAAM,QACtB,KAAI,CAAC,QAAQ,IAAI,IAAI,CACnB,OAAM,KAAK,IAAI;;;CAOvB,MAAM,aAAuB,EAAE;CAC/B,MAAM,2BAAW,IAAI,KAAa;AAClC,MAAK,MAAM,OAAO,OAAO,KAAK,cAAc,EAAE;EAC5C,MAAM,QAAQ,cAAc;AAC5B,MAAI,MAAM,QAAQ,CAAC,SAAS,IAAI,MAAM,KAAK,EAAE;AAC3C,YAAS,IAAI,MAAM,KAAK;AACxB,OAAI,CAAC,WAAW,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,SAAS,MAAM,CAC3D,YAAW,KAAK,MAAM,KAAK;;;AAKjC,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vinext",
3
- "version": "0.0.44",
3
+ "version": "0.0.46",
4
4
  "description": "Run Next.js apps on Vite. Drop-in replacement for the next CLI.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,6 +41,10 @@
41
41
  "types": "./dist/server/image-optimization.d.ts",
42
42
  "import": "./dist/server/image-optimization.js"
43
43
  },
44
+ "./server/request-pipeline": {
45
+ "types": "./dist/server/request-pipeline.d.ts",
46
+ "import": "./dist/server/request-pipeline.js"
47
+ },
44
48
  "./server/app-router-entry": {
45
49
  "types": "./dist/server/app-router-entry.d.ts",
46
50
  "import": "./dist/server/app-router-entry.js"
@@ -57,6 +61,7 @@
57
61
  "dependencies": {
58
62
  "@unpic/react": "^1.0.2",
59
63
  "@vercel/og": "^0.8.6",
64
+ "image-size": "2.0.2",
60
65
  "magic-string": "^0.30.21",
61
66
  "vite-plugin-commonjs": "^0.10.4",
62
67
  "vite-tsconfig-paths": "^6.1.1"
@@ -1,54 +0,0 @@
1
- //#region src/server/middleware-codegen.d.ts
2
- /**
3
- * Shared middleware matching code generator.
4
- *
5
- * Both the App Router RSC entry (entries/app-rsc-entry.ts) and the Pages Router
6
- * production entry (index.ts) need middleware matching logic inlined as
7
- * generated JavaScript strings. This module provides a single source of
8
- * truth to prevent the implementations from diverging.
9
- *
10
- * The regex detection guard (checking for "(" or "\\") is critical.
11
- * Without it, dot-escaping corrupts regex patterns like
12
- * /((?!api|_next).*), causing middleware to silently skip paths.
13
- */
14
- /**
15
- * Returns the generated JavaScript source for `__isSafeRegex` and `__safeRegExp`.
16
- *
17
- * @param style - "modern" emits const/let (for RSC entry), "es5" emits var (for prod entry)
18
- */
19
- declare function generateSafeRegExpCode(style?: "modern" | "es5"): string;
20
- /**
21
- * Returns the generated JavaScript source for `__normalizePath`.
22
- *
23
- * This must be kept in sync with `normalizePath()` in `normalize-path.ts`.
24
- * The inline version is used by codegen entries that can't import modules.
25
- *
26
- * @param style - "modern" emits const/let, "es5" emits var
27
- */
28
- declare function generateNormalizePathCode(style?: "modern" | "es5"): string;
29
- /**
30
- * Returns generated JavaScript source for route-path normalization that
31
- * preserves encoded path delimiters within a single segment.
32
- *
33
- * This mirrors decodeRouteSegment()/normalizePathnameForRouteMatch() in
34
- * routing/utils.ts so "%5F" becomes "_" while "%2F" remains "%2F".
35
- *
36
- * @param style - "modern" emits const/let, "es5" emits var
37
- */
38
- declare function generateRouteMatchNormalizationCode(style?: "modern" | "es5"): string;
39
- /**
40
- * Returns the generated JavaScript source for middleware pattern matching.
41
- *
42
- * This includes:
43
- * - `matchMiddlewarePattern(pathname, pattern)` — matches a single pattern
44
- * - `matchesMiddleware(pathname, matcher, request, i18nConfig)` — matches the full matcher config
45
- *
46
- * The generated code depends on `__safeRegExp` being defined in the same scope
47
- * (use `generateSafeRegExpCode` to emit it).
48
- *
49
- * @param style - "modern" emits const/let/arrow functions, "es5" emits var/function
50
- */
51
- declare function generateMiddlewareMatcherCode(style?: "modern" | "es5"): string;
52
- //#endregion
53
- export { generateMiddlewareMatcherCode, generateNormalizePathCode, generateRouteMatchNormalizationCode, generateSafeRegExpCode };
54
- //# sourceMappingURL=middleware-codegen.d.ts.map
@@ -1,414 +0,0 @@
1
- //#region src/server/middleware-codegen.ts
2
- /**
3
- * Shared middleware matching code generator.
4
- *
5
- * Both the App Router RSC entry (entries/app-rsc-entry.ts) and the Pages Router
6
- * production entry (index.ts) need middleware matching logic inlined as
7
- * generated JavaScript strings. This module provides a single source of
8
- * truth to prevent the implementations from diverging.
9
- *
10
- * The regex detection guard (checking for "(" or "\\") is critical.
11
- * Without it, dot-escaping corrupts regex patterns like
12
- * /((?!api|_next).*), causing middleware to silently skip paths.
13
- */
14
- /**
15
- * Returns the generated JavaScript source for `__isSafeRegex` and `__safeRegExp`.
16
- *
17
- * @param style - "modern" emits const/let (for RSC entry), "es5" emits var (for prod entry)
18
- */
19
- function generateSafeRegExpCode(style = "modern") {
20
- const v = style === "modern" ? "const" : "var";
21
- const l = style === "modern" ? "let" : "var";
22
- return `
23
- function __isSafeRegex(pattern) {
24
- ${v} quantifierAtDepth = [];
25
- ${l} depth = 0;
26
- ${l} i = 0;
27
- while (i < pattern.length) {
28
- ${v} ch = pattern[i];
29
- if (ch === "\\\\") { i += 2; continue; }
30
- if (ch === "[") {
31
- i++;
32
- while (i < pattern.length && pattern[i] !== "]") {
33
- if (pattern[i] === "\\\\") i++;
34
- i++;
35
- }
36
- i++;
37
- continue;
38
- }
39
- if (ch === "(") {
40
- depth++;
41
- if (quantifierAtDepth.length <= depth) quantifierAtDepth.push(false);
42
- else quantifierAtDepth[depth] = false;
43
- i++;
44
- continue;
45
- }
46
- if (ch === ")") {
47
- ${v} hadQ = depth > 0 && quantifierAtDepth[depth];
48
- if (depth > 0) depth--;
49
- ${v} next = pattern[i + 1];
50
- if (next === "+" || next === "*" || next === "{") {
51
- if (hadQ) return false;
52
- if (depth >= 0 && depth < quantifierAtDepth.length) quantifierAtDepth[depth] = true;
53
- }
54
- i++;
55
- continue;
56
- }
57
- if (ch === "+" || ch === "*") {
58
- if (depth > 0) quantifierAtDepth[depth] = true;
59
- i++;
60
- continue;
61
- }
62
- if (ch === "?") {
63
- ${v} prev = i > 0 ? pattern[i - 1] : "";
64
- if (prev !== "+" && prev !== "*" && prev !== "?" && prev !== "}") {
65
- if (depth > 0) quantifierAtDepth[depth] = true;
66
- }
67
- i++;
68
- continue;
69
- }
70
- if (ch === "{") {
71
- ${l} j = i + 1;
72
- while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;
73
- if (j < pattern.length && pattern[j] === "}" && j > i + 1) {
74
- if (depth > 0) quantifierAtDepth[depth] = true;
75
- i = j + 1;
76
- continue;
77
- }
78
- }
79
- i++;
80
- }
81
- return true;
82
- }
83
- function __safeRegExp(pattern, flags) {
84
- if (!__isSafeRegex(pattern)) {
85
- console.warn("[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): " + pattern);
86
- return null;
87
- }
88
- try { return new RegExp(pattern, flags); } catch { return null; }
89
- }`;
90
- }
91
- /**
92
- * Returns the generated JavaScript source for `__normalizePath`.
93
- *
94
- * This must be kept in sync with `normalizePath()` in `normalize-path.ts`.
95
- * The inline version is used by codegen entries that can't import modules.
96
- *
97
- * @param style - "modern" emits const/let, "es5" emits var
98
- */
99
- function generateNormalizePathCode(style = "modern") {
100
- const v = style === "modern" ? "const" : "var";
101
- return `
102
- function __normalizePath(pathname) {
103
- if (
104
- pathname === "/" ||
105
- (pathname.length > 1 &&
106
- pathname[0] === "/" &&
107
- !pathname.includes("//") &&
108
- !pathname.includes("/./") &&
109
- !pathname.includes("/../") &&
110
- !pathname.endsWith("/.") &&
111
- !pathname.endsWith("/.."))
112
- ) {
113
- return pathname;
114
- }
115
- ${v} segments = pathname.split("/");
116
- ${v} resolved = [];
117
- for (${style === "modern" ? "let" : "var"} i = 0; i < segments.length; i++) {
118
- ${v} seg = segments[i];
119
- if (seg === "" || seg === ".") continue;
120
- if (seg === "..") { resolved.pop(); }
121
- else { resolved.push(seg); }
122
- }
123
- return "/" + resolved.join("/");
124
- }`;
125
- }
126
- /**
127
- * Returns generated JavaScript source for route-path normalization that
128
- * preserves encoded path delimiters within a single segment.
129
- *
130
- * This mirrors decodeRouteSegment()/normalizePathnameForRouteMatch() in
131
- * routing/utils.ts so "%5F" becomes "_" while "%2F" remains "%2F".
132
- *
133
- * @param style - "modern" emits const/let, "es5" emits var
134
- */
135
- function generateRouteMatchNormalizationCode(style = "modern") {
136
- const v = style === "modern" ? "const" : "var";
137
- const l = style === "modern" ? "let" : "var";
138
- return `
139
- ${v} __pathDelimiterRegex = /([/#?\\\\]|%(2f|23|3f|5c))/gi;
140
- function __decodeRouteSegment(segment) {
141
- return decodeURIComponent(segment).replace(__pathDelimiterRegex, function (char) {
142
- return encodeURIComponent(char);
143
- });
144
- }
145
- function __decodeRouteSegmentSafe(segment) {
146
- try { return __decodeRouteSegment(segment); } catch (e) { return segment; }
147
- }
148
- function __normalizePathnameForRouteMatch(pathname) {
149
- ${v} segments = pathname.split("/");
150
- ${v} normalized = [];
151
- for (${l} i = 0; i < segments.length; i++) {
152
- normalized.push(__decodeRouteSegmentSafe(segments[i]));
153
- }
154
- return normalized.join("/");
155
- }
156
- function __normalizePathnameForRouteMatchStrict(pathname) {
157
- ${v} segments = pathname.split("/");
158
- ${v} normalized = [];
159
- for (${l} i = 0; i < segments.length; i++) {
160
- normalized.push(__decodeRouteSegment(segments[i]));
161
- }
162
- return normalized.join("/");
163
- }`;
164
- }
165
- /**
166
- * Returns the generated JavaScript source for middleware pattern matching.
167
- *
168
- * This includes:
169
- * - `matchMiddlewarePattern(pathname, pattern)` — matches a single pattern
170
- * - `matchesMiddleware(pathname, matcher, request, i18nConfig)` — matches the full matcher config
171
- *
172
- * The generated code depends on `__safeRegExp` being defined in the same scope
173
- * (use `generateSafeRegExpCode` to emit it).
174
- *
175
- * @param style - "modern" emits const/let/arrow functions, "es5" emits var/function
176
- */
177
- function generateMiddlewareMatcherCode(style = "modern") {
178
- const v = style === "modern" ? "const" : "var";
179
- const l = style === "modern" ? "let" : "var";
180
- return `
181
- ${v} __mwPatternCache = new Map();
182
- function __extractConstraint(str, re) {
183
- if (str[re.lastIndex] !== "(") return null;
184
- ${v} start = re.lastIndex + 1;
185
- ${l} depth = 1;
186
- ${l} i = start;
187
- while (i < str.length && depth > 0) {
188
- if (str[i] === "(") depth++;
189
- else if (str[i] === ")") depth--;
190
- i++;
191
- }
192
- if (depth !== 0) return null;
193
- re.lastIndex = i;
194
- return str.slice(start, i - 1);
195
- }
196
- function __compileMwPattern(pattern) {
197
- ${v} hasConstraints = /:[\\w-]+[*+]?\\(/.test(pattern);
198
- if (!hasConstraints && (pattern.includes("(") || pattern.includes("\\\\"))) {
199
- return __safeRegExp("^" + pattern + "$");
200
- }
201
- ${l} regexStr = "";
202
- ${v} tokenRe = /\\/:([\\w-]+)\\*|\\/:([\\w-]+)\\+|:([\\w-]+)|[.]|[^/:.]+|./g;
203
- ${l} tok;
204
- while ((tok = tokenRe.exec(pattern)) !== null) {
205
- if (tok[1] !== undefined) {
206
- ${v} c1 = hasConstraints ? __extractConstraint(pattern, tokenRe) : null;
207
- regexStr += c1 !== null ? "(?:/(" + c1 + "))?" : "(?:/.*)?";
208
- }
209
- else if (tok[2] !== undefined) {
210
- ${v} c2 = hasConstraints ? __extractConstraint(pattern, tokenRe) : null;
211
- regexStr += c2 !== null ? "(?:/(" + c2 + "))" : "(?:/.+)";
212
- }
213
- else if (tok[3] !== undefined) {
214
- ${v} constraint = hasConstraints ? __extractConstraint(pattern, tokenRe) : null;
215
- ${v} isOptional = pattern[tokenRe.lastIndex] === "?";
216
- if (isOptional) tokenRe.lastIndex += 1;
217
- ${v} group = constraint !== null ? "(" + constraint + ")" : "([^/]+)";
218
- if (isOptional && regexStr.endsWith("/")) {
219
- regexStr = regexStr.slice(0, -1) + "(?:/" + group + ")?";
220
- } else if (isOptional) {
221
- regexStr += group + "?";
222
- } else {
223
- regexStr += group;
224
- }
225
- }
226
- else if (tok[0] === ".") { regexStr += "\\\\."; }
227
- else { regexStr += tok[0]; }
228
- }
229
- return __safeRegExp("^" + regexStr + "$");
230
- }
231
- function matchMiddlewarePattern(pathname, pattern) {
232
- ${l} cached = __mwPatternCache.get(pattern);
233
- if (cached === undefined) {
234
- cached = __compileMwPattern(pattern);
235
- __mwPatternCache.set(pattern, cached);
236
- }
237
- return cached ? cached.test(pathname) : pathname === pattern;
238
- }
239
-
240
- ${v} __middlewareConditionRegexCache = new Map();
241
- // Requestless matcher checks reuse this singleton. Treat it as immutable.
242
- ${v} __emptyMiddlewareRequestContext = {
243
- headers: new Headers(),
244
- cookies: {},
245
- query: new URLSearchParams(),
246
- host: "",
247
- };
248
-
249
- function __normalizeMiddlewareHost(hostHeader, fallbackHostname) {
250
- ${v} host = hostHeader ?? fallbackHostname;
251
- return host.split(":", 1)[0].toLowerCase();
252
- }
253
-
254
- function __parseMiddlewareCookies(cookieHeader) {
255
- if (!cookieHeader) return {};
256
- ${v} cookies = {};
257
- for (${v} part of cookieHeader.split(";")) {
258
- ${v} eq = part.indexOf("=");
259
- if (eq === -1) continue;
260
- ${v} key = part.slice(0, eq).trim();
261
- ${v} value = part.slice(eq + 1).trim();
262
- if (key) cookies[key] = value;
263
- }
264
- return cookies;
265
- }
266
-
267
- function __middlewareRequestContextFromRequest(request) {
268
- if (!request) return __emptyMiddlewareRequestContext;
269
- ${v} url = new URL(request.url);
270
- return {
271
- headers: request.headers,
272
- cookies: __parseMiddlewareCookies(request.headers.get("cookie")),
273
- query: url.searchParams,
274
- host: __normalizeMiddlewareHost(request.headers.get("host"), url.hostname),
275
- };
276
- }
277
-
278
- function __stripMiddlewareLocalePrefix(pathname, i18nConfig) {
279
- if (pathname === "/") return null;
280
- ${v} segments = pathname.split("/");
281
- ${v} firstSegment = segments[1];
282
- if (!firstSegment || !i18nConfig || !i18nConfig.locales.includes(firstSegment)) {
283
- return null;
284
- }
285
- ${v} stripped = "/" + segments.slice(2).join("/");
286
- return stripped === "/" ? "/" : stripped.replace(/\\/+$/, "") || "/";
287
- }
288
-
289
- function __matchMiddlewareMatcherPattern(pathname, pattern, i18nConfig) {
290
- if (!i18nConfig) return matchMiddlewarePattern(pathname, pattern);
291
- ${v} localeStrippedPathname = __stripMiddlewareLocalePrefix(pathname, i18nConfig);
292
- return matchMiddlewarePattern(localeStrippedPathname ?? pathname, pattern);
293
- }
294
-
295
- function __middlewareConditionRegex(value) {
296
- if (__middlewareConditionRegexCache.has(value)) {
297
- return __middlewareConditionRegexCache.get(value);
298
- }
299
- ${v} re = __safeRegExp(value);
300
- __middlewareConditionRegexCache.set(value, re);
301
- return re;
302
- }
303
-
304
- function __checkMiddlewareCondition(condition, ctx) {
305
- switch (condition.type) {
306
- case "header": {
307
- ${v} headerValue = ctx.headers.get(condition.key);
308
- if (headerValue === null) return false;
309
- if (condition.value !== undefined) {
310
- ${v} re = __middlewareConditionRegex(condition.value);
311
- if (re) return re.test(headerValue);
312
- return headerValue === condition.value;
313
- }
314
- return true;
315
- }
316
- case "cookie": {
317
- ${v} cookieValue = ctx.cookies[condition.key];
318
- if (cookieValue === undefined) return false;
319
- if (condition.value !== undefined) {
320
- ${v} re = __middlewareConditionRegex(condition.value);
321
- if (re) return re.test(cookieValue);
322
- return cookieValue === condition.value;
323
- }
324
- return true;
325
- }
326
- case "query": {
327
- ${v} queryValue = ctx.query.get(condition.key);
328
- if (queryValue === null) return false;
329
- if (condition.value !== undefined) {
330
- ${v} re = __middlewareConditionRegex(condition.value);
331
- if (re) return re.test(queryValue);
332
- return queryValue === condition.value;
333
- }
334
- return true;
335
- }
336
- case "host": {
337
- if (condition.value !== undefined) {
338
- ${v} re = __middlewareConditionRegex(condition.value);
339
- if (re) return re.test(ctx.host);
340
- return ctx.host === condition.value;
341
- }
342
- return ctx.host === condition.key;
343
- }
344
- default:
345
- return false;
346
- }
347
- }
348
-
349
- function __checkMiddlewareHasConditions(has, missing, ctx) {
350
- if (has) {
351
- for (${v} condition of has) {
352
- if (!__checkMiddlewareCondition(condition, ctx)) return false;
353
- }
354
- }
355
- if (missing) {
356
- for (${v} condition of missing) {
357
- if (__checkMiddlewareCondition(condition, ctx)) return false;
358
- }
359
- }
360
- return true;
361
- }
362
-
363
- // Keep this in sync with isValidMiddlewareMatcherObject in middleware.ts.
364
- function __isValidMiddlewareMatcherObject(matcher) {
365
- if (!matcher || typeof matcher !== "object" || Array.isArray(matcher)) return false;
366
- if (typeof matcher.source !== "string") return false;
367
- for (${v} key of Object.keys(matcher)) {
368
- if (key !== "source" && key !== "locale" && key !== "has" && key !== "missing") {
369
- return false;
370
- }
371
- }
372
- if ("locale" in matcher && matcher.locale !== undefined && matcher.locale !== false) return false;
373
- if ("has" in matcher && matcher.has !== undefined && !Array.isArray(matcher.has)) return false;
374
- if ("missing" in matcher && matcher.missing !== undefined && !Array.isArray(matcher.missing)) {
375
- return false;
376
- }
377
- return true;
378
- }
379
-
380
- function __matchMiddlewareObject(pathname, matcher, i18nConfig) {
381
- return matcher.locale === false
382
- ? matchMiddlewarePattern(pathname, matcher.source)
383
- : __matchMiddlewareMatcherPattern(pathname, matcher.source, i18nConfig);
384
- }
385
-
386
- function matchesMiddleware(pathname, matcher, request, i18nConfig) {
387
- if (!matcher) {
388
- return true;
389
- }
390
- if (typeof matcher === "string") {
391
- return __matchMiddlewareMatcherPattern(pathname, matcher, i18nConfig);
392
- }
393
- if (!Array.isArray(matcher)) {
394
- return false;
395
- }
396
- ${v} requestContext = __middlewareRequestContextFromRequest(request);
397
- for (${v} m of matcher) {
398
- if (typeof m === "string") {
399
- if (__matchMiddlewareMatcherPattern(pathname, m, i18nConfig)) return true;
400
- continue;
401
- }
402
- if (__isValidMiddlewareMatcherObject(m)) {
403
- if (!__matchMiddlewareObject(pathname, m, i18nConfig)) continue;
404
- if (!__checkMiddlewareHasConditions(m.has, m.missing, requestContext)) continue;
405
- return true;
406
- }
407
- }
408
- return false;
409
- }`;
410
- }
411
- //#endregion
412
- export { generateMiddlewareMatcherCode, generateNormalizePathCode, generateRouteMatchNormalizationCode, generateSafeRegExpCode };
413
-
414
- //# sourceMappingURL=middleware-codegen.js.map