@wular/pnext 0.1.5 → 0.1.7

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 (302) hide show
  1. package/bin/pnext +9 -2
  2. package/dist/server/_chunks/aliases-j47a10ce.js +44 -0
  3. package/dist/server/_chunks/analyze-arswqe6s.js +445 -0
  4. package/dist/server/_chunks/boot-af0mv3dy.js +36 -0
  5. package/dist/server/_chunks/build-spy3dxp4.js +84 -0
  6. package/dist/server/_chunks/build-t9h0hec3.js +3550 -0
  7. package/dist/server/_chunks/build-tier-m7yvqz61.js +2472 -0
  8. package/dist/server/_chunks/compile-53j02j27.js +22 -0
  9. package/dist/server/_chunks/config-1yzwexq6.js +27 -0
  10. package/dist/server/_chunks/config-n2z7yxps.js +22 -0
  11. package/dist/server/_chunks/create-meec9hs6.js +134 -0
  12. package/dist/server/_chunks/dev-fjmqg6en.js +220 -0
  13. package/dist/server/_chunks/esbuild-yyktfrtt.js +15 -0
  14. package/dist/server/_chunks/generate-n9sh6hzt.js +21 -0
  15. package/dist/server/_chunks/index-0374j2b9.js +66 -0
  16. package/dist/server/_chunks/index-06nyqntx.js +213 -0
  17. package/dist/server/_chunks/index-1011cscr.js +5263 -0
  18. package/dist/server/_chunks/index-11sfk4hb.js +170 -0
  19. package/dist/server/_chunks/index-20ppawv7.js +297 -0
  20. package/dist/server/_chunks/index-2dv4y4wd.js +1065 -0
  21. package/dist/server/_chunks/index-2vz0wzdn.js +59 -0
  22. package/dist/server/_chunks/index-2wfv4kvx.js +182 -0
  23. package/dist/server/_chunks/index-357na4a8.js +109 -0
  24. package/dist/server/_chunks/index-3b3at80h.js +109 -0
  25. package/dist/server/_chunks/index-3tf1xjsp.js +6166 -0
  26. package/dist/server/_chunks/index-3xbr4eyv.js +105 -0
  27. package/dist/server/_chunks/index-4399bvd2.js +18 -0
  28. package/dist/server/_chunks/index-4hgjrqh7.js +851 -0
  29. package/dist/server/_chunks/index-4q2gbfwk.js +2530 -0
  30. package/dist/server/_chunks/index-4t92hdxd.js +172 -0
  31. package/dist/server/_chunks/index-4zzebszd.js +10 -0
  32. package/dist/server/_chunks/index-5gyr4emz.js +107 -0
  33. package/dist/server/_chunks/index-5hr4062s.js +70 -0
  34. package/dist/server/_chunks/index-68m3mwbd.js +84 -0
  35. package/dist/server/_chunks/index-6b009mt0.js +56 -0
  36. package/dist/server/_chunks/index-6e4fqv30.js +588 -0
  37. package/dist/server/_chunks/index-6gex3pfa.js +15 -0
  38. package/dist/server/_chunks/index-6kp9r0d9.js +11 -0
  39. package/dist/server/_chunks/index-6q7zvrap.js +134 -0
  40. package/dist/server/_chunks/index-73z4esab.js +38 -0
  41. package/dist/server/_chunks/index-79ngvam8.js +60 -0
  42. package/dist/server/_chunks/index-7wc9n8be.js +25 -0
  43. package/dist/server/_chunks/index-8k7pfejn.js +1599 -0
  44. package/dist/server/_chunks/index-8kcxdfya.js +206 -0
  45. package/dist/server/_chunks/index-91x12ykq.js +274 -0
  46. package/dist/server/_chunks/index-9ch50vtq.js +18 -0
  47. package/dist/server/_chunks/index-9hx2641q.js +28 -0
  48. package/dist/server/_chunks/index-9n2914ww.js +535 -0
  49. package/dist/server/_chunks/index-9ych9ma8.js +207 -0
  50. package/dist/server/_chunks/index-b6wtkdp4.js +24 -0
  51. package/dist/server/_chunks/index-bcws5eh2.js +35 -0
  52. package/dist/server/_chunks/index-c0g2wf3z.js +92 -0
  53. package/dist/server/_chunks/index-cf4rvxv6.js +95 -0
  54. package/dist/server/_chunks/index-cjgqs13g.js +65 -0
  55. package/dist/server/_chunks/index-ckkdpht5.js +41 -0
  56. package/dist/server/_chunks/index-cyfednwb.js +87 -0
  57. package/dist/server/_chunks/index-danncfhy.js +311 -0
  58. package/dist/server/_chunks/index-dg0f05zs.js +199 -0
  59. package/dist/server/_chunks/index-e3a6yx84.js +18 -0
  60. package/dist/server/_chunks/index-e88tyv35.js +45 -0
  61. package/dist/server/_chunks/index-eajaspjk.js +1253 -0
  62. package/dist/server/_chunks/index-eeaanp2e.js +483 -0
  63. package/dist/server/_chunks/index-egykcqg3.js +101 -0
  64. package/dist/server/_chunks/index-en7n9f7m.js +22 -0
  65. package/dist/server/_chunks/index-ezgj0tr1.js +88 -0
  66. package/dist/server/_chunks/index-fkp000p1.js +590 -0
  67. package/dist/server/_chunks/index-fn1chkkd.js +214 -0
  68. package/dist/server/_chunks/index-fp8r0sqs.js +64 -0
  69. package/dist/server/_chunks/index-ggk2j965.js +9432 -0
  70. package/dist/server/_chunks/index-grta8ap3.js +238 -0
  71. package/dist/server/_chunks/index-h2a70tg4.js +7 -0
  72. package/dist/server/_chunks/index-h4xy648y.js +51 -0
  73. package/dist/server/_chunks/index-hkdfj58q.js +92 -0
  74. package/dist/server/_chunks/index-j2zrcp1k.js +66 -0
  75. package/dist/server/_chunks/index-jcsjq3d1.js +20 -0
  76. package/dist/server/_chunks/index-jepjvcrf.js +198 -0
  77. package/dist/server/_chunks/index-jks0x0a1.js +14 -0
  78. package/dist/server/_chunks/index-jx7bqvw1.js +57 -0
  79. package/dist/server/_chunks/index-k1g3epw0.js +1299 -0
  80. package/dist/server/_chunks/index-knp0s912.js +7 -0
  81. package/dist/server/_chunks/index-kq8kpzye.js +472 -0
  82. package/dist/server/_chunks/index-kqyy1d4f.js +50 -0
  83. package/dist/server/_chunks/index-kresp2n8.js +445 -0
  84. package/dist/server/_chunks/index-ms9v9tnx.js +31 -0
  85. package/dist/server/_chunks/index-n4hxpng2.js +11 -0
  86. package/dist/server/_chunks/index-ncnes8c6.js +17 -0
  87. package/dist/server/_chunks/index-nqh3xhdc.js +57 -0
  88. package/dist/server/_chunks/index-nyrba2kr.js +4130 -0
  89. package/dist/server/_chunks/index-p77b4kcx.js +296 -0
  90. package/dist/server/_chunks/index-pym1cezq.js +39 -0
  91. package/dist/server/_chunks/index-q738kkhj.js +100 -0
  92. package/dist/server/_chunks/index-qjj6gddn.js +54 -0
  93. package/dist/server/_chunks/index-qm6kmhqs.js +110 -0
  94. package/dist/server/_chunks/index-qn4z5s3c.js +819 -0
  95. package/dist/server/_chunks/index-qpwsgt3a.js +158 -0
  96. package/dist/server/_chunks/index-r97ptz1q.js +97 -0
  97. package/dist/server/_chunks/index-ras0sdab.js +26 -0
  98. package/dist/server/_chunks/index-rcs322t1.js +19 -0
  99. package/dist/server/_chunks/index-rn8dyr1f.js +126 -0
  100. package/dist/server/_chunks/index-rt9qq1va.js +4 -0
  101. package/dist/server/_chunks/index-rthrsed5.js +356 -0
  102. package/dist/server/_chunks/index-sctcgyvv.js +185 -0
  103. package/dist/server/_chunks/index-sjpckxqn.js +213 -0
  104. package/dist/server/_chunks/index-sq3kvz3g.js +200 -0
  105. package/dist/server/_chunks/index-stbk3jhn.js +31 -0
  106. package/dist/server/_chunks/index-sv8m6789.js +266 -0
  107. package/dist/server/_chunks/index-tgcakdxc.js +125 -0
  108. package/dist/server/_chunks/index-tgsfjmep.js +74 -0
  109. package/dist/server/_chunks/index-tq0pc7eg.js +154 -0
  110. package/dist/server/_chunks/index-tq1f96v7.js +51 -0
  111. package/dist/server/_chunks/index-tqn2qnnn.js +241 -0
  112. package/dist/server/_chunks/index-tvqkq6e6.js +128 -0
  113. package/dist/server/_chunks/index-v1ags1na.js +132 -0
  114. package/dist/server/_chunks/index-vvmmknm1.js +1431 -0
  115. package/dist/server/_chunks/index-vvq7rqtn.js +329 -0
  116. package/dist/server/_chunks/index-vz0km5qk.js +33 -0
  117. package/dist/server/_chunks/index-w6h8m6vp.js +138 -0
  118. package/dist/server/_chunks/index-web361b8.js +138 -0
  119. package/dist/server/_chunks/index-wpfhfbs4.js +194 -0
  120. package/dist/server/_chunks/index-x0y005nh.js +283 -0
  121. package/dist/server/_chunks/index-x3yn4ywm.js +22 -0
  122. package/dist/server/_chunks/index-x93hv0sc.js +271 -0
  123. package/dist/server/_chunks/index-xvj80c3a.js +30 -0
  124. package/dist/server/_chunks/index-xywjg2vc.js +100 -0
  125. package/dist/server/_chunks/index-y2jr2n72.js +152 -0
  126. package/dist/server/_chunks/index-y36a0ybw.js +57 -0
  127. package/dist/server/_chunks/index-ye9hmsvf.js +47 -0
  128. package/dist/server/_chunks/index-yhxkxghe.js +56 -0
  129. package/dist/server/_chunks/index-ym67zqxp.js +130 -0
  130. package/dist/server/_chunks/index-ytjvpbm2.js +736 -0
  131. package/dist/server/_chunks/index-yz54pxrh.js +960 -0
  132. package/dist/server/_chunks/index-z4z9zv3b.js +733 -0
  133. package/dist/server/_chunks/index-z84ab1w0.js +1270 -0
  134. package/dist/server/_chunks/index-z88qv16t.js +11 -0
  135. package/dist/server/_chunks/index-zqpqyg8p.js +666 -0
  136. package/dist/server/_chunks/loader-7yw0j98z.js +78 -0
  137. package/dist/server/_chunks/modules-jn8bmbn8.js +74 -0
  138. package/dist/server/_chunks/pipeline-yy9jhydf.js +832 -0
  139. package/dist/server/_chunks/production-jar9ztm3.js +44 -0
  140. package/dist/server/_chunks/proxy-config-j84dgksn.js +21 -0
  141. package/dist/server/_chunks/proxy-w1d0wmsn.js +33 -0
  142. package/dist/server/_chunks/router-k1reahfn.js +498 -0
  143. package/dist/server/_chunks/routes-2s277fc6.js +64 -0
  144. package/dist/server/_chunks/run-pvd8bs1t.js +696 -0
  145. package/dist/server/_chunks/server-mt4a994c.js +1835 -0
  146. package/dist/server/_chunks/tsconfig-defaults-1nb3308g.js +20 -0
  147. package/dist/server/_chunks/typegen-0qr0459b.js +35 -0
  148. package/dist/server/api/client-cache.js +14 -0
  149. package/dist/server/cli/index.js +378 -0
  150. package/dist/server/cli/start.js +137 -0
  151. package/dist/server/client/reference.js +16 -0
  152. package/dist/server/compat/next/cache.js +56 -0
  153. package/dist/server/compat/next/canonical-url.js +13 -0
  154. package/dist/server/compat/next/client-cache.js +57 -0
  155. package/dist/server/compat/next/client-navigation.js +232 -0
  156. package/dist/server/compat/next/client-only.js +1 -0
  157. package/dist/server/compat/next/client-script.js +178 -0
  158. package/dist/server/compat/next/client-server.js +34 -0
  159. package/dist/server/compat/next/config-headers.js +32 -0
  160. package/dist/server/compat/next/config-loader.js +25 -0
  161. package/dist/server/compat/next/config.js +10 -0
  162. package/dist/server/compat/next/constants.js +18 -0
  163. package/dist/server/compat/next/custom-server.js +10 -0
  164. package/dist/server/compat/next/dist/client/components/app-router-headers.js +48 -0
  165. package/dist/server/compat/next/dist/server/web/spec-extension/revalidate.js +27 -0
  166. package/dist/server/compat/next/dist/server/web/spec-extension/unstable-cache.js +25 -0
  167. package/dist/server/compat/next/dist/server/web/spec-extension/unstable-no-store.js +25 -0
  168. package/dist/server/compat/next/dynamic.js +32 -0
  169. package/dist/server/compat/next/error.js +112 -0
  170. package/dist/server/compat/next/font/cache.js +14 -0
  171. package/dist/server/compat/next/font/google.js +3 -0
  172. package/dist/server/compat/next/font/index.js +1 -0
  173. package/dist/server/compat/next/font/local.js +22 -0
  174. package/dist/server/compat/next/font/runtime-client.js +33 -0
  175. package/dist/server/compat/next/font/runtime.js +41 -0
  176. package/dist/server/compat/next/font/shared.js +22 -0
  177. package/dist/server/compat/next/form.js +129 -0
  178. package/dist/server/compat/next/head.js +10 -0
  179. package/dist/server/compat/next/headers.js +30 -0
  180. package/dist/server/compat/next/image/client.js +11 -0
  181. package/dist/server/compat/next/image/config.js +18 -0
  182. package/dist/server/compat/next/image/optimizer.js +25 -0
  183. package/dist/server/compat/next/image/patterns.js +12 -0
  184. package/dist/server/compat/next/image/props.js +16 -0
  185. package/dist/server/compat/next/image/shared.js +86 -0
  186. package/dist/server/compat/next/image/static-metadata.js +32 -0
  187. package/dist/server/compat/next/image/validate.js +8 -0
  188. package/dist/server/compat/next/image.js +59 -0
  189. package/dist/server/compat/next/index.js +1 -0
  190. package/dist/server/compat/next/legacy-image.js +78 -0
  191. package/dist/server/compat/next/legacy-request-apis.js +24 -0
  192. package/dist/server/compat/next/link-transform.js +14 -0
  193. package/dist/server/compat/next/link.js +14 -0
  194. package/dist/server/compat/next/navigation.js +190 -0
  195. package/dist/server/compat/next/offline.js +45 -0
  196. package/dist/server/compat/next/og.js +8 -0
  197. package/dist/server/compat/next/preferred-region.js +8 -0
  198. package/dist/server/compat/next/redirects.js +30 -0
  199. package/dist/server/compat/next/resource-hints.js +30 -0
  200. package/dist/server/compat/next/rewrites.js +41 -0
  201. package/dist/server/compat/next/root-params.js +121 -0
  202. package/dist/server/compat/next/route-state.js +23 -0
  203. package/dist/server/compat/next/router.js +103 -0
  204. package/dist/server/compat/next/script.js +37 -0
  205. package/dist/server/compat/next/server-only.js +1 -0
  206. package/dist/server/compat/next/server.js +131 -0
  207. package/dist/server/compat/next/svgr.js +14 -0
  208. package/dist/server/compat/next/telemetry.js +10 -0
  209. package/dist/server/compat/next/usage.js +13 -0
  210. package/dist/server/compat/next/user-agent.js +12 -0
  211. package/dist/server/compat/next/web-vitals.js +35 -0
  212. package/dist/server/compat/react/action-state.js +11 -0
  213. package/dist/server/compat/react/client-lite.js +83 -0
  214. package/dist/server/compat/react/client.js +131 -0
  215. package/dist/server/compat/react/compiler-runtime.js +42 -0
  216. package/dist/server/compat/react/dom-client.js +106 -0
  217. package/dist/server/compat/react/dom-react-server.js +37 -0
  218. package/dist/server/compat/react/dom-server.js +40 -0
  219. package/dist/server/compat/react/dom.js +52 -0
  220. package/dist/server/compat/react/hooks-extra.js +12 -0
  221. package/dist/server/compat/react/internals.js +14 -0
  222. package/dist/server/compat/react/parity.js +11 -0
  223. package/dist/server/compat/react/preact.js +113 -0
  224. package/dist/server/compat/react/react-server.js +133 -0
  225. package/dist/server/compat/react/router-shim.js +8 -0
  226. package/dist/server/compat/react/server-component-use.js +14 -0
  227. package/dist/server/compat/react/server-inserted-html.js +14 -0
  228. package/dist/server/compat/react/server.js +194 -0
  229. package/dist/server/compat/react/style-values.js +10 -0
  230. package/dist/server/compat/react/use.js +10 -0
  231. package/dist/server/compat/react/view-transition.js +12 -0
  232. package/dist/server/generation.json +1 -0
  233. package/package.json +4 -1
  234. package/src/api/dynamic.tsx +2 -0
  235. package/src/api/server.ts +24 -6
  236. package/src/cli/adapters/vercel-warm.ts +315 -61
  237. package/src/cli/adapters/vercel.ts +348 -71
  238. package/src/cli/build.ts +58 -33
  239. package/src/cli/index.ts +23 -10
  240. package/src/cli/serve/entry.ts +21 -159
  241. package/src/cli/serve/immutable.ts +31 -0
  242. package/src/cli/serve/pipeline.ts +82 -84
  243. package/src/cli/start.ts +3 -1
  244. package/src/client/chunk-fold.ts +19 -6
  245. package/src/client/react-tier.ts +3 -2
  246. package/src/client/reference-stub.ts +21 -2
  247. package/src/compat/actions/client-plugin.ts +4 -2
  248. package/src/compat/actions/config.ts +6 -5
  249. package/src/compat/actions/extensions.ts +2 -3
  250. package/src/compat/aliases.ts +8 -1
  251. package/src/compat/bundler/config.ts +88 -0
  252. package/src/compat/bundler/optimize-package-imports.ts +86 -26
  253. package/src/compat/bundler/relay-transform.ts +15 -3
  254. package/src/compat/cache-control.ts +16 -8
  255. package/src/compat/css/modules.ts +18 -5
  256. package/src/compat/lifecycle/error-funnel.ts +1 -1
  257. package/src/compat/lifecycle/instrumentation.ts +117 -24
  258. package/src/compat/lifecycle/testmode.ts +3 -2
  259. package/src/compat/next/config-loader.ts +137 -13
  260. package/src/compat/next/font/runtime.ts +22 -2
  261. package/src/compat/next/og.ts +3 -3
  262. package/src/compat/next/usage.ts +3 -2
  263. package/src/compat/pages/api.ts +83 -14
  264. package/src/compat/pages/router.ts +30 -14
  265. package/src/compat/register/bundler.ts +3 -1
  266. package/src/compat/register/middleware.ts +1 -1
  267. package/src/compat/register/otel.ts +5 -9
  268. package/src/compat/register/render.ts +3 -1
  269. package/src/compat/register/use-cache.ts +3 -1
  270. package/src/compat/release.ts +46 -0
  271. package/src/compat/segment/serve.ts +1 -1
  272. package/src/compat/validation/validate.ts +10 -7
  273. package/src/config.ts +51 -7
  274. package/src/css/assets.ts +213 -0
  275. package/src/css/build.ts +174 -238
  276. package/src/dev/server.ts +27 -8
  277. package/src/extensions.ts +4 -0
  278. package/src/render/hooks.ts +13 -0
  279. package/src/render/renderer.ts +52 -32
  280. package/src/request/context.ts +9 -0
  281. package/src/resolve/dynamic.ts +3 -1
  282. package/src/resolve/imports.ts +12 -52
  283. package/src/resolve/package-json.ts +56 -0
  284. package/src/resolve/scan-facts.ts +65 -0
  285. package/src/routing/href.ts +10 -3
  286. package/src/routing/match.ts +287 -0
  287. package/src/routing/metadata-files.ts +19 -5
  288. package/src/routing/proxy-config.ts +137 -0
  289. package/src/routing/proxy.ts +35 -134
  290. package/src/routing/routes.ts +22 -281
  291. package/src/runtime/fingerprint.ts +23 -8
  292. package/src/runtime/load.ts +170 -0
  293. package/src/runtime/loader.ts +215 -43
  294. package/src/runtime/module-cache.ts +13 -0
  295. package/src/runtime/modules.ts +370 -81
  296. package/src/runtime/prebundle.ts +81 -0
  297. package/src/runtime/production.ts +391 -0
  298. package/src/runtime/release-graph.ts +334 -0
  299. package/src/runtime/vendor-build.ts +724 -13
  300. package/src/runtime/vendor.ts +16 -3
  301. package/src/types.ts +2 -0
  302. package/src/utils/fs.ts +89 -3
@@ -0,0 +1,3550 @@
1
+ // @bun
2
+ import { join as __pnextJoin } from "node:path";
3
+ const __PNEXT_PACKAGE_ROOT__ = __pnextJoin(import.meta.dirname, "../../..");
4
+ import {
5
+ immutableAssetPath,
6
+ immutableAssetPrefixes,
7
+ immutableCacheControl
8
+ } from "./index-rcs322t1.js";
9
+ import {
10
+ buildClientEntries,
11
+ emitStaticClientChunks,
12
+ startClientSources
13
+ } from "./index-nyrba2kr.js";
14
+ import {
15
+ writeTypegen
16
+ } from "./index-wpfhfbs4.js";
17
+ import {
18
+ handleRouteModule,
19
+ staticRouteParams
20
+ } from "./index-qpwsgt3a.js";
21
+ import {
22
+ addClientEntryReason,
23
+ assertNoServerActionsWithoutCompat,
24
+ materializeRouteFacts,
25
+ scanRoutes
26
+ } from "./index-8k7pfejn.js";
27
+ import {
28
+ compiledSpecifiersManifestSuffix,
29
+ devServerModuleHref,
30
+ resetModuleGraphFailure,
31
+ setEmitCompiledSpecifiersManifest,
32
+ setReleaseCompile
33
+ } from "./index-1011cscr.js";
34
+ import"./index-n4hxpng2.js";
35
+ import"./index-x3yn4ywm.js";
36
+ import {
37
+ compiledSourceGraph,
38
+ flushDevModuleCaches,
39
+ registerServerRuntime
40
+ } from "./index-vvmmknm1.js";
41
+ import"./index-91x12ykq.js";
42
+ import"./index-tvqkq6e6.js";
43
+ import {
44
+ clientEntryName,
45
+ defaultNotFoundDocument,
46
+ discoverStaticMetadataFiles,
47
+ metadataRouteHandlerModule,
48
+ pprShellPath,
49
+ pprSubShellPath,
50
+ readModuleMetadata,
51
+ readModuleViewport,
52
+ renderFallbackShell,
53
+ renderGlobalNotFoundResponse,
54
+ renderPageWithStatus,
55
+ renderPartialShell,
56
+ renderSubShell,
57
+ staticMetadataCacheControl,
58
+ staticMetadataForPathFromFiles,
59
+ staticMetadataForRouteFromFiles,
60
+ staticMetadataOutputFile,
61
+ staticParamsFor,
62
+ staticRouteMetadataKey,
63
+ withDynamicMetadataRoutes
64
+ } from "./index-3tf1xjsp.js";
65
+ import {
66
+ findLayouts
67
+ } from "./index-jepjvcrf.js";
68
+ import {
69
+ findProxyFile,
70
+ proxyExternalLoadTarget,
71
+ proxyRoutePatterns,
72
+ validateProxyFiles
73
+ } from "./index-kq8kpzye.js";
74
+ import {
75
+ serverBundleTargetForRuntime,
76
+ throwIfModuleGraphFailed
77
+ } from "./index-3xbr4eyv.js";
78
+ import"./index-rn8dyr1f.js";
79
+ import {
80
+ buildGlobalCss,
81
+ buildNotFoundCss,
82
+ buildRouteStylesheets,
83
+ globalCssSources,
84
+ prepareRouteCssChunks,
85
+ warmCssPipeline
86
+ } from "./index-2dv4y4wd.js";
87
+ import {
88
+ createVerboseLogger
89
+ } from "./index-73z4esab.js";
90
+ import {
91
+ emittedAssetNames,
92
+ registerCssRuntime
93
+ } from "./index-y2jr2n72.js";
94
+ import {
95
+ nextCompatEnabled
96
+ } from "./index-web361b8.js";
97
+ import"./index-knp0s912.js";
98
+ import {
99
+ frameworkFingerprint
100
+ } from "./index-c0g2wf3z.js";
101
+ import"./index-ye9hmsvf.js";
102
+ import {
103
+ setRequestRuntime
104
+ } from "./index-z88qv16t.js";
105
+ import {
106
+ beginSourceScope,
107
+ endSourceScope,
108
+ sourceCacheStats
109
+ } from "./index-fp8r0sqs.js";
110
+ import"./index-cjgqs13g.js";
111
+ import"./index-yhxkxghe.js";
112
+ import"./index-fkp000p1.js";
113
+ import {
114
+ interceptionMarkerLevels
115
+ } from "./index-p77b4kcx.js";
116
+ import {
117
+ ensureEmptyDir,
118
+ listFiles,
119
+ readText,
120
+ resolveManifest,
121
+ serializeBuildManifest,
122
+ toPosixPath,
123
+ writeFileAtomic,
124
+ writeText
125
+ } from "./index-20ppawv7.js";
126
+ import {
127
+ cacheRoot,
128
+ namedBunBinary
129
+ } from "./index-cyfednwb.js";
130
+ import"./index-vz0km5qk.js";
131
+ import {
132
+ bootstrapCompat
133
+ } from "./index-5gyr4emz.js";
134
+ import {
135
+ readPrebundleStamp,
136
+ runtimeEntryDirs,
137
+ runtimeEntryFiles
138
+ } from "./index-y36a0ybw.js";
139
+ import {
140
+ DEFAULT_OUT_DIR,
141
+ devOutSegment,
142
+ loadConfig,
143
+ pathToFileHref
144
+ } from "./index-x93hv0sc.js";
145
+ import"./index-jcsjq3d1.js";
146
+ import {
147
+ buildIndexFile,
148
+ readBuildIndex,
149
+ releaseSourceFile
150
+ } from "./index-tqn2qnnn.js";
151
+ import {
152
+ bold,
153
+ cyan,
154
+ dim,
155
+ green
156
+ } from "./index-6kp9r0d9.js";
157
+ import {
158
+ compiledClientReferenceFiles
159
+ } from "./index-ras0sdab.js";
160
+ import {
161
+ beginDynamicBailoutProbe,
162
+ endDynamicBailoutProbe,
163
+ runWithWorkUnit
164
+ } from "./index-grta8ap3.js";
165
+ import {
166
+ abortActivePrerenderScopes,
167
+ beginShellSourceTracking,
168
+ cacheComponents,
169
+ endShellSourceTracking
170
+ } from "./index-kresp2n8.js";
171
+ import"./index-e3a6yx84.js";
172
+ import {
173
+ importSpecifiers,
174
+ scanFactsStats
175
+ } from "./index-z4z9zv3b.js";
176
+ import {
177
+ resolveImport,
178
+ workspacePackageRoots
179
+ } from "./index-yz54pxrh.js";
180
+ import"./index-7wc9n8be.js";
181
+ import"./index-pym1cezq.js";
182
+ import {
183
+ buildParallelPhaseError,
184
+ clearBuildParallelPhases,
185
+ getBuildExtensions,
186
+ getCompatModeExtensions,
187
+ getImportAliasExtensions,
188
+ getRenderExtensions,
189
+ runInitHooks,
190
+ withRouteRuntime
191
+ } from "./index-zqpqyg8p.js";
192
+ import {
193
+ escapeRegex
194
+ } from "./index-qjj6gddn.js";
195
+ import"./index-4399bvd2.js";
196
+ import {
197
+ __require
198
+ } from "./index-rt9qq1va.js";
199
+
200
+ // src/cli/build.ts
201
+ import { copyFile as copyFile2, mkdir as mkdir4, rename as rename2, writeFile as writeFile3 } from "fs/promises";
202
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2, realpathSync as realpathSync3, statSync as statSync2 } from "fs";
203
+ import { createRequire } from "module";
204
+ import path5 from "path";
205
+ import { fileURLToPath as fileURLToPath3 } from "url";
206
+
207
+ // src/cli/adapters/vercel.ts
208
+ import { copyFile, link, mkdir, readFile, rename, rm, symlink, writeFile } from "fs/promises";
209
+ import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync2, rmSync, statSync } from "fs";
210
+ import { builtinModules } from "module";
211
+ import path2 from "path";
212
+ import { fileURLToPath as fileURLToPath2 } from "url";
213
+
214
+ // src/cli/adapters/vercel-warm.ts
215
+ import { fileURLToPath } from "url";
216
+
217
+ // src/runtime/release-graph.ts
218
+ import { existsSync, readFileSync, realpathSync } from "fs";
219
+ import path from "path";
220
+ var layerDirs = {
221
+ "server:server": "rsc",
222
+ "client:client": "ssr"
223
+ };
224
+ var layers = Object.keys(layerDirs);
225
+ var frameworkRoot = realpathSync(path.resolve(__PNEXT_PACKAGE_ROOT__ + "/src/runtime", "..", ".."));
226
+
227
+ // src/cli/adapters/vercel-warm.ts
228
+ var DONE_MARKER = "pnext-warm-done:";
229
+ var COMPILED_MARKER = "pnext-warm-compiled";
230
+ var ATTEMPT_TIMEOUT_MS = 10 * 60000;
231
+ var MAX_ATTEMPTS = 3;
232
+ var FULL_MODE_FLAG = "--full";
233
+ function startWarmChild(config, mode = "full") {
234
+ const children = new Set;
235
+ let disposed = false;
236
+ const spawn = () => {
237
+ if (disposed)
238
+ return;
239
+ const child = spawnWarmProcess(config, mode);
240
+ if (!child)
241
+ return;
242
+ children.add(child);
243
+ child.exited.finally(() => children.delete(child));
244
+ forwardWarmStderr(child);
245
+ return child;
246
+ };
247
+ const killOnExit = () => kill();
248
+ const kill = () => {
249
+ if (disposed)
250
+ return;
251
+ disposed = true;
252
+ process.off("exit", killOnExit);
253
+ for (const child of children)
254
+ child.kill();
255
+ children.clear();
256
+ };
257
+ process.once("exit", killOnExit);
258
+ const first = spawn();
259
+ return {
260
+ prewarm(files) {
261
+ if (!first || files.length === 0)
262
+ return;
263
+ try {
264
+ first.stdin.write(`${JSON.stringify({ prewarm: files })}
265
+ `);
266
+ first.stdin.flush();
267
+ } catch {}
268
+ },
269
+ finish: (log, onCompiled, facts = { clientReferences: [] }) => warmWithRestarts(first, spawn, mode, log, facts, onCompiled).finally(kill),
270
+ kill
271
+ };
272
+ }
273
+ async function forwardWarmStderr(child) {
274
+ try {
275
+ const reader = child.stderr.getReader();
276
+ for (;; ) {
277
+ const { done, value } = await reader.read();
278
+ if (done)
279
+ return;
280
+ process.stderr.write(value);
281
+ }
282
+ } catch {}
283
+ }
284
+ function spawnWarmProcess(config, mode) {
285
+ const entry = fileURLToPath(new URL(Bun.pathToFileURL(__PNEXT_PACKAGE_ROOT__ + "/src/cli/adapters/vercel-warm.ts").href));
286
+ const argv = mode === "full" ? [config.root, FULL_MODE_FLAG] : [config.root];
287
+ try {
288
+ return Bun.spawn([namedBunBinary("pnext-warm"), "--conditions=react-server", entry, ...argv], {
289
+ cwd: config.root,
290
+ stdin: "pipe",
291
+ stdout: "pipe",
292
+ stderr: "pipe",
293
+ env: process.env
294
+ });
295
+ } catch {
296
+ return;
297
+ }
298
+ }
299
+ async function warmWithRestarts(first, spawn, mode, log, facts, onCompiled) {
300
+ const finished = new Map;
301
+ const compiled = () => [...finished.values()].filter((file) => Boolean(file));
302
+ let fired = false;
303
+ const fireOnCompiled = onCompiled ? () => {
304
+ if (fired)
305
+ return;
306
+ fired = true;
307
+ onCompiled(compiled());
308
+ } : undefined;
309
+ let child = first;
310
+ for (let attempt = 1;attempt <= MAX_ATTEMPTS && child; attempt++) {
311
+ const before = finished.size;
312
+ const failure = await runAttempt(child, {
313
+ skip: [...finished.keys()],
314
+ compiled: Object.fromEntries([...finished].filter((entry) => Boolean(entry[1]))),
315
+ ...facts
316
+ }, finished, fireOnCompiled);
317
+ if (!failure) {
318
+ log.log(`warmed ${compiled().length} modules`);
319
+ return compiled();
320
+ }
321
+ child = finished.size > before && attempt < MAX_ATTEMPTS ? spawn() : undefined;
322
+ if (child)
323
+ log.log(`warm-up ${failure} after ${finished.size} files; restarting past them`);
324
+ else
325
+ warmIncomplete(failure, finished.size, mode);
326
+ }
327
+ fireOnCompiled?.();
328
+ return compiled();
329
+ }
330
+ async function runAttempt(child, request, finished, onCompiled) {
331
+ try {
332
+ child.stdin.write(`${JSON.stringify(request)}
333
+ `);
334
+ child.stdin.end();
335
+ } catch {}
336
+ const timeout = setTimeout(() => child.kill("SIGKILL"), ATTEMPT_TIMEOUT_MS);
337
+ timeout.unref?.();
338
+ const processLine = (line) => {
339
+ if (!line)
340
+ return;
341
+ if (line === COMPILED_MARKER) {
342
+ onCompiled?.();
343
+ return;
344
+ }
345
+ if (!line.startsWith(DONE_MARKER)) {
346
+ console.log(line);
347
+ return;
348
+ }
349
+ const [source, artifact] = line.slice(DONE_MARKER.length).split("\t");
350
+ if (source)
351
+ finished.set(source, artifact || undefined);
352
+ };
353
+ const reader = child.stdout.getReader();
354
+ const decoder = new TextDecoder;
355
+ let buffer = "";
356
+ for (;; ) {
357
+ const { done, value } = await reader.read();
358
+ if (done)
359
+ break;
360
+ buffer += decoder.decode(value, { stream: true });
361
+ let newline;
362
+ while ((newline = buffer.indexOf(`
363
+ `)) >= 0) {
364
+ processLine(buffer.slice(0, newline));
365
+ buffer = buffer.slice(newline + 1);
366
+ }
367
+ }
368
+ if (buffer)
369
+ processLine(buffer);
370
+ const code = await child.exited.finally(() => clearTimeout(timeout));
371
+ if (code === 0)
372
+ return;
373
+ return child.signalCode ? `was killed by ${child.signalCode}` : `exited with code ${code}`;
374
+ }
375
+ function warmIncomplete(failure, done, mode) {
376
+ console.warn(`pnext build: module warm-up ${failure} after warming ${done} file(s). ` + (mode === "full" ? "The function ships without the rest of its module cache and may fail to render those " + "routes at request time, where Vercel's filesystem is read-only." : "The production server compiles the rest on the first request that needs them."));
377
+ }
378
+ if (false) {}
379
+
380
+ // src/cli/adapters/vercel.ts
381
+ var RUNTIME_ROOT = "/var/task";
382
+ var SERVER_FUNCTION = "_pnext";
383
+ var FUNCTION_PLATFORM = {
384
+ architecture: "x86_64",
385
+ os: "linux",
386
+ cpu: "x64",
387
+ libc: "glibc"
388
+ };
389
+ var prunedDirNames = [
390
+ "node_modules",
391
+ ".git",
392
+ ".next",
393
+ ".pnext",
394
+ ".turbo",
395
+ ".cache",
396
+ ".vercel",
397
+ ".tmp"
398
+ ];
399
+ var droppedFileSuffixes = [
400
+ ".map",
401
+ ".d.ts",
402
+ ".d.mts",
403
+ ".d.cts",
404
+ ".DS_Store",
405
+ compiledSpecifiersManifestSuffix
406
+ ];
407
+ var packPruningEnabled = true;
408
+ function packRules(config) {
409
+ const devPaths = new Set([config.outRootPath, path2.resolve(config.root, DEFAULT_OUT_DIR)].map((root) => path2.resolve(root, devOutSegment)).filter((dev) => !isInsideDir(dev, config.outPath)));
410
+ devPaths.add(path2.join(config.outRootPath, "pnext-pages-compat"));
411
+ if (!packPruningEnabled) {
412
+ return {
413
+ prunedDirs: new Set(["node_modules", ".git"]),
414
+ droppedSuffixes: [],
415
+ compiled: new Set,
416
+ keep: new Set,
417
+ keepPaths: new Set([path2.resolve(config.outPath)]),
418
+ devPaths
419
+ };
420
+ }
421
+ const keep = new Set(config.adapter?.keep ?? []);
422
+ const extra = config.adapter?.exclude ?? [];
423
+ const isSuffix = (entry) => entry.startsWith(".") && !prunedDirNames.includes(entry);
424
+ return {
425
+ prunedDirs: new Set([...prunedDirNames, ...extra.filter((entry) => !isSuffix(entry))].filter((name) => !keep.has(name))),
426
+ droppedSuffixes: [...droppedFileSuffixes, ...extra.filter(isSuffix)].filter((suffix) => !keep.has(suffix)),
427
+ compiled: new Set,
428
+ keep,
429
+ keepPaths: new Set([path2.resolve(config.outPath), path2.resolve(config.root, DEFAULT_OUT_DIR)]),
430
+ devPaths
431
+ };
432
+ }
433
+ function withinKeepPath(pack, source) {
434
+ const resolved = path2.resolve(source);
435
+ for (const keep of pack.keepPaths) {
436
+ if (resolved === keep || resolved.startsWith(`${keep}${path2.sep}`))
437
+ return true;
438
+ }
439
+ return false;
440
+ }
441
+ function shipsDir(pack, name, source, isLink = false) {
442
+ if (pack.devPaths.has(path2.resolve(source)))
443
+ return false;
444
+ if (!pack.prunedDirs.has(name))
445
+ return true;
446
+ return !isLink && withinKeepPath(pack, source);
447
+ }
448
+ function shipsFile(pack, name, source) {
449
+ if (pack.droppedSuffixes.some((suffix) => name.endsWith(suffix)))
450
+ return false;
451
+ if (!pack.compiled.has(path2.resolve(source)) || withinKeepPath(pack, source))
452
+ return true;
453
+ return [...pack.keep].some((entry) => name === entry || entry.startsWith(".") && name.endsWith(entry));
454
+ }
455
+ function releaseCompiledSources(config) {
456
+ flushDevModuleCaches();
457
+ const index = readBuildIndex(config.outPath);
458
+ const graph = compiledSourceGraph(config.outPath, config.workspaceRoot);
459
+ const queue = Object.keys(index.modules).map((key) => releaseSourceFile(key.slice(key.indexOf(":", key.indexOf(":") + 1) + 1), config.root, config.workspaceRoot));
460
+ if (index.proxy)
461
+ queue.push(path2.resolve(config.root, index.proxy.file));
462
+ const script = /\.(?:[cm]?[jt]s|[jt]sx)$/;
463
+ const frozen = (dir, pattern) => (readDirEntries(dir) ?? []).filter((entry) => pattern.test(entry.name) && script.test(entry.name)).forEach((entry) => queue.push(path2.join(dir, entry.name)));
464
+ frozen(config.root, /^(?:pnext|next)\.config\./);
465
+ if (index.instrumentation) {
466
+ for (const dir of [config.root, path2.join(config.root, "src")])
467
+ frozen(dir, /^instrumentation\./);
468
+ }
469
+ const compiled = new Set;
470
+ for (const file of queue) {
471
+ if (compiled.has(file))
472
+ continue;
473
+ compiled.add(file);
474
+ let real = file;
475
+ try {
476
+ real = realpathSync2(file);
477
+ } catch {
478
+ continue;
479
+ }
480
+ compiled.add(real);
481
+ queue.push(...graph.get(file) ?? [], ...graph.get(real) ?? []);
482
+ }
483
+ return compiled;
484
+ }
485
+ async function writeVercelOutput(config, manifest, options = {}) {
486
+ const log = createVerboseLogger(options.verbose ?? false, "vercel");
487
+ const outputPath = path2.join(config.root, ".vercel", "output");
488
+ const staticFiles = manifest.staticFiles ?? {};
489
+ const warm = options.warm ?? startWarmChild(config);
490
+ await log.step("prepare output directory", () => emptyDir(outputPath));
491
+ let resolveWarmedModules;
492
+ const warmedModulesEarly = new Promise((resolve) => {
493
+ resolveWarmedModules = resolve;
494
+ });
495
+ const warmSettled = warm.finish(log, (modules) => resolveWarmedModules(modules), {
496
+ globalCss: globalCssSources(config),
497
+ clientReferences: [...compiledClientReferenceFiles()]
498
+ });
499
+ warmSettled.catch(() => {
500
+ return;
501
+ });
502
+ const warmedModules = await log.step("warm module cache (compiled)", () => warmedModulesEarly);
503
+ const functionPath = path2.join(outputPath, "functions", `${SERVER_FUNCTION}.func`);
504
+ await writeServerFunction(config, manifest, functionPath, warmedModules, warmSettled, log);
505
+ await log.step("copy static files", () => copyStaticFiles(path2.join(config.outPath, "public"), path2.join(outputPath, "static"), (relative) => !staticFiles[relative] || canServeStaticOnVercel(staticFiles[relative])));
506
+ const overrides = await staticOverrides(path2.join(config.outPath, "public"), staticFiles);
507
+ const routes = [
508
+ ...compatStaticRewrite(config, outputPath),
509
+ ...await immutableAssetRoutes(path2.join(config.outPath, "public"), manifest.publicAssets),
510
+ ...await proxyRoutes(config),
511
+ ...staticHeaderRoutes(staticFiles),
512
+ { handle: "filesystem" },
513
+ { src: "^/.*$", dest: `/${SERVER_FUNCTION}` }
514
+ ];
515
+ const vercelConfig = {
516
+ version: 3,
517
+ routes,
518
+ ...Object.keys(overrides).length > 0 ? { overrides } : {}
519
+ };
520
+ await writeText(path2.join(outputPath, "config.json"), `${JSON.stringify(vercelConfig, null, 2)}
521
+ `);
522
+ }
523
+ async function emptyDir(dir) {
524
+ const parent = path2.dirname(dir);
525
+ await mkdir(parent, { recursive: true });
526
+ const staleMarker = `${path2.basename(dir)}.stale-`;
527
+ if (existsSync2(dir)) {
528
+ await rename(dir, path2.join(parent, `${staleMarker}${process.pid.toString(36)}-${Date.now().toString(36)}`));
529
+ }
530
+ const stale = readdirSync(parent).filter((entry) => entry.startsWith(staleMarker)).map((entry) => path2.join(parent, entry));
531
+ await mkdir(dir, { recursive: true });
532
+ if (stale.length > 0) {
533
+ Bun.spawn(["rm", "-rf", ...stale], { stdout: "ignore", stderr: "ignore" });
534
+ }
535
+ }
536
+ function compatStaticRewrite(config, outputPath) {
537
+ if (!nextCompatEnabled(config))
538
+ return [];
539
+ const staticDir = path2.join(outputPath, "static");
540
+ const names = readdirSyncSafe(path2.join(staticDir, "assets")).filter((name) => !existsSync2(path2.join(staticDir, "_next", "static", name)));
541
+ if (names.length === 0)
542
+ return [];
543
+ const alternation = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
544
+ return [{ src: `^/_next/static/(${alternation})(/.*)?$`, dest: "/assets/$1$2", continue: true }];
545
+ }
546
+ function readdirSyncSafe(dir) {
547
+ return existsSync2(dir) ? readdirSync(dir) : [];
548
+ }
549
+ async function proxyRoutes(config) {
550
+ const proxyFile = findProxyFile(config);
551
+ if (!proxyFile)
552
+ return [];
553
+ const proxyModule = await import(pathToFileHref(proxyFile));
554
+ return [...proxyRoutePatterns(proxyModule.config), "^.*(?:%|//).*$"].map((src) => ({
555
+ src,
556
+ dest: `/${SERVER_FUNCTION}`
557
+ }));
558
+ }
559
+ async function writeServerFunction(config, manifest, functionPath, warmedModules, warmSettled, log) {
560
+ const workspaceRoot = config.workspaceRoot;
561
+ await mkdir(functionPath, { recursive: true });
562
+ const pack = packRules(config);
563
+ const framework = await resolveFrameworkPackage(workspaceRoot);
564
+ const { root: pnextRoot, inWorkspace: pnextInWorkspace, targetRel: pnextTargetRel } = framework;
565
+ const release = releaseEntries(config, manifest);
566
+ const prebundle = release ? readPrebundleStamp(pnextRoot, frameworkFingerprint()) : undefined;
567
+ const closure = await traceNodeModulesClosure(config, manifest, functionPath, framework, [...warmedModules, ...release ?? []], pack, log, Boolean(release));
568
+ const replicaPathFor = (file) => {
569
+ if (isInsideDir(pnextRoot, file)) {
570
+ return path2.join(functionPath, pnextTargetRel, path2.relative(pnextRoot, file));
571
+ }
572
+ if (isInsideDir(workspaceRoot, file)) {
573
+ return path2.join(functionPath, path2.relative(workspaceRoot, file));
574
+ }
575
+ return;
576
+ };
577
+ const appRel = path2.relative(workspaceRoot, config.root);
578
+ const packageRoots = workspacePackageRoots(workspaceRoot).map((root) => path2.resolve(root));
579
+ const neededRoots = new Set;
580
+ for (const file of closure.tracedFiles) {
581
+ const root = packageRoots.find((candidate) => isInsideDir(candidate, file));
582
+ if (root)
583
+ neededRoots.add(root);
584
+ }
585
+ for (const relative of closure.workspacePackages) {
586
+ neededRoots.add(path2.resolve(workspaceRoot, relative));
587
+ }
588
+ if (!release) {
589
+ for (const file of globalCssSources(config)) {
590
+ const root = packageRoots.find((candidate) => isInsideDir(candidate, file));
591
+ if (root)
592
+ neededRoots.add(root);
593
+ }
594
+ addWorkspaceDependencies(neededRoots, packageRoots, [path2.resolve(config.root), ...neededRoots]);
595
+ }
596
+ neededRoots.delete(path2.resolve(config.root));
597
+ neededRoots.delete(pnextRoot);
598
+ await log.step("await handler warm-up", () => warmSettled);
599
+ const roots = neededRoots.size + 2;
600
+ await log.step(`copy function tree (${closure.packageCount} packages, ${roots} roots)`, () => Promise.all([
601
+ closure.copy(),
602
+ copyTree(config.root, path2.join(functionPath, appRel), release ? { ...pack, compiled: releaseCompiledSources(config) } : pack, ["public", ".vercel", ".next", ".turbo"]),
603
+ copyPackageTree(pnextRoot, path2.join(functionPath, pnextTargetRel), pack, prebundle && ["config", "dist", ...prebundle.source]),
604
+ ...[...neededRoots].map((packageRoot) => copyPackageTree(packageRoot, path2.join(functionPath, path2.relative(workspaceRoot, packageRoot)), pack)),
605
+ ...["package.json", "tsconfig.json", "bunfig.toml"].map((name) => path2.join(workspaceRoot, name)).filter((file) => existsSync2(file)).map((file) => copyFile(file, path2.join(functionPath, path2.basename(file))))
606
+ ]));
607
+ await log.step("rewrite baked paths", () => rewriteBakedPaths(path2.join(functionPath, appRel, path2.relative(config.root, config.outPath)), [
608
+ ...pnextInWorkspace ? [] : [[pnextRoot, toPosixPath(path2.join(RUNTIME_ROOT, pnextTargetRel))]],
609
+ [workspaceRoot, RUNTIME_ROOT]
610
+ ]));
611
+ await log.step("inject compat tsconfig paths", () => injectCompatPaths(config, functionPath, pnextRoot, replicaPathFor));
612
+ const startEntry = toPosixPath(path2.join(pnextTargetRel, prebundle ? "dist/server/cli/start.js" : "src/cli/start.ts"));
613
+ await writeText(path2.join(functionPath, "index.mjs"), `import path from 'node:path';
614
+ import { createRequestHandler } from ${JSON.stringify(`./${startEntry}`)};
615
+
616
+ const handlerPromise = createRequestHandler({
617
+ root: path.join(import.meta.dirname, ${JSON.stringify(appRel)}),
618
+ });
619
+
620
+ async function handler(request) {
621
+ return (await handlerPromise)(request);
622
+ }
623
+
624
+ // Callable for the Node-style launcher, \`fetch\` for the Bun runtime.
625
+ export default Object.assign(handler, { fetch: handler });
626
+ `);
627
+ const maxDuration = manifest.routes.reduce((max, route) => route.maxDuration ? Math.max(max ?? 0, route.maxDuration) : max, undefined);
628
+ await writeText(path2.join(functionPath, ".vc-config.json"), `${JSON.stringify({
629
+ runtime: "bun1.4.x",
630
+ handler: "index.mjs",
631
+ launcherType: "Nodejs",
632
+ architecture: FUNCTION_PLATFORM.architecture,
633
+ useWebApi: true,
634
+ supportsResponseStreaming: true,
635
+ ...maxDuration ? { maxDuration } : {}
636
+ }, null, 2)}
637
+ `);
638
+ }
639
+ function addWorkspaceDependencies(roots, packageRoots, from) {
640
+ const byName = new Map;
641
+ for (const root of packageRoots) {
642
+ const name = packageManifest(root)?.name;
643
+ if (name && !byName.has(name))
644
+ byName.set(name, root);
645
+ }
646
+ const queue = [...from];
647
+ const seen = new Set(queue);
648
+ while (queue.length > 0) {
649
+ const manifest = packageManifest(queue.pop());
650
+ if (!manifest)
651
+ continue;
652
+ for (const field of ["dependencies", "optionalDependencies"]) {
653
+ for (const name of Object.keys(manifest[field] ?? {})) {
654
+ const root = byName.get(name);
655
+ if (!root || seen.has(root))
656
+ continue;
657
+ seen.add(root);
658
+ roots.add(root);
659
+ queue.push(root);
660
+ }
661
+ }
662
+ }
663
+ }
664
+ var manifests = new Map;
665
+ function packageManifest(root) {
666
+ const cached = manifests.get(root);
667
+ if (cached !== undefined || manifests.has(root))
668
+ return cached;
669
+ let parsed;
670
+ try {
671
+ parsed = JSON.parse(readFileSync2(path2.join(root, "package.json"), "utf8"));
672
+ } catch {
673
+ parsed = undefined;
674
+ }
675
+ manifests.set(root, parsed);
676
+ return parsed;
677
+ }
678
+ async function copyTree(from, to, pack, excludeNames = [], visited = new Set([realDir(from) ?? path2.resolve(from)])) {
679
+ const exclude = new Set(excludeNames);
680
+ const clone = directoryCloneEnabled ? await directoryCloner() : null;
681
+ if (exclude.size === 0 && !existsSync2(to)) {
682
+ await mkdir(path2.dirname(to), { recursive: true });
683
+ if (clone?.(from, to))
684
+ return normalizeClone(to, from, pack, visited);
685
+ }
686
+ const entries = readDirEntries(from);
687
+ if (!entries)
688
+ return;
689
+ await mkdir(to, { recursive: true });
690
+ await Promise.all(entries.map(async (entry) => {
691
+ const source = path2.join(from, entry.name);
692
+ const target = path2.join(to, entry.name);
693
+ if (exclude.has(entry.name) || !shipsDir(pack, entry.name, source, entry.isSymbolicLink()))
694
+ return;
695
+ if (entry.isSymbolicLink()) {
696
+ const link2 = resolveLinkTarget(source);
697
+ if (!link2)
698
+ return;
699
+ if (link2.isDirectory) {
700
+ if (visited.has(link2.path))
701
+ return;
702
+ visited.add(link2.path);
703
+ return copyTree(link2.path, target, pack, [], visited);
704
+ }
705
+ return shipsFile(pack, entry.name, source) ? linkOrCopyFile(link2.path, target) : undefined;
706
+ }
707
+ if (entry.isDirectory() && clone?.(source, target)) {
708
+ return normalizeClone(target, source, pack, visited);
709
+ }
710
+ if (entry.isDirectory())
711
+ return copyTree(source, target, pack, [], visited);
712
+ if (entry.isFile() && shipsFile(pack, entry.name, source))
713
+ return linkOrCopyFile(source, target);
714
+ }));
715
+ }
716
+ function readDirEntries(dir) {
717
+ try {
718
+ return readdirSync(dir, { withFileTypes: true });
719
+ } catch (error) {
720
+ if (error.code === "ENOENT")
721
+ return;
722
+ throw error;
723
+ }
724
+ }
725
+ var directoryCloneEnabled = true;
726
+ var cloner;
727
+ async function directoryCloner() {
728
+ if (cloner !== undefined)
729
+ return cloner;
730
+ cloner = null;
731
+ if (process.platform === "darwin") {
732
+ try {
733
+ const { dlopen } = await import("bun:ffi");
734
+ const { symbols } = dlopen("libSystem.B.dylib", {
735
+ clonefile: { args: ["cstring", "cstring", "i32"], returns: "i32" }
736
+ });
737
+ cloner = (from, to) => symbols.clonefile(Buffer.from(`${from}\x00`), Buffer.from(`${to}\x00`), 0) === 0;
738
+ } catch {}
739
+ }
740
+ return cloner;
741
+ }
742
+ async function normalizeClone(dir, from, pack, visited) {
743
+ const stack = [[dir, from]];
744
+ const pending = [];
745
+ while (stack.length > 0) {
746
+ const [current, currentFrom] = stack.pop();
747
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
748
+ const full = path2.join(current, entry.name);
749
+ const source = path2.join(currentFrom, entry.name);
750
+ if (!shipsDir(pack, entry.name, source, entry.isSymbolicLink())) {
751
+ rmSync(full, { recursive: true, force: true });
752
+ } else if (entry.isSymbolicLink()) {
753
+ const link2 = resolveLinkTarget(source);
754
+ rmSync(full, { force: true });
755
+ if (!link2)
756
+ continue;
757
+ if (link2.isDirectory) {
758
+ if (visited.has(link2.path))
759
+ continue;
760
+ visited.add(link2.path);
761
+ pending.push(copyTree(link2.path, full, pack, [], visited));
762
+ } else if (shipsFile(pack, entry.name, source)) {
763
+ pending.push(linkOrCopyFile(link2.path, full));
764
+ }
765
+ } else if (entry.isDirectory()) {
766
+ stack.push([full, source]);
767
+ } else if (!shipsFile(pack, entry.name, source)) {
768
+ rmSync(full, { force: true });
769
+ }
770
+ }
771
+ }
772
+ await Promise.all(pending);
773
+ }
774
+ async function resolveFrameworkPackage(workspaceRoot) {
775
+ const root = path2.resolve(__PNEXT_PACKAGE_ROOT__ + "/src/cli/adapters", "../../..");
776
+ const packageJson = await readPackageJson(root);
777
+ const packageName = packageJson?.name ?? "pnext";
778
+ const inWorkspace = isInsideDir(workspaceRoot, root) && !root.includes("node_modules");
779
+ return {
780
+ root,
781
+ packageName,
782
+ dependencies: Object.keys(packageJson?.dependencies ?? {}),
783
+ optionalDependencies: Object.keys(packageJson?.optionalDependencies ?? {}),
784
+ inWorkspace,
785
+ targetRel: inWorkspace ? path2.relative(workspaceRoot, root) : path2.join("node_modules", packageName)
786
+ };
787
+ }
788
+ var packageCopyExcludes = [
789
+ "node_modules",
790
+ ".cache",
791
+ ".vercel",
792
+ ".next",
793
+ ".pnext",
794
+ ".turbo",
795
+ "test",
796
+ "tests",
797
+ "__tests__"
798
+ ];
799
+ async function copyPackageTree(from, to, pack, only) {
800
+ const files = only ?? (await readPackageJson(from))?.files;
801
+ if (!files?.length || files.some((entry) => /[*?[\]{}!]/.test(entry))) {
802
+ return copyTree(from, to, pack, packageCopyExcludes);
803
+ }
804
+ await mkdir(to, { recursive: true });
805
+ await Promise.all([...files, "package.json", "tsconfig.json"].map(async (name) => {
806
+ const source = path2.join(from, name);
807
+ const stats = statSync(source, { throwIfNoEntry: false });
808
+ if (!stats)
809
+ return;
810
+ if (stats.isDirectory())
811
+ return copyTree(source, path2.join(to, name), pack);
812
+ if (!shipsFile(pack, name, source))
813
+ return;
814
+ await mkdir(path2.dirname(path2.join(to, name)), { recursive: true });
815
+ return linkOrCopyFile(source, path2.join(to, name));
816
+ }));
817
+ }
818
+ async function readPackageJson(dir) {
819
+ const file = path2.join(dir, "package.json");
820
+ if (!existsSync2(file))
821
+ return;
822
+ return JSON.parse(await readFile(file, "utf8"));
823
+ }
824
+ var dependencyClosureEnabled = true;
825
+ function skipDependencyClosure() {
826
+ return !dependencyClosureEnabled;
827
+ }
828
+ async function linkOrCopyFile(from, to) {
829
+ try {
830
+ await link(from, to);
831
+ } catch {
832
+ await copyFile(from, to).catch((error) => {
833
+ if (error.code !== "ENOENT")
834
+ throw error;
835
+ });
836
+ }
837
+ }
838
+ function resolveLinkTarget(link2) {
839
+ const resolved = realDir(link2) ?? realFile(link2);
840
+ if (!resolved)
841
+ return;
842
+ try {
843
+ return { path: resolved, isDirectory: statSync(resolved).isDirectory() };
844
+ } catch {
845
+ return;
846
+ }
847
+ }
848
+ function realFile(file) {
849
+ try {
850
+ return realpathSync2(file);
851
+ } catch {
852
+ return;
853
+ }
854
+ }
855
+ function isInsideDir(root, file) {
856
+ const relative = path2.relative(root, file);
857
+ return relative === "" || !relative.startsWith("..") && !path2.isAbsolute(relative);
858
+ }
859
+ function isFrameworkOwnedAliasTarget(frameworkRoot2, target) {
860
+ if (!path2.isAbsolute(target) || !isInsideDir(frameworkRoot2, target))
861
+ return false;
862
+ return !path2.relative(frameworkRoot2, target).split(path2.sep).includes("node_modules");
863
+ }
864
+ function frameworkOwnedAliases(config, frameworkRoot2) {
865
+ return Object.entries(getImportAliasExtensions().aliases(config, "server")).filter(([, target]) => isFrameworkOwnedAliasTarget(frameworkRoot2, target));
866
+ }
867
+ async function injectCompatPaths(config, functionPath, frameworkRoot2, replicaPathFor) {
868
+ const aliasTargets = frameworkOwnedAliases(config, frameworkRoot2).map(([specifier, target]) => [specifier, replicaPathFor(target)]).filter((entry) => Boolean(entry[1]));
869
+ if (aliasTargets.length === 0)
870
+ return;
871
+ for (const file of walkTsconfigFiles(functionPath)) {
872
+ let parsed;
873
+ try {
874
+ const source = stripJsonComments(await readFile(file, "utf8")).replace(/,\s*([}\]])/g, "$1");
875
+ parsed = JSON.parse(source);
876
+ } catch (error) {
877
+ console.warn(`vercel adapter: could not update ${file}:`, error);
878
+ continue;
879
+ }
880
+ const dir = path2.dirname(file);
881
+ const compilerOptions = parsed.compilerOptions ??= {};
882
+ const paths = compilerOptions.paths ??= {};
883
+ for (const [specifier, target] of aliasTargets) {
884
+ if (paths[specifier])
885
+ continue;
886
+ const relative = toPosixPath(path2.relative(dir, target));
887
+ paths[specifier] = [relative.startsWith(".") ? relative : `./${relative}`];
888
+ }
889
+ compilerOptions.baseUrl ??= ".";
890
+ await rm(file);
891
+ await writeFile(file, `${JSON.stringify(parsed, null, 2)}
892
+ `);
893
+ }
894
+ }
895
+ function stripJsonComments(source) {
896
+ let result = "";
897
+ let inString = false;
898
+ for (let index = 0;index < source.length; index++) {
899
+ const char = source[index];
900
+ if (inString) {
901
+ result += char;
902
+ if (char === "\\") {
903
+ result += source[++index] ?? "";
904
+ } else if (char === '"') {
905
+ inString = false;
906
+ }
907
+ continue;
908
+ }
909
+ if (char === '"') {
910
+ inString = true;
911
+ result += char;
912
+ continue;
913
+ }
914
+ if (char === "/" && source[index + 1] === "/") {
915
+ while (index < source.length && source[index] !== `
916
+ `)
917
+ index++;
918
+ result += `
919
+ `;
920
+ continue;
921
+ }
922
+ if (char === "/" && source[index + 1] === "*") {
923
+ index += 2;
924
+ while (index < source.length && !(source[index] === "*" && source[index + 1] === "/"))
925
+ index++;
926
+ index++;
927
+ continue;
928
+ }
929
+ result += char;
930
+ }
931
+ return result;
932
+ }
933
+ var bakedPathFileFilter = /\.(?:m?js|cjs|jsx|tsx?|json|html|css)$/;
934
+ var BAKED_PATH_CONCURRENCY = 64;
935
+ async function rewriteBakedPaths(dir, replacements) {
936
+ if (!existsSync2(dir))
937
+ return;
938
+ const files = (await listFiles(dir)).filter((file) => bakedPathFileFilter.test(file));
939
+ for (let i = 0;i < files.length; i += BAKED_PATH_CONCURRENCY) {
940
+ await Promise.all(files.slice(i, i + BAKED_PATH_CONCURRENCY).map(async (file) => {
941
+ const source = await readFile(file, "utf8");
942
+ let rewritten = source;
943
+ for (const [from, to] of replacements) {
944
+ if (rewritten.includes(from))
945
+ rewritten = rewritten.replaceAll(from, to);
946
+ }
947
+ if (rewritten === source)
948
+ return;
949
+ await rm(file);
950
+ await writeFile(file, rewritten);
951
+ }));
952
+ }
953
+ }
954
+ async function artifactSpecifiers(file) {
955
+ const sidecar = await readFile(`${file}${compiledSpecifiersManifestSuffix}`, "utf8").catch(() => null);
956
+ if (sidecar !== null) {
957
+ try {
958
+ const parsed = JSON.parse(sidecar);
959
+ if (Array.isArray(parsed) && parsed.every((entry) => typeof entry === "string")) {
960
+ return parsed;
961
+ }
962
+ } catch {}
963
+ }
964
+ const source = await readFile(file, "utf8").catch(() => null);
965
+ return source === null ? null : importSpecifiers(source, file);
966
+ }
967
+ async function traceNodeModulesClosure(config, manifest, functionPath, framework, warmedModules, pack, log, release = false) {
968
+ const workspaceRoot = config.workspaceRoot;
969
+ const specifiers = new Set;
970
+ const tracedFiles = new Set;
971
+ const hrefPackageDirs = new Set;
972
+ const frameworkAliasedSpecifiers = new Set(frameworkOwnedAliases(config, path2.resolve(framework.root)).map(([specifier]) => specifier));
973
+ await log.step("trace runtime imports", async () => {
974
+ const queue2 = [];
975
+ const seen2 = tracedFiles;
976
+ const enqueue = (file) => {
977
+ if (!file)
978
+ return;
979
+ const resolved = path2.resolve(file);
980
+ if (seen2.has(resolved) || !existsSync2(resolved))
981
+ return;
982
+ seen2.add(resolved);
983
+ queue2.push(resolved);
984
+ };
985
+ if (!release) {
986
+ for (const route of manifest.routes) {
987
+ if (route.kind === "handler")
988
+ enqueue(route.file);
989
+ }
990
+ enqueue(findProxyFile(config) ?? undefined);
991
+ enqueue(path2.join(config.root, "pnext.config.ts"));
992
+ enqueue(path2.join(config.root, "next.config.js"));
993
+ }
994
+ for (const file of warmedModules)
995
+ enqueue(file);
996
+ const visit = async (file) => {
997
+ if (!scriptFilePattern.test(file))
998
+ return;
999
+ const found = await artifactSpecifiers(file);
1000
+ if (found === null)
1001
+ return;
1002
+ for (const specifier of found) {
1003
+ if (frameworkAliasedSpecifiers.has(specifier))
1004
+ continue;
1005
+ const absolute = absolutePathFromSpecifier(specifier);
1006
+ if (absolute && isInsideDir(framework.root, absolute))
1007
+ continue;
1008
+ if (absolute) {
1009
+ const name2 = packageNameFromPath(absolute);
1010
+ if (name2) {
1011
+ specifiers.add(name2);
1012
+ hrefPackageDirs.add(packageDirFromPath(absolute, name2));
1013
+ } else if (isInsideDir(config.outPath, absolute))
1014
+ enqueue(absolute);
1015
+ continue;
1016
+ }
1017
+ if (/^(?:node:|bun$|bun:|data:)/.test(specifier))
1018
+ continue;
1019
+ const resolved = resolveImport(config.root, file, specifier, config.workspaceRoot);
1020
+ if (resolved && isInsideDir(workspaceRoot, resolved) && !resolved.includes("node_modules")) {
1021
+ enqueue(resolved);
1022
+ }
1023
+ const installed = specifier.startsWith(".") && resolved && packageNameFromPath(resolved);
1024
+ if (installed) {
1025
+ specifiers.add(installed);
1026
+ hrefPackageDirs.add(packageDirFromPath(resolved, installed));
1027
+ }
1028
+ const name = packageNameFromSpecifier(specifier);
1029
+ if (name)
1030
+ specifiers.add(name);
1031
+ }
1032
+ };
1033
+ const READ_BATCH = 64;
1034
+ for (let frontier = queue2.splice(0);frontier.length > 0; frontier = queue2.splice(0)) {
1035
+ for (let index = 0;index < frontier.length; index += READ_BATCH) {
1036
+ await Promise.all(frontier.slice(index, index + READ_BATCH).map(visit));
1037
+ }
1038
+ }
1039
+ log.log(`traced ${seen2.size} runtime modules`);
1040
+ });
1041
+ const packageDirs = new Map;
1042
+ const nestedCopies = new Map;
1043
+ const workspaceLinks = new Map;
1044
+ const hostNatives = new Map;
1045
+ const appDependencies = await declaredDependencies(config.root);
1046
+ const runtimeDependencies = release ? await frameworkRuntimePackages(framework.root) : undefined;
1047
+ const queue = [
1048
+ ...framework.dependencies.filter((name) => !runtimeDependencies || runtimeDependencies.has(name)).map((name) => ({ name, from: framework.root })),
1049
+ ...framework.optionalDependencies.filter((name) => appDependencies.has(name)).map((name) => ({ name, from: framework.root })),
1050
+ ...[...specifiers].map((name) => ({ name, from: workspaceRoot }))
1051
+ ];
1052
+ const seen = new Set;
1053
+ while (queue.length > 0) {
1054
+ const { name, from, owner } = queue.shift();
1055
+ if (seen.has(name))
1056
+ continue;
1057
+ seen.add(name);
1058
+ if (name === framework.packageName) {
1059
+ if (framework.inWorkspace)
1060
+ workspaceLinks.set(name, framework.targetRel);
1061
+ continue;
1062
+ }
1063
+ const dir = resolvePackageDir(name, [from, workspaceRoot, config.root]);
1064
+ if (!dir)
1065
+ continue;
1066
+ const workspaceRelative = path2.relative(workspaceRoot, dir);
1067
+ if (!workspaceRelative.startsWith("..") && !workspaceRelative.startsWith("node_modules")) {
1068
+ workspaceLinks.set(name, workspaceRelative);
1069
+ continue;
1070
+ }
1071
+ const packageJson = await readPackageJson(dir);
1072
+ const platformBound = Boolean(packageJson?.os ?? packageJson?.cpu);
1073
+ if (packageJson && platformBound && !matchesFunctionPlatform(packageJson)) {
1074
+ hostNatives.set(name, { dir, owner });
1075
+ continue;
1076
+ }
1077
+ packageDirs.set(name, dir);
1078
+ if (!packageJson)
1079
+ continue;
1080
+ const expand = async (packageDir, packageJson2, target) => {
1081
+ const self = { name: packageJson2?.name ?? name, version: packageJson2?.version ?? "" };
1082
+ for (const dependency of [
1083
+ ...Object.keys(packageJson2?.dependencies ?? {}),
1084
+ ...Object.keys(packageJson2?.optionalDependencies ?? {})
1085
+ ]) {
1086
+ const nested = path2.join(packageDir, "node_modules", dependency);
1087
+ const nestedJson = existsSync2(path2.join(nested, "package.json")) ? await readPackageJson(nested) : undefined;
1088
+ if (!nestedJson || nestedJson.os || nestedJson.cpu) {
1089
+ queue.push({ name: dependency, from: packageDir, owner: self });
1090
+ continue;
1091
+ }
1092
+ const nestedTarget = path2.join(target, "node_modules", dependency);
1093
+ if (nestedCopies.has(nestedTarget))
1094
+ continue;
1095
+ nestedCopies.set(nestedTarget, nested);
1096
+ await expand(nested, nestedJson, nestedTarget);
1097
+ }
1098
+ };
1099
+ await expand(dir, packageJson, path2.join("node_modules", name));
1100
+ }
1101
+ if (hostNatives.size > 0 && !skipDependencyClosure()) {
1102
+ const targets = await log.step(`resolve ${FUNCTION_PLATFORM.os}-${FUNCTION_PLATFORM.cpu} natives (${hostNatives.size} packages)`, () => platformNativePackages(hostNatives, log));
1103
+ for (const [name, dir] of targets)
1104
+ packageDirs.set(name, dir);
1105
+ }
1106
+ const copy = async () => {
1107
+ const entries = skipDependencyClosure() ? [] : [...packageDirs];
1108
+ const batchSize = 16;
1109
+ for (let index = 0;index < entries.length; index += batchSize) {
1110
+ await Promise.all(entries.slice(index, index + batchSize).map(async ([name, dir]) => {
1111
+ const target = path2.join(functionPath, "node_modules", name);
1112
+ await mkdir(path2.dirname(target), { recursive: true });
1113
+ await copyTree(dir, target, pack);
1114
+ }));
1115
+ }
1116
+ for (const [target, dir] of skipDependencyClosure() ? [] : nestedCopies) {
1117
+ await mkdir(path2.dirname(path2.join(functionPath, target)), { recursive: true });
1118
+ await copyTree(dir, path2.join(functionPath, target), pack);
1119
+ }
1120
+ for (const dir of skipDependencyClosure() ? [] : hrefPackageDirs) {
1121
+ const relative = path2.relative(workspaceRoot, dir);
1122
+ const target = path2.join(functionPath, relative);
1123
+ if (relative.startsWith("..") || existsSync2(target))
1124
+ continue;
1125
+ await mkdir(path2.dirname(target), { recursive: true });
1126
+ await copyTree(dir, target, pack);
1127
+ }
1128
+ for (const [name, workspaceRelative] of workspaceLinks) {
1129
+ const linkPath = path2.join(functionPath, "node_modules", name);
1130
+ await mkdir(path2.dirname(linkPath), { recursive: true });
1131
+ const target = path2.relative(path2.dirname(linkPath), path2.join(functionPath, workspaceRelative));
1132
+ if (!existsSync2(linkPath))
1133
+ await symlink(target, linkPath, "dir");
1134
+ }
1135
+ };
1136
+ return {
1137
+ tracedFiles,
1138
+ workspacePackages: [...workspaceLinks.values()],
1139
+ packageCount: packageDirs.size,
1140
+ copy
1141
+ };
1142
+ }
1143
+ function releaseEntries(config, manifest) {
1144
+ if (!existsSync2(buildIndexFile(config.outPath)))
1145
+ return;
1146
+ const index = readBuildIndex(config.outPath);
1147
+ return [
1148
+ ...Object.values(index.modules),
1149
+ index.nextConfig,
1150
+ index.instrumentation?.file,
1151
+ index.instrumentation?.edge,
1152
+ ...Object.values(index.compat?.cacheHandlers ?? {}),
1153
+ manifest.proxyModule
1154
+ ].filter((artifact) => artifact !== undefined).map((artifact) => path2.resolve(config.outPath, artifact));
1155
+ }
1156
+ async function frameworkRuntimePackages(frameworkRoot2) {
1157
+ const src = path2.join(frameworkRoot2, "src");
1158
+ const scanners = {
1159
+ ts: new Bun.Transpiler({ loader: "ts" }),
1160
+ tsx: new Bun.Transpiler({ loader: "tsx" })
1161
+ };
1162
+ const queue = [
1163
+ ...runtimeEntryFiles.map((file) => path2.join(src, file)),
1164
+ ...runtimeEntryDirs.flatMap((dir) => listSourceFiles(path2.join(src, dir)).filter((file) => /(?<!\.d)\.tsx?$/.test(file)))
1165
+ ];
1166
+ const seen = new Set(queue);
1167
+ const packages = new Set;
1168
+ for (const file of queue) {
1169
+ const scanner = file.endsWith(".tsx") || file.endsWith(".jsx") ? scanners.tsx : scanners.ts;
1170
+ for (const edge of scanner.scanImports(await readFile(file, "utf8"))) {
1171
+ if (edge.kind !== "import-statement" && edge.kind !== "dynamic-import")
1172
+ continue;
1173
+ if (!edge.path.startsWith(".")) {
1174
+ const name = packageNameFromSpecifier(edge.path);
1175
+ if (name)
1176
+ packages.add(name);
1177
+ continue;
1178
+ }
1179
+ const target = resolveFrom(edge.path, path2.dirname(file));
1180
+ if (target && !seen.has(target) && isInsideDir(src, target) && scriptFilePattern.test(target)) {
1181
+ seen.add(target);
1182
+ queue.push(target);
1183
+ }
1184
+ }
1185
+ }
1186
+ return packages;
1187
+ }
1188
+ function resolveFrom(specifier, dir) {
1189
+ try {
1190
+ return Bun.resolveSync(specifier, dir);
1191
+ } catch {
1192
+ return;
1193
+ }
1194
+ }
1195
+ function listSourceFiles(dir) {
1196
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? listSourceFiles(path2.join(dir, entry.name)) : [path2.join(dir, entry.name)]);
1197
+ }
1198
+ async function platformNativePackages(hostNatives, log) {
1199
+ const owners = new Map;
1200
+ for (const [name, { dir, owner }] of hostNatives) {
1201
+ const spec = owner ?? { name, version: (await readPackageJson(dir))?.version ?? "" };
1202
+ if (spec.version)
1203
+ owners.set(spec.name, spec.version);
1204
+ }
1205
+ const specs = [...owners].map(([name, version]) => `${name}@${version}`).sort();
1206
+ const fallback = () => new Map([...hostNatives].map(([name, { dir }]) => [name, dir]));
1207
+ if (specs.length === 0)
1208
+ return fallback();
1209
+ try {
1210
+ const installed = await crossPlatformInstall(specs);
1211
+ const matches = new Map;
1212
+ for (const [name, dir] of installed) {
1213
+ const packageJson = await readPackageJson(dir);
1214
+ if (packageJson && matchesFunctionPlatform(packageJson))
1215
+ matches.set(name, dir);
1216
+ }
1217
+ if (matches.size === 0) {
1218
+ throw new Error(`no ${FUNCTION_PLATFORM.os} builds in ${specs.join(" ")}`);
1219
+ }
1220
+ return matches;
1221
+ } catch (error) {
1222
+ console.warn(`vercel adapter: could not fetch ${FUNCTION_PLATFORM.os}-${FUNCTION_PLATFORM.cpu} native packages; the function will carry this machine's builds and fail at runtime:`, error);
1223
+ log.log("falling back to host native packages");
1224
+ return fallback();
1225
+ }
1226
+ }
1227
+ function matchesFunctionPlatform(packageJson) {
1228
+ const matches = (declared, value) => {
1229
+ if (!declared?.length)
1230
+ return true;
1231
+ if (declared.every((entry) => entry.startsWith("!")))
1232
+ return !declared.includes(`!${value}`);
1233
+ return declared.includes(value);
1234
+ };
1235
+ return matches(packageJson.os, FUNCTION_PLATFORM.os) && matches(packageJson.cpu, FUNCTION_PLATFORM.cpu) && matches(packageJson.libc, FUNCTION_PLATFORM.libc);
1236
+ }
1237
+ async function crossPlatformInstall(specs) {
1238
+ const key = Bun.hash.xxHash3(`${FUNCTION_PLATFORM.os}-${FUNCTION_PLATFORM.cpu}\x00${specs.join("\x00")}`).toString(16);
1239
+ const dir = path2.join(cacheRoot(), "vercel-natives", key);
1240
+ const modules = path2.join(dir, "node_modules");
1241
+ if (!existsSync2(modules)) {
1242
+ const staging = `${dir}.${process.pid.toString(36)}`;
1243
+ await rm(staging, { recursive: true, force: true });
1244
+ await mkdir(staging, { recursive: true });
1245
+ await writeText(path2.join(staging, "package.json"), `{"name":"pnext-natives"}
1246
+ `);
1247
+ const install = Bun.spawn([
1248
+ "bun",
1249
+ "add",
1250
+ "--no-save",
1251
+ "--ignore-scripts",
1252
+ "--silent",
1253
+ `--os=${FUNCTION_PLATFORM.os}`,
1254
+ `--cpu=${FUNCTION_PLATFORM.cpu}`,
1255
+ ...specs
1256
+ ], { cwd: staging, stdout: "ignore", stderr: "pipe" });
1257
+ if (await install.exited !== 0) {
1258
+ const stderr = await new Response(install.stderr).text();
1259
+ await rm(staging, { recursive: true, force: true });
1260
+ throw new Error(stderr.trim() || "bun add failed");
1261
+ }
1262
+ await rm(dir, { recursive: true, force: true });
1263
+ await rename(staging, dir);
1264
+ }
1265
+ const installed = new Map;
1266
+ for (const entry of readdirSync(modules)) {
1267
+ if (entry.startsWith("."))
1268
+ continue;
1269
+ if (!entry.startsWith("@")) {
1270
+ installed.set(entry, path2.join(modules, entry));
1271
+ continue;
1272
+ }
1273
+ for (const scoped of readdirSync(path2.join(modules, entry))) {
1274
+ installed.set(`${entry}/${scoped}`, path2.join(modules, entry, scoped));
1275
+ }
1276
+ }
1277
+ return installed;
1278
+ }
1279
+ var scriptFilePattern = /\.(?:m?js|cjs|jsx|tsx?)$/;
1280
+ var skippedScanDirs = new Set(["node_modules", ".git", ".next", ".pnext", ".turbo", ".vercel"]);
1281
+ function* walkTsconfigFiles(root) {
1282
+ const stack = [root];
1283
+ while (stack.length > 0) {
1284
+ const dir = stack.pop();
1285
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1286
+ const full = path2.join(dir, entry.name);
1287
+ if (entry.isDirectory()) {
1288
+ if (!skippedScanDirs.has(entry.name))
1289
+ stack.push(full);
1290
+ } else if (entry.isFile() && entry.name === "tsconfig.json") {
1291
+ yield full;
1292
+ }
1293
+ }
1294
+ }
1295
+ }
1296
+ async function declaredDependencies(root) {
1297
+ const packageJson = await readPackageJson(root);
1298
+ return new Set(["dependencies", "optionalDependencies", "devDependencies"].flatMap((field) => Object.keys(packageJson?.[field] ?? {})));
1299
+ }
1300
+ function absolutePathFromSpecifier(specifier) {
1301
+ if (specifier.startsWith("file://"))
1302
+ return fileURLToPath2(specifier);
1303
+ return path2.isAbsolute(specifier) ? specifier : undefined;
1304
+ }
1305
+ function packageDirFromPath(file, name) {
1306
+ const posix = toPosixPath(file);
1307
+ const marker = `/node_modules/${name}/`;
1308
+ return posix.slice(0, posix.lastIndexOf(marker) + marker.length - 1);
1309
+ }
1310
+ function packageNameFromPath(file) {
1311
+ const parts = toPosixPath(file).split("/node_modules/");
1312
+ const tail = parts.at(-1);
1313
+ if (parts.length < 2 || !tail)
1314
+ return;
1315
+ const segments = tail.split("/");
1316
+ return segments[0]?.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
1317
+ }
1318
+ function packageNameFromSpecifier(specifier) {
1319
+ if (/^[./#]|^file:|^node:|^data:/.test(specifier))
1320
+ return;
1321
+ if (specifier === "bun" || specifier.startsWith("bun:"))
1322
+ return;
1323
+ if (specifier.includes(":"))
1324
+ return;
1325
+ if (specifier.startsWith("@") && !/^@[^/]+\/[^/]+/.test(specifier))
1326
+ return;
1327
+ const parts = specifier.split("/");
1328
+ const name = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
1329
+ if (!name || builtinModules.includes(name))
1330
+ return;
1331
+ return name;
1332
+ }
1333
+ function resolvePackageDir(name, fromDirs) {
1334
+ for (const from of fromDirs) {
1335
+ let dir = path2.resolve(from);
1336
+ while (true) {
1337
+ const candidate = path2.join(dir, "node_modules", name);
1338
+ if (existsSync2(path2.join(candidate, "package.json")))
1339
+ return realDir(candidate);
1340
+ const parent = path2.dirname(dir);
1341
+ if (parent === dir)
1342
+ break;
1343
+ dir = parent;
1344
+ }
1345
+ }
1346
+ return;
1347
+ }
1348
+ function realDir(dir) {
1349
+ try {
1350
+ return statSync(dir).isDirectory() ? realpathSync2(dir) : undefined;
1351
+ } catch {
1352
+ return;
1353
+ }
1354
+ }
1355
+ async function copyStaticFiles(from, to, shouldCopy = () => true) {
1356
+ const files = (await listFiles(from)).filter((file) => shouldCopy(toPosixPath(path2.relative(from, file))));
1357
+ const directories = new Set(files.map((file) => path2.dirname(path2.join(to, path2.relative(from, file)))));
1358
+ await Promise.all([...directories].map((dir) => mkdir(dir, { recursive: true })));
1359
+ await Promise.all(files.map((file) => linkOrCopyFile(file, path2.join(to, path2.relative(from, file)))));
1360
+ }
1361
+ async function staticOverrides(publicPath, staticFiles) {
1362
+ const overrides = {};
1363
+ for (const file of await listFiles(publicPath)) {
1364
+ const relative = toPosixPath(path2.relative(publicPath, file));
1365
+ if (!relative.endsWith("/index.html"))
1366
+ continue;
1367
+ overrides[relative] = { path: relative.replace(/\/index\.html$/, "") };
1368
+ }
1369
+ for (const [relative, metadata] of Object.entries(staticFiles)) {
1370
+ if (!canServeStaticOnVercel(metadata))
1371
+ continue;
1372
+ const contentType = metadata.headers.find(([name]) => name.toLowerCase() === "content-type")?.[1];
1373
+ if (contentType)
1374
+ overrides[relative] = { ...overrides[relative], contentType };
1375
+ }
1376
+ return overrides;
1377
+ }
1378
+ async function immutableAssetRoutes(publicDir, publicAssets = []) {
1379
+ const app = new Set(publicAssets);
1380
+ const built = publicAssets.length > 0 ? (await listFiles(publicDir)).map((file) => toPosixPath(path2.relative(publicDir, file))).filter((relative) => !app.has(relative) && immutableAssetPath(relative)) : [];
1381
+ const patterns = immutableAssetPatterns(built, publicAssets);
1382
+ return routeSources(patterns, (source) => `^/(?:${source})`).map((src) => ({
1383
+ src,
1384
+ headers: { "cache-control": immutableCacheControl },
1385
+ continue: true,
1386
+ important: true
1387
+ }));
1388
+ }
1389
+ function immutableAssetPatterns(built, publicAssets) {
1390
+ const appDirs = new Set(publicAssets.flatMap(ancestorDirs));
1391
+ const prefixes = [...new Set(immutableAssetPrefixes())];
1392
+ const patterns = prefixes.filter((prefix) => !appDirs.has(prefix)).map(escapeRegex);
1393
+ for (const relative of built) {
1394
+ const prefix = prefixes.find((prefix2) => relative.startsWith(prefix2));
1395
+ if (!prefix || !appDirs.has(prefix))
1396
+ continue;
1397
+ const dir = ancestorDirs(relative).find((dir2) => dir2.length > prefix.length && !appDirs.has(dir2));
1398
+ patterns.push(dir ? escapeRegex(requestPath(dir)) : `${escapeRegex(requestPath(relative))}$`);
1399
+ }
1400
+ return [...new Set(patterns)];
1401
+ }
1402
+ function requestPath(relative) {
1403
+ return relative.replace(/[\0-\x20"#<>?`{}\x7f-\u{10ffff}]/gu, (char) => encodeURIComponent(char));
1404
+ }
1405
+ function ancestorDirs(relative) {
1406
+ const parts = relative.split("/").slice(0, -1);
1407
+ return parts.map((_, index) => `${parts.slice(0, index + 1).join("/")}/`);
1408
+ }
1409
+ var functionOnlyHeaders = new Set([
1410
+ "content-length",
1411
+ "content-encoding",
1412
+ "transfer-encoding",
1413
+ "connection",
1414
+ "set-cookie"
1415
+ ]);
1416
+ function canServeStaticOnVercel(metadata) {
1417
+ if (metadata.status !== 200)
1418
+ return false;
1419
+ const headers = routeHeaders(metadata);
1420
+ if (headers.length === 0)
1421
+ return true;
1422
+ return metadata.revalidateSeconds === undefined && metadata.expireSeconds === undefined && !metadata.tags?.length && headers.every(([name]) => !functionOnlyHeaders.has(name.toLowerCase()));
1423
+ }
1424
+ function routeHeaders(metadata) {
1425
+ return metadata.headers.filter(([name]) => name.toLowerCase() !== "content-type");
1426
+ }
1427
+ var maxRouteSourceLength = 2000;
1428
+ function staticHeaderRoutes(staticFiles) {
1429
+ const groups = new Map;
1430
+ for (const [relative, metadata] of Object.entries(staticFiles)) {
1431
+ const extra = routeHeaders(metadata);
1432
+ if (extra.length === 0 || !canServeStaticOnVercel(metadata))
1433
+ continue;
1434
+ const headers = Object.fromEntries(new Headers(extra));
1435
+ const key = JSON.stringify(headers);
1436
+ const group = groups.get(key) ?? { headers, patterns: [] };
1437
+ groups.set(key, group);
1438
+ group.patterns.push(servedPathPattern(relative));
1439
+ }
1440
+ return [...groups.values()].flatMap(({ headers, patterns }) => routeSources(patterns, (source) => `^/(?:${source})$`).map((src) => ({
1441
+ src,
1442
+ methods: ["GET", "HEAD"],
1443
+ headers,
1444
+ continue: true,
1445
+ important: true
1446
+ })));
1447
+ }
1448
+ function routeSources(patterns, wrap) {
1449
+ const sources = [];
1450
+ for (const pattern of patterns) {
1451
+ const last = sources.length - 1;
1452
+ if (last >= 0 && wrap(`${sources[last]}|${pattern}`).length <= maxRouteSourceLength) {
1453
+ sources[last] += `|${pattern}`;
1454
+ } else {
1455
+ sources.push(pattern);
1456
+ }
1457
+ }
1458
+ return sources.map(wrap);
1459
+ }
1460
+ function servedPathPattern(relative) {
1461
+ if (relative === "index.html")
1462
+ return "(?:index\\.html)?";
1463
+ if (!relative.endsWith("/index.html"))
1464
+ return escapeRegex(relative);
1465
+ return `${escapeRegex(relative.slice(0, -"/index.html".length))}(?:/|/index\\.html)?`;
1466
+ }
1467
+
1468
+ // src/cli/build.ts
1469
+ import { runWithCacheScope } from "../../../src/request/cache.ts";
1470
+
1471
+ // src/cli/build/cache.ts
1472
+ import { createHash } from "crypto";
1473
+ import { existsSync as existsSync3 } from "fs";
1474
+ import { lstat, mkdir as mkdir2, readFile as readFile2, readdir, readlink } from "fs/promises";
1475
+ import path3 from "path";
1476
+ var CACHE_VERSION = 2;
1477
+ var CACHE_SEGMENTS = ["cache", "build"];
1478
+ var SKIP_INPUT_DIRS = new Set([
1479
+ ".claude",
1480
+ ".git",
1481
+ ".husky",
1482
+ ".next",
1483
+ ".pnext",
1484
+ ".tmp",
1485
+ ".turbo",
1486
+ ".vercel",
1487
+ ".vscode",
1488
+ "node_modules"
1489
+ ]);
1490
+ var SKIP_INPUT_FILE = /(?:^\.DS_Store$|\.(?:log|pid)$)/i;
1491
+ var LOCK_FILES = [
1492
+ "bun.lock",
1493
+ "bun.lockb",
1494
+ "package-lock.json",
1495
+ "npm-shrinkwrap.json",
1496
+ "pnpm-lock.yaml",
1497
+ "yarn.lock"
1498
+ ];
1499
+ async function lookupBuildCache(config, options) {
1500
+ if (!cacheEnabled(options))
1501
+ return { enabled: false };
1502
+ const record = await readRecord(config.outPath);
1503
+ const inputs = await inputRecords(config, record?.inputs);
1504
+ const context = buildContext();
1505
+ const key = buildKey(context, inputs);
1506
+ if (record?.key !== key)
1507
+ return { enabled: true, context, inputs, reason: "inputs" };
1508
+ const output = await outputSnapshot(config.outPath);
1509
+ if (output.hash !== record.outputHash) {
1510
+ const changed = changedFiles(record.outputs, output.files).slice(0, 3).join(", ");
1511
+ return { enabled: true, context, inputs, reason: `output (${changed || "unknown"})` };
1512
+ }
1513
+ try {
1514
+ const manifest = resolveManifest(JSON.parse(await readFile2(path3.join(config.outPath, "manifest.json"), "utf8")), config.outPath, config.root);
1515
+ return { enabled: true, context, inputs, manifest, reason: "hit" };
1516
+ } catch {
1517
+ return { enabled: true, context, inputs, reason: "manifest" };
1518
+ }
1519
+ }
1520
+ async function writeBuildCache(config, options, session) {
1521
+ if (!session.enabled || !session.context || !cacheEnabled(options))
1522
+ return;
1523
+ const inputs = await inputRecords(config, session.inputs);
1524
+ const output = await outputSnapshot(config.outPath);
1525
+ const record = {
1526
+ version: CACHE_VERSION,
1527
+ key: buildKey(session.context, inputs),
1528
+ inputs,
1529
+ outputHash: output.hash,
1530
+ outputs: output.files
1531
+ };
1532
+ await mkdir2(cacheDir(config.outPath), { recursive: true });
1533
+ await writeFileAtomic(recordFile(config.outPath), JSON.stringify(record));
1534
+ }
1535
+ function cacheEnabled(options) {
1536
+ if (process.env.PNEXT_BUILD_CACHE !== "1")
1537
+ return false;
1538
+ return options.adapter === undefined && options.debugBuildPaths === undefined && options.buildMode === undefined && options.debugPrerender !== true;
1539
+ }
1540
+ function cacheDir(outPath) {
1541
+ return path3.join(outPath, ...CACHE_SEGMENTS);
1542
+ }
1543
+ function recordFile(outPath) {
1544
+ return path3.join(cacheDir(outPath), "result.json");
1545
+ }
1546
+ async function readRecord(outPath) {
1547
+ try {
1548
+ const parsed = JSON.parse(await readFile2(recordFile(outPath), "utf8"));
1549
+ if (parsed.version === CACHE_VERSION && parsed.key && parsed.inputs && parsed.outputHash && parsed.outputs) {
1550
+ return parsed;
1551
+ }
1552
+ } catch {}
1553
+ return;
1554
+ }
1555
+ function buildContext() {
1556
+ const hash = createHash("sha256");
1557
+ hash.update(`pnext-build-cache:${CACHE_VERSION}\x00`);
1558
+ hash.update(frameworkFingerprint());
1559
+ hash.update(`\x00bun:${Bun.version}\x00`);
1560
+ for (const [name, value] of Object.entries(process.env).sort(([a], [b]) => a.localeCompare(b))) {
1561
+ hash.update(`${name}=${value ?? ""}\x00`);
1562
+ }
1563
+ return hash.digest("hex");
1564
+ }
1565
+ function buildKey(context, inputs) {
1566
+ const hash = createHash("sha256");
1567
+ hash.update(context);
1568
+ for (const [file, record] of Object.entries(inputs).sort(([a], [b]) => a.localeCompare(b))) {
1569
+ hash.update(`${file}\x00${record[2]}\x00`);
1570
+ }
1571
+ return hash.digest("hex");
1572
+ }
1573
+ async function inputRecords(config, previous) {
1574
+ const files = new Map;
1575
+ await collectTree(config.root, "root", files, config.outPath);
1576
+ await collectModuleGraphInputs(config, files);
1577
+ for (const [prefix, root] of [
1578
+ ["root-deps", config.root],
1579
+ ["workspace-deps", config.workspaceRoot]
1580
+ ]) {
1581
+ for (const name of LOCK_FILES)
1582
+ addFile(files, `${prefix}:${name}`, path3.join(root, name));
1583
+ addFile(files, `${prefix}:node_modules/.package-lock.json`, path3.join(root, "node_modules", ".package-lock.json"));
1584
+ }
1585
+ const frameworkRoot2 = path3.resolve(__PNEXT_PACKAGE_ROOT__ + "/src/cli/build", "..", "..");
1586
+ addFile(files, "framework:package.json", path3.join(frameworkRoot2, "package.json"));
1587
+ for (const name of LOCK_FILES) {
1588
+ addFile(files, `framework:${name}`, path3.join(frameworkRoot2, name));
1589
+ addFile(files, `framework-workspace:${name}`, path3.join(frameworkRoot2, "..", name));
1590
+ }
1591
+ const entries = await Promise.all([...files].map(async ([key, file]) => {
1592
+ const stats = await lstat(file).catch(() => {
1593
+ return;
1594
+ });
1595
+ if (!stats?.isFile() && !stats?.isSymbolicLink())
1596
+ return;
1597
+ const old = previous?.[key];
1598
+ if (old?.[0] === stats.mtimeMs && old[1] === stats.size)
1599
+ return [key, old];
1600
+ const contents = stats.isSymbolicLink() ? Buffer.from(`link:${await readlink(file)}`) : await readFile2(file);
1601
+ return [key, [stats.mtimeMs, stats.size, contentHash(contents)]];
1602
+ }));
1603
+ return Object.fromEntries(entries.filter((entry) => Boolean(entry)));
1604
+ }
1605
+ async function collectModuleGraphInputs(config, files) {
1606
+ let parsed;
1607
+ try {
1608
+ parsed = JSON.parse(await readFile2(path3.join(config.outPath, "cache", "server", "graph.json"), "utf8"));
1609
+ } catch {
1610
+ return;
1611
+ }
1612
+ const frameworkRoot2 = path3.resolve(__PNEXT_PACKAGE_ROOT__ + "/src/cli/build", "..", "..");
1613
+ for (const source of Object.keys(parsed.files ?? {})) {
1614
+ const value = source.slice(2).split("/").join(path3.sep);
1615
+ const file = source.startsWith("w:") ? path3.resolve(config.workspaceRoot, value) : source.startsWith("f:") ? path3.resolve(frameworkRoot2, value) : source.startsWith("a:") ? value : undefined;
1616
+ if (file)
1617
+ addFile(files, `module:${source}`, file);
1618
+ }
1619
+ }
1620
+ async function collectTree(root, prefix, files, outPath, dir = root) {
1621
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
1622
+ await Promise.all(entries.map(async (entry) => {
1623
+ const file = path3.join(dir, entry.name);
1624
+ if (file === outPath || file.startsWith(`${outPath}${path3.sep}`))
1625
+ return;
1626
+ if (entry.isDirectory()) {
1627
+ if (!SKIP_INPUT_DIRS.has(entry.name))
1628
+ await collectTree(root, prefix, files, outPath, file);
1629
+ return;
1630
+ }
1631
+ if (!entry.isFile() && !entry.isSymbolicLink())
1632
+ return;
1633
+ const relative = path3.relative(root, file);
1634
+ if (SKIP_INPUT_FILE.test(entry.name) || !relative.includes(path3.sep) && /\.html?$/i.test(entry.name)) {
1635
+ return;
1636
+ }
1637
+ addFile(files, `${prefix}:${toPosix(relative)}`, file);
1638
+ }));
1639
+ }
1640
+ function addFile(files, key, file) {
1641
+ if (existsSync3(file))
1642
+ files.set(key, file);
1643
+ }
1644
+ async function outputSnapshot(outPath) {
1645
+ const files = new Map;
1646
+ const entries = await readdir(outPath, { withFileTypes: true }).catch(() => []);
1647
+ await Promise.all(entries.map(async (entry) => {
1648
+ if (entry.name === "cache" || entry.name === "dev")
1649
+ return;
1650
+ const file = path3.join(outPath, entry.name);
1651
+ if (entry.isDirectory())
1652
+ await collectOutputTree(outPath, file, files);
1653
+ else if (entry.isFile() || entry.isSymbolicLink()) {
1654
+ files.set(toPosix(entry.name), file);
1655
+ }
1656
+ }));
1657
+ const hash = createHash("sha256");
1658
+ const hashes = {};
1659
+ for (const [name, file] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
1660
+ const stats = await lstat(file);
1661
+ const contents = stats.isSymbolicLink() ? Buffer.from(`link:${await readlink(file)}`) : await readFile2(file);
1662
+ const contentsHash = contentHash(contents);
1663
+ hashes[name] = contentsHash;
1664
+ hash.update(`${name}\x00${contentsHash}\x00`);
1665
+ }
1666
+ return { hash: hash.digest("hex"), files: hashes };
1667
+ }
1668
+ function changedFiles(before, after) {
1669
+ return [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((file) => before[file] !== after[file]);
1670
+ }
1671
+ async function collectOutputTree(root, dir, files) {
1672
+ const entries = await readdir(dir, { withFileTypes: true });
1673
+ await Promise.all(entries.map(async (entry) => {
1674
+ const file = path3.join(dir, entry.name);
1675
+ if (entry.isDirectory())
1676
+ await collectOutputTree(root, file, files);
1677
+ else if (entry.isFile() || entry.isSymbolicLink()) {
1678
+ files.set(toPosix(path3.relative(root, file)), file);
1679
+ }
1680
+ }));
1681
+ }
1682
+ function contentHash(contents) {
1683
+ return createHash("sha256").update(contents).digest("hex");
1684
+ }
1685
+ function toPosix(file) {
1686
+ return path3.sep === "/" ? file : file.split(path3.sep).join("/");
1687
+ }
1688
+
1689
+ // src/cli/serve/entry.ts
1690
+ import { readFileSync as readFileSync3 } from "fs";
1691
+ import { mkdir as mkdir3, writeFile as writeFile2 } from "fs/promises";
1692
+ import path4 from "path";
1693
+ var frameworkRoot2 = path4.resolve(__PNEXT_PACKAGE_ROOT__ + "/src/cli/serve", "..", "..", "..");
1694
+ function frameworkVersion() {
1695
+ try {
1696
+ const pkg = readFileSync3(path4.join(frameworkRoot2, "package.json"), "utf8");
1697
+ return JSON.parse(pkg).version ?? "0";
1698
+ } catch {
1699
+ return "0";
1700
+ }
1701
+ }
1702
+ function serverEntryDir(outPath) {
1703
+ const generation = frameworkFingerprint(path4.join(outPath, "cache", "server"));
1704
+ return path4.join(outPath, "server", `bundle-${frameworkVersion()}-${generation}`);
1705
+ }
1706
+ async function emitServerEntry(outPath) {
1707
+ const start = await Bun.file(path4.join(__PNEXT_PACKAGE_ROOT__ + "/src/cli/serve", "..", "start.ts")).text();
1708
+ const names = new Bun.Transpiler({ loader: "ts" }).scan(start).exports;
1709
+ const dir = serverEntryDir(outPath);
1710
+ const target = readPrebundleStamp(frameworkRoot2, frameworkFingerprint()) ? "../dist/server/cli/start.js" : "./cli/start.ts";
1711
+ await mkdir3(dir, { recursive: true });
1712
+ await writeFile2(path4.join(dir, "entry.js"), `const pnext = await import(new URL('${target}', import.meta.resolve('@wular/pnext')).href)
1713
+ ` + `export const { ${names.join(", ")} } = pnext
1714
+ `);
1715
+ }
1716
+
1717
+ // src/cli/build.ts
1718
+ function nextCompatEnabled2(config) {
1719
+ return getCompatModeExtensions().nextEnabled(config);
1720
+ }
1721
+ function reactCompatEnabled(config) {
1722
+ return getCompatModeExtensions().reactEnabled(config);
1723
+ }
1724
+ function buildCompat() {
1725
+ return getBuildExtensions().compat;
1726
+ }
1727
+ async function buildProject(root, options = {}) {
1728
+ clearBuildParallelPhases();
1729
+ resetModuleGraphFailure();
1730
+ beginSourceScope();
1731
+ const restoreSpecifiersManifest = setEmitCompiledSpecifiersManifest(options.adapter === "vercel");
1732
+ const restoreReleaseCompile = setReleaseCompile(true);
1733
+ const lifecycle = {};
1734
+ try {
1735
+ return await runBuild(root, options, lifecycle);
1736
+ } catch (error) {
1737
+ const phaseError = buildParallelPhaseError();
1738
+ throw phaseError ?? error;
1739
+ } finally {
1740
+ lifecycle.warm?.kill();
1741
+ endSourceScope();
1742
+ restoreSpecifiersManifest();
1743
+ restoreReleaseCompile();
1744
+ flushDevModuleCaches();
1745
+ }
1746
+ }
1747
+ async function runBuild(root, options, lifecycle) {
1748
+ const verbose = options.verbose ?? false;
1749
+ const log = createVerboseLogger(verbose, "build");
1750
+ const startedAt = performance.now();
1751
+ console.log(`\u26A1 ${bold("pnext")} ${dim(`\u2014 Creating an optimized production build ...
1752
+ `)}`);
1753
+ const config = await loadConfig(root);
1754
+ const buildCache = lookupBuildCache(config, options);
1755
+ await bootstrapCompat(config);
1756
+ log.log(`config loaded \u2014 out ${path5.relative(config.root, config.outPath) || "."}`);
1757
+ runInitHooks(config, { build: true });
1758
+ const cached = await buildCache;
1759
+ log.log(`build cache ${cached.reason ?? "disabled"}`);
1760
+ if (cached.manifest) {
1761
+ printBuildSummary(config, cached.manifest.routes, cached.manifest.staticFiles ?? {}, performance.now() - startedAt, Boolean(cached.manifest.proxyModule));
1762
+ return cached.manifest;
1763
+ }
1764
+ warmCssPipeline(config);
1765
+ const warmMode = options.adapter === "vercel" ? "full" : "compile";
1766
+ const warm = startWarmChild(config, warmMode);
1767
+ lifecycle.warm = warm;
1768
+ const publicFiles = await log.step("prepare output directory", async () => {
1769
+ await ensureEmptyDir(config.outPath, [devOutSegment, "pnext-pages-compat"]);
1770
+ return copyPublicDir(config.publicPath, path5.join(config.outPath, "public"));
1771
+ });
1772
+ const documentCss = Promise.resolve().then(() => buildGlobalCss(config, { verbose })).then(() => buildNotFoundCss(config, { verbose }));
1773
+ documentCss.catch(() => {
1774
+ return;
1775
+ });
1776
+ const partytownLib = log.step("partytown lib", () => copyPartytownLib(config));
1777
+ partytownLib.catch(() => {
1778
+ return;
1779
+ });
1780
+ let routes = await log.step("scan routes", () => scanRoutes(config.appPath, config.workspaceRoot));
1781
+ log.log(`found ${routes.length} route${routes.length === 1 ? "" : "s"}`);
1782
+ if (options.debugBuildPaths) {
1783
+ routes = filterDebugBuildRoutes(config.root, routes, options.debugBuildPaths);
1784
+ log.log(`--debug-build-paths ${options.debugBuildPaths} \u2014 ${routes.length} route${routes.length === 1 ? "" : "s"} kept`);
1785
+ }
1786
+ warm.prewarm(routes.filter((route) => route.kind === "page").map((route) => route.file));
1787
+ const buildState = { actions: [] };
1788
+ const stepContext = { config, routes, manifest: buildState, log };
1789
+ const { steps } = getBuildExtensions();
1790
+ const earlySteps = runBuildSteps(steps.filter((step) => step.early), stepContext);
1791
+ earlySteps.catch(() => {
1792
+ return;
1793
+ });
1794
+ const clientSources = startClientSources(config);
1795
+ await log.step("scan route facts", async () => materializeRouteFacts(routes, (route) => clientSources.warmRoutes([route])));
1796
+ assertNoServerActionsWithoutCompat(routes, nextCompatEnabled2(config), config.root);
1797
+ setRequestRuntime({ config, routes, dev: false });
1798
+ prepareRouteCssChunks(routes);
1799
+ const routeStylesheets = buildRouteStylesheets(config, routes.filter((route) => route.kind !== "handler" && !route.dynamicErrorApi), documentCss, { verbose });
1800
+ const flatExportLayout = nextCompatEnabled2(config) && buildCompat().nextOutputExport() && config.trailingSlash !== true;
1801
+ const proxyBuild = log.step("proxy module", () => buildProxyModule(config));
1802
+ proxyBuild.catch(() => {
1803
+ return;
1804
+ });
1805
+ await runBuildSteps(steps.filter((step) => !step.early && step.gate), stepContext);
1806
+ const staticFiles = {};
1807
+ const staticMetadata = (async () => {
1808
+ const files = await log.step("discover static metadata files", () => Promise.resolve(discoverStaticMetadataFiles(config.appPath)));
1809
+ await log.step("static metadata files", () => copyStaticMetadataFiles(config, staticFiles, files));
1810
+ return files;
1811
+ })();
1812
+ staticMetadata.catch(() => {
1813
+ return;
1814
+ });
1815
+ await earlySteps;
1816
+ const deferredSteps = buildState.deferred ?? Promise.resolve();
1817
+ deferredSteps.catch(() => {
1818
+ return;
1819
+ });
1820
+ const staticMetadataFiles = await staticMetadata;
1821
+ const metadataWarnings = nextCompatEnabled2(config) ? log.step("next metadata warnings", () => buildCompat().warnMetadataIssues({
1822
+ appPath: config.appPath,
1823
+ routes,
1824
+ staticMetadataFiles
1825
+ })) : undefined;
1826
+ metadataWarnings?.catch(() => {
1827
+ return;
1828
+ });
1829
+ const moduleMetadata = log.step("core module metadata", () => collectStaticModuleMetadata(config, routes));
1830
+ moduleMetadata.catch(() => {
1831
+ return;
1832
+ });
1833
+ const actionSources = buildState.actionSources ?? buildState.actions.map((a) => a.sourceKey);
1834
+ const actionFiles = new Set(actionSources.map((source) => realFilePath(path5.resolve(config.root, source))));
1835
+ const actionImporters = new Set((buildState.actionImporters ?? []).map(realFilePath));
1836
+ const realFiles = new Map;
1837
+ const reachesAction = (file) => {
1838
+ let real = realFiles.get(file);
1839
+ if (real === undefined)
1840
+ realFiles.set(file, real = realFilePath(file));
1841
+ return actionFiles.has(real) || actionImporters.has(real);
1842
+ };
1843
+ for (const route of routes) {
1844
+ if (route.kind === "page" && (actionFiles.size > 0 || actionImporters.size > 0) && route.sourceFiles.some(reachesAction)) {
1845
+ addClientEntryReason(route, "actions");
1846
+ }
1847
+ }
1848
+ const clientRoutes = routes.filter((route) => route.kind !== "handler" && (route.client || route.clientReferences.length > 0 || route.needsRouterEntry));
1849
+ for (const route of clientRoutes)
1850
+ route.clientEntry = `assets/${clientEntryName(route)}.js`;
1851
+ const clientBundles = log.step(`client bundles (${clientRoutes.length} route${clientRoutes.length === 1 ? "" : "s"})`, () => buildClientEntries({
1852
+ config,
1853
+ routes: clientRoutes,
1854
+ outDir: path5.join(config.outPath, "public", "assets"),
1855
+ verbose,
1856
+ hasServerActions: actionSources.length > 0,
1857
+ pipeline: clientSources
1858
+ }));
1859
+ clientBundles.catch(() => {
1860
+ return;
1861
+ });
1862
+ const notFoundDocuments = clientBundles.then(async () => renderNotFoundDocuments({
1863
+ config,
1864
+ log,
1865
+ skip: options.buildMode === "compile",
1866
+ documentCss,
1867
+ staticMetadataFiles,
1868
+ staticModuleMetadata: await moduleMetadata
1869
+ }));
1870
+ notFoundDocuments.catch(() => {
1871
+ return;
1872
+ });
1873
+ const remainingSteps = runBuildSteps(steps.filter((step) => !step.early && !step.gate), stepContext).then(() => log.step("typegen", () => writeTypegen(config, routes)));
1874
+ remainingSteps.catch(() => {
1875
+ return;
1876
+ });
1877
+ await remainingSteps;
1878
+ const staticModuleMetadata = await moduleMetadata;
1879
+ await clientBundles;
1880
+ const proxyModule = await proxyBuild;
1881
+ await partytownLib;
1882
+ await emitStaticClientChunks(config, path5.join(config.outPath, "public", "assets"));
1883
+ if (verbose) {
1884
+ const sources = sourceCacheStats();
1885
+ log.log(`source cache \u2014 ${sources.reads} reads, ${sources.hits} shared, ${sources.files} files \xB7 parses ${JSON.stringify(scanFactsStats())}`);
1886
+ }
1887
+ await metadataWarnings;
1888
+ let hadAfterPrerenderError = false;
1889
+ let hadDynamicErrorFailure = false;
1890
+ const descendantHandlerIds = collectDescendantHandlerIds(routes);
1891
+ const isCompile = options.buildMode === "compile";
1892
+ const isGenerate = options.buildMode === "generate";
1893
+ const debugPrerender = options.debugPrerender ?? false;
1894
+ buildCompat().recordBuildFlags(config.outPath, debugPrerender);
1895
+ const generateRouteLines = [];
1896
+ const partialPrerenders = new Set;
1897
+ const generateFailures = [];
1898
+ if (isGenerate)
1899
+ console.log(" Collecting page data ...");
1900
+ await documentCss;
1901
+ for (const route of routes) {
1902
+ if (route.dynamicErrorApi) {
1903
+ console.error(`Error: Route ${toNextRoutePattern(route.route || "/")} with \`dynamic = "error"\` ` + `couldn't be rendered statically because it used ${route.dynamicErrorApi}. ` + `See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`);
1904
+ hadDynamicErrorFailure = true;
1905
+ continue;
1906
+ }
1907
+ if (route.kind === "handler") {
1908
+ if (isCompile)
1909
+ continue;
1910
+ if (!await staticRouteHandlerCandidate(route))
1911
+ continue;
1912
+ const dynamicUsage = await staticHandlerDynamicUsage(route);
1913
+ if (dynamicUsage) {
1914
+ console.log(`Caught Error: Dynamic server usage: Route ${route.route || "/"} couldn't be rendered statically because it used \`${dynamicUsage}\`.`);
1915
+ continue;
1916
+ }
1917
+ try {
1918
+ Object.assign(staticFiles, await log.step(`route handler ${route.route}`, () => buildStaticRouteHandler(config, route, {
1919
+ skipPhysicalWrite: descendantHandlerIds.has(route.id)
1920
+ })));
1921
+ } catch (error) {
1922
+ rethrowIfProgrammingError(error);
1923
+ if (isAfterPrerenderError(error))
1924
+ hadAfterPrerenderError = true;
1925
+ warnSkippedStatic(route.route, error instanceof Error ? error.message : String(error));
1926
+ }
1927
+ continue;
1928
+ }
1929
+ await routeStylesheets.get(route)?.();
1930
+ if (isCompile)
1931
+ continue;
1932
+ if (isGenerate && cacheComponents() && !route.client && !route.interception) {
1933
+ const diagnosticRoute = toNextRoutePattern(route.route || "/");
1934
+ const diagnostic = buildCompat().diagnoseCacheComponentsPrerender({
1935
+ route: diagnosticRoute,
1936
+ pageFile: route.file,
1937
+ appPath: config.appPath,
1938
+ debugPrerender
1939
+ });
1940
+ if (diagnostic) {
1941
+ console.error(diagnostic);
1942
+ generateFailures.push({
1943
+ route: diagnosticRoute,
1944
+ omitErrorLine: buildCompat().diagnosticLeadsWithErrorLine(diagnostic)
1945
+ });
1946
+ continue;
1947
+ }
1948
+ }
1949
+ if (route.ppr) {
1950
+ await log.step(`ppr shell ${route.route}`, () => buildPprShell(config, route));
1951
+ continue;
1952
+ }
1953
+ if (cacheComponents() && !route.interception && (!route.client || route.params.length === 0 && !route.catchAll)) {
1954
+ const built = await log.step(`cache-components shell ${route.route}`, () => buildCacheComponentsShell(config, route));
1955
+ if (built) {
1956
+ const paramFallback = (route.params.length > 0 || Boolean(route.catchAll)) && !route.hasStaticParams;
1957
+ if (paramFallback || (route.pprHoles?.length ?? 0) > 0 || route.pprMetadata) {
1958
+ partialPrerenders.add(route.id);
1959
+ }
1960
+ if (isGenerate)
1961
+ generateRouteLines.push(` \u25D0 ${route.route || "/"}`);
1962
+ continue;
1963
+ }
1964
+ }
1965
+ if (cacheComponents() && route.client && (route.params.length > 0 || route.catchAll))
1966
+ continue;
1967
+ const segmentConfig = route.segmentConfig;
1968
+ const forceStatic = segmentConfig?.dynamic === "force-static";
1969
+ if (forceStatic && segmentConfig?.runtime === "edge") {
1970
+ console.warn(`Page "${route.route}" is using runtime = 'edge' which is currently incompatible with dynamic = 'force-static'. Please remove either "runtime" or "force-static" for correct behavior`);
1971
+ }
1972
+ const configForcesDynamic = segmentConfig?.dynamic === "force-dynamic" || segmentConfig?.revalidate === 0 || segmentConfig?.fetchCache === "force-no-store" || segmentConfig?.runtime === "edge" && !forceStatic;
1973
+ let staticParams = null;
1974
+ if (!configForcesDynamic && route.hasStaticParams) {
1975
+ try {
1976
+ staticParams = await log.step(`static params ${route.route}`, () => getRenderExtensions().collectRenderMeta(() => staticParamsFor(config, route), {
1977
+ route: route.route,
1978
+ prerender: true
1979
+ }).then((result) => result.value));
1980
+ } catch (error) {
1981
+ rethrowIfProgrammingError(error);
1982
+ if (!isAfterPrerenderError(error))
1983
+ throw error;
1984
+ console.error(`Failed to collect page data for ${toNextRoutePattern(route.route)}`);
1985
+ console.error(error instanceof Error ? error.stack ?? error.message : String(error));
1986
+ hadAfterPrerenderError = true;
1987
+ continue;
1988
+ }
1989
+ }
1990
+ const validateUnstableCacheScope = !configForcesDynamic && route.usesRequest && !forceStatic && await usesUnstableCache(route);
1991
+ const paramSets = staticParams ? staticParams.paths : validateUnstableCacheScope ? [{}] : configForcesDynamic || route.usesRequest && !forceStatic ? [] : route.mode === "static" && route.params.length === 0 && !route.catchAll ? [{}] : [];
1992
+ if (staticParams)
1993
+ route.prerenderedParams = staticParams.allSets;
1994
+ if (process.env.NEXT_DEBUG_BUILD && paramSets.length === 0 && !staticParams && !configForcesDynamic && route.usesRequest && !forceStatic && route.params.length === 0 && !route.catchAll) {
1995
+ logStaticBailout(route.route || "/", await requestApiBailoutReason(route));
1996
+ }
1997
+ if (paramSets.length === 0) {
1998
+ if (!configForcesDynamic && !forceStatic && route.usesRequest && route.params.length === 0 && !route.catchAll && await schedulesDeferredWork(route)) {
1999
+ await probeDeferredDynamicUsage(config, route, staticMetadataFiles, staticModuleMetadata);
2000
+ }
2001
+ continue;
2002
+ }
2003
+ if (!forceStatic && await needsRequestOriginForMetadataImages(config.appPath, route))
2004
+ continue;
2005
+ await log.step(`prerender ${route.route} (${paramSets.length} page${paramSets.length === 1 ? "" : "s"})`, async () => {
2006
+ for (const rawParams of paramSets) {
2007
+ const params = encodeStaticRouteParams(rawParams);
2008
+ const routePath = fillRoutePath(route.route, rawParams);
2009
+ const file = staticHtmlPath(config.outPath, routePath, flatExportLayout);
2010
+ const collision = staticOutputCollision(config.outPath, file);
2011
+ if (collision) {
2012
+ warnSkippedStatic(routePath, collision);
2013
+ continue;
2014
+ }
2015
+ const url = new URL(`http://pnext.local${routePath}`);
2016
+ try {
2017
+ let cacheLife;
2018
+ let fontLinkHeader;
2019
+ let prerenderVary;
2020
+ const rendered = await runWithWorkUnit("render", async () => {
2021
+ const tracked = await buildCompat().withVaryParamsTracking(() => getRenderExtensions().collectRenderMeta(() => runWithNextBuildPhase(() => withRouteRuntime(route.segmentConfig?.runtime, () => renderPageWithStatus({
2022
+ config,
2023
+ route,
2024
+ params,
2025
+ url,
2026
+ ...route.usesRequest ? { request: new Request(url) } : {},
2027
+ staticMetadataFiles,
2028
+ staticModuleMetadata
2029
+ }))), {
2030
+ fetchCache: segmentConfig?.fetchCache,
2031
+ route: routePath || "/",
2032
+ prerender: true
2033
+ }));
2034
+ const result = tracked.value;
2035
+ prerenderVary = tracked.vary;
2036
+ cacheLife = buildCompat().takeCacheLifeStash();
2037
+ fontLinkHeader = buildCompat().takeFontLinkHeader();
2038
+ return result;
2039
+ });
2040
+ const optedStatic = forceStatic || typeof segmentConfig?.revalidate === "number" || segmentConfig?.revalidate === false;
2041
+ if (rendered.noStore && !optedStatic) {
2042
+ if (process.env.NEXT_DEBUG_BUILD)
2043
+ logStaticBailout(routePath || "/", "no-store fetch");
2044
+ continue;
2045
+ }
2046
+ await writeText(file, rendered.value.html);
2047
+ recordPrerenderVary(route, routePath || "/", prerenderVary);
2048
+ const routeLine = `${dim(" \u25CB")} ${routePath || "/"}`;
2049
+ if (isGenerate)
2050
+ generateRouteLines.push(routeLine);
2051
+ else
2052
+ console.log(routeLine);
2053
+ await emitConcreteNextPageArtifacts(config, route, routePath || "/", {
2054
+ html: rendered.value.html,
2055
+ status: rendered.value.status
2056
+ });
2057
+ const relative = toPosixPath(path5.relative(path5.join(config.outPath, "public"), file));
2058
+ const revalidateSeconds = combineRevalidate(segmentConfig?.revalidate, rendered.revalidateSeconds);
2059
+ const defaultExpireTime = buildCompat().defaultExpireTimeSeconds();
2060
+ const effectiveCacheLife = cacheLife ?? (rendered.expireSeconds !== undefined || rendered.staleSeconds !== undefined ? {
2061
+ ...revalidateSeconds !== undefined ? { revalidateSeconds } : {},
2062
+ ...rendered.expireSeconds !== undefined ? { expireSeconds: rendered.expireSeconds } : {},
2063
+ ...rendered.staleSeconds !== undefined ? { staleSeconds: rendered.staleSeconds } : {}
2064
+ } : revalidateSeconds !== undefined && defaultExpireTime !== undefined ? {
2065
+ revalidateSeconds,
2066
+ expireSeconds: defaultExpireTime
2067
+ } : undefined);
2068
+ const cacheLifeHeaders = cacheLifeResponseHeaders(effectiveCacheLife);
2069
+ const headers = [
2070
+ ...rendered.value.location ? [["location", rendered.value.location]] : [],
2071
+ ...fontLinkHeader ? [["link", fontLinkHeader]] : [],
2072
+ ...cacheLifeHeaders
2073
+ ];
2074
+ staticFiles[relative] = {
2075
+ status: rendered.value.status,
2076
+ headers,
2077
+ routeId: route.id,
2078
+ kind: "page",
2079
+ ...revalidateSeconds !== undefined ? { revalidateSeconds } : {},
2080
+ ...effectiveCacheLife?.expireSeconds !== undefined ? { expireSeconds: effectiveCacheLife.expireSeconds } : {},
2081
+ ...effectiveCacheLife?.staleSeconds !== undefined ? { staleSeconds: effectiveCacheLife.staleSeconds } : {},
2082
+ ...rendered.tags.length > 0 ? { tags: rendered.tags } : {}
2083
+ };
2084
+ } catch (error) {
2085
+ rethrowIfProgrammingError(error);
2086
+ if (isAfterPrerenderError(error))
2087
+ hadAfterPrerenderError = true;
2088
+ warnSkippedStatic(routePath, error instanceof Error ? error.message : String(error));
2089
+ }
2090
+ }
2091
+ });
2092
+ }
2093
+ if (isGenerate && generateFailures.length > 0) {
2094
+ for (const failed of generateFailures) {
2095
+ console.error(buildCompat().prerenderFailureFooter(failed.route, debugPrerender, failed.omitErrorLine));
2096
+ }
2097
+ console.error("Next.js build worker exited with code: 1 and signal: null");
2098
+ process.exit(1);
2099
+ }
2100
+ if (isGenerate) {
2101
+ console.log(`
2102
+ Route (app)`);
2103
+ for (const line of generateRouteLines)
2104
+ console.log(line);
2105
+ }
2106
+ throwIfModuleGraphFailed();
2107
+ if (hadAfterPrerenderError) {
2108
+ throw new Error("Build failed because an error was thrown inside `after()` while prerendering.");
2109
+ }
2110
+ if (hadDynamicErrorFailure) {
2111
+ throw new Error('Build failed because a route with `dynamic = "error"` read dynamic data during prerendering.');
2112
+ }
2113
+ const interceptionPrerenders = isCompile ? new Map : await logInterceptionPrerenders(config, routes);
2114
+ const fallback404 = await notFoundDocuments;
2115
+ await emitNextNotFoundArtifacts(config, fallback404);
2116
+ await emitProxyServerArtifacts(config, proxyModule);
2117
+ if (config.compat?.next) {
2118
+ const sourceApp = path5.join(config.appPath, "..", "source-app");
2119
+ const layoutRoot = existsSync4(sourceApp) ? sourceApp : config.appPath;
2120
+ const hasTopLevelRootLayout = ["tsx", "ts", "jsx", "js"].some((ext) => existsSync4(path5.join(layoutRoot, `layout.${ext}`)));
2121
+ const pseudos = hasTopLevelRootLayout ? ["_not-found.html", "_global-error.html"] : ["_not-found.html"];
2122
+ for (const pseudo of pseudos) {
2123
+ if (!(pseudo in staticFiles)) {
2124
+ staticFiles[pseudo] = { status: 200, headers: [], kind: "page" };
2125
+ }
2126
+ }
2127
+ }
2128
+ await deferredSteps;
2129
+ const actions = buildState.actions;
2130
+ const publicAssets = publicFiles.filter((relative) => immutableAssetPath(relative));
2131
+ const manifest = {
2132
+ version: 0,
2133
+ root: config.root,
2134
+ appDir: config.appPath,
2135
+ outDir: config.outPath,
2136
+ routes,
2137
+ staticFiles,
2138
+ assetNames: emittedAssetNames(config.outPath),
2139
+ ...publicAssets.length > 0 ? { publicAssets } : {},
2140
+ staticMetadataFiles,
2141
+ ...Object.keys(staticModuleMetadata).length > 0 ? { staticModuleMetadata } : {},
2142
+ ...!config.compat?.next ? {
2143
+ staticRouteMetadata: await log.step("core route metadata", () => collectStaticRouteMetadata(config, routes, staticMetadataFiles))
2144
+ } : {},
2145
+ ...proxyModule ? { proxyModule } : {},
2146
+ ...actions.length > 0 ? { actions } : {}
2147
+ };
2148
+ await writeBuildManifest(config.outPath, manifest);
2149
+ log.log(`wrote manifest.json (${routes.length} route${routes.length === 1 ? "" : "s"})`);
2150
+ await log.step("server entry", () => emitServerEntry(config.outPath));
2151
+ for (const hook of getBuildExtensions().completeHooks) {
2152
+ await hook({ config, manifest, log });
2153
+ }
2154
+ if (options.adapter === "vercel")
2155
+ await log.step("vercel adapter output", () => writeVercelOutput(config, manifest, { verbose, warm }));
2156
+ else {
2157
+ await log.step("warm module cache", () => warm.finish(log, undefined, {
2158
+ globalCss: globalCssSources(config),
2159
+ clientReferences: [...compiledClientReferenceFiles()]
2160
+ }));
2161
+ }
2162
+ if (!existsSync4(buildIndexFile(config.outPath))) {
2163
+ throw new Error("pnext build: the server compile did not complete (see the error above).");
2164
+ }
2165
+ throwIfModuleGraphFailed();
2166
+ const buildDurationMs = performance.now() - startedAt;
2167
+ const phases = await settleBuildParallelPhases();
2168
+ flushDevModuleCaches();
2169
+ await writeBuildCache(config, options, cached);
2170
+ printBuildSummary(config, routes, staticFiles, buildDurationMs, Boolean(proxyModule), interceptionPrerenders, partialPrerenders, phases);
2171
+ return manifest;
2172
+ }
2173
+ async function runBuildSteps(steps, ctx) {
2174
+ for (const [index, step] of steps.entries()) {
2175
+ await ctx.log.step(`build step ${step.name || index}`, () => step(ctx));
2176
+ }
2177
+ }
2178
+ async function settleBuildParallelPhases() {
2179
+ const phases = getBuildExtensions().parallelPhases;
2180
+ const timings = [];
2181
+ for (const phase of phases)
2182
+ timings.push({ name: phase.name, durationMs: await phase.run });
2183
+ return timings;
2184
+ }
2185
+ async function logInterceptionPrerenders(config, routes) {
2186
+ const prerenders = new Map;
2187
+ for (const route of routes) {
2188
+ if (route.kind !== "page" || !route.interception)
2189
+ continue;
2190
+ if (!routeFileExportsStaticParams(route.file))
2191
+ continue;
2192
+ let paths;
2193
+ try {
2194
+ const staticParams = await staticParamsFor(config, route);
2195
+ paths = staticParams.paths.map((params) => interceptionDisplayRoute(route, fillRoutePath(route.route, params)));
2196
+ } catch (error) {
2197
+ rethrowIfProgrammingError(error);
2198
+ warnSkippedStatic(route.route, error instanceof Error ? error.message : String(error));
2199
+ continue;
2200
+ }
2201
+ if (paths.length === 0)
2202
+ continue;
2203
+ prerenders.set(route.id, paths);
2204
+ for (const routePath of paths)
2205
+ console.log(`${dim(" \u25CB")} ${routePath}`);
2206
+ }
2207
+ return prerenders;
2208
+ }
2209
+ function routeFileExportsStaticParams(file) {
2210
+ if (!existsSync4(file))
2211
+ return false;
2212
+ const source = readTextSync(file);
2213
+ return /\bexport\s+(?:async\s+)?function\s+generateStaticParams\b/.test(source) || /\bexport\s+const\s+generateStaticParams\b/.test(source);
2214
+ }
2215
+ function interceptionDisplayRoute(route, filled) {
2216
+ const interception = route.interception;
2217
+ if (!interception)
2218
+ return route.route;
2219
+ const base = interception.base === "/" ? [] : interception.base.split("/").filter(Boolean);
2220
+ const levels = interceptionMarkerLevels(interception.marker);
2221
+ const target = (filled ?? toNextRoutePattern(route.route)).split("/").filter(Boolean);
2222
+ const cut = Number.isFinite(levels) ? Math.max(0, base.length - levels) : 0;
2223
+ const below = target.slice(cut);
2224
+ const segments = [...base, `${interception.marker}${below[0] ?? ""}`, ...below.slice(1)];
2225
+ return `/${segments.join("/")}`;
2226
+ }
2227
+ async function writeBuildManifest(outPath, manifest) {
2228
+ assertManifestServerArtifacts(outPath, manifest);
2229
+ const file = path5.join(outPath, "manifest.json");
2230
+ const temporary = path5.join(outPath, `.manifest-${process.pid}.tmp`);
2231
+ await writeFile3(temporary, serializeBuildManifest(manifest));
2232
+ await rename2(temporary, file);
2233
+ }
2234
+ function assertManifestServerArtifacts(outPath, manifest) {
2235
+ const artifacts = [
2236
+ ...manifest.proxyModule ? [manifest.proxyModule] : [],
2237
+ ...manifest.actions?.map((action) => action.modulePath) ?? []
2238
+ ];
2239
+ for (const artifact of artifacts) {
2240
+ const file = path5.resolve(outPath, artifact);
2241
+ if (file !== outPath && !file.startsWith(`${outPath}${path5.sep}`)) {
2242
+ throw new Error(`Build manifest server artifact escapes output directory: ${artifact}`);
2243
+ }
2244
+ if (!existsSync4(file)) {
2245
+ throw new Error(`Build manifest server artifact is missing: ${artifact}`);
2246
+ }
2247
+ }
2248
+ }
2249
+ function printBuildSummary(config, routes, staticFiles, durationMs, hasMiddleware = false, interceptionPrerenders = new Map, partialPrerenders = new Set, parallelPhases = []) {
2250
+ const pages = routes.filter((route) => route.kind !== "handler").length;
2251
+ const handlers = routes.length - pages;
2252
+ const parts = [`${pages} ${pages === 1 ? "page" : "pages"}`];
2253
+ if (handlers > 0)
2254
+ parts.push(`${handlers} ${handlers === 1 ? "route handler" : "route handlers"}`);
2255
+ const outDir = path5.relative(config.root, config.outPath) || ".";
2256
+ console.log("");
2257
+ console.log("Route (app)");
2258
+ const usedMarkers = new Set;
2259
+ for (const route of routes) {
2260
+ const intercepted = interceptionPrerenders.get(route.id);
2261
+ const marker = route.kind === "handler" ? Object.values(staticFiles).some((file) => file.routeId === route.id) ? "\u25CB" : "\u0192" : intercepted ? "\u25CF" : partialPrerenders.has(route.id) ? "\u25D0" : route.mode === "dynamic" && !route.hasStaticParams ? "\u0192" : route.hasStaticParams ? "\u25CF" : "\u25CB";
2262
+ const label = route.interception ? interceptionDisplayRoute(route) : route.route || "/";
2263
+ usedMarkers.add(marker);
2264
+ console.log(` ${marker} ${nextCompatEnabled2(config) ? toNextRoutePattern(label) : label}`);
2265
+ }
2266
+ for (const file of staticMetadataSummaryFiles(staticFiles)) {
2267
+ usedMarkers.add("\u25CB");
2268
+ console.log(` ${dim("\u25CB")} /${file}`);
2269
+ }
2270
+ if (hasMiddleware) {
2271
+ usedMarkers.add("\u0192");
2272
+ console.log("");
2273
+ console.log(` ${dim("\u0192")} Middleware`);
2274
+ }
2275
+ const legend = [
2276
+ ["\u25CB", "static"],
2277
+ ["\u25CF", "SSG"],
2278
+ ["\u25D0", "partial prerender"],
2279
+ ["\u0192", "dynamic"]
2280
+ ];
2281
+ const legendLine = legend.filter(([marker]) => usedMarkers.has(marker)).map(([marker, meaning]) => `${marker} ${meaning}`).join(" ");
2282
+ if (legendLine)
2283
+ console.log(`
2284
+ ${dim(legendLine)}`);
2285
+ console.log("");
2286
+ console.log(`${green("\u2713")} ${bold("Build complete")} ${dim(`in ${formatBuildDuration(durationMs)}`)}`);
2287
+ for (const phase of parallelPhases) {
2288
+ console.log(`${green("\u2713")} ${bold(`${phase.name} complete`)} ${dim(`in ${formatBuildDuration(phase.durationMs)}`)}`);
2289
+ }
2290
+ console.log(` ${dim(`${parts.join(", ")} \u2192 ${outDir}`)}`);
2291
+ console.log("");
2292
+ console.log(` Serve the production build: ${cyan("pnext start")}`);
2293
+ console.log(` Analyze the build: ${cyan("pnext analyze")}`);
2294
+ }
2295
+ function staticMetadataSummaryFiles(staticFiles) {
2296
+ return Object.entries(staticFiles).filter(([, metadata]) => metadata.headers.some(([name, value]) => name.toLowerCase() === "cache-control" && value === staticMetadataCacheControl)).map(([file]) => file).sort();
2297
+ }
2298
+ function formatBuildDuration(durationMs) {
2299
+ const totalSeconds = Math.max(0, durationMs) / 1000;
2300
+ if (totalSeconds < 60)
2301
+ return `${totalSeconds.toFixed(totalSeconds < 10 ? 2 : 1)}s`;
2302
+ const minutes = Math.floor(totalSeconds / 60);
2303
+ const seconds = Math.round(totalSeconds % 60);
2304
+ return `${minutes}m ${seconds}s`;
2305
+ }
2306
+ async function renderShellWithCacheMeta(config, route, render) {
2307
+ let linkHeader;
2308
+ const tracked = await buildCompat().withVaryParamsTracking(async () => runWithWorkUnit("render", async () => {
2309
+ const rendered = await getRenderExtensions().collectRenderMeta(() => runWithNextBuildPhase(render), {
2310
+ fetchCache: route.segmentConfig?.fetchCache,
2311
+ route: route.route || "/",
2312
+ prerender: true
2313
+ });
2314
+ linkHeader = buildCompat().takeFontLinkHeader();
2315
+ return rendered;
2316
+ }));
2317
+ const result = tracked.value;
2318
+ const cacheLife = result.revalidateSeconds !== undefined || result.expireSeconds !== undefined || result.staleSeconds !== undefined ? {
2319
+ ...result.revalidateSeconds !== undefined ? { revalidateSeconds: result.revalidateSeconds } : {},
2320
+ ...result.expireSeconds !== undefined ? { expireSeconds: result.expireSeconds } : {},
2321
+ ...result.staleSeconds !== undefined ? { staleSeconds: result.staleSeconds } : {}
2322
+ } : undefined;
2323
+ return {
2324
+ prebuilt: result.value,
2325
+ meta: {
2326
+ ...cacheLife ? { cacheLife } : {},
2327
+ tags: result.tags,
2328
+ ...linkHeader ? { linkHeader } : {}
2329
+ },
2330
+ vary: tracked.vary
2331
+ };
2332
+ }
2333
+ var DYNAMIC_EXPIRE_SECONDS = 300;
2334
+ function routeDeclaresShortLivedCache(route) {
2335
+ for (const file of route.sourceFiles) {
2336
+ if (!existsSync4(file))
2337
+ continue;
2338
+ const source = readTextSync(file);
2339
+ for (const literal of source.matchAll(/cacheLife\s*\(\s*\{[^}]*\bexpire\s*:\s*([^,}]+)/gs)) {
2340
+ const value = staticNumberExpression(literal[1]);
2341
+ if (value !== undefined && value < DYNAMIC_EXPIRE_SECONDS)
2342
+ return true;
2343
+ }
2344
+ for (const named of source.matchAll(/cacheLife\s*\(\s*['"]([^'"]+)['"]\s*\)/g)) {
2345
+ const expire = builtInCacheLifeExpire(named[1]);
2346
+ if (expire !== undefined && expire < DYNAMIC_EXPIRE_SECONDS)
2347
+ return true;
2348
+ }
2349
+ }
2350
+ return false;
2351
+ }
2352
+ async function renderPrefetchBody(config, route, render) {
2353
+ if (!routeDeclaresShortLivedCache(route))
2354
+ return;
2355
+ try {
2356
+ const { prebuilt, vary } = await renderShellWithCacheMeta(config, route, render);
2357
+ return prebuilt ? { prebuilt, vary } : undefined;
2358
+ } catch {
2359
+ return;
2360
+ } finally {
2361
+ abortActivePrerenderScopes();
2362
+ }
2363
+ }
2364
+ async function buildPprShell(config, route) {
2365
+ const url = new URL(`http://pnext.local${route.route}`);
2366
+ const { prebuilt, meta, vary } = await renderShellWithCacheMeta(config, route, () => renderPartialShell({ config, route, url }));
2367
+ if (!prebuilt) {
2368
+ route.ppr = false;
2369
+ return;
2370
+ }
2371
+ route.pprHoles = prebuilt.holes;
2372
+ route.pprMetadata = prebuilt.metadataDynamic || undefined;
2373
+ persistRouteCacheLife(route, meta.cacheLife);
2374
+ recordRouteCacheTags(route, meta.tags);
2375
+ if (meta.linkHeader)
2376
+ route.linkHeader = meta.linkHeader;
2377
+ const file = pprShellPath(config.outPath, route.id);
2378
+ await mkdir4(path5.dirname(file), { recursive: true });
2379
+ await writeText(file, prebuilt.shell);
2380
+ const prefetchBody = await renderPrefetchBody(config, route, () => renderPartialShell({ config, route, url, prefetchShell: true })) ?? { prebuilt, vary };
2381
+ await emitSegmentArtifacts(config, route, prefetchBody.prebuilt.shell, prefetchBody.prebuilt.holes.length > 0, meta, undefined, prefetchBody.vary, true);
2382
+ }
2383
+ function recordRouteCacheTags(route, tags) {
2384
+ if (tags.length === 0)
2385
+ return;
2386
+ route.cacheTags = [...new Set([...route.cacheTags ?? [], ...tags])];
2387
+ }
2388
+ function persistRouteCacheLife(route, life) {
2389
+ if (!life)
2390
+ return;
2391
+ route.cacheLife = {
2392
+ ...life.revalidateSeconds !== undefined ? { revalidateSeconds: life.revalidateSeconds } : {},
2393
+ ...life.expireSeconds !== undefined ? { expireSeconds: life.expireSeconds } : {},
2394
+ ...life.staleSeconds !== undefined ? { staleSeconds: life.staleSeconds } : {}
2395
+ };
2396
+ }
2397
+ async function emitSegmentArtifacts(config, route, body, postponed, cacheMeta, statusOverride, vary, fallbackParamsRender = false) {
2398
+ const isStatic = route.mode === "static" && !postponed;
2399
+ const compat = buildCompat();
2400
+ const staleTime = staleTimeFromRouteSources(route) ?? (isStatic ? compat.defaultStaticStaleTimeSeconds : compat.defaultDynamicStaleTimeSeconds);
2401
+ const bodySizeBytes = Buffer.byteLength(body);
2402
+ const tree = compat.buildRootTreePrefetch({
2403
+ pathname: route.route,
2404
+ isStatic,
2405
+ staleTimeSeconds: staleTime,
2406
+ routeId: route.id,
2407
+ bodySizeBytes,
2408
+ postponed,
2409
+ runtimePrefetch: route.segmentConfig?.prefetch === "allow-runtime",
2410
+ ...route.pprMetadata === true ? { headOutlined: true, .../[:*]/.test(route.route) ? { headFirst: true } : {} } : {}
2411
+ });
2412
+ const meta = compat.buildSegmentMeta({
2413
+ status: statusOverride ?? 200,
2414
+ staleTime,
2415
+ postponed,
2416
+ bodySizeBytes,
2417
+ prefetchHints: { [route.route]: tree.tree.prefetchHints },
2418
+ ...vary && buildVaryTrusted(route, vary, fallbackParamsRender) ? { vary } : {}
2419
+ });
2420
+ await mkdir4(compat.segmentDir(config.outPath, route.id), { recursive: true });
2421
+ await writeText(compat.treeSegmentFile(config.outPath, route.id), JSON.stringify(tree));
2422
+ await writeText(compat.bodySegmentFile(config.outPath, route.id), body);
2423
+ await writeText(compat.segmentMetaFile(config.outPath, route.id), JSON.stringify(meta));
2424
+ await emitNextSegmentArtifacts(config.root, route, body, compat.rootTreePrefetchText(tree, "flight"), meta, segmentMetaHeaders(cacheMeta));
2425
+ }
2426
+ function recordPrerenderVary(route, routePath, vary) {
2427
+ if (!vary || !buildVaryTrusted(route, vary, false))
2428
+ return;
2429
+ if (vary.params.length === 0 && !vary.search)
2430
+ return;
2431
+ route.prerenderVary ??= {};
2432
+ route.prerenderVary[routePath] = {
2433
+ vary: buildCompat().varyNamesFor(vary, "body"),
2434
+ layoutVary: buildCompat().varyNamesFor(vary, "layout"),
2435
+ pageVary: buildCompat().varyNamesFor(vary, "page")
2436
+ };
2437
+ }
2438
+ function buildVaryTrusted(route, vary, fallbackParamsRender) {
2439
+ if (vary.params.length > 0 || vary.search)
2440
+ return true;
2441
+ if (fallbackParamsRender)
2442
+ return true;
2443
+ return route.params.length === 0 && !route.catchAll;
2444
+ }
2445
+ function segmentMetaHeaders(cacheMeta) {
2446
+ const headers = {};
2447
+ if (!cacheMeta)
2448
+ return headers;
2449
+ for (const [key, value] of cacheLifeResponseHeaders(cacheMeta.cacheLife))
2450
+ headers[key] = value;
2451
+ if (cacheMeta.tags.length > 0)
2452
+ headers["x-next-cache-tags"] = cacheMeta.tags.join(",");
2453
+ return headers;
2454
+ }
2455
+ async function emitNextSegmentArtifacts(root, route, body, tree, meta, headers = {}) {
2456
+ const appPath = nextAppRoutePath(route.route);
2457
+ const appFile = path5.join(root, ".next", "server", "app", appPath);
2458
+ const segmentsDir = `${appFile}.segments`;
2459
+ const nextMeta = {
2460
+ status: meta.status,
2461
+ headers,
2462
+ staleTime: meta.staleTime,
2463
+ ...meta.postponed ? { postponed: "1" } : {},
2464
+ segmentPaths: meta.segmentPaths,
2465
+ ...meta.segmentSizes ? { segmentSizes: meta.segmentSizes } : {},
2466
+ ...meta.inlinedSegmentPaths ? { inlinedSegmentPaths: meta.inlinedSegmentPaths } : {},
2467
+ ...meta.prefetchHints ? { prefetchHints: meta.prefetchHints } : {}
2468
+ };
2469
+ await mkdir4(segmentsDir, { recursive: true });
2470
+ await writeText(`${appFile}.html`, meta.postponed ? body : `${body}
2471
+ </body></html>`);
2472
+ await writeText(`${appFile}.meta`, JSON.stringify(nextMeta));
2473
+ await writeText(path5.join(segmentsDir, "_tree.segment.rsc"), tree);
2474
+ await writeText(path5.join(segmentsDir, "_full.segment.rsc"), body);
2475
+ await writeText(path5.join(segmentsDir, "_index.segment.rsc"), body);
2476
+ const routeSegment = appPath === "index" ? "__PAGE__" : appPath;
2477
+ await writeNestedSegment(segmentsDir, `${routeSegment}.segment.rsc`, body);
2478
+ await writeNestedSegment(segmentsDir, path5.join(routeSegment, "__PAGE__.segment.rsc"), body);
2479
+ }
2480
+ async function emitConcreteNextPageArtifacts(config, route, routePath, rendered) {
2481
+ if (!config.compat?.next || !cacheComponents())
2482
+ return;
2483
+ const compat = buildCompat();
2484
+ const postponed = rendered.postponed ?? false;
2485
+ const bodySizeBytes = Buffer.byteLength(rendered.html);
2486
+ const staleTime = staleTimeFromRouteSources(route) ?? compat.defaultStaticStaleTimeSeconds;
2487
+ const tree = compat.buildRootTreePrefetch({
2488
+ pathname: routePath,
2489
+ isStatic: !postponed,
2490
+ staleTimeSeconds: staleTime,
2491
+ routeId: route.id,
2492
+ bodySizeBytes,
2493
+ postponed
2494
+ });
2495
+ const meta = compat.buildSegmentMeta({
2496
+ status: rendered.status,
2497
+ staleTime,
2498
+ postponed,
2499
+ bodySizeBytes
2500
+ });
2501
+ const appFile = path5.join(config.root, ".next", "server", "app", nextAppRoutePath(routePath));
2502
+ const segmentsDir = `${appFile}.segments`;
2503
+ await mkdir4(segmentsDir, { recursive: true });
2504
+ await writeText(`${appFile}.html`, rendered.html);
2505
+ await writeText(`${appFile}.meta`, JSON.stringify({
2506
+ status: meta.status,
2507
+ headers: {},
2508
+ staleTime: meta.staleTime,
2509
+ ...postponed ? { postponed: "1" } : {},
2510
+ segmentPaths: meta.segmentPaths,
2511
+ ...meta.segmentSizes ? { segmentSizes: meta.segmentSizes } : {}
2512
+ }));
2513
+ await writeText(path5.join(segmentsDir, "_tree.segment.rsc"), compat.rootTreePrefetchText(tree, "flight"));
2514
+ }
2515
+ function staleTimeFromRouteSources(route) {
2516
+ let found;
2517
+ for (const file of route.sourceFiles) {
2518
+ if (!existsSync4(file))
2519
+ continue;
2520
+ const source = readTextSync(file);
2521
+ for (const literal of source.matchAll(/cacheLife\s*\(\s*\{[^}]*\bstale\s*:\s*([^,}]+)/gs)) {
2522
+ const value = staticNumberExpression(literal[1]);
2523
+ if (value !== undefined)
2524
+ found = minDefined(found, value);
2525
+ }
2526
+ for (const named of source.matchAll(/cacheLife\s*\(\s*['"]([^'"]+)['"]\s*\)/g)) {
2527
+ const namedValue = builtInCacheLifeStale(named[1]);
2528
+ if (namedValue !== undefined)
2529
+ found = minDefined(found, namedValue);
2530
+ }
2531
+ }
2532
+ return found;
2533
+ }
2534
+ function readTextSync(file) {
2535
+ try {
2536
+ return existsSync4(file) && statSync2(file).isFile() ? readFileSync4(file, "utf8") : "";
2537
+ } catch {
2538
+ return "";
2539
+ }
2540
+ }
2541
+ function staticNumberExpression(expression) {
2542
+ const trimmed = expression.trim();
2543
+ if (/^\d+(?:\.\d+)?$/.test(trimmed))
2544
+ return Number(trimmed);
2545
+ const product = trimmed.split("*").map((part) => part.trim());
2546
+ if (product.length > 1 && product.every((part) => /^\d+(?:\.\d+)?$/.test(part))) {
2547
+ return product.reduce((value, part) => value * Number(part), 1);
2548
+ }
2549
+ return;
2550
+ }
2551
+ function builtInCacheLifeStale(profile) {
2552
+ switch (profile) {
2553
+ case "seconds":
2554
+ return;
2555
+ case "default":
2556
+ case "minutes":
2557
+ case "hours":
2558
+ case "days":
2559
+ case "weeks":
2560
+ case "max":
2561
+ return 300;
2562
+ default:
2563
+ return;
2564
+ }
2565
+ }
2566
+ function builtInCacheLifeExpire(profile) {
2567
+ switch (profile) {
2568
+ case "seconds":
2569
+ return 60;
2570
+ case "minutes":
2571
+ return 3600;
2572
+ case "hours":
2573
+ return 86400;
2574
+ case "days":
2575
+ return 604800;
2576
+ case "weeks":
2577
+ return 2592000;
2578
+ case "default":
2579
+ case "max":
2580
+ return 31536000;
2581
+ default:
2582
+ return;
2583
+ }
2584
+ }
2585
+ function minDefined(a, b) {
2586
+ if (a === undefined)
2587
+ return b;
2588
+ if (b === undefined)
2589
+ return a;
2590
+ return Math.min(a, b);
2591
+ }
2592
+ async function writeNestedSegment(root, relative, body) {
2593
+ const file = path5.join(root, relative);
2594
+ await mkdir4(path5.dirname(file), { recursive: true });
2595
+ await writeText(file, body);
2596
+ }
2597
+ function nextAppRoutePath(route) {
2598
+ return route.replace(/^\/+/, "") || "index";
2599
+ }
2600
+ function shellRendersContentOutsideHoles(shell) {
2601
+ const open = /<body[^>]*>/.exec(shell);
2602
+ if (!open)
2603
+ return false;
2604
+ const rest = shell.slice(open.index + open[0].length);
2605
+ const body = rest.split("</body>")[0] ?? "";
2606
+ const outside = stripBalanced(body, "pnext-suspense").replace(/<(script|template|style)[^>]*>[\s\S]*?<\/\1>/g, "").replace(/<!--[\s\S]*?-->/g, "");
2607
+ if (/<(img|svg|video|canvas|input)[\s>]/.test(outside))
2608
+ return true;
2609
+ return outside.replace(/<[^>]*>/g, "").trim().length > 0;
2610
+ }
2611
+ function shellHolesRenderFallbackContent(shell) {
2612
+ const open = /<body[^>]*>/.exec(shell);
2613
+ if (!open)
2614
+ return false;
2615
+ const body = (shell.slice(open.index + open[0].length).split("</body>")[0] ?? "").replace(/<(script|template|style)[^>]*>[\s\S]*?<\/\1>/g, "").replace(/<!--[\s\S]*?-->/g, "");
2616
+ const outside = stripBalanced(body, "pnext-suspense");
2617
+ const text = (h) => h.replace(/<[^>]*>/g, "").trim().length;
2618
+ const media = (h) => /<(img|svg|video|canvas|input)[\s>]/.test(h);
2619
+ return text(body) - text(outside) > 0 || media(body) && !media(outside);
2620
+ }
2621
+ function stripBalanced(html, tag) {
2622
+ const open = new RegExp(`<${tag}[\\s>]`, "g");
2623
+ const boundary = new RegExp(`<${tag}[\\s>]|</${tag}>`, "g");
2624
+ let out = "";
2625
+ let cursor = 0;
2626
+ for (let start = open.exec(html);start; start = open.exec(html)) {
2627
+ if (start.index < cursor)
2628
+ continue;
2629
+ out += html.slice(cursor, start.index);
2630
+ boundary.lastIndex = start.index + 1;
2631
+ let depth = 1;
2632
+ let end = html.length;
2633
+ for (let hit = boundary.exec(html);hit; hit = boundary.exec(html)) {
2634
+ depth += hit[0].startsWith("</") ? -1 : 1;
2635
+ if (depth === 0) {
2636
+ end = hit.index + hit[0].length;
2637
+ break;
2638
+ }
2639
+ }
2640
+ cursor = end;
2641
+ open.lastIndex = cursor;
2642
+ }
2643
+ return out + html.slice(cursor);
2644
+ }
2645
+ async function buildCacheComponentsShell(config, route) {
2646
+ const url = new URL(`http://pnext.local${route.route}`);
2647
+ const hasDynamicParams = route.params.length > 0 || Boolean(route.catchAll);
2648
+ beginShellSourceTracking();
2649
+ let renderResult;
2650
+ try {
2651
+ renderResult = await renderShellWithCacheMeta(config, route, () => hasDynamicParams ? renderFallbackShell({ config, route, url }) : renderPartialShell({ config, route, url }));
2652
+ } finally {
2653
+ abortActivePrerenderScopes();
2654
+ }
2655
+ const { prebuilt, meta } = renderResult;
2656
+ const shellSources = endShellSourceTracking();
2657
+ const baseShellIsEmpty = prebuilt === null || prebuilt.holes.length > 0 && !prebuilt.metadataDynamic && !shellSources.cacheIO && !shellSources.nonParamsRequest && !(meta.cacheLife === undefined && (shellRendersContentOutsideHoles(prebuilt.shell) || shellHolesRenderFallbackContent(prebuilt.shell))) && !(hasDynamicParams && routeSourcesUseRequestApi(config.root, route));
2658
+ if (!baseShellIsEmpty) {
2659
+ route.ppr = true;
2660
+ route.pprHoles = prebuilt.holes;
2661
+ route.pprMetadata = prebuilt.metadataDynamic || undefined;
2662
+ persistRouteCacheLife(route, meta.cacheLife);
2663
+ recordRouteCacheTags(route, meta.tags);
2664
+ if (meta.linkHeader)
2665
+ route.linkHeader = meta.linkHeader;
2666
+ const file = pprShellPath(config.outPath, route.id);
2667
+ await mkdir4(path5.dirname(file), { recursive: true });
2668
+ await writeText(file, prebuilt.shell);
2669
+ let fallbackStatus;
2670
+ if (!hasDynamicParams && routeSourcesUseHttpFallback(config.root, route)) {
2671
+ try {
2672
+ const probe = await runWithWorkUnit("render", () => getRenderExtensions().collectRenderMeta(() => runWithNextBuildPhase(() => renderPageWithStatus({ config, route, params: {}, url })), { route: route.route || "/", prerender: true }).then((result) => result.value));
2673
+ if (probe.status !== 200)
2674
+ fallbackStatus = probe.status;
2675
+ } catch {}
2676
+ }
2677
+ const prefetchBody = await renderPrefetchBody(config, route, () => hasDynamicParams ? renderFallbackShell({ config, route, url, prefetchShell: true }) : renderPartialShell({ config, route, url, prefetchShell: true })) ?? { prebuilt, vary: renderResult.vary };
2678
+ await emitSegmentArtifacts(config, route, prefetchBody.prebuilt.shell, prefetchBody.prebuilt.holes.length > 0, meta, fallbackStatus, prefetchBody.vary, true);
2679
+ if (hasDynamicParams && route.hasStaticParams) {
2680
+ await buildSubShells(config, route);
2681
+ }
2682
+ return true;
2683
+ }
2684
+ if (hasDynamicParams && route.hasStaticParams && (await hasPartialStaticPrefix(config, route) || cacheComponents() && routeSourcesUseRequestApi(config.root, route) && await hasFullStaticParamSet(config, route))) {
2685
+ route.ppr = true;
2686
+ route.pprMetadata = prebuilt?.metadataDynamic || undefined;
2687
+ if (prebuilt) {
2688
+ persistRouteCacheLife(route, meta.cacheLife);
2689
+ recordRouteCacheTags(route, meta.tags);
2690
+ if (meta.linkHeader)
2691
+ route.linkHeader = meta.linkHeader;
2692
+ }
2693
+ await buildSubShells(config, route);
2694
+ return true;
2695
+ }
2696
+ return false;
2697
+ }
2698
+ async function hasPartialStaticPrefix(config, route) {
2699
+ if (!route.hasStaticParams)
2700
+ return false;
2701
+ let staticParams;
2702
+ try {
2703
+ staticParams = await staticParamsFor(config, route);
2704
+ } catch {
2705
+ return false;
2706
+ }
2707
+ const paramKeys = [...route.params, ...route.catchAll ? [route.catchAll] : []];
2708
+ for (const set of staticParams.allSets) {
2709
+ let filled = 0;
2710
+ while (filled < paramKeys.length && set[paramKeys[filled]] !== undefined)
2711
+ filled++;
2712
+ if (filled > 0 && filled < paramKeys.length)
2713
+ return true;
2714
+ }
2715
+ return false;
2716
+ }
2717
+ async function hasFullStaticParamSet(config, route) {
2718
+ if (!route.hasStaticParams)
2719
+ return false;
2720
+ let staticParams;
2721
+ try {
2722
+ staticParams = await staticParamsFor(config, route);
2723
+ } catch {
2724
+ return false;
2725
+ }
2726
+ const paramKeys = [...route.params, ...route.catchAll ? [route.catchAll] : []];
2727
+ if (paramKeys.length === 0)
2728
+ return false;
2729
+ return staticParams.allSets.some((set) => paramKeys.every((key) => set[key] !== undefined));
2730
+ }
2731
+ async function buildSubShells(config, route) {
2732
+ let staticParams;
2733
+ try {
2734
+ staticParams = await staticParamsFor(config, route);
2735
+ } catch {
2736
+ return;
2737
+ }
2738
+ route.prerenderedParams = staticParams.allSets;
2739
+ const paramKeys = [...route.params, ...route.catchAll ? [route.catchAll] : []];
2740
+ const prefixes = new Map;
2741
+ for (const set of staticParams.allSets) {
2742
+ let filled = 0;
2743
+ while (filled < paramKeys.length && set[paramKeys[filled]] !== undefined)
2744
+ filled++;
2745
+ if (filled === 0)
2746
+ continue;
2747
+ const concrete = {};
2748
+ for (let i = 0;i < filled; i++)
2749
+ concrete[paramKeys[i]] = set[paramKeys[i]];
2750
+ const key = subShellKey(concrete);
2751
+ if (!prefixes.has(key))
2752
+ prefixes.set(key, concrete);
2753
+ }
2754
+ if (prefixes.size === 0)
2755
+ return;
2756
+ const subShells = [];
2757
+ for (const [key, concreteParams] of prefixes) {
2758
+ const routePath = fillRoutePath(route.route, concreteParams);
2759
+ const url = new URL(`http://pnext.local${routePath}`);
2760
+ const { value: prebuilt, tags } = await runWithWorkUnit("render", () => getRenderExtensions().collectRenderMeta(() => runWithNextBuildPhase(() => renderSubShell({ config, route, url, concreteParams, paramKeys })), { fetchCache: route.segmentConfig?.fetchCache, route: routePath || "/", prerender: true }));
2761
+ recordRouteCacheTags(route, tags);
2762
+ if (!prebuilt)
2763
+ continue;
2764
+ const file = pprSubShellPath(config.outPath, route.id, key);
2765
+ await mkdir4(path5.dirname(file), { recursive: true });
2766
+ await writeText(file, prebuilt.shell);
2767
+ subShells.push({ key, concreteParams, holes: prebuilt.holes });
2768
+ if (Object.keys(concreteParams).length === paramKeys.length) {
2769
+ try {
2770
+ const probe = await runWithWorkUnit("render", () => getRenderExtensions().collectRenderMeta(() => runWithNextBuildPhase(() => renderPageWithStatus({
2771
+ config,
2772
+ route,
2773
+ params: encodeStaticRouteParams(concreteParams),
2774
+ url
2775
+ })), { route: routePath || "/", prerender: true }).then((result) => result.value));
2776
+ const postponed = prebuilt.holes.length > 0 || prebuilt.metadataDynamic || route.pprMetadata === true || routeSourcesHaveDynamicHead(route);
2777
+ await emitConcreteNextPageArtifacts(config, route, routePath, {
2778
+ html: postponed ? prebuilt.shell : `${prebuilt.shell}
2779
+ </body></html>`,
2780
+ status: probe.status,
2781
+ postponed
2782
+ });
2783
+ } catch {}
2784
+ }
2785
+ }
2786
+ subShells.sort((a, b) => Object.keys(b.concreteParams).length - Object.keys(a.concreteParams).length);
2787
+ if (subShells.length > 0)
2788
+ route.pprSubShells = subShells;
2789
+ }
2790
+ function routeSourcesUseHttpFallback(root, route) {
2791
+ for (const file of route.sourceFiles) {
2792
+ if (!file.startsWith(root) || file.includes(`${path5.sep}node_modules${path5.sep}`))
2793
+ continue;
2794
+ if (!existsSync4(file))
2795
+ continue;
2796
+ const source = readTextSync(file);
2797
+ if (/\b(?:notFound|forbidden|unauthorized)\s*\(\s*\)/.test(source))
2798
+ return true;
2799
+ }
2800
+ return false;
2801
+ }
2802
+ function routeSourcesUseRequestApi(root, route) {
2803
+ for (const file of route.sourceFiles) {
2804
+ if (!file.startsWith(root) || file.includes(`${path5.sep}node_modules${path5.sep}`))
2805
+ continue;
2806
+ if (!existsSync4(file))
2807
+ continue;
2808
+ const source = readTextSync(file).replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
2809
+ if (/\b(?:connection|cookies|headers|draftMode)\s*\(\s*\)/.test(source))
2810
+ return true;
2811
+ }
2812
+ return false;
2813
+ }
2814
+ function routeSourcesHaveDynamicHead(route) {
2815
+ for (const file of route.sourceFiles) {
2816
+ if (!existsSync4(file))
2817
+ continue;
2818
+ const source = readTextSync(file);
2819
+ const match = /export\s+(?:async\s+)?function\s+(?:generateMetadata|generateViewport)\s*\([^)]*\)\s*(?::[^{]+)?\{/.exec(source);
2820
+ if (!match)
2821
+ continue;
2822
+ const body = source.slice(match.index + match[0].length);
2823
+ if (/\bawait\b/.test(body.split(`
2824
+ export `)[0] ?? body) && !body.includes("use cache")) {
2825
+ return true;
2826
+ }
2827
+ }
2828
+ return false;
2829
+ }
2830
+ function filterDebugBuildRoutes(root, routes, patterns) {
2831
+ const matchers = patterns.split(",").map((pattern) => pattern.trim()).filter((pattern) => pattern.length > 0 && !pattern.startsWith("!")).map(debugBuildPathMatcher);
2832
+ if (matchers.length === 0)
2833
+ return routes;
2834
+ return routes.filter((route) => {
2835
+ const relative = toPosixPath(path5.relative(root, route.file));
2836
+ return matchers.some((matcher) => matcher(relative));
2837
+ });
2838
+ }
2839
+ function debugBuildPathMatcher(pattern) {
2840
+ if (!/[*?]/.test(pattern)) {
2841
+ return (file) => file === pattern || file.endsWith(`/${pattern}`);
2842
+ }
2843
+ const regex = new RegExp(`^${pattern.split(/(\*\*\/|\*\*|\*|\?)/).map((part) => {
2844
+ if (part === "**/")
2845
+ return "(?:.*/)?";
2846
+ if (part === "**")
2847
+ return ".*";
2848
+ if (part === "*")
2849
+ return "[^/]*";
2850
+ if (part === "?")
2851
+ return "[^/]";
2852
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2853
+ }).join("")}$`);
2854
+ return (file) => regex.test(file);
2855
+ }
2856
+ function subShellKey(concrete) {
2857
+ return Object.entries(concrete).map(([k, v]) => `${k}-${(Array.isArray(v) ? v.join("_") : v).replace(/[^a-zA-Z0-9_]/g, "_")}`).join(".");
2858
+ }
2859
+ async function buildProxyModule(config) {
2860
+ await validateProxyFiles(config);
2861
+ const file = findProxyFile(config);
2862
+ if (!file)
2863
+ return;
2864
+ const href = await devServerModuleHref(config, file, "prod", {
2865
+ conditionTarget: "edge",
2866
+ externalLoadTarget: proxyExternalLoadTarget(file),
2867
+ reactServerLayer: true
2868
+ });
2869
+ const compiled = fileURLToPath3(href);
2870
+ return toPosixPath(path5.relative(config.outPath, compiled));
2871
+ }
2872
+ async function renderNotFoundDocuments({
2873
+ config,
2874
+ log,
2875
+ skip,
2876
+ documentCss,
2877
+ staticMetadataFiles,
2878
+ staticModuleMetadata
2879
+ }) {
2880
+ if (skip)
2881
+ return;
2882
+ const render = async () => {
2883
+ const response = await renderGlobalNotFoundResponse({
2884
+ config,
2885
+ url: new URL("http://pnext.local/_not-found"),
2886
+ staticMetadataFiles,
2887
+ staticModuleMetadata
2888
+ });
2889
+ return response.text();
2890
+ };
2891
+ await documentCss;
2892
+ if (await shouldBuildGlobalNotFound(config)) {
2893
+ await log.step("global not-found", async () => writeText(path5.join(config.outPath, "public", "404.html"), await render()));
2894
+ }
2895
+ if (!config.compat?.next)
2896
+ return;
2897
+ if (existsSync4(path5.join(config.outPath, "public", "404.html")))
2898
+ return;
2899
+ return defaultNotFoundDocument();
2900
+ }
2901
+ async function shouldBuildGlobalNotFound(config) {
2902
+ const file = ["tsx", "ts", "jsx", "js"].flatMap((ext) => [
2903
+ path5.join(config.appPath, `global-not-found.${ext}`),
2904
+ path5.join(config.appPath, `not-found.${ext}`)
2905
+ ]).find((candidate) => existsSync4(candidate));
2906
+ if (!file)
2907
+ return false;
2908
+ return !/\bexport\s+const\s+dynamic\s*=\s*['"]force-dynamic['"]/.test(await readText(file));
2909
+ }
2910
+ async function emitProxyServerArtifacts(config, proxyModule) {
2911
+ if (!config.compat?.next || !proxyModule)
2912
+ return;
2913
+ const compiled = path5.resolve(config.outPath, proxyModule);
2914
+ if (!existsSync4(compiled))
2915
+ return;
2916
+ const serverDir = path5.join(config.root, ".next", "server");
2917
+ await mkdir4(serverDir, { recursive: true });
2918
+ const middlewareFile = path5.join(serverDir, "middleware.js");
2919
+ await copyFile2(compiled, middlewareFile);
2920
+ const files = ["middleware.js"].filter((name) => existsSync4(path5.join(serverDir, name)));
2921
+ await writeFile3(path5.join(serverDir, "middleware.js.nft.json"), `${JSON.stringify({ version: 1, files })}
2922
+ `);
2923
+ }
2924
+ async function emitNextNotFoundArtifacts(config, fallback404) {
2925
+ if (!config.compat?.next)
2926
+ return;
2927
+ const source = path5.join(config.outPath, "public", "404.html");
2928
+ const html = existsSync4(source) ? readFileSync4(source, "utf8") : fallback404;
2929
+ if (html === undefined)
2930
+ return;
2931
+ const serverDir = path5.join(config.root, ".next", "server");
2932
+ const pagesDir = path5.join(serverDir, "pages");
2933
+ const notFoundDir = path5.join(serverDir, "app", "_not-found");
2934
+ await mkdir4(pagesDir, { recursive: true });
2935
+ await mkdir4(notFoundDir, { recursive: true });
2936
+ await writeFile3(path5.join(pagesDir, "404.html"), html);
2937
+ await writeFile3(path5.join(serverDir, "app", "_not-found.html"), html);
2938
+ await writeFile3(path5.join(serverDir, "app", "_not-found.rsc"), html);
2939
+ const pagesManifestFile = path5.join(serverDir, "pages-manifest.json");
2940
+ let pagesManifest = {};
2941
+ try {
2942
+ pagesManifest = JSON.parse(readFileSync4(pagesManifestFile, "utf8"));
2943
+ } catch {}
2944
+ pagesManifest["/404"] = "pages/404.html";
2945
+ await writeFile3(pagesManifestFile, `${JSON.stringify(pagesManifest, null, 2)}
2946
+ `);
2947
+ const clientReferenceManifest = "page_client-reference-manifest.js";
2948
+ await writeFile3(path5.join(notFoundDir, clientReferenceManifest), `self.__RSC_MANIFEST={}
2949
+ `);
2950
+ await writeFile3(path5.join(notFoundDir, "page.js.nft.json"), `${JSON.stringify({ version: 1, files: [clientReferenceManifest] }, null, 2)}
2951
+ `);
2952
+ }
2953
+ async function collectStaticModuleMetadata(config, routes) {
2954
+ const metadata = {};
2955
+ if (config.compat?.next)
2956
+ return metadata;
2957
+ const files = new Set;
2958
+ for (const route of routes) {
2959
+ if (route.kind !== "page")
2960
+ continue;
2961
+ for (const file of findLayouts(config.appPath, route.file)) {
2962
+ if (existsSync4(file))
2963
+ files.add(file);
2964
+ }
2965
+ files.add(route.file);
2966
+ }
2967
+ if (files.size === 0)
2968
+ return metadata;
2969
+ registerServerRuntime(config, [...files]);
2970
+ registerCssRuntime();
2971
+ for (const file of files) {
2972
+ const href = reactCompatEnabled(config) ? await devServerModuleHref(config, file, "build") : pathToFileHref(file);
2973
+ const module = await import(href);
2974
+ const entry = {};
2975
+ const routeMetadata = await readModuleMetadata(module);
2976
+ const viewport = await readModuleViewport(module);
2977
+ if (routeMetadata)
2978
+ entry.metadata = routeMetadata;
2979
+ if (viewport)
2980
+ entry.viewport = viewport;
2981
+ if (entry.metadata || entry.viewport)
2982
+ metadata[file] = entry;
2983
+ }
2984
+ return metadata;
2985
+ }
2986
+ async function collectStaticRouteMetadata(config, routes, staticMetadataFiles) {
2987
+ const metadata = {};
2988
+ if (config.compat?.next)
2989
+ return metadata;
2990
+ for (const route of routes) {
2991
+ if (route.kind !== "page" || route.interception)
2992
+ continue;
2993
+ const paramSets = route.prerenderedParams ?? (route.params.length === 0 ? [{}] : []);
2994
+ for (const params of paramSets) {
2995
+ const routePath = fillRoutePath(route.route, params);
2996
+ const base = route.interception ? staticMetadataForRouteFromFiles(staticMetadataFiles, config.appPath, route.file, routePath) : staticMetadataForPathFromFiles(staticMetadataFiles, routePath);
2997
+ const resolved = await withDynamicMetadataRoutes(base, config.appPath, route.file, routePath, (file) => importMetadataModule(config, file));
2998
+ metadata[staticRouteMetadataKey(routePath)] = resolved;
2999
+ }
3000
+ }
3001
+ return metadata;
3002
+ }
3003
+ async function importMetadataModule(config, file) {
3004
+ const href = reactCompatEnabled(config) ? await devServerModuleHref(config, file, "build") : pathToFileHref(file);
3005
+ return import(href);
3006
+ }
3007
+ async function buildStaticRouteHandler(config, route, options = {}) {
3008
+ const skipPhysicalWrite = options.skipPhysicalWrite ?? false;
3009
+ registerServerRuntime(config, route.sourceFiles);
3010
+ const moduleHref = reactCompatEnabled(config) ? await devServerModuleHref(config, route.file, "build", {
3011
+ conditionTarget: serverBundleTargetForRuntime(route.segmentConfig?.runtime)
3012
+ }) : pathToFileHref(route.file);
3013
+ const imported = await import(moduleHref);
3014
+ const routeModule = metadataRouteHandlerModule(imported, route) ?? imported;
3015
+ const module = nextCompatEnabled2(config) ? buildCompat().normalizeStaticParamsModule(routeModule) : routeModule;
3016
+ const paramSets = await staticRouteParams(route, module);
3017
+ const staticFiles = {};
3018
+ if (route.metadataRoute?.generatedParam && paramSets.length > 0) {
3019
+ route.metadataRoute.generatedRoutes = paramSets.map((params) => fillRoutePath(route.route, params, route.metadataRoute?.generatedParam));
3020
+ }
3021
+ const requestBase = route.segmentConfig?.dynamic === "force-static" ? "http://localhost:3000" : "http://pnext.local";
3022
+ for (const params of paramSets) {
3023
+ const routePath = fillRoutePath(route.route, params, route.metadataRoute?.generatedParam);
3024
+ const file = staticRouteHandlerPath(config.outPath, routePath);
3025
+ if (!skipPhysicalWrite) {
3026
+ const collision = staticOutputCollision(config.outPath, file);
3027
+ if (collision) {
3028
+ warnSkippedStatic(routePath, collision);
3029
+ continue;
3030
+ }
3031
+ }
3032
+ const prerender = runWithWorkUnit("render", () => getRenderExtensions().collectRenderMeta(() => runWithCacheScope(() => runWithNextBuildPhase(() => withRouteRuntime(route.segmentConfig?.runtime, () => handleRouteModule(module, new Request(`${requestBase}${routePath}`), params, {
3033
+ routeFile: route.file
3034
+ })))), {
3035
+ fetchCache: route.segmentConfig?.fetchCache,
3036
+ route: routePath || "/",
3037
+ prerender: true,
3038
+ handler: true,
3039
+ dynamicError: route.segmentConfig?.dynamic === "error"
3040
+ }));
3041
+ const early = await settleBeforeNextTask(prerender);
3042
+ const completed = early ?? await prerender;
3043
+ const rendered = early ?? (route.segmentConfig?.dynamic === "force-static" || await handlerHasEntirelyCachedIo(route) ? completed : undefined);
3044
+ if (!rendered)
3045
+ continue;
3046
+ const response = rendered.value;
3047
+ if (response.status >= 500) {
3048
+ throw new Error(`route handler prerender returned ${response.status}`);
3049
+ }
3050
+ if (rendered.noStore && !staticRouteHandlerExplicitlyCached(route))
3051
+ continue;
3052
+ const body = await settleBeforeNextTask(response.clone().arrayBuffer());
3053
+ if (!body)
3054
+ continue;
3055
+ const relative = toPosixPath(path5.relative(path5.join(config.outPath, "public"), file));
3056
+ if (!skipPhysicalWrite) {
3057
+ await mkdir4(path5.dirname(file), { recursive: true });
3058
+ await writeFile3(file, new Uint8Array(body));
3059
+ }
3060
+ const revalidateSeconds = combineRevalidate(route.segmentConfig?.revalidate, rendered.revalidateSeconds);
3061
+ staticFiles[relative] = {
3062
+ status: response.status,
3063
+ headers: [...response.headers.entries()],
3064
+ routeId: route.id,
3065
+ ...revalidateSeconds !== undefined ? { revalidateSeconds } : {},
3066
+ ...rendered.tags.length > 0 ? { tags: rendered.tags } : {}
3067
+ };
3068
+ }
3069
+ return staticFiles;
3070
+ }
3071
+ function settleBeforeNextTask(value) {
3072
+ return new Promise((resolve, reject) => {
3073
+ let settled = false;
3074
+ const timer = setTimeout(() => {
3075
+ if (!settled)
3076
+ resolve(undefined);
3077
+ }, 0);
3078
+ value.then((result) => {
3079
+ settled = true;
3080
+ clearTimeout(timer);
3081
+ resolve(result);
3082
+ }, (error) => {
3083
+ settled = true;
3084
+ clearTimeout(timer);
3085
+ reject(error instanceof Error ? error : new Error(String(error)));
3086
+ });
3087
+ });
3088
+ }
3089
+ async function handlerHasEntirelyCachedIo(route) {
3090
+ if (route.synthetic || !existsSync4(route.file))
3091
+ return false;
3092
+ const source = await readText(route.file);
3093
+ if (route.metadataRoute && metadataDefaultUsesCache(source))
3094
+ return true;
3095
+ const getStart = source.search(/\bexport\s+(?:async\s+)?function\s+GET\s*\(/);
3096
+ if (getStart === -1)
3097
+ return false;
3098
+ const afterGet = source.slice(getStart);
3099
+ const nextDeclaration = afterGet.slice(1).search(/^(?:async\s+)?(?:function|const|let)\s+/m);
3100
+ const body = nextDeclaration === -1 ? afterGet : afterGet.slice(0, nextDeclaration + 1);
3101
+ if (/\bnew\s+Date\s*\(\s*\)/.test(body) || /\bDate\s*\.\s*now\s*\(/.test(body)) {
3102
+ return false;
3103
+ }
3104
+ const awaited = [...body.matchAll(/\bawait\s+([A-Za-z_$][\w$]*)\s*\(/g)].map((match) => match[1]);
3105
+ if (awaited.length === 0)
3106
+ return false;
3107
+ const cached = new Set(["import"]);
3108
+ for (const match of source.matchAll(/\bconst\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*\(/g)) {
3109
+ if (match[2] === "cache" || match[2] === "unstable_cache")
3110
+ cached.add(match[1]);
3111
+ }
3112
+ for (const match of source.matchAll(/\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{\s*['"]use cache['"]/g)) {
3113
+ cached.add(match[1]);
3114
+ }
3115
+ for (const name of awaited) {
3116
+ const start = source.search(new RegExp(`\\b(?:const\\s+${name}\\s*=|function\\s+${name}\\s*\\()`));
3117
+ if (start === -1)
3118
+ continue;
3119
+ const tail = source.slice(start);
3120
+ const next = tail.slice(1).search(/^(?:async\s+)?(?:function|const|let)\s+/m);
3121
+ const declaration = next === -1 ? tail : tail.slice(0, next + 1);
3122
+ if (/\bcache\s*:\s*['"]force-cache['"]/.test(declaration))
3123
+ cached.add(name);
3124
+ }
3125
+ return awaited.every((name) => cached.has(name));
3126
+ }
3127
+ function metadataDefaultUsesCache(source) {
3128
+ return /\bexport\s+default\s+(?:async\s+)?function\b[^(]*\([^)]*\)\s*(?::[^{]*)?\{\s*(?:\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*['"]use cache['"]/.test(source);
3129
+ }
3130
+ async function usesUnstableCache(route) {
3131
+ if (route.synthetic || !existsSync4(route.file))
3132
+ return false;
3133
+ const source = await readText(route.file);
3134
+ const localNames = [];
3135
+ const dynamicNames = [];
3136
+ for (const match of source.matchAll(/\bimport\s*\{([^}]*)\}\s*from\s*['"]next\/(cache|headers|server)(?:\.js)?['"]/g)) {
3137
+ for (const item of match[1].split(",")) {
3138
+ const [imported, local] = item.trim().split(/\s+as\s+/);
3139
+ if (match[2] === "cache" && imported === "unstable_cache") {
3140
+ localNames.push(local ?? imported);
3141
+ } else if (match[2] === "headers" && (imported === "cookies" || imported === "headers") || match[2] === "server" && imported === "connection") {
3142
+ dynamicNames.push(local ?? imported);
3143
+ }
3144
+ }
3145
+ }
3146
+ if (dynamicNames.length === 0)
3147
+ return false;
3148
+ const dynamicCall = dynamicNames.join("|");
3149
+ return localNames.some((name) => new RegExp(`\\b${name}\\s*\\(\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)?\\s*=>[\\s\\S]{0,1000}?\\b(?:${dynamicCall})\\s*\\(`).test(source));
3150
+ }
3151
+ async function staticHandlerDynamicUsage(route) {
3152
+ if (!route.usesRequest)
3153
+ return;
3154
+ if (route.segmentConfig?.dynamic === "force-static" || route.segmentConfig?.dynamic === "error") {
3155
+ return;
3156
+ }
3157
+ if (route.synthetic || !existsSync4(route.file))
3158
+ return;
3159
+ const source = await readText(route.file);
3160
+ if (/\b(?:request|req)\.url\b/.test(source))
3161
+ return "request.url";
3162
+ if (/\bnextUrl\s*\.\s*toString\s*\(/.test(source))
3163
+ return "nextUrl.toString";
3164
+ if (/\bheaders\s*\(/.test(source))
3165
+ return "headers()";
3166
+ if (/\bcookies\s*\(/.test(source))
3167
+ return "cookies()";
3168
+ if (/\bconnection\s*\(/.test(source))
3169
+ return "connection()";
3170
+ return;
3171
+ }
3172
+ function collectDescendantHandlerIds(routes) {
3173
+ const ids = new Set;
3174
+ const paths = routes.map((route) => ({ route, norm: (route.route || "/").replace(/\/+$/, "") }));
3175
+ for (const { route, norm } of paths) {
3176
+ if (route.kind !== "handler")
3177
+ continue;
3178
+ const hasAncestor = paths.some((other) => other.route !== route && other.norm.length > 0 && norm !== other.norm && norm.startsWith(`${other.norm}/`));
3179
+ if (hasAncestor)
3180
+ ids.add(route.id);
3181
+ }
3182
+ return ids;
3183
+ }
3184
+ async function staticRouteHandlerCandidate(route) {
3185
+ const config = route.segmentConfig;
3186
+ if (config?.dynamic === "force-dynamic")
3187
+ return false;
3188
+ if (config?.revalidate === 0)
3189
+ return false;
3190
+ if (config?.fetchCache === "force-no-store")
3191
+ return false;
3192
+ if (route.handlerUsesRevalidationApi)
3193
+ return false;
3194
+ if (route.metadataRoute)
3195
+ return !route.usesRequest;
3196
+ if (config?.dynamic === "error")
3197
+ return true;
3198
+ if (config?.dynamic === "force-static")
3199
+ return true;
3200
+ if (staticRouteHandlerExplicitlyCached(route) || route.hasStaticParams)
3201
+ return true;
3202
+ if (route.usesRequest)
3203
+ return false;
3204
+ if (!cacheComponents() || route.mode !== "static")
3205
+ return false;
3206
+ if (!handlerUsesUncachedIo(route))
3207
+ return true;
3208
+ return handlerHasEntirelyCachedIo(route);
3209
+ }
3210
+ function handlerUsesUncachedIo(route) {
3211
+ const source = readTextSync(route.file);
3212
+ if (!source)
3213
+ return false;
3214
+ return /\bnew Date\s*\(|\bDate\.now\s*\(|\bMath\.random\s*\(/.test(stripUseCacheBodies(source));
3215
+ }
3216
+ function stripUseCacheBodies(source) {
3217
+ let out = source;
3218
+ for (;; ) {
3219
+ const directive = /\{\s*(['"])use cache(?:\s*:\s*[\w-]+)?\1\s*;?/.exec(out);
3220
+ if (!directive)
3221
+ break;
3222
+ const bodyOpen = directive.index + 1;
3223
+ let balance = 1;
3224
+ let end = out.length;
3225
+ for (let i = bodyOpen;i < out.length; i += 1) {
3226
+ const ch = out[i];
3227
+ if (ch === "{")
3228
+ balance += 1;
3229
+ else if (ch === "}") {
3230
+ balance -= 1;
3231
+ if (balance === 0) {
3232
+ end = i;
3233
+ break;
3234
+ }
3235
+ }
3236
+ }
3237
+ out = `${out.slice(0, bodyOpen)}${out.slice(end)}`;
3238
+ }
3239
+ return out;
3240
+ }
3241
+ function staticRouteHandlerExplicitlyCached(route) {
3242
+ const config = route.segmentConfig;
3243
+ return config?.dynamic === "force-static" || config?.revalidate === false || typeof config?.revalidate === "number" && config.revalidate > 0;
3244
+ }
3245
+ async function needsRequestOriginForMetadataImages(appPath, route) {
3246
+ if (!await routeNullsMetadataBase(route))
3247
+ return false;
3248
+ return routeMetadataImageFiles(appPath, route.file);
3249
+ }
3250
+ async function routeNullsMetadataBase(route) {
3251
+ const sourceFiles = route.sourceFiles.filter((file) => /\.(tsx?|jsx?|mjs|cjs)$/.test(file));
3252
+ for (const file of sourceFiles) {
3253
+ try {
3254
+ if (/\bmetadataBase\s*:\s*null\b|\bmetadataBase\s*=\s*null\b/.test(await readText(file))) {
3255
+ return true;
3256
+ }
3257
+ } catch {}
3258
+ }
3259
+ return false;
3260
+ }
3261
+ function routeMetadataImageFiles(appPath, routeFile) {
3262
+ let dir = path5.dirname(routeFile);
3263
+ const root = path5.resolve(appPath);
3264
+ while (dir.startsWith(root)) {
3265
+ if (existsSync4(dir)) {
3266
+ for (const entry of readdirSync2(dir)) {
3267
+ if (/^(opengraph-image|twitter-image)\d*\.(tsx?|jsx?|mjs|png|jpe?g|gif|webp|svg)$/.test(entry)) {
3268
+ return true;
3269
+ }
3270
+ }
3271
+ }
3272
+ if (dir === root)
3273
+ break;
3274
+ dir = path5.dirname(dir);
3275
+ }
3276
+ return false;
3277
+ }
3278
+ async function copyStaticMetadataFiles(config, staticFiles, metadataFiles = discoverStaticMetadataFiles(config.appPath)) {
3279
+ for (const metadataFile of metadataFiles) {
3280
+ const target = staticMetadataOutputFile(config.outPath, metadataFile);
3281
+ const collision = staticOutputCollision(config.outPath, target);
3282
+ if (collision) {
3283
+ warnSkippedStatic(`/${metadataFile.outputPath}`, collision);
3284
+ continue;
3285
+ }
3286
+ await mkdir4(path5.dirname(target), { recursive: true });
3287
+ await copyFile2(metadataFile.file, target);
3288
+ staticFiles[metadataFile.outputPath] = {
3289
+ status: 200,
3290
+ headers: [
3291
+ ["content-type", metadataFile.contentType],
3292
+ ["cache-control", staticMetadataCacheControl]
3293
+ ]
3294
+ };
3295
+ }
3296
+ }
3297
+ function staticHtmlPath(outPath, routePath, flatLayout = false) {
3298
+ if (routePath === "/")
3299
+ return path5.join(outPath, "public", "index.html");
3300
+ const normalized = routePath.replace(/^\/|\/$/g, "");
3301
+ if (flatLayout)
3302
+ return safePublicPath(outPath, `${normalized}.html`);
3303
+ return safePublicPath(outPath, normalized, "index.html");
3304
+ }
3305
+ function encodeStaticRouteParams(params) {
3306
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [
3307
+ key,
3308
+ Array.isArray(value) ? value.map(encodeURIComponent) : encodeURIComponent(value)
3309
+ ]));
3310
+ }
3311
+ function fillRoutePath(route, params, generatedParam) {
3312
+ let value = route;
3313
+ for (const [key, param] of Object.entries(params)) {
3314
+ const segment = Array.isArray(param) ? param.join("/") : param;
3315
+ value = value.replace(`:${key}*`, segment).replace(`:${key}`, segment);
3316
+ }
3317
+ if (generatedParam && params[generatedParam] !== undefined) {
3318
+ const param = params[generatedParam];
3319
+ const segment = Array.isArray(param) ? param.join("/") : param;
3320
+ value = value.replace(":id", segment);
3321
+ }
3322
+ return value;
3323
+ }
3324
+ async function runWithNextBuildPhase(task) {
3325
+ const previous = process.env.NEXT_PHASE;
3326
+ process.env.NEXT_PHASE = "phase-production-build";
3327
+ try {
3328
+ return await task();
3329
+ } finally {
3330
+ if (previous === undefined)
3331
+ delete process.env.NEXT_PHASE;
3332
+ else
3333
+ process.env.NEXT_PHASE = previous;
3334
+ }
3335
+ }
3336
+ function cacheLifeResponseHeaders(life) {
3337
+ if (!life)
3338
+ return [];
3339
+ const headers = [];
3340
+ const { revalidateSeconds, expireSeconds, staleSeconds } = life;
3341
+ if (revalidateSeconds !== undefined && expireSeconds !== undefined) {
3342
+ const swr = Math.max(0, expireSeconds - revalidateSeconds);
3343
+ headers.push(["cache-control", `s-maxage=${revalidateSeconds}, stale-while-revalidate=${swr}`]);
3344
+ }
3345
+ if (staleSeconds !== undefined) {
3346
+ headers.push(["x-nextjs-stale-time", String(staleSeconds)]);
3347
+ }
3348
+ return headers;
3349
+ }
3350
+ function combineRevalidate(segmentRevalidate, collected) {
3351
+ const candidates = [
3352
+ ...typeof segmentRevalidate === "number" && segmentRevalidate > 0 ? [segmentRevalidate] : [],
3353
+ ...collected !== undefined && collected > 0 ? [collected] : []
3354
+ ];
3355
+ if (candidates.length === 0)
3356
+ return;
3357
+ return Math.min(...candidates);
3358
+ }
3359
+ function staticRouteHandlerPath(outPath, routePath) {
3360
+ return safePublicPath(outPath, routePath.replace(/^\/+/, "") || "index");
3361
+ }
3362
+ function staticOutputCollision(outPath, file) {
3363
+ const publicPath = path5.join(outPath, "public");
3364
+ if (existsSync4(file) && statSync2(file).isDirectory()) {
3365
+ return `${toPosixPath(path5.relative(publicPath, file))} already exists as a directory`;
3366
+ }
3367
+ let dir = path5.dirname(file);
3368
+ while (dir !== publicPath && dir !== path5.dirname(dir)) {
3369
+ if (existsSync4(dir)) {
3370
+ if (!statSync2(dir).isDirectory()) {
3371
+ return `${toPosixPath(path5.relative(publicPath, dir))} already exists as a file`;
3372
+ }
3373
+ break;
3374
+ }
3375
+ dir = path5.dirname(dir);
3376
+ }
3377
+ return null;
3378
+ }
3379
+ function rethrowIfProgrammingError(error) {
3380
+ if (error instanceof ReferenceError || error instanceof SyntaxError || error instanceof TypeError && isBuildInternalStack(error)) {
3381
+ throw error;
3382
+ }
3383
+ }
3384
+ function isBuildInternalStack(error) {
3385
+ const stack = error.stack ?? "";
3386
+ const firstFrame = stack.split(`
3387
+ `).find((line) => /^\s*at\s/.test(line)) ?? "";
3388
+ return /packages[/\\]pnext[/\\]src[/\\]/.test(firstFrame);
3389
+ }
3390
+ function logStaticBailout(routePath, reason) {
3391
+ console.log(`Static generation failed due to dynamic usage on ${routePath}, reason: ${reason}`);
3392
+ }
3393
+ async function requestApiBailoutReason(route) {
3394
+ for (const file of ownSourceFiles(route)) {
3395
+ let source;
3396
+ try {
3397
+ source = await readText(file);
3398
+ } catch {
3399
+ continue;
3400
+ }
3401
+ const match = /\b(headers|cookies|draftMode|connection)\s*\(/.exec(source);
3402
+ if (match?.[1])
3403
+ return match[1];
3404
+ }
3405
+ return "dynamic usage";
3406
+ }
3407
+ function ownSourceFiles(route) {
3408
+ const frameworkRoot3 = path5.resolve(fileURLToPath3(Bun.pathToFileURL(__PNEXT_PACKAGE_ROOT__ + "/src/cli/build.ts").href), "..", "..");
3409
+ return route.sourceFiles.filter((file) => {
3410
+ const resolved = path5.resolve(file);
3411
+ return !resolved.includes(`${path5.sep}node_modules${path5.sep}`) && !resolved.startsWith(frameworkRoot3 + path5.sep);
3412
+ });
3413
+ }
3414
+ async function schedulesDeferredWork(route) {
3415
+ for (const file of ownSourceFiles(route)) {
3416
+ let source;
3417
+ try {
3418
+ source = await readText(file);
3419
+ } catch {
3420
+ continue;
3421
+ }
3422
+ if (/\b(?:setTimeout|setImmediate|queueMicrotask)\s*\(/.test(source))
3423
+ return true;
3424
+ }
3425
+ return false;
3426
+ }
3427
+ function captureDeferredFailures(record) {
3428
+ const globals = globalThis;
3429
+ const originals = new Map;
3430
+ for (const name of ["setTimeout", "setImmediate", "queueMicrotask"]) {
3431
+ const original = globals[name];
3432
+ if (typeof original !== "function")
3433
+ continue;
3434
+ originals.set(name, original);
3435
+ globals[name] = function patched(callback, ...rest) {
3436
+ if (typeof callback !== "function")
3437
+ return original.call(this, callback, ...rest);
3438
+ const guarded = function guardedCallback(...args) {
3439
+ try {
3440
+ const value = callback.apply(this, args);
3441
+ if (isThenable(value))
3442
+ value.then(undefined, record);
3443
+ return value;
3444
+ } catch (error) {
3445
+ record(error);
3446
+ }
3447
+ };
3448
+ return original.call(this, guarded, ...rest);
3449
+ };
3450
+ }
3451
+ return () => {
3452
+ for (const [name, original] of originals)
3453
+ globals[name] = original;
3454
+ };
3455
+ }
3456
+ function isThenable(value) {
3457
+ return typeof value?.then === "function";
3458
+ }
3459
+ async function probeDeferredDynamicUsage(config, route, staticMetadataFiles, staticModuleMetadata) {
3460
+ const routePath = toNextRoutePattern(route.route || "/");
3461
+ const failures = [];
3462
+ const restore = captureDeferredFailures((error) => failures.push(error));
3463
+ beginDynamicBailoutProbe(routePath);
3464
+ try {
3465
+ await runWithWorkUnit("render", () => getRenderExtensions().collectRenderMeta(() => runWithNextBuildPhase(() => withRouteRuntime(route.segmentConfig?.runtime, () => renderPageWithStatus({
3466
+ config,
3467
+ route,
3468
+ params: {},
3469
+ url: new URL(`http://pnext.local${route.route || "/"}`),
3470
+ staticMetadataFiles,
3471
+ staticModuleMetadata
3472
+ }))), { route: route.route || "/", prerender: true }));
3473
+ await new Promise((resolve) => setTimeout(resolve, 0));
3474
+ } catch {
3475
+ return;
3476
+ } finally {
3477
+ endDynamicBailoutProbe();
3478
+ restore();
3479
+ }
3480
+ for (const failure of failures) {
3481
+ if (!(failure instanceof Error) || failure.name !== "DynamicServerError")
3482
+ continue;
3483
+ console.error(`Error occurred prerendering page "${routePath}". Read more: https://nextjs.org/docs/messages/prerender-error`);
3484
+ console.error(`${failure.name}: ${failure.message}`);
3485
+ }
3486
+ }
3487
+ function warnSkippedStatic(routePath, reason) {
3488
+ console.warn(`pnext build: skipping static output for ${routePath} (${reason}); the route will be served dynamically`);
3489
+ }
3490
+ function toNextRoutePattern(route) {
3491
+ return route.replace(/:\.\.\.([^/]+)/g, "[...$1]").replace(/:([^/]+)/g, "[$1]");
3492
+ }
3493
+ function isAfterPrerenderError(error) {
3494
+ return typeof error === "object" && error !== null && error[Symbol.for("pnext.afterPrerenderError")] === true;
3495
+ }
3496
+ function realFilePath(file) {
3497
+ try {
3498
+ return realpathSync3.native(file);
3499
+ } catch {
3500
+ return path5.resolve(file);
3501
+ }
3502
+ }
3503
+ function safePublicPath(outPath, ...segments) {
3504
+ const publicPath = path5.join(outPath, "public");
3505
+ const file = path5.join(publicPath, ...segments);
3506
+ const relative = path5.relative(publicPath, file);
3507
+ if (relative.startsWith("..") || path5.isAbsolute(relative)) {
3508
+ throw new Error(`Static output path escapes public directory: ${segments.join("/")}`);
3509
+ }
3510
+ return file;
3511
+ }
3512
+ async function copyPartytownLib(config) {
3513
+ if (!nextCompatEnabled2(config))
3514
+ return;
3515
+ if (!buildCompat().nextScriptWorkersEnabled())
3516
+ return;
3517
+ const libDir = resolvePartytownLibDir(config.root);
3518
+ if (!libDir) {
3519
+ console.warn("pnext build: experimental.nextScriptWorkers is enabled but no Partytown package was found (@qwik.dev/partytown or @builder.io/partytown); worker scripts will 404 the library until it is installed");
3520
+ return;
3521
+ }
3522
+ const target = path5.join(config.outPath, "public", "_next", "static", "~partytown");
3523
+ await mkdir4(target, { recursive: true });
3524
+ await copyPublicDir(libDir, target);
3525
+ }
3526
+ function resolvePartytownLibDir(root) {
3527
+ const requireFromRoot = createRequire(path5.join(root, "package.json"));
3528
+ for (const pkg of ["@qwik.dev/partytown", "@builder.io/partytown"]) {
3529
+ try {
3530
+ const pkgJson = requireFromRoot.resolve(`${pkg}/package.json`);
3531
+ const libDir = path5.join(path5.dirname(pkgJson), "lib");
3532
+ if (existsSync4(libDir) && statSync2(libDir).isDirectory())
3533
+ return libDir;
3534
+ } catch {}
3535
+ }
3536
+ return null;
3537
+ }
3538
+ async function copyPublicDir(from, to) {
3539
+ const files = (await listFiles(from)).map((file) => toPosixPath(path5.relative(from, file)));
3540
+ for (const relative of files) {
3541
+ const target = path5.join(to, relative);
3542
+ await mkdir4(path5.dirname(target), { recursive: true });
3543
+ await copyFile2(path5.join(from, relative), target);
3544
+ }
3545
+ return files;
3546
+ }
3547
+ export {
3548
+ buildProject,
3549
+ staticHtmlPath
3550
+ };