@cloudhal/astro-renderer 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -2
  3. package/dist/src/ambient-client.d.ts +17 -0
  4. package/dist/src/ambient-client.js +55 -0
  5. package/dist/src/analytics-client.d.ts +17 -0
  6. package/dist/src/analytics-client.js +96 -0
  7. package/dist/src/analytics-middleware.d.ts +6 -0
  8. package/dist/src/analytics-middleware.js +43 -0
  9. package/dist/src/analytics-node.d.ts +46 -0
  10. package/dist/src/analytics-node.js +134 -0
  11. package/dist/src/analytics.d.ts +117 -0
  12. package/dist/src/analytics.js +372 -0
  13. package/dist/src/archive.d.ts +106 -0
  14. package/dist/src/archive.js +207 -0
  15. package/dist/src/astro-env.d.ts +21 -0
  16. package/dist/src/block-html.d.ts +14 -0
  17. package/dist/src/block-html.js +103 -0
  18. package/dist/src/blocks.d.ts +24 -0
  19. package/dist/src/blocks.js +66 -0
  20. package/dist/src/cache-tags.d.ts +25 -0
  21. package/dist/src/cache-tags.js +59 -0
  22. package/dist/src/carousel-client.d.ts +28 -0
  23. package/dist/src/carousel-client.js +67 -0
  24. package/dist/src/chart.d.ts +34 -0
  25. package/dist/src/chart.js +182 -0
  26. package/dist/src/chrome-client.d.ts +27 -0
  27. package/dist/src/chrome-client.js +64 -0
  28. package/dist/src/cloudflare-entry.d.ts +87 -0
  29. package/dist/src/cloudflare-entry.js +548 -0
  30. package/dist/src/comments-client.d.ts +11 -0
  31. package/dist/src/comments-client.js +58 -0
  32. package/dist/src/comments-html.d.ts +42 -0
  33. package/dist/src/comments-html.js +303 -0
  34. package/dist/src/comments-middleware.d.ts +6 -0
  35. package/dist/src/comments-middleware.js +38 -0
  36. package/dist/src/comments-node.d.ts +42 -0
  37. package/dist/src/comments-node.js +112 -0
  38. package/dist/src/comments-view.d.ts +68 -0
  39. package/dist/src/comments-view.js +174 -0
  40. package/dist/src/comments.d.ts +66 -0
  41. package/dist/src/comments.js +258 -0
  42. package/dist/src/components/Block.astro +39 -0
  43. package/dist/src/components/Body.astro +43 -0
  44. package/dist/src/components/Comments.astro +19 -0
  45. package/dist/src/components/ContentList.astro +31 -0
  46. package/dist/src/components/EntryArticle.astro +31 -0
  47. package/dist/src/components/Hero.astro +36 -0
  48. package/dist/src/components/Image.astro +36 -0
  49. package/dist/src/components/RichText.astro +19 -0
  50. package/dist/src/components/Sections.astro +66 -0
  51. package/dist/src/components/SeoHead.astro +22 -0
  52. package/dist/src/components/Surface.astro +36 -0
  53. package/dist/src/components/SurfaceNode.astro +82 -0
  54. package/dist/src/components/index.d.ts +12 -0
  55. package/dist/src/components/index.js +12 -0
  56. package/dist/src/csp.d.ts +20 -0
  57. package/dist/src/csp.js +28 -0
  58. package/dist/src/embed-client.d.ts +38 -0
  59. package/dist/src/embed-client.js +98 -0
  60. package/dist/src/embed-middleware.d.ts +9 -0
  61. package/dist/src/embed-middleware.js +49 -0
  62. package/dist/src/feeds.d.ts +72 -0
  63. package/dist/src/feeds.js +246 -0
  64. package/dist/src/gates.d.ts +25 -0
  65. package/dist/src/gates.js +63 -0
  66. package/dist/src/index.d.ts +17 -0
  67. package/dist/src/index.js +17 -0
  68. package/dist/src/integration.d.ts +55 -0
  69. package/dist/src/integration.js +244 -0
  70. package/dist/src/kit.d.ts +48 -0
  71. package/dist/src/kit.js +83 -0
  72. package/dist/src/locale-feeds.d.ts +29 -0
  73. package/dist/src/locale-feeds.js +152 -0
  74. package/dist/src/locale-middleware.d.ts +5 -0
  75. package/dist/src/locale-middleware.js +26 -0
  76. package/dist/src/locales.d.ts +87 -0
  77. package/dist/src/locales.js +336 -0
  78. package/dist/src/markdown.d.ts +83 -0
  79. package/dist/src/markdown.js +533 -0
  80. package/dist/src/media-middleware.d.ts +5 -0
  81. package/dist/src/media-middleware.js +18 -0
  82. package/dist/src/media-route.d.ts +47 -0
  83. package/dist/src/media-route.js +238 -0
  84. package/dist/src/media.d.ts +109 -0
  85. package/dist/src/media.js +298 -0
  86. package/dist/src/motion-client.d.ts +39 -0
  87. package/dist/src/motion-client.js +115 -0
  88. package/dist/src/navigation.d.ts +127 -0
  89. package/dist/src/navigation.js +382 -0
  90. package/dist/src/not-found.d.ts +16 -0
  91. package/dist/src/not-found.js +41 -0
  92. package/dist/src/overlay-client.d.ts +20 -0
  93. package/dist/src/overlay-client.js +49 -0
  94. package/dist/src/prefs-client.d.ts +14 -0
  95. package/dist/src/prefs-client.js +18 -0
  96. package/dist/src/preview.d.ts +70 -0
  97. package/dist/src/preview.js +551 -0
  98. package/dist/src/resolver.d.ts +71 -0
  99. package/dist/src/resolver.js +206 -0
  100. package/dist/src/routing.d.ts +108 -0
  101. package/dist/src/routing.js +285 -0
  102. package/dist/src/runtime-workerd.d.ts +87 -0
  103. package/dist/src/runtime-workerd.js +275 -0
  104. package/dist/src/runtime.d.ts +59 -0
  105. package/dist/src/runtime.js +153 -0
  106. package/dist/src/safe-urls.d.ts +13 -0
  107. package/dist/src/safe-urls.js +35 -0
  108. package/dist/src/sanitize.d.ts +7 -0
  109. package/dist/src/sanitize.js +217 -0
  110. package/dist/src/search-client.d.ts +29 -0
  111. package/dist/src/search-client.js +92 -0
  112. package/dist/src/search-limit.d.ts +36 -0
  113. package/dist/src/search-limit.js +66 -0
  114. package/dist/src/search.d.ts +64 -0
  115. package/dist/src/search.js +155 -0
  116. package/dist/src/seo.d.ts +85 -0
  117. package/dist/src/seo.js +468 -0
  118. package/dist/src/site-dispatch.d.ts +37 -0
  119. package/dist/src/site-dispatch.js +86 -0
  120. package/dist/src/site-hosts.d.ts +35 -0
  121. package/dist/src/site-hosts.js +110 -0
  122. package/dist/src/source.d.ts +227 -0
  123. package/dist/src/source.js +794 -0
  124. package/dist/src/static-gates.d.ts +3 -0
  125. package/dist/src/static-gates.js +28 -0
  126. package/dist/src/static-headers.d.ts +30 -0
  127. package/dist/src/static-headers.js +140 -0
  128. package/dist/src/static-media.d.ts +4 -0
  129. package/dist/src/static-media.js +65 -0
  130. package/dist/src/static-redirects.d.ts +4 -0
  131. package/dist/src/static-redirects.js +40 -0
  132. package/dist/src/surface-client.d.ts +34 -0
  133. package/dist/src/surface-client.js +146 -0
  134. package/dist/src/surfaces/html.d.ts +35 -0
  135. package/dist/src/surfaces/html.js +184 -0
  136. package/dist/src/surfaces/markup.d.ts +57 -0
  137. package/dist/src/surfaces/markup.js +135 -0
  138. package/dist/src/surfaces/motion.d.ts +33 -0
  139. package/dist/src/surfaces/motion.js +132 -0
  140. package/dist/src/surfaces/primitives/carousel.d.ts +2 -0
  141. package/dist/src/surfaces/primitives/carousel.js +95 -0
  142. package/dist/src/surfaces/primitives/content.d.ts +13 -0
  143. package/dist/src/surfaces/primitives/content.js +159 -0
  144. package/dist/src/surfaces/primitives/data.d.ts +5 -0
  145. package/dist/src/surfaces/primitives/data.js +80 -0
  146. package/dist/src/surfaces/primitives/index.d.ts +54 -0
  147. package/dist/src/surfaces/primitives/index.js +106 -0
  148. package/dist/src/surfaces/primitives/inputs.d.ts +8 -0
  149. package/dist/src/surfaces/primitives/inputs.js +68 -0
  150. package/dist/src/surfaces/primitives/layout.d.ts +14 -0
  151. package/dist/src/surfaces/primitives/layout.js +61 -0
  152. package/dist/src/surfaces/primitives/motion.d.ts +9 -0
  153. package/dist/src/surfaces/primitives/motion.js +45 -0
  154. package/dist/src/surfaces/primitives/overlays.d.ts +6 -0
  155. package/dist/src/surfaces/primitives/overlays.js +79 -0
  156. package/dist/src/surfaces/tree.d.ts +107 -0
  157. package/dist/src/surfaces/tree.js +321 -0
  158. package/dist/src/surfaces.d.ts +14 -0
  159. package/dist/src/surfaces.js +33 -0
  160. package/dist/src/taxonomy.d.ts +86 -0
  161. package/dist/src/taxonomy.js +268 -0
  162. package/dist/src/theme-settings.d.ts +24 -0
  163. package/dist/src/theme-settings.js +111 -0
  164. package/package.json +219 -3
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Reader comments in a page (RFC-0007 §8.1), the theme boundary: an article route calls
3
+ * `loadComments` in its frontmatter (response headers can only be set there) and places
4
+ * `<Comments view={…} />` after the article.
5
+ *
6
+ * ```astro
7
+ * const comments = route.kind === "entry" ? await loadComments(config, Astro, route.entry) : undefined;
8
+ * if (comments?.notFound) return new Response(null, { status: 404 });
9
+ * …
10
+ * <Comments view={comments} />
11
+ * ```
12
+ *
13
+ * `loadComments`:
14
+ * - returns `undefined` when the deployment has no comments (no usable `CLOUDHAL_COMMENTS_KEY` on
15
+ * Cloudflare, `comments.available: false`, or a static build, which has no endpoint);
16
+ * - tags the response `cloudhal-comments-<entryId>` (published responses on Cloudflare only), so
17
+ * moderation purges that article and its comment pages, never archives or feeds — every entry
18
+ * page carries it, so turning comments on for a collection reaches pages cached while it was off;
19
+ * - previews (and drafts in `cloudhal dev`) get a placeholder and never read comments;
20
+ * - otherwise reads the settings, the thread row and one page of approved comments
21
+ * (`?comments=<n>`, 50 top-level comments a page; an out-of-range page is `notFound`, which the
22
+ * route answers with a `404`, never cached) and computes the thread state with `threadState`;
23
+ * - on a page with an **open** form on a Turnstile site, sets the page's own CSP with Turnstile's
24
+ * origin added (every other page keeps the default).
25
+ *
26
+ * A read error renders no section (fail closed); the page itself still renders.
27
+ */
28
+
29
+ import { commentsBackend } from "@cloudhal/astro-renderer/runtime";
30
+ import {
31
+
32
+
33
+
34
+ threadState,
35
+ withoutScriptAllowed,
36
+ } from "@cloudhal/comments";
37
+
38
+ import { addCacheTags, commentsCacheTag } from "./cache-tags.js";
39
+ import { turnstileCsp } from "./csp.js";
40
+
41
+ import { entryPath } from "./routing.js";
42
+
43
+ export { commentStrings, commentsHtml } from "./comments-html.js";
44
+
45
+ /** What `<Comments />` renders. */
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+ /** Minimal shape of the Astro global the page passes in. */
65
+
66
+
67
+
68
+
69
+
70
+
71
+ const PAGE_PARAM = "comments";
72
+
73
+ /** `?comments=<n>`: `1` when absent, `undefined` when malformed. */
74
+ export function commentsPageParam(url ) {
75
+ const raw = url.searchParams.get(PAGE_PARAM);
76
+ if (raw === null) return 1;
77
+ return /^[1-9][0-9]{0,4}$/.test(raw) ? Number(raw) : undefined;
78
+ }
79
+
80
+ /** The JSON-LD the article's `BlogPosting` gains (§8.1): `commentCount` and the first 10. */
81
+ export function commentsJsonLd(
82
+ view ,
83
+ origin ,
84
+ ) {
85
+ if (!view?.page || (view.state !== "open" && view.state !== "closed")) return undefined;
86
+ const url = `${origin}${view.path}`;
87
+ const comments = view.page.items
88
+ .flatMap((i) => ("comment" in i ? [i.comment, ...i.replies] : i.replies))
89
+ .slice(0, 10)
90
+ .map((c) => ({
91
+ "@type": "Comment",
92
+ url: `${url}#comment-${c.id}`,
93
+ dateCreated: c.createdAt,
94
+ ...(c.body ? { text: c.body.text } : {}),
95
+ author: {
96
+ "@type": "Person",
97
+ name: c.author.kind === "erased" ? "Anonymous" : c.author.name,
98
+ },
99
+ }));
100
+ return {
101
+ commentCount: view.page.total,
102
+ ...(comments.length ? { comment: comments } : {}),
103
+ };
104
+ }
105
+
106
+ export async function loadComments(
107
+ config ,
108
+ astro ,
109
+ entry ,
110
+ options = {},
111
+ ) {
112
+ const backend = await commentsBackend(config);
113
+ if (!backend) return undefined;
114
+ const headers = astro.response.headers;
115
+ addCacheTags(headers, [commentsCacheTag(entry.id)]);
116
+ const base = {
117
+ nodeId: entry.id,
118
+ path: entryPath(entry),
119
+ locale: options.locale ?? entry.locale,
120
+ ...(config.commentsScript ? { script: config.commentsScript } : {}),
121
+ };
122
+ const preview = () => ({
123
+ ...base,
124
+ state: "preview",
125
+ protection: "pow",
126
+ turnstileSiteKey: null,
127
+ allowWithoutScript: true,
128
+ notFound: false,
129
+ });
130
+ // Previews never read comments; in `cloudhal dev` (live source) a draft is a preview too.
131
+ if (headers.get("x-cloudhal-mode") === "preview" || entry.status !== "published")
132
+ return preview();
133
+ const pageNumber = commentsPageParam(astro.url);
134
+ let settings ;
135
+ let page ;
136
+ let state ;
137
+ try {
138
+ const store = backend.store;
139
+ const [s, thread] = await Promise.all([
140
+ store.settings(entry.siteId),
141
+ store.thread(entry.siteId, entry.id),
142
+ ]);
143
+ settings = s;
144
+ page = await store.renderPage(entry.siteId, entry.id, pageNumber ?? 1);
145
+ state = threadState({
146
+ settings,
147
+ entry: {
148
+ nodeId: entry.id,
149
+ collection: entry.collection,
150
+ publishedAt: entry.publishedAt ?? null,
151
+ },
152
+ thread,
153
+ hasApproved: page.total > 0,
154
+ now: options.now ?? new Date(),
155
+ });
156
+ } catch (error) {
157
+ console.warn(`cloudhal: comments of ${entry.id} could not be read`, error);
158
+ return undefined;
159
+ }
160
+ const visible = state === "open" || state === "closed";
161
+ const notFound =
162
+ pageNumber === undefined || (pageNumber > 1 && (!visible || pageNumber > page.pageCount));
163
+ if (state === "open" && settings.protection === "turnstile" && settings.turnstileSiteKey)
164
+ headers.set("content-security-policy", turnstileCsp());
165
+ return {
166
+ ...base,
167
+ state,
168
+ page,
169
+ protection: settings.protection,
170
+ turnstileSiteKey: settings.turnstileSiteKey,
171
+ allowWithoutScript: withoutScriptAllowed(settings),
172
+ notFound,
173
+ };
174
+ }
@@ -0,0 +1,66 @@
1
+ import type { SqlCommentStore } from "@cloudhal/comments/sql";
2
+ import type { Site } from "@cloudhal/core-contracts";
3
+ import type { GraphSource } from "./source.js";
4
+ export declare const COMMENTS_PATH = "/__cloudhal/comments";
5
+ export declare const COMMENTS_REPORT_PATH = "/__cloudhal/comments/report";
6
+ export declare const COMMENTS_CHALLENGE_PATH = "/__cloudhal/comments/challenge";
7
+ /** The name of the owner's Turnstile secret in `comment_secrets` (RFC-0007 §7.6, §12). */
8
+ export declare const TURNSTILE_SECRET_NAME = "turnstile-secret";
9
+ export declare const TURNSTILE_SITEVERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
10
+ /** Settings and the published pointer are re-read at most this often per isolate (§6.2). */
11
+ export declare const COMMENTS_MEMO_MS = 60000;
12
+ /** Whether a path is one of the comment endpoints. */
13
+ export declare const isCommentsPath: (pathname: string) => boolean;
14
+ /** Whether a deployment secret can carry the comment keys (else comments are off). */
15
+ export declare const usableCommentsKey: (secret: string | undefined) => secret is string;
16
+ /** A Workers Rate Limiting binding (`limit({ key })`), optional (`comments.rateLimit`). */
17
+ export interface CommentsRateLimit {
18
+ limit(options: {
19
+ key: string;
20
+ }): Promise<{
21
+ success: boolean;
22
+ }>;
23
+ }
24
+ export interface SiteCommentsOptions {
25
+ readonly siteId: string;
26
+ /** `CLOUDHAL_COMMENTS_KEY`. Absent or too short: comments are off (no crash). */
27
+ readonly secret: string | undefined;
28
+ /** The deployment switch (`comments.available`; the integration built the module). */
29
+ readonly available: boolean;
30
+ /** The comment store (D1 on Cloudflare, the local SQLite store on Node). */
31
+ readonly store: () => Promise<SqlCommentStore>;
32
+ /** The site row as stored now (published pointer, domains). */
33
+ readonly site: () => Promise<Site | undefined>;
34
+ /** The source of a snapshot (cached by the caller; snapshots are immutable). */
35
+ readonly snapshot: (id: string) => Promise<GraphSource>;
36
+ /** Hosts the site answers on besides `Site.domains` (`CLOUDHAL_SITE_HOSTS`). */
37
+ readonly hosts?: readonly string[];
38
+ /** Also accept the request's own host (`*.workers.dev` on Cloudflare; every host on Node). */
39
+ readonly acceptRequestHost?: (host: string) => boolean;
40
+ /** The optional cross-isolate limiter, keyed by an HMAC under the comments key (never the IP). */
41
+ readonly rateLimit?: CommentsRateLimit | undefined;
42
+ /** For Turnstile's `siteverify` (tests replace it). */
43
+ readonly fetch?: typeof fetch;
44
+ readonly now?: () => Date;
45
+ readonly onError?: (message: string, error?: unknown) => void;
46
+ }
47
+ /**
48
+ * Per-isolate comment state of one site. Create one per isolate (module scope) and `reset()` it on
49
+ * a purge (a settings change purges, so the next request re-reads them).
50
+ */
51
+ export declare class SiteComments {
52
+ #private;
53
+ constructor(options: SiteCommentsOptions);
54
+ /** Comments can be answered at all: the deployment has them and a usable key. */
55
+ get available(): boolean;
56
+ /** Forget the memoised settings and pointer (after a purge). */
57
+ reset(): void;
58
+ /**
59
+ * Answers a comment endpoint, or `undefined` for any other path. `clientAddress` is the address
60
+ * the runtime vouches for (Cloudflare's `CF-Connecting-IP`, Node's socket address); request
61
+ * headers are never trusted for it. Every answer is `no-store`.
62
+ */
63
+ handle(request: Request, extra?: {
64
+ clientAddress?: string | undefined;
65
+ }): Promise<Response | undefined>;
66
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Reader comments on the site (RFC-0007 §6, rollout step 4), shared by the Cloudflare Site Worker
3
+ * entry and the Node middleware (`cloudhal dev`, Node self-host). Worker-safe: no Node module.
4
+ *
5
+ * `SiteComments` holds one site's per-isolate state — the derived keys, the isolate rate limits,
6
+ * today's stored count, the replay cache, the memoised settings and published pointer — and answers
7
+ * the three endpoints before Astro, never cached:
8
+ *
9
+ * - `GET /__cloudhal/comments/challenge?node=…&for=comment|report` — a signed proof-of-work
10
+ * challenge (`no-store`, no write);
11
+ * - `POST /__cloudhal/comments` — a comment or reply (form posts get `303` to a fragment of the
12
+ * entry's cached page, JSON posts a JSON answer);
13
+ * - `POST /__cloudhal/comments/report` — a report (DSA Art. 16).
14
+ *
15
+ * Everything else is `@cloudhal/comments`' pipeline (`handleCommentSubmission`, …): this module
16
+ * only wires it. The entry is resolved in the **published** snapshot (a draft's id is `404`), the
17
+ * client address is the one the runtime vouches for (`CF-Connecting-IP` on Cloudflare, the socket
18
+ * address on Node; never another header), `site_id` is the Worker's own. Without a usable comments
19
+ * key (`CLOUDHAL_COMMENTS_KEY`, ≥ 32 characters) the endpoints answer `404`: comments are off.
20
+ */
21
+ import {
22
+
23
+ CommentLimiter,
24
+ challengeResponse,
25
+ DailyCount,
26
+ deriveCommentKeys,
27
+ handleChallengeRequest,
28
+ handleCommentSubmission,
29
+ handleReportSubmission,
30
+ MIN_SECRET_LENGTH,
31
+ memoize,
32
+
33
+
34
+ ReplayCache,
35
+ rateLimitKey,
36
+ submissionResponse,
37
+
38
+ } from "@cloudhal/comments";
39
+
40
+
41
+ import { entryPath } from "./routing.js";
42
+
43
+
44
+ export const COMMENTS_PATH = "/__cloudhal/comments";
45
+ export const COMMENTS_REPORT_PATH = "/__cloudhal/comments/report";
46
+ export const COMMENTS_CHALLENGE_PATH = "/__cloudhal/comments/challenge";
47
+ /** The name of the owner's Turnstile secret in `comment_secrets` (RFC-0007 §7.6, §12). */
48
+ export const TURNSTILE_SECRET_NAME = "turnstile-secret";
49
+ export const TURNSTILE_SITEVERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
50
+ /** Settings and the published pointer are re-read at most this often per isolate (§6.2). */
51
+ export const COMMENTS_MEMO_MS = 60_000;
52
+
53
+ /** Whether a path is one of the comment endpoints. */
54
+ export const isCommentsPath = (pathname ) =>
55
+ pathname === COMMENTS_PATH ||
56
+ pathname === COMMENTS_REPORT_PATH ||
57
+ pathname === COMMENTS_CHALLENGE_PATH;
58
+
59
+ /** Whether a deployment secret can carry the comment keys (else comments are off). */
60
+ export const usableCommentsKey = (secret ) =>
61
+ typeof secret === "string" && secret.length >= MIN_SECRET_LENGTH;
62
+
63
+ /** A Workers Rate Limiting binding (`limit({ key })`), optional (`comments.rateLimit`). */
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+ const notFound = () =>
93
+ Response.json({ error: "not_found" }, { status: 404, headers: { "cache-control": "no-store" } });
94
+
95
+ /**
96
+ * Per-isolate comment state of one site. Create one per isolate (module scope) and `reset()` it on
97
+ * a purge (a settings change purges, so the next request re-reads them).
98
+ */
99
+ export class SiteComments {
100
+ #o ;
101
+ #now ;
102
+ #limiter = new CommentLimiter();
103
+ #daily = new DailyCount();
104
+ #replay = new ReplayCache();
105
+ #settings ;
106
+ #site ;
107
+ #keys ;
108
+
109
+ constructor(options ) {
110
+ this.#o = options;
111
+ this.#now = options.now ?? (() => new Date());
112
+ const now = () => this.#now().getTime();
113
+ this.#settings = memoize(async () => (await options.store()).settings(options.siteId), {
114
+ ttlMs: COMMENTS_MEMO_MS,
115
+ now,
116
+ });
117
+ this.#site = memoize(() => options.site(), { ttlMs: COMMENTS_MEMO_MS, now });
118
+ }
119
+
120
+ /** Comments can be answered at all: the deployment has them and a usable key. */
121
+ get available() {
122
+ return this.#o.available && usableCommentsKey(this.#o.secret);
123
+ }
124
+
125
+ /** Forget the memoised settings and pointer (after a purge). */
126
+ reset() {
127
+ this.#settings.reset();
128
+ this.#site.reset();
129
+ }
130
+
131
+ #deriveKeys() {
132
+ this.#keys ??= deriveCommentKeys(this.#o.secret );
133
+ this.#keys.catch(() => {
134
+ this.#keys = undefined;
135
+ });
136
+ return this.#keys;
137
+ }
138
+
139
+ /** The published entry with this id (`null` for drafts, other sites and unknown ids). */
140
+ async #resolveEntry(nodeId ) {
141
+ const site = await this.#site();
142
+ if (!site?.publishedSnapshotId) return null;
143
+ const source = await this.#o.snapshot(site.publishedSnapshotId);
144
+ const entry = await source.entryById?.(nodeId);
145
+ if (entry?.status !== "published" || entry.siteId !== this.#o.siteId) return null;
146
+ return {
147
+ nodeId: entry.id,
148
+ collection: entry.collection,
149
+ path: entryPath(entry),
150
+ publishedAt: entry.publishedAt ?? null,
151
+ };
152
+ }
153
+
154
+ async #hosts(requestHost ) {
155
+ let site ;
156
+ try {
157
+ site = await this.#site();
158
+ } catch (error) {
159
+ this.#o.onError?.("comments: reading the site failed", error);
160
+ }
161
+ const hosts = [
162
+ ...(site?.domains ?? []).map((d) => d.hostname.toLowerCase()),
163
+ ...(this.#o.hosts ?? []).map((h) => h.toLowerCase()),
164
+ ];
165
+ const host = requestHost.toLowerCase();
166
+ if (this.#o.acceptRequestHost?.(host.replace(/:\d+$/, ""))) hosts.push(host);
167
+ return hosts;
168
+ }
169
+
170
+ async #deps(request , clientAddress ) {
171
+ const keys = await this.#deriveKeys();
172
+ const store = await this.#o.store();
173
+ const siteId = this.#o.siteId;
174
+ const binding = this.#o.rateLimit;
175
+ const doFetch = this.#o.fetch ?? fetch;
176
+ return {
177
+ siteId,
178
+ available: this.available,
179
+ hosts: await this.#hosts(request.headers.get("host") ?? new URL(request.url).host),
180
+ clientAddress,
181
+ keys,
182
+ now: this.#now,
183
+ settings: () => this.#settings(),
184
+ resolveEntry: (nodeId) => this.#resolveEntry(nodeId),
185
+ store,
186
+ limiter: this.#limiter,
187
+ daily: this.#daily,
188
+ replay: this.#replay,
189
+ ...(binding
190
+ ? {
191
+ // the isolate's client key differs per isolate; the binding needs one key per client
192
+ // across isolates: an HMAC of the client's network under a key derived from the
193
+ // deployment secret for this purpose (never the raw secret)
194
+ rateLimit: async () =>
195
+ (await binding.limit({ key: await rateLimitKey(keys, clientAddress) })).success,
196
+ }
197
+ : {}),
198
+ turnstile: async ({ token, remoteip, idempotencyKey }) => {
199
+ const turnstileSecret = await store.readSecret(siteId, TURNSTILE_SECRET_NAME, keys);
200
+ if (!turnstileSecret) throw new Error("no Turnstile secret is stored for this site");
201
+ const body = new FormData();
202
+ body.set("secret", turnstileSecret);
203
+ body.set("response", token);
204
+ body.set("remoteip", remoteip);
205
+ body.set("idempotency_key", idempotencyKey);
206
+ const res = await doFetch(TURNSTILE_SITEVERIFY, { method: "POST", body });
207
+ if (!res.ok) throw new Error(`siteverify answered ${res.status}`);
208
+ const answer = (await res.json()) ;
209
+ return {
210
+ success: answer.success === true,
211
+ ...(typeof answer.hostname === "string" ? { hostname: answer.hostname } : {}),
212
+ ...(typeof answer.action === "string" ? { action: answer.action } : {}),
213
+ };
214
+ },
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Answers a comment endpoint, or `undefined` for any other path. `clientAddress` is the address
220
+ * the runtime vouches for (Cloudflare's `CF-Connecting-IP`, Node's socket address); request
221
+ * headers are never trusted for it. Every answer is `no-store`.
222
+ */
223
+ async handle(
224
+ request ,
225
+ extra = {},
226
+ ) {
227
+ const url = new URL(request.url);
228
+ const path = url.pathname;
229
+ if (!isCommentsPath(path)) return undefined;
230
+ if (!this.available) return notFound();
231
+ // The same-origin check compares `Host` with the site's hosts. The runtime builds the URL from
232
+ // that header (Cloudflare, Node), so they agree in production; a proxy in front (a test
233
+ // harness, a local tunnel) keeps the routed URL but may send its own `Host`. The URL decides.
234
+ const host = request.headers.get("host");
235
+ if (host !== null && host.toLowerCase() !== url.host.toLowerCase()) {
236
+ const headers = new Headers(request.headers);
237
+ headers.set("host", url.host);
238
+ request = new Request(request, { headers });
239
+ }
240
+ try {
241
+ // Without an address every client shares one bucket: stricter, never looser.
242
+ const deps = await this.#deps(request, extra.clientAddress?.trim() || "unknown");
243
+ if (path === COMMENTS_CHALLENGE_PATH)
244
+ return challengeResponse(await handleChallengeRequest(request, deps));
245
+ if (path === COMMENTS_REPORT_PATH)
246
+ return submissionResponse(await handleReportSubmission(request, deps), {
247
+ pendingFragment: "comment-reported",
248
+ });
249
+ return submissionResponse(await handleCommentSubmission(request, deps));
250
+ } catch (error) {
251
+ this.#o.onError?.("comments: request failed", error);
252
+ return Response.json(
253
+ { error: "try_again" },
254
+ { status: 503, headers: { "cache-control": "no-store" } },
255
+ );
256
+ }
257
+ }
258
+ }
@@ -0,0 +1,39 @@
1
+ ---
2
+ /**
3
+ * A component section (RFC-0015 §5): the theme's own component for the type when it maps one
4
+ * (`blocks` in theme.ts, given `{ section, props, content, contentHtml, media }`), else Cloudhal's
5
+ * built-in markup (`renderComponentSection`). Props are checked against the type first (the
6
+ * theme's types from `src/blocks.ts`); unknown types and props that do not fit render nothing.
7
+ */
8
+ import type { ComponentSection } from "@cloudhal/core-contracts";
9
+ import type { BlockType } from "@cloudhal/core-ts/blocks";
10
+ import { renderComponentSection, themeRegistry } from "../blocks.js";
11
+ import { renderMarkdown } from "../markdown.js";
12
+ import type { MediaContext } from "../media.js";
13
+
14
+ interface Props {
15
+ section: ComponentSection;
16
+ media?: MediaContext;
17
+ /** The theme's components by block type name. */
18
+ blocks?: Record<string, unknown>;
19
+ /** The theme's block types (`src/blocks.ts`). */
20
+ blockTypes?: readonly BlockType[];
21
+ }
22
+ const { section, media, blocks = {}, blockTypes } = Astro.props;
23
+ type AnyComponent = (props: never) => unknown;
24
+ const registry = themeRegistry(blockTypes);
25
+ const Own = blocks[section.type] as AnyComponent | undefined;
26
+ // A type the theme declares must fit; one it only maps a component for is its own business.
27
+ const fits = (registry.checkSection(section.type, section.props) ?? []).length === 0;
28
+ const content = typeof section.props.content === "string" ? section.props.content : undefined;
29
+ const contentHtml = content !== undefined ? renderMarkdown(content, media) : undefined;
30
+ ---
31
+ {Own ? (
32
+ fits && (
33
+ <section class="ch-block" data-section-id={section.id} data-kind="component" data-block-type={section.type}>
34
+ <Own section={section} props={section.props} content={content} contentHtml={contentHtml} media={media} />
35
+ </section>
36
+ )
37
+ ) : (
38
+ <Fragment set:html={renderComponentSection(section, { registry, ...(media ? { media } : {}) })} />
39
+ )}
@@ -0,0 +1,43 @@
1
+ ---
2
+ /**
3
+ * A markdown or HTML body (RFC-0015 §5): Cloudhal's safe renderer, with the block types the theme
4
+ * renders itself (`blocks` in theme.ts, declared in `src/blocks.ts`) placed as its components.
5
+ * They get `{ props, content, contentHtml, media }`: `content` is a container's inner markdown,
6
+ * `contentHtml` the same rendered safely. Props were checked against the type first.
7
+ */
8
+ import type { SurfaceSection } from "@cloudhal/core-contracts";
9
+ import type { BlockType } from "@cloudhal/core-ts/blocks";
10
+ import { themeRegistry } from "../blocks.js";
11
+ import { renderBodyParts, SURFACE_SLOT } from "../markdown.js";
12
+ import type { MediaContext } from "../media.js";
13
+ import Surface from "./Surface.astro";
14
+
15
+ interface Props {
16
+ body: { format: "markdown" | "html"; value: string };
17
+ media?: MediaContext;
18
+ /** The theme's components by block type name. */
19
+ blocks?: Record<string, unknown>;
20
+ /** The theme's block types (`src/blocks.ts`). */
21
+ blockTypes?: readonly BlockType[];
22
+ }
23
+ const { body, media, blocks = {}, blockTypes } = Astro.props;
24
+ type AnyComponent = (props: never) => unknown;
25
+ const names = new Set(Object.keys(blocks));
26
+ const parts = renderBodyParts(
27
+ body,
28
+ media,
29
+ names.size ? { registry: themeRegistry(blockTypes), components: names } : undefined,
30
+ );
31
+ ---
32
+ {parts.map((part) => {
33
+ if ("html" in part) return <Fragment set:html={part.html} />;
34
+ // RFC-0020 §5: a ```surface fence, drawn with the theme's components where it has them.
35
+ if (part.slot.type === SURFACE_SLOT)
36
+ return <Surface section={part.slot.props.surface as SurfaceSection} blocks={blocks} blockTypes={blockTypes} media={media} />;
37
+ const Own = blocks[part.slot.type] as AnyComponent;
38
+ return (
39
+ <div class="ch-block" data-block-type={part.slot.type}>
40
+ <Own props={part.slot.props} content={part.slot.content} contentHtml={part.slot.contentHtml} media={media} />
41
+ </div>
42
+ );
43
+ })}
@@ -0,0 +1,19 @@
1
+ ---
2
+ /**
3
+ * Reader comments under an article (RFC-0007 §8.1): approved comments, the plain HTML form on open
4
+ * threads, "Comments are closed" on closed ones, nothing on hidden or off ones, a placeholder in
5
+ * previews. The route loads the view in its frontmatter with `loadComments` (it sets the cache tag
6
+ * and, for Turnstile sites, the page's CSP); themes place this and style the `cloudhal-comment*`
7
+ * classes. Words default to the entry's locale (English or Turkish); pass `strings` to override.
8
+ */
9
+ import type { CommentStrings } from "../comments-html.js";
10
+ import { commentsHtml } from "../comments-html.js";
11
+ import type { CommentsView } from "../comments-view.js";
12
+
13
+ interface Props {
14
+ view: CommentsView | undefined;
15
+ strings?: CommentStrings;
16
+ }
17
+ const { view, strings } = Astro.props;
18
+ ---
19
+ <Fragment set:html={commentsHtml(view, strings)} />
@@ -0,0 +1,31 @@
1
+ ---
2
+ import type { ContentEntry, ContentListSection } from "@cloudhal/core-contracts";
3
+
4
+ interface Props {
5
+ section: ContentListSection;
6
+ entries: ContentEntry[];
7
+ hrefFor?: (entry: ContentEntry) => string;
8
+ }
9
+ const { section, entries, hrefFor = (e) => `/${e.collection}/${e.slug}` } = Astro.props;
10
+ const sorted = [...entries]
11
+ .sort((a, b) =>
12
+ section.sort === "title"
13
+ ? a.title.localeCompare(b.title)
14
+ : section.sort === "oldest"
15
+ ? (a.publishedAt ?? a.createdAt).localeCompare(b.publishedAt ?? b.createdAt)
16
+ : (b.publishedAt ?? b.createdAt).localeCompare(a.publishedAt ?? a.createdAt),
17
+ )
18
+ .slice(0, section.limit);
19
+ ---
20
+ <section class="ch-contentlist" data-section-id={section.id} data-kind="contentList" data-collection={section.collection}>
21
+ {sorted.length === 0 ? <p class="ch-contentlist__empty">Nothing published yet.</p> : (
22
+ <ul>
23
+ {sorted.map((e) => (
24
+ <li>
25
+ <a href={hrefFor(e)}>{e.title}</a>
26
+ {e.summary && <p>{e.summary}</p>}
27
+ </li>
28
+ ))}
29
+ </ul>
30
+ )}
31
+ </section>
@@ -0,0 +1,31 @@
1
+ ---
2
+ /**
3
+ * An article page's content (`renderEntryArticle`'s markup) with the theme's own block components
4
+ * inside the body (RFC-0015 §5, `Body.astro`).
5
+ */
6
+ import type { ContentEntry } from "@cloudhal/core-contracts";
7
+ import type { BlockType } from "@cloudhal/core-ts/blocks";
8
+ import { entryArticleParts } from "../markdown.js";
9
+ import type { MediaContext } from "../media.js";
10
+ import Body from "./Body.astro";
11
+
12
+ interface Props {
13
+ entry: Pick<
14
+ ContentEntry,
15
+ "id" | "title" | "summary" | "body" | "publishedAt" | "createdAt" | "coverImage"
16
+ >;
17
+ locale?: string;
18
+ media?: MediaContext;
19
+ blocks?: Record<string, unknown>;
20
+ blockTypes?: readonly BlockType[];
21
+ }
22
+ const { entry, locale = "en", media, blocks, blockTypes } = Astro.props;
23
+ const parts = entryArticleParts(entry, locale, media);
24
+ ---
25
+ <article class="ch-article" data-entry-id={entry.id}>
26
+ <Fragment set:html={parts.header} />
27
+ <Fragment set:html={parts.cover} />
28
+ <div class="ch-richtext">
29
+ <Body body={parts.body} media={parts.media} blocks={blocks} blockTypes={blockTypes} />
30
+ </div>
31
+ </article>