@plitzi/sdk-server 0.39.0 → 0.39.2

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 (666) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +364 -61
  3. package/dist/adapters/authAdapters.d.ts +2 -1
  4. package/dist/adapters/cloudAdapters.d.ts +2 -1
  5. package/dist/adapters/jsonAdapters.d.ts +2 -1
  6. package/dist/adapters/space/index.d.ts +3 -3
  7. package/dist/adapters/space/resolvers.d.ts +41 -4
  8. package/dist/adapters/space/types.d.ts +11 -1
  9. package/dist/auth.d.ts +9 -29
  10. package/dist/auth.js +2323 -22
  11. package/dist/bundle.d.ts +6 -0
  12. package/dist/bundle.js +171 -0
  13. package/dist/cache.d.ts +7 -0
  14. package/dist/cache.js +1 -0
  15. package/dist/chunks/buildBody-W9D8ySNY.js +1450 -0
  16. package/dist/chunks/core-TlrWmT4B.js +2118 -0
  17. package/dist/chunks/createServer-Bd_b7T3k.js +2956 -0
  18. package/dist/chunks/platform-DhdFYWm5.js +38 -0
  19. package/dist/{core/auth/routes.js → chunks/renewal-D98v6-Jd.js} +23 -4
  20. package/dist/chunks/template-M3IEZ6os.js +42 -0
  21. package/dist/{core/auth/throttle.js → chunks/throttle-BH7JLIOF.js} +4 -5
  22. package/dist/chunks/token-B2uY9JzU.js +824 -0
  23. package/dist/chunks/views/inline/keepTaps.js +1 -0
  24. package/dist/chunks/views/inline/motionSeen.js +2 -0
  25. package/dist/{modules/ssr → chunks}/views/template.ejs +62 -100
  26. package/dist/core/auth/api/admin.d.ts +2 -3
  27. package/dist/core/auth/api/context.d.ts +24 -29
  28. package/dist/core/auth/api/factors.d.ts +1 -2
  29. package/dist/core/auth/api/index.d.ts +30 -30
  30. package/dist/core/auth/api/profile.d.ts +1 -1
  31. package/dist/core/auth/api/session.d.ts +1 -2
  32. package/dist/core/auth/api/types.d.ts +2 -280
  33. package/dist/core/auth/api/values.d.ts +2 -3
  34. package/dist/core/auth/createAuth.d.ts +67 -76
  35. package/dist/core/auth/oauth/index.d.ts +1 -1
  36. package/dist/core/auth/oauth/providers/oidc.d.ts +0 -6
  37. package/dist/core/auth/renewal.d.ts +1 -3
  38. package/dist/core/auth/routes.d.ts +1 -5
  39. package/dist/core/auth/throttle.d.ts +2 -2
  40. package/dist/core/createServer.d.ts +14 -5
  41. package/dist/core/handlers/authMiddleware.d.ts +1 -2
  42. package/dist/core/handlers/authRouteHandlers.d.ts +1 -2
  43. package/dist/core/handlers/csrfMiddleware.d.ts +1 -2
  44. package/dist/core/handlers/oauthRouteHandlers.d.ts +1 -1
  45. package/dist/core/handlers/socialRouteHandlers.d.ts +2 -3
  46. package/dist/core/handlers/types.d.ts +1 -3
  47. package/dist/core/http/pageContext.d.ts +25 -0
  48. package/dist/core/http/stages/authApi.d.ts +1 -1
  49. package/dist/core/http/stages/authRoutes.d.ts +4 -10
  50. package/dist/core/http/stages/cspReport.d.ts +6 -0
  51. package/dist/core/http/stages/defaultFavicon.d.ts +3 -0
  52. package/dist/core/http/stages/exchangeRoute.d.ts +3 -2
  53. package/dist/core/http/stages/fontAssets.d.ts +3 -2
  54. package/dist/core/http/stages/googleFonts.d.ts +7 -0
  55. package/dist/core/http/stages/images.d.ts +4 -3
  56. package/dist/core/http/stages/livePages.d.ts +3 -2
  57. package/dist/core/http/stages/oauth.d.ts +2 -2
  58. package/dist/core/http/stages/pluginAssets.d.ts +2 -1
  59. package/dist/core/http/stages/{static.d.ts → sdkAssets.d.ts} +1 -4
  60. package/dist/core/http/stages/sessionRenewal.d.ts +4 -3
  61. package/dist/core/http/stages/signInRoute.d.ts +3 -2
  62. package/dist/core/oauth/authorize.d.ts +1 -1
  63. package/dist/core/oauth/challenge.d.ts +1 -1
  64. package/dist/core/oauth/consentPage.d.ts +1 -1
  65. package/dist/core/oauth/issueContext.d.ts +1 -1
  66. package/dist/core/oauth/metadata.d.ts +1 -5
  67. package/dist/core/oauth/records.d.ts +1 -1
  68. package/dist/core/oauth/register.d.ts +1 -1
  69. package/dist/core/oauth/respond.d.ts +1 -1
  70. package/dist/core/oauth/token.d.ts +1 -1
  71. package/dist/core/platform.d.ts +13 -0
  72. package/dist/core/sdkAssets.d.ts +11 -1
  73. package/dist/core/server/pageServer.d.ts +4 -3
  74. package/dist/core/server/{fleet/relay.d.ts → relay.d.ts} +1 -2
  75. package/dist/core/server/reportCacheSharing.d.ts +11 -0
  76. package/dist/core/services/registry.d.ts +4 -2
  77. package/dist/core/services/resolve.d.ts +1 -9
  78. package/dist/core/services/robotsTxt.d.ts +2 -1
  79. package/dist/core/services/rsc.d.ts +2 -1
  80. package/dist/core/services/servedSpace.d.ts +1 -1
  81. package/dist/core/services/sitemapXml.d.ts +2 -1
  82. package/dist/core/services/spaceDocument.d.ts +2 -1
  83. package/dist/core/services/ssr.d.ts +2 -1
  84. package/dist/core/services/styleSheet.d.ts +3 -0
  85. package/dist/env.js +1 -2
  86. package/dist/handlers.d.ts +1 -1
  87. package/dist/handlers.js +517 -5
  88. package/dist/helpers/buildServerInfo.d.ts +3 -1
  89. package/dist/helpers/cache/cacheManager.d.ts +1 -1
  90. package/dist/helpers/cache/defaults.d.ts +22 -1
  91. package/dist/helpers/cache/index.d.ts +11 -4
  92. package/dist/helpers/cache/keys.d.ts +27 -4
  93. package/dist/helpers/cache/limits.d.ts +16 -0
  94. package/dist/helpers/cache/pages.d.ts +20 -0
  95. package/dist/helpers/cache/queryParams.d.ts +11 -0
  96. package/dist/helpers/cache/serverCaches.d.ts +24 -11
  97. package/dist/helpers/cache/sharedCache.d.ts +29 -0
  98. package/dist/helpers/hydrationPayload.d.ts +35 -8
  99. package/dist/helpers/metrics.d.ts +5 -1
  100. package/dist/helpers/paintedCookie.d.ts +13 -0
  101. package/dist/helpers/visitorScheme.d.ts +10 -0
  102. package/dist/hosts/authoringHost/index.d.ts +1 -1
  103. package/dist/hosts/project/agentRuns.d.ts +1 -1
  104. package/dist/hosts/project/bundle.d.ts +22 -0
  105. package/dist/hosts/project/laterAsks.d.ts +1 -1
  106. package/dist/hosts/project/plugins.d.ts +3 -2
  107. package/dist/hosts/project/serveProject.d.ts +17 -7
  108. package/dist/hosts/project/spaceFailure.d.ts +1 -1
  109. package/dist/index.d.ts +9 -18
  110. package/dist/index.js +168 -24
  111. package/dist/modules/fonts/googleFonts.d.ts +27 -0
  112. package/dist/modules/images/imageProxy.d.ts +1 -1
  113. package/dist/modules/rsc/connectorRscData.d.ts +10 -12
  114. package/dist/modules/rsc/externalQueryReader.d.ts +28 -5
  115. package/dist/modules/rsc/handler.d.ts +3 -1
  116. package/dist/modules/rsc/matchRscPage.d.ts +0 -8
  117. package/dist/modules/rsc/publicFileResolver.d.ts +1 -1
  118. package/dist/modules/rsc/resolveRscData.d.ts +3 -31
  119. package/dist/modules/ssr/Component.d.ts +6 -3
  120. package/dist/modules/ssr/applySSRResult.d.ts +2 -6
  121. package/dist/modules/ssr/buildBody.d.ts +7 -2
  122. package/dist/modules/ssr/defaultFavicon.d.ts +10 -0
  123. package/dist/modules/ssr/earlyHints.d.ts +18 -0
  124. package/dist/modules/ssr/handler.d.ts +4 -2
  125. package/dist/modules/ssr/loadPluginComponents.d.ts +2 -1
  126. package/dist/modules/ssr/meterPage.d.ts +4 -0
  127. package/dist/modules/ssr/pageCache.d.ts +47 -0
  128. package/dist/modules/ssr/prepareRender.d.ts +11 -3
  129. package/dist/modules/ssr/preview.d.ts +5 -3
  130. package/dist/modules/ssr/redisPageStore.d.ts +29 -0
  131. package/dist/modules/ssr/registerExternalPlugins.d.ts +1 -1
  132. package/dist/modules/ssr/renderTurns.d.ts +34 -0
  133. package/dist/modules/ssr/reportMissingPlugins.d.ts +0 -7
  134. package/dist/modules/ssr/scriptPolicy.d.ts +39 -0
  135. package/dist/modules/ssr/spaceDocument.d.ts +25 -2
  136. package/dist/modules/ssr/streamBody.d.ts +9 -3
  137. package/dist/modules/ssr/styleSheet.d.ts +15 -0
  138. package/dist/modules/ssr/template.d.ts +8 -1
  139. package/dist/oauth.js +139 -9
  140. package/dist/platform.d.ts +6 -0
  141. package/dist/platform.js +1 -0
  142. package/dist/project.js +939 -1
  143. package/dist/spaces.d.ts +7 -0
  144. package/dist/spaces.js +1 -0
  145. package/dist/ssr.d.ts +1 -2
  146. package/dist/ssr.js +1 -4
  147. package/dist/types/config.d.ts +252 -0
  148. package/dist/types/index.d.ts +2 -0
  149. package/dist/types/server.d.ts +111 -0
  150. package/package.json +41 -83
  151. package/skills/plitzi-authoring/recipes/server-data.ts +4 -0
  152. package/skills/plitzi-authoring/reference/accessibility.md +9 -2
  153. package/skills/plitzi-authoring/reference/auth.md +6 -1
  154. package/skills/plitzi-authoring/reference/authoring-errors.md +7 -4
  155. package/skills/plitzi-authoring/reference/flows.md +9 -9
  156. package/skills/plitzi-authoring/reference/kept-state.md +12 -0
  157. package/skills/plitzi-authoring/reference/lists.md +7 -1
  158. package/skills/plitzi-authoring/reference/plugins.md +5 -2
  159. package/skills/plitzi-authoring/reference/testing.md +3 -3
  160. package/dist/actions.d.ts +0 -87
  161. package/dist/actions.js +0 -23
  162. package/dist/adapters/authAdapters.js +0 -12
  163. package/dist/adapters/cloudAdapters.js +0 -364
  164. package/dist/adapters/jsonAdapters.js +0 -88
  165. package/dist/adapters/space/index.js +0 -122
  166. package/dist/adapters/space/resolvers.js +0 -79
  167. package/dist/adapters/space/types.js +0 -41
  168. package/dist/core/auth/api/accounts.js +0 -175
  169. package/dist/core/auth/api/admin.js +0 -146
  170. package/dist/core/auth/api/context.js +0 -262
  171. package/dist/core/auth/api/factors.js +0 -209
  172. package/dist/core/auth/api/index.js +0 -43
  173. package/dist/core/auth/api/profile.js +0 -243
  174. package/dist/core/auth/api/session.js +0 -312
  175. package/dist/core/auth/api/values.js +0 -90
  176. package/dist/core/auth/authorize.d.ts +0 -96
  177. package/dist/core/auth/authorize.js +0 -92
  178. package/dist/core/auth/createAuth.js +0 -216
  179. package/dist/core/auth/credentials.d.ts +0 -40
  180. package/dist/core/auth/credentials.js +0 -56
  181. package/dist/core/auth/csrf.d.ts +0 -143
  182. package/dist/core/auth/csrf.js +0 -295
  183. package/dist/core/auth/domains.d.ts +0 -41
  184. package/dist/core/auth/domains.js +0 -78
  185. package/dist/core/auth/identity.d.ts +0 -118
  186. package/dist/core/auth/identity.js +0 -194
  187. package/dist/core/auth/oauth/client.js +0 -52
  188. package/dist/core/auth/oauth/index.js +0 -130
  189. package/dist/core/auth/oauth/providers/github.js +0 -48
  190. package/dist/core/auth/oauth/providers/google.js +0 -30
  191. package/dist/core/auth/oauth/providers/oidc.js +0 -197
  192. package/dist/core/auth/oauth/state.js +0 -57
  193. package/dist/core/auth/oauth/types.js +0 -16
  194. package/dist/core/auth/passwords.d.ts +0 -15
  195. package/dist/core/auth/passwords.js +0 -32
  196. package/dist/core/auth/redirects.js +0 -31
  197. package/dist/core/auth/renewal.js +0 -24
  198. package/dist/core/auth/session.d.ts +0 -194
  199. package/dist/core/auth/session.js +0 -237
  200. package/dist/core/auth/sessionActivity.d.ts +0 -11
  201. package/dist/core/auth/sessionActivity.js +0 -14
  202. package/dist/core/auth/spaceTokens.d.ts +0 -173
  203. package/dist/core/auth/spaceTokens.js +0 -264
  204. package/dist/core/auth/tokens.d.ts +0 -224
  205. package/dist/core/auth/tokens.js +0 -264
  206. package/dist/core/auth/totp.js +0 -123
  207. package/dist/core/configSeam.d.ts +0 -10
  208. package/dist/core/configSeam.js +0 -151
  209. package/dist/core/createServer.js +0 -119
  210. package/dist/core/fontStore.js +0 -53
  211. package/dist/core/freePort.d.ts +0 -24
  212. package/dist/core/freePort.js +0 -74
  213. package/dist/core/handlers/authMiddleware.js +0 -38
  214. package/dist/core/handlers/authRouteHandlers.js +0 -112
  215. package/dist/core/handlers/csrfMiddleware.js +0 -56
  216. package/dist/core/handlers/oauthRouteHandlers.js +0 -161
  217. package/dist/core/handlers/socialRouteHandlers.js +0 -169
  218. package/dist/core/health.d.ts +0 -21
  219. package/dist/core/health.js +0 -40
  220. package/dist/core/http/dispatcher.d.ts +0 -15
  221. package/dist/core/http/dispatcher.js +0 -115
  222. package/dist/core/http/navigation.d.ts +0 -14
  223. package/dist/core/http/navigation.js +0 -19
  224. package/dist/core/http/securityHeaders.d.ts +0 -2
  225. package/dist/core/http/securityHeaders.js +0 -17
  226. package/dist/core/http/socketResponse.d.ts +0 -18
  227. package/dist/core/http/socketResponse.js +0 -59
  228. package/dist/core/http/sse.d.ts +0 -26
  229. package/dist/core/http/sse.js +0 -78
  230. package/dist/core/http/stages/authApi.js +0 -66
  231. package/dist/core/http/stages/authRoutes.js +0 -116
  232. package/dist/core/http/stages/crossSiteWrites.d.ts +0 -24
  233. package/dist/core/http/stages/crossSiteWrites.js +0 -45
  234. package/dist/core/http/stages/exchangeRoute.js +0 -69
  235. package/dist/core/http/stages/fontAssets.js +0 -27
  236. package/dist/core/http/stages/health.d.ts +0 -11
  237. package/dist/core/http/stages/health.js +0 -34
  238. package/dist/core/http/stages/images.js +0 -49
  239. package/dist/core/http/stages/livePages.js +0 -80
  240. package/dist/core/http/stages/middlewares.d.ts +0 -2
  241. package/dist/core/http/stages/middlewares.js +0 -23
  242. package/dist/core/http/stages/oauth.js +0 -118
  243. package/dist/core/http/stages/pluginAssets.js +0 -21
  244. package/dist/core/http/stages/sessionRenewal.js +0 -82
  245. package/dist/core/http/stages/signInRoute.js +0 -139
  246. package/dist/core/http/stages/static.js +0 -48
  247. package/dist/core/http/types.d.ts +0 -56
  248. package/dist/core/http/webExchange.d.ts +0 -18
  249. package/dist/core/http/webExchange.js +0 -53
  250. package/dist/core/mimeTypes.d.ts +0 -13
  251. package/dist/core/mimeTypes.js +0 -42
  252. package/dist/core/oauth/authorize.js +0 -279
  253. package/dist/core/oauth/challenge.js +0 -33
  254. package/dist/core/oauth/consentPage.js +0 -134
  255. package/dist/core/oauth/issueContext.js +0 -32
  256. package/dist/core/oauth/metadata.js +0 -71
  257. package/dist/core/oauth/params.js +0 -5
  258. package/dist/core/oauth/pkce.js +0 -15
  259. package/dist/core/oauth/records.js +0 -49
  260. package/dist/core/oauth/register.js +0 -76
  261. package/dist/core/oauth/respond.js +0 -59
  262. package/dist/core/oauth/token.js +0 -145
  263. package/dist/core/previewToken.d.ts +0 -21
  264. package/dist/core/previewToken.js +0 -32
  265. package/dist/core/requestParser.d.ts +0 -22
  266. package/dist/core/requestParser.js +0 -79
  267. package/dist/core/sdkAssets.js +0 -46
  268. package/dist/core/server/baseServer.d.ts +0 -30
  269. package/dist/core/server/baseServer.js +0 -106
  270. package/dist/core/server/closeOnSignals.d.ts +0 -28
  271. package/dist/core/server/closeOnSignals.js +0 -47
  272. package/dist/core/server/drain.d.ts +0 -18
  273. package/dist/core/server/drain.js +0 -82
  274. package/dist/core/server/fleet/channel.d.ts +0 -103
  275. package/dist/core/server/fleet/channel.js +0 -191
  276. package/dist/core/server/fleet/link.d.ts +0 -23
  277. package/dist/core/server/fleet/link.js +0 -70
  278. package/dist/core/server/fleet/relay.js +0 -112
  279. package/dist/core/server/fleet/role.d.ts +0 -46
  280. package/dist/core/server/fleet/role.js +0 -59
  281. package/dist/core/server/fleet/stores.d.ts +0 -21
  282. package/dist/core/server/fleet/stores.js +0 -46
  283. package/dist/core/server/fleet/supervisor.d.ts +0 -28
  284. package/dist/core/server/fleet/supervisor.js +0 -120
  285. package/dist/core/server/pageServer.js +0 -124
  286. package/dist/core/services/action.d.ts +0 -11
  287. package/dist/core/services/action.js +0 -123
  288. package/dist/core/services/functionRoutes.d.ts +0 -9
  289. package/dist/core/services/functionRoutes.js +0 -53
  290. package/dist/core/services/realtime.d.ts +0 -8
  291. package/dist/core/services/realtime.js +0 -62
  292. package/dist/core/services/registry.js +0 -47
  293. package/dist/core/services/resolve.js +0 -25
  294. package/dist/core/services/robotsTxt.js +0 -50
  295. package/dist/core/services/rsc.js +0 -13
  296. package/dist/core/services/servedSpace.js +0 -16
  297. package/dist/core/services/sitemapXml.js +0 -37
  298. package/dist/core/services/spaceDocument.js +0 -11
  299. package/dist/core/services/ssr.js +0 -13
  300. package/dist/core/staticFiles.d.ts +0 -3
  301. package/dist/core/staticFiles.js +0 -49
  302. package/dist/core/transports.d.ts +0 -31
  303. package/dist/core/transports.js +0 -61
  304. package/dist/core/unusedPort.d.ts +0 -10
  305. package/dist/core/unusedPort.js +0 -38
  306. package/dist/functions-api.d.ts +0 -679
  307. package/dist/functions.d.ts +0 -21
  308. package/dist/functions.js +0 -6
  309. package/dist/functionsRunner.d.ts +0 -20
  310. package/dist/functionsRunner.js +0 -7
  311. package/dist/helpers/atomicFile.d.ts +0 -10
  312. package/dist/helpers/atomicFile.js +0 -33
  313. package/dist/helpers/buildResponseHelpers.d.ts +0 -21
  314. package/dist/helpers/buildResponseHelpers.js +0 -84
  315. package/dist/helpers/buildServerInfo.js +0 -86
  316. package/dist/helpers/cache/CompressedFileCache.d.ts +0 -18
  317. package/dist/helpers/cache/CompressedFileCache.js +0 -44
  318. package/dist/helpers/cache/TtlCache.d.ts +0 -15
  319. package/dist/helpers/cache/TtlCache.js +0 -57
  320. package/dist/helpers/cache/cacheManager.js +0 -50
  321. package/dist/helpers/cache/defaults.js +0 -9
  322. package/dist/helpers/cache/keys.js +0 -130
  323. package/dist/helpers/cache/serverCaches.js +0 -15
  324. package/dist/helpers/compress.d.ts +0 -20
  325. package/dist/helpers/compress.js +0 -61
  326. package/dist/helpers/debugAuthorization.d.ts +0 -24
  327. package/dist/helpers/debugAuthorization.js +0 -27
  328. package/dist/helpers/escapeHtml.js +0 -13
  329. package/dist/helpers/escapeJson.js +0 -4
  330. package/dist/helpers/fileStore.d.ts +0 -60
  331. package/dist/helpers/fileStore.js +0 -127
  332. package/dist/helpers/flagOverrides.d.ts +0 -30
  333. package/dist/helpers/flagOverrides.js +0 -26
  334. package/dist/helpers/hydrationPayload.js +0 -57
  335. package/dist/helpers/metrics.js +0 -37
  336. package/dist/helpers/normalizePlugins.js +0 -16
  337. package/dist/helpers/offlineDataLoader.js +0 -15
  338. package/dist/helpers/onAbort.d.ts +0 -12
  339. package/dist/helpers/onAbort.js +0 -22
  340. package/dist/helpers/outboundGuard.d.ts +0 -64
  341. package/dist/helpers/outboundGuard.js +0 -218
  342. package/dist/helpers/paintedCookie.js +0 -13
  343. package/dist/helpers/readCookie.js +0 -11
  344. package/dist/helpers/reportReactBuild.js +0 -18
  345. package/dist/helpers/resolveDebugMode.js +0 -13
  346. package/dist/helpers/runMiddlewares.d.ts +0 -2
  347. package/dist/helpers/runMiddlewares.js +0 -21
  348. package/dist/helpers/serverLog.d.ts +0 -37
  349. package/dist/helpers/serverLog.js +0 -116
  350. package/dist/helpers/wsFrame.d.ts +0 -3
  351. package/dist/helpers/wsFrame.js +0 -5
  352. package/dist/hosts/authoringHost/index.js +0 -118
  353. package/dist/hosts/project/agentRuns.js +0 -107
  354. package/dist/hosts/project/laterAsks.js +0 -117
  355. package/dist/hosts/project/plugins.js +0 -185
  356. package/dist/hosts/project/serveProject.js +0 -396
  357. package/dist/hosts/project/spaceFailure.js +0 -86
  358. package/dist/hosts/project/watchSpace.js +0 -86
  359. package/dist/kernel.d.ts +0 -25
  360. package/dist/kernel.js +0 -10
  361. package/dist/middlewares/auth.d.ts +0 -2
  362. package/dist/middlewares/auth.js +0 -10
  363. package/dist/middlewares/basicAuth.d.ts +0 -6
  364. package/dist/middlewares/basicAuth.js +0 -67
  365. package/dist/middlewares/spaceDeployment.d.ts +0 -2
  366. package/dist/middlewares/spaceDeployment.js +0 -17
  367. package/dist/modules/actions/connectorWrite.d.ts +0 -11
  368. package/dist/modules/actions/connectorWrite.js +0 -83
  369. package/dist/modules/actions/index.d.ts +0 -78
  370. package/dist/modules/actions/index.js +0 -129
  371. package/dist/modules/actions/jobs/failureStreak.d.ts +0 -17
  372. package/dist/modules/actions/jobs/failureStreak.js +0 -47
  373. package/dist/modules/actions/jobs/fileQueue.d.ts +0 -34
  374. package/dist/modules/actions/jobs/fileQueue.js +0 -72
  375. package/dist/modules/actions/jobs/index.d.ts +0 -34
  376. package/dist/modules/actions/jobs/index.js +0 -60
  377. package/dist/modules/actions/jobs/later.d.ts +0 -43
  378. package/dist/modules/actions/jobs/later.js +0 -69
  379. package/dist/modules/actions/jobs/memoryQueue.d.ts +0 -33
  380. package/dist/modules/actions/jobs/memoryQueue.js +0 -42
  381. package/dist/modules/actions/jobs/queueDocument.d.ts +0 -14
  382. package/dist/modules/actions/jobs/queueDocument.js +0 -22
  383. package/dist/modules/actions/jobs/queueRules.d.ts +0 -39
  384. package/dist/modules/actions/jobs/queueRules.js +0 -270
  385. package/dist/modules/actions/jobs/scheduler.d.ts +0 -64
  386. package/dist/modules/actions/jobs/scheduler.js +0 -133
  387. package/dist/modules/actions/jobs/schedules.d.ts +0 -23
  388. package/dist/modules/actions/jobs/schedules.js +0 -47
  389. package/dist/modules/actions/jobs/storeClock.d.ts +0 -16
  390. package/dist/modules/actions/jobs/storeClock.js +0 -32
  391. package/dist/modules/actions/jobs/worker.d.ts +0 -67
  392. package/dist/modules/actions/jobs/worker.js +0 -361
  393. package/dist/modules/actions/moduleFor.d.ts +0 -3
  394. package/dist/modules/actions/moduleFor.js +0 -44
  395. package/dist/modules/actions/runtime/check.d.ts +0 -24
  396. package/dist/modules/actions/runtime/check.js +0 -122
  397. package/dist/modules/actions/runtime/credentials.d.ts +0 -10
  398. package/dist/modules/actions/runtime/credentials.js +0 -28
  399. package/dist/modules/actions/runtime/email.d.ts +0 -39
  400. package/dist/modules/actions/runtime/email.js +0 -91
  401. package/dist/modules/actions/runtime/errors.d.ts +0 -42
  402. package/dist/modules/actions/runtime/errors.js +0 -53
  403. package/dist/modules/actions/runtime/fileKv.d.ts +0 -35
  404. package/dist/modules/actions/runtime/fileKv.js +0 -81
  405. package/dist/modules/actions/runtime/flags.d.ts +0 -16
  406. package/dist/modules/actions/runtime/flags.js +0 -49
  407. package/dist/modules/actions/runtime/guards.d.ts +0 -144
  408. package/dist/modules/actions/runtime/guards.js +0 -255
  409. package/dist/modules/actions/runtime/kvChange.d.ts +0 -67
  410. package/dist/modules/actions/runtime/kvChange.js +0 -45
  411. package/dist/modules/actions/runtime/kvList.d.ts +0 -55
  412. package/dist/modules/actions/runtime/kvList.js +0 -56
  413. package/dist/modules/actions/runtime/kvStore.d.ts +0 -35
  414. package/dist/modules/actions/runtime/kvStore.js +0 -81
  415. package/dist/modules/actions/runtime/limits.d.ts +0 -11
  416. package/dist/modules/actions/runtime/limits.js +0 -35
  417. package/dist/modules/actions/runtime/memoryKv.d.ts +0 -28
  418. package/dist/modules/actions/runtime/memoryKv.js +0 -110
  419. package/dist/modules/actions/runtime/namespaceKv.d.ts +0 -9
  420. package/dist/modules/actions/runtime/namespaceKv.js +0 -35
  421. package/dist/modules/actions/runtime/precheck.d.ts +0 -27
  422. package/dist/modules/actions/runtime/precheck.js +0 -41
  423. package/dist/modules/actions/runtime/projectData.d.ts +0 -18
  424. package/dist/modules/actions/runtime/projectData.js +0 -69
  425. package/dist/modules/actions/runtime/rateLimit.d.ts +0 -26
  426. package/dist/modules/actions/runtime/rateLimit.js +0 -25
  427. package/dist/modules/actions/runtime/redisKv.d.ts +0 -27
  428. package/dist/modules/actions/runtime/redisKv.js +0 -46
  429. package/dist/modules/actions/runtime/renderResolver.d.ts +0 -16
  430. package/dist/modules/actions/runtime/renderResolver.js +0 -240
  431. package/dist/modules/actions/runtime/renderShare.d.ts +0 -12
  432. package/dist/modules/actions/runtime/renderShare.js +0 -70
  433. package/dist/modules/actions/runtime/report.d.ts +0 -14
  434. package/dist/modules/actions/runtime/report.js +0 -23
  435. package/dist/modules/actions/runtime/runAction.d.ts +0 -26
  436. package/dist/modules/actions/runtime/runAction.js +0 -606
  437. package/dist/modules/actions/runtime/runLogger.d.ts +0 -36
  438. package/dist/modules/actions/runtime/runLogger.js +0 -72
  439. package/dist/modules/actions/runtime/scope.d.ts +0 -40
  440. package/dist/modules/actions/runtime/scope.js +0 -129
  441. package/dist/modules/actions/runtime/signing.d.ts +0 -27
  442. package/dist/modules/actions/runtime/signing.js +0 -50
  443. package/dist/modules/actions/runtime/taskContext.d.ts +0 -51
  444. package/dist/modules/actions/runtime/taskContext.js +0 -125
  445. package/dist/modules/actions/runtime/triggers.d.ts +0 -12
  446. package/dist/modules/actions/runtime/triggers.js +0 -14
  447. package/dist/modules/actions/taskCatalog.d.ts +0 -28
  448. package/dist/modules/actions/taskCatalog.js +0 -25
  449. package/dist/modules/actions/tasks/auth.d.ts +0 -2
  450. package/dist/modules/actions/tasks/auth.js +0 -42
  451. package/dist/modules/actions/tasks/builtins.d.ts +0 -10
  452. package/dist/modules/actions/tasks/builtins.js +0 -32
  453. package/dist/modules/actions/tasks/connector.d.ts +0 -2
  454. package/dist/modules/actions/tasks/connector.js +0 -145
  455. package/dist/modules/actions/tasks/db.d.ts +0 -2
  456. package/dist/modules/actions/tasks/db.js +0 -59
  457. package/dist/modules/actions/tasks/email.d.ts +0 -2
  458. package/dist/modules/actions/tasks/email.js +0 -72
  459. package/dist/modules/actions/tasks/flow.d.ts +0 -3
  460. package/dist/modules/actions/tasks/flow.js +0 -282
  461. package/dist/modules/actions/tasks/helpers.d.ts +0 -16
  462. package/dist/modules/actions/tasks/helpers.js +0 -30
  463. package/dist/modules/actions/tasks/http.d.ts +0 -2
  464. package/dist/modules/actions/tasks/http.js +0 -111
  465. package/dist/modules/actions/tasks/kv.d.ts +0 -2
  466. package/dist/modules/actions/tasks/kv.js +0 -146
  467. package/dist/modules/actions/tasks/list.d.ts +0 -2
  468. package/dist/modules/actions/tasks/list.js +0 -154
  469. package/dist/modules/actions/tasks/realtime.d.ts +0 -2
  470. package/dist/modules/actions/tasks/realtime.js +0 -104
  471. package/dist/modules/actions/tasks/registry.d.ts +0 -26
  472. package/dist/modules/actions/tasks/registry.js +0 -63
  473. package/dist/modules/actions/tasks/transform.d.ts +0 -2
  474. package/dist/modules/actions/tasks/transform.js +0 -36
  475. package/dist/modules/actions/transport/callHandler.d.ts +0 -24
  476. package/dist/modules/actions/transport/callHandler.js +0 -296
  477. package/dist/modules/actions/transport/cancelHandler.d.ts +0 -23
  478. package/dist/modules/actions/transport/cancelHandler.js +0 -23
  479. package/dist/modules/actions/transport/catalogHandler.d.ts +0 -21
  480. package/dist/modules/actions/transport/catalogHandler.js +0 -22
  481. package/dist/modules/actions/transport/stream.d.ts +0 -22
  482. package/dist/modules/actions/transport/stream.js +0 -36
  483. package/dist/modules/actions/transport/verifySignature.d.ts +0 -16
  484. package/dist/modules/actions/transport/verifySignature.js +0 -72
  485. package/dist/modules/actions/transport/webhookHandler.d.ts +0 -25
  486. package/dist/modules/actions/transport/webhookHandler.js +0 -207
  487. package/dist/modules/actions/types.d.ts +0 -520
  488. package/dist/modules/connectors/engine.d.ts +0 -47
  489. package/dist/modules/connectors/engine.js +0 -222
  490. package/dist/modules/connectors/getByPath.d.ts +0 -8
  491. package/dist/modules/connectors/getByPath.js +0 -21
  492. package/dist/modules/connectors/index.d.ts +0 -7
  493. package/dist/modules/connectors/projection.d.ts +0 -18
  494. package/dist/modules/connectors/projection.js +0 -108
  495. package/dist/modules/connectors/resolver.d.ts +0 -27
  496. package/dist/modules/connectors/resolver.js +0 -74
  497. package/dist/modules/connectors/types.d.ts +0 -19
  498. package/dist/modules/functions/build.d.ts +0 -27
  499. package/dist/modules/functions/build.js +0 -216
  500. package/dist/modules/functions/capabilities.d.ts +0 -22
  501. package/dist/modules/functions/capabilities.js +0 -435
  502. package/dist/modules/functions/config.d.ts +0 -76
  503. package/dist/modules/functions/config.js +0 -40
  504. package/dist/modules/functions/context.d.ts +0 -20
  505. package/dist/modules/functions/context.js +0 -146
  506. package/dist/modules/functions/contract.d.ts +0 -329
  507. package/dist/modules/functions/contract.js +0 -9
  508. package/dist/modules/functions/driver.d.ts +0 -37
  509. package/dist/modules/functions/driver.js +0 -368
  510. package/dist/modules/functions/jobControl.d.ts +0 -21
  511. package/dist/modules/functions/jobControl.js +0 -43
  512. package/dist/modules/functions/jobs.d.ts +0 -98
  513. package/dist/modules/functions/jobs.js +0 -438
  514. package/dist/modules/functions/load.d.ts +0 -22
  515. package/dist/modules/functions/load.js +0 -49
  516. package/dist/modules/functions/local.d.ts +0 -31
  517. package/dist/modules/functions/local.js +0 -64
  518. package/dist/modules/functions/manifest.d.ts +0 -31
  519. package/dist/modules/functions/manifest.js +0 -337
  520. package/dist/modules/functions/native.d.ts +0 -9
  521. package/dist/modules/functions/native.js +0 -22
  522. package/dist/modules/functions/oauth.d.ts +0 -33
  523. package/dist/modules/functions/oauth.js +0 -360
  524. package/dist/modules/functions/protocol.d.ts +0 -344
  525. package/dist/modules/functions/protocol.js +0 -32
  526. package/dist/modules/functions/routes.d.ts +0 -51
  527. package/dist/modules/functions/routes.js +0 -242
  528. package/dist/modules/functions/runner/messages.d.ts +0 -4
  529. package/dist/modules/functions/runner/messages.js +0 -229
  530. package/dist/modules/functions/runner/remote.d.ts +0 -19
  531. package/dist/modules/functions/runner/remote.js +0 -168
  532. package/dist/modules/functions/runner/service.d.ts +0 -32
  533. package/dist/modules/functions/runner/service.js +0 -255
  534. package/dist/modules/functions/sandbox/guest/bytes.d.ts +0 -27
  535. package/dist/modules/functions/sandbox/guest/bytes.js +0 -108
  536. package/dist/modules/functions/sandbox/guest/crypto.d.ts +0 -47
  537. package/dist/modules/functions/sandbox/guest/crypto.js +0 -144
  538. package/dist/modules/functions/sandbox/guest/events.d.ts +0 -152
  539. package/dist/modules/functions/sandbox/guest/events.js +0 -143
  540. package/dist/modules/functions/sandbox/guest/fetch.d.ts +0 -305
  541. package/dist/modules/functions/sandbox/guest/fetch.js +0 -237
  542. package/dist/modules/functions/sandbox/guest/index.d.ts +0 -28
  543. package/dist/modules/functions/sandbox/guest/index.js +0 -130
  544. package/dist/modules/functions/sandbox/guest/types.d.ts +0 -38
  545. package/dist/modules/functions/sandbox/isolate.d.ts +0 -37
  546. package/dist/modules/functions/sandbox/isolate.js +0 -360
  547. package/dist/modules/functions/sandbox/prelude.d.ts +0 -2
  548. package/dist/modules/functions/sandbox/prelude.js +0 -49
  549. package/dist/modules/functions/scope.d.ts +0 -30
  550. package/dist/modules/functions/scope.js +0 -28
  551. package/dist/modules/functions/space.d.ts +0 -47
  552. package/dist/modules/functions/space.js +0 -185
  553. package/dist/modules/functions/tryEntry.d.ts +0 -9
  554. package/dist/modules/functions/tryEntry.js +0 -49
  555. package/dist/modules/images/allowlist.js +0 -18
  556. package/dist/modules/images/imageProxy.js +0 -291
  557. package/dist/modules/images/transform.js +0 -28
  558. package/dist/modules/mongo/index.d.ts +0 -4
  559. package/dist/modules/mongo/jobQueue.d.ts +0 -38
  560. package/dist/modules/mongo/jobQueue.js +0 -453
  561. package/dist/modules/mongo/kv.d.ts +0 -15
  562. package/dist/modules/mongo/kv.js +0 -129
  563. package/dist/modules/mysql/accounts.d.ts +0 -5
  564. package/dist/modules/mysql/accounts.js +0 -378
  565. package/dist/modules/mysql/admin.d.ts +0 -58
  566. package/dist/modules/mysql/admin.js +0 -133
  567. package/dist/modules/mysql/config.d.ts +0 -82
  568. package/dist/modules/mysql/config.js +0 -30
  569. package/dist/modules/mysql/identities.d.ts +0 -35
  570. package/dist/modules/mysql/identities.js +0 -43
  571. package/dist/modules/mysql/index.d.ts +0 -68
  572. package/dist/modules/mysql/index.js +0 -62
  573. package/dist/modules/mysql/jobs/index.d.ts +0 -5
  574. package/dist/modules/mysql/jobs/jobQueue.d.ts +0 -40
  575. package/dist/modules/mysql/jobs/jobQueue.js +0 -458
  576. package/dist/modules/mysql/jobs/kv.d.ts +0 -18
  577. package/dist/modules/mysql/jobs/kv.js +0 -108
  578. package/dist/modules/mysql/jobs/schema.d.ts +0 -28
  579. package/dist/modules/mysql/jobs/schema.js +0 -109
  580. package/dist/modules/mysql/pool.d.ts +0 -3
  581. package/dist/modules/mysql/pool.js +0 -88
  582. package/dist/modules/mysql/query.d.ts +0 -12
  583. package/dist/modules/mysql/query.js +0 -21
  584. package/dist/modules/mysql/schema.d.ts +0 -43
  585. package/dist/modules/mysql/schema.js +0 -390
  586. package/dist/modules/mysql/sessions.d.ts +0 -23
  587. package/dist/modules/mysql/sessions.js +0 -52
  588. package/dist/modules/mysql/spaceTokens.d.ts +0 -11
  589. package/dist/modules/mysql/spaceTokens.js +0 -59
  590. package/dist/modules/realtime/declarations.d.ts +0 -11
  591. package/dist/modules/realtime/declarations.js +0 -26
  592. package/dist/modules/realtime/failure.d.ts +0 -6
  593. package/dist/modules/realtime/failure.js +0 -11
  594. package/dist/modules/realtime/grants.d.ts +0 -23
  595. package/dist/modules/realtime/grants.js +0 -61
  596. package/dist/modules/realtime/handlers.d.ts +0 -85
  597. package/dist/modules/realtime/handlers.js +0 -266
  598. package/dist/modules/realtime/hub.d.ts +0 -71
  599. package/dist/modules/realtime/hub.js +0 -184
  600. package/dist/modules/realtime/index.d.ts +0 -75
  601. package/dist/modules/realtime/index.js +0 -89
  602. package/dist/modules/realtime/jobs.d.ts +0 -20
  603. package/dist/modules/realtime/jobs.js +0 -41
  604. package/dist/modules/realtime/memoryPubSub.d.ts +0 -10
  605. package/dist/modules/realtime/memoryPubSub.js +0 -43
  606. package/dist/modules/realtime/message.d.ts +0 -3
  607. package/dist/modules/realtime/message.js +0 -5
  608. package/dist/modules/realtime/presence.d.ts +0 -33
  609. package/dist/modules/realtime/presence.js +0 -56
  610. package/dist/modules/realtime/redisPubSub.d.ts +0 -24
  611. package/dist/modules/realtime/redisPubSub.js +0 -36
  612. package/dist/modules/realtime/retained.d.ts +0 -25
  613. package/dist/modules/realtime/retained.js +0 -47
  614. package/dist/modules/realtime/socket.d.ts +0 -30
  615. package/dist/modules/realtime/socket.js +0 -123
  616. package/dist/modules/rsc/connectorRscData.js +0 -79
  617. package/dist/modules/rsc/externalQueryReader.js +0 -43
  618. package/dist/modules/rsc/handler.js +0 -176
  619. package/dist/modules/rsc/matchRscPage.js +0 -26
  620. package/dist/modules/rsc/publicFileResolver.js +0 -73
  621. package/dist/modules/rsc/resolveRscData.js +0 -146
  622. package/dist/modules/runtime/bundle.d.ts +0 -29
  623. package/dist/modules/runtime/bundle.js +0 -117
  624. package/dist/modules/runtime/contract.d.ts +0 -37
  625. package/dist/modules/runtime/contract.js +0 -21
  626. package/dist/modules/runtime/host.d.ts +0 -38
  627. package/dist/modules/runtime/host.js +0 -68
  628. package/dist/modules/runtime/inside.d.ts +0 -36
  629. package/dist/modules/runtime/inside.js +0 -95
  630. package/dist/modules/runtime/runner.d.ts +0 -12
  631. package/dist/modules/runtime/runner.js +0 -48
  632. package/dist/modules/runtime/stages.d.ts +0 -53
  633. package/dist/modules/runtime/stages.js +0 -117
  634. package/dist/modules/sqlite/jobQueue.d.ts +0 -35
  635. package/dist/modules/sqlite/jobQueue.js +0 -56
  636. package/dist/modules/sqlite/kv.d.ts +0 -34
  637. package/dist/modules/sqlite/kv.js +0 -91
  638. package/dist/modules/sqlite/open.d.ts +0 -3
  639. package/dist/modules/sqlite/open.js +0 -13
  640. package/dist/modules/ssr/Component.js +0 -37
  641. package/dist/modules/ssr/applySSRResult.js +0 -54
  642. package/dist/modules/ssr/buildBody.js +0 -35
  643. package/dist/modules/ssr/handler.js +0 -103
  644. package/dist/modules/ssr/loadPluginComponents.js +0 -81
  645. package/dist/modules/ssr/prepareRender.js +0 -332
  646. package/dist/modules/ssr/preview.js +0 -70
  647. package/dist/modules/ssr/registerExternalPlugins.js +0 -111
  648. package/dist/modules/ssr/reportMissingPlugins.js +0 -24
  649. package/dist/modules/ssr/resolvePageSeo.js +0 -41
  650. package/dist/modules/ssr/spaceDocument.js +0 -85
  651. package/dist/modules/ssr/streamBody.js +0 -69
  652. package/dist/modules/ssr/template.js +0 -10
  653. package/dist/mongo.d.ts +0 -25
  654. package/dist/mongo.js +0 -3
  655. package/dist/mysql.d.ts +0 -37
  656. package/dist/mysql.js +0 -7
  657. package/dist/plugins/compile.js +0 -53
  658. package/dist/plugins/copy.js +0 -28
  659. package/dist/plugins/detect.js +0 -9
  660. package/dist/plugins/manager.js +0 -508
  661. package/dist/plugins/validate.js +0 -23
  662. package/dist/plugins/watch.js +0 -79
  663. package/dist/runtime.d.ts +0 -16
  664. package/dist/runtime.js +0 -7
  665. package/dist/sqlite.d.ts +0 -24
  666. package/dist/sqlite.js +0 -3
@@ -0,0 +1,2956 @@
1
+ import { C as draftSessionCookie, E as matchRscPage, S as createMemoryDraftStore, T as invalidatePluginComponentCache, _ as handleSpaceDocument, a as resolveSdkAssetsDir, b as resolveServices, c as applySSRResult, d as withNotFound, f as withRefusal, g as handleCurrentSpace, h as answerCurrentSpacePreflight, i as pageAssets, l as isReusable, n as prepareRender, o as imagesStage, s as Component, t as buildBody, u as renderParamsOf, v as meterPage, w as takeDraftOverride, x as DRAFT_STORE_METHODS, y as resolveRscEndpoint } from "./buildBody-W9D8ySNY.js";
2
+ import { A as shareCache, B as renderLimitOf, C as createOfflineDataLoader, D as cacheLimitsOf, E as normalizePlugins, G as buildCacheManager, H as keepPage, J as keepsVersion, K as buildHtmlCacheKey, L as styleSheetOf, M as destroyServerCaches, O as cacheFilterOf, Q as SCHEME_HINT_HEADER, S as sendScriptPolicy, T as normalizePluginSource, U as pageHtml, V as fromSharedPage, W as toSharedPage, X as ignoredQueryParamsOf, Y as offlineDataCacheKeyOf, Z as renderedQuery, h as escapeHtml, it as requestPaintedState, j as createServerCaches, m as RequestMetrics, q as buildRscCacheKey, rt as DEFAULT_TTL_MS$1, tt as DEFAULT_CACHE_BYTES, v as googleFontsStage, w as reportReactBuild, z as renderLimitFor } from "./core-TlrWmT4B.js";
3
+ import { n as renewForNavigation, t as isDocumentNavigation } from "./renewal-D98v6-Jd.js";
4
+ import { t as compileTemplate } from "./template-M3IEZ6os.js";
5
+ import { n as createMemoryRateLimit, t as RATE_LIMIT_METHODS } from "./throttle-BH7JLIOF.js";
6
+ import { dataDirLookup } from "@plitzi/sdk-kernel/data";
7
+ import { cappedResponse, fetchOutbound, privateOriginsOf } from "@plitzi/sdk-kernel/outbound";
8
+ import { DEFAULT_FAVICON, RSC_FAILURE, collectServerElements, inputProviders, inputReadings, pageAccessOf, pageAccessRefusal, serverInputOf, serverProviderSource, serverQueryOf, serverWhenValues, whenOf, whenProviders, whenUnknownToServer, withholdPages } from "@plitzi/sdk-shared/schema";
9
+ import http from "node:http";
10
+ import https from "node:https";
11
+ import fs, { readFile } from "node:fs/promises";
12
+ import path from "node:path";
13
+ import { PROJECT_DATA_PREFIX } from "@plitzi/sdk-shared/project/paths";
14
+ import { broadcast, configStaticStage, createHttpServer, createMiddlewaresStage, crossSiteWritesStage, fleetRole, fleetStore, healthStage, hostable, isNavigation, makeHandler, onAbort, onBroadcast, openEventStream, publicDirStage, readRawBody, refusedCrossSite, requestAuthority, requestOrigin, resolveCompression, resolveWorkers, safeRedirectTarget, serveStatic, wellKnownStage } from "@plitzi/sdk-kernel/http";
15
+ import { configureServerLog, defaultLogLevel, isLogged, logLevelOf, serverLog } from "@plitzi/sdk-kernel/log";
16
+ import { evaluateRuleGroup } from "@plitzi/sdk-shared/conditions";
17
+ import { getSourceName } from "@plitzi/sdk-shared/dataSource/helpers";
18
+ import { resolveVariables } from "@plitzi/sdk-shared/dataSource/variables";
19
+ import { flagUserFromSSR, flagValues, forcedFlagsFromCookies, requestFlagOverrides, resolveFlags } from "@plitzi/sdk-shared/flags";
20
+ import { sitemapPaths } from "@plitzi/sdk-shared/navigation";
21
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
22
+ import { knowHostDeployment } from "@plitzi/sdk-kernel/deployment";
23
+ import { PREVIEW_TOKEN_PARAM, appendCookies, clearSessionCookies, readCookies, readDraftToken, readRenewalGuard, readSessionHint, readSessionToken, resolveDebugAuthorization, writeRenewalGuard, writeSessionCookies } from "@plitzi/sdk-kernel/identity";
24
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
25
+ import { STYLE_SHEET_PATH, inPluginLayer } from "@plitzi/sdk-shared/style";
26
+ import fs$1, { watch } from "node:fs";
27
+ import { copyFileAtomic, writeFileAtomic } from "@plitzi/sdk-kernel/files";
28
+ import { esbuildBuild } from "@plitzi/sdk-kernel/build";
29
+ import { pluginAssetLoaders, pluginImportQueries } from "@plitzi/sdk-shared/plugins/bundle";
30
+ import { statsStage } from "@plitzi/sdk-kernel/stats";
31
+ import { renderToPipeableStream } from "react-dom/server";
32
+ import { jsx } from "react/jsx-runtime";
33
+ import { Writable } from "node:stream";
34
+ // src/modules/rsc/externalQueryReader.ts
35
+ /** What one answer of another site may carry into a page: the same ceiling an action's response has by default. */
36
+ var EXTERNAL_QUERY_MAX_BYTES = 5e6;
37
+ var originOf = (value, field) => {
38
+ let url;
39
+ try {
40
+ url = new URL(value);
41
+ } catch {
42
+ throw new Error(`rsc.visitorCredentials.${field}: "${value}" is not an origin — write it as https://host:port`);
43
+ }
44
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.origin !== value.replace(/\/$/, "")) throw new Error(`rsc.visitorCredentials.${field}: "${value}" is not an origin — write it as https://host, no path`);
45
+ return url.origin;
46
+ };
47
+ var visitorCredentialsOf = (config) => {
48
+ if (!config) return;
49
+ const origins = new Set(config.origins.map((origin) => originOf(origin, "origins")));
50
+ return {
51
+ origins,
52
+ via: new Map(Object.entries(config.via ?? {}).map(([from, to]) => {
53
+ const origin = originOf(from, "via");
54
+ if (!origins.has(origin)) throw new Error(`rsc.visitorCredentials.via: "${from}" is not one of its origins — name it there first`);
55
+ return [origin, new URL(originOf(to, "via"))];
56
+ })),
57
+ ...config.cookies ? { cookies: new Set(config.cookies) } : {},
58
+ spaces: config.spaces
59
+ };
60
+ };
61
+ /**
62
+ * A request to the deployment's API where this server reaches it (`via`), addressed as the public edge delivers it: to
63
+ * its public host, `https`, from the visitor's address — what the API reads the session's name and the visit from.
64
+ * `fetch` sends the host it connects to whatever `Host` it is given, so the hop is made with `node:http`.
65
+ */
66
+ var throughFetch = (publicUrl, visitorIp) => (input, init = {}) => {
67
+ const url = new URL(input instanceof Request ? input.url : input.toString());
68
+ const headers = Object.fromEntries(new Headers(init.headers).entries());
69
+ headers.host = publicUrl.host;
70
+ headers["x-forwarded-host"] = publicUrl.host;
71
+ headers["x-forwarded-proto"] = publicUrl.protocol.slice(0, -1);
72
+ if (visitorIp) headers["x-forwarded-for"] = visitorIp;
73
+ return new Promise((resolve, reject) => {
74
+ const request = (url.protocol === "https:" ? https : http).request(url, {
75
+ method: init.method ?? "GET",
76
+ headers,
77
+ ...init.signal ? { signal: init.signal } : {}
78
+ }, (answer) => {
79
+ const status = answer.statusCode ?? 502;
80
+ const answered = new Headers();
81
+ Object.entries(answer.headers).forEach(([name, value]) => {
82
+ (Array.isArray(value) ? value : value === void 0 ? [] : [value]).forEach((one) => {
83
+ answered.append(name, one);
84
+ });
85
+ });
86
+ const body = status === 204 || status === 304 ? null : new ReadableStream({
87
+ start: (controller) => {
88
+ answer.on("data", (chunk) => {
89
+ controller.enqueue(new Uint8Array(chunk));
90
+ });
91
+ answer.on("end", () => {
92
+ controller.close();
93
+ });
94
+ answer.on("error", (error) => {
95
+ controller.error(error);
96
+ });
97
+ },
98
+ cancel: () => {
99
+ answer.destroy();
100
+ }
101
+ });
102
+ resolve(new Response(body, {
103
+ status,
104
+ headers: answered
105
+ }));
106
+ });
107
+ request.on("error", reject);
108
+ request.end();
109
+ });
110
+ };
111
+ /** The page request's cookies a provider carries: the ones named, or every one when none are. */
112
+ var cookieOf = (header, names) => {
113
+ if (!header) return;
114
+ if (!names) return header;
115
+ const kept = header.split(";").map((pair) => pair.trim()).filter((pair) => names.has(pair.slice(0, pair.indexOf("=") === -1 ? pair.length : pair.indexOf("="))));
116
+ return kept.length > 0 ? kept.join("; ") : void 0;
117
+ };
118
+ /**
119
+ * A server provider whose `query` is another site's address, asked by the page server while the page is built — so
120
+ * the page arrives with it, as it does with a connector's or an action's answer, rather than drawing empty and
121
+ * filling in once the browser has asked.
122
+ *
123
+ * Asked as the browser would have asked it — GET, the headers the provider declares — and never with what the browser
124
+ * would have added: no cookie, no credential of the visitor's. Every hop is judged by the rule every authored request
125
+ * is (`fetchOutbound`: no private network but the origins the deployment names as its own, every redirect checked),
126
+ * the answer is held to a ceiling, and the element's own budget aborts it. Answered as a browser request publishes,
127
+ * `{ status, data }`; an answer that is not a success, or not JSON, is the provider's error state — as it is in the
128
+ * browser — with why said.
129
+ *
130
+ * But one that says `credentials: 'include'` is asked as the visitor, with their cookies, where the deployment allows
131
+ * it (`visitor`): an API it names, from a space it trusts, reached where it says — and the response is marked as read
132
+ * so (`ctx.readAsVisitor`), which keeps it from every cache. A redirect away from that origin drops the cookies, as
133
+ * the Fetch standard drops them. Anywhere else it is refused with what to change, never asked as a stranger: the
134
+ * answer a stranger gets is not the one the page was written for.
135
+ */
136
+ var externalQueryReader = ({ base = fetch, maxBytes = EXTERNAL_QUERY_MAX_BYTES, outbound, visitor } = {}) => {
137
+ const asVisitor = async (query, { req, spaceId, environment }) => {
138
+ const origin = query.url.origin;
139
+ if (!visitor?.origins.has(origin)) throw new Error(`${origin} is not an API this server asks as the visitor (credentials: 'include') — name it in rsc.visitorCredentials.origins, or ask it from the browser (runtime: 'client')`);
140
+ if (visitor.spaces && !await visitor.spaces({
141
+ spaceId,
142
+ environment
143
+ })) throw new Error(`this space may not ask ${origin} as the visitor (credentials: 'include') — the server does not trust it to (rsc.visitorCredentials.spaces); ask it from the browser (runtime: 'client')`);
144
+ const through = visitor.via.get(origin);
145
+ const url = through ? new URL(`${query.url.pathname}${query.url.search}`, through) : query.url;
146
+ const cookie = cookieOf(req.headers.cookie, visitor.cookies);
147
+ req.ctx.readAsVisitor = true;
148
+ return {
149
+ url,
150
+ base: through ? throughFetch(query.url, req.ip) : base,
151
+ headers: { ...cookie ? { Cookie: cookie } : {} },
152
+ outbound: through ? {
153
+ ...outbound,
154
+ privateOrigins: [...outbound?.privateOrigins ?? [], through.origin]
155
+ } : outbound
156
+ };
157
+ };
158
+ const read = async (query, signal, asker) => {
159
+ const visit = query.asVisitor ? await asVisitor(query, asker) : void 0;
160
+ const response = await fetchOutbound(visit?.base ?? base, visit?.url ?? query.url, {
161
+ method: "GET",
162
+ headers: {
163
+ Accept: "application/json",
164
+ ...query.headers,
165
+ ...visit?.headers
166
+ },
167
+ credentials: "omit",
168
+ signal
169
+ }, visit?.outbound ?? outbound);
170
+ const text = await cappedResponse(response, maxBytes, (message) => /* @__PURE__ */ new Error(`${query.url.href}: ${message}`)).text();
171
+ if (!response.ok) throw new Error(`${query.url.href} answered ${String(response.status)}`);
172
+ let data;
173
+ try {
174
+ data = JSON.parse(text);
175
+ } catch {
176
+ throw new Error(`${query.url.href} did not answer JSON`);
177
+ }
178
+ return {
179
+ status: response.status,
180
+ data
181
+ };
182
+ };
183
+ /**
184
+ * One read per address a render asks: two providers of a page asking the same thing — the dashboard's space page
185
+ * asked its entitlements twice — share the one answer. Per request, so no visitor is answered with another's; each
186
+ * provider keeps its own budget (it stops waiting when its own signal aborts), and the read stops only when no
187
+ * provider waits for it any more.
188
+ */
189
+ const asked = /* @__PURE__ */ new WeakMap();
190
+ return (query, signal, asker) => {
191
+ const reads = asked.get(asker.req) ?? /* @__PURE__ */ new Map();
192
+ asked.set(asker.req, reads);
193
+ const key = JSON.stringify([
194
+ query.url.href,
195
+ query.headers,
196
+ query.asVisitor
197
+ ]);
198
+ let shared = reads.get(key);
199
+ if (!shared || shared.controller.signal.aborted) {
200
+ const controller = new AbortController();
201
+ shared = {
202
+ answer: read(query, controller.signal, asker),
203
+ controller,
204
+ waiting: 0
205
+ };
206
+ reads.set(key, shared);
207
+ }
208
+ return waitFor(shared, signal);
209
+ };
210
+ };
211
+ /** The shared answer for one provider: given up on its own signal, and the read with it once nobody waits. */
212
+ var waitFor = (shared, signal) => {
213
+ if (signal.aborted) return Promise.reject(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
214
+ shared.waiting++;
215
+ return new Promise((resolve, reject) => {
216
+ const leave = () => {
217
+ shared.waiting--;
218
+ if (shared.waiting === 0) shared.controller.abort(signal.reason);
219
+ reject(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
220
+ };
221
+ signal.addEventListener("abort", leave, { once: true });
222
+ shared.answer.then((answer) => {
223
+ signal.removeEventListener("abort", leave);
224
+ resolve(answer);
225
+ }, (error) => {
226
+ signal.removeEventListener("abort", leave);
227
+ reject(error instanceof Error ? error : new Error(String(error)));
228
+ });
229
+ });
230
+ };
231
+ // src/modules/rsc/publicFileResolver.ts
232
+ /** Where a provider's `query` is a path: a URL, a protocol-relative one or one with `{{tokens}}` is not. */
233
+ var pathOf$1 = (query) => {
234
+ if (typeof query !== "string" || !query.startsWith("/") || query.startsWith("//") || query.includes("{{")) return;
235
+ try {
236
+ return decodeURIComponent(query.split(/[?#]/)[0]);
237
+ } catch {
238
+ return;
239
+ }
240
+ };
241
+ /**
242
+ * A server provider whose `query` names a JSON file under `prefix`, read from the same path inside `folder` and handed
243
+ * to the render — answered in the shape a browser request publishes, `{ status, data }`, so a provider reads
244
+ * `<source>.data.<field>` whichever runtime it has. A path outside `prefix`, or one that climbs out of the folder, is
245
+ * not this resolver's, and the element is left as it was; a file not there, or not JSON, is the provider's error state.
246
+ */
247
+ var fileResolver = (folder, prefix) => {
248
+ const root = path.resolve(folder);
249
+ return async ({ element, signal }) => {
250
+ const pathname = pathOf$1(element.attributes.query);
251
+ if (pathname === void 0 || !pathname.startsWith(prefix)) return;
252
+ const file = path.resolve(root, `.${pathname.slice(prefix.length - 1)}`);
253
+ if (!file.startsWith(`${root}${path.sep}`)) return;
254
+ try {
255
+ return {
256
+ status: 200,
257
+ data: JSON.parse(await readFile(file, {
258
+ encoding: "utf8",
259
+ signal
260
+ }))
261
+ };
262
+ } catch {
263
+ return null;
264
+ }
265
+ };
266
+ };
267
+ /**
268
+ * A server provider whose `query` is a file this server serves from `publicDir` — `/hours.json` — read from disk, so
269
+ * the page arrives with the section in it rather than fetching in the browser what the server already has. The same
270
+ * bytes the browser would have fetched.
271
+ */
272
+ var publicFileResolver = (publicDir) => fileResolver(publicDir, "/");
273
+ /**
274
+ * A server provider whose `query` is `/data/<file>`, answered from the space's own data — of the version being
275
+ * rendered, read off the same deployment record an action's run is (`req.ctx.spaceDeployment`), so a published page
276
+ * reads the data it was published with. The lookup is the platform's, or a self-hosted server's `dataDir`
277
+ * (`dataDirLookup`): the data is never served as a file, and what the provider reads is in the page it renders.
278
+ */
279
+ var dataLookupResolver = (getData) => {
280
+ return async ({ element, spaceId, environment, req }) => {
281
+ const pathname = pathOf$1(element.attributes.query);
282
+ if (pathname === void 0 || !pathname.startsWith(PROJECT_DATA_PREFIX)) return;
283
+ const deployment = req.ctx.spaceDeployment;
284
+ const text = (await getData(spaceId, {
285
+ environment: deployment?.environment ?? environment,
286
+ revision: deployment?.revision ?? 0
287
+ }))?.[pathname.slice(PROJECT_DATA_PREFIX.length)];
288
+ if (text === void 0) return null;
289
+ try {
290
+ return {
291
+ status: 200,
292
+ data: JSON.parse(text)
293
+ };
294
+ } catch {
295
+ return null;
296
+ }
297
+ };
298
+ };
299
+ // src/modules/rsc/resolveRscData.ts
300
+ var DEFAULT_ELEMENT_TIMEOUT_MS = 5e3;
301
+ /**
302
+ * Runs one element's resolution against its budget, and CANCELS it when the budget is gone.
303
+ *
304
+ * The race decides what the payload waits for; the abort decides what the server keeps doing. Racing alone left
305
+ * the loser running to its own timeout — for actions, five more seconds of a held slot and an in-flight request
306
+ * per element, for a page that was answered without it.
307
+ */
308
+ var withBudget = async (run, timeoutMs, label, asked) => {
309
+ const controller = new AbortController();
310
+ let timer;
311
+ const releaseAsked = asked ? onAbort(asked, () => controller.abort()) : void 0;
312
+ try {
313
+ return await Promise.race([run(controller.signal), new Promise((_resolve, reject) => {
314
+ timer = setTimeout(() => {
315
+ controller.abort();
316
+ reject(/* @__PURE__ */ new Error(`RSC resolution timed out after ${timeoutMs}ms for ${label} — its section arrives empty. This server gives a section ${timeoutMs} ms (its \`rsc.elementTimeoutMs\`): a producer slower than that is better read from what a schedule keeps (\`kv\`, warmed by a \`trigger: schedule\` action), so the page waits for nothing.`));
317
+ }, timeoutMs);
318
+ })]);
319
+ } finally {
320
+ if (timer) clearTimeout(timer);
321
+ releaseAsked?.();
322
+ }
323
+ };
324
+ /**
325
+ * Resolves the server-side data slices for the page addressed by `req`.
326
+ *
327
+ * The URL is matched against the schema's pages with the same matcher the client router uses, so the element set
328
+ * and the route params are what the browser will see. Each `runtime: 'server'` element resolves independently:
329
+ * a provider that fails or hangs costs its own slice and nothing else.
330
+ */
331
+ var resolveRscData = async ({ schema, req, spaceId, environment, user, ids, resolveElement, flagOverrides, timeoutMs = DEFAULT_ELEMENT_TIMEOUT_MS, signal, sayFailures = false }) => {
332
+ if (schema.rsc?.enabled === false) return {};
333
+ const match = matchRscPage(schema, req.path, user);
334
+ if (!match) return { serverData: {} };
335
+ const { pageId, routeParams } = match;
336
+ const drawn = pageAccessRefusal(pageAccessOf(schema.flat[pageId].attributes), user) !== void 0 ? withholdPages(schema, user).schema : schema;
337
+ const flags = flagValues(resolveFlags(schema.flags, {
338
+ environment,
339
+ hostname: req.hostname,
340
+ routeParams,
341
+ queryParams: req.query,
342
+ user: flagUserFromSSR(user)
343
+ }, flagOverrides));
344
+ const all = collectServerElements(drawn, pageId, void 0, flags);
345
+ const asked = ids ? new Set(ids) : void 0;
346
+ const targets = asked ? all.filter((element) => asked.has(element.id)) : all;
347
+ if (targets.length === 0) return { serverData: {} };
348
+ const painted = requestPaintedState(req, schema.settings, user?.id);
349
+ const templateData = {
350
+ variables: resolveVariables(schema.variables, {
351
+ routeParams,
352
+ queryParams: req.query,
353
+ hostname: req.hostname,
354
+ environment
355
+ }),
356
+ routeParams,
357
+ queryParams: req.query,
358
+ origin: requestOrigin(req) || `${req.protocol}://${req.hostname}`,
359
+ paintedKeys: painted.keys,
360
+ state: painted.state ?? {}
361
+ };
362
+ const byId = new Map(all.map((element) => [element.id, element]));
363
+ const serverIds = new Set(byId.keys());
364
+ const resolving = /* @__PURE__ */ new Map();
365
+ const readingsOf = /* @__PURE__ */ new Map();
366
+ const resolveOne = (element, chain) => {
367
+ const started = resolving.get(element.id);
368
+ if (started) return started;
369
+ const run = async () => {
370
+ const answersOf = async (ids, what) => Object.fromEntries(await Promise.all(ids.filter((id) => id !== element.id && !chain.includes(id)).map(async (id) => {
371
+ const other = byId.get(id);
372
+ return [id, {
373
+ answer: other ? await resolveOne(other, [...chain, element.id]).catch((reason) => {
374
+ if (asked && !asked.has(id)) serverLog.warn("RSC", `element ${element.id}'s ${what} reads ${id}, which failed to resolve`, reason);
375
+ }) : void 0,
376
+ singleRecord: other?.attributes.singleRecord === true
377
+ }];
378
+ })));
379
+ const gate = whenOf(element);
380
+ if (gate && whenUnknownToServer(gate, schema.flat, serverIds).length === 0) {
381
+ const values = serverWhenValues({
382
+ routeParams,
383
+ queryParams: req.query,
384
+ pageId,
385
+ user,
386
+ answers: await answersOf(whenProviders(gate, serverIds), "`when`")
387
+ });
388
+ if (!evaluateRuleGroup(gate, values)) return;
389
+ }
390
+ const reads = await answersOf(inputProviders(element, serverIds), "input");
391
+ const address = {
392
+ routeParams,
393
+ queryParams: req.query
394
+ };
395
+ const providers = Object.fromEntries(Object.entries(reads).map(([id, { answer, singleRecord }]) => [getSourceName("apiContainer", id), serverProviderSource(answer, singleRecord)]));
396
+ const input = serverInputOf(element, address, providers);
397
+ readingsOf.set(element.id, inputReadings(element, address, providers));
398
+ return withBudget((elementSignal) => resolveElement({
399
+ element,
400
+ input,
401
+ flat: schema.flat,
402
+ routeParams,
403
+ queryParams: req.query,
404
+ templateData,
405
+ req,
406
+ spaceId,
407
+ environment,
408
+ user,
409
+ signal: elementSignal
410
+ }), timeoutMs, `element ${element.id}`, signal);
411
+ };
412
+ const promise = run();
413
+ resolving.set(element.id, promise);
414
+ return promise;
415
+ };
416
+ return { serverData: (await Promise.allSettled(targets.map(async (element) => ({
417
+ id: element.id,
418
+ data: await resolveOne(element, [])
419
+ })))).reduce((acum, result, index) => {
420
+ if (result.status === "rejected") {
421
+ if (!signal?.aborted) {
422
+ const reason = result.reason;
423
+ const readings = readingsOf.get(targets[index].id) ?? [];
424
+ const itsInput = readings.length > 0 ? ` — its input: ${readings.join("; ")}` : "";
425
+ if (reason instanceof Error && "refused" in reason && reason.refused === true) serverLog.warn("RSC", `element ${targets[index].id}: ${reason.message}${itsInput}`);
426
+ else serverLog.error("RSC", `element ${targets[index].id} failed to resolve${itsInput}`, reason);
427
+ const said = reason instanceof Error && "said" in reason && typeof reason.said === "string" ? reason.said : void 0;
428
+ if (said !== void 0) acum[targets[index].id] = { [RSC_FAILURE]: said };
429
+ else if (sayFailures) acum[targets[index].id] = { [RSC_FAILURE]: `${reason instanceof Error ? reason.message : String(reason)}${itsInput}` };
430
+ }
431
+ return acum;
432
+ }
433
+ if (result.value.data !== void 0) acum[result.value.id] = result.value.data;
434
+ return acum;
435
+ }, {}) };
436
+ };
437
+ // src/modules/rsc/connectorRscData.ts
438
+ /**
439
+ * `getRscData`, built from the producers the server was already given — connectors, actions, its own static files.
440
+ *
441
+ * Every deployment that served server-driven elements wrote this same adapter: await the render payload, check the
442
+ * schema opted into RSC, then hand `resolveRscData` a resolver over the lookups — all of which are this package's
443
+ * own exports, assembled by the consumer only because nothing assembled them here. That made the lookups a thing
444
+ * you passed twice, once as config and once folded into an adapter, and put a copy of the enabled check in every
445
+ * deployment.
446
+ *
447
+ * Either half may be absent: a space whose server elements all name actions configures no connectors, and an
448
+ * element naming a producer this deployment does not have resolves to nothing rather than to an error — the same
449
+ * answer it gets for a connector the space never created.
450
+ *
451
+ * A deployment that resolves server elements some other way still supplies its own `getRscData`, and that one wins.
452
+ */
453
+ var connectorRscData = ({ engine, publicDir, data, elementTimeoutMs, sayFailures = false, outbound, visitorCredentials }) => {
454
+ const resolvePublicFile = publicDir ? publicFileResolver(publicDir) : void 0;
455
+ const resolveDataFile = data ? dataLookupResolver(data) : void 0;
456
+ const readExternal = externalQueryReader({
457
+ outbound,
458
+ visitor: visitorCredentialsOf(visitorCredentials)
459
+ });
460
+ /**
461
+ * An element names ONE producer, and which one decides how its data is fetched.
462
+ *
463
+ * A connector is the declarative read and stays the default; an action is the read a manifest cannot express; a
464
+ * file of the server's own is the read with no backend at all, and another site's address is asked as the browser
465
+ * would have asked it (`externalQueryResolver`). Checked in that order so an element carrying more
466
+ * than one keeps resolving the way its page already renders, instead of silently changing under them.
467
+ */
468
+ const resolveElement = async (context) => {
469
+ const attributes = context.element.attributes;
470
+ if (attributes.connector || attributes.action) return engine ? engine(context) : void 0;
471
+ const query = serverQueryOf(context.element, context.templateData);
472
+ if (query === void 0) return;
473
+ if (query.kind === "unresolved") throw new Error(`the page server cannot read its query: ${query.why}`);
474
+ if (query.kind === "url") return readExternal(query, context.signal, context);
475
+ const atPath = {
476
+ ...context,
477
+ element: {
478
+ ...context.element,
479
+ attributes: {
480
+ ...context.element.attributes,
481
+ query: query.path
482
+ }
483
+ }
484
+ };
485
+ const fromData = resolveDataFile ? await resolveDataFile(atPath) : void 0;
486
+ const fromFile = fromData !== void 0 ? fromData : resolvePublicFile ? await resolvePublicFile(atPath) : void 0;
487
+ if (fromFile === void 0) throw new Error(`no file of this server's answers ${query.path}`);
488
+ return fromFile;
489
+ };
490
+ return async ({ req, spaceId, environment, user, ids, loadOfflineData, flagOverrides, signal }) => {
491
+ const offlineData = await loadOfflineData();
492
+ if (!offlineData || offlineData.schema.rsc?.enabled === false) return {};
493
+ return resolveRscData({
494
+ schema: offlineData.schema,
495
+ req,
496
+ spaceId,
497
+ environment,
498
+ user,
499
+ ids,
500
+ resolveElement,
501
+ ...flagOverrides ? { flagOverrides } : {},
502
+ ...signal ? { signal } : {},
503
+ ...elementTimeoutMs === void 0 ? {} : { timeoutMs: elementTimeoutMs },
504
+ sayFailures
505
+ });
506
+ };
507
+ };
508
+ // src/core/http/stages/authApi.ts
509
+ var parseBody$1 = (raw, contentType) => {
510
+ if (!raw) return;
511
+ if (typeof contentType === "string" && contentType.includes("application/json")) try {
512
+ return JSON.parse(raw);
513
+ } catch {
514
+ return;
515
+ }
516
+ return Object.fromEntries(new URLSearchParams(raw));
517
+ };
518
+ /**
519
+ * Serves the whole `/auth` surface: signing in and out, renewing before the credential lapses, answering who this
520
+ * is, revoking every session, and whichever of signup and password reset the deployment offers.
521
+ *
522
+ * A page server that stops at login and logout leaves a space unable to keep anybody signed in — the SDK renews
523
+ * against `refreshUrl`, and with nothing there a visitor is signed out the moment their access token ages out. So
524
+ * `createServer({ auth })` mounts these, and a deployment gets the whole cycle rather than the two ends of it.
525
+ *
526
+ * It owns login and logout too, rather than leaving them to the adapter-only stages that can also answer on those
527
+ * paths: those know how to establish a session and nothing about the account behind it, so they can only answer a
528
+ * bodyless 200 where this one returns the grant — the token, its expiry and who it belongs to. Whichever runs is
529
+ * what a caller gets, so having both live meant a signed-in client that could not tell it had signed in.
530
+ * `createServer` stands the adapter-only pair down when an auth kernel is present.
531
+ */
532
+ var createAuthApiStage = (auth, basePath = auth.basePath) => {
533
+ const byPath = new Map(auth.routes.map((route) => [`${basePath}${route.path}`, route]));
534
+ return async (ctx) => {
535
+ const { req, res, raw } = ctx;
536
+ const route = byPath.get(req.path);
537
+ if (!route || route.method !== req.method) return false;
538
+ const decision = await auth.authorize(req, req.path);
539
+ if (!decision.ok) {
540
+ res.setStatus(decision.status);
541
+ res.setHeader("Content-Type", "application/json");
542
+ res.send(JSON.stringify({
543
+ error: "Access Not Authorized",
544
+ reason: decision.reason
545
+ }));
546
+ return true;
547
+ }
548
+ req.body = req.method === "POST" ? await readRawBody(raw) : void 0;
549
+ const authRequest = {
550
+ headers: req.headers,
551
+ hostname: req.hostname,
552
+ query: req.query,
553
+ body: parseBody$1(req.body, req.headers["content-type"]),
554
+ actor: decision.actor
555
+ };
556
+ const outcome = await route.handler(authRequest);
557
+ auth.applySession(req, res, outcome);
558
+ if (isNavigation(req)) {
559
+ res.setStatus(303);
560
+ res.setHeader("Location", outcome.ok ? safeRedirectTarget(req) : req.path);
561
+ res.end();
562
+ return true;
563
+ }
564
+ res.setStatus(outcome.ok ? outcome.status ?? 200 : outcome.status);
565
+ res.setHeader("Content-Type", "application/json");
566
+ res.send(JSON.stringify(outcome.body));
567
+ return true;
568
+ };
569
+ };
570
+ // src/core/http/stages/sessionRenewal.ts
571
+ /** Renewal this close to its deadline is not worth the round trip: it would be refused on arrival. */
572
+ var REFRESH_MARGIN_SECONDS = 30;
573
+ var nowInSeconds = () => Math.floor(Date.now() / 1e3);
574
+ /**
575
+ * This page's own address, absolute, for a renewal served by another host to send the browser back to. The port is
576
+ * read off the authority rather than taken whole, so a forged `Host` cannot put anything but digits after the name.
577
+ */
578
+ var pageUrl = (req) => {
579
+ const authority = requestAuthority(req);
580
+ const port = /:(\d{1,5})$/u.exec(authority)?.[1];
581
+ return `${req.protocol}://${req.hostname}${port ? `:${port}` : ""}${req.path}${req.search}`;
582
+ };
583
+ /**
584
+ * Whether this page request comes from a browser whose session has only half-lapsed.
585
+ *
586
+ * The access cookie dies with its token, while the refresh cookie lives on — confined to the refresh path, so it never
587
+ * reaches a page. Rendered now, the page would be a guest's, and the browser, which renews as soon as it boots, would
588
+ * swap it for the signed-in one: a guest page in the HTML, a different page on screen, and a guest-only page shown
589
+ * and then redirected away from instead of answered with a redirect.
590
+ *
591
+ * The readable hint is what tells the two apart without presenting anything: it outlives the access cookie exactly
592
+ * as long as renewal is still possible. It is also what keeps this from looping — a renewal that succeeds rewrites
593
+ * it with an access expiry in the future, one that is refused clears it, and one that fails any other way leaves the
594
+ * guard cookie behind.
595
+ */
596
+ var halfLapsed = (req, cookie) => {
597
+ if (readSessionToken(req, cookie) !== void 0 || readRenewalGuard(req, cookie)) return false;
598
+ const hint = readSessionHint(req, cookie);
599
+ if (!hint?.refreshExpiresAt) return false;
600
+ const now = nowInSeconds();
601
+ return hint.expiresAt <= now && hint.refreshExpiresAt > now + REFRESH_MARGIN_SECONDS;
602
+ };
603
+ /**
604
+ * Sends a page request from a half-lapsed session to renew first — to `url`, the renewal endpoint — so the server
605
+ * renders the visitor the browser is going to end up with. See `renewForNavigation` for the other half.
606
+ *
607
+ * `url` is a path when this server serves `/auth` itself, and an absolute URL when another host does; the page's
608
+ * own address travels as `redirect` accordingly, and the endpoint only sends the browser back to a host that shares
609
+ * the session's cookies. Only whole-tab `GET` navigations take part: a renewal rotates the session.
610
+ */
611
+ var createSessionRenewalStage = (url) => {
612
+ const sameHost = url.startsWith("/") && !url.startsWith("//");
613
+ const renewalPath = sameHost ? new URL(url, "http://localhost").pathname : void 0;
614
+ return async ({ req, res, config }) => {
615
+ if (req.method !== "GET" || req.path === renewalPath || !isDocumentNavigation(req.headers)) return false;
616
+ if (!halfLapsed(req, config.authCookie)) return false;
617
+ const target = new URL(url, pageUrl(req));
618
+ target.searchParams.set("redirect", sameHost ? `${req.path}${req.search}` : pageUrl(req));
619
+ await knowHostDeployment({
620
+ req,
621
+ config
622
+ });
623
+ writeRenewalGuard(req, res, config.authCookie);
624
+ res.setStatus(303);
625
+ res.setHeader("Cache-Control", "no-store");
626
+ res.setHeader("Location", sameHost ? `${target.pathname}${target.search}` : target.toString());
627
+ res.end();
628
+ return true;
629
+ };
630
+ };
631
+ /**
632
+ * The renewal endpoint, on a page server that serves `/auth` itself: `GET <basePath>/refresh`. The `POST` flow at the
633
+ * same path is the auth API stage's; this one only ever answers a whole-tab navigation.
634
+ */
635
+ var createRenewalEndpointStage = (auth) => {
636
+ const path = `${auth.basePath}/refresh`;
637
+ return async ({ req, res }) => {
638
+ if (req.method !== "GET" || req.path !== path || !isDocumentNavigation(req.headers)) return false;
639
+ const location = await renewForNavigation(req, res, {
640
+ api: auth.api,
641
+ cookies: auth.cookies,
642
+ csrf: auth.csrf
643
+ });
644
+ res.setStatus(303);
645
+ res.setHeader("Cache-Control", "no-store");
646
+ res.setHeader("Location", location);
647
+ res.end();
648
+ return true;
649
+ };
650
+ };
651
+ // src/core/server/relay.ts
652
+ /**
653
+ * `server.cache` and `server.plugins` in a fleet, whose workers each keep their own: what one process is told, every
654
+ * other hears. A single server's are handed back unwrapped (`baseServer.ts`). The call that matters is the one that lands on a random worker — a publish webhook, a
655
+ * `/revalidate` endpoint — and without this it would clear one worker's pages and leave the rest serving the old
656
+ * ones until their TTL ran out.
657
+ *
658
+ * Code that runs in every process (a pub/sub subscription made where the server is created) is told N times; what
659
+ * is relayed is safe to apply again, and cheap: it only drops entries from memory.
660
+ */
661
+ var PLUGIN_ACTIONS = [
662
+ "copy",
663
+ "compile",
664
+ "download",
665
+ "cdn"
666
+ ];
667
+ var isPluginAction = (value) => PLUGIN_ACTIONS.some((action) => action === value);
668
+ var relayCache = (cache, channel) => {
669
+ onBroadcast(channel, (payload) => {
670
+ if (!isRecord(payload)) return;
671
+ if (payload.op === "clear") cache.clear();
672
+ else if (payload.op === "invalidate") cache.invalidate(cacheFilterOf(payload.filter));
673
+ });
674
+ return {
675
+ invalidate: (filter) => {
676
+ const count = cache.invalidate(filter);
677
+ broadcast(channel, {
678
+ op: "invalidate",
679
+ filter: filter ?? {}
680
+ });
681
+ return count;
682
+ },
683
+ clear: () => {
684
+ cache.clear();
685
+ broadcast(channel, { op: "clear" });
686
+ },
687
+ get size() {
688
+ return cache.size;
689
+ }
690
+ };
691
+ };
692
+ var pluginSourceOf = (value) => {
693
+ if (!isRecord(value) || typeof value.js !== "string") return;
694
+ return {
695
+ js: value.js,
696
+ ...typeof value.css === "string" ? { css: value.css } : {},
697
+ ...typeof value.version === "string" ? { version: value.version } : {},
698
+ ...isPluginAction(value.action) ? { action: value.action } : {},
699
+ ...isRecord(value.props) ? { props: value.props } : {}
700
+ };
701
+ };
702
+ var optionalString = (value) => typeof value === "string" ? value : void 0;
703
+ /**
704
+ * A plugin registered or invalidated in one process is registered or forgotten in all of them. The files are
705
+ * shared — the process that invalidated removed them — so the others only drop what they remember (`forget`).
706
+ *
707
+ * A plugin registered with a `component` cannot be sent: a function does not cross between processes. It is
708
+ * registered where it was called, and said so, rather than silently missing from the other workers.
709
+ */
710
+ var relayPlugins = (plugins, forget, channel, label) => {
711
+ onBroadcast(channel, (payload) => {
712
+ if (!isRecord(payload)) return;
713
+ if (payload.op === "register" && typeof payload.name === "string") {
714
+ const source = pluginSourceOf(payload.source);
715
+ if (source) plugins.register(payload.name, source);
716
+ } else if (payload.op === "unregister" && typeof payload.name === "string") plugins.unregister(payload.name);
717
+ else if (payload.op === "forget") forget(optionalString(payload.name), optionalString(payload.version));
718
+ });
719
+ return {
720
+ register: (name, source) => {
721
+ plugins.register(name, source);
722
+ if ("component" in source) {
723
+ serverLog.warn(label, `plugin "${name}" is a component: only this process has it. Register component plugins where the server is created, so every worker does.`);
724
+ return;
725
+ }
726
+ broadcast(channel, {
727
+ op: "register",
728
+ name,
729
+ source
730
+ });
731
+ },
732
+ unregister: (name) => {
733
+ plugins.unregister(name);
734
+ broadcast(channel, {
735
+ op: "unregister",
736
+ name
737
+ });
738
+ },
739
+ invalidate: async (name, version) => {
740
+ await plugins.invalidate(name, version);
741
+ broadcast(channel, {
742
+ op: "forget",
743
+ name,
744
+ version
745
+ });
746
+ }
747
+ };
748
+ };
749
+ // src/core/server/reportCacheSharing.ts
750
+ var megabytes = (bytes) => `${Math.round(bytes / 1048576)} MB`;
751
+ var seconds = (ms) => `${Math.round(ms / 1e3)} s`;
752
+ /**
753
+ * Says once, where the server starts, how its pages are kept and what an invalidation reaches. The case it is there
754
+ * for is the silent one: several replicas and no bus, where a publish is seen by the replica that was told and by the
755
+ * others only when their copies expire. A development server, one process by nature, is not told what it knows.
756
+ */
757
+ var reportCacheSharing = (config, { ttlMs, bus, store }) => {
758
+ if (config.devMode && !bus && !store) return;
759
+ const kept = `Pages are kept ${seconds(ttlMs)} (served ${seconds(config.cache?.staleMs ?? DEFAULT_TTL_MS$1.stale)} more while rendered again), up to ${megabytes(config.cache?.maxBytes ?? DEFAULT_CACHE_BYTES.html)} a process`;
760
+ const where = store ? ", and shared by every replica (cache.store)" : ", each process its own";
761
+ const reach = bus ? "an invalidation reaches every replica (cache.bus)." : "an invalidation reaches this host's processes only — with several replicas, give the server cache.bus (createRedisPubSub) or each serves what a write made untrue until its copy expires.";
762
+ serverLog.info("SSR cache", `${kept}${where}; ${reach}`);
763
+ };
764
+ // src/plugins/compile.ts
765
+ var EXTERNAL = [
766
+ "react",
767
+ "react-dom",
768
+ "react-dom/client",
769
+ "react/jsx-runtime",
770
+ "@plitzi/plitzi-sdk",
771
+ "@plitzi/sdk-shared"
772
+ ];
773
+ /**
774
+ * Everything that went into the bundle, so a server can tell when any of it has moved on: a dev server as it is
775
+ * edited, and any server — a deployment — when it finds a bundle built from something else (its content digest).
776
+ *
777
+ * The entry file is one file and a plugin is a directory: a component edited beside its `index.ts` leaves the entry's
778
+ * timestamp exactly where it was, and a watcher looking only at that never rebuilds. esbuild already knows the answer
779
+ * — this is its own list of inputs — so nothing has to be guessed from the file system.
780
+ *
781
+ * Dependencies are left out. They change when something is installed, which is not an edit anybody is waiting to see,
782
+ * and stat'ing a few thousand files on every cache miss to find that out is a real cost for no answer.
783
+ */
784
+ var sourceInputs = (metafile) => metafile ? Object.keys(metafile.inputs).filter((input) => !input.includes("node_modules")).map((input) => path.resolve(input.replace(/^plitzi-(raw|inline):/, ""))) : [];
785
+ var compilePlugin = async (jsPath, outDir, devMode = false) => {
786
+ const result = await esbuildBuild({
787
+ entryPoints: [jsPath],
788
+ bundle: true,
789
+ format: "esm",
790
+ external: EXTERNAL,
791
+ loader: pluginAssetLoaders(),
792
+ plugins: [pluginImportQueries()],
793
+ outdir: outDir,
794
+ entryNames: "index",
795
+ jsx: "automatic",
796
+ minify: !devMode,
797
+ splitting: false,
798
+ logLevel: "warning",
799
+ metafile: true,
800
+ write: false
801
+ });
802
+ await fs.mkdir(outDir, { recursive: true });
803
+ await Promise.all(result.outputFiles.map((output) => writeFileAtomic(output.path, output.path.endsWith(".css") ? inPluginLayer(output.text) : output.contents)));
804
+ return {
805
+ hasCSS: result.outputFiles.some((output) => path.basename(output.path) === "index.css"),
806
+ inputs: sourceInputs(result.metafile)
807
+ };
808
+ };
809
+ // src/plugins/copy.ts
810
+ var copyPlugin = async (src, destDir, filename) => {
811
+ const dest = path.join(destDir, filename);
812
+ if (src.startsWith("http://") || src.startsWith("https://")) {
813
+ const res = await fetch(src);
814
+ if (!res.ok) throw new Error(`[SSR] Plugin fetch failed ${src}: ${res.status}`);
815
+ await writeFileAtomic(dest, await res.text());
816
+ } else await copyFileAtomic(src, dest);
817
+ };
818
+ /**
819
+ * A plugin's stylesheet, copied or downloaded into the cache in the plugins' cascade layer — below the space's styles,
820
+ * as a compiled one is — whatever the file it came from says.
821
+ */
822
+ var copyPluginStylesheet = async (src, destDir) => {
823
+ let css;
824
+ if (src.startsWith("http://") || src.startsWith("https://")) {
825
+ const res = await fetch(src);
826
+ if (!res.ok) throw new Error(`[SSR] Plugin stylesheet fetch failed ${src}: ${res.status}`);
827
+ css = await res.text();
828
+ } else css = await fs.readFile(src, "utf8");
829
+ await writeFileAtomic(path.join(destDir, "index.css"), inPluginLayer(css));
830
+ };
831
+ // src/plugins/detect.ts
832
+ var isComponentSource = (source) => "component" in source;
833
+ var detectAction = (js) => {
834
+ if (js.startsWith("http://") || js.startsWith("https://")) return "copy";
835
+ if (js.endsWith(".tsx") || js.endsWith(".ts") || js.endsWith(".jsx")) return "compile";
836
+ return "copy";
837
+ };
838
+ // src/plugins/validate.ts
839
+ var isRemote = (js) => js.startsWith("http://") || js.startsWith("https://");
840
+ /** The file a plugin source needs on disk, or null when nothing local is involved — a remote URL (fetched and
841
+ * cached at request time) or a component handed in directly. */
842
+ var localSourcePath = (source) => {
843
+ if (isComponentSource(source) || isRemote(source.js)) return null;
844
+ return source.js;
845
+ };
846
+ /** Fail at boot on a plugin whose entry file is missing. A plugin entry is a plain string path in the server
847
+ * config, so nothing — not tsc, not eslint — notices when that file is moved or deleted; without this check the
848
+ * server starts happily and only dies on the first render that needs the plugin, with an esbuild resolve error
849
+ * far from its cause. */
850
+ var assertPluginSources = (plugins) => {
851
+ const missing = Object.entries(plugins).map(([name, source]) => ({
852
+ name,
853
+ file: localSourcePath(source)
854
+ })).filter((entry) => entry.file !== null && !fs$1.existsSync(entry.file)).map((entry) => ` ${entry.name}: ${entry.file ?? ""}`);
855
+ if (missing.length > 0) throw new Error(`Plugin entry file not found (declared in the server config):\n${missing.join("\n")}`);
856
+ };
857
+ // src/plugins/manager.ts
858
+ var META_FILE = "meta.json";
859
+ var DEFAULT_TTL_MS = 6048e5;
860
+ var DEFAULT_CACHE_DIR = "tmp/.sdk-plugins";
861
+ /** How long a rebuild of vanished bundles waits, once none is pending, for another of the same render to be noticed. */
862
+ var RESTORE_SETTLE_MS = 100;
863
+ /** One hash over every input's path and content — a file gone counts as changed, like a file edited. */
864
+ var digestOf = async (files) => {
865
+ const hash = createHash("sha256");
866
+ for (const file of [...files].sort()) {
867
+ hash.update(file);
868
+ hash.update("\0");
869
+ hash.update(await fs.readFile(file).catch(() => Buffer.from("\0missing")));
870
+ }
871
+ return hash.digest("hex");
872
+ };
873
+ /**
874
+ * Whether a key is this plugin — every version of it, or with `version` that one release — counting the sources a
875
+ * render named under it (`name@1.0.0+<identity>`, see {@link PluginManager.ensure}).
876
+ */
877
+ var isKeyOf = (key, name, version) => {
878
+ if (version) return key === `${name}@${version}` || key.startsWith(`${name}@${version}+`);
879
+ return key === name || key.startsWith(`${name}@`);
880
+ };
881
+ /**
882
+ * How often a dev server re-asks whether a cached plugin is still current.
883
+ *
884
+ * The check is a handful of `stat`s and this runs on every render, so it is throttled rather than free — a second is
885
+ * far below what anybody notices between saving a file and reloading a page, and far above per-request.
886
+ */
887
+ var STALE_CHECK_MS = 1e3;
888
+ var PluginManager = class {
889
+ urlPrefix = "/sdk-plugins";
890
+ outputDir;
891
+ plugins;
892
+ ttlMs;
893
+ mem = /* @__PURE__ */ new Map();
894
+ inflight = /* @__PURE__ */ new Map();
895
+ failed = /* @__PURE__ */ new Set();
896
+ /** Maps base plugin name → most recently registered effective key (may include @version) */
897
+ nameIndex = /* @__PURE__ */ new Map();
898
+ devMode = false;
899
+ /** Who is told what each built plugin was built from — a dev server's watcher (`watchPluginSources`). */
900
+ sourceListeners = /* @__PURE__ */ new Set();
901
+ /** The bundles being built again because they vanished from disk under this server — see `restore`. */
902
+ restoring;
903
+ constructor(plugins, cacheDir, ttlMs, devMode = false) {
904
+ assertPluginSources(plugins);
905
+ this.plugins = plugins;
906
+ this.outputDir = path.resolve(process.cwd(), cacheDir ?? DEFAULT_CACHE_DIR);
907
+ this.ttlMs = ttlMs ?? DEFAULT_TTL_MS;
908
+ this.devMode = devMode;
909
+ for (const key of Object.keys(plugins)) {
910
+ const baseName = key.replace(/@[^@]*$/, "");
911
+ this.nameIndex.set(baseName, key);
912
+ }
913
+ }
914
+ /**
915
+ * Tells `listener` the files every built plugin was built from — those built so far, at once, and each one built or
916
+ * found built from now on. Only a compiled plugin has any: a copied or downloaded one is not this server's source.
917
+ */
918
+ onSources(listener) {
919
+ this.sourceListeners.add(listener);
920
+ this.mem.forEach((cached, key) => {
921
+ if (cached.inputs?.length) listener(key, cached.inputs);
922
+ });
923
+ return () => {
924
+ this.sourceListeners.delete(listener);
925
+ };
926
+ }
927
+ /**
928
+ * Builds a plugin again because its source changed — and again after a build that failed, which `prepare` otherwise
929
+ * never retries: the edit that fixes a syntax error is exactly the one a dev server must not ignore.
930
+ */
931
+ async rebuild(name) {
932
+ const key = this.resolveKey(name) ?? name;
933
+ this.mem.delete(key);
934
+ this.failed.delete(key);
935
+ return this.prepare(key);
936
+ }
937
+ remember(key, cached) {
938
+ this.mem.set(key, cached);
939
+ const { inputs } = cached;
940
+ if (inputs?.length) this.sourceListeners.forEach((listener) => {
941
+ listener(key, inputs);
942
+ });
943
+ }
944
+ hasPlugin(name) {
945
+ return this.resolveKey(name) !== null;
946
+ }
947
+ /**
948
+ * A plugin no longer there — its folder removed under a dev server: never built again, nothing of it remembered. A run's
949
+ * preview logged "build failed … Could not resolve" for a plugin a task had deleted, build after build.
950
+ */
951
+ unregister(name) {
952
+ const base = name.replace(/@[^@]*$/, "");
953
+ for (const key of Object.keys(this.plugins).filter((each) => each.replace(/@[^@]*$/, "") === base)) Reflect.deleteProperty(this.plugins, key);
954
+ this.forget(base);
955
+ }
956
+ register(name, source) {
957
+ this.plugins[name] = source;
958
+ this.mem.delete(name);
959
+ this.failed.delete(name);
960
+ const baseName = name.replace(/@[^@]*$/, "");
961
+ this.nameIndex.set(baseName, name);
962
+ }
963
+ /**
964
+ * Keeps a source a render names, and returns the key to pass to getEntries(): `name@version+<identity>`, or
965
+ * `name@<identity>` without a version.
966
+ *
967
+ * The identity is what the source IS — where its files are, how they are served, the props it carries — because a
968
+ * name and a version are only what its author said about it. Keyed on those alone, the first source to arrive held
969
+ * the key for as long as the process ran: a plugin published again under the same version kept its old, now missing
970
+ * URLs, and two spaces each with a `board@1.0.0` of their own were served whichever this process had met first.
971
+ * Worked out from the source rather than handed out in order of arrival, so every worker names one source the same
972
+ * way — the key is also the folder a built bundle is written to, and all of them share it.
973
+ *
974
+ * Never taken as what a bare name means: {@link resolveKey} answers for the plugins this server was set up with, not
975
+ * for whichever space rendered last.
976
+ */
977
+ ensure(name, source) {
978
+ const identity = createHash("sha256").update(JSON.stringify([
979
+ source.js,
980
+ source.css,
981
+ isComponentSource(source) ? void 0 : source.action,
982
+ source.props
983
+ ])).digest("hex").slice(0, 12);
984
+ const key = `${name}@${source.version ? `${source.version}+` : ""}${identity}`;
985
+ if (!(key in this.plugins)) this.plugins[key] = source;
986
+ return key;
987
+ }
988
+ /**
989
+ * Resolves a caller-supplied name to the effective key stored in the plugins map.
990
+ * Accepts both the exact key (`plitziBuilder@1.0.0`) and the base name (`plitziBuilder`).
991
+ */
992
+ resolveKey(name) {
993
+ if (name in this.plugins) return name;
994
+ const indexed = this.nameIndex.get(name);
995
+ if (indexed && indexed in this.plugins) return indexed;
996
+ return null;
997
+ }
998
+ pluginDir(name) {
999
+ return path.join(this.outputDir, name);
1000
+ }
1001
+ isExpired(compiledAt) {
1002
+ return Date.now() - compiledAt > this.ttlMs;
1003
+ }
1004
+ /**
1005
+ * Whether anything the bundle was built from has moved on since. Dev mode only.
1006
+ *
1007
+ * The cache is keyed on time and version, neither of which changes when somebody edits a component: a versioned
1008
+ * plugin never expires and an unversioned one lasts a week, so a change to the source showed up nowhere and the
1009
+ * server kept serving the bundle it built the first time. In production that is exactly right — a deployment's
1010
+ * plugins do not change under it — and while somebody is writing one it is a file that appears to do nothing.
1011
+ *
1012
+ * Every INPUT, not the entry file. A plugin is a directory and the entry is usually a barrel that re-exports it, so
1013
+ * watching only `source.js` answers "nothing has changed" to every edit anybody actually makes — the file whose
1014
+ * timestamp moves is the component next to it. The list comes from the build itself (see `compilePlugin`), so it is
1015
+ * exactly what went in, including a file imported from another plugin's folder. A bundle built before this existed
1016
+ * has no list, and falls back to the entry file rather than claiming to be fresh.
1017
+ */
1018
+ /**
1019
+ * The same question of the entry this process is holding, asked at most once a second.
1020
+ *
1021
+ * `checkedAt` is stamped on the cached entry rather than kept in a second map, so it cannot outlive what it is about.
1022
+ */
1023
+ async isStaleInMemory(cached, source) {
1024
+ if (!this.devMode) return false;
1025
+ const now = Date.now();
1026
+ if (cached.checkedAt && now - cached.checkedAt < STALE_CHECK_MS) return false;
1027
+ cached.checkedAt = now;
1028
+ return this.isStale({
1029
+ compiledAt: cached.compiledAt,
1030
+ inputs: cached.inputs
1031
+ }, source);
1032
+ }
1033
+ /**
1034
+ * Whether what a bundle on disk was built from reads differently now — asked once, when a process first finds the
1035
+ * bundle, in production as much as in development.
1036
+ *
1037
+ * A version names a release, and a release is only as good as whoever bumps it: a deployment rebuilt from new source
1038
+ * under the same version found last deployment's bundle in its cache folder and served it, with nothing anywhere
1039
+ * saying so. The content decides instead. A bundle written before digests were recorded has none, and is built again
1040
+ * once. What this server does not build from files — a download, a CDN, a component — is its version's business.
1041
+ */
1042
+ async contentChanged(meta, source) {
1043
+ const inputs = this.inputsOf(source, meta.inputs ?? []);
1044
+ if (inputs.length === 0) return false;
1045
+ return meta.digest !== await digestOf(inputs);
1046
+ }
1047
+ /** The local files a bundle is built from: what the compiler reported, or the files it was copied from. */
1048
+ inputsOf(source, compiled) {
1049
+ if (isComponentSource(source) || source.action === "download" || source.action === "cdn") return [];
1050
+ if (compiled.length > 0) return compiled;
1051
+ return [source.js, source.css].filter((file) => typeof file === "string" && file !== "" && !/^https?:\/\//.test(file));
1052
+ }
1053
+ async isStale(meta, source) {
1054
+ if (!this.devMode || !source.js || /^https?:\/\//.test(source.js) || isComponentSource(source)) return false;
1055
+ const watched = meta.inputs?.length ? meta.inputs : [source.js];
1056
+ if (meta.inputs?.length) {
1057
+ const entry = await fs.realpath(source.js).catch(() => path.resolve(source.js));
1058
+ if (!meta.inputs.includes(entry)) return true;
1059
+ }
1060
+ return (await Promise.all(watched.map((file) => fs.stat(file).then((stats) => stats.mtimeMs).catch(() => Number.POSITIVE_INFINITY)))).some((modifiedAt) => modifiedAt > meta.compiledAt);
1061
+ }
1062
+ /**
1063
+ * The bundle's URL, stamped with when it was built.
1064
+ *
1065
+ * Plugin assets are served `immutable` for a year, which is right for a file whose URL identifies its contents
1066
+ * and catastrophic for one whose URL never changes: a browser told a resource is immutable does not revalidate
1067
+ * it at all — no conditional request, no ETag — so a rebuilt plugin never reaches anyone who had already loaded
1068
+ * the old one. Not a stale render either: the page's own CSS is fresh while the plugin's is a year old, and the
1069
+ * two disagree in ways nobody can read. The stamp is what makes the promise true.
1070
+ */
1071
+ assetUrl(name, file, compiledAt) {
1072
+ return `${this.urlPrefix}/${name}/${file}?v=${compiledAt.toString(36)}`;
1073
+ }
1074
+ toEntry(name, hasJS, cssUrl, props = {}, compiledAt = 0) {
1075
+ const keyName = name.split("@")[0];
1076
+ return {
1077
+ name,
1078
+ varName: keyName.split("-").join("_").split(".").join("_"),
1079
+ keyName,
1080
+ js: hasJS ? this.assetUrl(name, "index.js", compiledAt) : void 0,
1081
+ filePath: hasJS ? path.join(this.outputDir, name, "index.js") : void 0,
1082
+ css: cssUrl,
1083
+ props
1084
+ };
1085
+ }
1086
+ /**
1087
+ * A plugin served from where it was published, with nothing on this server's disk.
1088
+ *
1089
+ * No `filePath`, which is the whole point: `loadPluginComponents` only imports entries that have one, so a
1090
+ * bundle this server did not build never enters the render process — and cannot bring a second copy of React
1091
+ * in with it. The template already imports `js` in the browser, so the plugin still renders, just on the
1092
+ * client.
1093
+ */
1094
+ toRemoteEntry(name, source) {
1095
+ const keyName = name.split("@")[0];
1096
+ return {
1097
+ name,
1098
+ varName: keyName.split("-").join("_").split(".").join("_"),
1099
+ keyName,
1100
+ js: source.js,
1101
+ css: source.css,
1102
+ props: source.props ?? {}
1103
+ };
1104
+ }
1105
+ isWebUrl(s) {
1106
+ return s.startsWith("/") || s.startsWith("http://") || s.startsWith("https://");
1107
+ }
1108
+ /**
1109
+ * Builds every registered plugin now rather than on first use. A primary does it before starting its workers, so
1110
+ * the workers find each one built — instead of all of them compiling the same plugin into the same folder at once.
1111
+ */
1112
+ async prepareAll() {
1113
+ await Promise.all(Object.keys(this.plugins).map((key) => this.prepare(key)));
1114
+ }
1115
+ async prepare(name) {
1116
+ const key = this.resolveKey(name) ?? name;
1117
+ if (this.failed.has(key)) return null;
1118
+ const inflight = this.inflight.get(key);
1119
+ if (inflight !== void 0) return inflight;
1120
+ const source = this.plugins[key];
1121
+ if (source === void 0) return null;
1122
+ if (isComponentSource(source) && !source.js) return this.toEntry(key, false, void 0, source.props);
1123
+ if (!isComponentSource(source) && source.action === "cdn") return this.toRemoteEntry(key, source);
1124
+ const cached = this.mem.get(key);
1125
+ let missing = false;
1126
+ if (cached && !this.isExpired(cached.compiledAt)) {
1127
+ if (await this.fileExists(path.join(this.pluginDir(key), "index.js"))) {
1128
+ /**
1129
+ * The disk check below never runs while this process holds the entry in memory, and a versioned plugin never
1130
+ * expires — so without this a dev server serves the bundle it built when it started, for as long as it runs.
1131
+ * Nothing else brings it back either: the components are named by PATH rather than imported, so editing one
1132
+ * does not even restart the watcher.
1133
+ */
1134
+ if (!await this.isStaleInMemory(cached, source)) return cached.entry;
1135
+ serverLog.info("SSR", `Plugin "${key}" source changed since it was built, rebuilding…`);
1136
+ this.mem.delete(key);
1137
+ await fs.rm(this.pluginDir(key), {
1138
+ recursive: true,
1139
+ force: true
1140
+ });
1141
+ } else {
1142
+ serverLog.info("SSR", `Plugin "${key}" output missing, rebuilding…`);
1143
+ this.mem.delete(key);
1144
+ missing = true;
1145
+ }
1146
+ }
1147
+ const meta = await this.readMeta(key);
1148
+ if (meta) {
1149
+ const sourceVersion = source.version;
1150
+ if (await this.isStale(meta, source) || await this.contentChanged(meta, source)) {
1151
+ serverLog.info("SSR", `Plugin "${key}" source changed since it was built, rebuilding…`);
1152
+ await fs.rm(this.pluginDir(key), {
1153
+ recursive: true,
1154
+ force: true
1155
+ });
1156
+ } else if (sourceVersion && meta.version !== sourceVersion) {
1157
+ serverLog.info("SSR", `Plugin "${key}" version changed (${meta.version ?? "none"} → ${sourceVersion}), rebuilding…`);
1158
+ await fs.rm(this.pluginDir(key), {
1159
+ recursive: true,
1160
+ force: true
1161
+ });
1162
+ } else if (sourceVersion || !this.isExpired(meta.compiledAt)) {
1163
+ if (await this.fileExists(path.join(this.pluginDir(key), "index.js"))) {
1164
+ const sourceCss = source.css;
1165
+ let cssUrl;
1166
+ if (await this.fileExists(path.join(this.pluginDir(key), "index.css"))) cssUrl = this.assetUrl(key, "index.css", meta.compiledAt);
1167
+ else if (sourceCss && this.isWebUrl(sourceCss)) cssUrl = sourceCss;
1168
+ const entry = this.toEntry(key, true, cssUrl, source.props, meta.compiledAt);
1169
+ this.remember(key, {
1170
+ compiledAt: meta.compiledAt,
1171
+ entry,
1172
+ inputs: meta.inputs
1173
+ });
1174
+ return entry;
1175
+ }
1176
+ }
1177
+ }
1178
+ const promise = this.build(key, source).finally(() => this.inflight.delete(key));
1179
+ this.inflight.set(key, promise);
1180
+ if (missing) this.restore(key, promise);
1181
+ return promise;
1182
+ }
1183
+ /**
1184
+ * Bundles that vanished from disk under a running server are built again as one episode: said once when the first
1185
+ * is noticed and once when the last is built — how many, how long, which failed — at the level it was noticed at.
1186
+ * Said per plugin, it was a warning for each and a "ready" for each at a level a project's terminal does not show,
1187
+ * so the rebuild never said it had finished.
1188
+ */
1189
+ restore(key, build) {
1190
+ if (!this.restoring) {
1191
+ this.restoring = {
1192
+ started: Date.now(),
1193
+ pending: /* @__PURE__ */ new Set(),
1194
+ rebuilt: 0,
1195
+ failed: []
1196
+ };
1197
+ const where = path.relative(process.cwd(), this.outputDir) || this.outputDir;
1198
+ serverLog.warn("SSR", `Plugin bundles missing from ${where}: building them again…`);
1199
+ }
1200
+ const episode = this.restoring;
1201
+ clearTimeout(episode.closing);
1202
+ episode.pending.add(key);
1203
+ build.then((entry) => {
1204
+ episode.pending.delete(key);
1205
+ if (entry) episode.rebuilt += 1;
1206
+ else episode.failed.push(key);
1207
+ if (episode.pending.size > 0) return;
1208
+ episode.closing = setTimeout(() => {
1209
+ if (this.restoring !== episode || episode.pending.size > 0) return;
1210
+ this.restoring = void 0;
1211
+ const seconds = ((Date.now() - episode.started) / 1e3).toFixed(1);
1212
+ const failed = episode.failed.length > 0 ? ` — ${String(episode.failed.length)} failed (${episode.failed.join(", ")}), said above` : "";
1213
+ serverLog.warn("SSR", `Plugin bundles built again: ${String(episode.rebuilt)} in ${seconds}s${failed}`);
1214
+ }, RESTORE_SETTLE_MS);
1215
+ episode.closing.unref();
1216
+ });
1217
+ }
1218
+ async build(name, source) {
1219
+ const dir = this.pluginDir(name);
1220
+ await fs.mkdir(dir, { recursive: true });
1221
+ const jsPath = source.js;
1222
+ const cssPath = source.css;
1223
+ const action = isComponentSource(source) ? source.js ? detectAction(source.js) : void 0 : source.action ?? detectAction(source.js);
1224
+ if (!jsPath || !action) return this.toEntry(name, false, void 0, source.props);
1225
+ serverLog.info("SSR", `Plugin "${name}" building (${action}: ${jsPath})…`);
1226
+ try {
1227
+ let cssUrl;
1228
+ let buildInputs = [];
1229
+ if (action === "compile") {
1230
+ const { hasCSS, inputs } = await compilePlugin(jsPath, dir, this.devMode);
1231
+ buildInputs = inputs;
1232
+ if (hasCSS) cssUrl = `${this.urlPrefix}/${name}/index.css`;
1233
+ else if (cssPath) {
1234
+ if (this.isWebUrl(cssPath)) cssUrl = cssPath;
1235
+ else {
1236
+ await copyPluginStylesheet(cssPath, dir);
1237
+ cssUrl = `${this.urlPrefix}/${name}/index.css`;
1238
+ }
1239
+ }
1240
+ } else if (action === "download") {
1241
+ const jsRes = await fetch(jsPath);
1242
+ if (!jsRes.ok) throw new Error(`HTTP ${jsRes.status} downloading ${jsPath}`);
1243
+ await writeFileAtomic(path.join(dir, "index.js"), await jsRes.text());
1244
+ if (cssPath) {
1245
+ if (cssPath.startsWith("http://") || cssPath.startsWith("https://")) await copyPluginStylesheet(cssPath, dir);
1246
+ else if (this.isWebUrl(cssPath)) cssUrl = cssPath;
1247
+ else await copyPluginStylesheet(cssPath, dir);
1248
+ cssUrl = `${this.urlPrefix}/${name}/index.css`;
1249
+ }
1250
+ } else {
1251
+ await copyPlugin(jsPath, dir, "index.js");
1252
+ if (cssPath) {
1253
+ if (this.isWebUrl(cssPath)) cssUrl = cssPath;
1254
+ else {
1255
+ await copyPluginStylesheet(cssPath, dir);
1256
+ cssUrl = `${this.urlPrefix}/${name}/index.css`;
1257
+ }
1258
+ }
1259
+ }
1260
+ const compiledAt = Date.now();
1261
+ const inputs = this.inputsOf(source, buildInputs);
1262
+ await this.writeMeta(name, {
1263
+ compiledAt,
1264
+ version: source.version,
1265
+ inputs: buildInputs,
1266
+ ...inputs.length > 0 ? { digest: await digestOf(inputs) } : {}
1267
+ });
1268
+ if (cssUrl?.startsWith(this.urlPrefix)) cssUrl = this.assetUrl(name, "index.css", compiledAt);
1269
+ const entry = this.toEntry(name, true, cssUrl, source.props, compiledAt);
1270
+ this.remember(name, {
1271
+ compiledAt,
1272
+ entry,
1273
+ inputs: buildInputs
1274
+ });
1275
+ serverLog.info("SSR", `Plugin "${name}" ready → ${entry.js}`);
1276
+ return entry;
1277
+ } catch (err) {
1278
+ serverLog.error("SSR", `Plugin "${name}" build failed (js: ${source.js ?? "none"})`, err);
1279
+ this.failed.add(name);
1280
+ return null;
1281
+ }
1282
+ }
1283
+ async getEntries(names) {
1284
+ if (names.length === 0) return [];
1285
+ return (await Promise.all(names.map((n) => this.prepare(n)))).filter((e) => e !== null && e.js !== void 0);
1286
+ }
1287
+ getComponents() {
1288
+ const out = {};
1289
+ for (const [name, source] of Object.entries(this.plugins)) if (isComponentSource(source)) out[name.replace(/@[^@]*$/, "")] = source.component;
1290
+ return out;
1291
+ }
1292
+ /**
1293
+ * Drops what this process remembers of a plugin — its entry, its failure, which version its name means — and
1294
+ * leaves the disk alone. What an invalidation elsewhere in the fleet does here: that process removes the files,
1295
+ * and each of the others only has to stop pointing at them.
1296
+ */
1297
+ forget(name, version) {
1298
+ if (!name) {
1299
+ this.mem.clear();
1300
+ this.failed.clear();
1301
+ this.nameIndex.clear();
1302
+ return;
1303
+ }
1304
+ const keysToEvict = /* @__PURE__ */ new Set();
1305
+ for (const key of [
1306
+ ...Object.keys(this.plugins),
1307
+ ...this.mem.keys(),
1308
+ ...this.failed
1309
+ ]) if (isKeyOf(key, name, version)) keysToEvict.add(key);
1310
+ for (const key of keysToEvict) {
1311
+ this.mem.delete(key);
1312
+ this.failed.delete(key);
1313
+ }
1314
+ const indexed = this.nameIndex.get(name);
1315
+ if (indexed !== void 0 && isKeyOf(indexed, name, version)) this.nameIndex.delete(name);
1316
+ }
1317
+ async invalidate(name, version) {
1318
+ this.forget(name, version);
1319
+ if (!name) {
1320
+ await fs.rm(this.outputDir, {
1321
+ recursive: true,
1322
+ force: true
1323
+ });
1324
+ return;
1325
+ }
1326
+ try {
1327
+ const entries = await fs.readdir(this.outputDir);
1328
+ await Promise.all(entries.filter((entry) => isKeyOf(entry, name, version)).map((entry) => fs.rm(path.join(this.outputDir, entry), {
1329
+ recursive: true,
1330
+ force: true
1331
+ })));
1332
+ } catch {}
1333
+ }
1334
+ destroy() {
1335
+ this.mem.clear();
1336
+ this.failed.clear();
1337
+ this.nameIndex.clear();
1338
+ }
1339
+ async readMeta(name) {
1340
+ try {
1341
+ const raw = await fs.readFile(path.join(this.pluginDir(name), META_FILE), "utf-8");
1342
+ return JSON.parse(raw);
1343
+ } catch {
1344
+ return null;
1345
+ }
1346
+ }
1347
+ async writeMeta(name, meta) {
1348
+ await writeFileAtomic(path.join(this.pluginDir(name), META_FILE), JSON.stringify(meta));
1349
+ }
1350
+ async fileExists(p) {
1351
+ return fs.access(p).then(() => true).catch(() => false);
1352
+ }
1353
+ };
1354
+ // src/plugins/watch.ts
1355
+ /** How long a burst of writes — an editor saving, formatting, saving again — is waited out before one rebuild. */
1356
+ var SETTLE_MS = 80;
1357
+ /**
1358
+ * Calls `onChange(key)` when a file a built plugin was built from changes: what a development server rebuilds and
1359
+ * hands to the open pages (`livePages`), without restarting the process that serves them.
1360
+ *
1361
+ * The FOLDERS are watched, not the files. An editor that saves through a temporary file renames it over the old one,
1362
+ * and a watcher on the old file hears nothing after the first save. Which files matter comes from the build itself
1363
+ * (`PluginManager.onSources`), so a file one plugin imports from another's folder belongs to both.
1364
+ *
1365
+ * Returns the function that stops watching.
1366
+ */
1367
+ var watchPluginSources = (manager, onChange) => {
1368
+ /** File → the plugins built from it. */
1369
+ const owners = /* @__PURE__ */ new Map();
1370
+ /** Plugin → the files it was built from, to take its claim back when a build names others. */
1371
+ const claims = /* @__PURE__ */ new Map();
1372
+ const folders = /* @__PURE__ */ new Map();
1373
+ const pending = /* @__PURE__ */ new Map();
1374
+ const changed = (key) => {
1375
+ clearTimeout(pending.get(key));
1376
+ pending.set(key, setTimeout(() => {
1377
+ pending.delete(key);
1378
+ onChange(key);
1379
+ }, SETTLE_MS));
1380
+ };
1381
+ const watchFolder = (folder) => {
1382
+ if (folders.has(folder)) return;
1383
+ try {
1384
+ const watcher = watch(folder, { persistent: false }, (_event, name) => {
1385
+ if (!name) return;
1386
+ owners.get(path.join(folder, name))?.forEach(changed);
1387
+ });
1388
+ watcher.on("error", () => {
1389
+ watcher.close();
1390
+ folders.delete(folder);
1391
+ });
1392
+ folders.set(folder, watcher);
1393
+ } catch {}
1394
+ };
1395
+ const unwatchUnused = () => {
1396
+ const used = new Set([...owners.keys()].map((file) => path.dirname(file)));
1397
+ folders.forEach((watcher, folder) => {
1398
+ if (!used.has(folder)) {
1399
+ watcher.close();
1400
+ folders.delete(folder);
1401
+ }
1402
+ });
1403
+ };
1404
+ const stopListening = manager.onSources((key, inputs) => {
1405
+ (claims.get(key) ?? []).forEach((file) => {
1406
+ const keys = owners.get(file);
1407
+ keys?.delete(key);
1408
+ if (keys?.size === 0) owners.delete(file);
1409
+ });
1410
+ claims.set(key, inputs);
1411
+ inputs.forEach((file) => {
1412
+ owners.set(file, (owners.get(file) ?? /* @__PURE__ */ new Set()).add(key));
1413
+ watchFolder(path.dirname(file));
1414
+ });
1415
+ unwatchUnused();
1416
+ });
1417
+ return () => {
1418
+ stopListening();
1419
+ pending.forEach((timer) => {
1420
+ clearTimeout(timer);
1421
+ });
1422
+ pending.clear();
1423
+ folders.forEach((watcher) => {
1424
+ watcher.close();
1425
+ });
1426
+ folders.clear();
1427
+ };
1428
+ };
1429
+ // src/core/http/stages/livePages.ts
1430
+ /** Where an open page listens for what the server has to tell it: its space changed, a plugin was built again. */
1431
+ var LIVE_PAGES_PATH = "/__plitzi/live";
1432
+ /**
1433
+ * The pages open on this server, told what changed under them without the server restarting.
1434
+ *
1435
+ * - **The space** (`updatePages`): every page showing it swaps it where it stands — its state, scroll and focus kept —
1436
+ * or loads again when it cannot (`replaceSpace` of the SDK's `render`). The edit loop of a project that authors its
1437
+ * space in code (`serveProject` re-authors and hands the new documents over), and a page an agent keeps rewriting
1438
+ * (`createAuthoringHost`'s `update`). A page listens for the space it was drawn with: the host's own, or one draft
1439
+ * (`?__pt=<id>`, named by the page in its listening address — never by the cookie, which one browser shares between
1440
+ * every draft it has open).
1441
+ * - **Everything** (`reloadPages`): every page loads again.
1442
+ * - **A plugin built again** (`plugin`): every page imports the new bundle and swaps it where it is drawn.
1443
+ *
1444
+ * Only with `livePages` on: every open page keeps a connection for it, which a server whose space never changes under
1445
+ * it — a published one, or a platform's — would pay for and get nothing from. The template listens only then too.
1446
+ *
1447
+ * Each connection is greeted with this process's `boot`, and a page that reconnects to a different one loads again: the
1448
+ * server restarted — `start:dev` saw its code change (`main.ts`, its options, its actions, `src/functions/`) — and
1449
+ * what is on screen was built by the one before. Without it the page kept the old plugin until somebody reloaded it,
1450
+ * which reads as "my change did nothing".
1451
+ */
1452
+ var createLivePages = () => {
1453
+ /** Each open page's stream, by the space it shows: `''` the host's own, otherwise the draft's token. */
1454
+ const listening = /* @__PURE__ */ new Map();
1455
+ const boot = randomUUID();
1456
+ const stage = (ctx) => {
1457
+ if (!ctx.config.livePages || ctx.req.path !== "/__plitzi/live") return Promise.resolve(false);
1458
+ const stream = openEventStream(ctx.rawRes, {
1459
+ onAbort: () => listening.delete(stream),
1460
+ retryMs: 1e3
1461
+ });
1462
+ listening.set(stream, ctx.req.query[PREVIEW_TOKEN_PARAM] ?? "");
1463
+ stream.send("hello", { boot });
1464
+ ctx.raw.once("close", () => {
1465
+ listening.delete(stream);
1466
+ stream.close();
1467
+ });
1468
+ return Promise.resolve(true);
1469
+ };
1470
+ return {
1471
+ stage,
1472
+ /** Every page open on this server loads again. */
1473
+ reload: () => listening.forEach((_, stream) => stream.send("reload", {})),
1474
+ /**
1475
+ * The pages showing the host's own space — or, with `draft`, that draft — swap it for `documents` where they stand;
1476
+ * one that cannot loads again. How many pages were told.
1477
+ */
1478
+ update: (documents, { draft = "" } = {}) => {
1479
+ let told = 0;
1480
+ listening.forEach((scope, stream) => {
1481
+ if (scope === draft) {
1482
+ stream.send("space", { documents });
1483
+ told += 1;
1484
+ }
1485
+ });
1486
+ return told;
1487
+ },
1488
+ /**
1489
+ * A plugin built again: every open page imports its new bundle and swaps it where it is drawn (`keyName` is what
1490
+ * the page registered it as), and points its stylesheet at the new one — without loading again.
1491
+ */
1492
+ plugin: ({ keyName, js, css }) => listening.forEach((_, stream) => stream.send("plugin", {
1493
+ key: keyName,
1494
+ js,
1495
+ css
1496
+ })),
1497
+ /** The streams ended — the server is going away, and each page reconnects to whichever comes up next. */
1498
+ close: () => {
1499
+ listening.forEach((_, stream) => stream.close());
1500
+ listening.clear();
1501
+ }
1502
+ };
1503
+ };
1504
+ // src/core/services/servedSpace.ts
1505
+ /**
1506
+ * The space a page at this address renders (no deployment: the server's one space), for a file the server answers from
1507
+ * it — `/robots.txt`, `/sitemap.xml`. A space that cannot be read answers nothing, said in the server's log with the
1508
+ * file it was read for.
1509
+ */
1510
+ var servedSpace = async (ctx, file) => {
1511
+ const { environment = "main", spaceId = 1, revision = 0 } = ctx.req.ctx.spaceDeployment ?? {};
1512
+ if (spaceId === null) return;
1513
+ return ctx.config.adapters.getOfflineData(spaceId, environment, revision).catch((error) => {
1514
+ serverLog.warn("SSR", `${file} answered without the space: space ${String(spaceId)} could not be read`, error);
1515
+ });
1516
+ };
1517
+ // src/core/services/robotsTxt.ts
1518
+ /** What a space that says nothing answers: everything may be crawled. */
1519
+ var DEFAULT_ROBOTS_TXT = "User-agent: *\nAllow: /\n";
1520
+ /**
1521
+ * The crawlers that gather pages to train AI models, by the user agent each reads `/robots.txt` as — what a space that
1522
+ * says `blockAiCrawlers` keeps out. A search engine's own crawler is none of them: Googlebot reads on, Google-Extended
1523
+ * (the one that trains) does not.
1524
+ */
1525
+ var AI_CRAWLERS = [
1526
+ "GPTBot",
1527
+ "ChatGPT-User",
1528
+ "OAI-SearchBot",
1529
+ "ClaudeBot",
1530
+ "anthropic-ai",
1531
+ "Google-Extended",
1532
+ "Applebot-Extended",
1533
+ "CCBot",
1534
+ "PerplexityBot",
1535
+ "Bytespider",
1536
+ "Amazonbot",
1537
+ "meta-externalagent"
1538
+ ];
1539
+ var SITEMAP_LINE = /^\s*sitemap\s*:/im;
1540
+ /**
1541
+ * `/robots.txt`: the space's own (`settings.robotsTxt`) or one that lets crawlers read everything, then — when the space
1542
+ * keeps them out (`settings.blockAiCrawlers`) — a `Disallow: /` for each AI crawler, and the address of its sitemap
1543
+ * unless its own text names one. Never the space's page for an address it has none for: a crawler reads a 404 page as
1544
+ * "no rules", and an HTML page as rules it cannot parse.
1545
+ */
1546
+ var robotsTxtStage = async (ctx) => {
1547
+ const { req } = ctx;
1548
+ if (req.method !== "GET" || req.path !== "/robots.txt") return false;
1549
+ ctx.operation = "robots";
1550
+ const settings = (await servedSpace(ctx, "/robots.txt"))?.schema.settings;
1551
+ const own = settings?.robotsTxt?.trim() ? settings.robotsTxt.trim() : DEFAULT_ROBOTS_TXT.trim();
1552
+ const origin = requestOrigin(req);
1553
+ const sections = [
1554
+ own,
1555
+ ...settings?.blockAiCrawlers ? AI_CRAWLERS.map((agent) => `User-agent: ${agent}\nDisallow: /`) : [],
1556
+ ...origin && !SITEMAP_LINE.test(own) ? [`Sitemap: ${origin}/sitemap.xml`] : []
1557
+ ];
1558
+ ctx.res.setStatus(200);
1559
+ ctx.res.setHeader("Content-Type", "text/plain; charset=utf-8");
1560
+ ctx.res.send(`${sections.join("\n\n")}\n`);
1561
+ return true;
1562
+ };
1563
+ // src/modules/rsc/handler.ts
1564
+ /** Bounds the reflected location: it only ever selects one of this space's own pages, but it is still input. */
1565
+ var MAX_PAGE_LOCATION = 2048;
1566
+ var meterRsc = async (req, config, spaceId, environment, revision, cached) => {
1567
+ if (!config.adapters.meter) return;
1568
+ try {
1569
+ await config.adapters.meter({
1570
+ kind: "rsc_query",
1571
+ cached,
1572
+ req,
1573
+ spaceId,
1574
+ environment,
1575
+ revision
1576
+ });
1577
+ } catch {}
1578
+ };
1579
+ /**
1580
+ * Whether the browser asked for the server's answer as of now — a refresh that exists because something changed (a
1581
+ * write, an explicit reload), which the answer kept for the last `cacheTtlMs` would undo.
1582
+ *
1583
+ * It skips reading the cache, never writing it: the answer it gets is the newest there is, and the next visitor is
1584
+ * served it. Nobody gains anything they could not already have by changing the query string, which misses the cache
1585
+ * as well.
1586
+ */
1587
+ var asksFresh = (req) => (req.headers["cache-control"] ?? "").split(",").some((directive) => directive.trim().toLowerCase() === "no-cache");
1588
+ /** The endpoint's own parameters: what it is asked about, never input to what it resolves. */
1589
+ var ENDPOINT_PARAMS = /* @__PURE__ */ new Set(["location", "ids"]);
1590
+ /**
1591
+ * Rewrites the request to the page the browser is actually on.
1592
+ *
1593
+ * A refresh is issued against `/_rsc`, not against `/blog/my-post`, so resolving straight from `req.path` matches
1594
+ * nothing in `schema.pages` and every client-side refresh silently returns no data. The SDK sends the visitor's
1595
+ * location as `?location=`, and route params plus the page parameter are read from that instead.
1596
+ *
1597
+ * What a refresh asks for besides — the next page of a "load more", a search a provider was reloaded with — rides on
1598
+ * the query string beside `location`, and is read over the location's own query. It used to be dropped with the rest
1599
+ * of the endpoint's query, so a provider paged in place was answered its first page every time.
1600
+ *
1601
+ * Reflecting both is safe by construction: the location is matched against this space's own page list, and the rest
1602
+ * is what the same visitor could have put in the page's own address; the cache key is the whole request, so no answer
1603
+ * is served for a query it was not made for.
1604
+ */
1605
+ /** What a refresh asked for beside the endpoint's own parameters. */
1606
+ var refreshParams = (req) => Object.fromEntries(Object.entries(req.query).filter(([key]) => !ENDPOINT_PARAMS.has(key)));
1607
+ var withPageLocation = (req) => {
1608
+ const location = req.query.location;
1609
+ if (!location || !location.startsWith("/") || location.length > MAX_PAGE_LOCATION) return req;
1610
+ const url = new URL(location, `${req.protocol}://${req.hostname}`);
1611
+ const query = {
1612
+ ...Object.fromEntries(url.searchParams.entries()),
1613
+ ...refreshParams(req)
1614
+ };
1615
+ const search = new URLSearchParams(query).toString();
1616
+ return {
1617
+ ...req,
1618
+ path: url.pathname,
1619
+ search: search ? `?${search}` : "",
1620
+ url: `${url.pathname}${search ? `?${search}` : ""}`,
1621
+ query
1622
+ };
1623
+ };
1624
+ /**
1625
+ * Handles GET /_rsc requests.
1626
+ *
1627
+ * Calls adapters.getRscData to get server-side data for elements marked
1628
+ * runtime:'server' in the schema, then returns a JSON payload. The SDK
1629
+ * client uses this payload to update server-driven portions of the page
1630
+ * without a full navigation.
1631
+ *
1632
+ * Responses are cached server-side (TtlCache) and via Cache-Control headers:
1633
+ * - main environment: no-store (development, always fresh)
1634
+ * - Authenticated requests: Cache-Control: private, max-age=<ttl>
1635
+ * - Unauthenticated requests: Cache-Control: public, max-age=<ttl>
1636
+ * - A request carrying `Cache-Control: no-cache` is resolved again, and its answer replaces the one cached.
1637
+ * - An answer a provider read with the visitor's cookies (`ctx.readAsVisitor`): no-store, and never kept.
1638
+ */
1639
+ var handleRsc = async (req, res, config, _pluginManager, cache, signal) => {
1640
+ if (!config.adapters.getRscData) {
1641
+ res.setStatus(501);
1642
+ res.send(JSON.stringify({ error: "getRscData adapter not configured" }));
1643
+ return;
1644
+ }
1645
+ const { environment = "main", spaceId, revision = 0 } = req.ctx.spaceDeployment ?? {};
1646
+ if (typeof spaceId !== "number") {
1647
+ res.setStatus(400);
1648
+ res.send(JSON.stringify({ error: "Invalid space deployment" }));
1649
+ return;
1650
+ }
1651
+ const idsRaw = req.query.ids;
1652
+ const ids = idsRaw ? idsRaw.split(",").filter(Boolean).slice(0, 50).map((id) => id.slice(0, 128)) : void 0;
1653
+ const idsParam = ids?.join(",");
1654
+ const pageRequest = withPageLocation(req);
1655
+ req.ctx.rscParams = refreshParams(req);
1656
+ /**
1657
+ * Whether this refresh belongs to somebody looking at a draft.
1658
+ *
1659
+ * The page render already refuses to meter or cache a draft, and before draft SESSIONS existed that was the whole
1660
+ * story: a one-shot token was spent by the render, so no refresh could ever carry one. A reusable token can, and a
1661
+ * page left open in a preview asks for data on its own — so without this, iterating on unsaved work would be
1662
+ * billed as live traffic and would show up on the live view as visitors nobody has.
1663
+ *
1664
+ * The token is not resolved here: whether the draft is still in the store decides what the PAGE renders, and a
1665
+ * refresh that arrives a second after it expired is still part of the same preview.
1666
+ */
1667
+ const previewing = readDraftToken(req) !== void 0;
1668
+ /**
1669
+ * A tester forcing flags from the dev tools sees data for features nobody else has on — and must never be handed a
1670
+ * slice resolved without them. Their refreshes go around the cache both ways, like a draft's.
1671
+ */
1672
+ const forcingFlags = Object.keys(forcedFlagsFromCookies(req.headers.cookie, requestAuthority(req))).length > 0;
1673
+ const uncached = previewing || forcingFlags;
1674
+ const ttlMs = config.rsc?.cacheTtlMs ?? DEFAULT_TTL_MS$1.rsc;
1675
+ const isAuthenticated = !!req.ctx.user;
1676
+ const cacheControl = environment === "main" || uncached ? "no-store" : isAuthenticated ? `private, max-age=${Math.floor(ttlMs / 1e3)}` : `public, max-age=${Math.floor(ttlMs / 1e3)}`;
1677
+ const cacheKey = environment !== "main" && !uncached ? buildRscCacheKey(spaceId, environment, revision, req.ctx.user?.id, idsParam, req) : void 0;
1678
+ const cached = cacheKey && !asksFresh(req) ? cache?.get(cacheKey) : void 0;
1679
+ if (!previewing) await meterRsc(req, config, spaceId, environment, revision, !!cached);
1680
+ if (cached) {
1681
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1682
+ res.setHeader("Cache-Control", cacheControl);
1683
+ res.setHeader("X-Cache", "HIT");
1684
+ res.send(cached);
1685
+ return;
1686
+ }
1687
+ const loadOfflineData = createOfflineDataLoader(() => config.adapters.getOfflineData(spaceId, environment, revision));
1688
+ const settings = async () => (await loadOfflineData())?.schema.settings;
1689
+ const flagOverrides = await requestFlagOverrides(config, {
1690
+ cookie: req.headers.cookie,
1691
+ authority: requestAuthority(req)
1692
+ }, {
1693
+ spaceId,
1694
+ environment
1695
+ }, () => resolveDebugAuthorization(config, settings));
1696
+ let rscData;
1697
+ try {
1698
+ rscData = await config.adapters.getRscData({
1699
+ req: pageRequest,
1700
+ spaceId,
1701
+ environment,
1702
+ revision,
1703
+ user: req.ctx.user,
1704
+ ids,
1705
+ loadOfflineData,
1706
+ flagOverrides,
1707
+ ...signal ? { signal } : {}
1708
+ });
1709
+ } catch (err) {
1710
+ serverLog.error("RSC", "getRscData error", err);
1711
+ res.setStatus(500);
1712
+ res.send(JSON.stringify({ error: "RSC data fetch failed" }));
1713
+ return;
1714
+ }
1715
+ const actionRuns = Boolean(req.ctx.actionRuns?.length) && await resolveDebugAuthorization(config, settings) ? req.ctx.actionRuns : void 0;
1716
+ const payload = {
1717
+ version: 1,
1718
+ transport: "json",
1719
+ spaceId,
1720
+ environment,
1721
+ revision,
1722
+ ...rscData,
1723
+ ...actionRuns ? { actionRuns } : {}
1724
+ };
1725
+ const payloadStr = JSON.stringify(payload);
1726
+ const readAsVisitor = req.ctx.readAsVisitor === true;
1727
+ if (cacheKey && !actionRuns?.length && !readAsVisitor) cache?.set(cacheKey, payloadStr);
1728
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1729
+ res.setHeader("Cache-Control", readAsVisitor ? "no-store" : cacheControl);
1730
+ res.setHeader("X-Cache", "MISS");
1731
+ res.send(payloadStr);
1732
+ };
1733
+ // src/core/services/rsc.ts
1734
+ var rscStage = async (ctx) => {
1735
+ const { config, req } = ctx;
1736
+ const rscPath = resolveRscEndpoint(config);
1737
+ if (!rscPath || req.method !== "GET" || req.path !== rscPath) return false;
1738
+ ctx.operation = "rsc";
1739
+ await handleRsc(req, ctx.res, config, ctx.pluginManager, ctx.caches.rsc, ctx.signal);
1740
+ return true;
1741
+ };
1742
+ // src/core/services/sitemapXml.ts
1743
+ var XML_ESCAPES = {
1744
+ "&": "&amp;",
1745
+ "<": "&lt;",
1746
+ ">": "&gt;",
1747
+ "\"": "&quot;",
1748
+ "'": "&apos;"
1749
+ };
1750
+ var escapeXml = (value) => value.replace(/[&<>"']/g, (character) => XML_ESCAPES[character] ?? character);
1751
+ /**
1752
+ * `/sitemap.xml`: every page of the space a search engine may read (`sitemapPaths` — the same pages the builder's map
1753
+ * marks as listed), at this address's origin, so a space answers its own on its own domain and on the platform's.
1754
+ * A space that cannot be read answers an empty list rather than an error: a crawler retries an error, and lists nothing.
1755
+ */
1756
+ var sitemapXmlStage = async (ctx) => {
1757
+ const { req } = ctx;
1758
+ if (req.method !== "GET" || req.path !== "/sitemap.xml") return false;
1759
+ ctx.operation = "sitemap";
1760
+ const schema = (await servedSpace(ctx, "/sitemap.xml"))?.schema;
1761
+ const origin = requestOrigin(req);
1762
+ const urls = schema && origin ? sitemapPaths(schema).map((path) => ` <url><loc>${escapeXml(`${origin}${path}`)}</loc></url>`) : [];
1763
+ ctx.res.setStatus(200);
1764
+ ctx.res.setHeader("Content-Type", "application/xml; charset=utf-8");
1765
+ ctx.res.send([
1766
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
1767
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">",
1768
+ ...urls,
1769
+ "</urlset>",
1770
+ ""
1771
+ ].join("\n"));
1772
+ return true;
1773
+ };
1774
+ // src/core/services/spaceDocument.ts
1775
+ var spaceDocumentStage = async (ctx) => {
1776
+ const { config, req } = ctx;
1777
+ if (req.path === "/_plitzi/space.json") {
1778
+ if (req.method === "OPTIONS") {
1779
+ answerCurrentSpacePreflight(req, ctx.res);
1780
+ return true;
1781
+ }
1782
+ if (req.method !== "GET") return false;
1783
+ ctx.operation = "space";
1784
+ await handleCurrentSpace(req, ctx.res, config, ctx.caches.offlineData);
1785
+ return true;
1786
+ }
1787
+ if (req.method !== "GET" || !req.path.startsWith("/_plitzi/space/")) return false;
1788
+ ctx.operation = "space";
1789
+ await handleSpaceDocument(req, ctx.res, config, ctx.caches.offlineData);
1790
+ return true;
1791
+ };
1792
+ // src/modules/ssr/earlyHints.ts
1793
+ /**
1794
+ * What every page this server renders paints with, as `Link` values: the SDK's stylesheets. Only what is the same
1795
+ * whatever the page turns out to be — the space's own stylesheet is known once it is read — and only what the first
1796
+ * paint waits for: the SDK itself is asked once the page has painted (the bootstrap, `views/template.ejs`), and a
1797
+ * hint for it would put it back on the line beside the stylesheets.
1798
+ */
1799
+ var pageLinks = (config) => {
1800
+ const { cssPath, iconsCssPath } = pageAssets(config.assetVersion);
1801
+ return [`<${cssPath}>; rel=preload; as=style`, `<${iconsCssPath}>; rel=preload; as=style`];
1802
+ };
1803
+ /**
1804
+ * Says what the page will load: the same `Link` on every response, which is what a CDN in front (Cloudflare) keeps to
1805
+ * answer the next request's hints itself — and a `103 Early Hints` where the connection can carry one, sent by the
1806
+ * function this returns, called only when the page is to be rendered. The browser fetches the hinted files while the
1807
+ * server reads the space and renders it, which on a small server is most of what the visitor waits; a kept page is
1808
+ * answered in under a millisecond, and a 103 before it was one more write on the socket for every page served: the
1809
+ * bench served cached pages up to a quarter slower with it.
1810
+ */
1811
+ var pageHints = (config, res) => {
1812
+ if (config.earlyHints === false) return () => void 0;
1813
+ const links = pageLinks(config);
1814
+ res.setHeader("Link", links.join(", "));
1815
+ let sent = false;
1816
+ return () => {
1817
+ if (!sent) {
1818
+ sent = true;
1819
+ res.earlyHints?.(links);
1820
+ }
1821
+ };
1822
+ };
1823
+ // src/modules/ssr/pageCache.ts
1824
+ var LABEL = "SSR cache";
1825
+ /** The key a page is shared under: a digest, so the visitor's token a key holds is never written to a store. */
1826
+ var sharedKeyOf = (key) => createHash("sha256").update(key).digest("base64url");
1827
+ var pageSlot = (config, caches, key, facts, anonymous, compression) => {
1828
+ const store = config.cache?.store;
1829
+ return {
1830
+ caches,
1831
+ key,
1832
+ ...store && anonymous ? { shared: {
1833
+ store,
1834
+ key: sharedKeyOf(key),
1835
+ facts
1836
+ } } : {},
1837
+ ttlMs: config.cacheTtlMs ?? DEFAULT_TTL_MS$1.html,
1838
+ staleMs: config.cache?.staleMs ?? DEFAULT_TTL_MS$1.stale,
1839
+ compression
1840
+ };
1841
+ };
1842
+ /**
1843
+ * The page as kept: this process's copy, else the shared one — taken into this process, so the next request does not
1844
+ * ask the store again. A store that cannot answer is a miss, said in the log: the page is rendered, not refused.
1845
+ */
1846
+ var readPage = async ({ caches, key, shared, ttlMs, staleMs }) => {
1847
+ const local = caches.html?.read(key);
1848
+ if (local) return {
1849
+ page: local.value,
1850
+ stale: local.stale
1851
+ };
1852
+ if (!shared) return;
1853
+ const found = await shared.store.get(shared.key).catch((error) => {
1854
+ serverLog.warn(LABEL, "The shared page store did not answer; the page is rendered here instead", error);
1855
+ });
1856
+ const age = found ? Date.now() - found.renderedAt : Infinity;
1857
+ if (!found || age > ttlMs + staleMs) return;
1858
+ const page = fromSharedPage(found);
1859
+ caches.html?.set(key, page, found.renderedAt);
1860
+ return {
1861
+ page,
1862
+ stale: age > ttlMs
1863
+ };
1864
+ };
1865
+ /** Keeps a page just rendered, here and in the shared store, and hands back what was kept. */
1866
+ var storePage = ({ caches, key, shared, ttlMs, staleMs, compression }, { html, nonce }) => {
1867
+ const page = keepPage(html, compression, nonce);
1868
+ const renderedAt = Date.now();
1869
+ caches.html?.set(key, page, renderedAt);
1870
+ if (shared) shared.store.set(shared.key, toSharedPage(page, renderedAt), shared.facts, ttlMs + staleMs).catch((error) => {
1871
+ serverLog.warn(LABEL, "A page could not be put in the shared page store; the other replicas render it", error);
1872
+ });
1873
+ return page;
1874
+ };
1875
+ /**
1876
+ * Takes on rendering the page, for every request that wants it meanwhile. Taken in the same turn as the look that
1877
+ * found nobody rendering it — with an `await` between the two, every request of a burst found nobody and rendered.
1878
+ */
1879
+ var claimRender = (slot) => {
1880
+ const { rendering } = slot.caches;
1881
+ let settle = () => void 0;
1882
+ const promise = new Promise((resolve) => {
1883
+ settle = resolve;
1884
+ });
1885
+ rendering.set(slot.key, promise);
1886
+ return {
1887
+ keep: (rendered) => {
1888
+ const page = rendered === void 0 ? void 0 : storePage(slot, rendered);
1889
+ settle(page);
1890
+ return page;
1891
+ },
1892
+ release: () => {
1893
+ settle(void 0);
1894
+ if (rendering.get(slot.key) === promise) rendering.delete(slot.key);
1895
+ }
1896
+ };
1897
+ };
1898
+ /** The render another request started for this page, which this one may wait on rather than render it too. */
1899
+ var renderingNow = (slot) => slot.caches.rendering.get(slot.key);
1900
+ // src/modules/ssr/streamBody.tsx
1901
+ var SSR_SENTINEL = "<!--SSR_CONTENT-->";
1902
+ var streamBody = async (req, res, config, spaceId, environment, revision, renderFn, pluginManager, offlineDataCache, keep, metrics, offlineDataOverride, published) => {
1903
+ const prep = await prepareRender(req, config, spaceId, environment, revision, pluginManager, offlineDataCache, metrics, offlineDataOverride, published);
1904
+ const templateStart = metrics ? performance.now() : 0;
1905
+ const fullTemplate = renderFn({
1906
+ ...prep.templateParams,
1907
+ html: SSR_SENTINEL
1908
+ });
1909
+ metrics?.record("template", Math.round(performance.now() - templateStart));
1910
+ const sentinelIdx = fullTemplate.indexOf(SSR_SENTINEL);
1911
+ const head = sentinelIdx >= 0 ? fullTemplate.slice(0, sentinelIdx) : fullTemplate;
1912
+ const tail = sentinelIdx >= 0 ? fullTemplate.slice(sentinelIdx + 18) : "";
1913
+ const result = {};
1914
+ const nonce = prep.templateParams.nonce ?? "";
1915
+ await new Promise((resolve, reject) => {
1916
+ const chunks = keep && prep.cacheable ? [] : null;
1917
+ const writable = new Writable({
1918
+ write(chunk, _enc, cb) {
1919
+ chunks?.push(chunk);
1920
+ res.write(chunk);
1921
+ cb();
1922
+ },
1923
+ final(cb) {
1924
+ const tailBuf = Buffer.from(tail, "utf-8");
1925
+ res.write(tailBuf);
1926
+ res.end();
1927
+ if (chunks && keep && isReusable(result)) keep({
1928
+ html: head + Buffer.concat(chunks).toString("utf-8") + tail,
1929
+ nonce
1930
+ });
1931
+ resolve();
1932
+ cb();
1933
+ }
1934
+ });
1935
+ const reactStart = metrics ? performance.now() : 0;
1936
+ const { pipe, abort } = renderToPipeableStream(/* @__PURE__ */ jsx(Component, {
1937
+ ...prep.componentProps,
1938
+ ssrResult: result
1939
+ }), {
1940
+ onShellReady() {
1941
+ metrics?.record("react", Math.round(performance.now() - reactStart));
1942
+ if (metrics) {
1943
+ res.setHeader("Server-Timing", metrics.toServerTimingHeader());
1944
+ metrics.log(`${req.method} ${req.path}`);
1945
+ }
1946
+ withNotFound(result, prep.notFound);
1947
+ withRefusal(result, prep.refused);
1948
+ if (applySSRResult(res, result, renderParamsOf(req.query))) {
1949
+ abort();
1950
+ resolve();
1951
+ return;
1952
+ }
1953
+ sendScriptPolicy(res, config, nonce, req.ctx.spaceDeployment);
1954
+ res.write(Buffer.from(head, "utf-8"));
1955
+ pipe(writable);
1956
+ },
1957
+ onError(err) {
1958
+ reject(err instanceof Error ? err : new Error(String(err)));
1959
+ }
1960
+ });
1961
+ });
1962
+ };
1963
+ // src/modules/ssr/handler.tsx
1964
+ /**
1965
+ * A page the deployment holds back (`SSRMeterDecision.unavailable`), in the words it chose: 503, kept by nobody — no
1966
+ * cache, no index — and nothing of the space rendered. Light and dark, as the visitor's system is.
1967
+ */
1968
+ var sendUnavailable = (res, said) => {
1969
+ res.setStatus(503);
1970
+ res.setHeader("Cache-Control", "no-store");
1971
+ res.setHeader("X-Robots-Tag", "noindex, nofollow");
1972
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1973
+ res.send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Not available</title><style>:root{color-scheme:light dark}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font:16px/1.5 ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;background:#fff;color:#18181b}@media (prefers-color-scheme:dark){body{background:#09090b;color:#f4f4f5}}main{max-width:520px;padding:24px;text-align:center}</style></head><body><main><p>${escapeHtml(said)}</p></main></body></html>`);
1974
+ };
1975
+ /** How long a page answered busy tells its visitor to wait before asking again, in seconds. */
1976
+ var BUSY_RETRY_AFTER_S = 2;
1977
+ /** The turn of a space with no limit: nothing to give back. */
1978
+ var noTurn = () => void 0;
1979
+ var renderSSR = async (req, res, config, renderFn, pluginManager, caches, published) => {
1980
+ const { environment = "main", spaceId = 1, revision = 0 } = req.ctx.spaceDeployment || {};
1981
+ const devMode = config.devMode ?? false;
1982
+ const limit = renderLimitFor(req.ctx.spaceDeployment, config.renderLimit);
1983
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1984
+ res.setHeader("Accept-CH", SCHEME_HINT_HEADER);
1985
+ res.setHeader("Vary", SCHEME_HINT_HEADER);
1986
+ const hint = pageHints(config, res);
1987
+ const draft = await takeDraftOverride(req, config);
1988
+ const offlineDataOverride = draft?.data;
1989
+ if (draft?.inspected) req.ctx.inspectedDraft = true;
1990
+ if (draft) {
1991
+ /**
1992
+ * Unsaved work, told not to travel.
1993
+ *
1994
+ * `no-store` because every layer between here and the browser would otherwise be free to hand this render to
1995
+ * somebody else, and `noindex` because a draft URL that reaches a crawler puts unpublished copy in a search
1996
+ * result. Neither is a nicety: the whole point of a draft is that it is not the site yet.
1997
+ */
1998
+ res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1999
+ res.setHeader("X-Robots-Tag", "noindex, nofollow");
2000
+ if (draft.reusable) res.setHeader("Set-Cookie", draftSessionCookie(req, draft.token, config.preview?.sessionTtlMs ?? 9e5));
2001
+ }
2002
+ const htmlCache = keepsVersion(req.ctx.spaceDeployment) && !offlineDataOverride ? caches.html : void 0;
2003
+ const ignored = ignoredQueryParamsOf(config);
2004
+ if (htmlCache) req.query = renderedQuery(req.query, ignored);
2005
+ const compression = resolveCompression(config.compression);
2006
+ const slot = htmlCache ? pageSlot(config, caches, buildHtmlCacheKey(req.ctx.user?.token, spaceId, environment, revision, req, ignored), {
2007
+ spaceId,
2008
+ environment,
2009
+ hostname: req.hostname
2010
+ }, req.ctx.user === void 0, compression) : void 0;
2011
+ const renderPage = (metrics) => () => buildBody(req, config, spaceId, environment, revision, renderFn, pluginManager, caches.offlineData, metrics, offlineDataOverride, published);
2012
+ const keepable = ({ body, result, cacheable, nonce }) => body !== void 0 && cacheable && isReusable(result) ? {
2013
+ html: body,
2014
+ nonce
2015
+ } : void 0;
2016
+ /**
2017
+ * A kept page, served — and counted: a space that stopped being metered the moment it got popular enough to hit the
2018
+ * cache would be metered backwards. What the meter is told is that this one was cheap to serve, the same fact
2019
+ * `X-Cache` puts on the wire.
2020
+ */
2021
+ const serveKept = async (page, cacheState) => {
2022
+ res.setHeader("X-Cache", cacheState);
2023
+ if (devMode) res.setHeader("Server-Timing", `html;desc="cache-${cacheState.toLowerCase()}";dur=0`);
2024
+ const decision = await meterPage(req, config, spaceId, environment, revision, true);
2025
+ if (decision?.unavailable !== void 0) {
2026
+ sendUnavailable(res, decision.unavailable);
2027
+ return decision;
2028
+ }
2029
+ if (decision?.noindex) res.setHeader("X-Robots-Tag", "noindex, nofollow");
2030
+ sendScriptPolicy(res, config, page.nonce, req.ctx.spaceDeployment);
2031
+ res.send(() => pageHtml(page), { compressed: { ...page.compressed } });
2032
+ return decision;
2033
+ };
2034
+ /** The page rendered for this request — kept for the others when `claim` says this render is the one they wait on. */
2035
+ const renderFresh = async (claim) => {
2036
+ if (!offlineDataOverride) {
2037
+ req.ctx.meter = await meterPage(req, config, spaceId, environment, revision, false);
2038
+ if (req.ctx.meter?.unavailable !== void 0) {
2039
+ sendUnavailable(res, req.ctx.meter.unavailable);
2040
+ return;
2041
+ }
2042
+ if (req.ctx.meter?.noindex) res.setHeader("X-Robots-Tag", "noindex, nofollow");
2043
+ }
2044
+ const metrics = devMode ? new RequestMetrics(req.ctx.timings) : void 0;
2045
+ if (slot) res.setHeader("X-Cache", "MISS");
2046
+ if (config.streaming) {
2047
+ await streamBody(req, res, config, spaceId, environment, revision, renderFn, pluginManager, caches.offlineData, claim ? (page) => claim.keep(page) : void 0, metrics, offlineDataOverride, published);
2048
+ return;
2049
+ }
2050
+ const rendered = await renderPage(metrics)();
2051
+ const page = claim?.keep(keepable(rendered));
2052
+ if (metrics) {
2053
+ res.setHeader("Server-Timing", metrics.toServerTimingHeader());
2054
+ metrics.log(`${req.method} ${req.path}`);
2055
+ }
2056
+ if (applySSRResult(res, rendered.result, renderParamsOf(req.query))) return;
2057
+ sendScriptPolicy(res, config, rendered.nonce, req.ctx.spaceDeployment);
2058
+ res.send(rendered.body ?? "", page ? { compressed: { ...page.compressed } } : void 0);
2059
+ };
2060
+ if (slot) {
2061
+ const kept = await readPage(slot);
2062
+ if (kept) {
2063
+ const decision = await serveKept(kept.page, kept.stale ? "STALE" : "HIT");
2064
+ const turn = kept.stale && decision?.unavailable === void 0 && !renderingNow(slot) ? limit === void 0 ? noTurn : caches.turns.tryTake(spaceId, limit) : void 0;
2065
+ if (turn) {
2066
+ const claim = claimRender(slot);
2067
+ req.ctx.meter = decision;
2068
+ renderPage()().then((rendered) => {
2069
+ if (!claim.keep(keepable(rendered))) caches.html?.delete(slot.key);
2070
+ }).catch((error) => {
2071
+ caches.html?.delete(slot.key);
2072
+ serverLog.warn("SSR cache", `${req.path} could not be rendered again; the next request renders it`, error);
2073
+ }).finally(() => {
2074
+ claim.release();
2075
+ turn();
2076
+ });
2077
+ }
2078
+ return;
2079
+ }
2080
+ const waiting = renderingNow(slot);
2081
+ if (waiting) {
2082
+ hint();
2083
+ const waited = await waiting;
2084
+ if (waited) {
2085
+ await serveKept(waited, "HIT");
2086
+ return;
2087
+ }
2088
+ }
2089
+ }
2090
+ const claim = slot && !renderingNow(slot) ? claimRender(slot) : void 0;
2091
+ hint();
2092
+ try {
2093
+ const turn = limit === void 0 ? noTurn : await caches.turns.take(spaceId, limit, config.renderLimit?.waitMs ?? 2e3);
2094
+ if (!turn) {
2095
+ caches.turns.refused(spaceId, limit ?? 0);
2096
+ res.setHeader("Retry-After", String(BUSY_RETRY_AFTER_S));
2097
+ sendUnavailable(res, "This site is busy right now. Try again in a moment.");
2098
+ return;
2099
+ }
2100
+ try {
2101
+ await renderFresh(claim);
2102
+ } finally {
2103
+ turn();
2104
+ }
2105
+ } finally {
2106
+ claim?.release();
2107
+ }
2108
+ };
2109
+ // src/core/services/ssr.ts
2110
+ var ssrStage = async (ctx) => {
2111
+ await renderSSR(ctx.req, ctx.res, ctx.config, ctx.renderFn, ctx.pluginManager, ctx.caches, ctx.engine?.published);
2112
+ return true;
2113
+ };
2114
+ var notFoundStage = (ctx) => {
2115
+ ctx.res.setStatus(404);
2116
+ ctx.res.end();
2117
+ return true;
2118
+ };
2119
+ // src/modules/ssr/styleSheet.ts
2120
+ var SHEET_PATH = new RegExp(`^${STYLE_SHEET_PATH.replace(/\//g, "\\/")}([\\w-]{1,64})\\.css$`);
2121
+ /**
2122
+ * The space's compiled stylesheet, linked by the page (`styleSheetOf`) — answered by whichever replica the request
2123
+ * reaches, from the space as the request resolves it: nothing of the page that linked it is needed, so a replica that
2124
+ * never drew that page answers it the same.
2125
+ *
2126
+ * The name is the text's: asked for by the name it has now, it is kept for good (`immutable`); by an older one — the
2127
+ * space changed since that page was drawn — it answers the stylesheet as it is, kept by nobody, and the page is
2128
+ * styled as the space now is rather than not at all. Public whoever asks: it is the same for every visitor, and the
2129
+ * page it styles is where who may see what is decided.
2130
+ */
2131
+ var handleStyleSheet = async (req, res, config, offlineDataCache) => {
2132
+ const hash = SHEET_PATH.exec(req.path)?.[1];
2133
+ const { environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
2134
+ const spaceId = req.ctx.spaceDeployment?.spaceId ?? 1;
2135
+ const cacheKey = offlineDataCacheKeyOf(req.ctx.spaceDeployment);
2136
+ const offlineData = hash === void 0 ? void 0 : (cacheKey ? offlineDataCache?.get(cacheKey) : void 0) ?? await config.adapters.getOfflineData(spaceId, environment, revision);
2137
+ const sheet = offlineData ? styleSheetOf(offlineData) : void 0;
2138
+ if (!sheet) {
2139
+ res.setStatus(404);
2140
+ res.setHeader("Cache-Control", "no-store");
2141
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
2142
+ res.send(`/* This request resolves to space ${String(spaceId)} (${environment}), which links no stylesheet: its pages carry their styles. */`);
2143
+ return;
2144
+ }
2145
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
2146
+ res.setHeader("Cache-Control", sheet.hash === hash ? "public, max-age=31536000, immutable" : "no-store");
2147
+ res.send(() => sheet.css, { compressed: sheet.compressed });
2148
+ };
2149
+ // src/core/services/styleSheet.ts
2150
+ var styleSheetStage = async (ctx) => {
2151
+ const { config, req } = ctx;
2152
+ if (req.method !== "GET" || !req.path.startsWith(STYLE_SHEET_PATH)) return false;
2153
+ ctx.operation = "style";
2154
+ await handleStyleSheet(req, ctx.res, config, ctx.caches.offlineData);
2155
+ return true;
2156
+ };
2157
+ // src/core/http/stages/exchangeRoute.ts
2158
+ var parseBody = (req) => {
2159
+ if (!req.body) return {};
2160
+ try {
2161
+ const parsed = JSON.parse(req.body);
2162
+ return {
2163
+ provider: typeof parsed.provider === "string" ? parsed.provider : void 0,
2164
+ token: typeof parsed.token === "string" ? parsed.token : void 0
2165
+ };
2166
+ } catch {
2167
+ return {};
2168
+ }
2169
+ };
2170
+ /**
2171
+ * Turns a credential the browser obtained on its own into a session of this server's, through the
2172
+ * `exchangeCredential` adapter. A deployment running the auth kernel gets `POST /auth/exchange` from the flows
2173
+ * instead, and `createServer` stands this one down so the two never answer on the same path.
2174
+ *
2175
+ * It exists for identity providers that live in the front-end — Auth0 and the like — where this server never sees
2176
+ * the sign-in and would go on rendering every page as a guest while the browser knows perfectly well who the
2177
+ * visitor is. The page then changes under them as it hydrates. Handing the credential over closes that gap.
2178
+ *
2179
+ * Everything that decides whether the credential is any good is the adapter's: which providers this deployment
2180
+ * trusts, whether the token was minted for *this* application, and who it belongs to. This layer contributes the
2181
+ * part that is the same everywhere — reading the request, and writing the session it gets back.
2182
+ */
2183
+ var exchangeStage = async (ctx) => {
2184
+ const { config, raw, req, res } = ctx;
2185
+ const exchangePath = config.exchangePath === false ? null : config.exchangePath ?? "/auth/exchange";
2186
+ if (!exchangePath || req.method !== "POST" || req.path !== exchangePath) return false;
2187
+ if (refusedCrossSite(ctx)) return true;
2188
+ if (!config.adapters.exchangeCredential) {
2189
+ res.setStatus(404);
2190
+ res.end();
2191
+ return true;
2192
+ }
2193
+ req.body = await readRawBody(raw);
2194
+ const { provider, token } = parseBody(req);
2195
+ if (!provider || !token) {
2196
+ res.setStatus(400);
2197
+ res.setHeader("Content-Type", "application/json");
2198
+ res.send(JSON.stringify({ error: "A provider and a token are required" }));
2199
+ return true;
2200
+ }
2201
+ const result = await config.adapters.exchangeCredential(provider, token, req);
2202
+ if (!result.ok) {
2203
+ res.setStatus(result.status ?? 401);
2204
+ res.setHeader("Content-Type", "application/json");
2205
+ res.send(JSON.stringify({
2206
+ error: result.error,
2207
+ reason: result.reason ?? "revoked"
2208
+ }));
2209
+ return true;
2210
+ }
2211
+ await knowHostDeployment({
2212
+ req,
2213
+ config
2214
+ });
2215
+ writeSessionCookies(req, res, result.session, config.authCookie);
2216
+ res.setStatus(200);
2217
+ res.setHeader("Content-Type", "application/json");
2218
+ res.send(JSON.stringify({
2219
+ success: true,
2220
+ details: result.user,
2221
+ access_token: result.session.token
2222
+ }));
2223
+ return true;
2224
+ };
2225
+ // src/core/http/stages/signInRoute.ts
2226
+ /**
2227
+ * Signing a visitor in by redirect (`config.signIn`): out to an authorization server, back with a code, and a session
2228
+ * of this host's own made from it through `exchangeCredential`.
2229
+ *
2230
+ * Everything that decides whether the person may sign in, and into what, is the authorization server's and the
2231
+ * exchange adapter's. What is here is the part that is the same for any of them: registering this host as a client,
2232
+ * PKCE, the state that ties the callback to the browser that started, and never sending anybody off-site on the way
2233
+ * back.
2234
+ */
2235
+ /**
2236
+ * The flow's state, in the browser that started it. `__Host-` is the point: a cookie with that prefix cannot carry a
2237
+ * Domain, so a sibling host — another space on the same parent domain — cannot plant one and finish a sign-in it
2238
+ * started in this browser, as whoever it signed in as.
2239
+ */
2240
+ var STATE_COOKIE = "__Host-sign-in";
2241
+ var STATE_TTL_SECONDS = 600;
2242
+ var base64url = (bytes) => bytes.toString("base64url");
2243
+ var readState = (req) => {
2244
+ const raw = readCookies(req)[STATE_COOKIE];
2245
+ if (!raw) return;
2246
+ try {
2247
+ const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf-8"));
2248
+ return typeof parsed.state === "string" && typeof parsed.verifier === "string" && typeof parsed.returnTo === "string" ? {
2249
+ state: parsed.state,
2250
+ verifier: parsed.verifier,
2251
+ returnTo: parsed.returnTo
2252
+ } : void 0;
2253
+ } catch {
2254
+ return;
2255
+ }
2256
+ };
2257
+ var stateCookie = (value, maxAge) => `${STATE_COOKIE}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
2258
+ /**
2259
+ * The client id this host is registered under, per authorization server and redirect address. Registration is
2260
+ * idempotent there — the same metadata is the same client — and each one renews the registration's time to live, so a
2261
+ * process keeps the answer only for {@link REGISTRATION_KEPT_MS} and asks again: kept for good, a registration the
2262
+ * server lost (its store emptied or restored, or its TTL run out under a host that never asked again) answered every
2263
+ * sign-in on this host with "Unknown client" until the process restarted.
2264
+ */
2265
+ var REGISTRATION_KEPT_MS = 6e5;
2266
+ var clients = /* @__PURE__ */ new Map();
2267
+ var clientFor = (signIn, redirectUri, hostname) => {
2268
+ const key = `${signIn.registerUrl} ${redirectUri}`;
2269
+ const known = clients.get(key);
2270
+ if (known && known.until > Date.now()) return known.clientId;
2271
+ const registering = (async () => {
2272
+ const response = await fetch(signIn.registerUrl, {
2273
+ method: "POST",
2274
+ headers: { "Content-Type": "application/json" },
2275
+ body: JSON.stringify({
2276
+ client_name: hostname,
2277
+ redirect_uris: [redirectUri],
2278
+ grant_types: ["authorization_code"],
2279
+ response_types: ["code"],
2280
+ token_endpoint_auth_method: "none"
2281
+ })
2282
+ });
2283
+ const body = await response.json();
2284
+ if (!response.ok || typeof body.client_id !== "string") throw new Error(`Registering ${hostname} with the authorization server failed (${response.status})`);
2285
+ return body.client_id;
2286
+ })();
2287
+ clients.set(key, {
2288
+ clientId: registering,
2289
+ until: Date.now() + REGISTRATION_KEPT_MS
2290
+ });
2291
+ registering.catch(() => clients.delete(key));
2292
+ return registering;
2293
+ };
2294
+ var redirect = (res, location) => {
2295
+ res.setStatus(303);
2296
+ res.setHeader("Location", location);
2297
+ res.end();
2298
+ return true;
2299
+ };
2300
+ var signInStage = async (ctx) => {
2301
+ const { config, req, res } = ctx;
2302
+ const { signIn } = config;
2303
+ if (!signIn || req.method !== "GET") return false;
2304
+ const path = signIn.path ?? "/auth/sign-in";
2305
+ const callbackPath = `${path}/callback`;
2306
+ if (req.path !== path && req.path !== callbackPath) return false;
2307
+ const { exchangeCredential, getSpaceDeployment } = config.adapters;
2308
+ const origin = requestOrigin(req);
2309
+ if (!exchangeCredential || !origin) {
2310
+ res.setStatus(404);
2311
+ res.end();
2312
+ return true;
2313
+ }
2314
+ const redirectUri = `${origin}${callbackPath}`;
2315
+ if (req.path === path) {
2316
+ const deployment = await getSpaceDeployment(req);
2317
+ if (typeof deployment.spaceId !== "number") {
2318
+ res.setStatus(404);
2319
+ res.end();
2320
+ return true;
2321
+ }
2322
+ const clientId = await clientFor(signIn, redirectUri, req.hostname);
2323
+ const verifier = base64url(randomBytes(32));
2324
+ const state = base64url(randomBytes(16));
2325
+ const flow = {
2326
+ state,
2327
+ verifier,
2328
+ returnTo: safeRedirectTarget(req, "return")
2329
+ };
2330
+ appendCookies(res, [stateCookie(base64url(Buffer.from(JSON.stringify(flow))), STATE_TTL_SECONDS)]);
2331
+ const authorize = new URL(signIn.authorizeUrl);
2332
+ authorize.search = new URLSearchParams({
2333
+ response_type: "code",
2334
+ client_id: clientId,
2335
+ redirect_uri: redirectUri,
2336
+ scope: signIn.scope(deployment.spaceId),
2337
+ state,
2338
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()),
2339
+ code_challenge_method: "S256"
2340
+ }).toString();
2341
+ return redirect(res, authorize.toString());
2342
+ }
2343
+ const flow = readState(req);
2344
+ appendCookies(res, [stateCookie("", 0)]);
2345
+ const code = req.query["code"];
2346
+ if (!flow || !code || req.query["state"] !== flow.state) return redirect(res, flow?.returnTo ?? "/");
2347
+ const token = await fetch(signIn.tokenUrl, {
2348
+ method: "POST",
2349
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
2350
+ body: new URLSearchParams({
2351
+ grant_type: "authorization_code",
2352
+ code,
2353
+ redirect_uri: redirectUri,
2354
+ client_id: await clientFor(signIn, redirectUri, req.hostname),
2355
+ code_verifier: flow.verifier
2356
+ }).toString()
2357
+ });
2358
+ const granted = await token.json();
2359
+ if (!token.ok || typeof granted.access_token !== "string") return redirect(res, flow.returnTo);
2360
+ const result = await exchangeCredential(signIn.provider, granted.access_token, req);
2361
+ if (result.ok) {
2362
+ await knowHostDeployment({
2363
+ req,
2364
+ config
2365
+ });
2366
+ writeSessionCookies(req, res, result.session, config.authCookie);
2367
+ }
2368
+ return redirect(res, flow.returnTo);
2369
+ };
2370
+ // src/core/http/stages/authRoutes.ts
2371
+ /**
2372
+ * Credentials as they arrive from a page: a posted form, or JSON from a script. Every field is handed to the
2373
+ * adapter — a deployment may sign people in with something other than a username and a password, and this layer
2374
+ * has no opinion about which fields those are.
2375
+ */
2376
+ var parseCredentials = (req) => {
2377
+ if (!req.body) return {};
2378
+ const contentType = req.headers["content-type"];
2379
+ if (typeof contentType === "string" && contentType.includes("application/json")) try {
2380
+ const parsed = JSON.parse(req.body);
2381
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
2382
+ } catch {
2383
+ return {};
2384
+ }
2385
+ return Object.fromEntries(new URLSearchParams(req.body));
2386
+ };
2387
+ var loginStage = async (ctx) => {
2388
+ const { config, raw, req, res } = ctx;
2389
+ const loginPath = config.loginPath === false ? null : config.loginPath ?? "/auth/login";
2390
+ if (!loginPath || req.method !== "POST" || req.path !== loginPath) return false;
2391
+ if (refusedCrossSite(ctx)) return true;
2392
+ req.body = await readRawBody(raw);
2393
+ const session = await config.adapters.authenticate?.(parseCredentials(req), req);
2394
+ if (session) {
2395
+ await knowHostDeployment(ctx);
2396
+ writeSessionCookies(req, res, session, config.authCookie);
2397
+ }
2398
+ if (isNavigation(req)) {
2399
+ res.setStatus(303);
2400
+ res.setHeader("Location", session ? safeRedirectTarget(req) : loginPath);
2401
+ res.end();
2402
+ return true;
2403
+ }
2404
+ res.setStatus(session ? 200 : 401);
2405
+ res.setHeader("Content-Type", "application/json");
2406
+ res.send(JSON.stringify(session ? {
2407
+ success: true,
2408
+ access_token: session.token,
2409
+ expire_at: session.expiresAt
2410
+ } : {
2411
+ error: "Invalid credentials",
2412
+ reason: "invalid"
2413
+ }));
2414
+ return true;
2415
+ };
2416
+ var logoutStage = async (ctx) => {
2417
+ const { config, raw, req, res } = ctx;
2418
+ const logoutPath = config.logoutPath === false ? null : config.logoutPath ?? "/auth/logout";
2419
+ if (!logoutPath || req.method !== "POST" || req.path !== logoutPath) return false;
2420
+ if (refusedCrossSite(ctx)) return true;
2421
+ req.body = await readRawBody(raw);
2422
+ await config.adapters.endSession?.(req);
2423
+ clearSessionCookies(req, res, config.authCookie);
2424
+ if (isNavigation(req)) {
2425
+ res.setStatus(303);
2426
+ res.setHeader("Location", safeRedirectTarget(req));
2427
+ res.end();
2428
+ return true;
2429
+ }
2430
+ res.setStatus(204);
2431
+ res.end();
2432
+ return true;
2433
+ };
2434
+ var isSessionScope = (value) => value === "site" || value === "all";
2435
+ /**
2436
+ * Signing the person out on every device (`endSessions`): `{ scope: 'site' }`, this host's sessions — a space's visitor
2437
+ * ending it on their phone too; `{ scope: 'all' }`, every session of the account. Said, never assumed: a sign-out the
2438
+ * page did not mean is one the person did not ask for. Guarded as a sign-out is — a page of another origin is refused.
2439
+ */
2440
+ var logoutEverywhereStage = async (ctx) => {
2441
+ const { config, raw, req, res } = ctx;
2442
+ const path = config.logoutEverywherePath === false ? null : config.logoutEverywherePath ?? "/auth/logout-everywhere";
2443
+ const { endSessions } = config.adapters;
2444
+ if (!path || !endSessions || req.method !== "POST" || req.path !== path) return false;
2445
+ if (refusedCrossSite(ctx)) return true;
2446
+ req.body = await readRawBody(raw);
2447
+ const { scope } = parseCredentials(req);
2448
+ const answer = (status, body) => {
2449
+ res.setStatus(status);
2450
+ res.setHeader("Content-Type", "application/json");
2451
+ res.send(JSON.stringify(body));
2452
+ return true;
2453
+ };
2454
+ if (!isSessionScope(scope)) return answer(400, {
2455
+ error: "Say which sessions end: { \"scope\": \"site\" } for this site's, { \"scope\": \"all\" } for every one of the account",
2456
+ reason: "invalid"
2457
+ });
2458
+ if (!await endSessions(req, scope)) return answer(401, {
2459
+ error: "Nobody is signed in here",
2460
+ reason: "missing"
2461
+ });
2462
+ clearSessionCookies(req, res, config.authCookie);
2463
+ if (isNavigation(req)) {
2464
+ res.setStatus(303);
2465
+ res.setHeader("Location", safeRedirectTarget(req));
2466
+ res.end();
2467
+ return true;
2468
+ }
2469
+ return answer(200, {
2470
+ scope,
2471
+ ended: true
2472
+ });
2473
+ };
2474
+ var authRoutesStages = [
2475
+ loginStage,
2476
+ logoutStage,
2477
+ logoutEverywhereStage,
2478
+ exchangeStage,
2479
+ signInStage
2480
+ ];
2481
+ // src/core/http/stages/cspReport.ts
2482
+ var dispositionOf = (value) => value === "enforce" ? "enforce" : "report";
2483
+ var text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
2484
+ /** A browser's report, either way they come: `report-uri`'s `{ "csp-report": … }` or the Reporting API's list. */
2485
+ var violationsOf = (body) => {
2486
+ if (isRecord(body) && isRecord(body["csp-report"])) {
2487
+ const report = body["csp-report"];
2488
+ return [{
2489
+ page: text(report["document-uri"]),
2490
+ blocked: text(report["blocked-uri"]),
2491
+ directive: text(report["effective-directive"]) || text(report["violated-directive"]),
2492
+ source: [text(report["source-file"]), text(report["line-number"])].filter(Boolean).join(":"),
2493
+ sample: text(report["script-sample"]),
2494
+ disposition: dispositionOf(report.disposition)
2495
+ }];
2496
+ }
2497
+ return (Array.isArray(body) ? body : []).flatMap((entry) => {
2498
+ if (!isRecord(entry) || entry.type !== "csp-violation" || !isRecord(entry.body)) return [];
2499
+ const report = entry.body;
2500
+ return [{
2501
+ page: text(report.documentURL),
2502
+ blocked: text(report.blockedURL),
2503
+ directive: text(report.effectiveDirective),
2504
+ source: [text(report.sourceFile), text(report.lineNumber)].filter(Boolean).join(":"),
2505
+ sample: text(report.sample),
2506
+ disposition: dispositionOf(report.disposition)
2507
+ }];
2508
+ });
2509
+ };
2510
+ /** A violation said once an hour, a hundred a minute at most: anyone may post a report, and a page reports on every load. */
2511
+ var SAY_AGAIN_MS = 36e5;
2512
+ var MAX_PER_MINUTE = 100;
2513
+ var MAX_KNOWN = 1e3;
2514
+ var said = /* @__PURE__ */ new Map();
2515
+ var minute = {
2516
+ startedAt: 0,
2517
+ count: 0
2518
+ };
2519
+ var pathOf = (page) => {
2520
+ try {
2521
+ const url = new URL(page);
2522
+ return `${url.host}${url.pathname}`;
2523
+ } catch {
2524
+ return page;
2525
+ }
2526
+ };
2527
+ var say = (violation) => {
2528
+ const now = Date.now();
2529
+ const key = `${violation.directive}|${violation.blocked}|${violation.source}`;
2530
+ const last = said.get(key);
2531
+ if (last !== void 0 && now - last < SAY_AGAIN_MS) return;
2532
+ if (now - minute.startedAt >= 6e4) minute = {
2533
+ startedAt: now,
2534
+ count: 0
2535
+ };
2536
+ minute.count += 1;
2537
+ if (minute.count > MAX_PER_MINUTE) return;
2538
+ if (last !== void 0 || said.size < MAX_KNOWN) said.set(key, now);
2539
+ serverLog.warn("CSP", `A page's script policy ${violation.disposition === "enforce" ? "refused" : "would refuse"} ${violation.blocked || "(an inline script)"} under ${violation.directive || "its script policy"} (first seen on ${pathOf(violation.page)})` + (violation.source ? `, from ${violation.source}` : "") + (violation.disposition === "enforce" ? " — the policy is enforced, and it did not run" : " — the policy only reports (`scriptPolicy`); enforced, this would not run"));
2540
+ };
2541
+ /**
2542
+ * Each space's violations, handed to the deployment (`recordScriptPolicyReport`) once in a while rather than on every
2543
+ * page a visitor opens: by space and by what would be refused, again after `KEEP_AGAIN_MS`. Bounded as the log's is.
2544
+ */
2545
+ var KEEP_AGAIN_MS = 6e5;
2546
+ var kept = /* @__PURE__ */ new Map();
2547
+ var pageOf = (page) => {
2548
+ try {
2549
+ const url = new URL(page);
2550
+ return `${url.origin}${url.pathname}`;
2551
+ } catch {
2552
+ return page;
2553
+ }
2554
+ };
2555
+ /** The space is the one the report's host serves, never one the report names: anyone may post one. */
2556
+ var keep = async (ctx, violations) => {
2557
+ const record = ctx.config.adapters.recordScriptPolicyReport;
2558
+ if (!record || violations.length === 0) return;
2559
+ await knowHostDeployment(ctx);
2560
+ const deployment = ctx.req.ctx.spaceDeployment;
2561
+ if (typeof deployment?.spaceId !== "number") return;
2562
+ const { spaceId, environment = "main" } = deployment;
2563
+ const now = Date.now();
2564
+ for (const violation of violations) {
2565
+ const key = `${String(spaceId)}|${violation.directive}|${violation.blocked}|${violation.source}`;
2566
+ const last = kept.get(key);
2567
+ if (last !== void 0 && now - last < KEEP_AGAIN_MS) continue;
2568
+ if (last !== void 0 || kept.size < MAX_KNOWN) kept.set(key, now);
2569
+ try {
2570
+ await record({
2571
+ ...violation,
2572
+ page: pageOf(violation.page),
2573
+ spaceId,
2574
+ environment
2575
+ });
2576
+ } catch (error) {
2577
+ serverLog.warn("CSP", `A report for space ${String(spaceId)} could not be kept: it is in the log alone`, error);
2578
+ }
2579
+ }
2580
+ };
2581
+ /**
2582
+ * Where a page's script policy reports (`SSRServerConfig.scriptPolicy`): said in the log, kept for its space when the
2583
+ * deployment keeps them (`recordScriptPolicyReport`), answered with nothing.
2584
+ */
2585
+ var cspReportStage = async (ctx) => {
2586
+ const { raw, req, res } = ctx;
2587
+ if (req.path !== "/_plitzi/csp-report") return false;
2588
+ if (req.method !== "POST") {
2589
+ res.setStatus(405);
2590
+ res.setHeader("Allow", "POST");
2591
+ res.send("Method not allowed");
2592
+ return true;
2593
+ }
2594
+ let body;
2595
+ try {
2596
+ body = JSON.parse(await readRawBody(raw));
2597
+ } catch {
2598
+ res.setStatus(400);
2599
+ res.send("Not a report");
2600
+ return true;
2601
+ }
2602
+ const violations = violationsOf(body);
2603
+ violations.forEach(say);
2604
+ await keep(ctx, violations);
2605
+ res.setStatus(204);
2606
+ res.end();
2607
+ return true;
2608
+ };
2609
+ // src/modules/ssr/defaultFavicon.ts
2610
+ /**
2611
+ * Plitzi's icon: the tab of a space that names none (`DEFAULT_FAVICON`, `@plitzi/sdk-shared/schema`), served by the
2612
+ * page server itself at that address. It was Plitzi's CDN, another site: in local, on `*.plitzi.app` or on a server of
2613
+ * one's own, every page that named no icon asked another site for one, and the browser sent that site's cookies with
2614
+ * it — Lighthouse's "Uses third-party cookies".
2615
+ *
2616
+ * Kept as text rather than a file beside the module: the server's build moves its modules into chunks, and a deployment
2617
+ * bundles them again (a project's server, `bundleProject`) — a string goes wherever its module goes.
2618
+ */
2619
+ var DEFAULT_FAVICON_SVG = `<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="147.5px" height="149px" viewBox="0 0 147.5 149" enable-background="new 0 0 147.5 149" xml:space="preserve"> <path fill="#4422EE" d="M94.008,120.333l-14.699,14.699c-17.816,17.816-46.86,17.816-64.676,0s-17.816-46.86,0-64.676l14.699-14.699 l5.88,5.88L20.513,76.236c-14.581,14.581-14.581,38.335,0,52.917s38.335,14.581,52.917,0l14.699-14.699L94.008,120.333z"/> <circle fill="#4422EE" cx="32.058" cy="58.79" r="4.178"/> <ellipse fill="#4422EE" cx="90.876" cy="117.587" rx="4.165" ry="4.15"/> <path fill="#4422EE" d="M73.469,44.587c1.562,1.562,1.546,4.111-0.037,5.694L54.09,69.623c-1.583,1.583-4.132,1.599-5.694,0.037l0,0 c-1.562-1.562-1.546-4.111,0.037-5.694l19.342-19.342C69.357,43.041,71.907,43.025,73.469,44.587L73.469,44.587z"/> <path fill="#4422EE" d="M112.978,5.077c1.667,1.667,1.655,4.001,0.208,5.449L81.746,41.967c-1.447,1.447-3.781,1.459-5.449-0.208 l0,0c-1.667-1.667-1.655-4.001-0.208-5.449L107.53,4.869C108.977,3.422,111.311,3.41,112.978,5.077L112.978,5.077z"/> <path fill="#4422EE" d="M82.843,8.292c1.647,1.647,1.599,4.765-0.354,6.718L46.427,51.072c-1.953,1.953-5.071,2-6.718,0.354l0,0 c-1.647-1.647-1.599-4.765,0.354-6.718L76.125,8.646C78.078,6.693,81.196,6.645,82.843,8.292L82.843,8.292z"/> <path fill="#4422EE" d="M99.814,49.304c1.367,1.367,1.367,3.583,0,4.95L87.086,66.982c-1.367,1.367-3.583,1.367-4.95,0l0,0 c-1.367-1.367-1.367-3.583,0-4.95l12.728-12.728C96.231,47.937,98.447,47.937,99.814,49.304L99.814,49.304z"/> <path fill="#4422EE" d="M136.605,12.557c1.355,1.355,1.355,3.551,0,4.906l-28.328,28.328c-1.355,1.355-3.551,1.355-4.906,0 l-0.044-0.044c-1.355-1.355-1.355-3.551,0-4.906l28.328-28.328c1.355-1.355,3.551-1.355,4.906,0L136.605,12.557z"/> <path fill="#4422EE" d="M105.824,77.942c1.562,1.562,1.546,4.111-0.037,5.694l-19.342,19.342c-1.583,1.583-4.132,1.599-5.694,0.037 l0,0c-1.562-1.562-1.546-4.111,0.037-5.694l19.342-19.342C101.713,76.397,104.262,76.38,105.824,77.942L105.824,77.942z"/> <path fill="#4422EE" d="M145.334,38.432c1.667,1.667,1.655,4.001,0.208,5.449l-31.441,31.441c-1.447,1.447-3.781,1.459-5.449-0.208 l0,0c-1.667-1.667-1.655-4.001-0.208-5.449l31.441-31.441C141.332,36.777,143.666,36.765,145.334,38.432L145.334,38.432z"/> <path fill="#4422EE" d="M141.533,66.982c1.647,1.647,1.599,4.765-0.354,6.718l-36.062,36.062c-1.953,1.953-5.071,2-6.718,0.354l0,0 c-1.647-1.647-1.599-4.765,0.354-6.718l36.062-36.062C136.768,65.383,139.886,65.335,141.533,66.982L141.533,66.982z"/> <g> <path fill="#4422EE" d="M80.474,72.436c-1.181,2.571-4.779,10.395-4.779,30.029c0,16.274-13.242,29.516-29.516,29.516 s-29.516-13.242-29.516-29.516s13.242-29.516,29.516-29.516c19.642,0,27.477-3.585,30.053-4.76 c0.985-0.453,2.646-1.216,4.057,0.193C81.692,69.788,80.93,71.446,80.474,72.436z M64.907,79.179 c-1.921,0.202-4.232,1.481-7.065,3.909c-5.126,4.393-11.172,11.979-15.066,17.437c-2.843-0.443-5.84,0.773-7.615,2.991 c-3.257,4.071-0.53,7.704-3.603,10.944c-0.535,0.564-0.344,1.491,0.371,1.797c5.026,2.152,11.451,0.811,14.464-2.367 c1.842-1.942,2.844-4.809,2.341-7.509c5.386-4.133,12.828-10.504,17.042-15.789c2.334-2.927,3.518-5.281,3.62-7.198 C69.535,80.812,67.531,78.903,64.907,79.179L64.907,79.179z"/> <path fill="#4422EE" d="M44.727,112.307c-2.039,2.15-6.55,3.402-10.564,2.331c2.244-3.58,0.315-6.79,2.699-9.77 c1.956-2.445,5.889-3.129,8.175-0.843C47.708,106.696,46.464,110.476,44.727,112.307z"/> <path fill="#4422EE" d="M44.956,101.215c0.548-0.758,1.407-1.927,2.481-3.328l3.668,3.668c-1.351,1.111-2.479,2.002-3.21,2.57 C47.236,102.943,46.216,101.882,44.956,101.215L44.956,101.215z"/> <path fill="#4422EE" d="M67.12,83.23c-0.251,4.695-10.719,13.862-14.292,16.887l-4.008-4.008 c2.94-3.723,11.57-14.256,16.276-14.751C66.352,81.226,67.185,82.018,67.12,83.23z"/> </g> </svg>`;
2620
+ // src/core/http/stages/defaultFavicon.ts
2621
+ /** Plitzi's icon, at the address a page that names none points its tab at — see `DEFAULT_FAVICON_SVG`. */
2622
+ var defaultFaviconStage = (ctx) => {
2623
+ if (ctx.req.path !== DEFAULT_FAVICON) return false;
2624
+ if (ctx.req.method !== "GET" && ctx.req.method !== "HEAD") {
2625
+ ctx.res.setStatus(405);
2626
+ ctx.res.setHeader("Allow", "GET, HEAD");
2627
+ ctx.res.send("Method not allowed");
2628
+ return true;
2629
+ }
2630
+ ctx.res.setHeader("Content-Type", "image/svg+xml");
2631
+ ctx.res.setHeader("Cache-Control", "public, max-age=86400, stale-while-revalidate=604800");
2632
+ ctx.res.send(ctx.req.method === "HEAD" ? "" : DEFAULT_FAVICON_SVG);
2633
+ return true;
2634
+ };
2635
+ // src/core/http/stages/fontAssets.ts
2636
+ /** Where a manifest's `hosted` paths are addressed from by default — see `fontUrlResolver`. */
2637
+ var FONTS_PREFIX = "/fonts";
2638
+ /**
2639
+ * The font files this deployment stores, when it stores them itself.
2640
+ *
2641
+ * Off unless `fonts.dir` is configured, because a cloud deployment serves them from a CDN and would otherwise
2642
+ * shadow that path with a directory it does not have. Served CORS-open on purpose: a font is fetched in CORS mode
2643
+ * whatever its origin, so without this a page on the space's own domain cannot use a face from this server.
2644
+ */
2645
+ var fontAssetsStage = (ctx) => {
2646
+ const dir = ctx.config.fonts?.dir;
2647
+ if (!dir || !ctx.req.path.startsWith(`${FONTS_PREFIX}/`)) return false;
2648
+ ctx.res.setHeader("Access-Control-Allow-Origin", "*");
2649
+ ctx.res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
2650
+ const strippedReq = {
2651
+ ...ctx.req,
2652
+ path: ctx.req.path.slice(6) || "/"
2653
+ };
2654
+ if (serveStatic(strippedReq, ctx.res, dir)) return true;
2655
+ ctx.res.setStatus(404);
2656
+ ctx.res.send("Not found");
2657
+ return true;
2658
+ };
2659
+ // src/core/http/stages/pluginAssets.ts
2660
+ var pluginAssetsStage = async (ctx) => {
2661
+ const { pluginManager, req, res } = ctx;
2662
+ if (!req.path.startsWith(pluginManager.urlPrefix + "/")) return false;
2663
+ const relative = req.path.slice(pluginManager.urlPrefix.length);
2664
+ const pluginName = relative.split("/")[1];
2665
+ if (pluginName && pluginManager.hasPlugin(pluginName)) {
2666
+ await pluginManager.prepare(pluginName);
2667
+ const strippedReq = {
2668
+ ...req,
2669
+ path: relative
2670
+ };
2671
+ if (serveStatic(strippedReq, res, pluginManager.outputDir)) return true;
2672
+ }
2673
+ res.setStatus(404);
2674
+ res.send("Not found");
2675
+ return true;
2676
+ };
2677
+ // src/core/http/stages/sdkAssets.ts
2678
+ var sdkAssetsDir = resolveSdkAssetsDir();
2679
+ /**
2680
+ * The SDK bundle, served from this package's own copy.
2681
+ *
2682
+ * The rendered page is told to fetch `/sdk-assets/plitzi-sdk.js`, and it is this server that puts the URL there — so
2683
+ * answering it is this server's job too, not a mount every deployment has to remember to declare. It runs after
2684
+ * `configStaticStage`, so a deployment serving its own build (a pinned version, a CDN mirror) still wins by
2685
+ * declaring `static: { '/sdk-assets': … }`.
2686
+ */
2687
+ var sdkAssetsStage = (ctx) => {
2688
+ if (!sdkAssetsDir || !ctx.req.path.startsWith(`/sdk-assets/`)) return false;
2689
+ ctx.res.setHeader("Access-Control-Allow-Origin", "*");
2690
+ ctx.res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
2691
+ const strippedReq = {
2692
+ ...ctx.req,
2693
+ path: ctx.req.path.slice(11) || "/"
2694
+ };
2695
+ return serveStatic(strippedReq, ctx.res, sdkAssetsDir);
2696
+ };
2697
+ // src/core/services/registry.ts
2698
+ var buildPagePipeline = (services, extensions = {}, engine) => {
2699
+ const stages = [
2700
+ healthStage,
2701
+ statsStage,
2702
+ publicDirStage,
2703
+ defaultFaviconStage,
2704
+ cspReportStage,
2705
+ wellKnownStage,
2706
+ pluginAssetsStage,
2707
+ fontAssetsStage,
2708
+ googleFontsStage,
2709
+ imagesStage,
2710
+ ...authRoutesStages,
2711
+ configStaticStage,
2712
+ sdkAssetsStage
2713
+ ];
2714
+ stages.push(...extensions.preAuth ?? []);
2715
+ stages.push(crossSiteWritesStage);
2716
+ stages.push(createMiddlewaresStage());
2717
+ if (services.rsc) stages.push(rscStage);
2718
+ stages.push(...engine?.endpoints ?? []);
2719
+ stages.push(...extensions.data ?? []);
2720
+ stages.push(...engine?.routes ?? []);
2721
+ if (services.ssr) {
2722
+ stages.push(spaceDocumentStage);
2723
+ stages.push(styleSheetStage);
2724
+ stages.push(robotsTxtStage);
2725
+ stages.push(sitemapXmlStage);
2726
+ }
2727
+ stages.push(services.ssr ? ssrStage : notFoundStage);
2728
+ return stages;
2729
+ };
2730
+ // src/core/server/pageServer.ts
2731
+ /** The page-serving machinery: html/rsc caches, the render template and the plugin manager, driving the page
2732
+ * pipeline. Which services it mounts is the CALLER's decision — {@link createServer} passes whatever the config
2733
+ * enables — so this unit never second-guesses a factory's promise. */
2734
+ var createPageServer = (config, services, extensions, engine) => {
2735
+ const { cacheTtlMs: htmlTtlMs = DEFAULT_TTL_MS$1.html } = config;
2736
+ const logLevel = config.logLevel ?? defaultLogLevel(config.devMode);
2737
+ const { logger } = config;
2738
+ config.logLevel = logLevel;
2739
+ if (logger) config.logger = (event) => {
2740
+ if (isLogged(logLevel, logLevelOf(event))) logger(event);
2741
+ };
2742
+ configureServerLog({
2743
+ level: logLevel,
2744
+ logger,
2745
+ ...config.slowRunMs === void 0 ? {} : { slowRunMs: config.slowRunMs }
2746
+ });
2747
+ reportReactBuild(config.devMode);
2748
+ if (config.preview?.enabled && !config.draftStore) config.draftStore = fleetStore("ssr.drafts", DRAFT_STORE_METHODS) ?? createMemoryDraftStore();
2749
+ config.cache = {
2750
+ ...config.cache,
2751
+ ...cacheLimitsOf(config)
2752
+ };
2753
+ config.renderLimit = renderLimitOf(config.renderLimit);
2754
+ const caches = createServerCaches({
2755
+ htmlTtlMs,
2756
+ rscTtlMs: config.rsc?.cacheTtlMs ?? DEFAULT_TTL_MS$1.rsc,
2757
+ htmlBytes: config.cache.maxBytes,
2758
+ staleMs: config.cache.staleMs
2759
+ });
2760
+ const local = caches.html || caches.rsc ? buildCacheManager(caches) : null;
2761
+ const { bus, store } = config.cache;
2762
+ const shared = local && (bus || store) ? shareCache(local, {
2763
+ bus,
2764
+ store
2765
+ }) : void 0;
2766
+ const cache = shared?.cache ?? local;
2767
+ if (fleetRole(resolveWorkers(config.workers)) !== "worker" && caches.html) reportCacheSharing(config, {
2768
+ ttlMs: htmlTtlMs,
2769
+ bus: Boolean(bus),
2770
+ store: Boolean(store)
2771
+ });
2772
+ const renderFn = config.templateFn ?? compileTemplate();
2773
+ const pluginManager = new PluginManager(normalizePlugins(config.plugins ?? {}), config.pluginsCacheDir, config.pluginsTtlMs, config.devMode);
2774
+ const plugins = {
2775
+ register: (name, source) => {
2776
+ const normalized = normalizePluginSource(source);
2777
+ pluginManager.register(`${name}@${normalized.version}`, normalized);
2778
+ },
2779
+ unregister: (name) => {
2780
+ pluginManager.unregister(name);
2781
+ invalidatePluginComponentCache();
2782
+ },
2783
+ invalidate: async (name, version) => {
2784
+ await pluginManager.invalidate(name, version);
2785
+ invalidatePluginComponentCache();
2786
+ }
2787
+ };
2788
+ const livePages = config.livePages ? createLivePages() : void 0;
2789
+ /**
2790
+ * A plugin whose source changed is built again and handed to the open pages, which swap it where it is drawn — the
2791
+ * rest of the page, its state included, stays as it was. Only while developing (`devMode`) with `livePages` on: nobody edits a
2792
+ * deployment's plugins under it, and a page that does not listen has nothing to swap.
2793
+ */
2794
+ const stopWatchingPlugins = livePages && config.devMode ? watchPluginSources(pluginManager, (key) => {
2795
+ invalidatePluginComponentCache();
2796
+ pluginManager.rebuild(key).then((entry) => {
2797
+ if (entry?.js) livePages.plugin(entry);
2798
+ });
2799
+ }) : void 0;
2800
+ const stages = [...livePages ? [livePages.stage] : [], ...buildPagePipeline(services, extensions, engine)];
2801
+ const makeHandlerForPort = (port) => {
2802
+ const buildContext = (raw, rawRes, req, res) => ({
2803
+ raw,
2804
+ rawRes,
2805
+ req,
2806
+ res,
2807
+ config,
2808
+ port,
2809
+ renderFn,
2810
+ caches,
2811
+ pluginManager,
2812
+ ...engine ? { engine } : {}
2813
+ });
2814
+ return makeHandler("SSR", buildContext, stages, {
2815
+ compression: config.compression,
2816
+ ...engine?.upgrades ? { upgrades: engine.upgrades } : {}
2817
+ });
2818
+ };
2819
+ const server = createHttpServer(config, makeHandlerForPort, {
2820
+ label: "SSR",
2821
+ onListen: () => {
2822
+ engine?.listening?.();
2823
+ },
2824
+ beforeFork: () => pluginManager.prepareAll(),
2825
+ fleetStores: {
2826
+ ...engine?.fleetStores,
2827
+ "ssr.drafts": hostable(createMemoryDraftStore, DRAFT_STORE_METHODS),
2828
+ "auth.rateLimit": hostable(() => ({ check: createMemoryRateLimit() }), RATE_LIMIT_METHODS)
2829
+ },
2830
+ onStopping: () => {
2831
+ engine?.stopping?.();
2832
+ },
2833
+ onClosing: () => {
2834
+ engine?.closing?.();
2835
+ stopWatchingPlugins?.();
2836
+ livePages?.close();
2837
+ },
2838
+ onDestroy: async () => {
2839
+ await engine?.destroy?.();
2840
+ await shared?.close();
2841
+ destroyServerCaches(caches);
2842
+ pluginManager.destroy();
2843
+ }
2844
+ });
2845
+ const { channel } = server;
2846
+ return {
2847
+ listen: server.listen,
2848
+ close: server.close,
2849
+ cache: channel && cache && !bus ? relayCache(cache, `${channel}.cache`) : cache,
2850
+ plugins: channel ? relayPlugins(plugins, (name, version) => {
2851
+ pluginManager.forget(name, version);
2852
+ invalidatePluginComponentCache();
2853
+ }, `${channel}.plugins`, "SSR") : plugins,
2854
+ reloadPages: livePages?.reload ?? (() => void 0),
2855
+ updatePages: livePages?.update ?? (() => 0),
2856
+ functions: { setPlugin: (plugin, definition) => {
2857
+ if (!engine?.setPluginFunctions) throw new Error(`[SSR] This server runs no actions (\`createPlatform\` composes them), so no plugin's functions: "${plugin}"`);
2858
+ engine.setPluginFunctions(plugin, definition);
2859
+ } }
2860
+ };
2861
+ };
2862
+ // src/core/createServer.ts
2863
+ /**
2864
+ * What a page server is not configured with: the actions engine's own configuration, which `createPlatform` builds the
2865
+ * engine from and hands the server (`engine`), or a worker runs elsewhere (RFC 0032, D12).
2866
+ */
2867
+ var ENGINE_KEYS = [
2868
+ "action",
2869
+ "functions",
2870
+ "connectors",
2871
+ "realtime"
2872
+ ];
2873
+ /** The server this package makes: pages and RSC, mounting whatever the config enables, plus any stages a
2874
+ * companion package contributes through `extensions`. The MCP endpoint, the widget proxy and draft-preview
2875
+ * arrive that way from `@plitzi/sdk-mcp`, which a page-only deployment never installs.
2876
+ *
2877
+ * A dedicated MCP server is `createServer` from `@plitzi/sdk-mcp` — it builds none of the render template,
2878
+ * caches or plugin manager this one does. */
2879
+ /**
2880
+ * Fills in `getRscData` from whatever can produce a server element's data — `connectors`, `action.lookups`, the
2881
+ * files of `dataDir` and `publicDir`, another site's address — when the deployment did not write one. Always, then:
2882
+ * a provider that asks another site needs nothing configured, and with none of the rest it drew empty until the
2883
+ * browser asked.
2884
+ *
2885
+ * The lookups are already here and the assembly is entirely this package's — a resolver over `resolveRscData`.
2886
+ * Leaving it out meant every deployment passed the same lookups twice: once as config, for the write endpoint,
2887
+ * and once folded by hand into an adapter, for the read.
2888
+ *
2889
+ * Actions count on their own: a space whose server elements name actions rather than connectors has nothing to
2890
+ * configure under `connectors`, and keying this on that alone left its `render` elements resolving to nothing
2891
+ * with no configuration missing anywhere.
2892
+ */
2893
+ var withRsc = (config, engine) => {
2894
+ if (config.adapters.getRscData) return config;
2895
+ return {
2896
+ ...config,
2897
+ adapters: {
2898
+ ...config.adapters,
2899
+ getRscData: connectorRscData({
2900
+ ...engine?.resolveElement ? { engine: engine.resolveElement } : {},
2901
+ publicDir: config.publicDir,
2902
+ data: engine?.data ?? (config.dataDir ? dataDirLookup(config.dataDir) : void 0),
2903
+ elementTimeoutMs: config.rsc?.elementTimeoutMs,
2904
+ sayFailures: config.devMode === true,
2905
+ outbound: { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) },
2906
+ visitorCredentials: config.rsc?.visitorCredentials
2907
+ })
2908
+ }
2909
+ };
2910
+ };
2911
+ /** Refused rather than ignored: an `action` given here would leave every call a 404 with nothing said. */
2912
+ var refuseEngineConfig = (config) => {
2913
+ const given = ENGINE_KEYS.filter((key) => key in config);
2914
+ if (given.length > 0) throw new Error(`createServer serves pages: ${given.join(", ")} ${given.length === 1 ? "is" : "are"} the actions engine's configuration. Use createPlatform (@plitzi/sdk-server/platform) for pages and actions in one process, or a worker of its own.`);
2915
+ };
2916
+ /** The renewal stage in front of whatever else gates itself, when there is anywhere to renew. */
2917
+ var withRenewal = (extensions, url) => ({
2918
+ ...extensions,
2919
+ preAuth: [...extensions?.preAuth ?? [], ...url ? [createSessionRenewalStage(url)] : []]
2920
+ });
2921
+ var createServer = ({ auth, sessionRenewal, engine, ...config }, extensions) => {
2922
+ refuseEngineConfig(config);
2923
+ if (!auth) {
2924
+ const resolvedConfig = withRsc(config, engine);
2925
+ return createPageServer(resolvedConfig, resolveServices(resolvedConfig), withRenewal(extensions, sessionRenewal ? sessionRenewal.url : void 0), engine);
2926
+ }
2927
+ const entries = Object.entries(config.adapters);
2928
+ const supplied = Object.fromEntries(entries.filter(([, value]) => value !== void 0));
2929
+ const resolved = withRsc({
2930
+ loginPath: false,
2931
+ logoutPath: false,
2932
+ exchangePath: false,
2933
+ ...config,
2934
+ authCookie: config.authCookie ?? auth.cookieConfig,
2935
+ crossSiteWrites: {
2936
+ ...config.crossSiteWrites,
2937
+ origins: [...config.crossSiteWrites?.origins ?? [], ...auth.platformOrigins]
2938
+ },
2939
+ pageAuth: config.pageAuth ?? auth.pageAuth,
2940
+ adapters: {
2941
+ ...auth.ssrAdapters,
2942
+ ...supplied
2943
+ }
2944
+ }, engine);
2945
+ const withAuthRoutes = {
2946
+ ...extensions,
2947
+ preAuth: [
2948
+ ...extensions?.preAuth ?? [],
2949
+ createAuthApiStage(auth, auth.basePath),
2950
+ createRenewalEndpointStage(auth)
2951
+ ]
2952
+ };
2953
+ const renewalUrl = sessionRenewal === false ? void 0 : sessionRenewal?.url ?? `${auth.basePath}/refresh`;
2954
+ return createPageServer(resolved, resolveServices(resolved), withRenewal(withAuthRoutes, renewalUrl), engine);
2955
+ };
2956
+ export { LIVE_PAGES_PATH as n, resolveRscData as r, createServer as t };