@cloudhal/astro-renderer 0.6.3 → 0.6.4
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/dist/src/astro-env.d.ts +9 -0
- package/dist/src/cloudflare-entry.d.ts +6 -0
- package/dist/src/cloudflare-entry.js +135 -6
- package/dist/src/integration.js +34 -5
- package/dist/src/runtime-workerd.d.ts +26 -0
- package/dist/src/runtime-workerd.js +63 -3
- package/dist/src/runtime.d.ts +18 -0
- package/dist/src/runtime.js +19 -0
- package/dist/src/status-hook.d.ts +36 -0
- package/dist/src/status-hook.js +141 -0
- package/dist/src/status-html.d.ts +51 -0
- package/dist/src/status-html.js +157 -0
- package/dist/src/status-middleware.d.ts +6 -0
- package/dist/src/status-middleware.js +61 -0
- package/dist/src/status-page.d.ts +94 -0
- package/dist/src/status-page.js +323 -0
- package/dist/src/status-serve.d.ts +44 -0
- package/dist/src/status-serve.js +112 -0
- package/dist/src/status-strings/ar.d.ts +2 -0
- package/dist/src/status-strings/ar.js +34 -0
- package/dist/src/status-strings/catalog.d.ts +8 -0
- package/dist/src/status-strings/catalog.js +52 -0
- package/dist/src/status-strings/de.d.ts +2 -0
- package/dist/src/status-strings/de.js +34 -0
- package/dist/src/status-strings/en.d.ts +46 -0
- package/dist/src/status-strings/en.js +47 -0
- package/dist/src/status-strings/es.d.ts +2 -0
- package/dist/src/status-strings/es.js +34 -0
- package/dist/src/status-strings/fa.d.ts +2 -0
- package/dist/src/status-strings/fa.js +34 -0
- package/dist/src/status-strings/fr.d.ts +2 -0
- package/dist/src/status-strings/fr.js +34 -0
- package/dist/src/status-strings/he.d.ts +2 -0
- package/dist/src/status-strings/he.js +34 -0
- package/dist/src/status-strings/hi.d.ts +2 -0
- package/dist/src/status-strings/hi.js +34 -0
- package/dist/src/status-strings/id.d.ts +2 -0
- package/dist/src/status-strings/id.js +34 -0
- package/dist/src/status-strings/it.d.ts +2 -0
- package/dist/src/status-strings/it.js +34 -0
- package/dist/src/status-strings/ja.d.ts +2 -0
- package/dist/src/status-strings/ja.js +34 -0
- package/dist/src/status-strings/ko.d.ts +2 -0
- package/dist/src/status-strings/ko.js +34 -0
- package/dist/src/status-strings/nl.d.ts +2 -0
- package/dist/src/status-strings/nl.js +34 -0
- package/dist/src/status-strings/pl.d.ts +2 -0
- package/dist/src/status-strings/pl.js +34 -0
- package/dist/src/status-strings/pt-BR.d.ts +2 -0
- package/dist/src/status-strings/pt-BR.js +34 -0
- package/dist/src/status-strings/ru.d.ts +2 -0
- package/dist/src/status-strings/ru.js +34 -0
- package/dist/src/status-strings/tr.d.ts +2 -0
- package/dist/src/status-strings/tr.js +34 -0
- package/dist/src/status-strings/uk.d.ts +2 -0
- package/dist/src/status-strings/uk.js +34 -0
- package/dist/src/status-strings/zh-Hans.d.ts +2 -0
- package/dist/src/status-strings/zh-Hans.js +34 -0
- package/package.json +23 -7
package/dist/src/astro-env.d.ts
CHANGED
|
@@ -19,3 +19,12 @@ declare module "virtual:cloudhal/comments-client" {
|
|
|
19
19
|
const client: import("./comments-client.js").CommentsClient | null;
|
|
20
20
|
export default client;
|
|
21
21
|
}
|
|
22
|
+
|
|
23
|
+
declare module "virtual:cloudhal/theme-hooks" {
|
|
24
|
+
/**
|
|
25
|
+
* RFC-0043 §1.7: loads the project's `src/theme.ts` lazily (an empty module when the project
|
|
26
|
+
* has none), so a status page can ask for the theme's `statusPage` hook without evaluating
|
|
27
|
+
* the theme on the normal path.
|
|
28
|
+
*/
|
|
29
|
+
export const loadTheme: () => Promise<Record<string, unknown>>;
|
|
30
|
+
}
|
|
@@ -32,6 +32,12 @@
|
|
|
32
32
|
* render the section themselves (`loadComments`, `<Comments />`) and set their own CSP when an
|
|
33
33
|
* open form uses Turnstile; `withSecurityHeaders` keeps it. All of it is off without a usable
|
|
34
34
|
* `CLOUDHAL_COMMENTS_KEY` (or when the build has no comments module).
|
|
35
|
+
* - Status pages (RFC-0043 §1): before Astro, the entry decides the site's state — `not-published`
|
|
36
|
+
* before the first publish, `preview-expired` for a preview token that does not verify,
|
|
37
|
+
* `unavailable` for a Worker that serves no site — and answers page paths with the renderer's
|
|
38
|
+
* own page (`status-page.ts`: 503/410, `Retry-After`, `no-store`, its own CSP), restyled by the
|
|
39
|
+
* theme's optional `statusPage` hook. A failure anywhere becomes the `error` page (500) with the
|
|
40
|
+
* `cf-ray` as its reference. `GET /__cloudhal/health` answers `{ ok, state }` for monitors.
|
|
35
41
|
*/
|
|
36
42
|
import { type CommentsRateLimit } from "./comments.js";
|
|
37
43
|
import { type RedirectEnv } from "./host-redirect.js";
|
|
@@ -32,17 +32,26 @@
|
|
|
32
32
|
* render the section themselves (`loadComments`, `<Comments />`) and set their own CSP when an
|
|
33
33
|
* open form uses Turnstile; `withSecurityHeaders` keeps it. All of it is off without a usable
|
|
34
34
|
* `CLOUDHAL_COMMENTS_KEY` (or when the build has no comments module).
|
|
35
|
+
* - Status pages (RFC-0043 §1): before Astro, the entry decides the site's state — `not-published`
|
|
36
|
+
* before the first publish, `preview-expired` for a preview token that does not verify,
|
|
37
|
+
* `unavailable` for a Worker that serves no site — and answers page paths with the renderer's
|
|
38
|
+
* own page (`status-page.ts`: 503/410, `Retry-After`, `no-store`, its own CSP), restyled by the
|
|
39
|
+
* theme's optional `statusPage` hook. A failure anywhere becomes the `error` page (500) with the
|
|
40
|
+
* `cf-ray` as its reference. `GET /__cloudhal/health` answers `{ ok, state }` for monitors.
|
|
35
41
|
*/
|
|
36
42
|
|
|
37
43
|
import { cache } from "cloudflare:workers";
|
|
38
44
|
import config from "virtual:cloudhal/config";
|
|
45
|
+
import { loadTheme } from "virtual:cloudhal/theme-hooks";
|
|
39
46
|
import { handle } from "@astrojs/cloudflare/handler";
|
|
40
47
|
import { WaeWriter } from "@cloudhal/analytics/wae";
|
|
41
48
|
import {
|
|
42
49
|
analyticsBackend,
|
|
43
50
|
CACHE_TAG_PREFIX,
|
|
44
51
|
resetSource,
|
|
52
|
+
|
|
45
53
|
serveMedia,
|
|
54
|
+
siteState,
|
|
46
55
|
withRequestSite,
|
|
47
56
|
} from "@cloudhal/astro-renderer/runtime";
|
|
48
57
|
import { SqlCommentStore } from "@cloudhal/comments/sql";
|
|
@@ -63,6 +72,9 @@ import { hostRedirect, } from "./host-redirect.js";
|
|
|
63
72
|
import { PREVIEW_PARAM } from "./resolver.js";
|
|
64
73
|
import { SearchLimiter, searchCost } from "./search-limit.js";
|
|
65
74
|
import { SiteDispatch, unknownHost, withNoindex } from "./site-dispatch.js";
|
|
75
|
+
import { renderStatus, themeStatusHook } from "./status-hook.js";
|
|
76
|
+
import { statusPage } from "./status-page.js";
|
|
77
|
+
import { isStatusPagePath, statusInput } from "./status-serve.js";
|
|
66
78
|
|
|
67
79
|
|
|
68
80
|
|
|
@@ -142,6 +154,67 @@ const pendingWrites = new PendingWrites();
|
|
|
142
154
|
const analyticsBySite = new Map ();
|
|
143
155
|
const commentsBySite = new Map ();
|
|
144
156
|
let dispatch ;
|
|
157
|
+
/** RFC-0043 §1.7: the theme's `statusPage` hook, loaded the first time a status page is drawn. */
|
|
158
|
+
const statusHook = themeStatusHook(loadTheme, (m, e) => console.error(m, e));
|
|
159
|
+
|
|
160
|
+
/** RFC-0043 §1.3: the `error` page's reference — Cloudflare's ray id, else a random one. */
|
|
161
|
+
function referenceId(request ) {
|
|
162
|
+
return (
|
|
163
|
+
request.headers.get("cf-ray") ??
|
|
164
|
+
Array.from(crypto.getRandomValues(new Uint8Array(8)), (b) =>
|
|
165
|
+
b.toString(16).padStart(2, "0"),
|
|
166
|
+
).join("")
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The `error` page (RFC-0043 §1.2): never the theme's hook, nothing read from the store. */
|
|
171
|
+
function errorPage(request , error ) {
|
|
172
|
+
const rayId = referenceId(request);
|
|
173
|
+
console.error(`cloudhal: request failed (reference ${rayId})`, error);
|
|
174
|
+
return statusPage("error", { locale: "en", now: Date.now(), rayId }, { method: request.method });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* A 5xx HTML answer from Astro becomes the `error` page unless the theme marked it as its own
|
|
179
|
+
* (`x-cloudhal-error-page: theme`, a theme's `500.astro`).
|
|
180
|
+
*/
|
|
181
|
+
function withErrorPage(response , request ) {
|
|
182
|
+
if (
|
|
183
|
+
response.status < 500 ||
|
|
184
|
+
!(response.headers.get("content-type") ?? "").includes("text/html") ||
|
|
185
|
+
response.headers.get("x-cloudhal-error-page") === "theme"
|
|
186
|
+
)
|
|
187
|
+
return response;
|
|
188
|
+
return errorPage(request, new Error(`Astro answered ${response.status}`));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* RFC-0043 §1.9: `{ ok, state }`, the admin's `/api/health` shape plus the site's state, so one
|
|
193
|
+
* monitor rule reads both. Public, never cached, never indexed; reads only the memoised pointer.
|
|
194
|
+
*/
|
|
195
|
+
async function health(request ) {
|
|
196
|
+
const headers = {
|
|
197
|
+
"cache-control": "no-store",
|
|
198
|
+
"cloudflare-cdn-cache-control": "no-store",
|
|
199
|
+
"x-robots-tag": "noindex",
|
|
200
|
+
};
|
|
201
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
202
|
+
return Response.json(
|
|
203
|
+
{ error: "method_not_allowed" },
|
|
204
|
+
{ status: 405, headers: { ...headers, allow: "GET" } },
|
|
205
|
+
);
|
|
206
|
+
try {
|
|
207
|
+
const state = await siteState(request);
|
|
208
|
+
if (state.kind === "unavailable") return Response.json({ ok: false }, { status: 503, headers });
|
|
209
|
+
return Response.json(
|
|
210
|
+
{ ok: true, state: state.kind === "not-published" ? "not-published" : "published" },
|
|
211
|
+
{ headers },
|
|
212
|
+
);
|
|
213
|
+
} catch (error) {
|
|
214
|
+
console.error("cloudhal: health check could not read the store", error);
|
|
215
|
+
return Response.json({ ok: false }, { status: 503, headers });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
145
218
|
|
|
146
219
|
/** One per isolate: which site a request is for (RFC-0034 §4). */
|
|
147
220
|
function siteDispatch(env , siteIdFromBuild ) {
|
|
@@ -504,8 +577,11 @@ async function serveSite(
|
|
|
504
577
|
const media = siteId ? await serveMedia(request, { siteId }) : undefined;
|
|
505
578
|
const rendered =
|
|
506
579
|
media ??
|
|
507
|
-
|
|
508
|
-
|
|
580
|
+
withErrorPage(
|
|
581
|
+
withSecurityHeaders(
|
|
582
|
+
cacheOnlySuccess((await handle(request, env , ctx)) ),
|
|
583
|
+
),
|
|
584
|
+
request,
|
|
509
585
|
);
|
|
510
586
|
// Server-side render events (§5.4), off the response path: published HTML 200s (cache
|
|
511
587
|
// misses), redirects, 404, 410, 451 and 5xx; never previews or HEAD.
|
|
@@ -529,6 +605,44 @@ async function serveSite(
|
|
|
529
605
|
: stripped;
|
|
530
606
|
}
|
|
531
607
|
|
|
608
|
+
/**
|
|
609
|
+
* RFC-0043 §2.5: the status page for a request the site cannot serve, drawn with the site data
|
|
610
|
+
* the state allows (§1.6) and the theme's hook; counted as a render event like any 5xx (§1.8).
|
|
611
|
+
*/
|
|
612
|
+
async function statusResponse(
|
|
613
|
+
call ,
|
|
614
|
+
state ,
|
|
615
|
+
siteId ,
|
|
616
|
+
) {
|
|
617
|
+
const { request, env, ctx } = call;
|
|
618
|
+
const url = new URL(request.url);
|
|
619
|
+
const kind = state.kind;
|
|
620
|
+
const sites =
|
|
621
|
+
state.kind === "unavailable"
|
|
622
|
+
? {}
|
|
623
|
+
: {
|
|
624
|
+
live: state.site,
|
|
625
|
+
published: state.kind === "preview-expired" ? state.published : undefined,
|
|
626
|
+
};
|
|
627
|
+
const started = Date.now();
|
|
628
|
+
const response = await renderStatus(
|
|
629
|
+
kind,
|
|
630
|
+
statusInput(kind, sites, { host: url.host, pathname: url.pathname }, started),
|
|
631
|
+
{
|
|
632
|
+
hook: await statusHook(),
|
|
633
|
+
method: request.method,
|
|
634
|
+
csp: SITE_CSP,
|
|
635
|
+
onFailure: (m, e) => console.error(m, e),
|
|
636
|
+
},
|
|
637
|
+
);
|
|
638
|
+
const a = state.kind !== "unavailable" ? await siteAnalytics(env, siteId) : undefined;
|
|
639
|
+
if (a?.available)
|
|
640
|
+
ctx.waitUntil(
|
|
641
|
+
a.render(request, response, Date.now() - started).then(() => pendingWrites.settled()),
|
|
642
|
+
);
|
|
643
|
+
return response;
|
|
644
|
+
}
|
|
645
|
+
|
|
532
646
|
export function createSiteWorker(options = {}) {
|
|
533
647
|
const searchLimiter = new SearchLimiter();
|
|
534
648
|
async function route(request , env , ctx ) {
|
|
@@ -541,15 +655,30 @@ export function createSiteWorker(options = {}) {
|
|
|
541
655
|
// runs (Astro's render included) then sees that site.
|
|
542
656
|
const choice = await siteDispatch(env, options.siteId).choose(request);
|
|
543
657
|
if (choice.kind === "unknown") return unknownHost();
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
const
|
|
658
|
+
// Without `CLOUDHAL_SITE_ID` a single-site Worker serves the site it was built for, as
|
|
659
|
+
// Astro's `getSource` always did; `unavailable` is for a site row that is gone (§2.5).
|
|
660
|
+
const siteId = choice.siteId ?? config.siteId;
|
|
661
|
+
const call = { request, env, ctx };
|
|
662
|
+
const run = async () => {
|
|
663
|
+
if (url.pathname === "/__cloudhal/health") return health(request);
|
|
664
|
+
const page =
|
|
665
|
+
(request.method === "GET" || request.method === "HEAD") && isStatusPagePath(url.pathname);
|
|
666
|
+
const state = page ? await siteState(request) : undefined;
|
|
667
|
+
if (state && state.kind !== "serve") return statusResponse(call, state, siteId);
|
|
668
|
+
return serveSite(call, siteId, searchLimiter);
|
|
669
|
+
};
|
|
670
|
+
const response = await withRequestSite(siteId, run);
|
|
547
671
|
return choice.noindex ? withNoindex(response) : response;
|
|
548
672
|
}
|
|
549
673
|
return {
|
|
550
674
|
async fetch(request , env , ctx ) {
|
|
551
675
|
// #62: the edge cache is shared by every host this Worker answers on, unless told to vary.
|
|
552
|
-
|
|
676
|
+
try {
|
|
677
|
+
return varyByHost(await route(request, env, ctx));
|
|
678
|
+
} catch (error) {
|
|
679
|
+
// RFC-0043 §1.8: whatever failed, the visitor gets a page and a reference to quote.
|
|
680
|
+
return varyByHost(errorPage(request, error));
|
|
681
|
+
}
|
|
553
682
|
},
|
|
554
683
|
};
|
|
555
684
|
}
|
package/dist/src/integration.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
1
3
|
|
|
2
4
|
|
|
3
5
|
|
|
@@ -61,6 +63,14 @@ const RESOLVED_CLIENT_ID = `\0${CLIENT_ID}`;
|
|
|
61
63
|
/** Dev only: the built comments module and worker, served from memory by the comments middleware. */
|
|
62
64
|
const COMMENTS_CLIENT_ID = "virtual:cloudhal/comments-client";
|
|
63
65
|
const RESOLVED_COMMENTS_CLIENT_ID = `\0${COMMENTS_CLIENT_ID}`;
|
|
66
|
+
/**
|
|
67
|
+
* RFC-0043 §1.7: a lazy loader of the project's `src/theme.ts` for the status pages' theme hook
|
|
68
|
+
* (root-relative, so Vite resolves it in dev and in the Site Worker build), or of an empty module
|
|
69
|
+
* when the project has no theme module. Evaluated only when a status page is drawn.
|
|
70
|
+
*/
|
|
71
|
+
const THEME_HOOKS_ID = "virtual:cloudhal/theme-hooks";
|
|
72
|
+
const RESOLVED_THEME_HOOKS_ID = `\0${THEME_HOOKS_ID}`;
|
|
73
|
+
const THEME_MODULE = "src/theme.ts";
|
|
64
74
|
|
|
65
75
|
/** The virtual modules: the project config, and in dev the built analytics and comments clients. */
|
|
66
76
|
function configPlugin(modules ) {
|
|
@@ -68,27 +78,46 @@ function configPlugin(modules
|
|
|
68
78
|
[VIRTUAL_ID]: RESOLVED_ID,
|
|
69
79
|
[CLIENT_ID]: RESOLVED_CLIENT_ID,
|
|
70
80
|
[COMMENTS_CLIENT_ID]: RESOLVED_COMMENTS_CLIENT_ID,
|
|
81
|
+
[THEME_HOOKS_ID]: RESOLVED_THEME_HOOKS_ID,
|
|
71
82
|
};
|
|
72
83
|
const bodies = {
|
|
73
84
|
[RESOLVED_ID]: modules.config,
|
|
74
85
|
[RESOLVED_CLIENT_ID]: modules.client,
|
|
75
86
|
[RESOLVED_COMMENTS_CLIENT_ID]: modules.comments,
|
|
76
87
|
};
|
|
88
|
+
let root = process.cwd();
|
|
77
89
|
return {
|
|
78
90
|
name: "cloudhal-config",
|
|
91
|
+
configResolved: (config ) => {
|
|
92
|
+
root = config.root;
|
|
93
|
+
},
|
|
79
94
|
resolveId: (id ) => (Object.hasOwn(ids, id) ? ids[id] : undefined),
|
|
80
|
-
load: (id ) =>
|
|
81
|
-
|
|
95
|
+
load: (id ) => {
|
|
96
|
+
if (id === RESOLVED_THEME_HOOKS_ID)
|
|
97
|
+
return existsSync(path.join(root, THEME_MODULE))
|
|
98
|
+
? `export const loadTheme = () => import("/${THEME_MODULE}");`
|
|
99
|
+
: "export const loadTheme = () => Promise.resolve({});";
|
|
100
|
+
return Object.hasOwn(bodies, id)
|
|
101
|
+
? `export default ${JSON.stringify(bodies[id])};`
|
|
102
|
+
: undefined;
|
|
103
|
+
},
|
|
82
104
|
};
|
|
83
105
|
}
|
|
84
106
|
|
|
85
107
|
/**
|
|
86
108
|
* What only `cloudhal dev` runs as middleware (the Site Worker's entry and builds do these jobs):
|
|
87
109
|
* the analytics beacon (RFC-0006 §5.1); the click-to-load video player (RFC-0015 §4) and the
|
|
88
|
-
* interaction runtime (RFC-0020 §4), which builds write as files;
|
|
89
|
-
* report-only, so the console shows what a deploy would block
|
|
110
|
+
* interaction runtime (RFC-0020 §4), which builds write as files; the Site Worker's CSP sent
|
|
111
|
+
* report-only, so the console shows what a deploy would block; and the status pages' preview
|
|
112
|
+
* route (RFC-0043 §1.8).
|
|
90
113
|
*/
|
|
91
|
-
const DEV_MIDDLEWARE = [
|
|
114
|
+
const DEV_MIDDLEWARE = [
|
|
115
|
+
"analytics-middleware",
|
|
116
|
+
"embed-middleware",
|
|
117
|
+
"csp-middleware",
|
|
118
|
+
// RFC-0043 §1.8: the status pages drawn on demand at `/__cloudhal/status/<state>`.
|
|
119
|
+
"status-middleware",
|
|
120
|
+
].map((m) => ({
|
|
92
121
|
entrypoint: `@cloudhal/astro-renderer/${m}`,
|
|
93
122
|
order: "pre" ,
|
|
94
123
|
}));
|
|
@@ -40,6 +40,32 @@ export declare function withRequestSite<T>(siteId: string, fn: () => T): T;
|
|
|
40
40
|
export declare function withRequestStore<T>(store: SiteGraphStore, siteId: string, fn: () => T): T;
|
|
41
41
|
/** Test/purge hook: forget cached state in this isolate, for one site or all of them. */
|
|
42
42
|
export declare function resetSource(siteId?: string): void;
|
|
43
|
+
/** RFC-0043 §2.5: what the entry answers for this request, decided before Astro runs. */
|
|
44
|
+
export type SiteStateResult = {
|
|
45
|
+
readonly kind: "serve";
|
|
46
|
+
}
|
|
47
|
+
/** The site row is missing (deleted, RFC-0034). */
|
|
48
|
+
| {
|
|
49
|
+
readonly kind: "unavailable";
|
|
50
|
+
}
|
|
51
|
+
/** No published snapshot and no valid preview: `site` is the live node (its name, locales). */
|
|
52
|
+
| {
|
|
53
|
+
readonly kind: "not-published";
|
|
54
|
+
readonly site: Site;
|
|
55
|
+
}
|
|
56
|
+
/** A preview token in the URL that does not verify; `published` is the published snapshot's site node, if any. */
|
|
57
|
+
| {
|
|
58
|
+
readonly kind: "preview-expired";
|
|
59
|
+
readonly site: Site;
|
|
60
|
+
readonly published?: Site | undefined;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* The state of the request's site (RFC-0043 §2.5): `serve` for a published site or a valid
|
|
64
|
+
* preview, `not-published` before the first publish, `preview-expired` for a token in the URL
|
|
65
|
+
* that does not verify (§1.2: it no longer falls back to the published page). Shares the
|
|
66
|
+
* request's resolution with `getSource`.
|
|
67
|
+
*/
|
|
68
|
+
export declare function siteState(request: Request, siteId?: string): Promise<SiteStateResult>;
|
|
43
69
|
/**
|
|
44
70
|
* What site analytics read on the Site Worker (`SiteAnalytics`, RFC-0006 §5.2): D1 for settings and
|
|
45
71
|
* the daily salt, the site row (published pointer, domains) and the isolate's snapshot cache.
|
|
@@ -23,7 +23,7 @@ import { usableCommentsKey } from "./comments.js";
|
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
import { matchMediaRoute, serveMediaRequest } from "./media-route.js";
|
|
26
|
-
import { PREVIEW_PARAM,
|
|
26
|
+
import { PREVIEW_PARAM, SiteResolver } from "./resolver.js";
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
/** RFC-0029 §3: `AI_SEARCH`, `SEARCH_BUCKET` and `CLOUDHAL_SEARCH_*` turn on semantic search. */
|
|
@@ -143,6 +143,66 @@ export function resetSource(siteId ) {
|
|
|
143
143
|
for (const [id, r] of resolvers) if (!siteId || id === siteId) r.invalidate();
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
/**
|
|
147
|
+
* RFC-0043 §1.8: one resolution per request. The entry decides the site's state before Astro
|
|
148
|
+
* runs and Astro's `getSource` resolves the same request, so the verdict (pointer read, preview
|
|
149
|
+
* token) is memoised on the request object; a request Astro re-created simply resolves again.
|
|
150
|
+
*/
|
|
151
|
+
const resolutions = new WeakMap ();
|
|
152
|
+
|
|
153
|
+
function resolveRequest(r , request ) {
|
|
154
|
+
let pending = resolutions.get(request);
|
|
155
|
+
if (!pending) {
|
|
156
|
+
pending = r.resolve(request);
|
|
157
|
+
resolutions.set(request, pending);
|
|
158
|
+
}
|
|
159
|
+
return pending;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** RFC-0043 §2.5: what the entry answers for this request, decided before Astro runs. */
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The state of the request's site (RFC-0043 §2.5): `serve` for a published site or a valid
|
|
178
|
+
* preview, `not-published` before the first publish, `preview-expired` for a token in the URL
|
|
179
|
+
* that does not verify (§1.2: it no longer falls back to the published page). Shares the
|
|
180
|
+
* request's resolution with `getSource`.
|
|
181
|
+
*/
|
|
182
|
+
export async function siteState(request , siteId ) {
|
|
183
|
+
const id = siteOf(siteId);
|
|
184
|
+
if (!id) return { kind: "unavailable" };
|
|
185
|
+
const r = getResolver(id);
|
|
186
|
+
let resolution ;
|
|
187
|
+
try {
|
|
188
|
+
resolution = await resolveRequest(r, request);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (error instanceof Error && /^site .* not found$/.test(error.message))
|
|
191
|
+
return { kind: "unavailable" };
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
if (resolution.kind === "preview") return { kind: "serve" };
|
|
195
|
+
const fromUrl = new URL(request.url).searchParams.get(PREVIEW_PARAM);
|
|
196
|
+
if (resolution.previewError && fromUrl && fromUrl !== "exit")
|
|
197
|
+
return {
|
|
198
|
+
kind: "preview-expired",
|
|
199
|
+
site: await r.site(),
|
|
200
|
+
published: resolution.kind === "published" ? await resolution.source.site() : undefined,
|
|
201
|
+
};
|
|
202
|
+
if (resolution.kind === "unpublished") return { kind: "not-published", site: await r.site() };
|
|
203
|
+
return { kind: "serve" };
|
|
204
|
+
}
|
|
205
|
+
|
|
146
206
|
/**
|
|
147
207
|
* What site analytics read on the Site Worker (`SiteAnalytics`, RFC-0006 §5.2): D1 for settings and
|
|
148
208
|
* the daily salt, the site row (published pointer, domains) and the isolate's snapshot cache.
|
|
@@ -237,7 +297,7 @@ export async function getSource(
|
|
|
237
297
|
if (!astro) throw new Error("on Cloudflare, pass the Astro global: getSource(config, Astro)");
|
|
238
298
|
const siteId = siteOf(config.siteId) ;
|
|
239
299
|
const r = getResolver(siteId);
|
|
240
|
-
const resolution = await r
|
|
300
|
+
const resolution = await resolveRequest(r, astro.request);
|
|
241
301
|
const h = astro.response.headers;
|
|
242
302
|
if (resolution.kind === "preview") {
|
|
243
303
|
h.set("cache-control", "private, no-store");
|
|
@@ -296,7 +356,7 @@ export async function serveMedia(
|
|
|
296
356
|
const siteId = siteOf(options.siteId);
|
|
297
357
|
if (!siteId) return undefined;
|
|
298
358
|
const r = getResolver(siteId);
|
|
299
|
-
const resolution = await r
|
|
359
|
+
const resolution = await resolveRequest(r, request);
|
|
300
360
|
if (resolution.kind === "unpublished")
|
|
301
361
|
return new Response("not found", {
|
|
302
362
|
status: 404,
|
package/dist/src/runtime.d.ts
CHANGED
|
@@ -61,5 +61,23 @@ export declare function analyticsBackend(siteId: string, config?: Partial<Cloudh
|
|
|
61
61
|
export declare function commentsBackend(config: Partial<CloudhalRendererConfig>): Promise<{
|
|
62
62
|
store: SqlCommentStore;
|
|
63
63
|
} | undefined>;
|
|
64
|
+
/** RFC-0043 §2.5: the `workerd` build's verdict shape, for code importing either build. */
|
|
65
|
+
export type SiteStateResult = {
|
|
66
|
+
readonly kind: "serve";
|
|
67
|
+
} | {
|
|
68
|
+
readonly kind: "unavailable";
|
|
69
|
+
} | {
|
|
70
|
+
readonly kind: "not-published";
|
|
71
|
+
readonly site: Site;
|
|
72
|
+
} | {
|
|
73
|
+
readonly kind: "preview-expired";
|
|
74
|
+
readonly site: Site;
|
|
75
|
+
readonly published?: Site | undefined;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* RFC-0043 §1.8: `cloudhal dev` renders the working copy, drafts included, so a request on Node
|
|
79
|
+
* is always served; the status pages are drawn on demand at `/__cloudhal/status/<state>`.
|
|
80
|
+
*/
|
|
81
|
+
export declare function siteState(_request: Request, _siteId?: string): Promise<SiteStateResult>;
|
|
64
82
|
/** Shared with the `workerd` runtime so code importing either build sees the same names. */
|
|
65
83
|
export { CACHE_TAG_PREFIX } from "./cache-tags.js";
|
package/dist/src/runtime.js
CHANGED
|
@@ -158,5 +158,24 @@ export async function commentsBackend(
|
|
|
158
158
|
return { store: new SqlCommentStore((await localStore(config.dataDir)).sql) };
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
+
/** RFC-0043 §2.5: the `workerd` build's verdict shape, for code importing either build. */
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* RFC-0043 §1.8: `cloudhal dev` renders the working copy, drafts included, so a request on Node
|
|
174
|
+
* is always served; the status pages are drawn on demand at `/__cloudhal/status/<state>`.
|
|
175
|
+
*/
|
|
176
|
+
export async function siteState(_request , _siteId ) {
|
|
177
|
+
return { kind: "serve" };
|
|
178
|
+
}
|
|
179
|
+
|
|
161
180
|
/** Shared with the `workerd` runtime so code importing either build sees the same names. */
|
|
162
181
|
export { CACHE_TAG_PREFIX } from "./cache-tags.js";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type StatusDir } from "./status-html.js";
|
|
2
|
+
import { type SiteState, type StatusPageInput, type StatusStrings } from "./status-page.js";
|
|
3
|
+
/** The states a theme may draw. */
|
|
4
|
+
export type HookState = Exclude<SiteState, "error">;
|
|
5
|
+
export interface StatusContext extends StatusPageInput {
|
|
6
|
+
readonly status: 503 | 410;
|
|
7
|
+
readonly dir: StatusDir;
|
|
8
|
+
/** The built-in words, already in the page's locale. */
|
|
9
|
+
readonly strings: StatusStrings;
|
|
10
|
+
/** The owner's message, escaped, line breaks as `<br>` (never use `message.text` raw). */
|
|
11
|
+
readonly messageHtml?: string | undefined;
|
|
12
|
+
/** "Back by …", formatted. */
|
|
13
|
+
readonly untilText?: string | undefined;
|
|
14
|
+
/** The built-in document, with extra CSS appended. */
|
|
15
|
+
defaultHtml(options?: {
|
|
16
|
+
css?: string | undefined;
|
|
17
|
+
}): string;
|
|
18
|
+
}
|
|
19
|
+
export type StatusPageHook = (state: HookState, ctx: StatusContext) => string | undefined | Promise<string | undefined>;
|
|
20
|
+
/** How long a hook may take before the built-in page answers instead. */
|
|
21
|
+
export declare const HOOK_TIMEOUT_MS = 50;
|
|
22
|
+
/** Loads `src/theme.ts` lazily (the integration's `virtual:cloudhal/theme-hooks`) and memoises the hook. */
|
|
23
|
+
export declare function themeStatusHook(loadTheme: () => Promise<unknown>, onError?: (message: string, error: unknown) => void): () => Promise<StatusPageHook | undefined>;
|
|
24
|
+
export interface RenderStatusOptions {
|
|
25
|
+
readonly hook?: StatusPageHook | undefined;
|
|
26
|
+
readonly method?: string | undefined;
|
|
27
|
+
readonly onFailure?: ((message: string, error?: unknown) => void) | undefined;
|
|
28
|
+
/** The site's policy for a theme's document (default `SITE_CSP`). */
|
|
29
|
+
readonly csp?: string | undefined;
|
|
30
|
+
/** Test hook: the hook's time budget. */
|
|
31
|
+
readonly timeoutMs?: number | undefined;
|
|
32
|
+
}
|
|
33
|
+
/** Test hook: forget which states' hook failures were logged. */
|
|
34
|
+
export declare function resetHookFailures(): void;
|
|
35
|
+
/** The status response for `state`: the theme's document when the hook gives one, else the built-in page. */
|
|
36
|
+
export declare function renderStatus(state: SiteState, input: StatusPageInput, options?: RenderStatusOptions): Promise<Response>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The theme hook for status pages (RFC-0043 §1.7): a theme may export `statusPage(state, ctx)`
|
|
3
|
+
* from `src/theme.ts` and return its own document. The renderer keeps the status code, the
|
|
4
|
+
* headers and the CSP (invariant 9); the built-in page is used when the hook returns
|
|
5
|
+
* `undefined`, throws, answers with something other than a string, exceeds 64 KB, or takes more
|
|
6
|
+
* than 50 ms — logged once per state and isolate — and always for `error`, which must not depend
|
|
7
|
+
* on code that may be the cause. Worker-safe.
|
|
8
|
+
*/
|
|
9
|
+
import { SITE_CSP } from "./csp.js";
|
|
10
|
+
import { messageHtml, } from "./status-html.js";
|
|
11
|
+
import {
|
|
12
|
+
HOOK_HTML_LIMIT,
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
statusCode,
|
|
17
|
+
statusPage,
|
|
18
|
+
statusPageHtml,
|
|
19
|
+
statusStrings,
|
|
20
|
+
} from "./status-page.js";
|
|
21
|
+
|
|
22
|
+
/** The states a theme may draw. */
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
/** How long a hook may take before the built-in page answers instead. */
|
|
44
|
+
export const HOOK_TIMEOUT_MS = 50;
|
|
45
|
+
|
|
46
|
+
const failed = new Set ();
|
|
47
|
+
|
|
48
|
+
/** Loads `src/theme.ts` lazily (the integration's `virtual:cloudhal/theme-hooks`) and memoises the hook. */
|
|
49
|
+
export function themeStatusHook(
|
|
50
|
+
loadTheme ,
|
|
51
|
+
onError = () => {},
|
|
52
|
+
) {
|
|
53
|
+
let pending ;
|
|
54
|
+
return () => {
|
|
55
|
+
pending ??= loadTheme().then(
|
|
56
|
+
(mod) => {
|
|
57
|
+
const hook = (mod )?.statusPage;
|
|
58
|
+
return typeof hook === "function" ? (hook ) : undefined;
|
|
59
|
+
},
|
|
60
|
+
(error ) => {
|
|
61
|
+
onError("cloudhal: the theme module could not be loaded for the status page", error);
|
|
62
|
+
return undefined;
|
|
63
|
+
},
|
|
64
|
+
);
|
|
65
|
+
return pending;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
/** Runs the hook within its budget; `undefined` means the built-in page. */
|
|
80
|
+
async function hookHtml(
|
|
81
|
+
state ,
|
|
82
|
+
input ,
|
|
83
|
+
hook ,
|
|
84
|
+
options ,
|
|
85
|
+
) {
|
|
86
|
+
const strings = statusStrings(state, input);
|
|
87
|
+
const ctx = {
|
|
88
|
+
...input,
|
|
89
|
+
status: statusCode(state) ,
|
|
90
|
+
dir: strings.dir,
|
|
91
|
+
strings,
|
|
92
|
+
...(input.message && state === "maintenance"
|
|
93
|
+
? { messageHtml: messageHtml(input.message.text) }
|
|
94
|
+
: {}),
|
|
95
|
+
untilText: strings.untilText,
|
|
96
|
+
defaultHtml: (o = {}) => statusPageHtml(state, input, o),
|
|
97
|
+
};
|
|
98
|
+
let timer ;
|
|
99
|
+
const timeout = new Promise ((_, reject) => {
|
|
100
|
+
timer = setTimeout(
|
|
101
|
+
() => reject(new Error(`took more than ${options.timeoutMs ?? HOOK_TIMEOUT_MS} ms`)),
|
|
102
|
+
options.timeoutMs ?? HOOK_TIMEOUT_MS,
|
|
103
|
+
);
|
|
104
|
+
});
|
|
105
|
+
try {
|
|
106
|
+
const result = await Promise.race([Promise.resolve().then(() => hook(state, ctx)), timeout]);
|
|
107
|
+
if (result === undefined) return undefined;
|
|
108
|
+
if (typeof result !== "string") throw new Error("returned something other than a string");
|
|
109
|
+
if (result.length > HOOK_HTML_LIMIT)
|
|
110
|
+
throw new Error(`returned more than ${HOOK_HTML_LIMIT} bytes`);
|
|
111
|
+
return result;
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (!failed.has(state)) {
|
|
114
|
+
failed.add(state);
|
|
115
|
+
options.onFailure?.(`cloudhal: the theme's statusPage hook failed for ${state}`, error);
|
|
116
|
+
}
|
|
117
|
+
return undefined;
|
|
118
|
+
} finally {
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Test hook: forget which states' hook failures were logged. */
|
|
124
|
+
export function resetHookFailures() {
|
|
125
|
+
failed.clear();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The status response for `state`: the theme's document when the hook gives one, else the built-in page. */
|
|
129
|
+
export async function renderStatus(
|
|
130
|
+
state ,
|
|
131
|
+
input ,
|
|
132
|
+
options = {},
|
|
133
|
+
) {
|
|
134
|
+
if (state === "error" || !options.hook)
|
|
135
|
+
return statusPage(state, input, { method: options.method });
|
|
136
|
+
const html = await hookHtml(state, input, options.hook, options);
|
|
137
|
+
return statusPage(state, input, {
|
|
138
|
+
method: options.method,
|
|
139
|
+
...(html !== undefined ? { html, csp: options.csp ?? SITE_CSP } : {}),
|
|
140
|
+
});
|
|
141
|
+
}
|