@cloudhal/astro-renderer 0.0.0-stage → 0.1.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.
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,134 @@
1
+ /**
2
+ * Site analytics on Node (RFC-0006 §7.1 L3, §11): what the `cloudhal()` integration's analytics
3
+ * middleware does for `cloudhal dev` (and, later, a Node self-host server). The same
4
+ * `SiteAnalytics` as the Site Worker, writing raw events to the local SQLite store through
5
+ * `SqlAnalytics`:
6
+ *
7
+ * - `POST /__cloudhal/e` answers `204` always; it records only when recording is on (`cloudhal dev`
8
+ * records nothing unless `analytics.dev` is set: it is the author's own traffic);
9
+ * - while recording, HTML `200`s get the script tag and `/_cloudhal/*.js` is served from memory
10
+ * (the Site Worker build ships them as static assets instead);
11
+ * - `render` events for redirects, 404, 410 and 5xx, as on the Worker.
12
+ *
13
+ * Beacons resolve against the **published** snapshot of the local store, so a page that is only a
14
+ * draft in `cloudhal dev` is never counted.
15
+ */
16
+ import { parseAnalyticsDefaults } from "@cloudhal/analytics";
17
+ import { SqlAnalytics } from "@cloudhal/analytics/sql";
18
+
19
+
20
+ import {
21
+ ANALYTICS_BEACON_PATH,
22
+ deploymentDefaults,
23
+ insertTag,
24
+ SiteAnalytics,
25
+ } from "./analytics.js";
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+ /** Defaults and recording for `cloudhal dev`: the integration's options, else the environment. */
51
+ export function nodeAnalyticsSettings(
52
+ config ,
53
+ env = process.env,
54
+ ) {
55
+ const o = config.analytics;
56
+ const defaults = o
57
+ ? o.enabled
58
+ ? parseAnalyticsDefaults(o)
59
+ : undefined
60
+ : deploymentDefaults(env.CLOUDHAL_ANALYTICS, env.CLOUDHAL_ANALYTICS_DEFAULTS);
61
+ const record = o?.dev ?? env.CLOUDHAL_ANALYTICS_DEV === "1";
62
+ return { defaults, record };
63
+ }
64
+
65
+ const JS = { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-cache" };
66
+
67
+ /** A request handler around the page pipeline (`next`). */
68
+ export function createNodeAnalytics(
69
+ options ,
70
+ ) {
71
+ let analytics ;
72
+ const active = options.record && options.defaults !== undefined;
73
+ const get = () => {
74
+ analytics ??= (async () => {
75
+ const sql = await options.backend.open();
76
+ const writer = new SqlAnalytics(sql, {
77
+ ...(options.onError ? { onError: options.onError } : {}),
78
+ });
79
+ return new SiteAnalytics({
80
+ siteId: options.siteId,
81
+ defaults: options.defaults,
82
+ writer,
83
+ sql: options.backend.sql,
84
+ site: options.backend.site,
85
+ snapshot: options.backend.snapshot,
86
+ script: options.client?.script.path,
87
+ // local servers answer on whatever host they are reached by
88
+ acceptRequestHost: () => true,
89
+ ...(options.now ? { now: options.now } : {}),
90
+ ...(options.onError ? { onError: options.onError } : {}),
91
+ });
92
+ })();
93
+ return analytics;
94
+ };
95
+
96
+ return async (request, next, clientIp) => {
97
+ const url = new URL(request.url);
98
+ if (url.pathname === ANALYTICS_BEACON_PATH) {
99
+ if (!active)
100
+ return new Response(null, {
101
+ status: request.method === "POST" ? 204 : 405,
102
+ headers: {
103
+ "cache-control": "no-store",
104
+ ...(request.method === "POST" ? {} : { allow: "POST" }),
105
+ },
106
+ });
107
+ return (await get()).beacon(request, clientIp ? { clientIp } : {});
108
+ }
109
+ if (active && options.client) {
110
+ for (const file of [options.client.script, options.client.vitals])
111
+ if (url.pathname === file.path)
112
+ return new Response(request.method === "HEAD" ? null : file.code, { headers: JS });
113
+ }
114
+ const started = Date.now();
115
+ const response = await next();
116
+ if (!active) return response;
117
+ const a = await get();
118
+ void a.render(request, response, Date.now() - started);
119
+ if (
120
+ response.status !== 200 ||
121
+ !(response.headers.get("content-type") ?? "").includes("text/html")
122
+ )
123
+ return response;
124
+ const tag = await a.tag();
125
+ if (!tag) return response;
126
+ const headers = new Headers(response.headers);
127
+ headers.delete("content-length");
128
+ return new Response(insertTag(await response.text(), tag), {
129
+ status: response.status,
130
+ statusText: response.statusText,
131
+ headers,
132
+ });
133
+ };
134
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Site analytics in the renderer (RFC-0006 §5, rollout step 5), shared by the Cloudflare Site
3
+ * Worker entry and the Node middleware. Worker-safe: no Node module, no bundler.
4
+ *
5
+ * - **Settings** apply per request: the deployment switch and defaults (`CLOUDHAL_ANALYTICS`,
6
+ * `CLOUDHAL_ANALYTICS_DEFAULTS` on Cloudflare; integration options on Node), overridden by the
7
+ * site's `analytics_settings` row, memoised for 60 s per isolate. A missing table, a read error,
8
+ * a missing store or the deployment switch off all count as **off** (fail closed).
9
+ * - **The tag** (`<script type="module" src="/_cloudhal/p.<hash>.js" data-v="N">`) goes into the
10
+ * `<head>` of `200` `text/html` **published** responses only, while the setting is on.
11
+ * - **`POST /__cloudhal/e`** runs `@cloudhal/analytics`' beacon handler: same origin, size, agent,
12
+ * rate (per isolate, then the optional Rate Limiting binding across isolates), schema, then the path is resolved against the **published** snapshot with the
13
+ * renderer's own `resolveRoute` (the browser never names a node), and one event is written.
14
+ * - **Render events** (§5.4) for published HTML `200`s (cache misses by definition), redirects,
15
+ * `404`, `410`, `451` and `5xx`, never for previews, `/__cloudhal/*`, `/_cloudhal/*` or `HEAD`;
16
+ * flood-sampled by `RenderEventSampler`.
17
+ */
18
+ import { type AnalyticsDefaults, type AnalyticsWriter, type EffectiveAnalyticsSettings, type RateLimitBinding, type ResolvedNode } from "@cloudhal/analytics";
19
+ import type { Site } from "@cloudhal/core-contracts";
20
+ import type { SqlDriver } from "@cloudhal/storage";
21
+ import type { GraphSource } from "./source.js";
22
+ /** The beacon endpoint (kept equal to `@cloudhal/analytics/client`'s `BEACON_PATH` by a test). */
23
+ export declare const ANALYTICS_BEACON_PATH = "/__cloudhal/e";
24
+ /** Where the scripts are served from. */
25
+ export declare const ANALYTICS_SCRIPT_DIR = "/_cloudhal/";
26
+ /** Settings and the published pointer are re-read at most this often per isolate (§3.3, §5.2). */
27
+ export declare const ANALYTICS_MEMO_MS = 60000;
28
+ /** The tag the page-view script is loaded with (`data-v` = vitals sampling, one view in N). */
29
+ export declare function analyticsTag(script: string, vitalsOneIn: number): string;
30
+ /** Inserts the tag before `</head>` of an HTML string (Node; the Worker uses `HTMLRewriter`). */
31
+ export declare function insertTag(html: string, tag: string): string;
32
+ /**
33
+ * The node a normalised route shows in a published source: a page, an entry, or a term archive
34
+ * (any of its pages counts toward the term). Feeds, redirects, 404s and 410s are not page views.
35
+ */
36
+ export declare function publishedNode(source: GraphSource, path: string): Promise<ResolvedNode | undefined>;
37
+ /**
38
+ * The deployment switch and defaults as the site Worker reads them: `CLOUDHAL_ANALYTICS` must be
39
+ * `"on"` (anything else, or absent, is off); `CLOUDHAL_ANALYTICS_DEFAULTS` is compact JSON
40
+ * (`cloudhal.json`'s `analytics` block) in which `enabled` defaults to `true`.
41
+ */
42
+ export declare function deploymentDefaults(flag: string | undefined, defaults: string | undefined): AnalyticsDefaults | undefined;
43
+ /** Comma- or space-separated hostnames (e.g. `CLOUDHAL_SITE_HOSTS`), lower case. */
44
+ export declare function parseHosts(value: string | undefined): string[];
45
+ export interface SiteAnalyticsOptions {
46
+ readonly siteId: string;
47
+ /** Deployment defaults; `undefined` = analytics are off for the deployment. */
48
+ readonly defaults: AnalyticsDefaults | undefined;
49
+ /** Where events go; `undefined` = no store (nothing is collected, no tag). */
50
+ readonly writer: AnalyticsWriter | undefined;
51
+ /** Settings, salt (D1 on Cloudflare, SQLite on Node). */
52
+ readonly sql: () => SqlDriver;
53
+ /** The site row as stored now (for its published pointer and domains). */
54
+ readonly site: () => Promise<Site | undefined>;
55
+ /** The source of a snapshot (cached by the caller; snapshots are immutable). */
56
+ readonly snapshot: (id: string) => Promise<GraphSource>;
57
+ /** Hashed URL of the page-view script; without it no tag is injected. */
58
+ readonly script?: string | undefined;
59
+ /** Hosts the site answers on besides `Site.domains` (e.g. the workers.dev host). */
60
+ readonly hosts?: readonly string[];
61
+ /** Also accept the request's own host (`*.workers.dev` on Cloudflare; every host in dev). */
62
+ readonly acceptRequestHost?: (host: string) => boolean;
63
+ /**
64
+ * The optional Workers Rate Limiting binding (`analytics.rateLimit`, RFC-0006 §5.5), checked
65
+ * after the per-isolate limit and keyed by an HMAC under `secret` (a deployment secret every
66
+ * isolate has). Absent: the per-isolate limits alone apply.
67
+ */
68
+ readonly rateLimit?: {
69
+ readonly binding: RateLimitBinding;
70
+ readonly secret: string;
71
+ } | undefined;
72
+ readonly now?: () => number;
73
+ readonly onError?: (message: string, error?: unknown) => void;
74
+ }
75
+ /**
76
+ * Per-isolate analytics state of one site: memoised settings and pointer, the beacon rate limiter
77
+ * and the render-event sampler. Create one per isolate (module scope) and `reset()` it on a purge.
78
+ */
79
+ export declare class SiteAnalytics {
80
+ #private;
81
+ constructor(options: SiteAnalyticsOptions);
82
+ /**
83
+ * Forget memoised settings, the pointer and the day's salt (a purge follows every settings
84
+ * change, §9.2, including "unique visitors" on or off, which deletes the salt in D1).
85
+ */
86
+ reset(): void;
87
+ /** True when the deployment collects at all (switch on and a store bound). */
88
+ get available(): boolean;
89
+ /** The site's effective settings, or `undefined` when analytics are off or unreadable. */
90
+ settings(): Promise<EffectiveAnalyticsSettings | undefined>;
91
+ /** The tag for a published HTML page, or `undefined` (off, or no built script). */
92
+ tag(): Promise<string | undefined>;
93
+ /**
94
+ * `POST /__cloudhal/e`: `204` for every outcome (`405` for another method), `no-store`.
95
+ * `clientIp` is the client's address as the caller knows it (the Site Worker: Cloudflare's
96
+ * `CF-Connecting-IP`; Node: the socket address); request headers are never trusted for it.
97
+ * `country` stands in for `request.cf.country` off Cloudflare.
98
+ */
99
+ beacon(request: Request, extra?: {
100
+ clientIp?: string;
101
+ country?: string;
102
+ }): Promise<Response>;
103
+ /**
104
+ * Records the render event for a response the site rendered (§5.4), if it is one. Run it off
105
+ * the response path (`ctx.waitUntil`); it never throws.
106
+ */
107
+ render(request: Request, response: Response, renderMs: number, extra?: {
108
+ country?: string;
109
+ }): Promise<void>;
110
+ }
111
+ /**
112
+ * Whether a response is one the site Worker records as a `render` event (§5.4): a `GET` for a
113
+ * site path (not `/__cloudhal/*`, `/_cloudhal/*`, not a preview), answered with a published HTML
114
+ * `200`, a redirect, `404`, `410`, `451` or a `5xx`. Media `200`/`206`/`304` and feeds are not
115
+ * HTML, so they never count.
116
+ */
117
+ export declare function isRenderEvent(request: Request, response: Response): boolean;
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Site analytics in the renderer (RFC-0006 §5, rollout step 5), shared by the Cloudflare Site
3
+ * Worker entry and the Node middleware. Worker-safe: no Node module, no bundler.
4
+ *
5
+ * - **Settings** apply per request: the deployment switch and defaults (`CLOUDHAL_ANALYTICS`,
6
+ * `CLOUDHAL_ANALYTICS_DEFAULTS` on Cloudflare; integration options on Node), overridden by the
7
+ * site's `analytics_settings` row, memoised for 60 s per isolate. A missing table, a read error,
8
+ * a missing store or the deployment switch off all count as **off** (fail closed).
9
+ * - **The tag** (`<script type="module" src="/_cloudhal/p.<hash>.js" data-v="N">`) goes into the
10
+ * `<head>` of `200` `text/html` **published** responses only, while the setting is on.
11
+ * - **`POST /__cloudhal/e`** runs `@cloudhal/analytics`' beacon handler: same origin, size, agent,
12
+ * rate (per isolate, then the optional Rate Limiting binding across isolates), schema, then the path is resolved against the **published** snapshot with the
13
+ * renderer's own `resolveRoute` (the browser never names a node), and one event is written.
14
+ * - **Render events** (§5.4) for published HTML `200`s (cache misses by definition), redirects,
15
+ * `404`, `410`, `451` and `5xx`, never for previews, `/__cloudhal/*`, `/_cloudhal/*` or `HEAD`;
16
+ * flood-sampled by `RenderEventSampler`.
17
+ */
18
+ import {
19
+
20
+
21
+ BeaconRateLimiter,
22
+ buildRenderEvent,
23
+
24
+ effectiveSettings,
25
+ handleBeacon,
26
+ normaliseBeaconPath,
27
+ parseAnalyticsDefaults,
28
+
29
+ RenderEventSampler,
30
+
31
+ SharedBeaconRateLimiter,
32
+ } from "@cloudhal/analytics";
33
+ import {
34
+ createSaltProvider,
35
+ getAnalyticsSettings,
36
+
37
+ } from "@cloudhal/analytics/sql";
38
+
39
+
40
+ import { PREVIEW_PARAM } from "./resolver.js";
41
+ import { resolveRoute } from "./routing.js";
42
+
43
+
44
+ /** The beacon endpoint (kept equal to `@cloudhal/analytics/client`'s `BEACON_PATH` by a test). */
45
+ export const ANALYTICS_BEACON_PATH = "/__cloudhal/e";
46
+ /** Where the scripts are served from. */
47
+ export const ANALYTICS_SCRIPT_DIR = "/_cloudhal/";
48
+ /** Settings and the published pointer are re-read at most this often per isolate (§3.3, §5.2). */
49
+ export const ANALYTICS_MEMO_MS = 60_000;
50
+
51
+ /** The tag the page-view script is loaded with (`data-v` = vitals sampling, one view in N). */
52
+ export function analyticsTag(script , vitalsOneIn ) {
53
+ return `<script type="module" src="${script}" data-v="${vitalsOneIn}"></script>`;
54
+ }
55
+
56
+ /** Inserts the tag before `</head>` of an HTML string (Node; the Worker uses `HTMLRewriter`). */
57
+ export function insertTag(html , tag ) {
58
+ const at = html.search(/<\/head\s*>/i);
59
+ return at < 0 ? html : `${html.slice(0, at)}${tag}${html.slice(at)}`;
60
+ }
61
+
62
+ /**
63
+ * The node a normalised route shows in a published source: a page, an entry, or a term archive
64
+ * (any of its pages counts toward the term). Feeds, redirects, 404s and 410s are not page views.
65
+ */
66
+ export async function publishedNode(
67
+ source ,
68
+ path ,
69
+ ) {
70
+ const route = await resolveRoute(source, path);
71
+ switch (route.kind) {
72
+ case "page":
73
+ return { nodeId: route.page.id, nodeKind: "page", locale: route.page.locale };
74
+ case "entry":
75
+ return { nodeId: route.entry.id, nodeKind: "entry", locale: route.entry.locale };
76
+ case "archive":
77
+ return {
78
+ nodeId: route.archive.term.id,
79
+ nodeKind: "archive",
80
+ locale: route.archive.locale,
81
+ };
82
+ default:
83
+ return undefined;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * The deployment switch and defaults as the site Worker reads them: `CLOUDHAL_ANALYTICS` must be
89
+ * `"on"` (anything else, or absent, is off); `CLOUDHAL_ANALYTICS_DEFAULTS` is compact JSON
90
+ * (`cloudhal.json`'s `analytics` block) in which `enabled` defaults to `true`.
91
+ */
92
+ export function deploymentDefaults(
93
+ flag ,
94
+ defaults ,
95
+ ) {
96
+ if (flag?.trim().toLowerCase() !== "on") return undefined;
97
+ let parsed ;
98
+ try {
99
+ parsed = defaults ? JSON.parse(defaults) : {};
100
+ } catch {
101
+ parsed = {};
102
+ }
103
+ const o = parsed && typeof parsed === "object" ? (parsed ) : {};
104
+ return parseAnalyticsDefaults({ enabled: true, ...o });
105
+ }
106
+
107
+ /** Comma- or space-separated hostnames (e.g. `CLOUDHAL_SITE_HOSTS`), lower case. */
108
+ export function parseHosts(value ) {
109
+ return (value ?? "")
110
+ .split(/[\s,]+/)
111
+ .map((h) => h.trim().toLowerCase())
112
+ .filter(Boolean);
113
+ }
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+  
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+ /** What a request's analytics need from the published site. */
149
+
150
+
151
+
152
+
153
+
154
+ /**
155
+ * Per-isolate analytics state of one site: memoised settings and pointer, the beacon rate limiter
156
+ * and the render-event sampler. Create one per isolate (module scope) and `reset()` it on a purge.
157
+ */
158
+ export class SiteAnalytics {
159
+ #o ;
160
+ #now ;
161
+ #limiter ;
162
+ #shared ;
163
+ #sampler ;
164
+ #salt ;
165
+ #saltProvider ;
166
+ #settings ;
167
+ #site ;
168
+
169
+ constructor(options ) {
170
+ this.#o = options;
171
+ this.#now = options.now ?? Date.now;
172
+ this.#limiter = new BeaconRateLimiter({ now: this.#now });
173
+ this.#shared = options.rateLimit
174
+ ? new SharedBeaconRateLimiter(options.rateLimit.binding, {
175
+ secret: options.rateLimit.secret,
176
+ ...(options.onError ? { onError: options.onError } : {}),
177
+ })
178
+ : undefined;
179
+ this.#sampler = new RenderEventSampler({ now: this.#now });
180
+ this.#salt = (day) => {
181
+ this.#saltProvider ??= createSaltProvider(this.#o.sql(), { now: this.#now });
182
+ return this.#saltProvider(day);
183
+ };
184
+ }
185
+
186
+ /**
187
+ * Forget memoised settings, the pointer and the day's salt (a purge follows every settings
188
+ * change, §9.2, including "unique visitors" on or off, which deletes the salt in D1).
189
+ */
190
+ reset() {
191
+ this.#settings = undefined;
192
+ this.#site = undefined;
193
+ this.#saltProvider?.reset();
194
+ }
195
+
196
+ /** True when the deployment collects at all (switch on and a store bound). */
197
+ get available() {
198
+ return this.#o.defaults !== undefined && this.#o.writer !== undefined;
199
+ }
200
+
201
+ #memo (current , load ) {
202
+ const now = this.#now();
203
+ if (current && now - current.at < ANALYTICS_MEMO_MS) return current;
204
+ const value = load();
205
+ value.catch(() => {});
206
+ return { at: now, value };
207
+ }
208
+
209
+ /** The site's effective settings, or `undefined` when analytics are off or unreadable. */
210
+ async settings() {
211
+ const defaults = this.#o.defaults;
212
+ if (!defaults || !this.#o.writer) return undefined;
213
+ const before = this.#settings;
214
+ this.#settings = this.#memo(this.#settings, async () =>
215
+ effectiveSettings(
216
+ this.#o.siteId,
217
+ await getAnalyticsSettings(this.#o.sql(), this.#o.siteId),
218
+ defaults,
219
+ ),
220
+ );
221
+ // The salt is never older than the settings it is used with: whenever they are read again
222
+ // (every 60 s, or after a reset), the salt's row is read again too, so a salt deleted by
223
+ // switching unique visitors off is not used once this isolate sees the change.
224
+ if (this.#settings !== before) this.#saltProvider?.reset();
225
+ try {
226
+ const s = await this.#settings.value;
227
+ return s?.enabled ? s : undefined;
228
+ } catch {
229
+ return undefined; // a missing table (before migration 0014) or a read error: off
230
+ }
231
+ }
232
+
233
+ /** The tag for a published HTML page, or `undefined` (off, or no built script). */
234
+ async tag() {
235
+ if (!this.#o.script) return undefined;
236
+ const s = await this.settings();
237
+ return s ? analyticsTag(this.#o.script, s.vitalsOneIn) : undefined;
238
+ }
239
+
240
+ async #published() {
241
+ this.#site = this.#memo(this.#site, () => this.#o.site());
242
+ let site ;
243
+ try {
244
+ site = await this.#site.value;
245
+ } catch (error) {
246
+ this.#o.onError?.("analytics: reading the site failed", error);
247
+ return undefined;
248
+ }
249
+ if (!site?.publishedSnapshotId) return undefined;
250
+ return { site, source: await this.#o.snapshot(site.publishedSnapshotId) };
251
+ }
252
+
253
+ #hosts(site , requestHost ) {
254
+ const hosts = [...site.domains.map((d) => d.hostname), ...(this.#o.hosts ?? [])];
255
+ const bare = requestHost.toLowerCase().replace(/:\d+$/, "");
256
+ if (this.#o.acceptRequestHost?.(bare)) hosts.push(requestHost.toLowerCase());
257
+ return hosts;
258
+ }
259
+
260
+ /**
261
+ * `POST /__cloudhal/e`: `204` for every outcome (`405` for another method), `no-store`.
262
+ * `clientIp` is the client's address as the caller knows it (the Site Worker: Cloudflare's
263
+ * `CF-Connecting-IP`; Node: the socket address); request headers are never trusted for it.
264
+ * `country` stands in for `request.cf.country` off Cloudflare.
265
+ */
266
+ async beacon(
267
+ request ,
268
+ extra = {},
269
+ ) {
270
+ const writer = this.#o.writer;
271
+ const off = { settings: () => undefined, hosts: [], resolvePath: () => undefined };
272
+ const noop = { write: () => {} };
273
+ if (request.method !== "POST" || !writer)
274
+ return handleBeacon(request, { siteId: this.#o.siteId, writer: noop, ...off });
275
+ const settings = await this.settings();
276
+ const published = settings ? await this.#published() : undefined;
277
+ if (!settings || !published)
278
+ return handleBeacon(request, { siteId: this.#o.siteId, writer: noop, ...off });
279
+ const { source, site } = published;
280
+ return handleBeacon(request, {
281
+ siteId: this.#o.siteId,
282
+ settings: () => settings,
283
+ hosts: this.#hosts(site, new URL(request.url).host),
284
+ resolvePath: (path) => publishedNode(source, path),
285
+ writer,
286
+ salt: this.#salt,
287
+ rateLimit: async (ip, kind) =>
288
+ (await this.#limiter.allow(ip, kind)) && (await (this.#shared?.allow(ip) ?? true)),
289
+ now: () => new Date(this.#now()),
290
+ ...(extra.clientIp ? { clientIp: extra.clientIp } : {}),
291
+ ...(extra.country ? { country: extra.country } : {}),
292
+ ...(this.#o.onError ? { onError: this.#o.onError } : {}),
293
+ });
294
+ }
295
+
296
+ /**
297
+ * Records the render event for a response the site rendered (§5.4), if it is one. Run it off
298
+ * the response path (`ctx.waitUntil`); it never throws.
299
+ */
300
+ async render(
301
+ request ,
302
+ response ,
303
+ renderMs ,
304
+ extra = {},
305
+ ) {
306
+ try {
307
+ const writer = this.#o.writer;
308
+ if (!writer || !isRenderEvent(request, response)) return;
309
+ if (!(await this.settings())) return;
310
+ const published = await this.#published();
311
+ if (!published) return;
312
+ const decision = this.#sampler.next();
313
+ if (!decision.record) return;
314
+ const url = new URL(request.url);
315
+ const status = response.status;
316
+ const location = response.headers.get("location");
317
+ // the node shown (200) or redirected to (3xx, same-site targets only)
318
+ let nodePath ;
319
+ if (status === 200) nodePath = normaliseBeaconPath(url.pathname);
320
+ else if (status >= 300 && status < 400 && location) {
321
+ const target = new URL(location, url);
322
+ if (target.host === url.host) nodePath = normaliseBeaconPath(target.pathname);
323
+ }
324
+ const node = nodePath ? await publishedNode(published.source, nodePath) : undefined;
325
+ const cf = (request ).cf;
326
+ const country = typeof cf?.country === "string" ? cf.country : extra.country;
327
+ const h = request.headers;
328
+ const event = buildRenderEvent({
329
+ siteId: this.#o.siteId,
330
+ now: new Date(this.#now()),
331
+ url,
332
+ status,
333
+ hosts: this.#hosts(published.site, url.host),
334
+ userAgent: h.get("user-agent"),
335
+ hints: { mobile: h.get("sec-ch-ua-mobile"), platform: h.get("sec-ch-ua-platform") },
336
+ referer: h.get("referer"),
337
+ ...(node ? { node: { nodeId: node.nodeId, nodeKind: node.nodeKind } } : {}),
338
+ location,
339
+ renderMs,
340
+ sampleOneIn: decision.sampleOneIn,
341
+ ...(country ? { country } : {}),
342
+ });
343
+ if (event) writer.write(event);
344
+ } catch (error) {
345
+ this.#o.onError?.("analytics: render event failed", error);
346
+ }
347
+ }
348
+ }
349
+
350
+ const RENDER_STATUSES = new Set([301, 302, 303, 307, 308, 404, 410, 451]);
351
+
352
+ /**
353
+ * Whether a response is one the site Worker records as a `render` event (§5.4): a `GET` for a
354
+ * site path (not `/__cloudhal/*`, `/_cloudhal/*`, not a preview), answered with a published HTML
355
+ * `200`, a redirect, `404`, `410`, `451` or a `5xx`. Media `200`/`206`/`304` and feeds are not
356
+ * HTML, so they never count.
357
+ */
358
+ export function isRenderEvent(request , response ) {
359
+ if (request.method !== "GET") return false;
360
+ const url = new URL(request.url);
361
+ if (url.pathname.startsWith("/__cloudhal/") || url.pathname.startsWith(ANALYTICS_SCRIPT_DIR))
362
+ return false;
363
+ if (url.searchParams.has(PREVIEW_PARAM)) return false;
364
+ const mode = response.headers.get("x-cloudhal-mode");
365
+ if (mode === "preview" || mode === "unpublished") return false;
366
+ const status = response.status;
367
+ if (status === 200)
368
+ return (
369
+ mode === "published" && (response.headers.get("content-type") ?? "").includes("text/html")
370
+ );
371
+ return RENDER_STATUSES.has(status) || (status >= 500 && status <= 599);
372
+ }