prunelle 0.7.7 → 0.9.0
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/llms.txt +63 -46
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +15 -7
- package/src/build/index.ts +20 -10
- package/src/build/island-promote.ts +1 -1
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +57 -6
- package/src/cli/check.ts +40 -17
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +18 -4
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +72 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +4 -1
- package/src/compiler/emit.ts +1 -1
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/shared.ts +9 -16
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +8 -0
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +121 -10
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +22 -17
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +7 -4
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +35 -14
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +102 -299
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +11 -24
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +81 -20
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
package/src/server/index.ts
CHANGED
|
@@ -10,52 +10,57 @@ import type { ServedFile } from './assets'
|
|
|
10
10
|
import type { NormalizedConsentConfig } from './consent'
|
|
11
11
|
import type { CookieStore } from './cookies'
|
|
12
12
|
import type { NotifyError } from './errors'
|
|
13
|
-
import type {
|
|
14
|
-
|
|
13
|
+
import type { PhaseTiming } from './health'
|
|
14
|
+
|
|
15
|
+
import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext, ServeOptions } from './http'
|
|
15
16
|
import type { RateLimiter, RateLimitStore } from './rate-limit'
|
|
17
|
+
import { memoryLimiters } from './rate-limit'
|
|
16
18
|
export { rateLimitKey } from './rate-limit'
|
|
17
19
|
export { sanitizeMarkdownHtml } from './sanitize-html'
|
|
18
20
|
import type { LoadedMiddlewareModule } from './page'
|
|
19
21
|
import type { ServerPluginHost } from './plugin-host'
|
|
22
|
+
import type { RouteCache } from './route-cache'
|
|
20
23
|
import type { RequestPath } from './request-path'
|
|
21
|
-
import type { CompiledRoute } from './route-table'
|
|
22
24
|
import type { FastHandler } from './routing'
|
|
23
25
|
import type { OriginRefusal, TrustProxy } from './security'
|
|
26
|
+
import type { PerProcessInput } from './workers'
|
|
24
27
|
import { join } from 'node:path'
|
|
25
|
-
import {
|
|
28
|
+
import { getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
26
29
|
import { createNavigation } from '../ssr/navigation'
|
|
27
30
|
import { executeAction, finishActionRedirect, isServerAction } from './action'
|
|
28
31
|
import { createActionRegistry } from './action-registry'
|
|
29
32
|
import { createAssets } from './assets'
|
|
30
|
-
import { CompressionCache
|
|
33
|
+
import { CompressionCache } from './compress'
|
|
31
34
|
import { normalizeConsentConfig } from './consent'
|
|
35
|
+
import { createServerAppContext } from './cookie-inventory'
|
|
32
36
|
import { devFromEnv, nodeEnv } from './env'
|
|
33
|
-
import { createDocumentHooks, createHtmlHeaders
|
|
34
|
-
import { createErrorNotifier, createFallbackPages
|
|
35
|
-
import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
37
|
+
import { createDocumentHooks, createHtmlHeaders } from './document'
|
|
38
|
+
import { createErrorNotifier, createFallbackPages } from './errors'
|
|
39
|
+
import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain } from './health'
|
|
40
|
+
import { createRequestObserver } from './request-log'
|
|
41
|
+
import { createRequestGuards, createRequestHandler, maybeRenderDenied } from './request-handler'
|
|
42
|
+
import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, finalizeResponse, makeRequestContext, runChain } from './http'
|
|
43
|
+
import { hasPublicFavicon } from './page'
|
|
38
44
|
import { resolveParamMatchers } from './param-matchers'
|
|
39
|
-
import {
|
|
45
|
+
import { createServerPluginHost } from './plugin-host'
|
|
40
46
|
|
|
41
47
|
import { withRegionVary } from './region'
|
|
42
|
-
import {
|
|
48
|
+
import { literalPath } from './request-path'
|
|
43
49
|
import { nativePrerenderedCheck } from './prerendered'
|
|
50
|
+
import { receiveCacheInvalidation, serveCacheInvalidation } from './cache-invalidation'
|
|
44
51
|
import { createRouteCache } from './route-cache'
|
|
45
|
-
import {
|
|
52
|
+
import { SHARED_STORE } from './shared-store'
|
|
53
|
+
import { perProcessState } from './workers'
|
|
54
|
+
import { compileRouteTable, createCompiledRouteRenderer } from './route-table'
|
|
46
55
|
import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
|
|
47
|
-
import {
|
|
48
|
-
import { buildSecurityHeaderEntries, isLoopbackHost,
|
|
56
|
+
import { serveHandlers } from './serve-handlers'
|
|
57
|
+
import { buildSecurityHeaderEntries, isLoopbackHost, resolveHstsValue, resolveTrustProxy, verifyOrigin } from './security'
|
|
49
58
|
import { createStreamTracker } from './stream'
|
|
50
59
|
|
|
51
|
-
|
|
52
|
-
* Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
|
|
53
|
-
* Augment via `declare module 'prunelle/server' { interface PrunelleLocals { ... } }`.
|
|
54
|
-
*/
|
|
55
|
-
export interface PrunelleLocals {}
|
|
60
|
+
export type { PrunelleLocals } from './public'
|
|
56
61
|
|
|
57
|
-
export { CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, JOBS_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
|
|
58
|
-
export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ComplianceConfig, ComplianceRule, ConsentConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, JobsEnqueueOptions, JobsQueueOptions, JobsService, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
|
|
62
|
+
export { CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, JOBS_SERVICE, loadConfig, registerUserDataService, USER_DATA_SERVICE, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
|
|
63
|
+
export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ComplianceConfig, ComplianceRule, ConsentConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, JobsEnqueueOptions, JobsQueueOptions, JobsService, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, LogConfig, RequestPhase, RequestRecord, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig, UserDataService } from '../plugins/index'
|
|
59
64
|
export { currentRequest } from './request-scope'
|
|
60
65
|
export { action, getActionError } from './action'
|
|
61
66
|
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
|
|
@@ -66,7 +71,7 @@ export type { CookieOptions, Cookies } from './cookies'
|
|
|
66
71
|
export { defineEnv, devFromEnv, nodeEnv } from './env'
|
|
67
72
|
export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
|
|
68
73
|
export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
|
|
69
|
-
export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
|
|
74
|
+
export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, RoutePattern, ServerOptions, StatusPageProps } from './http'
|
|
70
75
|
export { createServer } from './loader'
|
|
71
76
|
export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
|
|
72
77
|
export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
|
|
@@ -79,83 +84,10 @@ export type { InferInput, InferOutput, StandardJSONSchemaConverter, StandardJSON
|
|
|
79
84
|
const DEFAULT_STREAM_TIMEOUT = 30_000
|
|
80
85
|
|
|
81
86
|
|
|
82
|
-
const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
|
|
83
|
-
const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
|
|
84
|
-
|
|
85
|
-
function maybeRenderDenied(
|
|
86
|
-
res: Response,
|
|
87
|
-
request: Request,
|
|
88
|
-
url: URL,
|
|
89
|
-
ctx: RequestContext,
|
|
90
|
-
renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
|
|
91
|
-
routeFile?: string,
|
|
92
|
-
isApi = false,
|
|
93
|
-
): Response | Promise<Response> {
|
|
94
|
-
if (isApi)
|
|
95
|
-
return res
|
|
96
|
-
const denied = getDeniedInfo(res)
|
|
97
|
-
if (denied === undefined || !acceptsHtml(request))
|
|
98
|
-
return res
|
|
99
|
-
return renderDenied(denied, url, request, ctx, routeFile)
|
|
100
|
-
}
|
|
101
|
-
|
|
102
87
|
const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
|
|
103
88
|
// A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
|
|
104
|
-
const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
105
89
|
const makeFileGone = (securityRecord: Record<string, string>) => (): Response => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...securityRecord } })
|
|
106
90
|
|
|
107
|
-
function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
|
|
108
|
-
const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
|
|
109
|
-
return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function matchStaticOrPublic(
|
|
113
|
-
request: Request,
|
|
114
|
-
requestPath: RequestPath,
|
|
115
|
-
assetMap: ReadonlyMap<string, ServedFile>,
|
|
116
|
-
publicMap: ReadonlyMap<string, ServedFile>,
|
|
117
|
-
pluginRouter: ServerPluginHost['router'],
|
|
118
|
-
): ServedFile | undefined {
|
|
119
|
-
const { staticPath } = requestPath
|
|
120
|
-
if (staticPath === undefined)
|
|
121
|
-
return undefined
|
|
122
|
-
const asset = assetMap.get(staticPath)
|
|
123
|
-
if (asset !== undefined)
|
|
124
|
-
return asset
|
|
125
|
-
const pub = publicMap.get(staticPath)
|
|
126
|
-
if (pub === undefined)
|
|
127
|
-
return undefined
|
|
128
|
-
const matchedPlugin = pluginRouter.match(requestPath)
|
|
129
|
-
const reqMethod = request.method.toUpperCase()
|
|
130
|
-
const shadowedByPlugin = matchedPlugin !== undefined
|
|
131
|
-
&& (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
|
|
132
|
-
return shadowedByPlugin ? undefined : pub
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function createRequestGuards(
|
|
136
|
-
maxRequestBodySize: number,
|
|
137
|
-
finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
|
|
138
|
-
) {
|
|
139
|
-
const refuseCrossSite = (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string): Response => {
|
|
140
|
-
logOriginHint(check.hint)
|
|
141
|
-
return finish(Response.json({ ok: false, status: 403, error: check.reason }, { status: 403 }), request, cookieStore, requestId)
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
|
|
145
|
-
if (bodyLimited)
|
|
146
|
-
return request
|
|
147
|
-
const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
|
|
148
|
-
if (bounded.ok)
|
|
149
|
-
return bounded.request
|
|
150
|
-
const status = bounded.aborted ? 400 : 413
|
|
151
|
-
const message = bounded.aborted ? 'Bad Request' : 'Payload Too Large'
|
|
152
|
-
return finish(wantsJson(request)
|
|
153
|
-
? Response.json({ ok: false, status, error: message }, { status })
|
|
154
|
-
: new Response(message, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
|
|
155
|
-
}
|
|
156
|
-
return { refuseCrossSite, checkBodyLimit }
|
|
157
|
-
}
|
|
158
|
-
|
|
159
91
|
interface ActionDispatcherDeps {
|
|
160
92
|
actions: ActionRegistry
|
|
161
93
|
rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
|
|
@@ -180,7 +112,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
|
|
|
180
112
|
return undefined
|
|
181
113
|
let limiter = limiters.get(act)
|
|
182
114
|
if (limiter === undefined) {
|
|
183
|
-
limiter = rateLimits.limiter(act.rateLimit)
|
|
115
|
+
limiter = rateLimits.limiter(act.rateLimit, `action:${act.url}`)
|
|
184
116
|
limiters.set(act, limiter)
|
|
185
117
|
}
|
|
186
118
|
return limiter
|
|
@@ -214,7 +146,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
|
|
|
214
146
|
for (const rewrite of rewrites)
|
|
215
147
|
rewrite(rawPathname, ctx)
|
|
216
148
|
}
|
|
217
|
-
const timing = createTiming(isDev)
|
|
149
|
+
const timing = createTiming(isDev, request)
|
|
218
150
|
try {
|
|
219
151
|
const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
|
|
220
152
|
actionHandler !== undefined
|
|
@@ -273,7 +205,7 @@ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
|
|
|
273
205
|
ctx: RequestContext,
|
|
274
206
|
effective: RequestPath,
|
|
275
207
|
rawScopedPath: string,
|
|
276
|
-
timing?:
|
|
208
|
+
timing?: PhaseTiming,
|
|
277
209
|
): Promise<Response> => {
|
|
278
210
|
const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
|
|
279
211
|
const ancestor = ancestorMiddlewaresFor(effective)
|
|
@@ -302,7 +234,7 @@ function createSecurityResponders(
|
|
|
302
234
|
const resolvedNodeEnv = explicitNodeEnv ?? nodeEnv()
|
|
303
235
|
// An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
|
|
304
236
|
const httpsSite = !isDev && resolvedNodeEnv !== 'development' && resolvedNodeEnv !== 'test' && site?.startsWith('https://') === true
|
|
305
|
-
const securityEntries = buildSecurityHeaderEntries(security)
|
|
237
|
+
const securityEntries = buildSecurityHeaderEntries(security, httpsSite)
|
|
306
238
|
const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
|
|
307
239
|
const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
|
|
308
240
|
const hstsValue = resolveHstsValue(security)
|
|
@@ -321,6 +253,14 @@ function createSecurityResponders(
|
|
|
321
253
|
return { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError: makeServerError(securityRecord), fileGone: makeFileGone(securityRecord) }
|
|
322
254
|
}
|
|
323
255
|
|
|
256
|
+
// `invalidateCache()` works from the plugins' own server hooks on, and hears the other processes once a plugin host opened the shared store.
|
|
257
|
+
async function startPlugins(options: Parameters<typeof createServerPluginHost>[0], routeCache: RouteCache | undefined): Promise<ServerPluginHost> {
|
|
258
|
+
serveCacheInvalidation(options.appCtx, routeCache)
|
|
259
|
+
const host = await createServerPluginHost(options)
|
|
260
|
+
receiveCacheInvalidation(options.appCtx.inject(SHARED_STORE), routeCache)
|
|
261
|
+
return host
|
|
262
|
+
}
|
|
263
|
+
|
|
324
264
|
export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
|
|
325
265
|
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
|
|
326
266
|
const plugins = resolvePlugins(config.plugins)
|
|
@@ -328,8 +268,8 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
328
268
|
const site = config.site?.replace(/\/$/, '') || undefined
|
|
329
269
|
const trustedOriginsList = config.trustedOrigins ?? []
|
|
330
270
|
const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
|
|
331
|
-
const trustProxy = config.trustProxy ?? false
|
|
332
|
-
const consent = normalizeConsentConfig(config.consent)
|
|
271
|
+
const trustProxy = resolveTrustProxy(config.trustProxy ?? false, site, trustedOriginsList)
|
|
272
|
+
const consent = normalizeConsentConfig(config.consent, lang)
|
|
333
273
|
const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
|
|
334
274
|
const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
|
|
335
275
|
const isDev = config.dev ?? devFromEnv()
|
|
@@ -339,14 +279,14 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
339
279
|
const parentAppCtx = getAppContext()
|
|
340
280
|
|
|
341
281
|
const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
|
|
342
|
-
const notifyError = createErrorNotifier(config.onError, plugins, { dev: isDev, sink: config.errorSink })
|
|
282
|
+
const notifyError = createErrorNotifier(config.onError, plugins, { dev: isDev, sink: config.errorSink, format: config.log?.format })
|
|
343
283
|
const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
|
|
344
284
|
const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
|
|
345
285
|
|
|
346
286
|
const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site, config.nodeEnv ?? parentAppCtx?.nodeEnv)
|
|
347
287
|
const resolveRequestId = createRequestIdResolver(trustProxy)
|
|
348
|
-
const navigation = createNavigation(config.navigation)
|
|
349
|
-
const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
|
|
288
|
+
const navigation = createNavigation(config.navigation, assetPrefix)
|
|
289
|
+
const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins, httpsSite)
|
|
350
290
|
const streams = createStreamTracker()
|
|
351
291
|
|
|
352
292
|
const compressEnabled = config.compress ?? !isDev
|
|
@@ -357,35 +297,16 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
357
297
|
const { assetMap, publicMap, serveFile } = files
|
|
358
298
|
files.registerPublicFiles(publicAssets, publicEtags)
|
|
359
299
|
|
|
360
|
-
const serverAppCtx =
|
|
361
|
-
root: serverRoot,
|
|
362
|
-
|
|
363
|
-
publicDir: serverPublicDir,
|
|
364
|
-
assetPrefix,
|
|
365
|
-
site,
|
|
366
|
-
dev: isDev, nodeEnv: config.nodeEnv ?? parentAppCtx?.nodeEnv,
|
|
367
|
-
onRegisterPublicFile: (rel) => {
|
|
368
|
-
parentAppCtx?.registerPublicFile(rel)
|
|
369
|
-
files.registerPublicFromDisk(serverPublicDir, rel)
|
|
370
|
-
},
|
|
300
|
+
const serverAppCtx = createServerAppContext({
|
|
301
|
+
root: serverRoot, outDir: serverOutDir, publicDir: serverPublicDir, assetPrefix, site, dev: isDev, nodeEnv: config.nodeEnv ?? parentAppCtx?.nodeEnv,
|
|
302
|
+
parent: parentAppCtx, registerPublicFromDisk: files.registerPublicFromDisk, consent, manifest, plugins, lang,
|
|
371
303
|
})
|
|
372
304
|
|
|
373
305
|
const actions = createActionRegistry()
|
|
374
|
-
const pluginHost = await
|
|
375
|
-
plugins,
|
|
376
|
-
config,
|
|
377
|
-
|
|
378
|
-
appCtx: serverAppCtx,
|
|
379
|
-
root: serverRoot,
|
|
380
|
-
outDir: serverOutDir,
|
|
381
|
-
assetPrefix,
|
|
382
|
-
site,
|
|
383
|
-
dev: isDev,
|
|
384
|
-
devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost),
|
|
385
|
-
trustProxy,
|
|
386
|
-
trustedOriginsList,
|
|
387
|
-
trustedOrigins,
|
|
388
|
-
})
|
|
306
|
+
const pluginHost = await startPlugins({
|
|
307
|
+
plugins, config, manifest, appCtx: serverAppCtx, root: serverRoot, outDir: serverOutDir, assetPrefix, site, dev: isDev,
|
|
308
|
+
devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost), trustProxy, trustedOriginsList, trustedOrigins, notifyError,
|
|
309
|
+
}, routeCache)
|
|
389
310
|
const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
|
|
390
311
|
const healthPath = `${assetPrefix}/health`
|
|
391
312
|
const hasPluginRewrites = pluginHost.rewrites.length > 0
|
|
@@ -424,12 +345,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
424
345
|
prerendered, prerenderedFiles, prerenderedEtags,
|
|
425
346
|
// The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
|
|
426
347
|
// no-cache, not public: an app middleware may gate the page, and its ETag still spares a revisit the download.
|
|
427
|
-
htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
|
|
348
|
+
htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0 || (route.usesRegion === true && manifest.runtimeScript !== undefined), false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
|
|
428
349
|
isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
|
|
429
350
|
})
|
|
430
351
|
fastPrerenderedMap = collected.fast
|
|
431
352
|
renderCompiledRoute = createCompiledRouteRenderer({
|
|
432
|
-
manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, streams, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
|
|
353
|
+
manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, streams, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, httpsSite, consent, resolveRequestId, serverAppCtx,
|
|
433
354
|
})
|
|
434
355
|
dispatchAction = createActionDispatcher({
|
|
435
356
|
actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
|
|
@@ -440,178 +361,60 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
440
361
|
throw error
|
|
441
362
|
}
|
|
442
363
|
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
const rawPathname = url.pathname
|
|
449
|
-
const requestPath = decodeRequestPath(rawPathname)
|
|
450
|
-
if (requestPath === undefined)
|
|
451
|
-
return finish(badRequest(), request, undefined, requestId)
|
|
452
|
-
const { staticPath, scopedPath } = requestPath
|
|
453
|
-
if (staticPath === healthPath)
|
|
454
|
-
return healthHandler(request, requestId)
|
|
455
|
-
const read = isRead(request)
|
|
456
|
-
|
|
457
|
-
// 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
|
|
458
|
-
if (read) {
|
|
459
|
-
const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
|
|
460
|
-
if (staticFile !== undefined)
|
|
461
|
-
return withRequestId(await serveFile(request, staticFile), requestId)
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
// 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
|
|
465
|
-
const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
|
|
466
|
-
if (registeredAction !== undefined)
|
|
467
|
-
return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
|
|
468
|
-
|
|
469
|
-
// 3. Prerendered static HTML, then 4. the zero-overhead static route path
|
|
470
|
-
const plainRead = isPlainRead(request)
|
|
471
|
-
if (plainRead && staticPath !== undefined) {
|
|
472
|
-
const pre = fastPrerenderedMap.get(staticPath)
|
|
473
|
-
if (pre !== undefined)
|
|
474
|
-
return withRequestId(await serveFile(request, pre), requestId)
|
|
475
|
-
const fast = fastStaticPages.get(staticPath)
|
|
476
|
-
if (fast !== undefined)
|
|
477
|
-
return fast(request, remoteIp, url, requestId)
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
// 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
|
|
481
|
-
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
|
|
482
|
-
const timing = createTiming(isDev)
|
|
483
|
-
|
|
484
|
-
// Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
|
|
485
|
-
let effectivePath = rawPathname
|
|
486
|
-
for (const rewrite of pluginHost.rewrites) {
|
|
487
|
-
const nextPath = rewrite(effectivePath, ctx)
|
|
488
|
-
if (nextPath !== undefined)
|
|
489
|
-
effectivePath = nextPath
|
|
490
|
-
}
|
|
491
|
-
let effective = requestPath
|
|
492
|
-
if (effectivePath !== rawPathname) {
|
|
493
|
-
const rewritten = decodeRequestPath(effectivePath)
|
|
494
|
-
if (rewritten === undefined)
|
|
495
|
-
return finish(badRequest(), request, cookieStore, requestId)
|
|
496
|
-
effective = rewritten
|
|
497
|
-
const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
|
|
498
|
-
if (rewrittenAction !== undefined)
|
|
499
|
-
return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
|
|
500
|
-
}
|
|
501
|
-
const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
|
|
502
|
-
|
|
503
|
-
// Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
|
|
504
|
-
const method = request.method.toUpperCase()
|
|
505
|
-
const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
|
|
506
|
-
const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
|
|
507
|
-
const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
|
|
508
|
-
const routeDef = directPluginDef ?? headFallbackPluginDef
|
|
509
|
-
if (pluginMatch !== undefined && routeDef !== undefined) {
|
|
510
|
-
if (routeDef.csrf) {
|
|
511
|
-
const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
|
|
512
|
-
if (!originCheck.ok)
|
|
513
|
-
return refuseCrossSite(request, originCheck, cookieStore, requestId)
|
|
514
|
-
}
|
|
515
|
-
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
516
|
-
if (checked instanceof Response)
|
|
517
|
-
return checked
|
|
518
|
-
ctx.request = checked
|
|
519
|
-
ctx.params = pluginMatch.params
|
|
520
|
-
const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
|
|
521
|
-
try {
|
|
522
|
-
let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
|
|
523
|
-
if (headFallbackPluginDef !== undefined)
|
|
524
|
-
res = stripHeadBody(res)
|
|
525
|
-
else if (isEventStream(res))
|
|
526
|
-
res = streams.track(res, setIdleTimeout)
|
|
527
|
-
return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
528
|
-
}
|
|
529
|
-
catch (error) {
|
|
530
|
-
notifyError(error, ctx.request, 'plugin', requestId)
|
|
531
|
-
return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// Localized/rewritten public/ links (e.g. /fr/logo.png -> /logo.png)
|
|
536
|
-
if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
|
|
537
|
-
const pub = publicMap.get(effectiveStaticPath)
|
|
538
|
-
if (pub !== undefined)
|
|
539
|
-
return withRequestId(await serveFile(request, pub), requestId)
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
const matched = router.match(effective)
|
|
543
|
-
// Before any middleware: an unmatched path, a 405 and a route without a handler for the method are checked too, unless the route opts out.
|
|
544
|
-
if (matched?.data.mod.csrf !== false) {
|
|
545
|
-
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
546
|
-
if (!originCheck.ok)
|
|
547
|
-
return refuseCrossSite(request, originCheck, cookieStore, requestId)
|
|
548
|
-
}
|
|
549
|
-
if (matched === undefined) {
|
|
550
|
-
if (pluginMatch !== undefined) {
|
|
551
|
-
ctx.params = pluginMatch.params
|
|
552
|
-
const allow = allowedPluginMethodsHeader(pluginMatch.data)
|
|
553
|
-
const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
|
|
554
|
-
try {
|
|
555
|
-
const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
|
|
556
|
-
return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
|
|
557
|
-
}
|
|
558
|
-
catch (error) {
|
|
559
|
-
notifyError(error, request, 'plugin', requestId)
|
|
560
|
-
return renderError(error, cookieStore, ctx.url, request, ctx)
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
ctx.params = matched.params
|
|
567
|
-
const route = matched.data
|
|
568
|
-
|
|
569
|
-
// Body limit for file-based API routes; the origin was checked above.
|
|
570
|
-
if (routeMethodHandler(route.mod, method) !== undefined) {
|
|
571
|
-
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
572
|
-
if (checked instanceof Response)
|
|
573
|
-
return checked
|
|
574
|
-
ctx.request = checked
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
const routeMiddlewares = pluginHost.hasPathScopedMiddlewares && (route.dynamic || effectiveScopedPath !== scopedPath)
|
|
578
|
-
? [...pluginMiddlewaresFor(effectiveScopedPath, scopedPath), ...route.dirMiddlewares]
|
|
579
|
-
: route.middlewares
|
|
580
|
-
|
|
581
|
-
try {
|
|
582
|
-
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
|
|
583
|
-
const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
|
|
584
|
-
const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
|
|
585
|
-
// Compress uncompressed API/middleware responses after the middleware chain unwinds.
|
|
586
|
-
const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
|
|
587
|
-
return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
588
|
-
}
|
|
589
|
-
catch (error) {
|
|
590
|
-
notifyError(error, ctx.request, 'route', requestId)
|
|
591
|
-
return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
catch (error) {
|
|
595
|
-
notifyError(error, request, 'route', requestId)
|
|
596
|
-
return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
|
|
597
|
-
}
|
|
598
|
-
}
|
|
364
|
+
const handleInternal = createRequestHandler({
|
|
365
|
+
isDev, healthPath, healthHandler, resolveRequestId, finish, withHsts, serverError, assetMap, publicMap, serveFile, pluginHost, pluginMiddlewaresFor,
|
|
366
|
+
actions, dispatchAction, fastPrerenderedMap, fastStaticPages, router, trustProxy, httpsSite, consent, trustedOrigins, refuseCrossSite, checkBodyLimit,
|
|
367
|
+
streams, htmlHeaders, compressCache, notifyError, renderError, renderDenied, renderNotFound, renderCompiledRoute,
|
|
368
|
+
})
|
|
599
369
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
370
|
+
const observe = createRequestObserver(config.log, pluginHost.requestHooks, isDev)
|
|
371
|
+
const handleRequest = (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
|
|
372
|
+
const handle = observe?.(handleRequest) ?? handleRequest
|
|
603
373
|
|
|
604
374
|
const runRequest = (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, setIdleTimeout, true))
|
|
605
375
|
const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
|
|
606
|
-
const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
|
|
376
|
+
const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe })
|
|
377
|
+
|
|
378
|
+
return appFacade({ config, plugins, handle, handlers, maxRequestBodySize, pluginHost, actions, inject: serverAppCtx.inject, streams, securityRecord })
|
|
379
|
+
}
|
|
607
380
|
|
|
608
|
-
|
|
609
|
-
|
|
381
|
+
interface AppFacadeDeps {
|
|
382
|
+
config: EmbeddedServerConfig
|
|
383
|
+
plugins: PerProcessInput['plugins']
|
|
384
|
+
handle: PrunelleApp['handle']
|
|
385
|
+
inject: NonNullable<PrunelleApp['inject']>
|
|
386
|
+
handlers: (server: () => PrunelleServer | undefined) => ReturnType<typeof serveHandlers>
|
|
387
|
+
maxRequestBodySize: number
|
|
388
|
+
pluginHost: ServerPluginHost
|
|
389
|
+
actions: ActionRegistry
|
|
390
|
+
streams: ReturnType<typeof createStreamTracker>
|
|
391
|
+
securityRecord: Readonly<Record<string, string>>
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// What `createServerFromEmbedded` hands its caller: the request handler, and the ways to listen, reload, shut down and report.
|
|
395
|
+
function appFacade(deps: AppFacadeDeps): PrunelleApp {
|
|
396
|
+
const { config, plugins, handlers, pluginHost, streams } = deps
|
|
397
|
+
function serve(port = 3000, hostname = '127.0.0.1', serveOptions: ServeOptions = {}): PrunelleServer {
|
|
398
|
+
const server: PrunelleServer = Bun.serve({ port, hostname, reusePort: serveOptions.reusePort === true, idleTimeout: 30, maxRequestBodySize: deps.maxRequestBodySize, development: false, ...handlers(() => server) })
|
|
610
399
|
return server
|
|
611
400
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
401
|
+
return {
|
|
402
|
+
handle: deps.handle,
|
|
403
|
+
serve,
|
|
404
|
+
reloadInto: server => server.reload(handlers(() => server)),
|
|
405
|
+
perProcessState: () => perProcessState({
|
|
406
|
+
store: config.store,
|
|
407
|
+
limiters: memoryLimiters(),
|
|
408
|
+
actionsRateLimited: deps.actions.rateLimited(),
|
|
409
|
+
cachedRoutes: config.manifest.routes.some(route => route.cache !== undefined),
|
|
410
|
+
plugins,
|
|
411
|
+
}),
|
|
412
|
+
inject: deps.inject,
|
|
413
|
+
closeStreams: streams.closeAll,
|
|
414
|
+
securityHeaders: deps.securityRecord,
|
|
415
|
+
dispose: async () => {
|
|
416
|
+
await streams.closeAll()
|
|
417
|
+
await pluginHost.dispose()
|
|
418
|
+
},
|
|
615
419
|
}
|
|
616
|
-
return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, securityHeaders: securityRecord, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
|
|
617
420
|
}
|
package/src/server/loader.ts
CHANGED
|
@@ -126,6 +126,7 @@ async function serveStaticDir(options: ServerOptions, root: string, outDir: stri
|
|
|
126
126
|
errorSink: options.errorSink,
|
|
127
127
|
httpsSite: !isDev && site?.startsWith('https://') === true,
|
|
128
128
|
nodeEnv: options.nodeEnv,
|
|
129
|
+
log: options.log ?? config.log,
|
|
129
130
|
},
|
|
130
131
|
)
|
|
131
132
|
}
|
package/src/server/page.ts
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
import type { BuildManifest, RouteManifestEntry } from '../build/index'
|
|
4
4
|
import type { Html } from '../jsx-runtime'
|
|
5
5
|
import type { Middleware, RequestContext } from './http'
|
|
6
|
-
import type { PrunelleLocals } from './
|
|
6
|
+
import type { PrunelleLocals } from './public'
|
|
7
7
|
import { existsSync } from 'node:fs'
|
|
8
8
|
import { join } from 'node:path'
|
|
9
|
+
import { cancelQuietly } from './discard'
|
|
9
10
|
|
|
10
11
|
export interface LoadedPageModule {
|
|
11
12
|
default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
|
|
@@ -70,16 +71,9 @@ export function allowedMethodsHeader(mod: LoadedPageModule): string {
|
|
|
70
71
|
return [...allowed].join(', ')
|
|
71
72
|
}
|
|
72
73
|
|
|
73
|
-
async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
|
|
74
|
-
try {
|
|
75
|
-
await body.cancel()
|
|
76
|
-
}
|
|
77
|
-
catch {}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
74
|
export function stripHeadBody(res: Response): Response {
|
|
81
75
|
if (res.body !== null)
|
|
82
|
-
void
|
|
76
|
+
void cancelQuietly(res.body)
|
|
83
77
|
return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
84
78
|
}
|
|
85
79
|
|
|
@@ -87,18 +81,14 @@ export function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
|
87
81
|
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
88
82
|
}
|
|
89
83
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
return undefined
|
|
84
|
+
// The keys of `obj` the island reads, as an object even when it holds none of them: the island reads `data.x` as the server did, on an object.
|
|
85
|
+
function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {
|
|
93
86
|
const picked: Record<string, unknown> = {}
|
|
94
|
-
let count = 0
|
|
95
87
|
for (const k of keys) {
|
|
96
|
-
if (Object.hasOwn(obj, k))
|
|
88
|
+
if (Object.hasOwn(obj, k))
|
|
97
89
|
Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
|
|
98
|
-
count++
|
|
99
|
-
}
|
|
100
90
|
}
|
|
101
|
-
return
|
|
91
|
+
return picked
|
|
102
92
|
}
|
|
103
93
|
|
|
104
94
|
export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
|
|
@@ -109,18 +99,15 @@ export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mo
|
|
|
109
99
|
return subset === undefined ? {} : { data: subset }
|
|
110
100
|
}
|
|
111
101
|
if (Array.isArray(mod.clientData)) {
|
|
112
|
-
if (!isPlainObject(data))
|
|
102
|
+
if (!isPlainObject(data) || mod.clientData.length === 0)
|
|
113
103
|
return {}
|
|
114
|
-
|
|
115
|
-
return subset === undefined ? {} : { data: subset }
|
|
104
|
+
return { data: pickObjectKeys(data, mod.clientData) }
|
|
116
105
|
}
|
|
117
106
|
if (entry.islandDataKeys !== undefined) {
|
|
118
107
|
if (entry.islandDataKeys.length === 0)
|
|
119
108
|
return {}
|
|
120
|
-
if (isPlainObject(data))
|
|
121
|
-
|
|
122
|
-
return subset === undefined ? {} : { data: subset }
|
|
123
|
-
}
|
|
109
|
+
if (isPlainObject(data))
|
|
110
|
+
return { data: pickObjectKeys(data, entry.islandDataKeys) }
|
|
124
111
|
}
|
|
125
112
|
return { data }
|
|
126
113
|
}
|