@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,217 @@
1
+ /**
2
+ * HTML bodies, sanitized at render time (RFC-0012, ADR-0026). An `html` body may come from any
3
+ * writer — agent keys over REST, `cloudhal push`, the least trusted roles — so it reaches a page,
4
+ * a preview, a feed or a static build only through this allowlist.
5
+ *
6
+ * 1. **Parse** the body as a fragment in a `<div>` context with parse5, the way a browser parses
7
+ * `innerHTML`: a sanitizer that parses differently from the browser can be bypassed (mutation
8
+ * XSS).
9
+ * 2. **Walk** the tree: allowlisted elements and attributes stay; other elements are unwrapped
10
+ * (their children kept); the drop set goes with its content; comments go.
11
+ * 3. **Serialize** ourselves: only allowlisted names are written as they are, every attribute
12
+ * value and text is escaped. Stored bodies are never modified.
13
+ */
14
+ import { defaultTreeAdapter, parseFragment } from "parse5";
15
+ import { safeHref, safeSrc } from "./safe-urls.js";
16
+
17
+
18
+
19
+
20
+ const HTML_NS = "http://www.w3.org/1999/xhtml";
21
+
22
+ /** Attributes any kept element may carry (`id` is rewritten to `user-content-<id>`). */
23
+ const GLOBAL = ["title", "lang", "dir", "class"] ;
24
+
25
+ /** Kept elements and the attributes each may carry besides `GLOBAL` and `id` (RFC-0012 v1). */
26
+ const ELEMENTS = {
27
+ // text and structure
28
+ p: [],
29
+ br: [],
30
+ hr: [],
31
+ h1: [],
32
+ h2: [],
33
+ h3: [],
34
+ h4: [],
35
+ h5: [],
36
+ h6: [],
37
+ blockquote: [],
38
+ pre: [],
39
+ code: [],
40
+ kbd: [],
41
+ samp: [],
42
+ var: [],
43
+ strong: [],
44
+ b: [],
45
+ em: [],
46
+ i: [],
47
+ u: [],
48
+ s: [],
49
+ del: [],
50
+ ins: [],
51
+ mark: [],
52
+ small: [],
53
+ sub: [],
54
+ sup: [],
55
+ q: [],
56
+ cite: [],
57
+ abbr: [],
58
+ dfn: [],
59
+ time: ["datetime"],
60
+ span: [],
61
+ div: [],
62
+ section: [],
63
+ aside: [],
64
+ figure: [],
65
+ figcaption: [],
66
+ details: ["open"],
67
+ summary: [],
68
+ // lists and tables
69
+ ul: [],
70
+ ol: ["start", "reversed", "type"],
71
+ li: [],
72
+ dl: [],
73
+ dt: [],
74
+ dd: [],
75
+ table: [],
76
+ caption: [],
77
+ thead: [],
78
+ tbody: [],
79
+ tfoot: [],
80
+ tr: [],
81
+ th: ["colspan", "rowspan", "scope", "headers"],
82
+ td: ["colspan", "rowspan", "scope", "headers"],
83
+ colgroup: [],
84
+ col: [],
85
+ // links and media
86
+ a: ["href", "target"],
87
+ img: ["src", "alt", "width", "height", "loading", "decoding"],
88
+ picture: [],
89
+ source: ["src", "type", "kind", "srclang", "label"],
90
+ audio: ["src", "poster", "controls", "preload", "muted", "loop", "playsinline"],
91
+ video: ["src", "poster", "controls", "preload", "muted", "loop", "playsinline"],
92
+ track: ["src", "type", "kind", "srclang", "label"],
93
+ };
94
+
95
+ /** Removed with everything inside them. */
96
+ const DROP = new Set([
97
+ "script",
98
+ "style",
99
+ "template",
100
+ "noscript",
101
+ "iframe",
102
+ "frame",
103
+ "frameset",
104
+ "object",
105
+ "embed",
106
+ "applet",
107
+ "svg",
108
+ "math",
109
+ "form",
110
+ "input",
111
+ "button",
112
+ "select",
113
+ "option",
114
+ "optgroup",
115
+ "textarea",
116
+ "datalist",
117
+ "output",
118
+ "meta",
119
+ "link",
120
+ "base",
121
+ "title",
122
+ "head",
123
+ "noembed",
124
+ "noframes",
125
+ "dialog",
126
+ "slot",
127
+ "portal",
128
+ ]);
129
+
130
+ /** Elements with no end tag. */
131
+ const VOID = new Set(["br", "hr", "img", "source", "track", "col"]);
132
+
133
+ /** Attributes whose value is a URL, and the rule each is checked by. */
134
+ const URL_ATTRS = {
135
+ href: (v) => safeHref(v),
136
+ src: (v, element) => (element === "img" ? safeSrc(v) : mediaUrl(v)),
137
+ poster: (v) => safeSrc(v),
138
+ };
139
+
140
+ /** Other media: `http`, `https` or relative only (no `data:`, `mailto:`, `tel:`). */
141
+ function mediaUrl(value ) {
142
+ const safe = safeHref(value);
143
+ return safe && !/^(mailto|tel):/i.test(safe) ? safe : undefined;
144
+ }
145
+
146
+ /** What survives, for docs and tests. */
147
+ export const HTML_ALLOWLIST
148
+
149
+
150
+ = { elements: ELEMENTS, global: [...GLOBAL, "id"] };
151
+
152
+ const escapeText = (s ) =>
153
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
154
+ const escapeAttr = (s ) => escapeText(s).replace(/"/g, "&quot;");
155
+
156
+ /** The sanitized HTML of a stored `html` body. */
157
+ export function sanitizeHtml(html ) {
158
+ const context = defaultTreeAdapter.createElement("div", HTML_NS , []);
159
+ const fragment = parseFragment(context, html, {});
160
+ return serializeChildren(fragment.childNodes);
161
+ }
162
+
163
+ function serializeChildren(nodes ) {
164
+ let out = "";
165
+ for (const node of nodes) out += serializeNode(node);
166
+ return out;
167
+ }
168
+
169
+ function serializeNode(node ) {
170
+ if (node.nodeName === "#text") return escapeText((node ).value);
171
+ if (node.nodeName === "#comment" || node.nodeName === "#documentType") return "";
172
+ const element = node ;
173
+ const name = element.tagName;
174
+ // Foreign content (SVG, MathML) never reaches the page, even where the parser put it.
175
+ if (element.namespaceURI !== HTML_NS || DROP.has(name)) return "";
176
+ const allowed = ELEMENTS[name];
177
+ if (!allowed) return serializeChildren(element.childNodes); // unwrap
178
+ const attrs = attributes(element, allowed);
179
+ if (attrs === undefined) return ""; // an image without a usable source
180
+ if (VOID.has(name)) return `<${name}${attrs}>`;
181
+ let inner = serializeChildren(element.childNodes);
182
+ // A browser drops one newline right after <pre>: keep a leading one that was really there.
183
+ if (name === "pre" && inner.startsWith("\n")) inner = `\n${inner}`;
184
+ return `<${name}${attrs}>${inner}</${name}>`;
185
+ }
186
+
187
+ /** The kept attributes, serialized; `undefined` when the element must go (an `img` with no src). */
188
+ function attributes(element , allowed ) {
189
+ const name = element.tagName;
190
+ let out = "";
191
+ let blank = false;
192
+ let src = false;
193
+ for (const attr of element.attrs) {
194
+ if (attr.namespace) continue; // xlink:, xml:, xmlns:
195
+ const key = attr.name;
196
+ let value = attr.value;
197
+ if (key === "id") {
198
+ value = attr.value.startsWith("user-content-") ? attr.value : `user-content-${attr.value}`;
199
+ } else if (!(GLOBAL ).includes(key) && !allowed.includes(key)) {
200
+ continue;
201
+ }
202
+ const checkUrl = URL_ATTRS[key];
203
+ if (checkUrl) {
204
+ value = checkUrl(attr.value, name);
205
+ if (value === undefined) continue;
206
+ if (key === "src") src = true;
207
+ }
208
+ if (key === "target") {
209
+ if (attr.value !== "_blank") continue;
210
+ blank = true;
211
+ }
212
+ out += ` ${key}="${escapeAttr(value)}"`;
213
+ }
214
+ if (name === "img" && !src) return undefined;
215
+ if (blank) out += ' rel="noopener noreferrer"';
216
+ return out;
217
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Cloudhal's search module (RFC-0029 §6): the reader's search modal. A self-contained, versioned
3
+ * file under `/_cloudhal/` (CSP `script-src 'self'`, `connect-src 'self'`), loaded only by pages of
4
+ * deployments that answer searches. Without it nothing is lost: the header form and `/search` work
5
+ * as plain HTML.
6
+ *
7
+ * The theme renders the markup and the words; this module only wires them:
8
+ * - `dialog[data-ch-search]` with `data-endpoint` (`/search.json`), `data-page` (`/search`) and
9
+ * `data-words` (JSON: `kinds`, `all`, `none`, `recent`, `clear`, `limited`, `error`, `updating`,
10
+ * `count` as plural forms with `#`), holding `[data-ch-search-input]` (the combobox),
11
+ * `[data-ch-search-list]` (the listbox), `[data-ch-search-note]`, `[data-ch-search-status]` (a
12
+ * live region) and `[data-ch-search-close]`.
13
+ * - Anything marked `[data-ch-search-open]` opens it (a link's click, a form field's focus), as do
14
+ * ⌘K / Ctrl+K and `/` outside text fields.
15
+ *
16
+ * Behaviour (WAI-ARIA combobox with a listbox popup): typing asks the endpoint after 200 ms and
17
+ * cancels the request it replaces; hits come grouped by kind, each a link with its context and
18
+ * a snippet the server escaped and marked; the last option is "all results" on `/search`. ↑↓ move
19
+ * the active option (`aria-activedescendant`), Enter opens it (or the results page when none is
20
+ * active), Escape (even in a search field, which would clear itself first) or a click on the
21
+ * backdrop closes, and focus returns to the trigger (a header field takes it back without opening
22
+ * the modal again).
23
+ * Before typing, the last five searches show; they stay in this browser (`localStorage`) and a
24
+ * button clears them. A `429` says to wait and links to the results page.
25
+ */
26
+ export declare const SEARCH_SCRIPT: {
27
+ readonly path: "/_cloudhal/search.1.js";
28
+ readonly code: string;
29
+ };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Cloudhal's search module (RFC-0029 §6): the reader's search modal. A self-contained, versioned
3
+ * file under `/_cloudhal/` (CSP `script-src 'self'`, `connect-src 'self'`), loaded only by pages of
4
+ * deployments that answer searches. Without it nothing is lost: the header form and `/search` work
5
+ * as plain HTML.
6
+ *
7
+ * The theme renders the markup and the words; this module only wires them:
8
+ * - `dialog[data-ch-search]` with `data-endpoint` (`/search.json`), `data-page` (`/search`) and
9
+ * `data-words` (JSON: `kinds`, `all`, `none`, `recent`, `clear`, `limited`, `error`, `updating`,
10
+ * `count` as plural forms with `#`), holding `[data-ch-search-input]` (the combobox),
11
+ * `[data-ch-search-list]` (the listbox), `[data-ch-search-note]`, `[data-ch-search-status]` (a
12
+ * live region) and `[data-ch-search-close]`.
13
+ * - Anything marked `[data-ch-search-open]` opens it (a link's click, a form field's focus), as do
14
+ * ⌘K / Ctrl+K and `/` outside text fields.
15
+ *
16
+ * Behaviour (WAI-ARIA combobox with a listbox popup): typing asks the endpoint after 200 ms and
17
+ * cancels the request it replaces; hits come grouped by kind, each a link with its context and
18
+ * a snippet the server escaped and marked; the last option is "all results" on `/search`. ↑↓ move
19
+ * the active option (`aria-activedescendant`), Enter opens it (or the results page when none is
20
+ * active), Escape (even in a search field, which would clear itself first) or a click on the
21
+ * backdrop closes, and focus returns to the trigger (a header field takes it back without opening
22
+ * the modal again).
23
+ * Before typing, the last five searches show; they stay in this browser (`localStorage`) and a
24
+ * button clears them. A `429` says to wait and links to the results page.
25
+ */
26
+
27
+ const code = String.raw`const d=document,dlg=d.querySelector("dialog[data-ch-search]");
28
+ if(dlg&&dlg.showModal){
29
+ const $=(s)=>dlg.querySelector(s),input=$("[data-ch-search-input]"),list=$("[data-ch-search-list]"),note=$("[data-ch-search-note]"),status=$("[data-ch-search-status]");
30
+ let W={};try{W=JSON.parse(dlg.getAttribute("data-words")||"{}");}catch(e){}
31
+ const endpoint=dlg.getAttribute("data-endpoint")||"/search.json",page=dlg.getAttribute("data-page")||"/search";
32
+ const lang=d.documentElement.lang||"en",rules=new Intl.PluralRules(lang),KEY="ch_search_recent";
33
+ const fill=(s,q)=>String(s||"").split("{q}").join(q);
34
+ const count=(n)=>{const c=W.count||{};return String(c[rules.select(n)]||c.other||"#").split("#").join(n.toLocaleString(lang));};
35
+ const recent=()=>{try{const r=JSON.parse(localStorage.getItem(KEY)||"[]");return Array.isArray(r)?r.filter((x)=>typeof x==="string").slice(0,5):[];}catch(e){return[];}};
36
+ const remember=(q)=>{q=q.trim();if(!q)return;try{localStorage.setItem(KEY,JSON.stringify([q,...recent().filter((x)=>x.toLowerCase()!==q.toLowerCase())].slice(0,5)));}catch(e){}};
37
+ const forget=()=>{try{localStorage.removeItem(KEY);}catch(e){}};
38
+ let options=[],active=-1,timer=0,ctrl=null,query="",back=null,returning=false,closedAt=0;
39
+ const shut=()=>{closedAt=Date.now();dlg.close();};
40
+ const el=(tag,cls,text)=>{const e=d.createElement(tag);if(cls)e.className=cls;if(text!=null)e.textContent=text;return e;};
41
+ const say=(text)=>{if(status)status.textContent=text||"";};
42
+ const show=(text,link)=>{if(!note)return;note.textContent=text||"";if(link){note.append(" ");const a=el("a","",link.text);a.href=link.href;note.append(a);}note.hidden=!text;};
43
+ const setActive=(i)=>{active=options.length?(i+options.length)%options.length:-1;
44
+ options.forEach((o,j)=>o.setAttribute("aria-selected",String(j===active)));
45
+ if(active<0){input.removeAttribute("aria-activedescendant");return;}
46
+ const o=options[active];input.setAttribute("aria-activedescendant",o.id);if(o.scrollIntoView)o.scrollIntoView({block:"nearest"});};
47
+ const option=(href,parts,onPick)=>{const o=el("a","ch-search-option");o.href=href;o.id="ch-search-o"+options.length;o.setAttribute("role","option");o.tabIndex=-1;
48
+ for(const p of parts)o.append(p);o.addEventListener("pointermove",()=>{if(options[active]!==o)setActive(options.indexOf(o));});
49
+ o.addEventListener("click",(e)=>{if(onPick){e.preventDefault();onPick();}else remember(query);});options.push(o);return o;};
50
+ const group=(label,items)=>{const g=el("div","ch-search-group");g.setAttribute("role","group");const h=el("div","ch-search-group__label",label);h.id="ch-search-g"+list.children.length;
51
+ h.setAttribute("role","presentation");g.setAttribute("aria-labelledby",h.id);g.append(h,...items);list.append(g);};
52
+ const reset=()=>{list.textContent="";options=[];active=-1;input.removeAttribute("aria-activedescendant");show("");};
53
+ const done=()=>{input.setAttribute("aria-expanded",String(options.length>0));};
54
+ const showRecent=()=>{reset();const r=recent();if(r.length){group(W.recent||"",r.map((q)=>option(page+"?q="+encodeURIComponent(q),[el("span","ch-search-option__title",q)],()=>{input.value=q;run(q);})));
55
+ const b=el("button","ch-search-clear",W.clear||"Clear");b.type="button";b.addEventListener("click",()=>{forget();showRecent();input.focus();});note.textContent="";note.append(b);note.hidden=false;}
56
+ done();say("");};
57
+ const render=(q,json)=>{reset();const order=[],by={};
58
+ for(const h of json.hits||[]){if(!by[h.kind]){by[h.kind]=[];order.push(h.kind);}const parts=[el("span","ch-search-option__title",h.title)];
59
+ if(h.context)parts.unshift(el("span","ch-search-option__context",h.context));if(h.snippetHtml){const s=el("span","ch-search-option__snippet");s.innerHTML=h.snippetHtml;parts.push(s);}
60
+ by[h.kind].push(option(h.href,parts));}
61
+ for(const k of order)group((W.kinds||{})[k]||k,by[k]);
62
+ if(json.total>0){const all=option(page+"?q="+encodeURIComponent(q),[el("span","ch-search-option__title",fill(W.all,q))],()=>{remember(q);location.href=page+"?q="+encodeURIComponent(q);});
63
+ all.classList.add("ch-search-option--all");const g=el("div","ch-search-group");g.setAttribute("role","group");g.append(all);list.append(g);}
64
+ else show(fill(W.none,q));
65
+ if(json.stale&&json.total>0)show(W.updating||"");setActive(json.total>0?0:-1);done();say(json.total>0?count(json.total):fill(W.none,q));};
66
+ const run=(q)=>{clearTimeout(timer);if(ctrl)ctrl.abort();query=q;if(!q.trim()){showRecent();return;}
67
+ ctrl=new AbortController();dlg.setAttribute("aria-busy","true");
68
+ fetch(endpoint+"?q="+encodeURIComponent(q),{signal:ctrl.signal,headers:{accept:"application/json"}})
69
+ .then((r)=>r.status===429?{limited:true}:r.ok?r.json():Promise.reject(new Error(String(r.status))))
70
+ .then((json)=>{if(q!==query)return;dlg.removeAttribute("aria-busy");
71
+ if(json.limited){reset();done();show(W.limited||"",{text:fill(W.all,q),href:page+"?q="+encodeURIComponent(q)});say(W.limited||"");return;}render(q,json);})
72
+ .catch((e)=>{if(e&&e.name==="AbortError")return;dlg.removeAttribute("aria-busy");reset();done();show(W.error||"",{text:fill(W.all,q),href:page+"?q="+encodeURIComponent(q)});});};
73
+ const open=(q)=>{if(!dlg.open)dlg.showModal();if(typeof q==="string"&&q)input.value=q;input.focus();input.select();run(input.value);};
74
+ input.setAttribute("role","combobox");input.setAttribute("aria-autocomplete","list");input.setAttribute("aria-expanded","false");if(list.id)input.setAttribute("aria-controls",list.id);
75
+ input.addEventListener("input",()=>{clearTimeout(timer);timer=setTimeout(()=>run(input.value),200);});
76
+ input.addEventListener("keydown",(e)=>{if(e.key==="ArrowDown"||e.key==="ArrowUp"){if(!options.length)return;e.preventDefault();setActive(active<0?(e.key==="ArrowDown"?0:-1):active+(e.key==="ArrowDown"?1:-1));}
77
+ else if(e.key==="Enter"&&active>=0&&options[active]){e.preventDefault();options[active].click();}
78
+ else if(e.key==="Enter")remember(input.value);
79
+ else if(e.key==="Escape"){e.preventDefault();shut();}});
80
+ dlg.addEventListener("click",(e)=>{if(e.target===dlg)shut();});
81
+ dlg.addEventListener("close",()=>{closedAt=Date.now();clearTimeout(timer);if(ctrl)ctrl.abort();dlg.removeAttribute("aria-busy");
82
+ if(back&&back.isConnected){returning=true;back.focus();returning=false;}back=null;});
83
+ for(const b of dlg.querySelectorAll("[data-ch-search-close]"))b.addEventListener("click",shut);
84
+ d.addEventListener("click",(e)=>{const t=e.target instanceof Element&&e.target.closest("[data-ch-search-open]");if(!t||dlg.open)return;e.preventDefault();open();});
85
+ d.addEventListener("focusin",(e)=>{const t=e.target instanceof Element&&e.target.closest("[data-ch-search-open]");if(returning||dlg.open||!t||!(e.target instanceof HTMLInputElement)||dlg.contains(e.relatedTarget)||Date.now()-closedAt<300)return;const q=e.target.value;back=e.target;open(q);});
86
+ d.addEventListener("keydown",(e)=>{const t=e.target,typing=t instanceof Element&&(t.closest("input,textarea,select,[contenteditable]")!==null);
87
+ if((e.metaKey||e.ctrlKey)&&!e.altKey&&e.key.toLowerCase()==="k"){e.preventDefault();if(dlg.open)shut();else open();}
88
+ else if(e.key==="/"&&!typing&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!dlg.open){e.preventDefault();open();}});
89
+ d.documentElement.setAttribute("data-ch-search-ready","");}
90
+ `;
91
+
92
+ export const SEARCH_SCRIPT = { path: "/_cloudhal/search.1.js", code } ;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Site search's rate limit on the Site Worker (RFC-0019 §3, RFC-0029 §5): a token bucket per client
3
+ * address, per isolate. A client holds up to `SEARCH_BUCKET` tokens, refilled at one a second; the
4
+ * search page costs `SEARCH_COST.page`, a modal request `SEARCH_COST.json`. So a reader may load 30
5
+ * result pages in a row, or type through a few queries in the modal (debounced), and a script
6
+ * hammering either is held to 30 pages or 60 requests a minute. Addresses live in memory only and
7
+ * are never logged or stored. Worker-safe.
8
+ */
9
+ /** Tokens a client starts with and can hold. */
10
+ export declare const SEARCH_BUCKET = 60;
11
+ /** Tokens refilled per second. */
12
+ export declare const SEARCH_REFILL_PER_SECOND = 1;
13
+ /** What each kind of request costs. */
14
+ export declare const SEARCH_COST: {
15
+ readonly page: 2;
16
+ readonly json: 1;
17
+ };
18
+ /** Result pages a client may load in a burst (`SEARCH_BUCKET / SEARCH_COST.page`). */
19
+ export declare const SEARCH_RATE_LIMIT: number;
20
+ export declare class SearchLimiter {
21
+ #private;
22
+ constructor(options?: {
23
+ capacity?: number;
24
+ refillPerSecond?: number;
25
+ now?: () => number;
26
+ });
27
+ /**
28
+ * Spends `cost` tokens of a client's bucket; returns the seconds to wait when it holds too few
29
+ * (nothing is spent then), else 0. Without an address (local tools, tests) nothing is limited.
30
+ */
31
+ take(client: string | undefined, cost?: number): number;
32
+ }
33
+ /** What a request to a search path costs, or undefined for any other path. */
34
+ export declare function searchCost(pathname: string): number | undefined;
35
+ /** True for the search page's path (with or without a trailing slash) and the modal's endpoint. */
36
+ export declare function isSearchPath(pathname: string): boolean;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Site search's rate limit on the Site Worker (RFC-0019 §3, RFC-0029 §5): a token bucket per client
3
+ * address, per isolate. A client holds up to `SEARCH_BUCKET` tokens, refilled at one a second; the
4
+ * search page costs `SEARCH_COST.page`, a modal request `SEARCH_COST.json`. So a reader may load 30
5
+ * result pages in a row, or type through a few queries in the modal (debounced), and a script
6
+ * hammering either is held to 30 pages or 60 requests a minute. Addresses live in memory only and
7
+ * are never logged or stored. Worker-safe.
8
+ */
9
+
10
+ /** Tokens a client starts with and can hold. */
11
+ export const SEARCH_BUCKET = 60;
12
+ /** Tokens refilled per second. */
13
+ export const SEARCH_REFILL_PER_SECOND = 1;
14
+ /** What each kind of request costs. */
15
+ export const SEARCH_COST = { page: 2, json: 1 } ;
16
+ /** Result pages a client may load in a burst (`SEARCH_BUCKET / SEARCH_COST.page`). */
17
+ export const SEARCH_RATE_LIMIT = SEARCH_BUCKET / SEARCH_COST.page;
18
+ /** Clients tracked per isolate; past this, the least recently seen are forgotten. */
19
+ const MAX_CLIENTS = 10_000;
20
+
21
+ export class SearchLimiter {
22
+ #capacity ;
23
+ #refill ;
24
+ #now ;
25
+ /** Insertion order is recency: a client's entry moves to the end on every request. */
26
+ #buckets = new Map ();
27
+
28
+ constructor(options = {}) {
29
+ this.#capacity = options.capacity ?? SEARCH_BUCKET;
30
+ this.#refill = options.refillPerSecond ?? SEARCH_REFILL_PER_SECOND;
31
+ this.#now = options.now ?? Date.now;
32
+ }
33
+
34
+ /**
35
+ * Spends `cost` tokens of a client's bucket; returns the seconds to wait when it holds too few
36
+ * (nothing is spent then), else 0. Without an address (local tools, tests) nothing is limited.
37
+ */
38
+ take(client , cost = SEARCH_COST.page) {
39
+ if (!client) return 0;
40
+ const now = this.#now();
41
+ const held = this.#buckets.get(client);
42
+ const tokens = held
43
+ ? Math.min(this.#capacity, held.tokens + ((now - held.at) / 1000) * this.#refill)
44
+ : this.#capacity;
45
+ this.#buckets.delete(client);
46
+ const enough = tokens >= cost;
47
+ this.#buckets.set(client, { tokens: enough ? tokens - cost : tokens, at: now });
48
+ if (this.#buckets.size > MAX_CLIENTS) {
49
+ const oldest = this.#buckets.keys().next().value;
50
+ if (oldest !== undefined) this.#buckets.delete(oldest);
51
+ }
52
+ return enough ? 0 : Math.ceil((cost - tokens) / this.#refill);
53
+ }
54
+ }
55
+
56
+ /** What a request to a search path costs, or undefined for any other path. */
57
+ export function searchCost(pathname ) {
58
+ if (pathname === "/search" || pathname === "/search/") return SEARCH_COST.page;
59
+ if (pathname === "/search.json") return SEARCH_COST.json;
60
+ return undefined;
61
+ }
62
+
63
+ /** True for the search page's path (with or without a trailing slash) and the modal's endpoint. */
64
+ export function isSearchPath(pathname ) {
65
+ return searchCost(pathname) !== undefined;
66
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Site search for themes (RFC-0019 §3, RFC-0029 §5): the `/search` route's view, safe snippet HTML,
3
+ * the modal's `/search.json` answer and whether the deployment can answer searches at all (static
4
+ * builds cannot; their themes hide the form).
5
+ * Worker-safe.
6
+ */
7
+ import { type SearchKind, type SearchResults } from "@cloudhal/core-ts";
8
+ import type { CloudhalRendererConfig } from "./integration.js";
9
+ import type { GraphSource } from "./source.js";
10
+ export { SEARCH_PATH } from "@cloudhal/core-ts";
11
+ /** What the `/search` route hands the theme. */
12
+ export type SearchView = SearchResults;
13
+ /** The `q` and page of a search request (`?q=…&page=n`); the query is capped by the store. */
14
+ export declare function searchRequest(search: string): {
15
+ query: string;
16
+ page: number;
17
+ };
18
+ /** The URL of a results page (page 1 has no `page` parameter). */
19
+ export declare function searchPageHref(query: string, page: number): string;
20
+ /** A hit's snippet as HTML: the text escaped first, then `<mark>` around the matches. */
21
+ export declare function snippetHtml(snippet: string): string;
22
+ /**
23
+ * True when this deployment answers `/search`: the Cloudflare Site Worker and `cloudhal dev` (a
24
+ * live source). A static `cloudhal build` renders a snapshot ahead of time with no server to ask,
25
+ * so its theme shows no search form.
26
+ */
27
+ export declare function searchAvailable(config: Pick<CloudhalRendererConfig, "target">, source: Pick<GraphSource, "mode" | "search">): boolean;
28
+ /** The modal's endpoint (`GET /search.json?q=&kinds=&page=`): same index, same rules as `/search`. */
29
+ export declare const SEARCH_JSON_PATH = "/search.json";
30
+ /** Hits the modal shows per request. */
31
+ export declare const SEARCH_SUGGEST_SIZE = 8;
32
+ /** One hit as the modal receives it: the snippet already escaped and marked (`snippetHtml`). */
33
+ export interface SearchJsonHit {
34
+ title: string;
35
+ href: string;
36
+ kind: SearchKind;
37
+ context?: string;
38
+ snippetHtml: string;
39
+ publishedAt?: string;
40
+ }
41
+ export interface SearchJson {
42
+ query: string;
43
+ total: number;
44
+ page: number;
45
+ pages: number;
46
+ stale: boolean;
47
+ hits: SearchJsonHit[];
48
+ }
49
+ /** A modal request: `q`, `page`, `kinds` (comma-separated, unknown ones ignored). */
50
+ export declare function searchJsonRequest(search: string): {
51
+ query: string;
52
+ page: number;
53
+ kinds: SearchKind[] | undefined;
54
+ };
55
+ /** Results as JSON for the modal: no node ids, snippets as safe HTML. */
56
+ export declare function searchJson(results: SearchResults): SearchJson;
57
+ /**
58
+ * The `/search.json` route's answer: the source's results as `SearchJson`, or an empty `404` where
59
+ * the deployment does not answer searches (static builds). Themes call it from their route file.
60
+ */
61
+ export declare function searchJsonResponse(config: Pick<CloudhalRendererConfig, "target">, source: Pick<GraphSource, "mode" | "search"> | undefined, url: URL, options?: {
62
+ locale?: string;
63
+ localize?: ((path: string) => string) | undefined;
64
+ }): Promise<Response>;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Site search for themes (RFC-0019 §3, RFC-0029 §5): the `/search` route's view, safe snippet HTML,
3
+ * the modal's `/search.json` answer and whether the deployment can answer searches at all (static
4
+ * builds cannot; their themes hide the form).
5
+ * Worker-safe.
6
+ */
7
+ import {
8
+ MARK_CLOSE,
9
+ MARK_OPEN,
10
+ SEARCH_PATH,
11
+
12
+
13
+ searchKinds,
14
+ } from "@cloudhal/core-ts";
15
+
16
+
17
+
18
+ export { SEARCH_PATH } from "@cloudhal/core-ts";
19
+
20
+ /** What the `/search` route hands the theme. */
21
+
22
+
23
+ /** The `q` and page of a search request (`?q=…&page=n`); the query is capped by the store. */
24
+ export function searchRequest(search ) {
25
+ const params = new URLSearchParams(search);
26
+ const page = Number(params.get("page") ?? "1");
27
+ return {
28
+ query: params.get("q") ?? "",
29
+ page: Number.isInteger(page) && page >= 1 ? page : 1,
30
+ };
31
+ }
32
+
33
+ /** The URL of a results page (page 1 has no `page` parameter). */
34
+ export function searchPageHref(query , page ) {
35
+ const params = new URLSearchParams({ q: query });
36
+ if (page > 1) params.set("page", String(page));
37
+ return `${SEARCH_PATH}?${params}`;
38
+ }
39
+
40
+ const escapeHtml = (s ) =>
41
+ s.replace(
42
+ /[&<>"']/g,
43
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] ,
44
+ );
45
+
46
+ /** A hit's snippet as HTML: the text escaped first, then `<mark>` around the matches. */
47
+ export function snippetHtml(snippet ) {
48
+ return escapeHtml(snippet).replaceAll(MARK_OPEN, "<mark>").replaceAll(MARK_CLOSE, "</mark>");
49
+ }
50
+
51
+ /**
52
+ * True when this deployment answers `/search`: the Cloudflare Site Worker and `cloudhal dev` (a
53
+ * live source). A static `cloudhal build` renders a snapshot ahead of time with no server to ask,
54
+ * so its theme shows no search form.
55
+ */
56
+ export function searchAvailable(
57
+ config ,
58
+ source ,
59
+ ) {
60
+ return source.search !== undefined && (config.target === "cloudflare" || source.mode === "live");
61
+ }
62
+
63
+ // ── RFC-0029 §5: the JSON the search modal asks ───────────────────────────────────────────────
64
+
65
+ /** The modal's endpoint (`GET /search.json?q=&kinds=&page=`): same index, same rules as `/search`. */
66
+ export const SEARCH_JSON_PATH = "/search.json";
67
+ /** Hits the modal shows per request. */
68
+ export const SEARCH_SUGGEST_SIZE = 8;
69
+
70
+ /** One hit as the modal receives it: the snippet already escaped and marked (`snippetHtml`). */
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+ /** A modal request: `q`, `page`, `kinds` (comma-separated, unknown ones ignored). */
90
+ export function searchJsonRequest(search )
91
+
92
+
93
+
94
+ {
95
+ const kinds = new URLSearchParams(search).get("kinds");
96
+ return {
97
+ ...searchRequest(search),
98
+ kinds: kinds ? searchKinds(kinds.split(",")) : undefined,
99
+ };
100
+ }
101
+
102
+ /** Results as JSON for the modal: no node ids, snippets as safe HTML. */
103
+ export function searchJson(results ) {
104
+ return {
105
+ query: results.query,
106
+ total: results.total,
107
+ page: results.page,
108
+ pages: results.pages,
109
+ stale: results.stale,
110
+ hits: results.hits.map((h) => ({
111
+ title: h.title,
112
+ href: h.href,
113
+ kind: h.kind ?? "article",
114
+ ...(h.context ? { context: h.context } : {}),
115
+ snippetHtml: snippetHtml(h.snippet),
116
+ ...(h.publishedAt ? { publishedAt: h.publishedAt } : {}),
117
+ })),
118
+ };
119
+ }
120
+
121
+ const JSON_HEADERS = {
122
+ "content-type": "application/json; charset=utf-8",
123
+ // per query: never in a browser or edge cache, never in search engines (RFC-0019 §3)
124
+ "cache-control": "no-store",
125
+ "cloudflare-cdn-cache-control": "no-store",
126
+ "x-robots-tag": "noindex",
127
+ };
128
+
129
+ /**
130
+ * The `/search.json` route's answer: the source's results as `SearchJson`, or an empty `404` where
131
+ * the deployment does not answer searches (static builds). Themes call it from their route file.
132
+ */
133
+ export async function searchJsonResponse(
134
+ config ,
135
+ source ,
136
+ url ,
137
+ options = {},
138
+ ) {
139
+ // No body: a static build, which prerenders the route once, then writes no file at all.
140
+ if (!source?.search || !searchAvailable(config, source))
141
+ return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
142
+ const { query, page, kinds } = searchJsonRequest(url.search);
143
+ const results = await source.search(query, {
144
+ page,
145
+ perPage: SEARCH_SUGGEST_SIZE,
146
+ ...(kinds ? { kinds } : {}),
147
+ ...(options.locale ? { locale: options.locale } : {}),
148
+ });
149
+ // RFC-0033: hits link to the locale's URLs (`linkLocalizer`).
150
+ const { localize } = options;
151
+ const shown = localize
152
+ ? { ...results, hits: results.hits.map((h) => ({ ...h, href: localize(h.href) })) }
153
+ : results;
154
+ return new Response(JSON.stringify(searchJson(shown)), { headers: JSON_HEADERS });
155
+ }