akanjs 3.2.0-rc.2 → 3.2.0-rc.21

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 (667) hide show
  1. package/ARCHITECTURE.md +42 -41
  2. package/CHANGELOG.md +593 -3
  3. package/CONTRIBUTING.md +26 -0
  4. package/base/base.ts +2 -1
  5. package/client/clientRuntime.ts +1 -0
  6. package/client/cn.ts +2 -2
  7. package/client/csrTypes.ts +15 -1
  8. package/client/frameConfig.ts +5 -2
  9. package/client/index.ts +249 -26
  10. package/client/locale.ts +1 -0
  11. package/client/makePageProto.tsx +33 -82
  12. package/client/nativeThemeColor.ts +51 -0
  13. package/client/route/RouteDefinition.ts +24 -7
  14. package/client/route/RouteGuards.ts +2 -1
  15. package/client/route/RouteHead.ts +11 -2
  16. package/client/route/routeArgs.ts +7 -0
  17. package/client/router.ts +25 -6
  18. package/client/rscNavigation.ts +3 -3
  19. package/client/rscRoutePatch.ts +42 -0
  20. package/client/viewportMeta.ts +34 -4
  21. package/common/CodeTranscript.ts +1 -1
  22. package/common/PipelinePlanSchema.ts +2 -2
  23. package/common/akanGraph.ts +1 -1
  24. package/common/err.ts +122 -0
  25. package/common/facetBarrel.ts +38 -0
  26. package/common/failureCode.ts +18 -0
  27. package/common/index.ts +9 -0
  28. package/common/isGuardRefusal.ts +14 -0
  29. package/common/mcpExposure.ts +17 -4
  30. package/common/mcpFailure.ts +9 -0
  31. package/common/pipelinePlan.ts +1 -1
  32. package/common/restartSchedule.ts +55 -0
  33. package/common/routeConvention.ts +3 -1
  34. package/common/types.ts +18 -1
  35. package/constant/constantRegistry.ts +4 -8
  36. package/constant/crystalize.ts +1 -2
  37. package/constant/getDefault.ts +1 -1
  38. package/constant/immerify.ts +1 -1
  39. package/constant/index.ts +78 -21
  40. package/constant/purify.ts +4 -9
  41. package/constant/serialize.ts +4 -2
  42. package/constant/types.ts +1 -0
  43. package/constant/via.ts +1 -2
  44. package/dictionary/agent.dictionary.ts +4 -0
  45. package/dictionary/base.dictionary.ts +1 -0
  46. package/dictionary/locale.ts +1 -1
  47. package/dictionary/trans.ts +14 -97
  48. package/document/databaseRegistry.ts +2 -1
  49. package/document/documentSchema.ts +1 -0
  50. package/document/filterMeta.ts +4 -1
  51. package/document/into.ts +2 -1
  52. package/document/loaderInfo.ts +2 -1
  53. package/document/noDocumentError.ts +4 -1
  54. package/document/queryEvaluator.ts +1 -1
  55. package/document/types.ts +1 -1
  56. package/fetch/client/fetchClient.ts +87 -270
  57. package/fetch/client/fetchClientTypes.ts +49 -0
  58. package/fetch/client/fetchHandle.ts +11 -1
  59. package/fetch/client/httpClient.ts +14 -2
  60. package/fetch/client/inflightQueries.ts +17 -0
  61. package/fetch/client/remoteError.ts +4 -20
  62. package/fetch/client/requestScope.ts +32 -0
  63. package/fetch/client/signalCatalog.ts +131 -0
  64. package/fetch/client/wsClient.ts +11 -0
  65. package/fetch/index.ts +1 -0
  66. package/fetch/staleReads.ts +27 -0
  67. package/fetch/streamedRead.ts +23 -0
  68. package/package.json +1 -1
  69. package/server/agentHooks.ts +16 -0
  70. package/server/akanApp.ts +107 -1272
  71. package/server/akanOption.ts +17 -4
  72. package/server/akanServer.ts +167 -675
  73. package/server/artifact/builderRpc.ts +33 -10
  74. package/server/artifact/ipcTypes.ts +9 -3
  75. package/server/artifact/routeSeedIndexStore.ts +4 -2
  76. package/server/assetHeaders.ts +6 -0
  77. package/server/console.ts +6 -4
  78. package/server/decorators.ts +2 -2
  79. package/server/devtools/README.md +4 -3
  80. package/server/devtools/devtoolsRouter.ts +9 -5
  81. package/server/devtools/studio/studioRoute.ts +18 -11
  82. package/server/di/diLifecycle.ts +24 -35
  83. package/server/di/predefinedAdaptor.ts +24 -1
  84. package/server/di/resolveHierarchy.ts +19 -6
  85. package/server/di/utils.ts +7 -3
  86. package/server/ed25519Key.ts +31 -15
  87. package/server/flightRowReader.ts +95 -18
  88. package/server/gateway/childSupervisor.ts +326 -0
  89. package/server/gateway/devHostChannel.ts +47 -0
  90. package/server/gateway/gatewayChildren.ts +135 -0
  91. package/server/gateway/gatewayConfig.ts +182 -0
  92. package/server/gateway/gatewayHttpProxy.ts +231 -0
  93. package/server/gateway/gatewayLogging.ts +111 -0
  94. package/server/gateway/gatewayRooms.ts +141 -0
  95. package/server/gateway/gatewayStatus.ts +116 -0
  96. package/server/gateway/gatewayStatusPage.ts +54 -0
  97. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  98. package/server/head.tsx +4 -19
  99. package/server/hmr/devHmrController.ts +10 -1
  100. package/server/htmlResultCache.ts +234 -0
  101. package/server/imageOptimizer.ts +4 -1
  102. package/server/index.ts +257 -17
  103. package/server/lifecycle/parentChannel.ts +78 -0
  104. package/server/lifecycle/shutdownManager.ts +6 -3
  105. package/server/lifecycle/startGuard.ts +90 -0
  106. package/server/logging/logControlSocket.ts +42 -3
  107. package/server/logging/serverLogging.ts +74 -0
  108. package/server/machine/machineToken.ts +10 -3
  109. package/server/mcp/AgentTools.ts +149 -0
  110. package/server/mcp/AgentToolsAccount.ts +26 -0
  111. package/server/mcp/McpDispatcher.ts +48 -19
  112. package/server/mcp/McpPages.ts +21 -6
  113. package/server/mcp/McpRateLimiter.ts +14 -0
  114. package/server/mcp/McpRouter.ts +52 -23
  115. package/server/mcp/McpUiSession.ts +2 -1
  116. package/server/mcp/index.ts +1 -0
  117. package/server/nativeFile.ts +30 -11
  118. package/server/nativeSecret.ts +12 -3
  119. package/server/oauth/OAuthClientIdMetadata.ts +2 -2
  120. package/server/ops/opsRoute.ts +5 -1
  121. package/server/ops/opsToken.ts +3 -1
  122. package/server/resolver/CascadeRunner.ts +10 -4
  123. package/server/resolver/database.resolver.ts +10 -417
  124. package/server/resolver/databaseModelInstance.ts +200 -0
  125. package/server/resolver/invalidSignal.ts +7 -0
  126. package/server/resolver/livePause.ts +34 -0
  127. package/server/resolver/modelFacade.ts +136 -0
  128. package/server/resolver/modelLoaders.ts +52 -0
  129. package/server/resolver/modelSchema.ts +52 -0
  130. package/server/resolver/signal.resolver.ts +92 -116
  131. package/server/resolver/timedQuery.ts +16 -0
  132. package/server/resolver/websocketOf.ts +23 -0
  133. package/server/routeElementComposer.tsx +131 -9
  134. package/server/routeState.ts +5 -1
  135. package/server/routeTreeBuilder.ts +22 -9
  136. package/server/routing/apiRouter.ts +44 -25
  137. package/server/routing/builtinRoutes.ts +194 -0
  138. package/server/routing/localRooms.ts +34 -0
  139. package/server/routing/roomReplay.ts +2 -2
  140. package/server/routing/serverLimits.ts +4 -1
  141. package/server/routing/serverListener.ts +194 -0
  142. package/server/rscClient.tsx +210 -227
  143. package/server/rscClientCache.ts +165 -0
  144. package/server/rscClientChunks.ts +209 -0
  145. package/server/rscClientFetch.ts +15 -3
  146. package/server/rscClientPatch.ts +78 -15
  147. package/server/rscDocumentHead.tsx +170 -0
  148. package/server/rscFlightRenderer.ts +83 -0
  149. package/server/rscFlightStream.ts +257 -0
  150. package/server/rscHeadPatch.ts +17 -56
  151. package/server/rscHostReloads.ts +238 -0
  152. package/server/rscHostRenderStream.ts +297 -0
  153. package/server/rscHostRequests.ts +158 -0
  154. package/server/rscHttp.ts +18 -6
  155. package/server/rscInlineStream.ts +34 -0
  156. package/server/rscNavigationState.ts +21 -1
  157. package/server/rscPagePrompts.ts +11 -5
  158. package/server/rscParkedRedirect.ts +23 -0
  159. package/server/rscPatchPlanner.ts +220 -0
  160. package/server/rscPrefetchCache.ts +68 -32
  161. package/server/rscRenderControl.ts +33 -0
  162. package/server/rscRenderFallbacks.ts +297 -0
  163. package/server/rscRenderHandler.ts +439 -0
  164. package/server/rscRenderStats.ts +49 -0
  165. package/server/rscResponse.ts +78 -0
  166. package/server/rscResultCaches.ts +74 -0
  167. package/server/rscRouteDocument.tsx +299 -0
  168. package/server/rscSegmentOutlet.tsx +24 -5
  169. package/server/rscSegmentOutletReference.ts +14 -12
  170. package/server/rscWorker.tsx +86 -1392
  171. package/server/rscWorkerCache.ts +56 -0
  172. package/server/rscWorkerHost.ts +145 -811
  173. package/server/rscWorkerProcess.ts +155 -0
  174. package/server/rscWorkerRecycler.ts +128 -0
  175. package/server/serverConfig.ts +128 -0
  176. package/server/serverMetrics.ts +52 -0
  177. package/server/sitemap.ts +1 -0
  178. package/server/ssrFromRscRenderer.tsx +20 -20
  179. package/server/ssrTypes.ts +9 -0
  180. package/server/webArtifact.ts +86 -0
  181. package/server/webAssetRoutes.ts +84 -0
  182. package/server/webCsrSurface.ts +172 -0
  183. package/server/webDocumentRoute.ts +180 -0
  184. package/server/webRouteContext.ts +232 -0
  185. package/server/webRouter.ts +126 -1242
  186. package/server/webRscRoute.ts +155 -0
  187. package/server/webSiteFiles.ts +139 -0
  188. package/server/wellKnownRoutes.ts +73 -0
  189. package/service/agent.service.ts +59 -5
  190. package/service/agentAccounts.ts +19 -0
  191. package/service/agentLoop/agentLoop.ts +387 -0
  192. package/service/agentLoop/agentLoopTypes.ts +112 -0
  193. package/service/agentLoop/deltaStream.ts +40 -0
  194. package/service/agentLoop/loopCompaction.ts +135 -0
  195. package/service/agentLoop/loopRequest.ts +62 -0
  196. package/service/agentLoop/loopToolOutput.ts +54 -0
  197. package/service/agentLoop/loopToolkits.ts +107 -0
  198. package/service/agentLoop/loopTranscript.ts +102 -0
  199. package/{signal → service}/agentMeter.ts +83 -15
  200. package/{signal → service}/agentRelayPolicy.ts +30 -7
  201. package/service/documentStoreError.ts +16 -0
  202. package/service/index.ts +7 -0
  203. package/service/injectError.ts +5 -0
  204. package/service/injectInfo.ts +30 -18
  205. package/service/insightQueryError.ts +19 -0
  206. package/service/ipcTypes.ts +3 -1
  207. package/service/liveSyncHub.ts +5 -2
  208. package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
  209. package/service/predefinedAdaptor/anthropicLlm.ts +52 -21
  210. package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
  211. package/service/predefinedAdaptor/compress.adaptor.ts +7 -3
  212. package/service/predefinedAdaptor/database.adaptor.ts +3 -1
  213. package/service/predefinedAdaptor/documentTransfer.ts +2 -1
  214. package/service/predefinedAdaptor/index.ts +2 -0
  215. package/service/predefinedAdaptor/insightQuery.ts +35 -11
  216. package/service/predefinedAdaptor/llm.adaptor.ts +22 -2
  217. package/service/predefinedAdaptor/llmSpend.ts +80 -0
  218. package/service/predefinedAdaptor/openaiDialect.ts +52 -17
  219. package/service/predefinedAdaptor/openaiLlm.ts +17 -9
  220. package/service/predefinedAdaptor/role.adaptor.ts +2 -0
  221. package/service/predefinedAdaptor/searchIndex.ts +5 -1
  222. package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
  223. package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
  224. package/service/predefinedAdaptor/solidSqlite.ts +3 -2
  225. package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
  226. package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
  227. package/service/predefinedAdaptor/sql/DocumentWriter.ts +292 -0
  228. package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
  229. package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
  230. package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
  231. package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
  232. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
  233. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +83 -1124
  234. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +319 -0
  235. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
  236. package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
  237. package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
  238. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +3 -3
  239. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  240. package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
  241. package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
  242. package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
  243. package/service/predefinedAdaptor/sql/values.ts +8 -4
  244. package/service/predefinedAdaptor/sseData.ts +14 -0
  245. package/service/predefinedAdaptor/storage.adaptor.ts +9 -4
  246. package/service/predefinedAdaptor/websocket.adaptor.ts +199 -43
  247. package/service/serve.ts +3 -2
  248. package/service/serviceModule.ts +2 -2
  249. package/service/serviceRegistry.ts +1 -0
  250. package/signal/SignalFailure.ts +30 -1
  251. package/signal/agent.signal.ts +30 -9
  252. package/signal/agentTurnStream.ts +12 -8
  253. package/signal/byIdRead.ts +18 -0
  254. package/signal/carriedClientIps.ts +1 -0
  255. package/signal/endpointErrorContract.ts +20 -2
  256. package/signal/endpointInfo.ts +6 -5
  257. package/signal/exception.ts +1 -0
  258. package/signal/index.ts +314 -30
  259. package/signal/internalInfo.ts +6 -4
  260. package/signal/mcp/McpDocument.ts +8 -1
  261. package/signal/mcp/Msg.ts +23 -10
  262. package/signal/mcp/index.ts +1 -0
  263. package/signal/mcp/promptError.ts +9 -0
  264. package/signal/middleware.ts +12 -3
  265. package/signal/openapi/openapi.ts +10 -1
  266. package/signal/resolveFieldContext.ts +34 -0
  267. package/signal/serializer/fetch.serializer.ts +23 -15
  268. package/signal/signalContext.ts +24 -57
  269. package/signal/signalContractError.ts +10 -0
  270. package/signal/signalDeclarationError.ts +13 -0
  271. package/signal/signalRegistry.ts +3 -1
  272. package/signal/slice.ts +24 -20
  273. package/signal/sliceInfo.ts +12 -9
  274. package/signal/trace.ts +3 -0
  275. package/signal/types.ts +35 -6
  276. package/store/action.ts +44 -1086
  277. package/store/actionErrorKey.ts +9 -0
  278. package/store/actionOption.ts +22 -0
  279. package/store/baseSt.ts +1 -0
  280. package/store/draftFlush.ts +5 -0
  281. package/store/draftStore.ts +2 -0
  282. package/store/formDrafts.ts +115 -0
  283. package/store/formFieldSetters.ts +229 -0
  284. package/store/index.ts +125 -17
  285. package/store/modelActionContext.ts +65 -0
  286. package/store/modelListPatch.ts +53 -0
  287. package/store/modelOpenActions.ts +158 -0
  288. package/store/modelWriteActions.ts +240 -0
  289. package/store/modelWriteGuard.ts +82 -0
  290. package/store/openSeq.ts +34 -0
  291. package/store/rootStore.ts +2 -0
  292. package/store/sliceListActions.ts +370 -0
  293. package/store/sliceLiveActions.ts +130 -0
  294. package/store/stateBuilder.ts +2 -0
  295. package/store/storeInstance.ts +9 -10
  296. package/store/uploadPoll.ts +52 -0
  297. package/store/withSelector.ts +6 -4
  298. package/types/base/base.d.ts +2 -1
  299. package/types/client/clientRuntime.d.ts +1 -0
  300. package/types/client/cn.d.ts +2 -2
  301. package/types/client/csrTypes.d.ts +15 -1
  302. package/types/client/frameConfig.d.ts +1 -0
  303. package/types/client/index.d.ts +25 -26
  304. package/types/client/locale.d.ts +1 -0
  305. package/types/client/makePageProto.d.ts +28 -26091
  306. package/types/client/nativeThemeColor.d.ts +6 -0
  307. package/types/client/route/RouteDefinition.d.ts +2 -2
  308. package/types/client/route/RouteHead.d.ts +5 -1
  309. package/types/client/route/routeArgs.d.ts +6 -0
  310. package/types/client/router.d.ts +6 -3
  311. package/types/client/rscNavigation.d.ts +3 -2
  312. package/types/client/rscRoutePatch.d.ts +22 -0
  313. package/types/client/viewportMeta.d.ts +3 -1
  314. package/types/common/CodeTranscript.d.ts +1 -1
  315. package/types/common/akanGraph.d.ts +1 -1
  316. package/types/common/err.d.ts +48 -0
  317. package/types/common/facetBarrel.d.ts +4 -0
  318. package/types/common/failureCode.d.ts +6 -0
  319. package/types/common/index.d.ts +8 -2
  320. package/types/common/isGuardRefusal.d.ts +3 -0
  321. package/types/common/mcpExposure.d.ts +9 -2
  322. package/types/common/mcpFailure.d.ts +6 -0
  323. package/types/common/restartSchedule.d.ts +16 -0
  324. package/types/common/routeConvention.d.ts +2 -0
  325. package/types/common/types.d.ts +18 -1
  326. package/types/constant/constantRegistry.d.ts +3 -1
  327. package/types/constant/crystalize.d.ts +1 -1
  328. package/types/constant/getDefault.d.ts +1 -1
  329. package/types/constant/immerify.d.ts +1 -1
  330. package/types/constant/index.d.ts +21 -21
  331. package/types/constant/purify.d.ts +2 -1
  332. package/types/constant/serialize.d.ts +1 -1
  333. package/types/constant/types.d.ts +1 -0
  334. package/types/dictionary/agent.dictionary.d.ts +1 -1
  335. package/types/dictionary/base.dictionary.d.ts +1 -1
  336. package/types/dictionary/dictionary.d.ts +9 -9
  337. package/types/dictionary/locale.d.ts +1 -1
  338. package/types/dictionary/trans.d.ts +3 -26
  339. package/types/document/databaseRegistry.d.ts +2 -1
  340. package/types/document/documentSchema.d.ts +1 -0
  341. package/types/document/filterMeta.d.ts +4 -1
  342. package/types/document/into.d.ts +1 -1
  343. package/types/document/loaderInfo.d.ts +2 -1
  344. package/types/document/noDocumentError.d.ts +8 -1
  345. package/types/document/queryEvaluator.d.ts +1 -1
  346. package/types/document/types.d.ts +1 -1
  347. package/types/fetch/client/fetchClient.d.ts +6 -36
  348. package/types/fetch/client/fetchClientTypes.d.ts +40 -0
  349. package/types/fetch/client/fetchHandle.d.ts +1 -0
  350. package/types/fetch/client/httpClient.d.ts +2 -0
  351. package/types/fetch/client/inflightQueries.d.ts +2 -0
  352. package/types/fetch/client/remoteError.d.ts +0 -4
  353. package/types/fetch/client/requestScope.d.ts +6 -0
  354. package/types/fetch/client/signalCatalog.d.ts +25 -0
  355. package/types/fetch/client/wsClient.d.ts +1 -0
  356. package/types/fetch/index.d.ts +1 -0
  357. package/types/fetch/staleReads.d.ts +8 -0
  358. package/types/fetch/streamedRead.d.ts +8 -0
  359. package/types/server/agentHooks.d.ts +4 -0
  360. package/types/server/akanApp.d.ts +2 -20
  361. package/types/server/akanOption.d.ts +9 -3
  362. package/types/server/akanServer.d.ts +1 -1
  363. package/types/server/artifact/builderRpc.d.ts +8 -0
  364. package/types/server/artifact/ipcTypes.d.ts +8 -0
  365. package/types/server/assetHeaders.d.ts +1 -0
  366. package/types/server/console.d.ts +4 -3
  367. package/types/server/devtools/devtoolsRouter.d.ts +4 -1
  368. package/types/server/devtools/studio/studioRoute.d.ts +2 -1
  369. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  370. package/types/server/ed25519Key.d.ts +1 -0
  371. package/types/server/flightRowReader.d.ts +3 -1
  372. package/types/server/gateway/childSupervisor.d.ts +33 -0
  373. package/types/server/gateway/devHostChannel.d.ts +14 -0
  374. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  375. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  376. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  377. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  378. package/types/server/gateway/gatewayRooms.d.ts +25 -0
  379. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  380. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  381. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  382. package/types/server/head.d.ts +2 -2
  383. package/types/server/htmlResultCache.d.ts +51 -0
  384. package/types/server/index.d.ts +17 -17
  385. package/types/server/lifecycle/parentChannel.d.ts +13 -0
  386. package/types/server/lifecycle/startGuard.d.ts +10 -0
  387. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  388. package/types/server/logging/serverLogging.d.ts +12 -0
  389. package/types/server/mcp/AgentTools.d.ts +31 -0
  390. package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
  391. package/types/server/mcp/McpDispatcher.d.ts +10 -1
  392. package/types/server/mcp/McpPages.d.ts +2 -1
  393. package/types/server/mcp/McpRateLimiter.d.ts +3 -0
  394. package/types/server/mcp/index.d.ts +1 -0
  395. package/types/server/resolver/database.resolver.d.ts +2 -2
  396. package/types/server/resolver/databaseModelInstance.d.ts +4 -0
  397. package/types/server/resolver/invalidSignal.d.ts +2 -0
  398. package/types/server/resolver/livePause.d.ts +5 -0
  399. package/types/server/resolver/modelFacade.d.ts +5 -0
  400. package/types/server/resolver/modelLoaders.d.ts +9 -0
  401. package/types/server/resolver/modelSchema.d.ts +6 -0
  402. package/types/server/resolver/signal.resolver.d.ts +2 -2
  403. package/types/server/resolver/timedQuery.d.ts +8 -0
  404. package/types/server/resolver/websocketOf.d.ts +2 -0
  405. package/types/server/routeElementComposer.d.ts +45 -6
  406. package/types/server/routeState.d.ts +2 -0
  407. package/types/server/routing/builtinRoutes.d.ts +24 -0
  408. package/types/server/routing/localRooms.d.ts +14 -0
  409. package/types/server/routing/roomReplay.d.ts +2 -2
  410. package/types/server/routing/serverListener.d.ts +31 -0
  411. package/types/server/rscClient.d.ts +1 -5
  412. package/types/server/rscClientCache.d.ts +34 -0
  413. package/types/server/rscClientChunks.d.ts +18 -0
  414. package/types/server/rscClientFetch.d.ts +1 -1
  415. package/types/server/rscClientPatch.d.ts +12 -1
  416. package/types/server/rscDocumentHead.d.ts +32 -0
  417. package/types/server/rscFlightRenderer.d.ts +14 -0
  418. package/types/server/rscFlightStream.d.ts +52 -0
  419. package/types/server/rscHeadPatch.d.ts +5 -4
  420. package/types/server/rscHostReloads.d.ts +54 -0
  421. package/types/server/rscHostRenderStream.d.ts +53 -0
  422. package/types/server/rscHostRequests.d.ts +29 -0
  423. package/types/server/rscHttp.d.ts +4 -2
  424. package/types/server/rscInlineStream.d.ts +9 -0
  425. package/types/server/rscNavigationState.d.ts +8 -3
  426. package/types/server/rscParkedRedirect.d.ts +12 -0
  427. package/types/server/rscPatchPlanner.d.ts +49 -0
  428. package/types/server/rscPrefetchCache.d.ts +8 -7
  429. package/types/server/rscRenderControl.d.ts +12 -0
  430. package/types/server/rscRenderFallbacks.d.ts +41 -0
  431. package/types/server/rscRenderHandler.d.ts +29 -0
  432. package/types/server/rscRenderStats.d.ts +32 -0
  433. package/types/server/rscResponse.d.ts +9 -0
  434. package/types/server/rscResultCaches.d.ts +18 -0
  435. package/types/server/rscRouteDocument.d.ts +52 -0
  436. package/types/server/rscSegmentOutlet.d.ts +5 -0
  437. package/types/server/rscSegmentOutletReference.d.ts +2 -1
  438. package/types/server/rscWorker.d.ts +1 -3
  439. package/types/server/rscWorkerCache.d.ts +33 -1
  440. package/types/server/rscWorkerHost.d.ts +9 -76
  441. package/types/server/rscWorkerProcess.d.ts +31 -0
  442. package/types/server/rscWorkerRecycler.d.ts +22 -0
  443. package/types/server/serverConfig.d.ts +30 -0
  444. package/types/server/serverMetrics.d.ts +11 -0
  445. package/types/server/sitemap.d.ts +1 -0
  446. package/types/server/ssrFromRscRenderer.d.ts +2 -2
  447. package/types/server/ssrTypes.d.ts +8 -0
  448. package/types/server/webArtifact.d.ts +7 -0
  449. package/types/server/webAssetRoutes.d.ts +11 -0
  450. package/types/server/webCsrSurface.d.ts +18 -0
  451. package/types/server/webDocumentRoute.d.ts +19 -0
  452. package/types/server/webRouteContext.d.ts +45 -0
  453. package/types/server/webRouter.d.ts +4 -35
  454. package/types/server/webRscRoute.d.ts +24 -0
  455. package/types/server/webSiteFiles.d.ts +12 -0
  456. package/types/server/wellKnownRoutes.d.ts +5 -0
  457. package/types/service/agent.service.d.ts +13 -4
  458. package/types/service/agentAccounts.d.ts +8 -0
  459. package/types/service/agentLoop/agentLoop.d.ts +31 -0
  460. package/types/service/agentLoop/agentLoopTypes.d.ts +126 -0
  461. package/types/service/agentLoop/deltaStream.d.ts +3 -0
  462. package/types/service/agentLoop/loopCompaction.d.ts +11 -0
  463. package/types/service/agentLoop/loopRequest.d.ts +6 -0
  464. package/types/service/agentLoop/loopToolOutput.d.ts +7 -0
  465. package/types/service/agentLoop/loopToolkits.d.ts +14 -0
  466. package/types/service/agentLoop/loopTranscript.d.ts +12 -0
  467. package/types/service/agentMeter.d.ts +50 -0
  468. package/types/service/agentRelayPolicy.d.ts +45 -0
  469. package/types/service/documentStoreError.d.ts +7 -0
  470. package/types/service/index.d.ts +7 -0
  471. package/types/service/injectError.d.ts +4 -0
  472. package/types/service/injectInfo.d.ts +2 -1
  473. package/types/service/insightQueryError.d.ts +9 -0
  474. package/types/service/ipcTypes.d.ts +6 -0
  475. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
  476. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
  477. package/types/service/predefinedAdaptor/index.d.ts +2 -0
  478. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +18 -2
  479. package/types/service/predefinedAdaptor/llmSpend.d.ts +22 -0
  480. package/types/service/predefinedAdaptor/openaiDialect.d.ts +2 -1
  481. package/types/service/predefinedAdaptor/openaiLlm.d.ts +1 -1
  482. package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
  483. package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
  484. package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
  485. package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
  486. package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
  487. package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +24 -0
  488. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
  489. package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
  490. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -32
  491. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +20 -0
  492. package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
  493. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +1 -14
  494. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  495. package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
  496. package/types/service/predefinedAdaptor/sseData.d.ts +5 -0
  497. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +14 -5
  498. package/types/service/serviceModule.d.ts +1 -1
  499. package/types/service/serviceRegistry.d.ts +1 -0
  500. package/types/signal/SignalFailure.d.ts +2 -0
  501. package/types/signal/agentTurnStream.d.ts +2 -1
  502. package/types/signal/byIdRead.d.ts +7 -0
  503. package/types/signal/carriedClientIps.d.ts +4 -0
  504. package/types/signal/endpointErrorContract.d.ts +3 -0
  505. package/types/signal/exception.d.ts +1 -0
  506. package/types/signal/index.d.ts +32 -30
  507. package/types/signal/mcp/McpDocument.d.ts +2 -0
  508. package/types/signal/mcp/index.d.ts +1 -0
  509. package/types/signal/mcp/promptError.d.ts +5 -0
  510. package/types/signal/resolveFieldContext.d.ts +15 -0
  511. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  512. package/types/signal/signalContext.d.ts +1 -13
  513. package/types/signal/signalContractError.d.ts +4 -0
  514. package/types/signal/signalDeclarationError.d.ts +4 -0
  515. package/types/signal/slice.d.ts +15 -13
  516. package/types/signal/trace.d.ts +3 -0
  517. package/types/signal/types.d.ts +33 -6
  518. package/types/store/action.d.ts +8 -27
  519. package/types/store/actionErrorKey.d.ts +1 -0
  520. package/types/store/actionOption.d.ts +24 -0
  521. package/types/store/baseSt.d.ts +2 -295
  522. package/types/store/draftFlush.d.ts +4 -0
  523. package/types/store/formDrafts.d.ts +21 -0
  524. package/types/store/formFieldSetters.d.ts +80 -0
  525. package/types/store/index.d.ts +17 -16
  526. package/types/store/modelActionContext.d.ts +189 -0
  527. package/types/store/modelListPatch.d.ts +34 -0
  528. package/types/store/modelOpenActions.d.ts +12 -0
  529. package/types/store/modelWriteActions.d.ts +16 -0
  530. package/types/store/modelWriteGuard.d.ts +42 -0
  531. package/types/store/openSeq.d.ts +17 -0
  532. package/types/store/rootStore.d.ts +6 -0
  533. package/types/store/sliceListActions.d.ts +295 -0
  534. package/types/store/sliceLiveActions.d.ts +6 -0
  535. package/types/store/stateBuilder.d.ts +2 -0
  536. package/types/store/uploadPoll.d.ts +16 -0
  537. package/types/store/withSelector.d.ts +1 -1
  538. package/types/ui/Agent/Chat.d.ts +5 -2
  539. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  540. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  541. package/types/ui/Field/Choice.d.ts +2 -1
  542. package/types/ui/Field/index.d.ts +1 -1
  543. package/types/ui/Link/inputModality.d.ts +5 -0
  544. package/types/ui/Link/viewportPrefetch.d.ts +4 -0
  545. package/types/ui/Load/Edit_Client.d.ts +2 -0
  546. package/types/ui/Load/Pagination.d.ts +4 -1
  547. package/types/ui/Load/Stream.d.ts +7 -1
  548. package/types/ui/Load/StreamBoundary.d.ts +20 -0
  549. package/types/ui/Load/Units.d.ts +2 -0
  550. package/types/ui/Load/View.d.ts +2 -0
  551. package/types/ui/Reference/origin.d.ts +1 -0
  552. package/types/ui/index.d.ts +1 -1
  553. package/types/ui/overlayLayer.d.ts +6 -1
  554. package/types/ui/recipe/badgeRecipe.d.ts +3 -3
  555. package/types/ui/recipe/buttonRecipe.d.ts +3 -3
  556. package/types/ui/recipe/inputRecipe.d.ts +1 -1
  557. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  558. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  559. package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
  560. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +18 -11
  561. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  562. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  563. package/types/vendor/use-agentic/index.d.ts +1 -0
  564. package/types/vendor/use-agentic/types.d.ts +11 -0
  565. package/types/webkit/CsrGuards.d.ts +2 -0
  566. package/types/webkit/RouteLevelBoundary.d.ts +17 -0
  567. package/types/webkit/nativeCore.d.ts +1 -0
  568. package/types/webkit/nativePurchase.d.ts +2 -1
  569. package/types/webkit/useCsrKeyboard.d.ts +19 -0
  570. package/types/webkit/useCsrLocationState.d.ts +21 -0
  571. package/types/webkit/useCsrNavigation.d.ts +25 -0
  572. package/types/webkit/useCsrRefs.d.ts +33 -0
  573. package/types/webkit/useCsrRenderTrace.d.ts +13 -0
  574. package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
  575. package/types/webkit/useCsrTransitions.d.ts +2 -0
  576. package/types/webkit/useFrameRuntime.d.ts +1 -0
  577. package/types/webkit/useGeoLocation.d.ts +1 -1
  578. package/types/webkit/useHistory.d.ts +2 -3
  579. package/types/webkit/usePurchase.d.ts +1 -1
  580. package/types/webkit/useResolvedFrame.d.ts +38 -0
  581. package/types/webkit/useSyncNavigation.d.ts +22 -0
  582. package/types/webkit/useTransitionStore.d.ts +1 -0
  583. package/ui/Agent/Chat.tsx +392 -235
  584. package/ui/Agent/ChatHeader.tsx +59 -0
  585. package/ui/Agent/ChatPendingCards.tsx +49 -0
  586. package/ui/Agent/fetchRunner.ts +8 -1
  587. package/ui/BottomSheet.tsx +1 -1
  588. package/ui/Button.tsx +1 -0
  589. package/ui/Data/Item.tsx +2 -2
  590. package/ui/Data/ListContainer.tsx +348 -181
  591. package/ui/Data/useViewModal.ts +10 -4
  592. package/ui/Dialog/LegacyModal.tsx +1 -1
  593. package/ui/Dialog/Modal.tsx +1 -1
  594. package/ui/Field/Choice.tsx +3 -1
  595. package/ui/Link/inputModality.ts +21 -0
  596. package/ui/Link/prefetchIntent.ts +7 -25
  597. package/ui/Link/viewportPrefetch.ts +30 -0
  598. package/ui/Load/Edit_Client.tsx +7 -1
  599. package/ui/Load/Pagination.tsx +10 -2
  600. package/ui/Load/Stream.tsx +24 -4
  601. package/ui/Load/StreamBoundary.tsx +65 -0
  602. package/ui/Load/Units.tsx +3 -0
  603. package/ui/Load/View.tsx +5 -1
  604. package/ui/Model/EditModal.tsx +2 -1
  605. package/ui/Popconfirm.tsx +1 -1
  606. package/ui/Reference/origin.ts +1 -0
  607. package/ui/Select.tsx +43 -51
  608. package/ui/Signal/RestApi.tsx +3 -2
  609. package/ui/System/Client.tsx +32 -8
  610. package/ui/index.ts +4 -0
  611. package/ui/overlayLayer.ts +22 -1
  612. package/vendor/@akanjs/native/CHANGELOG.md +7 -1
  613. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +27 -12
  614. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
  615. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  616. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  617. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +509 -0
  618. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  619. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
  620. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  621. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  622. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  623. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  624. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  625. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  626. package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
  627. package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
  628. package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
  629. package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
  630. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  631. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  632. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +18 -11
  633. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  634. package/vendor/use-agentic/AgentSession.ts +11 -11
  635. package/vendor/use-agentic/CHANGELOG.md +46 -1
  636. package/vendor/use-agentic/Compaction.ts +2 -1
  637. package/vendor/use-agentic/ToolRunner.ts +6 -3
  638. package/vendor/use-agentic/Transcript.ts +6 -3
  639. package/vendor/use-agentic/WIRE.md +29 -7
  640. package/vendor/use-agentic/failureCode.ts +44 -0
  641. package/vendor/use-agentic/httpRunner.ts +15 -4
  642. package/vendor/use-agentic/index.ts +1 -0
  643. package/vendor/use-agentic/types.ts +11 -0
  644. package/webkit/CsrGuards.ts +7 -2
  645. package/webkit/McpAppAgent.ts +8 -3
  646. package/webkit/McpAppFetchBridge.ts +11 -5
  647. package/webkit/RouteLevelBoundary.tsx +37 -0
  648. package/webkit/nativeCore.ts +1 -0
  649. package/webkit/nativePurchase.ts +6 -3
  650. package/webkit/useCamera.tsx +22 -21
  651. package/webkit/useCsrKeyboard.ts +155 -0
  652. package/webkit/useCsrLocationState.ts +58 -0
  653. package/webkit/useCsrNavigation.ts +302 -0
  654. package/webkit/useCsrRefs.ts +52 -0
  655. package/webkit/useCsrRenderTrace.ts +68 -0
  656. package/webkit/useCsrStackLifecycle.ts +120 -0
  657. package/webkit/useCsrTransitions.ts +552 -0
  658. package/webkit/useCsrValues.ts +69 -1234
  659. package/webkit/useGeoLocation.tsx +4 -1
  660. package/webkit/useHistory.ts +2 -2
  661. package/webkit/useLocation.ts +3 -2
  662. package/webkit/usePurchase.tsx +4 -2
  663. package/webkit/useResolvedFrame.ts +116 -0
  664. package/webkit/useSyncNavigation.ts +109 -0
  665. package/webkit/useTransitionStore.ts +13 -0
  666. package/types/signal/agentMeter.d.ts +0 -27
  667. package/types/signal/agentRelayPolicy.d.ts +0 -25
@@ -1,29 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { AkanWebConfig } from "akanjs";
4
- import {
5
- type AkanI18nConfig,
6
- AppHosts,
7
- CookieJar,
8
- DEFAULT_AKAN_I18N,
9
- getBasePathFromPathname,
10
- LocalePath,
11
- Logger,
12
- type LogRecord,
13
- parseAkanI18nEnv,
14
- RequestLocale,
15
- resolveSubRouteHosts,
16
- } from "akanjs/common";
17
- import { type AkanRequestStore, createRequestStore } from "akanjs/fetch";
4
+ import { AkanError } from "akanjs/base";
5
+ import { AppHosts, Logger, type LogRecord, resolveSubRouteHosts } from "akanjs/common";
18
6
  import type { AkanMetricsReport } from "akanjs/service";
19
7
  import { PageDefinition } from "../client/route/PageDefinition";
20
- import { type Dictionary, TranslatorState } from "../client/translatorState";
21
- import { getWebManifestBasePath } from "../client/webManifest";
22
8
  import type { PagePromptSource } from "../signal/mcp/pagePrompt";
23
- import { SignalContext } from "../signal/signalContext";
24
9
  import {
25
10
  type BuilderRpc,
26
- type MergedManifest,
27
11
  ModulePreloadPlan,
28
12
  RouteClientCache,
29
13
  type RouteSeedIndex,
@@ -31,254 +15,27 @@ import {
31
15
  type RoutesManifest,
32
16
  RoutesManifestStore,
33
17
  } from "./artifact";
34
- import { type AssetHeaderOptions, applySecurityHeaders, assetHeaders, strictTransportSecurity } from "./assetHeaders";
35
- import {
36
- getClientFacingOrigin,
37
- hasRouteCacheInvalidationScope,
38
- LruTtlCache,
39
- parsePositiveInt,
40
- type RouteCacheEntry,
41
- type RouteCacheInvalidation,
42
- type RouteCacheRenderState,
43
- resolveHtmlCacheControl,
44
- resolvePublicRouteCacheEntryDecision,
45
- resolveRouteCacheStoreTtl,
46
- shouldInvalidateRouteCacheEntry,
47
- shouldStoreRouteCache,
48
- } from "./cachePolicy";
49
- import {
50
- type EncodedBody,
51
- encodeBody,
52
- encodedBodyResponse,
53
- encodedFileResponse,
54
- isCompressibleContentType,
55
- matchesIfNoneMatch,
56
- varyOnEncoding,
57
- } from "./contentEncoding";
58
- import { isCrawlerUserAgent } from "./crawler";
59
- import { HMR_CLIENT_SCRIPT } from "./hmr/clientScript";
60
- import { CSR_DEV_ROUTE_PREFIX, resolveDevCsrMode, SSR_DEV_DIRNAME, SSR_DEV_ROUTE_PREFIX } from "./hmr/csrDevManifest";
18
+ import type { RouteCacheInvalidation } from "./cachePolicy";
19
+ import { resolveDevCsrMode, SSR_DEV_DIRNAME, SSR_DEV_ROUTE_PREFIX } from "./hmr/csrDevManifest";
61
20
  import { CsrDevShell } from "./hmr/csrDevShell";
62
21
  import { DevHmrController } from "./hmr/devHmrController";
63
- import { SsrDevShim } from "./hmr/ssrDevShim";
64
22
  import type { HmrWsData, HmrWsHub } from "./hmr/wsHub";
23
+ import { HtmlResultCache } from "./htmlResultCache";
65
24
  import { ImageOptimizer } from "./imageOptimizer";
66
25
  import type { McpAppShellSource } from "./mcp/McpApps";
67
- import { normalizeHost, resolveArtifactDir, warnIgnoredSubRouteBasePaths } from "./proxy/hostBasePathWebProxy";
68
- import { createDefaultRobotsTxt } from "./robots";
69
- import {
70
- AKAN_RSC_DICTIONARY_HEADER,
71
- AKAN_RSC_IMPORT_MAP_HEADER,
72
- AKAN_RSC_NOT_FOUND_HEADER,
73
- AKAN_RSC_PATCH_HEAD_SAFE_HEADER,
74
- AKAN_RSC_PATCH_HEAD_SNAPSHOT_HEADER,
75
- AKAN_RSC_PATCH_SEGMENT_PATH_HEADER,
76
- AKAN_RSC_PATCH_START_INDEX_HEADER,
77
- AKAN_RSC_PATCH_START_SEGMENT_HEADER,
78
- AKAN_RSC_PREFETCH_HEADER,
79
- AKAN_RSC_RESPONSE_STATE_HEADER,
80
- } from "./routeState";
81
- import {
82
- type RscRedirectMethod,
83
- type RscRedirectStatus,
84
- type RscRenderResult,
85
- RscWorker,
86
- type RscWorkerStatus,
87
- } from "./rscWorkerHost";
26
+ import { resolveArtifactDir, warnIgnoredSubRouteBasePaths } from "./proxy/hostBasePathWebProxy";
27
+ import { RscWorker, type RscWorkerStatus } from "./rscWorkerHost";
88
28
  import { SessionRefresh } from "./sessionRefresh";
89
- import { createDefaultSitemapXml, getSitemapBasePath } from "./sitemap";
90
29
  import { SsrFromRscRenderer } from "./ssrFromRscRenderer";
91
- import type { RscTraceMetadata, SsrManifest } from "./ssrTypes";
92
- import { resolveStaticPath, staysInTree } from "./staticPath";
93
- import { getPathnameLocale } from "./systemPageDocument";
94
- import { createSubRouteIndexResponse, createSystemPageResponse, getSystemPageHomeHref } from "./systemPages";
95
30
  import { type BaseBuildArtifact, type HttpRoutes, type RenderState, resolveWebConfig } from "./types";
96
-
97
- const CLIENT_CLOSED_REQUEST_STATUS = 499;
98
- export const DEFAULT_HTML_RESULT_CACHE_MAX_BODY_BYTES = 2 * 1024 * 1024;
99
- /** Well above any sensible TTL: this only has to reclaim a cache nobody is reading, not track expiry closely. */
100
- const ROUTE_CACHE_SWEEP_INTERVAL_MS = 60_000;
101
- const APPLE_APP_SITE_ASSOCIATION_PATH = "/.well-known/apple-app-site-association";
102
- const ANDROID_ASSET_LINKS_PATH = "/.well-known/assetlinks.json";
103
-
104
- export function createRscRedirectResponse(
105
- location: string,
106
- method: RscRedirectMethod,
107
- status: RscRedirectStatus = 307,
108
- ): Response {
109
- return new Response(JSON.stringify({ type: "redirect", location, method, status }), {
110
- status: 200,
111
- headers: {
112
- "Content-Type": "application/json; charset=utf-8",
113
- "Cache-Control": "no-store",
114
- "X-Akan-Redirect": location,
115
- "X-Akan-Redirect-Method": method,
116
- "X-Akan-Redirect-Status": String(status),
117
- },
118
- });
119
- }
120
-
121
- function createDocumentRedirectResponse(location: string, requestUrl: URL, status: RscRedirectStatus): Response {
122
- const target = new URL(location, requestUrl.origin);
123
- const sameOrigin = target.origin === requestUrl.origin && !target.pathname.startsWith("//");
124
- const href = sameOrigin ? `${target.pathname}${target.search}${target.hash}` : target.href;
125
- return new Response(null, { status, headers: { Location: href, "Cache-Control": "no-store" } });
126
- }
127
-
128
- export function createRscStreamResponse(stream: BodyInit, status = 200): Response {
129
- return new Response(stream, {
130
- status,
131
- headers: {
132
- "Content-Type": "text/x-component; charset=utf-8",
133
- "Cache-Control": "no-store",
134
- },
135
- });
136
- }
137
-
138
- export function createRscNotFoundFallbackResponse(): Response {
139
- return createRscStreamResponse("0:null\n", 404);
140
- }
141
-
142
- function appendRscTraceHeaders(headers: Headers, trace?: RscTraceMetadata): void {
143
- if (!trace) return;
144
- if (trace.navId) headers.set("X-Akan-Rsc-Nav-Id", trace.navId);
145
- headers.set("X-Akan-Rsc-Pathname", trace.pathname);
146
- headers.set("X-Akan-Rsc-Route", trace.routeId);
147
- headers.set("X-Akan-Rsc-Cache", trace.cache);
148
- if (trace.cacheReason) headers.set("X-Akan-Rsc-Cache-Reason", trace.cacheReason);
149
- if (trace.cacheKeyHash) headers.set("X-Akan-Rsc-Cache-Key", trace.cacheKeyHash);
150
- if (trace.partial) headers.set("X-Akan-Rsc-Partial", trace.partial);
151
- if (trace.partialReason) headers.set("X-Akan-Rsc-Partial-Reason", trace.partialReason);
152
- if (trace.partialCommonPrefixLength !== undefined) {
153
- headers.set("X-Akan-Rsc-Partial-Common-Prefix", String(trace.partialCommonPrefixLength));
154
- }
155
- if (trace.patchStartIndex !== undefined)
156
- headers.set(AKAN_RSC_PATCH_START_INDEX_HEADER, String(trace.patchStartIndex));
157
- if (trace.patchSegmentPath) headers.set(AKAN_RSC_PATCH_SEGMENT_PATH_HEADER, trace.patchSegmentPath);
158
- if (trace.patchStartSegment) headers.set(AKAN_RSC_PATCH_START_SEGMENT_HEADER, trace.patchStartSegment);
159
- if (trace.patchHeadSafe) headers.set(AKAN_RSC_PATCH_HEAD_SAFE_HEADER, "1");
160
- if (trace.patchHeadSnapshot) headers.set(AKAN_RSC_PATCH_HEAD_SNAPSHOT_HEADER, trace.patchHeadSnapshot);
161
- if (trace.routeState) headers.set(AKAN_RSC_RESPONSE_STATE_HEADER, trace.routeState);
162
- }
163
-
164
- export function cacheHtmlWhileStreaming(
165
- stream: ReadableStream<Uint8Array>,
166
- onComplete: (html: string) => void,
167
- options: {
168
- shouldCache?: () => boolean | Promise<boolean>;
169
- maxBodyBytes?: number | null;
170
- onSkip?: (reason: "body-too-large" | "store-skip") => void;
171
- } = {},
172
- ): ReadableStream<Uint8Array> {
173
- const chunks: Uint8Array[] = [];
174
- let byteLength = 0;
175
- let exceededMaxBodyBytes = false;
176
- const decoder = new TextDecoder();
177
-
178
- return stream.pipeThrough(
179
- new TransformStream<Uint8Array, Uint8Array>({
180
- transform(chunk, controller) {
181
- if (!exceededMaxBodyBytes) {
182
- byteLength += chunk.byteLength;
183
- if (options.maxBodyBytes && byteLength > options.maxBodyBytes) {
184
- exceededMaxBodyBytes = true;
185
- chunks.length = 0;
186
- } else {
187
- chunks.push(chunk.slice());
188
- }
189
- }
190
- controller.enqueue(chunk);
191
- },
192
- async flush() {
193
- if (exceededMaxBodyBytes) {
194
- options.onSkip?.("body-too-large");
195
- return;
196
- }
197
- const body = new Uint8Array(byteLength);
198
- let offset = 0;
199
- for (const chunk of chunks) {
200
- body.set(chunk, offset);
201
- offset += chunk.byteLength;
202
- }
203
- try {
204
- if (options.shouldCache && !(await options.shouldCache())) {
205
- options.onSkip?.("store-skip");
206
- return;
207
- }
208
- onComplete(decoder.decode(body));
209
- } catch {
210
- }
211
- },
212
- }),
213
- );
214
- }
215
-
216
- export function cancelStreamForHeadResponse(stream: ReadableStream<Uint8Array>, message: string): void {
217
- void stream.cancel(new DOMException(message, "AbortError")).catch(() => {
218
- });
219
- }
220
-
221
- export function resolveHtmlRouteCacheStoreTtl(input: {
222
- baseTtl: number;
223
- workerCacheState: RouteCacheRenderState;
224
- hostRequestStore: AkanRequestStore;
225
- lateControl?: { type: "redirect" | "not-found" } | null;
226
- }): number | null {
227
- if (input.lateControl) return null;
228
- const workerTtl = resolveRouteCacheStoreTtl(input.baseTtl, input.workerCacheState);
229
- if (workerTtl === null) return null;
230
- const hostCacheState = shouldStoreRouteCache({
231
- policy: input.hostRequestStore.policy,
232
- dynamicUsage: input.hostRequestStore.dynamicUsage,
233
- });
234
- return resolveRouteCacheStoreTtl(workerTtl, hostCacheState);
235
- }
236
-
237
- export async function createRscNavigationStreamResponse(
238
- result: Extract<RscRenderResult, { type: "stream" }>,
239
- ): Promise<Response> {
240
-
241
- const response = createRscStreamResponse(result.stream, result.status ?? 200);
242
- appendRscTraceHeaders(response.headers, result.trace);
243
- if (result.status === 404) response.headers.set(AKAN_RSC_NOT_FOUND_HEADER, "view");
244
- return response;
245
- }
246
-
247
- export function normalizeRscTargetUrlForHostBasePath(
248
- targetUrl: URL,
249
- options: {
250
- basePath: string | null;
251
- basePaths?: readonly string[];
252
- i18n: AkanI18nConfig;
253
- seedEntries?: RouteSeedIndex["entries"];
254
- },
255
- ): { url: URL; basePath: string | null } {
256
- const { basePath, basePaths = [], i18n, seedEntries } = options;
257
- const routeMatches = (url: URL) => !seedEntries || Boolean(RouteSeedIndexStore.match(url.pathname, seedEntries));
258
-
259
- const segments = targetUrl.pathname.split("/").filter(Boolean);
260
- const [locale, firstPath] = segments;
261
- if (!locale || !i18n.locales.includes(locale)) return { url: targetUrl, basePath: null };
262
-
263
- if (basePath) {
264
- if (firstPath === basePath) return { url: targetUrl, basePath };
265
- const normalized = new URL(targetUrl);
266
- normalized.pathname = `/${[locale, basePath, ...segments.slice(1)].join("/")}`;
267
- return { url: normalized, basePath };
268
- }
269
-
270
- const targetBasePath = firstPath && basePaths.includes(firstPath) ? firstPath : null;
271
- if (seedEntries && routeMatches(targetUrl)) return { url: targetUrl, basePath: targetBasePath ?? basePath };
272
- const candidates = [...new Set([basePath, ...basePaths].filter((bp): bp is string => Boolean(bp)))];
273
- for (const candidate of candidates) {
274
- if (firstPath === candidate) continue;
275
- const normalized = new URL(targetUrl);
276
- normalized.pathname = `/${[locale, candidate, ...segments.slice(1)].join("/")}`;
277
- if (routeMatches(normalized)) return { url: normalized, basePath: candidate };
278
- }
279
-
280
- return { url: targetUrl, basePath: targetBasePath };
281
- }
31
+ import { WebArtifact } from "./webArtifact";
32
+ import { WebAssetRoutes } from "./webAssetRoutes";
33
+ import { WebCsrSurface } from "./webCsrSurface";
34
+ import { WebDocumentRoute } from "./webDocumentRoute";
35
+ import { WebRouteContext } from "./webRouteContext";
36
+ import { WebRscRoute } from "./webRscRoute";
37
+ import { WebSiteFiles } from "./webSiteFiles";
38
+ import { WellKnownRoutes } from "./wellKnownRoutes";
282
39
 
283
40
  export interface SsrRoutesInputs {
284
41
  web: AkanWebConfig;
@@ -296,546 +53,158 @@ interface WebRouterOptions {
296
53
  prebuilt?: RoutesManifest | null;
297
54
  }
298
55
 
299
- interface CachedHtmlResult {
300
- body: EncodedBody;
301
- pathname: string;
302
- routeId?: string;
303
- tags?: string[];
304
- }
305
-
306
56
  export class WebRouter {
307
57
  /** Where the build writes each `.app()`'s view, beside `csr/`: a native app packs `csr/`, which needs none of them. */
308
58
  static readonly mcpAppViewDir = "mcp-apps";
309
59
  #logger = new Logger("WebRouter");
310
60
  #artifactDir = resolveArtifactDir();
311
- #artifact: BaseBuildArtifact;
312
- #importMapKey: string;
313
- #subRoutes: Record<string, string[]>;
314
61
  #rsc: RscWorker;
315
62
  #hub: HmrWsHub | null = null;
316
63
 
317
- #prodMode = process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
64
+ readonly #prodMode = process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
318
65
  #builderRpc: BuilderRpc | null;
319
- #routeCache: RouteClientCache;
320
66
  #devHmr: DevHmrController | null = null;
321
- #csrDevShell: CsrDevShell | null = null;
322
67
  /** Dev only: SSR pages load their client code from the dev module registry it serves. */
323
68
  #ssrDevShell: CsrDevShell | null = null;
324
- #csrArmed = false;
325
- readonly #builds = new Map<string, Promise<unknown>>();
326
- readonly #requestStats = {
327
- fullSsr: 0,
328
- rscNavigation: 0,
329
- rscPrefetch: 0,
330
- staticAsset: 0,
331
- csr: 0,
332
- image: 0,
333
- };
334
- readonly #htmlCache = new LruTtlCache<CachedHtmlResult>(
335
- parsePositiveInt(process.env.AKAN_HTML_RESULT_CACHE_MAX_ENTRIES) ?? 100,
336
- {
337
- sizeOf: (result) => result.body.byteLength,
338
- maxBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_HTML_RESULT_CACHE_MAX_BYTES),
339
- sweepIntervalMs: ROUTE_CACHE_SWEEP_INTERVAL_MS,
340
- },
341
- );
342
- #htmlCacheHits = 0;
343
- #htmlCacheMisses = 0;
344
- #htmlCacheBypass = 0;
345
- #runtimeManifest: { revision: number; manifest: MergedManifest } | null = null;
346
- renderState: RenderState;
69
+ readonly #context: WebRouteContext;
70
+ readonly #csr: WebCsrSurface;
71
+ readonly #htmlCache: HtmlResultCache;
72
+ readonly #rscRoute: WebRscRoute;
73
+ readonly #document: WebDocumentRoute;
74
+ readonly renderState: RenderState;
347
75
  /** What this router actually mounts, already intersected with what the artifact carries. */
348
76
  readonly web: AkanWebConfig;
349
- #seedIndex: RouteSeedIndex;
350
77
  readonly #prebuilt: RoutesManifest | null;
351
-
352
- readonly #modulePreloadPlan?: ModulePreloadPlan;
353
78
  constructor({ artifact, web, cssBytesByUrl, rsc, seedIndex, upgradeHmrWs, prebuilt = null }: WebRouterOptions) {
354
79
  this.#logger.verbose(`[SSR] loaded ${Object.keys(cssBytesByUrl).length} CSS assets`);
355
80
  this.web = web;
356
81
  if (process.env.NODE_ENV === "production" && !this.#prodMode)
357
82
  this.#logger.warn("[SSR] NODE_ENV=production ignored under `akan start`; serving in dev mode");
358
- this.#artifact = artifact;
359
- this.#importMapKey = Bun.hash(JSON.stringify(artifact.vendorMap)).toString(36);
83
+ const importMapKey = Bun.hash(JSON.stringify(artifact.vendorMap)).toString(36);
360
84
  const { subRoutes, ignoredBasePaths } = resolveSubRouteHosts({
361
85
  subRoutes: artifact.subRoutes,
362
86
  basePaths: artifact.basePaths,
363
87
  env: process.env.AKAN_SUB_ROUTE_HOSTS,
364
88
  });
365
- this.#subRoutes = subRoutes;
366
89
  AppHosts.declare([...artifact.domains, ...Object.values(subRoutes).flat()]);
367
90
  warnIgnoredSubRouteBasePaths(this.#logger, ignoredBasePaths);
368
91
  this.#rsc = rsc;
369
92
  this.renderState = {
370
93
  buildId: 0,
371
- cssAssets: this.#artifact.cssAssets ?? {},
94
+ cssAssets: artifact.cssAssets ?? {},
372
95
  cssBytesByUrl,
373
96
  };
374
- this.#seedIndex = seedIndex;
375
97
  this.#prebuilt = prebuilt;
376
- if (prebuilt?.modulePreloads)
377
- this.#modulePreloadPlan = new ModulePreloadPlan(prebuilt.modulePreloads, prebuilt.clientManifest);
378
- if (this.#prodMode) {
379
- this.#builderRpc = null;
380
- this.#routeCache = new RouteClientCache({
381
- buildRoute: async (routeId) => {
382
- throw new Error(
383
- `[SSR] route ${routeId} missing from production artifact — rebuild with \`akan build\` to include it`,
384
- );
385
- },
386
- });
387
- } else {
388
- this.#devHmr = new DevHmrController({
389
- artifactDir: this.#artifactDir,
98
+ let htmlCache: HtmlResultCache | null = null;
99
+ try {
100
+ let routeCache: RouteClientCache;
101
+ let csrDevShell: CsrDevShell | null = null;
102
+ if (this.#prodMode) {
103
+ this.#builderRpc = null;
104
+ routeCache = new RouteClientCache({
105
+ buildRoute: async (routeId) => {
106
+ throw new AkanError(
107
+ "artifactMissing",
108
+ `[SSR] route ${routeId} missing from production artifact — rebuild with \`akan build\` to include it`,
109
+ );
110
+ },
111
+ });
112
+ } else {
113
+ this.#devHmr = new DevHmrController({
114
+ artifactDir: this.#artifactDir,
115
+ renderState: this.renderState,
116
+ rsc: this.#rsc,
117
+ seedIndex,
118
+ upgradeHmrWs,
119
+ pagesBundlePath: artifact.pagesBundlePath,
120
+ });
121
+ this.#builderRpc = this.#devHmr.builderRpc;
122
+ routeCache = this.#devHmr.routeCache;
123
+ this.#hub = this.#devHmr.hub;
124
+ if (resolveDevCsrMode() === "registry") csrDevShell = new CsrDevShell(this.#artifactDir);
125
+ this.#ssrDevShell = new CsrDevShell(this.#artifactDir, {
126
+ dirName: SSR_DEV_DIRNAME,
127
+ routePrefix: SSR_DEV_ROUTE_PREFIX,
128
+ });
129
+ }
130
+ this.#context = new WebRouteContext({
131
+ artifact,
132
+ prodMode: this.#prodMode,
390
133
  renderState: this.renderState,
391
- rsc: this.#rsc,
392
- seedIndex: this.#seedIndex,
393
- upgradeHmrWs,
394
- pagesBundlePath: this.#artifact.pagesBundlePath,
134
+ subRoutes,
135
+ seedIndex,
136
+ routeCache,
137
+ hub: () => this.#hub,
395
138
  });
396
- this.#builderRpc = this.#devHmr.builderRpc;
397
- this.#routeCache = this.#devHmr.routeCache;
398
- this.#hub = this.#devHmr.hub;
399
- if (resolveDevCsrMode() === "registry") this.#csrDevShell = new CsrDevShell(this.#artifactDir);
400
- this.#ssrDevShell = new CsrDevShell(this.#artifactDir, {
401
- dirName: SSR_DEV_DIRNAME,
402
- routePrefix: SSR_DEV_ROUTE_PREFIX,
139
+ this.#csr = new WebCsrSurface(this.#context, { devShell: csrDevShell, builderRpc: () => this.#builderRpc });
140
+ htmlCache = new HtmlResultCache({ prodMode: this.#prodMode, devRegistry: this.#ssrDevShell !== null });
141
+ this.#htmlCache = htmlCache;
142
+ this.#rscRoute = new WebRscRoute(this.#context, { rsc, importMapKey });
143
+ this.#document = new WebDocumentRoute(this.#context, {
144
+ rsc,
145
+ importMapKey,
146
+ ssrDevShell: this.#ssrDevShell,
147
+ htmlCache: this.#htmlCache,
148
+
149
+ modulePreloadPlan: prebuilt?.modulePreloads
150
+ ? new ModulePreloadPlan(prebuilt.modulePreloads, prebuilt.clientManifest)
151
+ : undefined,
403
152
  });
153
+ } catch (error) {
154
+
155
+ this.#devHmr?.dispose();
156
+ htmlCache?.dispose();
157
+ throw error;
404
158
  }
405
159
  }
406
160
 
407
161
  async initializeRoute() {
408
- if (this.#prebuilt) this.#routeCache.seed(this.#prebuilt);
162
+ const context = this.#context;
163
+ if (this.#prebuilt) context.routeCache.seed(this.#prebuilt);
409
164
 
410
- const clientServePrefix = `/_akan/client`;
411
- const clientOutputDir = `${this.#artifactDir}/client`;
412
- const dictServePrefix = "/_akan/dict";
413
- const dictOutputDir = `${this.#artifactDir}/dict`;
414
- const stylesServePrefix = "/_akan/styles";
415
- const stylesOutputDir = `${this.#artifactDir}/styles`;
416
- const fontsServePrefix = "/_akan/fonts";
417
- const fontsOutputDir = `${this.#artifactDir}/fonts`;
418
165
  const localCsrDir = path.join(process.cwd(), "csr");
419
166
  const csrOutputDir = fs.existsSync(localCsrDir) ? localCsrDir : path.join(this.#artifactDir, "csr");
420
167
  const publicDir = path.join(process.env.AKAN_APP_DIR ?? path.dirname(Bun.main), "public");
421
- const shippedPublicFiles = this.#prodMode ? WebRouter.#shippedFiles(publicDir) : null;
422
- const imageCacheDir = path.join(this.#artifactDir, "image-cache");
168
+ const siteFiles = new WebSiteFiles(context, { rsc: this.#rsc, publicDir });
423
169
  const imageOptimizer = new ImageOptimizer({
424
170
  publicDir,
425
- cacheDir: imageCacheDir,
171
+ cacheDir: path.join(this.#artifactDir, "image-cache"),
426
172
  prodMode: this.#prodMode,
427
- config: this.#artifact.imageConfig,
173
+ config: context.artifact.imageConfig,
428
174
  });
429
175
 
430
176
  const renderEnvRoutes: HttpRoutes = {
431
- ...(this.web.csr
432
- ? {
433
- "/__csr": async (req) => {
434
- this.#requestStats.csr += 1;
435
- if (this.#csrDevShell) return await this.#serveCsrDevShell(req, "/", this.#csrDevShell);
436
- const csrHtml = await this.#resolveCsrHtml(csrOutputDir, "/");
437
- const csrFile = csrHtml ? Bun.file(csrHtml) : null;
438
- const htmlText =
439
- csrFile && (await csrFile.exists())
440
- ? await csrFile.text()
441
- : `<!doctype html>
442
- <html lang="en">
443
- <head>
444
- <meta charset="utf-8" />
445
- <title>Minimal</title>
446
- <base href="/" />
447
- <meta name="viewport" content="width=device-width, initial-scale=1" />
448
- </head>
449
- <body>
450
- <div id="root"></div>
451
- <script type="module" src="/csr.js"></script>
452
- </body>
453
- </html>`;
454
- return new Response(this.#withCsrHmr(htmlText), { headers: this.#htmlResponseHeaders(200, req) });
455
- },
456
- ...(this.#csrDevShell
457
- ? {
458
- [`${CSR_DEV_ROUTE_PREFIX}*`]: async (req: Request) => {
459
- this.#requestStats.staticAsset += 1;
460
- return (await this.#csrDevShell?.serve(req)) ?? new Response("Not Found", { status: 404 });
461
- },
462
- }
463
- : {}),
464
- }
465
- : {}),
177
+ ...(this.web.csr ? this.#csr.routes(csrOutputDir) : {}),
466
178
  ...(this.#ssrDevShell
467
179
  ? {
468
180
  [`${SSR_DEV_ROUTE_PREFIX}*`]: async (req: Request) => {
469
- this.#requestStats.staticAsset += 1;
181
+ context.stats.staticAsset += 1;
470
182
  return (await this.#ssrDevShell?.serve(req)) ?? new Response("Not Found", { status: 404 });
471
183
  },
472
184
  }
473
185
  : {}),
474
- [`${clientServePrefix}/*`]: async (req) => {
475
- this.#requestStats.staticAsset += 1;
476
- const url = new URL(req.url);
477
- const filePath = resolveStaticPath(clientOutputDir, url.pathname.slice(clientServePrefix.length + 1));
478
- if (!filePath) return new Response("Not Found", { status: 404 });
479
- return WebRouter.#fileResponse(req, filePath, {
480
- contentType: Bun.file(filePath).type || "application/javascript",
481
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : "no-store",
482
- });
483
- },
484
- [`${stylesServePrefix}/*`]: (req) => {
485
- this.#requestStats.staticAsset += 1;
486
- const url = new URL(req.url);
487
- if (this.#prodMode) {
488
- const filePath = resolveStaticPath(stylesOutputDir, url.pathname.slice(`${stylesServePrefix}/`.length));
489
- if (filePath) {
490
- return WebRouter.#fileResponse(req, filePath, {
491
- contentType: "text/css; charset=utf-8",
492
- cacheControl: "public, max-age=31536000, immutable",
493
- });
494
- }
495
- }
496
- const cssBytes = this.renderState.cssBytesByUrl[url.pathname];
497
- if (!cssBytes) return new Response("Not Found", { status: 404 });
498
- const headers = assetHeaders({
499
- contentType: "text/css; charset=utf-8",
500
- cacheControl: "no-store",
501
- });
502
- return new Response(
503
- cssBytes.buffer.slice(cssBytes.byteOffset, cssBytes.byteOffset + cssBytes.byteLength) as ArrayBuffer,
504
- { headers },
505
- );
506
- },
507
- [`${fontsServePrefix}/*`]: (req) => {
508
- this.#requestStats.staticAsset += 1;
509
- const url = new URL(req.url);
510
- const filePath = resolveStaticPath(fontsOutputDir, url.pathname.slice(`${fontsServePrefix}/`.length));
511
- if (!filePath) return new Response("Not Found", { status: 404 });
512
- return WebRouter.#fileResponse(req, filePath, {
513
- contentType: Bun.file(filePath).type || "font/woff2",
514
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : "no-store",
515
- anyOrigin: true,
516
- });
517
- },
518
- [`${dictServePrefix}/*`]: (req) => {
519
- this.#requestStats.staticAsset += 1;
520
- const url = new URL(req.url);
521
- const filePath = resolveStaticPath(dictOutputDir, url.pathname.slice(`${dictServePrefix}/`.length));
522
- if (!filePath) return new Response("Not Found", { status: 404 });
523
- return WebRouter.#fileResponse(req, filePath, {
524
- contentType: "text/javascript; charset=utf-8",
525
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : "no-store",
526
- });
527
- },
528
- "/_akan/image": (req) => {
529
- this.#requestStats.image += 1;
530
- return imageOptimizer.handle(req);
531
- },
186
+ ...WebAssetRoutes.build(context, { artifactDir: this.#artifactDir, imageOptimizer }),
532
187
  ...(!this.#prodMode
533
188
  ? {
534
189
  "/_akan/hmr": (req: Request) =>
535
190
  this.#devHmr?.handleWs(req) ?? new Response("HMR unavailable", { status: 404 }),
536
191
  }
537
192
  : {}),
538
- "/__rsc": SessionRefresh.answering(async (req) => {
539
- if (req.headers.get(AKAN_RSC_PREFETCH_HEADER) === "1") this.#requestStats.rscPrefetch += 1;
540
- else this.#requestStats.rscNavigation += 1;
541
- try {
542
-
543
- const importMap = req.headers.get(AKAN_RSC_IMPORT_MAP_HEADER);
544
- if (importMap && importMap !== this.#importMapKey)
545
- return new Response("Conflict", {
546
- status: 409,
547
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
548
- });
549
- const reqUrl = new URL(req.url);
550
-
551
- const clientOrigin = getClientFacingOrigin(req);
552
- const target = reqUrl.searchParams.get("url");
553
- const rawTargetUrl = target ? new URL(target, clientOrigin) : reqUrl;
554
- const i18n = this.#artifact.i18n;
555
- const { locale: targetLocale, path: targetPath, isPrefixed } = LocalePath.split(rawTargetUrl.pathname, i18n);
556
- const localizedTargetUrl = new URL(rawTargetUrl);
557
- if (targetLocale && !isPrefixed) localizedTargetUrl.pathname = `/${targetLocale}${rawTargetUrl.pathname}`;
558
- const requestBasePath = this.#requestBasePath(req);
559
- const normalizedTarget = normalizeRscTargetUrlForHostBasePath(localizedTargetUrl, {
560
- basePath: requestBasePath,
561
- basePaths: this.#artifact.basePaths,
562
- i18n,
563
- seedEntries: this.#seedIndex.entries,
564
- });
565
- const targetUrl = normalizedTarget.url;
566
- if (!WebRouter.#isTrustedRscTarget(clientOrigin, targetUrl))
567
- return new Response("Bad Request", { status: 400 });
568
- await SessionRefresh.apply(req);
569
- const manifest = await this.#ensureRoute(targetUrl);
570
- const rscHeaders = new Headers(req.headers);
571
- if (normalizedTarget.basePath) rscHeaders.set("x-base-path", normalizedTarget.basePath);
572
-
573
- if (targetLocale) {
574
- rscHeaders.set("x-locale", targetLocale);
575
- rscHeaders.set("x-path", targetPath);
576
- }
577
- const rscReq = new Request(targetUrl, {
578
- method: "GET",
579
- headers: rscHeaders,
580
- });
581
- const result = await this.#rsc.renderWithMeta(rscReq, {
582
- clientManifest: manifest.clientManifest,
583
- signal: req.signal,
584
- clientIp: SignalContext.clientIpOf(req),
585
- });
586
- if (result.type === "redirect")
587
- return createRscRedirectResponse(result.location, result.method, result.status);
588
- if (result.type === "not-found") return createRscNotFoundFallbackResponse();
589
- if (result.status && result.status >= 500)
590
- return this.#renderRscErrorResponse("__rsc", "Internal Server Error");
591
- const response = await createRscNavigationStreamResponse(result);
592
- const dictionaryUrl = this.#dictionaryUrlOf(rscHeaders, targetUrl.pathname);
593
- if (dictionaryUrl) response.headers.set(AKAN_RSC_DICTIONARY_HEADER, dictionaryUrl);
594
- return response;
595
- } catch (err) {
596
- return this.#renderRscErrorResponse("__rsc", err);
597
- }
598
- }),
599
- ...(!this.#prodMode || process.env.AKAN_EXPOSE_RSC_MANIFEST === "1"
600
- ? {
601
- "/__rsc/manifest": () =>
602
- new Response(JSON.stringify(this.#routeCache.merged.clientManifest, null, 2), {
603
- headers: applySecurityHeaders(
604
- new Headers({ "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }),
605
- ),
606
- }),
607
- }
608
- : {}),
609
- [APPLE_APP_SITE_ASSOCIATION_PATH]: () =>
610
- WebRouter.#deepLinkAssociationResponse(APPLE_APP_SITE_ASSOCIATION_PATH, this.#artifact, {
611
- cacheControl: this.#prodMode ? "public, max-age=3600" : "no-store",
612
- }) ?? new Response("Not Found", { status: 404 }),
613
- [ANDROID_ASSET_LINKS_PATH]: () =>
614
- WebRouter.#deepLinkAssociationResponse(ANDROID_ASSET_LINKS_PATH, this.#artifact, {
615
- cacheControl: this.#prodMode ? "public, max-age=3600" : "no-store",
616
- }) ?? new Response("Not Found", { status: 404 }),
617
-
618
- "/.well-known/*": () =>
619
- new Response("Not Found", {
620
- status: 404,
621
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
622
- }),
193
+ ...this.#rscRoute.routes(),
194
+ ...WellKnownRoutes.build(context.artifact, this.#prodMode),
623
195
  "/*": SessionRefresh.answering(async (req) => {
624
196
  const url = new URL(req.url);
625
197
  if (url.pathname.endsWith("/_akan/image")) {
626
- this.#requestStats.image += 1;
198
+ context.stats.image += 1;
627
199
  return imageOptimizer.handle(req);
628
200
  }
629
-
630
201
  if (this.web.csr) {
631
- const isCsr = url.searchParams.get("csr") === "true";
632
- if (isCsr) {
633
- this.#requestStats.csr += 1;
634
- if (this.#csrDevShell) return await this.#serveCsrDevShell(req, url.pathname, this.#csrDevShell);
635
- const csrHtml = await this.#resolveCsrHtml(csrOutputDir, url.pathname);
636
- if (!csrHtml) return this.#csrUnavailableResponse(url.pathname);
637
- const html = await Bun.file(csrHtml).text();
638
- return new Response(this.#withCsrHmr(html), { headers: this.#htmlResponseHeaders(200, req) });
639
- }
640
-
641
- const csrAssetPath = path.extname(url.pathname) ? resolveStaticPath(csrOutputDir, url.pathname) : null;
642
- if (csrAssetPath && (await Bun.file(csrAssetPath).exists())) {
643
- this.#requestStats.staticAsset += 1;
644
- return WebRouter.#fileResponse(req, csrAssetPath, {
645
- contentType: Bun.file(csrAssetPath).type || "application/octet-stream",
646
- cacheControl: this.#prodMode ? "public, max-age=31536000, immutable" : undefined,
647
- });
648
- }
649
- }
650
-
651
- const filePath = resolveStaticPath(publicDir, url.pathname);
652
- if (filePath && (await WebRouter.#isPublicFile(filePath, url.pathname, shippedPublicFiles))) {
653
- this.#requestStats.staticAsset += 1;
654
- const contentType = Bun.file(filePath).type || "application/octet-stream";
655
- return WebRouter.#fileResponse(req, filePath, {
656
- contentType,
657
-
658
- cacheControl: this.#prodMode ? "public, max-age=300, stale-while-revalidate=86400" : "no-store",
659
- anyOrigin: contentType.startsWith("font/"),
660
- });
661
- }
662
-
663
- if (url.pathname === "/robots.txt") {
664
- return new Response(createDefaultRobotsTxt(), {
665
- headers: {
666
- "Content-Type": "text/plain; charset=utf-8",
667
- "Cache-Control": this.#prodMode ? "public, max-age=3600" : "no-store",
668
- },
669
- });
670
- }
671
-
672
- const manifestBasePath = getWebManifestBasePath(
673
- url.pathname,
674
- this.#artifact.basePaths,
675
- this.#requestBasePath(req),
676
- );
677
- if (manifestBasePath !== undefined) {
678
- const manifestResponse = await this.#webManifestResponse(manifestBasePath);
679
- if (manifestResponse) return manifestResponse;
680
- }
681
-
682
- const sitemapBasePath = getSitemapBasePath(url.pathname, this.#artifact.basePaths, this.#requestBasePath(req));
683
- if (sitemapBasePath !== undefined) {
684
- return new Response(
685
- createDefaultSitemapXml({
686
- origin: getClientFacingOrigin(req),
687
- basePath: sitemapBasePath,
688
- entries: this.#seedIndex.entries,
689
- i18n: parseAkanI18nEnv(),
690
- }),
691
- {
692
- headers: {
693
- "Content-Type": "application/xml; charset=utf-8",
694
- "Cache-Control": this.#prodMode ? "public, max-age=3600" : "no-store",
695
- },
696
- },
697
- );
698
- }
699
-
700
- const subRouteIndex = this.#localSubRouteIndexResponse(req, url);
701
- if (subRouteIndex) return await subRouteIndex;
702
-
703
- try {
704
- this.#requestStats.fullSsr += 1;
705
- await SessionRefresh.apply(req);
706
- const manifest = await this.#ensureRoute(url);
707
- const isCrawler = isCrawlerUserAgent(req.headers.get("user-agent"));
708
- const htmlCacheDecision = this.#getHtmlCacheEntry(req, url, isCrawler);
709
- const htmlCacheEntry = htmlCacheDecision.entry;
710
- const cachedHtml = htmlCacheEntry ? this.#getCachedHtml(htmlCacheEntry.key) : null;
711
- if (cachedHtml) {
712
- const cachedHeaders = this.#htmlResponseHeaders(200, req);
713
- cachedHeaders.set("X-Akan-Cache", "HIT");
714
- return encodedBodyResponse(req, cachedHtml, { headers: cachedHeaders });
715
- }
716
- const rscResult = await this.#rsc.renderWithMeta(req, {
717
- clientManifest: manifest.clientManifest,
718
- signal: req.signal,
719
- clientIp: SignalContext.clientIpOf(req),
720
- });
721
- if (rscResult.type === "redirect")
722
- return createDocumentRedirectResponse(rscResult.location, url, rscResult.status);
723
- if (rscResult.type === "not-found") return this.#renderSystemNotFoundFallbackResponse(req, url);
724
-
725
- const cookieTheme = WebRouter.#cookieValue(req, "theme");
726
- const hostRequestStore = createRequestStore(req);
727
- const dictionaryUrl = this.#dictionaryUrlOf(req.headers, url.pathname);
728
- const extraBootstrapInline = [
729
- rscResult.trace?.routeState
730
- ? `self.__AKAN_RSC_INITIAL_STATE__=${JSON.stringify(rscResult.trace.routeState)};`
731
- : "",
732
- dictionaryUrl ? `self.__AKAN_DICT_URL__=${JSON.stringify(dictionaryUrl)};` : "",
733
- `self.__AKAN_IMPORT_MAP_KEY__=${JSON.stringify(this.#importMapKey)};`,
734
- this.#ssrDevShell
735
- ? SsrDevShim.script(await this.#ssrDevShell.readManifest(), Object.keys(this.#artifact.vendorMap))
736
- : "",
737
- !this.#prodMode ? HMR_CLIENT_SCRIPT : "",
738
- ]
739
- .filter(Boolean)
740
- .join("\n");
741
- const htmlStream = await new SsrFromRscRenderer().render({
742
- request: req,
743
- requestStore: hostRequestStore,
744
- rscStream: rscResult.stream,
745
- ssrManifest: manifest.ssrManifest,
746
- bootstrapModules: [this.#artifact.rscClientUrl],
747
- modulePreloads: dictionaryUrl ? [dictionaryUrl] : undefined,
748
- modulePreloadPlan: this.#modulePreloadPlan,
749
- extraBootstrapInline: extraBootstrapInline || undefined,
750
- importmap: this.#artifact.vendorMap,
751
-
752
- get theme() {
753
- return cookieTheme ?? rscResult.theme ?? "system";
754
- },
755
- lateControl: rscResult.lateControl,
756
- waitForAllReady: rscResult.trace?.ssrBlocking ?? false,
757
- inlineBoundaries: isCrawler,
758
- onCancel: (reason: unknown) => {
759
- rscResult.cancel(reason);
760
- },
761
- });
762
-
763
- const lateControl = await Promise.race([rscResult.lateControl, Promise.resolve(null)]);
764
- if (lateControl?.type === "redirect") {
765
- cancelStreamForHeadResponse(htmlStream, "redirected before the response started");
766
- return createDocumentRedirectResponse(lateControl.location, url, lateControl.status);
767
- }
768
- const responseStatus = lateControl?.type === "not-found" ? 404 : (rscResult.status ?? 200);
769
- const responseHeaders = this.#htmlResponseHeaders(responseStatus, req);
770
- if (req.method === "HEAD") {
771
- const headers = new Headers(responseHeaders);
772
- if (htmlCacheEntry && responseStatus === 200) headers.set("X-Akan-Cache", "MISS");
773
- else if (htmlCacheDecision.reason) {
774
- headers.set("X-Akan-Cache", "BYPASS");
775
- headers.set("X-Akan-Cache-Reason", htmlCacheDecision.reason);
776
- }
777
- cancelStreamForHeadResponse(htmlStream, "HEAD response does not consume body");
778
- return new Response(null, { status: responseStatus, headers });
779
- }
780
- if (htmlCacheEntry && responseStatus === 200) {
781
- const headers = new Headers(responseHeaders);
782
- headers.set("X-Akan-Cache", "MISS");
783
- let htmlStoreTtl = htmlCacheEntry.ttl;
784
- let htmlCacheMetadata: Omit<CachedHtmlResult, "body"> = { pathname: url.pathname };
785
- const shouldCacheHtml = Promise.all([rscResult.lateControl, rscResult.cacheState]).then(
786
- ([control, cacheState]) => {
787
- const storeTtl = resolveHtmlRouteCacheStoreTtl({
788
- baseTtl: htmlCacheEntry.ttl,
789
- workerCacheState: cacheState,
790
- hostRequestStore,
791
- lateControl: control,
792
- });
793
- if (storeTtl === null) return false;
794
- htmlStoreTtl = storeTtl;
795
- htmlCacheMetadata = {
796
- pathname: url.pathname,
797
- routeId: cacheState.routeId,
798
- tags: cacheState.tags,
799
- };
800
- return true;
801
- },
802
- );
803
- return new Response(
804
- cacheHtmlWhileStreaming(
805
- htmlStream,
806
- (html) => {
807
- void encodeBody(html).then((body) =>
808
- this.#htmlCache.set(htmlCacheEntry.key, { body, ...htmlCacheMetadata }, htmlStoreTtl),
809
- );
810
- },
811
- {
812
- shouldCache: () => shouldCacheHtml,
813
- maxBodyBytes:
814
- parsePositiveInt(process.env.AKAN_HTML_RESULT_CACHE_MAX_BODY_BYTES) ??
815
- DEFAULT_HTML_RESULT_CACHE_MAX_BODY_BYTES,
816
- onSkip: (reason) => {
817
- this.#logger.verbose(`html cache store skipped pathname=${url.pathname} reason=${reason}`);
818
- },
819
- },
820
- ),
821
- {
822
- status: responseStatus,
823
- headers,
824
- },
825
- );
826
- }
827
- const headers = new Headers(responseHeaders);
828
- if (htmlCacheDecision.reason) {
829
- headers.set("X-Akan-Cache", "BYPASS");
830
- headers.set("X-Akan-Cache-Reason", htmlCacheDecision.reason);
831
- }
832
- return new Response(htmlStream, {
833
- status: responseStatus,
834
- headers,
835
- });
836
- } catch (err) {
837
- return this.#renderErrorResponse(req, url.pathname, err);
202
+ const csrResponse = await this.#csr.answer(req, url, csrOutputDir);
203
+ if (csrResponse) return csrResponse;
838
204
  }
205
+ const siteFile = await siteFiles.answer(req, url);
206
+ if (siteFile) return siteFile;
207
+ return await this.#document.render(req, url);
839
208
  }),
840
209
  };
841
210
  return { renderEnvRoutes, hmrHub: this.#hub, builderRpc: this.#builderRpc };
@@ -880,8 +249,8 @@ export class WebRouter {
880
249
  read: async (app) => {
881
250
  if (!PageDefinition.promptName.test(app)) return null;
882
251
  const viewPath = path.join(viewDir, `${app}.html`);
883
- if (this.#csrDevShell) await this.#buildMcpAppViews();
884
- else if (!fs.existsSync(viewPath)) await this.#armCsrArtifact("mcp app view");
252
+ if (this.#csr.devShell) await this.#csr.buildMcpAppViews();
253
+ else if (!fs.existsSync(viewPath)) await this.#csr.armArtifact("mcp app view");
885
254
  const file = Bun.file(viewPath);
886
255
  if (!(await file.exists())) return null;
887
256
  const cached = views.get(app);
@@ -903,366 +272,38 @@ export class WebRouter {
903
272
 
904
273
  getMetrics(): AkanMetricsReport {
905
274
  const ssrStats = SsrFromRscRenderer.getChunkRegistryStats();
275
+ const stats = this.#context.stats;
906
276
  return {
907
277
  ...this.#rsc.getMetrics(),
908
278
  ssrChunkRegistrySize: ssrStats.ssrChunkRegistrySize,
909
279
  ssrChunkLoadCount: ssrStats.ssrChunkLoadCount,
910
280
  ssrChunkCacheHitCount: ssrStats.ssrChunkCacheHitCount,
911
281
  ssrChunkEvictionCount: ssrStats.ssrChunkEvictionCount,
912
- httpFullSsrCount: this.#requestStats.fullSsr,
913
- httpRscNavigationCount: this.#requestStats.rscNavigation,
914
- httpRscPrefetchCount: this.#requestStats.rscPrefetch,
915
- httpStaticAssetCount: this.#requestStats.staticAsset,
916
- httpCsrCount: this.#requestStats.csr,
917
- httpImageCount: this.#requestStats.image,
918
- httpHtmlCacheEntries: this.#htmlCache.size,
919
- httpHtmlCacheBytes: this.#htmlCache.byteSize,
920
- httpHtmlCacheHits: this.#htmlCacheHits,
921
- httpHtmlCacheMisses: this.#htmlCacheMisses,
922
- httpHtmlCacheBypass: this.#htmlCacheBypass,
282
+ httpFullSsrCount: stats.fullSsr,
283
+ httpRscNavigationCount: stats.rscNavigation,
284
+ httpRscPrefetchCount: stats.rscPrefetch,
285
+ httpStaticAssetCount: stats.staticAsset,
286
+ httpCsrCount: stats.csr,
287
+ httpImageCount: stats.image,
288
+ ...this.#htmlCache.metrics(),
923
289
  };
924
290
  }
925
291
 
926
292
  invalidateRouteCaches(invalidation?: string | RouteCacheInvalidation): void {
927
- const payload = typeof invalidation === "string" ? { reason: invalidation } : invalidation;
928
- if (!hasRouteCacheInvalidationScope(payload)) {
929
- this.#htmlCache.clear();
930
- } else if (payload) {
931
- this.#htmlCache.invalidate((_key, value) =>
932
- shouldInvalidateRouteCacheEntry(
933
- {
934
- pathname: value.pathname,
935
- routeId: value.routeId,
936
- tags: value.tags,
937
- },
938
- payload,
939
- ),
940
- );
941
- }
293
+ this.#htmlCache.invalidate(invalidation);
942
294
  this.#rsc.invalidateRouteResultCache(invalidation);
943
295
  }
944
296
 
945
- #requestBasePath(req: Request): string | null {
946
- const headerBasePath = req.headers.get("x-base-path");
947
- if (headerBasePath && this.#artifact.basePaths.includes(headerBasePath)) return headerBasePath;
948
- return WebRouter.#basePathForRequestHost(req, this.#subRoutes);
949
- }
950
-
951
- static #basePathForRequestHost(req: Request, subRoutes: Record<string, string[]>): string | null {
952
- const host = normalizeHost(req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ?? req.headers.get("host"));
953
- if (!host) return null;
954
- for (const [basePath, domains] of Object.entries(subRoutes)) {
955
- if (domains.some((domain) => normalizeHost(domain) === host)) return basePath;
956
- }
957
- return null;
958
- }
959
-
960
- static #isTrustedRscTarget(clientOrigin: string, targetUrl: URL): boolean {
961
- try {
962
- if (targetUrl.origin === clientOrigin) return true;
963
-
964
- return targetUrl.hostname === new URL(clientOrigin).hostname;
965
- } catch {
966
- return false;
967
- }
968
- }
969
-
970
- #getHtmlCacheEntry(req: Request, url: URL, isCrawler: boolean): { entry: RouteCacheEntry | null; reason?: string } {
971
-
972
- if (this.#ssrDevShell) {
973
- this.#htmlCacheBypass += 1;
974
- return { entry: null, reason: "dev-registry" };
975
- }
976
- const decision = resolvePublicRouteCacheEntryDecision({
977
- request: req,
978
- url,
979
- theme: WebRouter.#cookieValue(req, "theme"),
980
- variant: isCrawler ? "crawler" : undefined,
981
- defaultEnabled: this.#prodMode,
982
- defaultAllow: this.#prodMode,
983
- env: {
984
- enabled: process.env.AKAN_HTML_RESULT_CACHE,
985
- ttl: process.env.AKAN_HTML_RESULT_CACHE_TTL,
986
- allow: process.env.AKAN_HTML_RESULT_CACHE_PATHS,
987
- deny: process.env.AKAN_HTML_RESULT_CACHE_EXCLUDE_PATHS,
988
- },
989
- });
990
- if (!decision.entry) this.#htmlCacheBypass += 1;
991
- return decision;
992
- }
993
-
994
- #getCachedHtml(cacheKey: string): EncodedBody | null {
995
- const cached = this.#htmlCache.get(cacheKey);
996
- if (!cached) {
997
- this.#htmlCacheMisses += 1;
998
- return null;
999
- }
1000
- this.#htmlCacheHits += 1;
1001
- return cached.body;
1002
- }
1003
-
1004
- static #cookieValue(req: Request, name: string): string | undefined {
1005
- return CookieJar.parse(req.headers.get("cookie")).read(name).value;
1006
- }
1007
-
1008
- async #ensureRoute(url: URL) {
1009
- const started = Date.now();
1010
- const matched =
1011
- RouteSeedIndexStore.match(url.pathname, this.#seedIndex.entries) ??
1012
- RouteSeedIndexStore.matchPrefix(url.pathname, this.#seedIndex.entries);
1013
- if (matched) await this.#routeCache.ensure(matched.entry.routeId, matched.entry.seeds);
1014
- this.#logger.verbose(
1015
- `[route-cache] ensure pathname=${url.pathname} routeId=${matched?.entry.routeId ?? "(none)"} in ${Date.now() - started}ms`,
1016
- );
1017
- return this.#mergeRuntimeManifest();
1018
- }
1019
-
1020
- #mergeRuntimeManifest(): MergedManifest {
1021
- const revision = this.#routeCache.revision;
1022
- if (this.#runtimeManifest?.revision === revision) return this.#runtimeManifest.manifest;
1023
- const snapshot = this.#routeCache.snapshot();
1024
- const manifest: MergedManifest = {
1025
- ...snapshot,
1026
- clientManifest: Object.assign({}, this.#artifact.rscRuntimeClientManifest, snapshot.clientManifest),
1027
- ssrManifest: {
1028
- moduleLoading: null,
1029
- moduleMap: Object.assign({}, this.#artifact.rscRuntimeSsrManifest?.moduleMap, snapshot.ssrManifest.moduleMap),
1030
- },
1031
- };
1032
- this.#runtimeManifest = { revision, manifest };
1033
- return manifest;
1034
- }
1035
- #renderSystemNotFoundFallbackResponse(req: Request, url: URL): Promise<Response> {
1036
- return createSystemPageResponse({
1037
- kind: "not-found",
1038
- method: req.method,
1039
- pathname: url.pathname,
1040
- lang: getPathnameLocale(url.pathname, this.#artifact.i18n),
1041
- homeHref: this.#getSystemPageHomeHref(req, url.pathname),
1042
- stylesheetHref: this.#getStylesheetHref(req, url.pathname),
1043
- });
1044
- }
1045
-
1046
- async #webManifestResponse(basePath: string | null): Promise<Response | null> {
1047
- try {
1048
- const manifest = await this.#rsc.webManifest(basePath);
1049
- if (!manifest) return null;
1050
- return new Response(JSON.stringify(manifest), {
1051
- headers: {
1052
- "Content-Type": "application/manifest+json; charset=utf-8",
1053
- "Cache-Control": this.#prodMode ? "public, max-age=3600" : "no-store",
1054
- },
1055
- });
1056
- } catch (err) {
1057
- this.#logger.warn(
1058
- `web manifest unavailable basePath=${basePath ?? "(root)"}: ${err instanceof Error ? err.message : String(err)}`,
1059
- );
1060
- return new Response("Service Unavailable", {
1061
- status: 503,
1062
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
1063
- });
1064
- }
1065
- }
1066
-
1067
- #localSubRouteIndexResponse(req: Request, url: URL): Promise<Response> | null {
1068
- if (process.env.AKAN_PUBLIC_ENV !== "local" || !this.#artifact.basePaths.length) return null;
1069
- if (!WebRouter.#isSiteRootPathname(url.pathname, this.#artifact.i18n)) return null;
1070
- return createSubRouteIndexResponse({
1071
- method: req.method,
1072
- locale: getPathnameLocale(url.pathname, this.#artifact.i18n),
1073
- basePaths: this.#artifact.basePaths,
1074
- subRoutes: this.#subRoutes,
1075
- });
1076
- }
1077
-
1078
- static #isSiteRootPathname(pathname: string, i18n: AkanI18nConfig): boolean {
1079
- const segments = pathname.split("/").filter(Boolean);
1080
- if (!segments.length) return true;
1081
- return segments.length === 1 && i18n.locales.includes(segments[0] ?? "");
1082
- }
1083
-
1084
- #renderErrorResponse(req: Request, scope: string, err: unknown): Promise<Response> {
1085
- if (WebRouter.#isExpectedRequestAbort(err)) return Promise.resolve(WebRouter.#clientClosedResponse());
1086
- const message = err instanceof Error ? err.message : String(err);
1087
- this.#logger.error(`[SSR] render failed scope=${scope}: ${message}`);
1088
- this.#hub?.broadcast({ type: "error", message });
1089
- return createSystemPageResponse({
1090
- kind: "error",
1091
- method: req.method,
1092
- pathname: scope,
1093
- lang: getPathnameLocale(new URL(req.url).pathname, this.#artifact.i18n),
1094
- homeHref: this.#getSystemPageHomeHref(req, new URL(req.url).pathname),
1095
- stylesheetHref: this.#getStylesheetHref(req, new URL(req.url).pathname),
1096
- showDetails: !this.#prodMode,
1097
- error: err,
1098
- ...(this.#prodMode ? {} : { script: `self.__AKAN_HMR_SYSTEM_PAGE__=true;${HMR_CLIENT_SCRIPT}` }),
1099
- });
1100
- }
1101
-
1102
- #dictionaryUrlOf(headers: Headers, pathname: string): string | undefined {
1103
- const i18n = parseAkanI18nEnv();
1104
- const { locale } = RequestLocale.resolve(
1105
- { localeHeader: headers.get("x-locale"), pathHeader: headers.get("x-path"), pathname },
1106
- i18n,
1107
- );
1108
- const assets = this.#artifact.dictAssets ?? {};
1109
- return (assets[locale] ?? assets[i18n.defaultLocale])?.url;
1110
- }
1111
-
1112
- #renderRscErrorResponse(scope: string, err: unknown): Response {
1113
- if (WebRouter.#isExpectedRequestAbort(err)) return WebRouter.#clientClosedResponse();
1114
- const message = err instanceof Error ? err.message : String(err);
1115
- this.#logger.error(`[SSR] render failed scope=${scope}: ${message}`);
1116
- this.#hub?.broadcast({ type: "error", message });
1117
- return new Response("Internal Server Error", {
1118
- status: 500,
1119
- headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
1120
- });
1121
- }
1122
-
1123
- static #clientClosedResponse(): Response {
1124
- return new Response(null, {
1125
- status: CLIENT_CLOSED_REQUEST_STATUS,
1126
- headers: { "Cache-Control": "no-store" },
1127
- });
1128
- }
1129
-
1130
- static #isExpectedRequestAbort(error: unknown): boolean {
1131
- if (!(error instanceof Error)) return false;
1132
- return (
1133
- error.name === "AbortError" ||
1134
- error.message === "The connection was closed." ||
1135
- error.message === "Connection closed." ||
1136
- error.message.includes("The connection was closed")
1137
- );
1138
- }
1139
-
1140
- #getSystemPageHomeHref(req: Request, pathname: string): string {
1141
- return getSystemPageHomeHref({
1142
- pathname,
1143
- i18n: this.#artifact.i18n,
1144
- basePaths: this.#artifact.basePaths,
1145
- headerBasePath: this.#requestBasePath(req),
1146
- });
1147
- }
1148
-
1149
- #getStylesheetHref(req: Request, pathname: string): string | null {
1150
- const basePath = getBasePathFromPathname(pathname, {
1151
- basePaths: Object.keys(this.renderState.cssAssets),
1152
- i18n: this.#artifact.i18n,
1153
- headerBasePath: this.#requestBasePath(req),
1154
- });
1155
- return this.renderState.cssAssets[basePath ?? ""]?.cssUrl ?? null;
1156
- }
1157
-
1158
- #htmlResponseHeaders(status: number, req: Request): Headers {
1159
- const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" });
1160
- if (status >= 400 || !this.#prodMode) headers.set("Cache-Control", "no-store");
1161
- else {
1162
- const cacheControl = resolveHtmlCacheControl(req);
1163
- if (cacheControl) headers.set("Cache-Control", cacheControl);
1164
- }
1165
- const hsts = this.#prodMode ? strictTransportSecurity() : null;
1166
- if (hsts && getClientFacingOrigin(req).startsWith("https:")) headers.set("Strict-Transport-Security", hsts);
1167
- return applySecurityHeaders(headers, { html: true });
1168
- }
1169
- #withCsrHmr(html: string): string {
1170
- if (this.#prodMode) return html;
1171
- const csrGeneration = this.renderState.csrGeneration ?? null;
1172
- const flags = `self.__AKAN_HMR_CLIENT__="csr";self.__AKAN_CSR_GENERATION__=${csrGeneration};`;
1173
- return WebRouter.#injectBeforeBodyEnd(html, `<script>${flags}${HMR_CLIENT_SCRIPT}</script>`);
1174
- }
1175
-
1176
- async #serveCsrDevShell(req: Request, pathname: string, shell: CsrDevShell): Promise<Response> {
1177
- await this.#armCsrArtifact(pathname);
1178
- const basePath =
1179
- getBasePathFromPathname(pathname, { basePaths: this.#artifact.basePaths, i18n: this.#artifact.i18n }) ?? "";
1180
- const html = await shell.render({
1181
- basePath,
1182
- lang: "en",
1183
- title: process.env.AKAN_PUBLIC_APP_NAME ?? "akan",
1184
- cssHref: this.#getStylesheetHref(req, pathname),
1185
- });
1186
- if (!html) return this.#csrUnavailableResponse(pathname);
1187
- return new Response(this.#withCsrHmr(html), { headers: this.#htmlResponseHeaders(200, req) });
1188
- }
1189
- async #resolveCsrHtml(csrOutputDir: string, pathname: string): Promise<string | null> {
1190
- const resolved = WebRouter.#resolveCsrHtmlPath(csrOutputDir, pathname, this.#artifact);
1191
- if (resolved) return resolved;
1192
- await this.#armCsrArtifact(pathname);
1193
- return WebRouter.#resolveCsrHtmlPath(csrOutputDir, pathname, this.#artifact);
1194
- }
1195
- #armCsrArtifact(reason: string): Promise<unknown> {
1196
- const rpc = this.#builderRpc;
1197
-
1198
- if (this.#csrArmed || !rpc) return Promise.resolve();
1199
- return this.#singleFlight("csr", () =>
1200
- rpc
1201
- .buildCsr(reason)
1202
- .then(() => {
1203
- this.#csrArmed = true;
1204
- this.#logger.info(`[csr] dev CSR artifact built on demand (${reason})`);
1205
- })
1206
- .catch((err: unknown) => {
1207
- this.#logger.error(`[csr] on-demand build failed: ${err instanceof Error ? err.message : String(err)}`);
1208
- }),
1209
- );
1210
- }
1211
-
1212
- async #buildMcpAppViews(): Promise<void> {
1213
- const rpc = this.#builderRpc;
1214
- if (!rpc) return;
1215
- await this.#singleFlight("mcpShell", () =>
1216
- rpc.buildCsr("mcp app view", { shell: true }).catch((err: unknown) => {
1217
- this.#logger.error(`[mcp] view build failed: ${err instanceof Error ? err.message : String(err)}`);
1218
- }),
1219
- );
1220
- }
1221
- #singleFlight(kind: string, run: () => Promise<unknown>): Promise<unknown> {
1222
- const pending = this.#builds.get(kind) ?? run().finally(() => this.#builds.delete(kind));
1223
- this.#builds.set(kind, pending);
1224
- return pending;
1225
- }
1226
- #csrUnavailableResponse(pathname: string): Response {
1227
- if (this.#prodMode) return new Response("Not Found", { status: 404 });
1228
- const message = `No CSR artifact for ${pathname}. Dev CSR is built on demand; check the dev server log for a csr-build failure and verify the basePath in the URL.`;
1229
- this.#logger.warn(`[csr] ${message}`);
1230
- return new Response(message, { status: 404, headers: { "Content-Type": "text/plain; charset=utf-8" } });
1231
- }
1232
-
1233
- static async #isPublicFile(filePath: string, pathname: string, shipped: Set<string> | null) {
1234
- if (shipped && !path.extname(pathname)) return shipped.has(filePath);
1235
- return await Bun.file(filePath).exists();
1236
- }
1237
-
1238
- static #shippedFiles(dir: string): Set<string> {
1239
- const files = new Set<string>();
1240
- if (!fs.existsSync(dir)) return files;
1241
- const scan = new Bun.Glob("**/*").scanSync({ cwd: dir, onlyFiles: true, dot: true, followSymlinks: true });
1242
- for (const relative of scan) {
1243
- const filePath = path.resolve(dir, relative);
1244
- if (staysInTree(dir, filePath)) files.add(filePath);
1245
- }
1246
- return files;
1247
- }
1248
-
1249
- static #injectBeforeBodyEnd(html: string, snippet: string): string {
1250
- const matches = [...html.matchAll(/<\/body\s*>/gi)];
1251
- const last = matches.at(-1);
1252
- if (!last || last.index === undefined) return `${html}\n${snippet}`;
1253
- return `${html.slice(0, last.index)}${snippet}\n${html.slice(last.index)}`;
1254
- }
1255
-
1256
297
  /** `null` when the build has no web artifact (an api-only build, or no `page/`): boot without a web surface. */
1257
298
  static async create({ web, upgradeHmrWs }: SsrRoutesInputs): Promise<WebRouter | null> {
1258
299
  const artifactDir = resolveArtifactDir();
1259
300
  const artifactFile = Bun.file(path.join(artifactDir, "base-artifact.json"));
1260
301
  if (!(await artifactFile.exists())) return null;
1261
- const artifact = WebRouter.#normalizeArtifact((await artifactFile.json()) as BaseBuildArtifact, artifactDir);
302
+ const artifact = WebArtifact.normalize((await artifactFile.json()) as BaseBuildArtifact, artifactDir);
1262
303
  const builtWeb = resolveWebConfig(artifact.web);
1263
304
  if (!builtWeb.ssr) return null;
1264
- const cssBytesByUrl = await WebRouter.#loadCssBytesByUrl(artifact, artifactDir);
1265
- await WebRouter.#seedDictionaries(artifact, artifactDir);
305
+ const cssBytesByUrl = await WebArtifact.loadCssBytesByUrl(artifact, artifactDir);
306
+ await WebArtifact.seedDictionaries(artifact, artifactDir);
1266
307
  const prodMode = process.env.NODE_ENV === "production" && process.env.AKAN_COMMAND_TYPE !== "start";
1267
308
 
1268
309
  const prebuilt = prodMode ? await RoutesManifestStore.read(artifactDir) : null;
@@ -1280,178 +321,21 @@ export class WebRouter {
1280
321
  new Logger("WebRouter").error(`RSC worker failed to load the pages bundle: ${String(error)}`);
1281
322
  process.exit(1);
1282
323
  });
1283
- else await rsc.ready;
1284
- const seedIndex = await RouteSeedIndexStore.load(artifactDir);
1285
- return new WebRouter({
1286
- artifact,
1287
- web: { ssr: true, csr: web.csr && builtWeb.csr },
1288
- cssBytesByUrl,
1289
- rsc,
1290
- seedIndex,
1291
- upgradeHmrWs,
1292
- prebuilt,
1293
- });
1294
- }
1295
-
1296
- static #normalizeArtifact(artifact: BaseBuildArtifact, artifactDir: string): BaseBuildArtifact {
1297
- const normalizedArtifactDir = path.resolve(artifactDir);
1298
- const pagesBundlePath = WebRouter.#resolveArtifactPath(artifact.pagesBundlePath, normalizedArtifactDir);
1299
- return {
1300
- ...artifact,
1301
- cssAssets: artifact.cssAssets ?? {},
1302
- dictAssets: artifact.dictAssets ?? {},
1303
- pagesBundlePath,
1304
- rscRuntimeSsrManifest: artifact.rscRuntimeSsrManifest
1305
- ? WebRouter.#normalizeSsrManifest(artifact.rscRuntimeSsrManifest, normalizedArtifactDir)
1306
- : undefined,
1307
- i18n: artifact.i18n ?? DEFAULT_AKAN_I18N,
1308
- };
1309
- }
1310
-
1311
- static #normalizeSsrManifest(ssrManifest: SsrManifest, artifactDir: string): SsrManifest {
1312
- return {
1313
- ...ssrManifest,
1314
- moduleMap: Object.fromEntries(
1315
- Object.entries(ssrManifest.moduleMap).map(([entryUrl, byName]) => [
1316
- entryUrl,
1317
- Object.fromEntries(
1318
- Object.entries(byName).map(([name, entry]) => [
1319
- name,
1320
- {
1321
- ...entry,
1322
- id: WebRouter.#resolveArtifactPath(entry.id, artifactDir),
1323
- chunks: entry.chunks.map((chunk) => WebRouter.#resolveArtifactPath(chunk, artifactDir)),
1324
- },
1325
- ]),
1326
- ),
1327
- ]),
1328
- ),
1329
- };
1330
- }
1331
-
1332
- static async #loadCssBytesByUrl(
1333
- artifact: BaseBuildArtifact,
1334
- artifactDir: string,
1335
- ): Promise<Record<string, Uint8Array>> {
1336
- const normalizedArtifactDir = path.resolve(artifactDir);
1337
- return Object.fromEntries(
1338
- await Promise.all(
1339
- Object.values(artifact.cssAssets ?? {}).map(async (asset) => [
1340
- asset.cssUrl,
1341
- await Bun.file(path.join(normalizedArtifactDir, asset.cssRelPath)).bytes(),
1342
- ]),
1343
- ),
1344
- );
1345
- }
1346
-
1347
- static async #seedDictionaries(artifact: BaseBuildArtifact, artifactDir: string): Promise<void> {
1348
- const normalizedArtifactDir = path.resolve(artifactDir);
1349
- await Promise.all(
1350
- Object.values(artifact.dictAssets ?? {}).map(async (asset) => {
1351
- const { lang, default: dictionary } = (await import(path.join(normalizedArtifactDir, asset.relPath))) as {
1352
- lang: string;
1353
- default: Dictionary;
1354
- };
1355
- TranslatorState.replace(lang, dictionary);
1356
- }),
1357
- );
1358
- }
1359
-
1360
- static #resolveArtifactPath(artifactPath: string, artifactDir: string): string {
1361
- if (!path.isAbsolute(artifactPath)) return path.resolve(artifactDir, artifactPath);
1362
- if (fs.existsSync(artifactPath)) return artifactPath;
1363
-
1364
- const marker = `${path.sep}.akan${path.sep}artifact${path.sep}`;
1365
- const markerIndex = artifactPath.lastIndexOf(marker);
1366
- if (markerIndex >= 0) {
1367
- const rel = artifactPath.slice(markerIndex + marker.length);
1368
- return path.resolve(artifactDir, rel);
1369
- }
1370
-
1371
- return path.resolve(artifactDir, "server", path.basename(artifactPath));
1372
- }
1373
-
1374
- static #resolveCsrHtmlPath(csrOutputDir: string, pathname: string, artifact: BaseBuildArtifact): string | null {
1375
- const basePath = getBasePathFromPathname(pathname, {
1376
- basePaths: artifact.basePaths,
1377
- i18n: artifact.i18n,
1378
- });
1379
- const filename = basePath ? `${basePath}.html` : "index.html";
1380
- const filePath = resolveStaticPath(csrOutputDir, filename);
1381
- return filePath && fs.existsSync(filePath) ? filePath : null;
1382
- }
1383
-
1384
- static async #fileResponse(req: Request, filePath: string, options: AssetHeaderOptions): Promise<Response> {
1385
- const headers = assetHeaders(options);
1386
- const file = Bun.file(filePath);
1387
- if (!(await file.exists())) return new Response("Not Found", { status: 404 });
1388
- const stat = fs.statSync(filePath);
1389
- const lastModifiedMs = Math.floor(stat.mtimeMs / 1000) * 1000;
1390
- const etag = `W/"${stat.size.toString(16)}-${lastModifiedMs.toString(16)}"`;
1391
- headers.set("ETag", etag);
1392
- headers.set("Last-Modified", new Date(lastModifiedMs).toUTCString());
1393
- if (isCompressibleContentType(options.contentType)) varyOnEncoding(headers);
1394
- if (WebRouter.#isNotModified(req, etag, lastModifiedMs)) return new Response(null, { status: 304, headers });
1395
-
1396
- return await encodedFileResponse(req, filePath, options.contentType, headers);
1397
- }
1398
-
1399
- static #deepLinkAssociationResponse(
1400
- pathname: string,
1401
- artifact: BaseBuildArtifact,
1402
- { cacheControl }: { cacheControl: string },
1403
- ) {
1404
- const associations = artifact.deepLinkAssociations ?? [];
1405
- if (pathname === APPLE_APP_SITE_ASSOCIATION_PATH) {
1406
- const details = associations
1407
- .filter((association) => association.domains.length > 0 && association.iosTeamId && association.iosAppId)
1408
- .map((association) => ({
1409
- appIDs: [`${association.iosTeamId}.${association.iosAppId}`],
1410
- components: [{ "/": "/*" }],
1411
- }));
1412
- if (details.length === 0) return null;
1413
- return WebRouter.#jsonResponse({ applinks: { apps: [], details } }, cacheControl);
324
+ try {
325
+ if (!prodMode) await rsc.ready;
326
+ const seedIndex = await RouteSeedIndexStore.load(artifactDir);
327
+ return new WebRouter({
328
+ artifact,
329
+ web: { ssr: true, csr: web.csr && builtWeb.csr },
330
+ cssBytesByUrl,
331
+ rsc,
332
+ seedIndex,
333
+ upgradeHmrWs,
334
+ prebuilt,
335
+ });
336
+ } catch (error) {
337
+ rsc.kill();
338
+ throw error;
1414
339
  }
1415
-
1416
- const packageSuffixes = process.env.AKAN_PUBLIC_ENV === "main" ? [""] : ["", ".debug"];
1417
- const assetLinks = associations
1418
- .filter(
1419
- (association) =>
1420
- association.domains.length > 0 &&
1421
- !!association.androidAppId &&
1422
- (association.androidSha256CertFingerprints?.length ?? 0) > 0,
1423
- )
1424
- .flatMap((association) =>
1425
- packageSuffixes.map((suffix) => ({
1426
- relation: ["delegate_permission/common.handle_all_urls"],
1427
- target: {
1428
- namespace: "android_app",
1429
- package_name: `${association.androidAppId}${suffix}`,
1430
- sha256_cert_fingerprints: association.androidSha256CertFingerprints,
1431
- },
1432
- })),
1433
- );
1434
- if (assetLinks.length === 0) return null;
1435
- return WebRouter.#jsonResponse(assetLinks, cacheControl);
1436
- }
1437
-
1438
- static #jsonResponse(body: unknown, cacheControl: string) {
1439
- return new Response(JSON.stringify(body, null, 2), {
1440
- headers: {
1441
- "Content-Type": "application/json; charset=utf-8",
1442
- "Cache-Control": cacheControl,
1443
- },
1444
- });
1445
- }
1446
-
1447
- static #isNotModified(req: Request, etag: string, lastModifiedMs: number): boolean {
1448
- if (req.method !== "GET" && req.method !== "HEAD") return false;
1449
- const ifNoneMatch = req.headers.get("if-none-match");
1450
- if (ifNoneMatch) return matchesIfNoneMatch(ifNoneMatch, etag);
1451
-
1452
- const ifModifiedSince = req.headers.get("if-modified-since");
1453
- if (!ifModifiedSince) return false;
1454
- const sinceMs = Date.parse(ifModifiedSince);
1455
- return Number.isFinite(sinceMs) && sinceMs >= lastModifiedMs;
1456
340
  }
1457
341
  }