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.
- package/ARCHITECTURE.md +42 -41
- package/CHANGELOG.md +593 -3
- package/CONTRIBUTING.md +26 -0
- package/base/base.ts +2 -1
- package/client/clientRuntime.ts +1 -0
- package/client/cn.ts +2 -2
- package/client/csrTypes.ts +15 -1
- package/client/frameConfig.ts +5 -2
- package/client/index.ts +249 -26
- package/client/locale.ts +1 -0
- package/client/makePageProto.tsx +33 -82
- package/client/nativeThemeColor.ts +51 -0
- package/client/route/RouteDefinition.ts +24 -7
- package/client/route/RouteGuards.ts +2 -1
- package/client/route/RouteHead.ts +11 -2
- package/client/route/routeArgs.ts +7 -0
- package/client/router.ts +25 -6
- package/client/rscNavigation.ts +3 -3
- package/client/rscRoutePatch.ts +42 -0
- package/client/viewportMeta.ts +34 -4
- package/common/CodeTranscript.ts +1 -1
- package/common/PipelinePlanSchema.ts +2 -2
- package/common/akanGraph.ts +1 -1
- package/common/err.ts +122 -0
- package/common/facetBarrel.ts +38 -0
- package/common/failureCode.ts +18 -0
- package/common/index.ts +9 -0
- package/common/isGuardRefusal.ts +14 -0
- package/common/mcpExposure.ts +17 -4
- package/common/mcpFailure.ts +9 -0
- package/common/pipelinePlan.ts +1 -1
- package/common/restartSchedule.ts +55 -0
- package/common/routeConvention.ts +3 -1
- package/common/types.ts +18 -1
- package/constant/constantRegistry.ts +4 -8
- package/constant/crystalize.ts +1 -2
- package/constant/getDefault.ts +1 -1
- package/constant/immerify.ts +1 -1
- package/constant/index.ts +78 -21
- package/constant/purify.ts +4 -9
- package/constant/serialize.ts +4 -2
- package/constant/types.ts +1 -0
- package/constant/via.ts +1 -2
- package/dictionary/agent.dictionary.ts +4 -0
- package/dictionary/base.dictionary.ts +1 -0
- package/dictionary/locale.ts +1 -1
- package/dictionary/trans.ts +14 -97
- package/document/databaseRegistry.ts +2 -1
- package/document/documentSchema.ts +1 -0
- package/document/filterMeta.ts +4 -1
- package/document/into.ts +2 -1
- package/document/loaderInfo.ts +2 -1
- package/document/noDocumentError.ts +4 -1
- package/document/queryEvaluator.ts +1 -1
- package/document/types.ts +1 -1
- package/fetch/client/fetchClient.ts +87 -270
- package/fetch/client/fetchClientTypes.ts +49 -0
- package/fetch/client/fetchHandle.ts +11 -1
- package/fetch/client/httpClient.ts +14 -2
- package/fetch/client/inflightQueries.ts +17 -0
- package/fetch/client/remoteError.ts +4 -20
- package/fetch/client/requestScope.ts +32 -0
- package/fetch/client/signalCatalog.ts +131 -0
- package/fetch/client/wsClient.ts +11 -0
- package/fetch/index.ts +1 -0
- package/fetch/staleReads.ts +27 -0
- package/fetch/streamedRead.ts +23 -0
- package/package.json +1 -1
- package/server/agentHooks.ts +16 -0
- package/server/akanApp.ts +107 -1272
- package/server/akanOption.ts +17 -4
- package/server/akanServer.ts +167 -675
- package/server/artifact/builderRpc.ts +33 -10
- package/server/artifact/ipcTypes.ts +9 -3
- package/server/artifact/routeSeedIndexStore.ts +4 -2
- package/server/assetHeaders.ts +6 -0
- package/server/console.ts +6 -4
- package/server/decorators.ts +2 -2
- package/server/devtools/README.md +4 -3
- package/server/devtools/devtoolsRouter.ts +9 -5
- package/server/devtools/studio/studioRoute.ts +18 -11
- package/server/di/diLifecycle.ts +24 -35
- package/server/di/predefinedAdaptor.ts +24 -1
- package/server/di/resolveHierarchy.ts +19 -6
- package/server/di/utils.ts +7 -3
- package/server/ed25519Key.ts +31 -15
- package/server/flightRowReader.ts +95 -18
- package/server/gateway/childSupervisor.ts +326 -0
- package/server/gateway/devHostChannel.ts +47 -0
- package/server/gateway/gatewayChildren.ts +135 -0
- package/server/gateway/gatewayConfig.ts +182 -0
- package/server/gateway/gatewayHttpProxy.ts +231 -0
- package/server/gateway/gatewayLogging.ts +111 -0
- package/server/gateway/gatewayRooms.ts +141 -0
- package/server/gateway/gatewayStatus.ts +116 -0
- package/server/gateway/gatewayStatusPage.ts +54 -0
- package/server/gateway/gatewayWebSocketRelay.ts +149 -0
- package/server/head.tsx +4 -19
- package/server/hmr/devHmrController.ts +10 -1
- package/server/htmlResultCache.ts +234 -0
- package/server/imageOptimizer.ts +4 -1
- package/server/index.ts +257 -17
- package/server/lifecycle/parentChannel.ts +78 -0
- package/server/lifecycle/shutdownManager.ts +6 -3
- package/server/lifecycle/startGuard.ts +90 -0
- package/server/logging/logControlSocket.ts +42 -3
- package/server/logging/serverLogging.ts +74 -0
- package/server/machine/machineToken.ts +10 -3
- package/server/mcp/AgentTools.ts +149 -0
- package/server/mcp/AgentToolsAccount.ts +26 -0
- package/server/mcp/McpDispatcher.ts +48 -19
- package/server/mcp/McpPages.ts +21 -6
- package/server/mcp/McpRateLimiter.ts +14 -0
- package/server/mcp/McpRouter.ts +52 -23
- package/server/mcp/McpUiSession.ts +2 -1
- package/server/mcp/index.ts +1 -0
- package/server/nativeFile.ts +30 -11
- package/server/nativeSecret.ts +12 -3
- package/server/oauth/OAuthClientIdMetadata.ts +2 -2
- package/server/ops/opsRoute.ts +5 -1
- package/server/ops/opsToken.ts +3 -1
- package/server/resolver/CascadeRunner.ts +10 -4
- package/server/resolver/database.resolver.ts +10 -417
- package/server/resolver/databaseModelInstance.ts +200 -0
- package/server/resolver/invalidSignal.ts +7 -0
- package/server/resolver/livePause.ts +34 -0
- package/server/resolver/modelFacade.ts +136 -0
- package/server/resolver/modelLoaders.ts +52 -0
- package/server/resolver/modelSchema.ts +52 -0
- package/server/resolver/signal.resolver.ts +92 -116
- package/server/resolver/timedQuery.ts +16 -0
- package/server/resolver/websocketOf.ts +23 -0
- package/server/routeElementComposer.tsx +131 -9
- package/server/routeState.ts +5 -1
- package/server/routeTreeBuilder.ts +22 -9
- package/server/routing/apiRouter.ts +44 -25
- package/server/routing/builtinRoutes.ts +194 -0
- package/server/routing/localRooms.ts +34 -0
- package/server/routing/roomReplay.ts +2 -2
- package/server/routing/serverLimits.ts +4 -1
- package/server/routing/serverListener.ts +194 -0
- package/server/rscClient.tsx +210 -227
- package/server/rscClientCache.ts +165 -0
- package/server/rscClientChunks.ts +209 -0
- package/server/rscClientFetch.ts +15 -3
- package/server/rscClientPatch.ts +78 -15
- package/server/rscDocumentHead.tsx +170 -0
- package/server/rscFlightRenderer.ts +83 -0
- package/server/rscFlightStream.ts +257 -0
- package/server/rscHeadPatch.ts +17 -56
- package/server/rscHostReloads.ts +238 -0
- package/server/rscHostRenderStream.ts +297 -0
- package/server/rscHostRequests.ts +158 -0
- package/server/rscHttp.ts +18 -6
- package/server/rscInlineStream.ts +34 -0
- package/server/rscNavigationState.ts +21 -1
- package/server/rscPagePrompts.ts +11 -5
- package/server/rscParkedRedirect.ts +23 -0
- package/server/rscPatchPlanner.ts +220 -0
- package/server/rscPrefetchCache.ts +68 -32
- package/server/rscRenderControl.ts +33 -0
- package/server/rscRenderFallbacks.ts +297 -0
- package/server/rscRenderHandler.ts +439 -0
- package/server/rscRenderStats.ts +49 -0
- package/server/rscResponse.ts +78 -0
- package/server/rscResultCaches.ts +74 -0
- package/server/rscRouteDocument.tsx +299 -0
- package/server/rscSegmentOutlet.tsx +24 -5
- package/server/rscSegmentOutletReference.ts +14 -12
- package/server/rscWorker.tsx +86 -1392
- package/server/rscWorkerCache.ts +56 -0
- package/server/rscWorkerHost.ts +145 -811
- package/server/rscWorkerProcess.ts +155 -0
- package/server/rscWorkerRecycler.ts +128 -0
- package/server/serverConfig.ts +128 -0
- package/server/serverMetrics.ts +52 -0
- package/server/sitemap.ts +1 -0
- package/server/ssrFromRscRenderer.tsx +20 -20
- package/server/ssrTypes.ts +9 -0
- package/server/webArtifact.ts +86 -0
- package/server/webAssetRoutes.ts +84 -0
- package/server/webCsrSurface.ts +172 -0
- package/server/webDocumentRoute.ts +180 -0
- package/server/webRouteContext.ts +232 -0
- package/server/webRouter.ts +126 -1242
- package/server/webRscRoute.ts +155 -0
- package/server/webSiteFiles.ts +139 -0
- package/server/wellKnownRoutes.ts +73 -0
- package/service/agent.service.ts +59 -5
- package/service/agentAccounts.ts +19 -0
- package/service/agentLoop/agentLoop.ts +387 -0
- package/service/agentLoop/agentLoopTypes.ts +112 -0
- package/service/agentLoop/deltaStream.ts +40 -0
- package/service/agentLoop/loopCompaction.ts +135 -0
- package/service/agentLoop/loopRequest.ts +62 -0
- package/service/agentLoop/loopToolOutput.ts +54 -0
- package/service/agentLoop/loopToolkits.ts +107 -0
- package/service/agentLoop/loopTranscript.ts +102 -0
- package/{signal → service}/agentMeter.ts +83 -15
- package/{signal → service}/agentRelayPolicy.ts +30 -7
- package/service/documentStoreError.ts +16 -0
- package/service/index.ts +7 -0
- package/service/injectError.ts +5 -0
- package/service/injectInfo.ts +30 -18
- package/service/insightQueryError.ts +19 -0
- package/service/ipcTypes.ts +3 -1
- package/service/liveSyncHub.ts +5 -2
- package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
- package/service/predefinedAdaptor/anthropicLlm.ts +52 -21
- package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
- package/service/predefinedAdaptor/compress.adaptor.ts +7 -3
- package/service/predefinedAdaptor/database.adaptor.ts +3 -1
- package/service/predefinedAdaptor/documentTransfer.ts +2 -1
- package/service/predefinedAdaptor/index.ts +2 -0
- package/service/predefinedAdaptor/insightQuery.ts +35 -11
- package/service/predefinedAdaptor/llm.adaptor.ts +22 -2
- package/service/predefinedAdaptor/llmSpend.ts +80 -0
- package/service/predefinedAdaptor/openaiDialect.ts +52 -17
- package/service/predefinedAdaptor/openaiLlm.ts +17 -9
- package/service/predefinedAdaptor/role.adaptor.ts +2 -0
- package/service/predefinedAdaptor/searchIndex.ts +5 -1
- package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
- package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
- package/service/predefinedAdaptor/solidSqlite.ts +3 -2
- package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
- package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
- package/service/predefinedAdaptor/sql/DocumentWriter.ts +292 -0
- package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
- package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
- package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
- package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
- package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
- package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +83 -1124
- package/service/predefinedAdaptor/sql/SqlTableSchema.ts +319 -0
- package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
- package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
- package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
- package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +3 -3
- package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
- package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
- package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
- package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
- package/service/predefinedAdaptor/sql/values.ts +8 -4
- package/service/predefinedAdaptor/sseData.ts +14 -0
- package/service/predefinedAdaptor/storage.adaptor.ts +9 -4
- package/service/predefinedAdaptor/websocket.adaptor.ts +199 -43
- package/service/serve.ts +3 -2
- package/service/serviceModule.ts +2 -2
- package/service/serviceRegistry.ts +1 -0
- package/signal/SignalFailure.ts +30 -1
- package/signal/agent.signal.ts +30 -9
- package/signal/agentTurnStream.ts +12 -8
- package/signal/byIdRead.ts +18 -0
- package/signal/carriedClientIps.ts +1 -0
- package/signal/endpointErrorContract.ts +20 -2
- package/signal/endpointInfo.ts +6 -5
- package/signal/exception.ts +1 -0
- package/signal/index.ts +314 -30
- package/signal/internalInfo.ts +6 -4
- package/signal/mcp/McpDocument.ts +8 -1
- package/signal/mcp/Msg.ts +23 -10
- package/signal/mcp/index.ts +1 -0
- package/signal/mcp/promptError.ts +9 -0
- package/signal/middleware.ts +12 -3
- package/signal/openapi/openapi.ts +10 -1
- package/signal/resolveFieldContext.ts +34 -0
- package/signal/serializer/fetch.serializer.ts +23 -15
- package/signal/signalContext.ts +24 -57
- package/signal/signalContractError.ts +10 -0
- package/signal/signalDeclarationError.ts +13 -0
- package/signal/signalRegistry.ts +3 -1
- package/signal/slice.ts +24 -20
- package/signal/sliceInfo.ts +12 -9
- package/signal/trace.ts +3 -0
- package/signal/types.ts +35 -6
- package/store/action.ts +44 -1086
- package/store/actionErrorKey.ts +9 -0
- package/store/actionOption.ts +22 -0
- package/store/baseSt.ts +1 -0
- package/store/draftFlush.ts +5 -0
- package/store/draftStore.ts +2 -0
- package/store/formDrafts.ts +115 -0
- package/store/formFieldSetters.ts +229 -0
- package/store/index.ts +125 -17
- package/store/modelActionContext.ts +65 -0
- package/store/modelListPatch.ts +53 -0
- package/store/modelOpenActions.ts +158 -0
- package/store/modelWriteActions.ts +240 -0
- package/store/modelWriteGuard.ts +82 -0
- package/store/openSeq.ts +34 -0
- package/store/rootStore.ts +2 -0
- package/store/sliceListActions.ts +370 -0
- package/store/sliceLiveActions.ts +130 -0
- package/store/stateBuilder.ts +2 -0
- package/store/storeInstance.ts +9 -10
- package/store/uploadPoll.ts +52 -0
- package/store/withSelector.ts +6 -4
- package/types/base/base.d.ts +2 -1
- package/types/client/clientRuntime.d.ts +1 -0
- package/types/client/cn.d.ts +2 -2
- package/types/client/csrTypes.d.ts +15 -1
- package/types/client/frameConfig.d.ts +1 -0
- package/types/client/index.d.ts +25 -26
- package/types/client/locale.d.ts +1 -0
- package/types/client/makePageProto.d.ts +28 -26091
- package/types/client/nativeThemeColor.d.ts +6 -0
- package/types/client/route/RouteDefinition.d.ts +2 -2
- package/types/client/route/RouteHead.d.ts +5 -1
- package/types/client/route/routeArgs.d.ts +6 -0
- package/types/client/router.d.ts +6 -3
- package/types/client/rscNavigation.d.ts +3 -2
- package/types/client/rscRoutePatch.d.ts +22 -0
- package/types/client/viewportMeta.d.ts +3 -1
- package/types/common/CodeTranscript.d.ts +1 -1
- package/types/common/akanGraph.d.ts +1 -1
- package/types/common/err.d.ts +48 -0
- package/types/common/facetBarrel.d.ts +4 -0
- package/types/common/failureCode.d.ts +6 -0
- package/types/common/index.d.ts +8 -2
- package/types/common/isGuardRefusal.d.ts +3 -0
- package/types/common/mcpExposure.d.ts +9 -2
- package/types/common/mcpFailure.d.ts +6 -0
- package/types/common/restartSchedule.d.ts +16 -0
- package/types/common/routeConvention.d.ts +2 -0
- package/types/common/types.d.ts +18 -1
- package/types/constant/constantRegistry.d.ts +3 -1
- package/types/constant/crystalize.d.ts +1 -1
- package/types/constant/getDefault.d.ts +1 -1
- package/types/constant/immerify.d.ts +1 -1
- package/types/constant/index.d.ts +21 -21
- package/types/constant/purify.d.ts +2 -1
- package/types/constant/serialize.d.ts +1 -1
- package/types/constant/types.d.ts +1 -0
- package/types/dictionary/agent.dictionary.d.ts +1 -1
- package/types/dictionary/base.dictionary.d.ts +1 -1
- package/types/dictionary/dictionary.d.ts +9 -9
- package/types/dictionary/locale.d.ts +1 -1
- package/types/dictionary/trans.d.ts +3 -26
- package/types/document/databaseRegistry.d.ts +2 -1
- package/types/document/documentSchema.d.ts +1 -0
- package/types/document/filterMeta.d.ts +4 -1
- package/types/document/into.d.ts +1 -1
- package/types/document/loaderInfo.d.ts +2 -1
- package/types/document/noDocumentError.d.ts +8 -1
- package/types/document/queryEvaluator.d.ts +1 -1
- package/types/document/types.d.ts +1 -1
- package/types/fetch/client/fetchClient.d.ts +6 -36
- package/types/fetch/client/fetchClientTypes.d.ts +40 -0
- package/types/fetch/client/fetchHandle.d.ts +1 -0
- package/types/fetch/client/httpClient.d.ts +2 -0
- package/types/fetch/client/inflightQueries.d.ts +2 -0
- package/types/fetch/client/remoteError.d.ts +0 -4
- package/types/fetch/client/requestScope.d.ts +6 -0
- package/types/fetch/client/signalCatalog.d.ts +25 -0
- package/types/fetch/client/wsClient.d.ts +1 -0
- package/types/fetch/index.d.ts +1 -0
- package/types/fetch/staleReads.d.ts +8 -0
- package/types/fetch/streamedRead.d.ts +8 -0
- package/types/server/agentHooks.d.ts +4 -0
- package/types/server/akanApp.d.ts +2 -20
- package/types/server/akanOption.d.ts +9 -3
- package/types/server/akanServer.d.ts +1 -1
- package/types/server/artifact/builderRpc.d.ts +8 -0
- package/types/server/artifact/ipcTypes.d.ts +8 -0
- package/types/server/assetHeaders.d.ts +1 -0
- package/types/server/console.d.ts +4 -3
- package/types/server/devtools/devtoolsRouter.d.ts +4 -1
- package/types/server/devtools/studio/studioRoute.d.ts +2 -1
- package/types/server/di/predefinedAdaptor.d.ts +1 -0
- package/types/server/ed25519Key.d.ts +1 -0
- package/types/server/flightRowReader.d.ts +3 -1
- package/types/server/gateway/childSupervisor.d.ts +33 -0
- package/types/server/gateway/devHostChannel.d.ts +14 -0
- package/types/server/gateway/gatewayChildren.d.ts +47 -0
- package/types/server/gateway/gatewayConfig.d.ts +82 -0
- package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
- package/types/server/gateway/gatewayLogging.d.ts +16 -0
- package/types/server/gateway/gatewayRooms.d.ts +25 -0
- package/types/server/gateway/gatewayStatus.d.ts +62 -0
- package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
- package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
- package/types/server/head.d.ts +2 -2
- package/types/server/htmlResultCache.d.ts +51 -0
- package/types/server/index.d.ts +17 -17
- package/types/server/lifecycle/parentChannel.d.ts +13 -0
- package/types/server/lifecycle/startGuard.d.ts +10 -0
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/logging/serverLogging.d.ts +12 -0
- package/types/server/mcp/AgentTools.d.ts +31 -0
- package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
- package/types/server/mcp/McpDispatcher.d.ts +10 -1
- package/types/server/mcp/McpPages.d.ts +2 -1
- package/types/server/mcp/McpRateLimiter.d.ts +3 -0
- package/types/server/mcp/index.d.ts +1 -0
- package/types/server/resolver/database.resolver.d.ts +2 -2
- package/types/server/resolver/databaseModelInstance.d.ts +4 -0
- package/types/server/resolver/invalidSignal.d.ts +2 -0
- package/types/server/resolver/livePause.d.ts +5 -0
- package/types/server/resolver/modelFacade.d.ts +5 -0
- package/types/server/resolver/modelLoaders.d.ts +9 -0
- package/types/server/resolver/modelSchema.d.ts +6 -0
- package/types/server/resolver/signal.resolver.d.ts +2 -2
- package/types/server/resolver/timedQuery.d.ts +8 -0
- package/types/server/resolver/websocketOf.d.ts +2 -0
- package/types/server/routeElementComposer.d.ts +45 -6
- package/types/server/routeState.d.ts +2 -0
- package/types/server/routing/builtinRoutes.d.ts +24 -0
- package/types/server/routing/localRooms.d.ts +14 -0
- package/types/server/routing/roomReplay.d.ts +2 -2
- package/types/server/routing/serverListener.d.ts +31 -0
- package/types/server/rscClient.d.ts +1 -5
- package/types/server/rscClientCache.d.ts +34 -0
- package/types/server/rscClientChunks.d.ts +18 -0
- package/types/server/rscClientFetch.d.ts +1 -1
- package/types/server/rscClientPatch.d.ts +12 -1
- package/types/server/rscDocumentHead.d.ts +32 -0
- package/types/server/rscFlightRenderer.d.ts +14 -0
- package/types/server/rscFlightStream.d.ts +52 -0
- package/types/server/rscHeadPatch.d.ts +5 -4
- package/types/server/rscHostReloads.d.ts +54 -0
- package/types/server/rscHostRenderStream.d.ts +53 -0
- package/types/server/rscHostRequests.d.ts +29 -0
- package/types/server/rscHttp.d.ts +4 -2
- package/types/server/rscInlineStream.d.ts +9 -0
- package/types/server/rscNavigationState.d.ts +8 -3
- package/types/server/rscParkedRedirect.d.ts +12 -0
- package/types/server/rscPatchPlanner.d.ts +49 -0
- package/types/server/rscPrefetchCache.d.ts +8 -7
- package/types/server/rscRenderControl.d.ts +12 -0
- package/types/server/rscRenderFallbacks.d.ts +41 -0
- package/types/server/rscRenderHandler.d.ts +29 -0
- package/types/server/rscRenderStats.d.ts +32 -0
- package/types/server/rscResponse.d.ts +9 -0
- package/types/server/rscResultCaches.d.ts +18 -0
- package/types/server/rscRouteDocument.d.ts +52 -0
- package/types/server/rscSegmentOutlet.d.ts +5 -0
- package/types/server/rscSegmentOutletReference.d.ts +2 -1
- package/types/server/rscWorker.d.ts +1 -3
- package/types/server/rscWorkerCache.d.ts +33 -1
- package/types/server/rscWorkerHost.d.ts +9 -76
- package/types/server/rscWorkerProcess.d.ts +31 -0
- package/types/server/rscWorkerRecycler.d.ts +22 -0
- package/types/server/serverConfig.d.ts +30 -0
- package/types/server/serverMetrics.d.ts +11 -0
- package/types/server/sitemap.d.ts +1 -0
- package/types/server/ssrFromRscRenderer.d.ts +2 -2
- package/types/server/ssrTypes.d.ts +8 -0
- package/types/server/webArtifact.d.ts +7 -0
- package/types/server/webAssetRoutes.d.ts +11 -0
- package/types/server/webCsrSurface.d.ts +18 -0
- package/types/server/webDocumentRoute.d.ts +19 -0
- package/types/server/webRouteContext.d.ts +45 -0
- package/types/server/webRouter.d.ts +4 -35
- package/types/server/webRscRoute.d.ts +24 -0
- package/types/server/webSiteFiles.d.ts +12 -0
- package/types/server/wellKnownRoutes.d.ts +5 -0
- package/types/service/agent.service.d.ts +13 -4
- package/types/service/agentAccounts.d.ts +8 -0
- package/types/service/agentLoop/agentLoop.d.ts +31 -0
- package/types/service/agentLoop/agentLoopTypes.d.ts +126 -0
- package/types/service/agentLoop/deltaStream.d.ts +3 -0
- package/types/service/agentLoop/loopCompaction.d.ts +11 -0
- package/types/service/agentLoop/loopRequest.d.ts +6 -0
- package/types/service/agentLoop/loopToolOutput.d.ts +7 -0
- package/types/service/agentLoop/loopToolkits.d.ts +14 -0
- package/types/service/agentLoop/loopTranscript.d.ts +12 -0
- package/types/service/agentMeter.d.ts +50 -0
- package/types/service/agentRelayPolicy.d.ts +45 -0
- package/types/service/documentStoreError.d.ts +7 -0
- package/types/service/index.d.ts +7 -0
- package/types/service/injectError.d.ts +4 -0
- package/types/service/injectInfo.d.ts +2 -1
- package/types/service/insightQueryError.d.ts +9 -0
- package/types/service/ipcTypes.d.ts +6 -0
- package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
- package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
- package/types/service/predefinedAdaptor/index.d.ts +2 -0
- package/types/service/predefinedAdaptor/llm.adaptor.d.ts +18 -2
- package/types/service/predefinedAdaptor/llmSpend.d.ts +22 -0
- package/types/service/predefinedAdaptor/openaiDialect.d.ts +2 -1
- package/types/service/predefinedAdaptor/openaiLlm.d.ts +1 -1
- package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
- package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
- package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
- package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
- package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
- package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +24 -0
- package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
- package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
- package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -32
- package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +20 -0
- package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
- package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +1 -14
- package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
- package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
- package/types/service/predefinedAdaptor/sseData.d.ts +5 -0
- package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +14 -5
- package/types/service/serviceModule.d.ts +1 -1
- package/types/service/serviceRegistry.d.ts +1 -0
- package/types/signal/SignalFailure.d.ts +2 -0
- package/types/signal/agentTurnStream.d.ts +2 -1
- package/types/signal/byIdRead.d.ts +7 -0
- package/types/signal/carriedClientIps.d.ts +4 -0
- package/types/signal/endpointErrorContract.d.ts +3 -0
- package/types/signal/exception.d.ts +1 -0
- package/types/signal/index.d.ts +32 -30
- package/types/signal/mcp/McpDocument.d.ts +2 -0
- package/types/signal/mcp/index.d.ts +1 -0
- package/types/signal/mcp/promptError.d.ts +5 -0
- package/types/signal/resolveFieldContext.d.ts +15 -0
- package/types/signal/serializer/fetch.serializer.d.ts +3 -1
- package/types/signal/signalContext.d.ts +1 -13
- package/types/signal/signalContractError.d.ts +4 -0
- package/types/signal/signalDeclarationError.d.ts +4 -0
- package/types/signal/slice.d.ts +15 -13
- package/types/signal/trace.d.ts +3 -0
- package/types/signal/types.d.ts +33 -6
- package/types/store/action.d.ts +8 -27
- package/types/store/actionErrorKey.d.ts +1 -0
- package/types/store/actionOption.d.ts +24 -0
- package/types/store/baseSt.d.ts +2 -295
- package/types/store/draftFlush.d.ts +4 -0
- package/types/store/formDrafts.d.ts +21 -0
- package/types/store/formFieldSetters.d.ts +80 -0
- package/types/store/index.d.ts +17 -16
- package/types/store/modelActionContext.d.ts +189 -0
- package/types/store/modelListPatch.d.ts +34 -0
- package/types/store/modelOpenActions.d.ts +12 -0
- package/types/store/modelWriteActions.d.ts +16 -0
- package/types/store/modelWriteGuard.d.ts +42 -0
- package/types/store/openSeq.d.ts +17 -0
- package/types/store/rootStore.d.ts +6 -0
- package/types/store/sliceListActions.d.ts +295 -0
- package/types/store/sliceLiveActions.d.ts +6 -0
- package/types/store/stateBuilder.d.ts +2 -0
- package/types/store/uploadPoll.d.ts +16 -0
- package/types/store/withSelector.d.ts +1 -1
- package/types/ui/Agent/Chat.d.ts +5 -2
- package/types/ui/Agent/ChatHeader.d.ts +13 -0
- package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
- package/types/ui/Field/Choice.d.ts +2 -1
- package/types/ui/Field/index.d.ts +1 -1
- package/types/ui/Link/inputModality.d.ts +5 -0
- package/types/ui/Link/viewportPrefetch.d.ts +4 -0
- package/types/ui/Load/Edit_Client.d.ts +2 -0
- package/types/ui/Load/Pagination.d.ts +4 -1
- package/types/ui/Load/Stream.d.ts +7 -1
- package/types/ui/Load/StreamBoundary.d.ts +20 -0
- package/types/ui/Load/Units.d.ts +2 -0
- package/types/ui/Load/View.d.ts +2 -0
- package/types/ui/Reference/origin.d.ts +1 -0
- package/types/ui/index.d.ts +1 -1
- package/types/ui/overlayLayer.d.ts +6 -1
- package/types/ui/recipe/badgeRecipe.d.ts +3 -3
- package/types/ui/recipe/buttonRecipe.d.ts +3 -3
- package/types/ui/recipe/inputRecipe.d.ts +1 -1
- package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
- package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
- package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +18 -11
- package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
- package/types/vendor/use-agentic/failureCode.d.ts +4 -0
- package/types/vendor/use-agentic/index.d.ts +1 -0
- package/types/vendor/use-agentic/types.d.ts +11 -0
- package/types/webkit/CsrGuards.d.ts +2 -0
- package/types/webkit/RouteLevelBoundary.d.ts +17 -0
- package/types/webkit/nativeCore.d.ts +1 -0
- package/types/webkit/nativePurchase.d.ts +2 -1
- package/types/webkit/useCsrKeyboard.d.ts +19 -0
- package/types/webkit/useCsrLocationState.d.ts +21 -0
- package/types/webkit/useCsrNavigation.d.ts +25 -0
- package/types/webkit/useCsrRefs.d.ts +33 -0
- package/types/webkit/useCsrRenderTrace.d.ts +13 -0
- package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
- package/types/webkit/useCsrTransitions.d.ts +2 -0
- package/types/webkit/useFrameRuntime.d.ts +1 -0
- package/types/webkit/useGeoLocation.d.ts +1 -1
- package/types/webkit/useHistory.d.ts +2 -3
- package/types/webkit/usePurchase.d.ts +1 -1
- package/types/webkit/useResolvedFrame.d.ts +38 -0
- package/types/webkit/useSyncNavigation.d.ts +22 -0
- package/types/webkit/useTransitionStore.d.ts +1 -0
- package/ui/Agent/Chat.tsx +392 -235
- package/ui/Agent/ChatHeader.tsx +59 -0
- package/ui/Agent/ChatPendingCards.tsx +49 -0
- package/ui/Agent/fetchRunner.ts +8 -1
- package/ui/BottomSheet.tsx +1 -1
- package/ui/Button.tsx +1 -0
- package/ui/Data/Item.tsx +2 -2
- package/ui/Data/ListContainer.tsx +348 -181
- package/ui/Data/useViewModal.ts +10 -4
- package/ui/Dialog/LegacyModal.tsx +1 -1
- package/ui/Dialog/Modal.tsx +1 -1
- package/ui/Field/Choice.tsx +3 -1
- package/ui/Link/inputModality.ts +21 -0
- package/ui/Link/prefetchIntent.ts +7 -25
- package/ui/Link/viewportPrefetch.ts +30 -0
- package/ui/Load/Edit_Client.tsx +7 -1
- package/ui/Load/Pagination.tsx +10 -2
- package/ui/Load/Stream.tsx +24 -4
- package/ui/Load/StreamBoundary.tsx +65 -0
- package/ui/Load/Units.tsx +3 -0
- package/ui/Load/View.tsx +5 -1
- package/ui/Model/EditModal.tsx +2 -1
- package/ui/Popconfirm.tsx +1 -1
- package/ui/Reference/origin.ts +1 -0
- package/ui/Select.tsx +43 -51
- package/ui/Signal/RestApi.tsx +3 -2
- package/ui/System/Client.tsx +32 -8
- package/ui/index.ts +4 -0
- package/ui/overlayLayer.ts +22 -1
- package/vendor/@akanjs/native/CHANGELOG.md +7 -1
- package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +27 -12
- package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
- package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
- package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
- package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +509 -0
- package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
- package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
- package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
- package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
- package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
- package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
- package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
- package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
- package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
- package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
- package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
- package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
- package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
- package/vendor/@akanjs/native/plugins/external-view/src/index.ts +18 -11
- package/vendor/use-agentic/AgentClientTools.ts +33 -0
- package/vendor/use-agentic/AgentSession.ts +11 -11
- package/vendor/use-agentic/CHANGELOG.md +46 -1
- package/vendor/use-agentic/Compaction.ts +2 -1
- package/vendor/use-agentic/ToolRunner.ts +6 -3
- package/vendor/use-agentic/Transcript.ts +6 -3
- package/vendor/use-agentic/WIRE.md +29 -7
- package/vendor/use-agentic/failureCode.ts +44 -0
- package/vendor/use-agentic/httpRunner.ts +15 -4
- package/vendor/use-agentic/index.ts +1 -0
- package/vendor/use-agentic/types.ts +11 -0
- package/webkit/CsrGuards.ts +7 -2
- package/webkit/McpAppAgent.ts +8 -3
- package/webkit/McpAppFetchBridge.ts +11 -5
- package/webkit/RouteLevelBoundary.tsx +37 -0
- package/webkit/nativeCore.ts +1 -0
- package/webkit/nativePurchase.ts +6 -3
- package/webkit/useCamera.tsx +22 -21
- package/webkit/useCsrKeyboard.ts +155 -0
- package/webkit/useCsrLocationState.ts +58 -0
- package/webkit/useCsrNavigation.ts +302 -0
- package/webkit/useCsrRefs.ts +52 -0
- package/webkit/useCsrRenderTrace.ts +68 -0
- package/webkit/useCsrStackLifecycle.ts +120 -0
- package/webkit/useCsrTransitions.ts +552 -0
- package/webkit/useCsrValues.ts +69 -1234
- package/webkit/useGeoLocation.tsx +4 -1
- package/webkit/useHistory.ts +2 -2
- package/webkit/useLocation.ts +3 -2
- package/webkit/usePurchase.tsx +4 -2
- package/webkit/useResolvedFrame.ts +116 -0
- package/webkit/useSyncNavigation.ts +109 -0
- package/webkit/useTransitionStore.ts +13 -0
- package/types/signal/agentMeter.d.ts +0 -27
- package/types/signal/agentRelayPolicy.d.ts +0 -25
package/server/rscWorker.tsx
CHANGED
|
@@ -1,99 +1,26 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
PathRoute,
|
|
7
|
-
RedirectStatus,
|
|
8
|
-
ResolvedHead,
|
|
9
|
-
RouteRender,
|
|
10
|
-
RouteViewport,
|
|
11
|
-
} from "akanjs/client";
|
|
12
|
-
import {
|
|
13
|
-
type AkanI18nConfig,
|
|
14
|
-
DEFAULT_AKAN_I18N,
|
|
15
|
-
getBasePathFromPathname,
|
|
16
|
-
LocalePath,
|
|
17
|
-
Logger,
|
|
18
|
-
parseSearchParams,
|
|
19
|
-
} from "akanjs/common";
|
|
20
|
-
import {
|
|
21
|
-
type AkanTheme,
|
|
22
|
-
getRequestDynamicUsage,
|
|
23
|
-
getRequestFrameState,
|
|
24
|
-
getRequestPolicy,
|
|
25
|
-
getRequestTheme,
|
|
26
|
-
RenderScope,
|
|
27
|
-
requestStorage,
|
|
28
|
-
setRequestFrameState,
|
|
29
|
-
setRequestTheme,
|
|
30
|
-
untrackedCookies,
|
|
31
|
-
untrackedRequest,
|
|
32
|
-
updateRequestPolicy,
|
|
33
|
-
} from "akanjs/fetch";
|
|
34
|
-
import type { ReactNode } from "react";
|
|
35
|
-
import { renderToReadableStream } from "react-server-dom-webpack/server.node";
|
|
36
|
-
import { RouteHead } from "../client/route/RouteHead";
|
|
37
|
-
import { ViewportMeta } from "../client/viewportMeta";
|
|
38
|
-
import { toManifestJson, webManifestHref } from "../client/webManifest";
|
|
1
|
+
import { AkanError } from "akanjs/base";
|
|
2
|
+
import type { LayoutFallbackRoute, PathRoute } from "akanjs/client";
|
|
3
|
+
import { type AkanI18nConfig, DEFAULT_AKAN_I18N, Logger } from "akanjs/common";
|
|
4
|
+
import { RenderScope, requestStorage } from "akanjs/fetch";
|
|
5
|
+
import { toManifestJson } from "../client/webManifest";
|
|
39
6
|
import type { PagePromptRunInput, PagePromptVisibleInput } from "../signal/mcp/pagePrompt";
|
|
40
|
-
import {
|
|
7
|
+
import { runTraced, SignalTrace } from "../signal/trace";
|
|
41
8
|
import type { ClientManifest } from "./artifact";
|
|
42
|
-
import {
|
|
43
|
-
LruTtlCache,
|
|
44
|
-
type LruTtlCacheOptions,
|
|
45
|
-
parsePositiveInt,
|
|
46
|
-
type RouteCacheEntry,
|
|
47
|
-
type RouteCacheRenderState,
|
|
48
|
-
resolvePublicRouteCacheEntryDecision,
|
|
49
|
-
resolveRouteCacheStoreTtl,
|
|
50
|
-
shouldStoreRouteCache,
|
|
51
|
-
} from "./cachePolicy";
|
|
52
|
-
import { FallbackHead } from "./fallbackHead";
|
|
53
|
-
import {
|
|
54
|
-
createAkanLocaleAlternateHeadSnapshot,
|
|
55
|
-
mergeAkanHeadSnapshots,
|
|
56
|
-
renderAkanHeadSnapshot,
|
|
57
|
-
resolveHeadResult,
|
|
58
|
-
} from "./head";
|
|
59
9
|
import { LogForwarder } from "./logging/logForwarder";
|
|
60
10
|
import { ProcessMetricsCollector } from "./processMetricsCollector";
|
|
61
|
-
import { RouteElementComposer, type RouteNotFoundInPlace } from "./routeElementComposer";
|
|
62
|
-
import { RouteShellGate } from "./routeShellGate";
|
|
63
|
-
import {
|
|
64
|
-
type AkanRscPatchDecision,
|
|
65
|
-
createAkanRouterState,
|
|
66
|
-
encodeAkanHeadSnapshot,
|
|
67
|
-
encodeAkanRouterState,
|
|
68
|
-
encodeAkanRscPatchSegmentPath,
|
|
69
|
-
isAkanRscPartialCommitEnabled,
|
|
70
|
-
readAkanRouterStateRequest,
|
|
71
|
-
resolveAkanRscPartialDecision,
|
|
72
|
-
resolveAkanRscPatchDecision,
|
|
73
|
-
} from "./routeState";
|
|
74
11
|
import { type PagesContext, RouteTreeBuilder } from "./routeTreeBuilder";
|
|
75
|
-
import {
|
|
12
|
+
import { RscDocumentHead } from "./rscDocumentHead";
|
|
13
|
+
import { RscFlightRenderer } from "./rscFlightRenderer";
|
|
76
14
|
import { RscPagePrompts } from "./rscPagePrompts";
|
|
77
|
-
import {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
shouldCollectRscWorkerRenderChunks,
|
|
87
|
-
shouldStoreRscWorkerPatchResult,
|
|
88
|
-
shouldUseRscWorkerFullResultCache,
|
|
89
|
-
} from "./rscWorkerCache";
|
|
90
|
-
import type { RscTraceMetadata } from "./ssrTypes";
|
|
91
|
-
import {
|
|
92
|
-
createSystemPageDocument,
|
|
93
|
-
getPathnameLocale,
|
|
94
|
-
getSystemPageHomeHref,
|
|
95
|
-
SystemPageMain,
|
|
96
|
-
} from "./systemPageDocument";
|
|
15
|
+
import { RscPatchPlanner } from "./rscPatchPlanner";
|
|
16
|
+
import { RscRenderFallbacks } from "./rscRenderFallbacks";
|
|
17
|
+
import { RscRenderHandler } from "./rscRenderHandler";
|
|
18
|
+
import { RscRenderStats } from "./rscRenderStats";
|
|
19
|
+
import { RscResultCaches } from "./rscResultCaches";
|
|
20
|
+
import { RscRouteDocument } from "./rscRouteDocument";
|
|
21
|
+
import { invalidateCachedRscResults } from "./rscWorkerCache";
|
|
22
|
+
|
|
23
|
+
export { isAkanNotFoundError, isAkanRedirectError } from "./rscRenderControl";
|
|
97
24
|
|
|
98
25
|
interface InitMsg {
|
|
99
26
|
type: "init";
|
|
@@ -111,6 +38,7 @@ interface RenderMsg {
|
|
|
111
38
|
method?: string;
|
|
112
39
|
headers?: Record<string, string>;
|
|
113
40
|
clientManifest?: ClientManifest;
|
|
41
|
+
prefetch?: boolean;
|
|
114
42
|
}
|
|
115
43
|
interface CancelMsg {
|
|
116
44
|
type: "cancel";
|
|
@@ -169,72 +97,6 @@ type InMsg =
|
|
|
169
97
|
| PagePromptRunMsg
|
|
170
98
|
| PagePromptsVisibleMsg
|
|
171
99
|
| WebManifestMsg;
|
|
172
|
-
type RenderControl =
|
|
173
|
-
| { type: "redirect"; location: string; method: "replace" | "push"; status: RedirectStatus }
|
|
174
|
-
| { type: "not-found" }
|
|
175
|
-
| { type: "error"; error: unknown };
|
|
176
|
-
interface FlightRenderResult {
|
|
177
|
-
chunks: Uint8Array[];
|
|
178
|
-
bytes: number;
|
|
179
|
-
chunksCount: number;
|
|
180
|
-
control: RenderControl | null;
|
|
181
|
-
lateControlSent: boolean;
|
|
182
|
-
cancelled: boolean;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** Well above any sensible TTL: this reclaims a cache nobody is reading, not tracks expiry closely. */
|
|
186
|
-
const RESULT_CACHE_SWEEP_INTERVAL_MS = 60_000;
|
|
187
|
-
|
|
188
|
-
function hashRscTraceCacheKey(cacheKey: string): string {
|
|
189
|
-
let hash = 5381;
|
|
190
|
-
for (let index = 0; index < cacheKey.length; index += 1) hash = (hash * 33) ^ cacheKey.charCodeAt(index);
|
|
191
|
-
return (hash >>> 0).toString(36);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
interface RscRendererStats {
|
|
195
|
-
renderCount: number;
|
|
196
|
-
inFlightRenderCount: number;
|
|
197
|
-
lastRenderedPath?: string;
|
|
198
|
-
lastRenderKind?: string;
|
|
199
|
-
lastRenderRouteId?: string;
|
|
200
|
-
lastRenderDurationMs?: number;
|
|
201
|
-
lastRenderLoadedModuleDelta: number;
|
|
202
|
-
lastRenderLoadedModules: string[];
|
|
203
|
-
lastFlightBytes: number;
|
|
204
|
-
lastFlightChunks: number;
|
|
205
|
-
totalFlightBytes: number;
|
|
206
|
-
totalFlightChunks: number;
|
|
207
|
-
pagesBundleBuildId: number;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
interface RouteRenderStats {
|
|
211
|
-
routeId: string;
|
|
212
|
-
count: number;
|
|
213
|
-
flightBytes: number;
|
|
214
|
-
totalDurationMs: number;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
export function isAkanRedirectError(error: unknown): error is AkanRedirectError {
|
|
218
|
-
return (
|
|
219
|
-
typeof error === "object" &&
|
|
220
|
-
error !== null &&
|
|
221
|
-
"digest" in error &&
|
|
222
|
-
(error as { digest?: unknown }).digest === "AKAN_REDIRECT" &&
|
|
223
|
-
"location" in error &&
|
|
224
|
-
typeof (error as { location?: unknown }).location === "string" &&
|
|
225
|
-
"status" in error &&
|
|
226
|
-
typeof (error as { status?: unknown }).status === "number"
|
|
227
|
-
);
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
export function isAkanNotFoundError(error: unknown): error is AkanNotFoundError {
|
|
231
|
-
return (
|
|
232
|
-
typeof error === "object" &&
|
|
233
|
-
error !== null &&
|
|
234
|
-
"digest" in error &&
|
|
235
|
-
(error as { digest?: unknown }).digest === "AKAN_NOT_FOUND"
|
|
236
|
-
);
|
|
237
|
-
}
|
|
238
100
|
|
|
239
101
|
export class RscRenderer {
|
|
240
102
|
readonly #logger = new Logger("RscWorker");
|
|
@@ -249,43 +111,60 @@ export class RscRenderer {
|
|
|
249
111
|
#pagesBundleBuildId = 0;
|
|
250
112
|
#reloadSeq = 0;
|
|
251
113
|
#metricsTimer: Timer | null = null;
|
|
252
|
-
#stats
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
lastRenderLoadedModuleDelta: 0,
|
|
256
|
-
lastRenderLoadedModules: [],
|
|
257
|
-
lastFlightBytes: 0,
|
|
258
|
-
lastFlightChunks: 0,
|
|
259
|
-
totalFlightBytes: 0,
|
|
260
|
-
totalFlightChunks: 0,
|
|
261
|
-
pagesBundleBuildId: 0,
|
|
262
|
-
};
|
|
263
|
-
readonly #routeStats = new Map<string, RouteRenderStats>();
|
|
264
|
-
|
|
265
|
-
#resultCache = new LruTtlCache<CachedRscResult>(
|
|
266
|
-
parsePositiveInt(process.env.AKAN_RSC_RESULT_CACHE_MAX_ENTRIES) ?? 100,
|
|
267
|
-
RscRenderer.#resultCacheOptions(),
|
|
268
|
-
);
|
|
269
|
-
#patchResultCache = new LruTtlCache<CachedRscResult>(
|
|
270
|
-
parsePositiveInt(process.env.AKAN_RSC_RESULT_CACHE_MAX_ENTRIES) ?? 100,
|
|
271
|
-
RscRenderer.#resultCacheOptions(),
|
|
272
|
-
);
|
|
273
|
-
readonly #activeRenderReaders = new Map<string, ReadableStreamDefaultReader<Uint8Array>>();
|
|
274
|
-
readonly #cancelledRenderRequests = new Set<string>();
|
|
275
|
-
#resultCacheHits = 0;
|
|
276
|
-
#resultCacheMisses = 0;
|
|
277
|
-
#resultCacheBypass = 0;
|
|
114
|
+
readonly #stats = new RscRenderStats();
|
|
115
|
+
readonly #caches = new RscResultCaches(this.#logger);
|
|
116
|
+
readonly #flights = new RscFlightRenderer(this.#logger, (message) => this.#send(message));
|
|
278
117
|
readonly #send: (message: unknown) => void;
|
|
279
118
|
readonly #pagePrompts = new RscPagePrompts({
|
|
280
119
|
routes: () => this.#pathRoutes,
|
|
281
120
|
run: (request, routeId, fn) => this.#runWithRequest(request, routeId, fn),
|
|
282
121
|
defaultLocale: () => this.#i18n.defaultLocale,
|
|
283
122
|
});
|
|
123
|
+
readonly #head = new RscDocumentHead({
|
|
124
|
+
i18n: () => this.#i18n,
|
|
125
|
+
basePaths: () => this.#basePaths,
|
|
126
|
+
cssAssets: () => this.#cssAssets,
|
|
127
|
+
});
|
|
128
|
+
readonly #patchPlanner = new RscPatchPlanner({
|
|
129
|
+
logger: this.#logger,
|
|
130
|
+
routes: () => this.#pathRoutes,
|
|
131
|
+
buildId: () => this.#pagesBundleBuildId,
|
|
132
|
+
basePathOf: (url) => this.#head.getBasePath(url),
|
|
133
|
+
localeAlternatesOf: (url) => this.#head.getLocaleAlternateLanguages(url),
|
|
134
|
+
defaultHead: () => this.#head.renderDefaultHead(),
|
|
135
|
+
});
|
|
136
|
+
readonly #documents = new RscRouteDocument({
|
|
137
|
+
logger: this.#logger,
|
|
138
|
+
head: this.#head,
|
|
139
|
+
patchPlanner: this.#patchPlanner,
|
|
140
|
+
i18n: () => this.#i18n,
|
|
141
|
+
basePaths: () => this.#basePaths,
|
|
142
|
+
});
|
|
143
|
+
readonly #fallbacks = new RscRenderFallbacks((message) => this.#send(message), {
|
|
144
|
+
logger: this.#logger,
|
|
145
|
+
stats: this.#stats,
|
|
146
|
+
flights: this.#flights,
|
|
147
|
+
documents: this.#documents,
|
|
148
|
+
clientManifest: () => this.#clientManifest,
|
|
149
|
+
runInRequestScope: (request, fn) => this.#runInRequestScope(request, fn),
|
|
150
|
+
});
|
|
151
|
+
readonly #renders = new RscRenderHandler((message) => this.#send(message), {
|
|
152
|
+
logger: this.#logger,
|
|
153
|
+
stats: this.#stats,
|
|
154
|
+
caches: this.#caches,
|
|
155
|
+
flights: this.#flights,
|
|
156
|
+
documents: this.#documents,
|
|
157
|
+
fallbacks: this.#fallbacks,
|
|
158
|
+
patchPlanner: this.#patchPlanner,
|
|
159
|
+
routes: () => this.#pathRoutes,
|
|
160
|
+
fallbackRoutes: () => this.#fallbackRoutes,
|
|
161
|
+
clientManifest: () => this.#clientManifest,
|
|
162
|
+
runWithRequest: (request, routeId, fn) => this.#runWithRequest(request, routeId, fn),
|
|
163
|
+
});
|
|
284
164
|
|
|
285
165
|
constructor() {
|
|
286
|
-
if (typeof process.send !== "function")
|
|
287
|
-
throw new
|
|
288
|
-
}
|
|
166
|
+
if (typeof process.send !== "function")
|
|
167
|
+
throw new AkanError("ipcRequired", "rscWorker must be run as a Bun subprocess with ipc enabled");
|
|
289
168
|
this.#send = process.send.bind(process) as (message: unknown) => void;
|
|
290
169
|
Logger.role = "rsc-worker";
|
|
291
170
|
if (Logger.isNdjson) Logger.consoleOutput = false;
|
|
@@ -314,11 +193,11 @@ export class RscRenderer {
|
|
|
314
193
|
return;
|
|
315
194
|
case "render":
|
|
316
195
|
this.#logger.verbose(`received render requestId=${msg.requestId} url=${msg.url} method=${msg.method ?? "GET"}`);
|
|
317
|
-
void this.#handleRender(msg);
|
|
196
|
+
void this.#renders.handleRender(msg);
|
|
318
197
|
return;
|
|
319
198
|
case "cancel":
|
|
320
199
|
this.#logger.verbose(`received cancel requestId=${msg.requestId}`);
|
|
321
|
-
this.#handleCancel(msg.requestId);
|
|
200
|
+
this.#flights.handleCancel(msg.requestId);
|
|
322
201
|
return;
|
|
323
202
|
case "reload":
|
|
324
203
|
this.#logger.verbose(`received reload buildId=${msg.buildId}`);
|
|
@@ -330,8 +209,8 @@ export class RscRenderer {
|
|
|
330
209
|
return;
|
|
331
210
|
case "invalidate-cache":
|
|
332
211
|
this.#logger.verbose(`received invalidate-cache reason=${msg.reason ?? "(none)"}`);
|
|
333
|
-
invalidateCachedRscResults(this.#resultCache, msg);
|
|
334
|
-
invalidateCachedRscResults(this.#patchResultCache, msg);
|
|
212
|
+
invalidateCachedRscResults(this.#caches.resultCache, msg);
|
|
213
|
+
invalidateCachedRscResults(this.#caches.patchResultCache, msg);
|
|
335
214
|
return;
|
|
336
215
|
case "log-level":
|
|
337
216
|
this.#logForwarder.setMinSev(msg.minSev);
|
|
@@ -354,7 +233,7 @@ export class RscRenderer {
|
|
|
354
233
|
async #webManifest(basePath: string | null): Promise<unknown> {
|
|
355
234
|
const pathname = `/${this.#i18n.defaultLocale}${basePath ? `/${basePath}` : ""}`;
|
|
356
235
|
const rootLayouts = RouteTreeBuilder.matchFallback(pathname, this.#fallbackRoutes)?.fallbackRoute.renderRootLayouts;
|
|
357
|
-
const manifest = await
|
|
236
|
+
const manifest = await RscDocumentHead.firstRootValue(rootLayouts ?? [], (render) => render.getLayoutManifest?.());
|
|
358
237
|
return manifest ? toManifestJson(manifest) : null;
|
|
359
238
|
}
|
|
360
239
|
|
|
@@ -366,14 +245,6 @@ export class RscRenderer {
|
|
|
366
245
|
}
|
|
367
246
|
}
|
|
368
247
|
|
|
369
|
-
#handleCancel(requestId: string): void {
|
|
370
|
-
this.#cancelledRenderRequests.add(requestId);
|
|
371
|
-
const reader = this.#activeRenderReaders.get(requestId);
|
|
372
|
-
if (!reader) return;
|
|
373
|
-
void reader.cancel().catch(() => {
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
|
|
377
248
|
async #handleInit(msg: InitMsg): Promise<void> {
|
|
378
249
|
const startedAt = Date.now();
|
|
379
250
|
try {
|
|
@@ -384,9 +255,9 @@ export class RscRenderer {
|
|
|
384
255
|
this.#pagesBundlePath = msg.pagesBundlePath;
|
|
385
256
|
this.#pagesBundleBuildId = msg.pagesBundleBuildId;
|
|
386
257
|
this.#stats.pagesBundleBuildId = msg.pagesBundleBuildId;
|
|
387
|
-
this.#routeStats.clear();
|
|
388
|
-
this.#resultCache.clear();
|
|
389
|
-
this.#patchResultCache.clear();
|
|
258
|
+
this.#stats.routeStats.clear();
|
|
259
|
+
this.#caches.resultCache.clear();
|
|
260
|
+
this.#caches.patchResultCache.clear();
|
|
390
261
|
this.#logger.verbose(
|
|
391
262
|
`init state pagesBundlePath=${msg.pagesBundlePath} buildId=${msg.pagesBundleBuildId} cssAssets=${Object.keys(this.#cssAssets).length} clientEntries=${Object.keys(msg.clientManifest).length}`,
|
|
392
263
|
);
|
|
@@ -429,9 +300,9 @@ export class RscRenderer {
|
|
|
429
300
|
this.#stats.pagesBundleBuildId = msg.buildId;
|
|
430
301
|
this.#pathRoutes = routes.pathRoutes;
|
|
431
302
|
this.#fallbackRoutes = routes.fallbackRoutes;
|
|
432
|
-
this.#routeStats.clear();
|
|
433
|
-
this.#resultCache.clear();
|
|
434
|
-
this.#patchResultCache.clear();
|
|
303
|
+
this.#stats.routeStats.clear();
|
|
304
|
+
this.#caches.resultCache.clear();
|
|
305
|
+
this.#caches.patchResultCache.clear();
|
|
435
306
|
this.#logger.verbose(`reload complete buildId=${msg.buildId} in ${Date.now() - startedAt}ms`);
|
|
436
307
|
this.#send({
|
|
437
308
|
type: "reloaded",
|
|
@@ -466,7 +337,7 @@ export class RscRenderer {
|
|
|
466
337
|
const mod = (await import(specifier)) as { pages?: PagesContext; default?: PagesContext };
|
|
467
338
|
const importedAt = Date.now();
|
|
468
339
|
const pages = mod.pages ?? mod.default;
|
|
469
|
-
if (!pages) throw new
|
|
340
|
+
if (!pages) throw new AkanError("invalidArtifact", `pages export not found in ${specifier}`);
|
|
470
341
|
|
|
471
342
|
const routeBuildStart = Date.now();
|
|
472
343
|
const routeTree = new RouteTreeBuilder(pages);
|
|
@@ -478,368 +349,12 @@ export class RscRenderer {
|
|
|
478
349
|
return { pathRoutes, fallbackRoutes: routeTree.getFallbackRoutes() };
|
|
479
350
|
}
|
|
480
351
|
|
|
481
|
-
async #handleRender(msg: RenderMsg): Promise<void> {
|
|
482
|
-
const { requestId, url, method = "GET", headers = {} } = msg;
|
|
483
|
-
const startedAt = Date.now();
|
|
484
|
-
this.#stats.renderCount += 1;
|
|
485
|
-
this.#stats.inFlightRenderCount += 1;
|
|
486
|
-
const activeRoute: {
|
|
487
|
-
url: URL | null;
|
|
488
|
-
match: { pathRoute: PathRoute; params: Record<string, string> } | null;
|
|
489
|
-
request: Request | null;
|
|
490
|
-
} = { url: null, match: null, request: null };
|
|
491
|
-
try {
|
|
492
|
-
const request = new Request(url, { method, headers });
|
|
493
|
-
const urlObj = new URL(url);
|
|
494
|
-
const match = RouteTreeBuilder.match(urlObj.pathname, this.#pathRoutes);
|
|
495
|
-
const routeId = match?.pathRoute.path ?? "__not_found__";
|
|
496
|
-
await this.#runWithRequest(request, routeId, async () => {
|
|
497
|
-
activeRoute.url = urlObj;
|
|
498
|
-
activeRoute.request = request;
|
|
499
|
-
this.#stats.lastRenderedPath = urlObj.pathname;
|
|
500
|
-
activeRoute.match = match;
|
|
501
|
-
updateRequestPolicy({ routeId });
|
|
502
|
-
this.#stats.lastRenderRouteId = routeId;
|
|
503
|
-
this.#stats.lastRenderKind = match ? "route" : "not-found";
|
|
504
|
-
if (match)
|
|
505
|
-
this.#logger.verbose(
|
|
506
|
-
`render[${requestId}] matched route pathname=${urlObj.pathname} params=${JSON.stringify(match.params)}`,
|
|
507
|
-
);
|
|
508
|
-
else this.#logger.verbose(`render[${requestId}] no route matched pathname=${urlObj.pathname} — rendering 404`);
|
|
509
|
-
const beforeLoadedKeys = RouteTreeBuilder.getCacheStats().loadedModuleKeys;
|
|
510
|
-
const cacheDecision = match ? this.#getResultCacheEntry(request, urlObj) : { entry: null };
|
|
511
|
-
const cacheEntry = cacheDecision.entry;
|
|
512
|
-
const targetRouterState = match
|
|
513
|
-
? createAkanRouterState({
|
|
514
|
-
pathRoute: match.pathRoute,
|
|
515
|
-
href: urlObj.href,
|
|
516
|
-
buildId: this.#pagesBundleBuildId,
|
|
517
|
-
})
|
|
518
|
-
: null;
|
|
519
|
-
const searchParams = parseSearchParams(urlObj.search);
|
|
520
|
-
const currentRouterState = readAkanRouterStateRequest(request.headers);
|
|
521
|
-
const partialDecision = targetRouterState
|
|
522
|
-
? resolveAkanRscPartialDecision({
|
|
523
|
-
currentState: currentRouterState.state,
|
|
524
|
-
currentRoute: currentRouterState.currentRoute,
|
|
525
|
-
targetState: targetRouterState,
|
|
526
|
-
})
|
|
527
|
-
: { status: "full" as const, reason: "missing-route", commonPrefixLength: 0 };
|
|
528
|
-
const patchDecision: AkanRscPatchDecision =
|
|
529
|
-
targetRouterState && match
|
|
530
|
-
? resolveAkanRscPatchDecision({
|
|
531
|
-
currentState: currentRouterState.state,
|
|
532
|
-
targetState: targetRouterState,
|
|
533
|
-
partialDecision,
|
|
534
|
-
})
|
|
535
|
-
: { status: "full" as const, reason: partialDecision.reason, commonPrefixLength: 0 };
|
|
536
|
-
|
|
537
|
-
let admitted = false;
|
|
538
|
-
const safePatchDecision = match
|
|
539
|
-
? await this.#resolveHeadSafePatchDecision(match.pathRoute, patchDecision, async () => {
|
|
540
|
-
await RouteElementComposer.admit({ pathRoute: match.pathRoute, params: match.params, searchParams });
|
|
541
|
-
admitted = true;
|
|
542
|
-
return await this.#resolveRouteHeadSnapshot(urlObj, match, searchParams);
|
|
543
|
-
})
|
|
544
|
-
: patchDecision;
|
|
545
|
-
const patchCacheEntry = resolveRscWorkerPatchCacheEntry({
|
|
546
|
-
cacheEntry,
|
|
547
|
-
targetRouterState,
|
|
548
|
-
safePatchDecision,
|
|
549
|
-
partialCommitEnabled: isAkanRscPartialCommitEnabled(),
|
|
550
|
-
});
|
|
551
|
-
const createTraceBase = (
|
|
552
|
-
decision: AkanRscPatchDecision,
|
|
553
|
-
cacheKey = cacheEntry?.key,
|
|
554
|
-
routeState = targetRouterState,
|
|
555
|
-
) => ({
|
|
556
|
-
navId: requestId,
|
|
557
|
-
pathname: urlObj.pathname,
|
|
558
|
-
routeId,
|
|
559
|
-
partial: decision.status,
|
|
560
|
-
partialReason: decision.reason ?? currentRouterState.reason,
|
|
561
|
-
partialCommonPrefixLength: decision.commonPrefixLength,
|
|
562
|
-
...(decision.patch
|
|
563
|
-
? {
|
|
564
|
-
patchStartIndex: decision.patch.patchStartIndex,
|
|
565
|
-
patchSegmentPath: encodeAkanRscPatchSegmentPath(decision.patch.segmentPath),
|
|
566
|
-
patchStartSegment: decision.patch.patchStartSegmentKey,
|
|
567
|
-
patchHeadSafe: decision.patch.headSafe,
|
|
568
|
-
patchHeadSnapshot: decision.patch.headSnapshot
|
|
569
|
-
? (encodeAkanHeadSnapshot(decision.patch.headSnapshot) ?? undefined)
|
|
570
|
-
: undefined,
|
|
571
|
-
}
|
|
572
|
-
: {}),
|
|
573
|
-
...(routeState ? { routeState: encodeAkanRouterState(routeState) } : {}),
|
|
574
|
-
...(cacheKey ? { cacheKeyHash: hashRscTraceCacheKey(cacheKey) } : {}),
|
|
575
|
-
...(cacheDecision.reason ? { cacheReason: cacheDecision.reason } : {}),
|
|
576
|
-
});
|
|
577
|
-
const traceBase = createTraceBase(safePatchDecision, patchCacheEntry?.key ?? cacheEntry?.key);
|
|
578
|
-
const cachedPatch = patchCacheEntry ? this.#getCached(this.#patchResultCache, patchCacheEntry.key) : null;
|
|
579
|
-
if (
|
|
580
|
-
cachedPatch?.patch &&
|
|
581
|
-
patchCacheEntry &&
|
|
582
|
-
isCachedRscPatchMetadataCompatible({
|
|
583
|
-
cached: cachedPatch.patch,
|
|
584
|
-
targetRouterState,
|
|
585
|
-
safePatchDecision,
|
|
586
|
-
})
|
|
587
|
-
) {
|
|
588
|
-
const cachedPatchDecision = createRscWorkerCachedPatchReplayDecision({
|
|
589
|
-
cached: cachedPatch.patch,
|
|
590
|
-
safePatchDecision,
|
|
591
|
-
});
|
|
592
|
-
const cachedTraceBase = createTraceBase(
|
|
593
|
-
cachedPatchDecision,
|
|
594
|
-
patchCacheEntry.key,
|
|
595
|
-
cachedPatch.patch.targetRouterState,
|
|
596
|
-
);
|
|
597
|
-
await this.#replayCached(requestId, routeId, startedAt, cachedPatch, {
|
|
598
|
-
...cachedTraceBase,
|
|
599
|
-
cache: "hit",
|
|
600
|
-
partial: "patch",
|
|
601
|
-
partialReason: "cache-hit-patch-replay",
|
|
602
|
-
});
|
|
603
|
-
return;
|
|
604
|
-
}
|
|
605
|
-
const cached =
|
|
606
|
-
shouldUseRscWorkerFullResultCache({ cacheEntry, patchCacheEntry }) && cacheEntry
|
|
607
|
-
? this.#getCached(this.#resultCache, cacheEntry.key)
|
|
608
|
-
: null;
|
|
609
|
-
if (cached) {
|
|
610
|
-
await this.#replayCached(requestId, routeId, startedAt, cached, {
|
|
611
|
-
...traceBase,
|
|
612
|
-
cache: "hit",
|
|
613
|
-
partial: "full",
|
|
614
|
-
partialReason: "cache-hit-full-replay",
|
|
615
|
-
partialCommonPrefixLength: 0,
|
|
616
|
-
patchStartIndex: undefined,
|
|
617
|
-
patchSegmentPath: undefined,
|
|
618
|
-
patchStartSegment: undefined,
|
|
619
|
-
patchHeadSafe: undefined,
|
|
620
|
-
patchHeadSnapshot: undefined,
|
|
621
|
-
ssrBlocking: cached.ssrBlocking,
|
|
622
|
-
});
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
let element: ReactNode;
|
|
626
|
-
let effectivePatchDecision = safePatchDecision;
|
|
627
|
-
const notFoundProbe = { hit: false };
|
|
628
|
-
const notFound = this.#notFoundInPlace(urlObj, notFoundProbe);
|
|
629
|
-
const gate = new RouteShellGate();
|
|
630
|
-
if (match && safePatchDecision.status === "patch" && safePatchDecision.patch) {
|
|
631
|
-
const suffixElement = await this.#renderMatchedSuffix(
|
|
632
|
-
urlObj,
|
|
633
|
-
match,
|
|
634
|
-
safePatchDecision.patch.patchStartIndex,
|
|
635
|
-
searchParams,
|
|
636
|
-
notFound,
|
|
637
|
-
{ guarded: admitted },
|
|
638
|
-
);
|
|
639
|
-
if (suffixElement === null) {
|
|
640
|
-
effectivePatchDecision = {
|
|
641
|
-
status: "full",
|
|
642
|
-
reason: "suffix-compose-fallback",
|
|
643
|
-
commonPrefixLength: safePatchDecision.commonPrefixLength,
|
|
644
|
-
};
|
|
645
|
-
element = await this.#renderMatched(urlObj, match, searchParams, notFound, { guarded: true, gate });
|
|
646
|
-
} else element = suffixElement;
|
|
647
|
-
} else if (match)
|
|
648
|
-
element = await this.#renderMatched(urlObj, match, searchParams, notFound, { guarded: admitted, gate });
|
|
649
|
-
else element = await this.#renderNotFound(urlObj, gate);
|
|
650
|
-
const traceCacheKey =
|
|
651
|
-
effectivePatchDecision.status === "patch" ? (patchCacheEntry?.key ?? cacheEntry?.key) : cacheEntry?.key;
|
|
652
|
-
const ssrBlocking = getRequestFrameState<PageState>()?.ssr === "block";
|
|
653
|
-
const trace: RscTraceMetadata = {
|
|
654
|
-
...createTraceBase(effectivePatchDecision, traceCacheKey),
|
|
655
|
-
cache: cacheEntry ? "miss" : "bypass",
|
|
656
|
-
ssrBlocking,
|
|
657
|
-
};
|
|
658
|
-
this.#logger.verbose(`render[${requestId}] starting Flight stream`);
|
|
659
|
-
const result = await this.#renderFlightElement(element, msg.clientManifest ?? this.#clientManifest, {
|
|
660
|
-
requestId,
|
|
661
|
-
collectChunks: shouldCollectRscWorkerRenderChunks({
|
|
662
|
-
cacheEntry,
|
|
663
|
-
effectivePatchDecision,
|
|
664
|
-
patchCacheEntry,
|
|
665
|
-
}),
|
|
666
|
-
status: match ? undefined : 404,
|
|
667
|
-
trace,
|
|
668
|
-
notFoundProbe,
|
|
669
|
-
gate,
|
|
670
|
-
onComplete: ({ chunks, bytes, chunksCount, control, lateControlSent }) => {
|
|
671
|
-
const cacheState = shouldStoreRouteCache({
|
|
672
|
-
policy: getRequestPolicy(),
|
|
673
|
-
dynamicUsage: getRequestDynamicUsage(),
|
|
674
|
-
renderControlType: control?.type,
|
|
675
|
-
lateRedirect: control?.type === "redirect" && lateControlSent,
|
|
676
|
-
});
|
|
677
|
-
const storeTtl = cacheEntry ? resolveRouteCacheStoreTtl(cacheEntry.ttl, cacheState) : null;
|
|
678
|
-
const stored = (): CachedRscResult => ({
|
|
679
|
-
chunks,
|
|
680
|
-
bytes,
|
|
681
|
-
chunksCount,
|
|
682
|
-
pathname: urlObj.pathname,
|
|
683
|
-
routeId,
|
|
684
|
-
tags: cacheState.tags,
|
|
685
|
-
theme: getRequestTheme(),
|
|
686
|
-
ssrBlocking,
|
|
687
|
-
cacheState,
|
|
688
|
-
});
|
|
689
|
-
if (
|
|
690
|
-
shouldStoreRscWorkerPatchResult({
|
|
691
|
-
cacheEntry,
|
|
692
|
-
patchCacheEntry,
|
|
693
|
-
effectivePatchDecision,
|
|
694
|
-
storeTtl,
|
|
695
|
-
}) &&
|
|
696
|
-
patchCacheEntry &&
|
|
697
|
-
targetRouterState &&
|
|
698
|
-
effectivePatchDecision.patch &&
|
|
699
|
-
storeTtl !== null
|
|
700
|
-
) {
|
|
701
|
-
const patch = createCachedRscPatchMetadata({ targetRouterState, patch: effectivePatchDecision.patch });
|
|
702
|
-
this.#store("patch", this.#patchResultCache, patchCacheEntry.key, { ...stored(), patch }, storeTtl);
|
|
703
|
-
} else if (cacheEntry && storeTtl !== null && effectivePatchDecision.status !== "patch") {
|
|
704
|
-
this.#store("full", this.#resultCache, cacheEntry.key, stored(), storeTtl);
|
|
705
|
-
}
|
|
706
|
-
return cacheState;
|
|
707
|
-
},
|
|
708
|
-
});
|
|
709
|
-
if (result.cancelled) return;
|
|
710
|
-
const control = result.control;
|
|
711
|
-
if (control) {
|
|
712
|
-
this.#stats.lastRenderKind = control.type;
|
|
713
|
-
if (result.lateControlSent) {
|
|
714
|
-
this.#logger.verbose(`render[${requestId}] late ${control.type} delivered after stream start`);
|
|
715
|
-
return;
|
|
716
|
-
}
|
|
717
|
-
if (!match && control.type === "error") {
|
|
718
|
-
const systemResult = await this.#renderFlightElement(
|
|
719
|
-
this.#renderSystemNotFound(urlObj),
|
|
720
|
-
msg.clientManifest ?? this.#clientManifest,
|
|
721
|
-
{ requestId, status: 404, trace },
|
|
722
|
-
);
|
|
723
|
-
if (systemResult.cancelled || !systemResult.control) return;
|
|
724
|
-
}
|
|
725
|
-
if (
|
|
726
|
-
match &&
|
|
727
|
-
control.type !== "redirect" &&
|
|
728
|
-
(await this.#trySendFallbackRender({
|
|
729
|
-
requestId,
|
|
730
|
-
kind: control.type,
|
|
731
|
-
route: match.pathRoute,
|
|
732
|
-
params: match.params,
|
|
733
|
-
searchParams,
|
|
734
|
-
pathname: urlObj.pathname,
|
|
735
|
-
url: urlObj,
|
|
736
|
-
error: control.type === "error" ? control.error : undefined,
|
|
737
|
-
clientManifest: msg.clientManifest ?? this.#clientManifest,
|
|
738
|
-
trace,
|
|
739
|
-
}))
|
|
740
|
-
) {
|
|
741
|
-
return;
|
|
742
|
-
}
|
|
743
|
-
if (
|
|
744
|
-
control.type === "not-found" &&
|
|
745
|
-
(await this.#trySendSystemNotFoundRender({
|
|
746
|
-
requestId,
|
|
747
|
-
url: urlObj,
|
|
748
|
-
clientManifest: msg.clientManifest ?? this.#clientManifest,
|
|
749
|
-
trace,
|
|
750
|
-
}))
|
|
751
|
-
) {
|
|
752
|
-
return;
|
|
753
|
-
}
|
|
754
|
-
this.#sendRenderControl(requestId, control);
|
|
755
|
-
return;
|
|
756
|
-
}
|
|
757
|
-
this.#recordFlight(result);
|
|
758
|
-
this.#stats.lastRenderDurationMs = Date.now() - startedAt;
|
|
759
|
-
const afterLoadedKeys = RouteTreeBuilder.getCacheStats().loadedModuleKeys;
|
|
760
|
-
this.#stats.lastRenderLoadedModules = afterLoadedKeys.filter((key) => !beforeLoadedKeys.includes(key));
|
|
761
|
-
this.#stats.lastRenderLoadedModuleDelta = this.#stats.lastRenderLoadedModules.length;
|
|
762
|
-
this.#recordRouteStats(routeId, result.bytes, this.#stats.lastRenderDurationMs);
|
|
763
|
-
this.#logger.verbose(
|
|
764
|
-
`render[${requestId}] done chunks=${result.chunksCount} bytes=${result.bytes} theme=${getRequestTheme() ?? "(none)"} in ${
|
|
765
|
-
Date.now() - startedAt
|
|
766
|
-
}ms`,
|
|
767
|
-
);
|
|
768
|
-
});
|
|
769
|
-
} catch (error) {
|
|
770
|
-
if (isAkanRedirectError(error)) {
|
|
771
|
-
this.#stats.lastRenderKind = "redirect";
|
|
772
|
-
this.#logger.verbose(`render[${requestId}] redirect ${error.location}`);
|
|
773
|
-
this.#send({
|
|
774
|
-
type: "redirect",
|
|
775
|
-
requestId,
|
|
776
|
-
location: error.location,
|
|
777
|
-
method: error.method,
|
|
778
|
-
status: error.status,
|
|
779
|
-
});
|
|
780
|
-
return;
|
|
781
|
-
}
|
|
782
|
-
const { url: fallbackUrl, match: fallbackMatch, request: fallbackRequest } = activeRoute;
|
|
783
|
-
|
|
784
|
-
const inRequestScope = (send: () => Promise<boolean>) =>
|
|
785
|
-
fallbackRequest ? this.#runInRequestScope(fallbackRequest, send) : send();
|
|
786
|
-
const trySendFallback = async (kind: "not-found" | "error") =>
|
|
787
|
-
!!fallbackUrl &&
|
|
788
|
-
!!fallbackMatch &&
|
|
789
|
-
(await inRequestScope(() =>
|
|
790
|
-
this.#trySendFallbackRender({
|
|
791
|
-
requestId,
|
|
792
|
-
kind,
|
|
793
|
-
route: RouteElementComposer.fallbackRouteOf(fallbackMatch.pathRoute, error),
|
|
794
|
-
params: fallbackMatch.params,
|
|
795
|
-
searchParams: parseSearchParams(fallbackUrl.search),
|
|
796
|
-
pathname: fallbackUrl.pathname,
|
|
797
|
-
url: fallbackUrl,
|
|
798
|
-
error: kind === "error" ? error : undefined,
|
|
799
|
-
clientManifest: msg.clientManifest ?? this.#clientManifest,
|
|
800
|
-
}),
|
|
801
|
-
));
|
|
802
|
-
if (isAkanNotFoundError(error)) {
|
|
803
|
-
this.#stats.lastRenderKind = "not-found";
|
|
804
|
-
this.#logger.verbose(`render[${requestId}] not-found`);
|
|
805
|
-
if (await trySendFallback("not-found")) return;
|
|
806
|
-
if (
|
|
807
|
-
fallbackUrl &&
|
|
808
|
-
(await inRequestScope(() =>
|
|
809
|
-
this.#trySendSystemNotFoundRender({
|
|
810
|
-
requestId,
|
|
811
|
-
url: fallbackUrl,
|
|
812
|
-
clientManifest: msg.clientManifest ?? this.#clientManifest,
|
|
813
|
-
}),
|
|
814
|
-
))
|
|
815
|
-
) {
|
|
816
|
-
return;
|
|
817
|
-
}
|
|
818
|
-
this.#send({ type: "not-found", requestId });
|
|
819
|
-
return;
|
|
820
|
-
}
|
|
821
|
-
this.#logger.error(
|
|
822
|
-
`render[${requestId}] failed url=${url}: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
|
|
823
|
-
);
|
|
824
|
-
if (await trySendFallback("error")) return;
|
|
825
|
-
this.#send({
|
|
826
|
-
type: "error",
|
|
827
|
-
requestId,
|
|
828
|
-
message: error instanceof Error ? error.message : String(error),
|
|
829
|
-
});
|
|
830
|
-
} finally {
|
|
831
|
-
this.#activeRenderReaders.delete(requestId);
|
|
832
|
-
this.#cancelledRenderRequests.delete(requestId);
|
|
833
|
-
this.#stats.inFlightRenderCount = Math.max(0, this.#stats.inFlightRenderCount - 1);
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
|
|
837
352
|
async #sendMetricsReport() {
|
|
838
353
|
const routeStats = RouteTreeBuilder.getCacheStats();
|
|
839
354
|
const metrics = await ProcessMetricsCollector.collect({
|
|
840
355
|
role: "rsc-worker",
|
|
841
356
|
rscRenderCount: this.#stats.renderCount,
|
|
842
|
-
rscInFlightRenderCount: this.#
|
|
357
|
+
rscInFlightRenderCount: this.#flights.inFlightCount,
|
|
843
358
|
rscLastRenderedPath: this.#stats.lastRenderedPath,
|
|
844
359
|
rscLastRenderKind: this.#stats.lastRenderKind,
|
|
845
360
|
rscLastRenderRouteId: this.#stats.lastRenderRouteId,
|
|
@@ -857,449 +372,19 @@ export class RscRenderer {
|
|
|
857
372
|
rscRouteModuleCacheMisses: routeStats.cacheMisses,
|
|
858
373
|
rscRouteModuleCacheDisabled: routeStats.cacheDisabled,
|
|
859
374
|
rscLoadedRouteModuleKeys: routeStats.loadedModuleKeys,
|
|
860
|
-
rscTopRoutesByRenderCount: this.#topRoutes((route) => route.count),
|
|
861
|
-
rscTopRoutesByFlightBytes: this.#topRoutes((route) => route.flightBytes),
|
|
862
|
-
rscResultCacheEntries: this.#resultCache.size,
|
|
863
|
-
rscResultCacheBytes: this.#resultCache.byteSize,
|
|
864
|
-
rscPatchResultCacheEntries: this.#patchResultCache.size,
|
|
865
|
-
rscPatchResultCacheBytes: this.#patchResultCache.byteSize,
|
|
866
|
-
rscResultCacheHits: this.#resultCacheHits,
|
|
867
|
-
rscResultCacheMisses: this.#resultCacheMisses,
|
|
868
|
-
rscResultCacheBypass: this.#resultCacheBypass,
|
|
375
|
+
rscTopRoutesByRenderCount: this.#stats.topRoutes((route) => route.count),
|
|
376
|
+
rscTopRoutesByFlightBytes: this.#stats.topRoutes((route) => route.flightBytes),
|
|
377
|
+
rscResultCacheEntries: this.#caches.resultCache.size,
|
|
378
|
+
rscResultCacheBytes: this.#caches.resultCache.byteSize,
|
|
379
|
+
rscPatchResultCacheEntries: this.#caches.patchResultCache.size,
|
|
380
|
+
rscPatchResultCacheBytes: this.#caches.patchResultCache.byteSize,
|
|
381
|
+
rscResultCacheHits: this.#caches.resultCacheHits,
|
|
382
|
+
rscResultCacheMisses: this.#caches.resultCacheMisses,
|
|
383
|
+
rscResultCacheBypass: this.#caches.resultCacheBypass,
|
|
869
384
|
});
|
|
870
385
|
this.#send({ type: "metrics", metrics });
|
|
871
386
|
}
|
|
872
387
|
|
|
873
|
-
#reportRenderError(error: unknown, pathname?: string): string {
|
|
874
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
875
|
-
const description = error instanceof Error ? (error.stack ?? message) : message;
|
|
876
|
-
const opaque = process.env.NODE_ENV === "production";
|
|
877
|
-
const digest = opaque ? crypto.randomUUID().slice(0, 8) : message;
|
|
878
|
-
const scope = `${pathname ? ` path=${pathname}` : ""}${opaque ? ` digest=${digest}` : ""}`;
|
|
879
|
-
if (RscRenderer.#isExpectedRequestAbort(error)) this.#logger.debug(`[rsc] render aborted${scope}: ${description}`);
|
|
880
|
-
else this.#logger.error(`[rsc] render failed${scope}: ${description}`);
|
|
881
|
-
return digest;
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
static #isExpectedRequestAbort(error: unknown): boolean {
|
|
885
|
-
if (!(error instanceof Error)) return false;
|
|
886
|
-
return (
|
|
887
|
-
error.name === "AbortError" ||
|
|
888
|
-
error.message === "Connection closed." ||
|
|
889
|
-
error.message.includes("The connection was closed")
|
|
890
|
-
);
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
async #renderFlightElement(
|
|
894
|
-
element: ReactNode,
|
|
895
|
-
clientManifest: ClientManifest,
|
|
896
|
-
options: {
|
|
897
|
-
requestId?: string;
|
|
898
|
-
collectChunks?: boolean;
|
|
899
|
-
status?: number;
|
|
900
|
-
trace?: RscTraceMetadata;
|
|
901
|
-
/** Raised by a render that answered `router.notFound()` in place, which React never reports as an error. */
|
|
902
|
-
notFoundProbe?: { hit: boolean };
|
|
903
|
-
gate?: RouteShellGate;
|
|
904
|
-
onComplete?: (
|
|
905
|
-
result: Omit<FlightRenderResult, "cancelled">,
|
|
906
|
-
) => Promise<RouteCacheRenderState> | RouteCacheRenderState;
|
|
907
|
-
} = {},
|
|
908
|
-
): Promise<FlightRenderResult> {
|
|
909
|
-
const controlRef: { current: RenderControl | null } = { current: null };
|
|
910
|
-
|
|
911
|
-
let isCancelling = false;
|
|
912
|
-
const stream = await renderToReadableStream(element, clientManifest, {
|
|
913
|
-
onError: (error) => {
|
|
914
|
-
if (isCancelling || (options.requestId && this.#cancelledRenderRequests.has(options.requestId))) return;
|
|
915
|
-
if (isAkanRedirectError(error)) {
|
|
916
|
-
const { location, method, status } = error;
|
|
917
|
-
controlRef.current = { type: "redirect", location, method, status };
|
|
918
|
-
return encodeAkanRedirectDigest({ location, method, status });
|
|
919
|
-
}
|
|
920
|
-
if (isAkanNotFoundError(error)) {
|
|
921
|
-
controlRef.current = { type: "not-found" };
|
|
922
|
-
return error.digest;
|
|
923
|
-
}
|
|
924
|
-
controlRef.current = { type: "error", error };
|
|
925
|
-
return this.#reportRenderError(error, options.trace?.pathname);
|
|
926
|
-
},
|
|
927
|
-
});
|
|
928
|
-
const reader = stream.getReader();
|
|
929
|
-
if (options.requestId) this.#activeRenderReaders.set(options.requestId, reader);
|
|
930
|
-
let bytes = 0;
|
|
931
|
-
let chunksCount = 0;
|
|
932
|
-
let sentMeta = false;
|
|
933
|
-
let sentChunk = false;
|
|
934
|
-
let lateControlSent = false;
|
|
935
|
-
const chunks: Uint8Array[] = [];
|
|
936
|
-
|
|
937
|
-
let holding = options.gate?.holding ? options.gate : null;
|
|
938
|
-
let held: Uint8Array | null = null;
|
|
939
|
-
let reportedTheme: AkanTheme | undefined;
|
|
940
|
-
const sendMeta = () => {
|
|
941
|
-
if (!options.requestId || sentMeta) return;
|
|
942
|
-
sentMeta = true;
|
|
943
|
-
if (options.status !== undefined) {
|
|
944
|
-
const trace = getCurrentTrace();
|
|
945
|
-
if (trace) trace.status = options.status;
|
|
946
|
-
}
|
|
947
|
-
reportedTheme = getRequestTheme();
|
|
948
|
-
this.#send({
|
|
949
|
-
type: "meta",
|
|
950
|
-
requestId: options.requestId,
|
|
951
|
-
theme: reportedTheme,
|
|
952
|
-
status: options.status,
|
|
953
|
-
trace: options.trace,
|
|
954
|
-
});
|
|
955
|
-
};
|
|
956
|
-
|
|
957
|
-
const sendLateTheme = () => {
|
|
958
|
-
const theme = getRequestTheme();
|
|
959
|
-
if (!options.requestId || !sentMeta || theme === reportedTheme) return;
|
|
960
|
-
reportedTheme = theme;
|
|
961
|
-
this.#send({ type: "theme", requestId: options.requestId, theme });
|
|
962
|
-
};
|
|
963
|
-
const cancelWith = async (control: RenderControl | null, cancelled: boolean): Promise<FlightRenderResult> => {
|
|
964
|
-
isCancelling = true;
|
|
965
|
-
await reader.cancel();
|
|
966
|
-
return { chunks, bytes, chunksCount, control, lateControlSent, cancelled };
|
|
967
|
-
};
|
|
968
|
-
const readProbe = () => {
|
|
969
|
-
if (!controlRef.current && options.notFoundProbe?.hit) controlRef.current = { type: "not-found" };
|
|
970
|
-
};
|
|
971
|
-
const emit = (chunk: Uint8Array) => {
|
|
972
|
-
if (options.collectChunks) chunks.push(chunk);
|
|
973
|
-
if (!options.requestId) return;
|
|
974
|
-
sendMeta();
|
|
975
|
-
sendLateTheme();
|
|
976
|
-
this.#send({ type: "chunk", requestId: options.requestId, data: chunk });
|
|
977
|
-
sentChunk = true;
|
|
978
|
-
};
|
|
979
|
-
const releaseHeld = () => {
|
|
980
|
-
holding = null;
|
|
981
|
-
if (!held) return;
|
|
982
|
-
if (controlRef.current) {
|
|
983
|
-
sendMeta();
|
|
984
|
-
sendLateControl();
|
|
985
|
-
}
|
|
986
|
-
emit(held);
|
|
987
|
-
held = null;
|
|
988
|
-
};
|
|
989
|
-
|
|
990
|
-
const sendLateControl = () => {
|
|
991
|
-
const control = controlRef.current;
|
|
992
|
-
if (!options.requestId || lateControlSent || !control || control.type === "error") return;
|
|
993
|
-
lateControlSent = true;
|
|
994
|
-
if (control.type === "redirect") {
|
|
995
|
-
this.#send({
|
|
996
|
-
type: "late-redirect",
|
|
997
|
-
requestId: options.requestId,
|
|
998
|
-
location: control.location,
|
|
999
|
-
method: control.method,
|
|
1000
|
-
status: control.status,
|
|
1001
|
-
});
|
|
1002
|
-
return;
|
|
1003
|
-
}
|
|
1004
|
-
if (!options.notFoundProbe?.hit)
|
|
1005
|
-
this.#logger.warn(
|
|
1006
|
-
`render[${options.requestId}] not-found raised below a route render after the stream started; that subtree renders nothing — call router.notFound() from the page or layout body`,
|
|
1007
|
-
);
|
|
1008
|
-
this.#send({ type: "late-not-found", requestId: options.requestId });
|
|
1009
|
-
};
|
|
1010
|
-
try {
|
|
1011
|
-
let pendingRead: ReturnType<typeof reader.read> | null = null;
|
|
1012
|
-
for (;;) {
|
|
1013
|
-
if (options.requestId && this.#cancelledRenderRequests.has(options.requestId))
|
|
1014
|
-
return await cancelWith(null, true);
|
|
1015
|
-
pendingRead ??= reader.read();
|
|
1016
|
-
if (holding && (await Promise.race([pendingRead.then(() => false), holding.opened.then(() => true)]))) {
|
|
1017
|
-
readProbe();
|
|
1018
|
-
if (controlRef.current?.type === "error") return await cancelWith(controlRef.current, false);
|
|
1019
|
-
releaseHeld();
|
|
1020
|
-
continue;
|
|
1021
|
-
}
|
|
1022
|
-
const { value, done } = await pendingRead;
|
|
1023
|
-
pendingRead = null;
|
|
1024
|
-
readProbe();
|
|
1025
|
-
if (controlRef.current && !sentChunk && (!holding || controlRef.current.type === "error"))
|
|
1026
|
-
return await cancelWith(controlRef.current, false);
|
|
1027
|
-
if (controlRef.current && sentChunk) sendLateControl();
|
|
1028
|
-
if (done) break;
|
|
1029
|
-
|
|
1030
|
-
if (chunksCount === 0 && options.requestId) {
|
|
1031
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1032
|
-
readProbe();
|
|
1033
|
-
if (controlRef.current) return await cancelWith(controlRef.current, false);
|
|
1034
|
-
}
|
|
1035
|
-
const chunk = value instanceof Uint8Array ? value : new Uint8Array(value as ArrayBufferLike);
|
|
1036
|
-
bytes += chunk.byteLength;
|
|
1037
|
-
chunksCount += 1;
|
|
1038
|
-
if (holding) held = held ? concatBytes(held, chunk) : chunk;
|
|
1039
|
-
else emit(chunk);
|
|
1040
|
-
}
|
|
1041
|
-
} catch (error) {
|
|
1042
|
-
if (options.requestId && this.#cancelledRenderRequests.has(options.requestId)) {
|
|
1043
|
-
return { chunks, bytes, chunksCount, control: null, lateControlSent, cancelled: true };
|
|
1044
|
-
}
|
|
1045
|
-
throw error;
|
|
1046
|
-
} finally {
|
|
1047
|
-
if (options.requestId) this.#activeRenderReaders.delete(options.requestId);
|
|
1048
|
-
reader.releaseLock();
|
|
1049
|
-
}
|
|
1050
|
-
readProbe();
|
|
1051
|
-
if (holding && controlRef.current?.type !== "error") releaseHeld();
|
|
1052
|
-
if (controlRef.current && sentChunk) sendLateControl();
|
|
1053
|
-
if (controlRef.current && !sentChunk)
|
|
1054
|
-
return { chunks, bytes, chunksCount, control: controlRef.current, lateControlSent, cancelled: false };
|
|
1055
|
-
if (options.requestId) {
|
|
1056
|
-
sendMeta();
|
|
1057
|
-
const cacheState = (await options.onComplete?.({
|
|
1058
|
-
chunks,
|
|
1059
|
-
bytes,
|
|
1060
|
-
chunksCount,
|
|
1061
|
-
control: controlRef.current,
|
|
1062
|
-
lateControlSent,
|
|
1063
|
-
})) ?? { cacheable: false, reason: "uncacheable-render" };
|
|
1064
|
-
this.#send({ type: "cache-state", requestId: options.requestId, state: cacheState });
|
|
1065
|
-
this.#send({ type: "end", requestId: options.requestId });
|
|
1066
|
-
}
|
|
1067
|
-
return {
|
|
1068
|
-
chunks,
|
|
1069
|
-
bytes,
|
|
1070
|
-
chunksCount,
|
|
1071
|
-
control: lateControlSent ? controlRef.current : null,
|
|
1072
|
-
lateControlSent,
|
|
1073
|
-
cancelled: false,
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
async #trySendFallbackRender({
|
|
1078
|
-
requestId,
|
|
1079
|
-
kind,
|
|
1080
|
-
route,
|
|
1081
|
-
params,
|
|
1082
|
-
searchParams,
|
|
1083
|
-
pathname,
|
|
1084
|
-
url,
|
|
1085
|
-
error,
|
|
1086
|
-
clientManifest,
|
|
1087
|
-
trace,
|
|
1088
|
-
}: {
|
|
1089
|
-
requestId: string;
|
|
1090
|
-
kind: "not-found" | "error";
|
|
1091
|
-
route: PathRoute | LayoutFallbackRoute;
|
|
1092
|
-
params: Record<string, string>;
|
|
1093
|
-
searchParams: Record<string, string | string[]>;
|
|
1094
|
-
pathname: string;
|
|
1095
|
-
url: URL;
|
|
1096
|
-
error?: unknown;
|
|
1097
|
-
clientManifest: ClientManifest;
|
|
1098
|
-
trace?: RscTraceMetadata;
|
|
1099
|
-
}): Promise<boolean> {
|
|
1100
|
-
try {
|
|
1101
|
-
const gate = new RouteShellGate();
|
|
1102
|
-
const element = await this.#renderFallbackDocument({
|
|
1103
|
-
kind,
|
|
1104
|
-
route,
|
|
1105
|
-
params,
|
|
1106
|
-
searchParams,
|
|
1107
|
-
pathname,
|
|
1108
|
-
url,
|
|
1109
|
-
error: kind === "error" && process.env.NODE_ENV !== "production" ? error : undefined,
|
|
1110
|
-
digest: kind === "error" ? "AKAN_RENDER_ERROR" : undefined,
|
|
1111
|
-
gate,
|
|
1112
|
-
});
|
|
1113
|
-
if (!element) return false;
|
|
1114
|
-
return await this.#trySendFlight(
|
|
1115
|
-
requestId,
|
|
1116
|
-
element,
|
|
1117
|
-
clientManifest,
|
|
1118
|
-
kind === "not-found" ? 404 : 500,
|
|
1119
|
-
trace,
|
|
1120
|
-
gate,
|
|
1121
|
-
);
|
|
1122
|
-
} catch (fallbackError) {
|
|
1123
|
-
this.#logger.error(
|
|
1124
|
-
`render[${requestId}] custom ${kind} fallback failed: ${
|
|
1125
|
-
fallbackError instanceof Error ? (fallbackError.stack ?? fallbackError.message) : String(fallbackError)
|
|
1126
|
-
}`,
|
|
1127
|
-
);
|
|
1128
|
-
return false;
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
async #trySendSystemNotFoundRender({
|
|
1133
|
-
requestId,
|
|
1134
|
-
url,
|
|
1135
|
-
clientManifest,
|
|
1136
|
-
trace,
|
|
1137
|
-
}: {
|
|
1138
|
-
requestId: string;
|
|
1139
|
-
url: URL;
|
|
1140
|
-
clientManifest: ClientManifest;
|
|
1141
|
-
trace?: RscTraceMetadata;
|
|
1142
|
-
}): Promise<boolean> {
|
|
1143
|
-
try {
|
|
1144
|
-
return await this.#trySendFlight(requestId, this.#renderSystemNotFound(url), clientManifest, 404, trace);
|
|
1145
|
-
} catch (error) {
|
|
1146
|
-
this.#logger.error(
|
|
1147
|
-
`render[${requestId}] system not-found fallback failed: ${
|
|
1148
|
-
error instanceof Error ? (error.stack ?? error.message) : String(error)
|
|
1149
|
-
}`,
|
|
1150
|
-
);
|
|
1151
|
-
return false;
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
async #trySendFlight(
|
|
1156
|
-
requestId: string,
|
|
1157
|
-
element: ReactNode,
|
|
1158
|
-
clientManifest: ClientManifest,
|
|
1159
|
-
status: number,
|
|
1160
|
-
trace?: RscTraceMetadata,
|
|
1161
|
-
gate?: RouteShellGate,
|
|
1162
|
-
): Promise<boolean> {
|
|
1163
|
-
const result = await this.#renderFlightElement(element, clientManifest, { requestId, status, trace, gate });
|
|
1164
|
-
if (result.cancelled) return true;
|
|
1165
|
-
if (result.control) return false;
|
|
1166
|
-
this.#recordFlight(result);
|
|
1167
|
-
return true;
|
|
1168
|
-
}
|
|
1169
|
-
|
|
1170
|
-
async #replayCached(
|
|
1171
|
-
requestId: string,
|
|
1172
|
-
routeId: string,
|
|
1173
|
-
startedAt: number,
|
|
1174
|
-
cached: CachedRscResult,
|
|
1175
|
-
trace: RscTraceMetadata,
|
|
1176
|
-
): Promise<void> {
|
|
1177
|
-
this.#stats.lastRenderDurationMs = Date.now() - startedAt;
|
|
1178
|
-
this.#stats.lastRenderLoadedModuleDelta = 0;
|
|
1179
|
-
this.#stats.lastRenderLoadedModules = [];
|
|
1180
|
-
this.#recordFlight(cached);
|
|
1181
|
-
this.#recordRouteStats(routeId, cached.bytes, this.#stats.lastRenderDurationMs);
|
|
1182
|
-
await replayCachedRscResult({
|
|
1183
|
-
requestId,
|
|
1184
|
-
chunks: cached.chunks,
|
|
1185
|
-
theme: cached.theme,
|
|
1186
|
-
cacheState: cached.cacheState,
|
|
1187
|
-
trace,
|
|
1188
|
-
send: (message) => this.#send(message),
|
|
1189
|
-
isCancelled: () => this.#cancelledRenderRequests.has(requestId),
|
|
1190
|
-
});
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
#recordFlight({ bytes, chunksCount }: { bytes: number; chunksCount: number }): void {
|
|
1194
|
-
this.#stats.lastFlightBytes = bytes;
|
|
1195
|
-
this.#stats.lastFlightChunks = chunksCount;
|
|
1196
|
-
this.#stats.totalFlightBytes += bytes;
|
|
1197
|
-
this.#stats.totalFlightChunks += chunksCount;
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
#sendRenderControl(requestId: string, control: RenderControl): void {
|
|
1201
|
-
if (control.type === "redirect") {
|
|
1202
|
-
this.#logger.verbose(`render[${requestId}] redirect ${control.location}`);
|
|
1203
|
-
this.#send({
|
|
1204
|
-
type: "redirect",
|
|
1205
|
-
requestId,
|
|
1206
|
-
location: control.location,
|
|
1207
|
-
method: control.method,
|
|
1208
|
-
status: control.status,
|
|
1209
|
-
});
|
|
1210
|
-
return;
|
|
1211
|
-
}
|
|
1212
|
-
if (control.type === "error") {
|
|
1213
|
-
const message = control.error instanceof Error ? control.error.message : String(control.error);
|
|
1214
|
-
this.#logger.verbose(`render[${requestId}] error`);
|
|
1215
|
-
this.#send({ type: "error", requestId, message });
|
|
1216
|
-
return;
|
|
1217
|
-
}
|
|
1218
|
-
this.#logger.verbose(`render[${requestId}] not-found`);
|
|
1219
|
-
this.#send({ type: "not-found", requestId });
|
|
1220
|
-
}
|
|
1221
|
-
|
|
1222
|
-
async #resolveHeadSafePatchDecision(
|
|
1223
|
-
pathRoute: PathRoute,
|
|
1224
|
-
patchDecision: AkanRscPatchDecision,
|
|
1225
|
-
resolveHeadSnapshot: () => Promise<ResolvedHead["headSnapshot"]>,
|
|
1226
|
-
): Promise<AkanRscPatchDecision> {
|
|
1227
|
-
if (patchDecision.status !== "patch" || !patchDecision.patch) {
|
|
1228
|
-
return patchDecision;
|
|
1229
|
-
}
|
|
1230
|
-
if (!isAkanRscPartialCommitEnabled()) {
|
|
1231
|
-
return { status: "full", reason: "guard-disabled", commonPrefixLength: patchDecision.commonPrefixLength };
|
|
1232
|
-
}
|
|
1233
|
-
const pageConfig = await pathRoute.renderPage.getPageConfig?.();
|
|
1234
|
-
return resolveAkanRscHeadSafePatchDecision({
|
|
1235
|
-
partialCommitEnabled: true,
|
|
1236
|
-
patchDecision,
|
|
1237
|
-
pageConfig,
|
|
1238
|
-
headSnapshot: pageConfig?.rscPatchHeadSafe === true ? await resolveHeadSnapshot() : undefined,
|
|
1239
|
-
});
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
#recordRouteStats(routeId: string, flightBytes: number, durationMs: number): void {
|
|
1243
|
-
const current = this.#routeStats.get(routeId) ?? { routeId, count: 0, flightBytes: 0, totalDurationMs: 0 };
|
|
1244
|
-
current.count += 1;
|
|
1245
|
-
current.flightBytes += flightBytes;
|
|
1246
|
-
current.totalDurationMs += durationMs;
|
|
1247
|
-
this.#routeStats.set(routeId, current);
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
#topRoutes(sortBy: (route: RouteRenderStats) => number) {
|
|
1251
|
-
return [...this.#routeStats.values()]
|
|
1252
|
-
.sort((a, b) => sortBy(b) - sortBy(a))
|
|
1253
|
-
.slice(0, 10)
|
|
1254
|
-
.map((route) => ({
|
|
1255
|
-
routeId: route.routeId,
|
|
1256
|
-
count: route.count,
|
|
1257
|
-
flightBytes: route.flightBytes,
|
|
1258
|
-
avgDurationMs: route.count > 0 ? Math.round(route.totalDurationMs / route.count) : 0,
|
|
1259
|
-
}));
|
|
1260
|
-
}
|
|
1261
|
-
|
|
1262
|
-
#getResultCacheEntry(request: Request, url: URL): { entry: RouteCacheEntry | null; reason?: string } {
|
|
1263
|
-
const decision = resolvePublicRouteCacheEntryDecision({
|
|
1264
|
-
request,
|
|
1265
|
-
url,
|
|
1266
|
-
theme: untrackedCookies().get("theme")?.value,
|
|
1267
|
-
defaultEnabled: process.env.NODE_ENV === "production",
|
|
1268
|
-
defaultAllow: process.env.NODE_ENV === "production",
|
|
1269
|
-
env: {
|
|
1270
|
-
enabled: process.env.AKAN_RSC_RESULT_CACHE,
|
|
1271
|
-
ttl: process.env.AKAN_RSC_RESULT_CACHE_TTL,
|
|
1272
|
-
allow: process.env.AKAN_RSC_RESULT_CACHE_PATHS,
|
|
1273
|
-
deny: process.env.AKAN_RSC_RESULT_CACHE_EXCLUDE_PATHS,
|
|
1274
|
-
},
|
|
1275
|
-
});
|
|
1276
|
-
if (!decision.entry) this.#resultCacheBypass += 1;
|
|
1277
|
-
return decision;
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
static #resultCacheOptions(): LruTtlCacheOptions<CachedRscResult> {
|
|
1281
|
-
return {
|
|
1282
|
-
sizeOf: (result) => result.bytes,
|
|
1283
|
-
maxBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_RSC_RESULT_CACHE_MAX_BYTES),
|
|
1284
|
-
maxEntryBytes: LruTtlCache.parseByteCeiling(process.env.AKAN_RSC_RESULT_CACHE_MAX_BODY_BYTES),
|
|
1285
|
-
sweepIntervalMs: RESULT_CACHE_SWEEP_INTERVAL_MS,
|
|
1286
|
-
};
|
|
1287
|
-
}
|
|
1288
|
-
|
|
1289
|
-
#getCached(cache: LruTtlCache<CachedRscResult>, cacheKey: string): CachedRscResult | null {
|
|
1290
|
-
const cached = cache.get(cacheKey);
|
|
1291
|
-
if (cached) this.#resultCacheHits += 1;
|
|
1292
|
-
else this.#resultCacheMisses += 1;
|
|
1293
|
-
return cached;
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
#store(kind: string, cache: LruTtlCache<CachedRscResult>, cacheKey: string, result: CachedRscResult, ttl: number) {
|
|
1297
|
-
if (cache.set(cacheKey, result, ttl)) return;
|
|
1298
|
-
this.#logger.verbose(
|
|
1299
|
-
`${kind} result cache store skipped pathname=${result.pathname} bytes=${result.bytes} reason=body-too-large`,
|
|
1300
|
-
);
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
388
|
#runWithRequest<T>(request: Request, routeId: string, fn: () => Promise<T>): Promise<T> {
|
|
1304
389
|
return this.#runInRequestScope(request, () => runTraced(SignalTrace.create(routeId, "page", "page"), fn));
|
|
1305
390
|
}
|
|
@@ -1308,397 +393,6 @@ export class RscRenderer {
|
|
|
1308
393
|
const render = () => RenderScope.run(fn);
|
|
1309
394
|
return requestStorage ? requestStorage.run(request, render) : render();
|
|
1310
395
|
}
|
|
1311
|
-
|
|
1312
|
-
async #renderFallbackDocument({
|
|
1313
|
-
kind,
|
|
1314
|
-
route,
|
|
1315
|
-
params,
|
|
1316
|
-
searchParams,
|
|
1317
|
-
pathname,
|
|
1318
|
-
url,
|
|
1319
|
-
error,
|
|
1320
|
-
digest,
|
|
1321
|
-
gate,
|
|
1322
|
-
}: {
|
|
1323
|
-
kind: "not-found" | "error";
|
|
1324
|
-
route: PathRoute | LayoutFallbackRoute;
|
|
1325
|
-
params: Record<string, string>;
|
|
1326
|
-
searchParams: Record<string, string | string[]>;
|
|
1327
|
-
pathname: string;
|
|
1328
|
-
url: URL;
|
|
1329
|
-
error?: unknown;
|
|
1330
|
-
digest?: string;
|
|
1331
|
-
gate?: RouteShellGate;
|
|
1332
|
-
}): Promise<ReactNode | null> {
|
|
1333
|
-
setRequestFrameState(
|
|
1334
|
-
await RouteElementComposer.resolveSsrFallbackFrameState({
|
|
1335
|
-
route,
|
|
1336
|
-
basePath: this.#getBasePath(url),
|
|
1337
|
-
}),
|
|
1338
|
-
);
|
|
1339
|
-
const fallbackHead = new FallbackHead();
|
|
1340
|
-
const body = await RouteElementComposer.composeFallback({
|
|
1341
|
-
kind,
|
|
1342
|
-
route,
|
|
1343
|
-
params,
|
|
1344
|
-
searchParams,
|
|
1345
|
-
pathname,
|
|
1346
|
-
error,
|
|
1347
|
-
digest,
|
|
1348
|
-
gate,
|
|
1349
|
-
head: fallbackHead,
|
|
1350
|
-
});
|
|
1351
|
-
if (!body) return null;
|
|
1352
|
-
const viewport = await RscRenderer.#firstRootValue(route.renderRootLayouts, (render) =>
|
|
1353
|
-
render.getLayoutViewport?.(),
|
|
1354
|
-
);
|
|
1355
|
-
const manifestLink = await this.#renderManifestLink(url, route.renderRootLayouts);
|
|
1356
|
-
const routeHead = await RscRenderer.#resolveFallbackHead({ kind, route, params, searchParams });
|
|
1357
|
-
return (
|
|
1358
|
-
<html lang={params.lang ?? getPathnameLocale(pathname, this.#i18n)} suppressHydrationWarning>
|
|
1359
|
-
<head key="head">
|
|
1360
|
-
<meta key="charset" charSet="utf-8" />
|
|
1361
|
-
{this.#renderViewport(viewport)}
|
|
1362
|
-
<FallbackHead.Settled
|
|
1363
|
-
key="route-head"
|
|
1364
|
-
head={fallbackHead}
|
|
1365
|
-
until={gate?.opened ?? Promise.resolve()}
|
|
1366
|
-
render={(tags) => this.#renderHeadTags(url, { manifestLink, routeHead, noindex: true, tags })}
|
|
1367
|
-
/>
|
|
1368
|
-
{this.#renderStylesheet(pathname)}
|
|
1369
|
-
</head>
|
|
1370
|
-
<body key="body">
|
|
1371
|
-
{body}
|
|
1372
|
-
{gate?.holding ? <RouteShellGate.Wait until={gate.opened} /> : null}
|
|
1373
|
-
</body>
|
|
1374
|
-
</html>
|
|
1375
|
-
);
|
|
1376
|
-
}
|
|
1377
|
-
|
|
1378
|
-
static async #resolveFallbackHead({
|
|
1379
|
-
kind,
|
|
1380
|
-
route,
|
|
1381
|
-
params,
|
|
1382
|
-
searchParams,
|
|
1383
|
-
}: {
|
|
1384
|
-
kind: "not-found" | "error";
|
|
1385
|
-
route: PathRoute | LayoutFallbackRoute;
|
|
1386
|
-
params: Record<string, string>;
|
|
1387
|
-
searchParams: Record<string, string | string[]>;
|
|
1388
|
-
}): Promise<ResolvedHead> {
|
|
1389
|
-
if (!("resolveHead" in route)) return { node: undefined };
|
|
1390
|
-
if (kind === "error")
|
|
1391
|
-
return await RouteElementComposer.resolveHeadWithSnapshot({ pathRoute: route, params, searchParams });
|
|
1392
|
-
const levels = await Promise.all(
|
|
1393
|
-
[...route.renderRootLayouts, ...route.renderLayouts].map(async (render) => {
|
|
1394
|
-
try {
|
|
1395
|
-
return await render.resolveHead?.({ params, searchParams });
|
|
1396
|
-
} catch (error) {
|
|
1397
|
-
if (isAkanNotFoundError(error)) return undefined;
|
|
1398
|
-
throw error;
|
|
1399
|
-
}
|
|
1400
|
-
}),
|
|
1401
|
-
);
|
|
1402
|
-
return resolveHeadResult(RouteHead.mergePage(RouteHead.merge(levels), undefined));
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
async #renderMatched(
|
|
1406
|
-
url: URL,
|
|
1407
|
-
match: { pathRoute: PathRoute; params: Record<string, string> },
|
|
1408
|
-
searchParams: Record<string, string | string[]>,
|
|
1409
|
-
notFound: RouteNotFoundInPlace,
|
|
1410
|
-
{ guarded = false, gate }: { guarded?: boolean; gate?: RouteShellGate } = {},
|
|
1411
|
-
): Promise<ReactNode> {
|
|
1412
|
-
this.#logger.verbose(
|
|
1413
|
-
`composing route element pathname=${url.pathname} search=${url.search || "(none)"} params=${JSON.stringify(match.params)}`,
|
|
1414
|
-
);
|
|
1415
|
-
const pathRoute = await RouteElementComposer.resolveSsrFramePathRoute({
|
|
1416
|
-
pathRoute: match.pathRoute,
|
|
1417
|
-
basePath: this.#getBasePath(url),
|
|
1418
|
-
});
|
|
1419
|
-
setRequestFrameState(pathRoute.pageState);
|
|
1420
|
-
if (!guarded) await RouteElementComposer.admit({ pathRoute, params: match.params, searchParams });
|
|
1421
|
-
|
|
1422
|
-
const rootLayouts = pathRoute.renderRootLayouts;
|
|
1423
|
-
const rootTheme = await RscRenderer.#firstRootValue(rootLayouts, (render) => render.getLayoutTheme?.());
|
|
1424
|
-
if (rootTheme) setRequestTheme(rootTheme);
|
|
1425
|
-
const viewport = await RscRenderer.#firstRootValue(rootLayouts, (render) => render.getLayoutViewport?.());
|
|
1426
|
-
|
|
1427
|
-
const themeColorTheme = untrackedCookies().get("theme")?.value ?? rootTheme;
|
|
1428
|
-
const manifestLink = await this.#renderManifestLink(url, rootLayouts);
|
|
1429
|
-
const routeHead = await RouteElementComposer.resolveHeadWithSnapshot({
|
|
1430
|
-
pathRoute,
|
|
1431
|
-
params: match.params,
|
|
1432
|
-
searchParams,
|
|
1433
|
-
});
|
|
1434
|
-
const fallbackHead = new FallbackHead();
|
|
1435
|
-
const body = RouteElementComposer.compose({
|
|
1436
|
-
pathRoute,
|
|
1437
|
-
params: match.params,
|
|
1438
|
-
searchParams,
|
|
1439
|
-
navKey: url.pathname + url.search,
|
|
1440
|
-
notFound: { ...notFound, head: fallbackHead },
|
|
1441
|
-
gate,
|
|
1442
|
-
});
|
|
1443
|
-
const renderHead = async (tags: ReactNode[] | null) => {
|
|
1444
|
-
if (!tags) return this.#renderHeadTags(url, { manifestLink, routeHead });
|
|
1445
|
-
const layoutsHead = await RscRenderer.#resolveFallbackHead({
|
|
1446
|
-
kind: "not-found",
|
|
1447
|
-
route: pathRoute,
|
|
1448
|
-
params: match.params,
|
|
1449
|
-
searchParams,
|
|
1450
|
-
});
|
|
1451
|
-
return this.#renderHeadTags(url, { manifestLink, routeHead: layoutsHead, noindex: true, tags });
|
|
1452
|
-
};
|
|
1453
|
-
|
|
1454
|
-
return (
|
|
1455
|
-
<html lang={match.params.lang ?? this.#i18n.defaultLocale} suppressHydrationWarning>
|
|
1456
|
-
<head key="head">
|
|
1457
|
-
<meta key="charset" charSet="utf-8" />
|
|
1458
|
-
{this.#renderViewport(viewport, themeColorTheme)}
|
|
1459
|
-
<FallbackHead.Settled
|
|
1460
|
-
key="route-head"
|
|
1461
|
-
head={fallbackHead}
|
|
1462
|
-
until={gate?.opened ?? Promise.resolve()}
|
|
1463
|
-
render={renderHead}
|
|
1464
|
-
/>
|
|
1465
|
-
{this.#renderStylesheet(url.pathname)}
|
|
1466
|
-
</head>
|
|
1467
|
-
<body key="body">
|
|
1468
|
-
{body}
|
|
1469
|
-
{gate?.holding ? <RouteShellGate.Wait until={gate.opened} /> : null}
|
|
1470
|
-
</body>
|
|
1471
|
-
</html>
|
|
1472
|
-
);
|
|
1473
|
-
}
|
|
1474
|
-
|
|
1475
|
-
async #renderMatchedSuffix(
|
|
1476
|
-
url: URL,
|
|
1477
|
-
match: { pathRoute: PathRoute; params: Record<string, string> },
|
|
1478
|
-
patchStartIndex: number,
|
|
1479
|
-
searchParams: Record<string, string | string[]>,
|
|
1480
|
-
notFound: RouteNotFoundInPlace,
|
|
1481
|
-
{ guarded = false }: { guarded?: boolean } = {},
|
|
1482
|
-
): Promise<ReactNode | null> {
|
|
1483
|
-
this.#logger.verbose(
|
|
1484
|
-
`composing route suffix pathname=${url.pathname} start=${patchStartIndex} params=${JSON.stringify(match.params)}`,
|
|
1485
|
-
);
|
|
1486
|
-
const pathRoute = await RouteElementComposer.resolveSsrFramePathRoute({
|
|
1487
|
-
pathRoute: match.pathRoute,
|
|
1488
|
-
basePath: this.#getBasePath(url),
|
|
1489
|
-
});
|
|
1490
|
-
setRequestFrameState(pathRoute.pageState);
|
|
1491
|
-
if (!guarded) await RouteElementComposer.admit({ pathRoute, params: match.params, searchParams });
|
|
1492
|
-
await RouteElementComposer.resolveSuffixLoadings(pathRoute, patchStartIndex);
|
|
1493
|
-
return RouteElementComposer.composeSuffix({
|
|
1494
|
-
pathRoute,
|
|
1495
|
-
params: match.params,
|
|
1496
|
-
searchParams,
|
|
1497
|
-
patchStartIndex,
|
|
1498
|
-
navKey: url.pathname + url.search,
|
|
1499
|
-
notFound,
|
|
1500
|
-
});
|
|
1501
|
-
}
|
|
1502
|
-
|
|
1503
|
-
async #renderNotFound(url: URL, gate?: RouteShellGate): Promise<ReactNode> {
|
|
1504
|
-
const matchedFallback = RouteTreeBuilder.matchFallback(url.pathname, this.#fallbackRoutes);
|
|
1505
|
-
if (matchedFallback) {
|
|
1506
|
-
const searchParams = parseSearchParams(url.search);
|
|
1507
|
-
const route = await RouteElementComposer.admittedFallbackOf(matchedFallback.fallbackRoute, {
|
|
1508
|
-
params: matchedFallback.params,
|
|
1509
|
-
searchParams,
|
|
1510
|
-
});
|
|
1511
|
-
try {
|
|
1512
|
-
const fallback = await this.#renderFallbackDocument({
|
|
1513
|
-
kind: "not-found",
|
|
1514
|
-
route,
|
|
1515
|
-
params: matchedFallback.params,
|
|
1516
|
-
searchParams,
|
|
1517
|
-
pathname: url.pathname,
|
|
1518
|
-
url,
|
|
1519
|
-
gate,
|
|
1520
|
-
});
|
|
1521
|
-
if (fallback) return fallback;
|
|
1522
|
-
} catch (error) {
|
|
1523
|
-
this.#logger.error(
|
|
1524
|
-
`custom unmatched not-found fallback failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
|
|
1525
|
-
);
|
|
1526
|
-
}
|
|
1527
|
-
}
|
|
1528
|
-
return this.#renderSystemNotFound(url);
|
|
1529
|
-
}
|
|
1530
|
-
|
|
1531
|
-
#notFoundInPlace(url: URL, probe: { hit: boolean }): RouteNotFoundInPlace {
|
|
1532
|
-
return {
|
|
1533
|
-
pathname: url.pathname,
|
|
1534
|
-
onNotFound: () => {
|
|
1535
|
-
probe.hit = true;
|
|
1536
|
-
},
|
|
1537
|
-
systemFallback: () => (
|
|
1538
|
-
<SystemPageMain kind="not-found" pathname={url.pathname} homeHref={this.#systemHomeHref(url)} />
|
|
1539
|
-
),
|
|
1540
|
-
};
|
|
1541
|
-
}
|
|
1542
|
-
|
|
1543
|
-
#systemHomeHref(url: URL): string {
|
|
1544
|
-
return getSystemPageHomeHref({
|
|
1545
|
-
pathname: url.pathname,
|
|
1546
|
-
i18n: this.#i18n,
|
|
1547
|
-
basePaths: this.#basePaths,
|
|
1548
|
-
headerBasePath: untrackedRequest()?.headers.get("x-base-path"),
|
|
1549
|
-
});
|
|
1550
|
-
}
|
|
1551
|
-
|
|
1552
|
-
#renderSystemNotFound(url: URL): ReactNode {
|
|
1553
|
-
return createSystemPageDocument({
|
|
1554
|
-
kind: "not-found",
|
|
1555
|
-
pathname: url.pathname,
|
|
1556
|
-
lang: getPathnameLocale(url.pathname, this.#i18n),
|
|
1557
|
-
homeHref: this.#systemHomeHref(url),
|
|
1558
|
-
stylesheetHref: this.#getStylesheetHref(url.pathname),
|
|
1559
|
-
});
|
|
1560
|
-
}
|
|
1561
|
-
|
|
1562
|
-
static async #firstRootValue<T>(
|
|
1563
|
-
renderRootLayouts: RouteRender[],
|
|
1564
|
-
read: (render: RouteRender) => T | Promise<T | undefined> | undefined,
|
|
1565
|
-
): Promise<T | undefined> {
|
|
1566
|
-
const values = await Promise.all(renderRootLayouts.map(read));
|
|
1567
|
-
return values.find((value) => value !== undefined);
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
#renderViewport(viewport: RouteViewport | undefined, theme?: string): ReactNode {
|
|
1571
|
-
return (
|
|
1572
|
-
<>
|
|
1573
|
-
<meta key="viewport" name="viewport" content={ViewportMeta.content(viewport)} />
|
|
1574
|
-
{ViewportMeta.themeColors(viewport, theme).map(({ content, media }) => (
|
|
1575
|
-
<meta key={`theme-color:${media ?? ""}`} name="theme-color" content={content} media={media} />
|
|
1576
|
-
))}
|
|
1577
|
-
</>
|
|
1578
|
-
);
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
async #renderManifestLink(url: URL, renderRootLayouts: RouteRender[]): Promise<ReactNode> {
|
|
1582
|
-
const manifest = await RscRenderer.#firstRootValue(renderRootLayouts, (render) => render.getLayoutManifest?.());
|
|
1583
|
-
if (manifest === undefined) return null;
|
|
1584
|
-
|
|
1585
|
-
const basePath = getBasePathFromPathname(url.pathname, { basePaths: this.#basePaths, i18n: this.#i18n });
|
|
1586
|
-
return <link key="manifest" rel="manifest" href={webManifestHref(basePath)} />;
|
|
1587
|
-
}
|
|
1588
|
-
|
|
1589
|
-
#renderHeadTags(
|
|
1590
|
-
url: URL,
|
|
1591
|
-
{
|
|
1592
|
-
manifestLink,
|
|
1593
|
-
routeHead,
|
|
1594
|
-
noindex = false,
|
|
1595
|
-
tags = null,
|
|
1596
|
-
}: { manifestLink: ReactNode; routeHead: ResolvedHead; noindex?: boolean; tags?: ReactNode[] | null },
|
|
1597
|
-
): ReactNode {
|
|
1598
|
-
const routeHeadSnapshot = this.#createRouteHeadSnapshot(url, routeHead);
|
|
1599
|
-
const head = routeHeadSnapshot
|
|
1600
|
-
? renderAkanHeadSnapshot(routeHeadSnapshot)
|
|
1601
|
-
: (routeHead.node ?? this.#renderDefaultHead());
|
|
1602
|
-
return (
|
|
1603
|
-
<>
|
|
1604
|
-
{RouteHead.mergeNodes([manifestLink, head, noindex ? RouteHead.noindexOver(head) : null, tags])}
|
|
1605
|
-
{routeHeadSnapshot ? null : this.#renderLocaleAlternates(url)}
|
|
1606
|
-
</>
|
|
1607
|
-
);
|
|
1608
|
-
}
|
|
1609
|
-
|
|
1610
|
-
#renderDefaultHead(): ReactNode {
|
|
1611
|
-
return <title key="title">{process.env.AKAN_PUBLIC_APP_NAME ?? "Akan App"}</title>;
|
|
1612
|
-
}
|
|
1613
|
-
|
|
1614
|
-
#getBasePath(url: URL): string | null {
|
|
1615
|
-
return getBasePathFromPathname(url.pathname, {
|
|
1616
|
-
basePaths: this.#basePaths,
|
|
1617
|
-
i18n: this.#i18n,
|
|
1618
|
-
headerBasePath: untrackedRequest()?.headers.get("x-base-path"),
|
|
1619
|
-
});
|
|
1620
|
-
}
|
|
1621
|
-
|
|
1622
|
-
async #resolveRouteHeadSnapshot(
|
|
1623
|
-
url: URL,
|
|
1624
|
-
match: { pathRoute: PathRoute; params: Record<string, string> },
|
|
1625
|
-
searchParams: Record<string, string | string[]>,
|
|
1626
|
-
): Promise<ResolvedHead["headSnapshot"]> {
|
|
1627
|
-
const routeHead = await RouteElementComposer.resolveHeadWithSnapshot({
|
|
1628
|
-
pathRoute: match.pathRoute,
|
|
1629
|
-
params: match.params,
|
|
1630
|
-
searchParams,
|
|
1631
|
-
});
|
|
1632
|
-
return this.#createRouteHeadSnapshot(url, routeHead);
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
#createRouteHeadSnapshot(url: URL, routeHead: ResolvedHead): ResolvedHead["headSnapshot"] {
|
|
1636
|
-
if (!routeHead.headSnapshot) return undefined;
|
|
1637
|
-
return mergeAkanHeadSnapshots(
|
|
1638
|
-
routeHead.headSnapshot,
|
|
1639
|
-
createAkanLocaleAlternateHeadSnapshot(this.#getLocaleAlternateLanguages(url)),
|
|
1640
|
-
);
|
|
1641
|
-
}
|
|
1642
|
-
|
|
1643
|
-
#getLocaleAlternateLanguages(url: URL): Record<string, string> {
|
|
1644
|
-
const languages: Record<string, string> = {};
|
|
1645
|
-
const publicUrl = RscRenderer.#getPublicRequestUrl(url);
|
|
1646
|
-
for (const lang of this.#i18n.locales) {
|
|
1647
|
-
const alternateUrl = new URL(publicUrl);
|
|
1648
|
-
alternateUrl.pathname = RscRenderer.#replaceLocalePathSegment(publicUrl.pathname, lang, this.#i18n);
|
|
1649
|
-
languages[lang] = alternateUrl.href;
|
|
1650
|
-
}
|
|
1651
|
-
const xDefaultUrl = new URL(publicUrl);
|
|
1652
|
-
xDefaultUrl.pathname = "/";
|
|
1653
|
-
xDefaultUrl.search = "";
|
|
1654
|
-
xDefaultUrl.hash = "";
|
|
1655
|
-
languages["x-default"] = xDefaultUrl.href;
|
|
1656
|
-
return languages;
|
|
1657
|
-
}
|
|
1658
|
-
|
|
1659
|
-
#renderLocaleAlternates(url: URL): ReactNode {
|
|
1660
|
-
return Object.entries(this.#getLocaleAlternateLanguages(url)).map(([lang, href]) => (
|
|
1661
|
-
<link key={`alternate:${lang}`} rel="alternate" hrefLang={lang} href={href} />
|
|
1662
|
-
));
|
|
1663
|
-
}
|
|
1664
|
-
|
|
1665
|
-
#renderStylesheet(pathname: string): ReactNode {
|
|
1666
|
-
const cssUrl = this.#getStylesheetHref(pathname);
|
|
1667
|
-
if (!cssUrl) return null;
|
|
1668
|
-
return <link key="stylesheet" rel="stylesheet" href={cssUrl} precedence="default" data-akan-css="active" />;
|
|
1669
|
-
}
|
|
1670
|
-
|
|
1671
|
-
#getStylesheetHref(pathname: string): string | null {
|
|
1672
|
-
const basePath = getBasePathFromPathname(pathname, {
|
|
1673
|
-
basePaths: Object.keys(this.#cssAssets),
|
|
1674
|
-
i18n: this.#i18n,
|
|
1675
|
-
headerBasePath: untrackedRequest()?.headers.get("x-base-path"),
|
|
1676
|
-
});
|
|
1677
|
-
return this.#cssAssets[basePath ?? ""]?.cssUrl ?? null;
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
static #getPublicRequestUrl(url: URL): URL {
|
|
1681
|
-
const publicUrl = new URL(url);
|
|
1682
|
-
const req = untrackedRequest();
|
|
1683
|
-
const headers = req?.headers;
|
|
1684
|
-
const host = headers?.get("x-forwarded-host")?.split(",")[0]?.trim() ?? headers?.get("host");
|
|
1685
|
-
const proto = headers?.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
1686
|
-
if (host) publicUrl.host = host;
|
|
1687
|
-
if (host && !host.includes(":")) publicUrl.port = "";
|
|
1688
|
-
if (proto) publicUrl.protocol = proto.endsWith(":") ? proto : `${proto}:`;
|
|
1689
|
-
|
|
1690
|
-
const basePath = headers?.get("x-base-path");
|
|
1691
|
-
const parts = publicUrl.pathname.split("/").filter(Boolean);
|
|
1692
|
-
if (basePath && parts[1] === basePath) {
|
|
1693
|
-
publicUrl.pathname = `/${[parts[0], ...parts.slice(2)].filter(Boolean).join("/")}`;
|
|
1694
|
-
}
|
|
1695
|
-
return publicUrl;
|
|
1696
|
-
}
|
|
1697
|
-
|
|
1698
|
-
static #replaceLocalePathSegment(pathname: string, lang: string, i18n: AkanI18nConfig): string {
|
|
1699
|
-
const parts = pathname.split("/").filter(Boolean);
|
|
1700
|
-
return LocalePath.join(lang, `/${parts.slice(1).join("/")}`, i18n);
|
|
1701
|
-
}
|
|
1702
396
|
}
|
|
1703
397
|
|
|
1704
398
|
if (import.meta.main) new RscRenderer().start();
|