@brimsites/brimjs 0.0.0-stage → 1.0.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 (238) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +22 -2
  3. package/bin/brim.js +5 -0
  4. package/dist/cli.js +3802 -0
  5. package/editor-dist/editor.css +1 -0
  6. package/editor-dist/editor.js +91 -0
  7. package/package.json +71 -3
  8. package/skills/brim-convert/SKILL.md +256 -0
  9. package/skills/brim-hosting/SKILL.md +221 -0
  10. package/src/astro-shim.d.ts +5 -0
  11. package/src/auth/accounts.ts +341 -0
  12. package/src/auth/password.ts +34 -0
  13. package/src/auth/permissions.ts +44 -0
  14. package/src/blocks/accordion/Accordion.astro +48 -0
  15. package/src/blocks/accordion/accordion.css +63 -0
  16. package/src/blocks/analytics/Analytics.astro +45 -0
  17. package/src/blocks/analytics/ConsentBanner.astro +41 -0
  18. package/src/blocks/analytics/analytics.client.ts +125 -0
  19. package/src/blocks/analytics/analytics.css +51 -0
  20. package/src/blocks/analytics/consent.ts +51 -0
  21. package/src/blocks/button/Button.astro +64 -0
  22. package/src/blocks/button/button.css +100 -0
  23. package/src/blocks/carousel/Carousel.astro +140 -0
  24. package/src/blocks/carousel/carousel.client.ts +153 -0
  25. package/src/blocks/carousel/carousel.css +181 -0
  26. package/src/blocks/data/icons.ts +285 -0
  27. package/src/blocks/data/image-shapes.ts +91 -0
  28. package/src/blocks/data/social-icons.ts +41 -0
  29. package/src/blocks/data/social-networks.ts +256 -0
  30. package/src/blocks/divider/Divider.astro +27 -0
  31. package/src/blocks/divider/divider.css +17 -0
  32. package/src/blocks/form/Captcha.astro +27 -0
  33. package/src/blocks/form/Form.astro +250 -0
  34. package/src/blocks/form/FormField.astro +138 -0
  35. package/src/blocks/form/Newsletter.astro +80 -0
  36. package/src/blocks/form/form.client.ts +339 -0
  37. package/src/blocks/form/form.css +271 -0
  38. package/src/blocks/gallery/ImageGallery.astro +126 -0
  39. package/src/blocks/gallery/gallery.css +43 -0
  40. package/src/blocks/gallery/lightbox.client.ts +178 -0
  41. package/src/blocks/gallery/lightbox.css +134 -0
  42. package/src/blocks/icon/Icon.astro +41 -0
  43. package/src/blocks/icon/icon.css +16 -0
  44. package/src/blocks/image/Image.astro +158 -0
  45. package/src/blocks/image/image.css +42 -0
  46. package/src/blocks/images.ts +64 -0
  47. package/src/blocks/in-editor.client.ts +8 -0
  48. package/src/blocks/listing/Listing.astro +288 -0
  49. package/src/blocks/listing/ListingCards.astro +48 -0
  50. package/src/blocks/listing/listing.css +136 -0
  51. package/src/blocks/listing/query.ts +363 -0
  52. package/src/blocks/map/Map.astro +75 -0
  53. package/src/blocks/map/map.css +32 -0
  54. package/src/blocks/schemas/accordion.ts +118 -0
  55. package/src/blocks/schemas/button.ts +78 -0
  56. package/src/blocks/schemas/carousel.ts +133 -0
  57. package/src/blocks/schemas/divider.ts +29 -0
  58. package/src/blocks/schemas/form-field-types.ts +29 -0
  59. package/src/blocks/schemas/form.ts +350 -0
  60. package/src/blocks/schemas/icon.ts +24 -0
  61. package/src/blocks/schemas/image-gallery.ts +54 -0
  62. package/src/blocks/schemas/image.ts +87 -0
  63. package/src/blocks/schemas/index.ts +33 -0
  64. package/src/blocks/schemas/listing.ts +14 -0
  65. package/src/blocks/schemas/map.ts +81 -0
  66. package/src/blocks/schemas/newsletter.ts +324 -0
  67. package/src/blocks/schemas/social-media.ts +348 -0
  68. package/src/blocks/schemas/text.ts +151 -0
  69. package/src/blocks/schemas/video.ts +57 -0
  70. package/src/blocks/search/Search.astro +147 -0
  71. package/src/blocks/search/search.css +69 -0
  72. package/src/blocks/search/state.ts +28 -0
  73. package/src/blocks/settings.ts +94 -0
  74. package/src/blocks/social/SocialMedia.astro +102 -0
  75. package/src/blocks/social/social-links.ts +16 -0
  76. package/src/blocks/social/social.css +31 -0
  77. package/src/blocks/theme.ts +35 -0
  78. package/src/blocks/types.ts +52 -0
  79. package/src/blocks/video/Video.astro +90 -0
  80. package/src/blocks/video/video-source.ts +77 -0
  81. package/src/blocks/video/video.client.ts +43 -0
  82. package/src/blocks/video/video.css +29 -0
  83. package/src/check.ts +1119 -0
  84. package/src/cli.ts +493 -0
  85. package/src/components/Blocks.astro +68 -0
  86. package/src/components/Field.astro +61 -0
  87. package/src/components/Footer.astro +36 -0
  88. package/src/components/Link.astro +18 -0
  89. package/src/components/MobileMenu.astro +77 -0
  90. package/src/components/Navbar.astro +42 -0
  91. package/src/components/RichText.astro +32 -0
  92. package/src/components/Seo.astro +202 -0
  93. package/src/components/Setting.astro +46 -0
  94. package/src/components/Shared.astro +17 -0
  95. package/src/components/Text.astro +91 -0
  96. package/src/components/blocks.css +86 -0
  97. package/src/components/index.ts +27 -0
  98. package/src/components/mobile-menu.client.ts +21 -0
  99. package/src/components/mobile-menu.css +52 -0
  100. package/src/components/text.css +48 -0
  101. package/src/config.ts +413 -0
  102. package/src/content/block-layout.ts +63 -0
  103. package/src/content/block-values.ts +48 -0
  104. package/src/content/content-check.ts +174 -0
  105. package/src/content/content-types.ts +408 -0
  106. package/src/content/drafts.ts +115 -0
  107. package/src/content/feed.ts +237 -0
  108. package/src/content/field-types.ts +107 -0
  109. package/src/content/history.ts +140 -0
  110. package/src/content/ids.ts +50 -0
  111. package/src/content/image-size.ts +212 -0
  112. package/src/content/image-sizes.ts +126 -0
  113. package/src/content/item-fields.ts +110 -0
  114. package/src/content/item-head.ts +126 -0
  115. package/src/content/item-image.ts +26 -0
  116. package/src/content/item-path.ts +122 -0
  117. package/src/content/items.ts +580 -0
  118. package/src/content/language-scopes.ts +40 -0
  119. package/src/content/media.ts +271 -0
  120. package/src/content/menus.ts +51 -0
  121. package/src/content/page-templates.ts +52 -0
  122. package/src/content/redirects.ts +112 -0
  123. package/src/content/references.ts +165 -0
  124. package/src/content/rich-text.ts +63 -0
  125. package/src/content/search.ts +167 -0
  126. package/src/content/seed.ts +229 -0
  127. package/src/content/site-settings.ts +111 -0
  128. package/src/content/sitemap.ts +143 -0
  129. package/src/content/store.ts +225 -0
  130. package/src/content/tags.ts +67 -0
  131. package/src/content/text-default.ts +139 -0
  132. package/src/content/types.ts +137 -0
  133. package/src/content/validate.ts +253 -0
  134. package/src/content/validation-error.ts +2 -0
  135. package/src/db/cached.ts +140 -0
  136. package/src/db/database.ts +15 -0
  137. package/src/db/libsql.ts +29 -0
  138. package/src/db/schema.ts +189 -0
  139. package/src/db/url.ts +44 -0
  140. package/src/editor/client/BlockSettings.tsx +1063 -0
  141. package/src/editor/client/Chrome.tsx +284 -0
  142. package/src/editor/client/ContentBrowser.tsx +1299 -0
  143. package/src/editor/client/Editor.tsx +1756 -0
  144. package/src/editor/client/HistoryPanel.tsx +114 -0
  145. package/src/editor/client/ImagesWidget.tsx +113 -0
  146. package/src/editor/client/Inspector.tsx +127 -0
  147. package/src/editor/client/ItemForm.tsx +535 -0
  148. package/src/editor/client/LinkWidget.tsx +440 -0
  149. package/src/editor/client/ListingPanel.tsx +99 -0
  150. package/src/editor/client/Login.tsx +338 -0
  151. package/src/editor/client/Menu.tsx +64 -0
  152. package/src/editor/client/PageSettings.tsx +270 -0
  153. package/src/editor/client/RedirectsSettings.tsx +130 -0
  154. package/src/editor/client/Resize.tsx +204 -0
  155. package/src/editor/client/Sidebar.tsx +51 -0
  156. package/src/editor/client/SiteMap.tsx +568 -0
  157. package/src/editor/client/SiteSettings.tsx +409 -0
  158. package/src/editor/client/TextTools.tsx +391 -0
  159. package/src/editor/client/Toolbar.tsx +449 -0
  160. package/src/editor/client/VideoUpload.tsx +251 -0
  161. package/src/editor/client/api.ts +417 -0
  162. package/src/editor/client/brand.ts +20 -0
  163. package/src/editor/client/connection.ts +98 -0
  164. package/src/editor/client/context.ts +19 -0
  165. package/src/editor/client/css.d.ts +2 -0
  166. package/src/editor/client/editor.css +4656 -0
  167. package/src/editor/client/fields.tsx +812 -0
  168. package/src/editor/client/icons.tsx +174 -0
  169. package/src/editor/client/keys.ts +15 -0
  170. package/src/editor/client/kinds.ts +289 -0
  171. package/src/editor/client/languages.ts +32 -0
  172. package/src/editor/client/main.tsx +100 -0
  173. package/src/editor/client/responses.ts +26 -0
  174. package/src/editor/client/rich-text.ts +326 -0
  175. package/src/editor/client/site-tree.ts +239 -0
  176. package/src/editor/client/theme.ts +55 -0
  177. package/src/editor/client/tsconfig.json +18 -0
  178. package/src/editor/client/tus.ts +137 -0
  179. package/src/editor/client/use-rect.ts +50 -0
  180. package/src/editor/client/widgets.tsx +1218 -0
  181. package/src/forms/captcha.ts +83 -0
  182. package/src/forms/define.ts +166 -0
  183. package/src/forms/fields.ts +197 -0
  184. package/src/forms/file-types.ts +108 -0
  185. package/src/forms/files.ts +216 -0
  186. package/src/forms/form-page.ts +9 -0
  187. package/src/forms/handler.ts +622 -0
  188. package/src/forms/spec.ts +89 -0
  189. package/src/forms/store.ts +96 -0
  190. package/src/forms/work.ts +50 -0
  191. package/src/icons/library.ts +144 -0
  192. package/src/icons/load.ts +63 -0
  193. package/src/index.ts +99 -0
  194. package/src/init.ts +257 -0
  195. package/src/integration.ts +469 -0
  196. package/src/mail/mailer.ts +197 -0
  197. package/src/mail/notify.ts +272 -0
  198. package/src/mail/settings.ts +173 -0
  199. package/src/mail/templates.ts +191 -0
  200. package/src/mcp/page-nodes.ts +209 -0
  201. package/src/mcp/server.ts +111 -0
  202. package/src/mcp/tools.ts +637 -0
  203. package/src/runtime/TemplatePage.astro +39 -0
  204. package/src/runtime/TemplatePageStatic.astro +13 -0
  205. package/src/runtime/admin-route.ts +80 -0
  206. package/src/runtime/connect.ts +53 -0
  207. package/src/runtime/content.ts +188 -0
  208. package/src/runtime/context.ts +131 -0
  209. package/src/runtime/form-files.ts +18 -0
  210. package/src/runtime/forms-route.ts +33 -0
  211. package/src/runtime/forms.ts +28 -0
  212. package/src/runtime/icons.ts +5 -0
  213. package/src/runtime/media.ts +175 -0
  214. package/src/runtime/middleware.ts +186 -0
  215. package/src/runtime/nav.ts +13 -0
  216. package/src/runtime/query-reads.ts +49 -0
  217. package/src/runtime/query-store.ts +16 -0
  218. package/src/runtime/request-state.ts +69 -0
  219. package/src/runtime/robots.ts +29 -0
  220. package/src/runtime/rss-static.ts +16 -0
  221. package/src/runtime/rss.ts +29 -0
  222. package/src/runtime/server.ts +29 -0
  223. package/src/runtime/sitemap.ts +34 -0
  224. package/src/runtime/template-paths.ts +34 -0
  225. package/src/runtime/uploads-route.ts +13 -0
  226. package/src/seed-cli.ts +253 -0
  227. package/src/server/auth.ts +31 -0
  228. package/src/server/fetch-image.ts +219 -0
  229. package/src/server/handler.ts +2106 -0
  230. package/src/server/http.ts +162 -0
  231. package/src/server/locales.ts +73 -0
  232. package/src/server/node.ts +57 -0
  233. package/src/server/query-params.ts +249 -0
  234. package/src/server/rate-limit.ts +72 -0
  235. package/src/server/video-host.ts +162 -0
  236. package/src/starter.ts +70 -0
  237. package/src/version.ts +4 -0
  238. package/src/virtual.d.ts +65 -0
@@ -0,0 +1,143 @@
1
+ import { type LocaleConfig, itemPagePath } from "../server/locales.ts";
2
+ import { fillItemPath, itemPathSegments } from "./item-path.ts";
3
+ import type { ContentType } from "./content-types.ts";
4
+ import { normalizePagePath } from "./ids.ts";
5
+ import type { Item, ItemStore } from "./items.ts";
6
+ import type { PageTemplate } from "./page-templates.ts";
7
+ import type { ContentStore } from "./store.ts";
8
+
9
+ /** The site's routes as Astro resolved them, which is all the sitemap needs to know about the code. */
10
+ export interface SiteRoutes {
11
+ /** Pages with a fixed address, written in `src/pages`. */
12
+ pages: string[];
13
+ /** Patterns of dynamic pages, e.g. `/projects/[slug]`: the pages of items a type without a template has. */
14
+ patterns: string[];
15
+ }
16
+
17
+ export interface SitemapEntry {
18
+ path: string;
19
+ /** `YYYY-MM-DD`, when Brim knows when the page last changed. */
20
+ lastModified?: string;
21
+ }
22
+
23
+ interface Sources {
24
+ content: ContentStore;
25
+ items: ItemStore;
26
+ contentTypes: ContentType[];
27
+ pageTemplates: PageTemplate[];
28
+ routes: SiteRoutes;
29
+ /** The site's languages: an item in another language has its page under that language's prefix. */
30
+ locales?: LocaleConfig | undefined;
31
+ }
32
+
33
+ /**
34
+ * Every page the public build contains and search engines may list: pages written in code, pages added
35
+ * from templates and the pages of content items, published and not hidden from search engines.
36
+ * It reads the content when asked, so a page or item the owner just added is in the next sitemap.
37
+ */
38
+ export async function sitemapEntries({
39
+ content,
40
+ items,
41
+ contentTypes,
42
+ pageTemplates,
43
+ routes,
44
+ locales,
45
+ }: Sources): Promise<SitemapEntry[]> {
46
+ const listed = new Map<string, SitemapEntry>();
47
+ const templateKeys = new Set(pageTemplates.map((template) => template.key));
48
+
49
+ const pages = [
50
+ ...(await Promise.all([...new Set(routes.pages.map(normalizePagePath))].map((path) => content.page(path)))),
51
+ // A page whose template left the code is not built, so it is not listed either.
52
+ ...(await content.templatePages({ publishedOnly: true })).filter((page) => templateKeys.has(page.template ?? "")),
53
+ ];
54
+ for (const page of pages) {
55
+ if (page.visibility === "published" && !page.seo.noindex && pointsHere(page.path, page.seo.canonical)) {
56
+ listed.set(page.path, { path: page.path });
57
+ }
58
+ }
59
+
60
+ // An item's page takes the same settings by address as any page: "hide from search engines" and a canonical
61
+ // address elsewhere keep it out, as they do for pages.
62
+ const seoByPath = await content.pageSeoSettings();
63
+ for (const type of contentTypes) {
64
+ for (const item of await items.list(type.key, { publishedOnly: true, sort: "oldest" })) {
65
+ const path = itemPagePath(type, item, locales);
66
+ if (!itemHasPage(type, item, path, routes)) continue;
67
+ const seo = seoByPath.get(normalizePagePath(path));
68
+ if (seo?.noindex || !pointsHere(normalizePagePath(path), seo?.canonical)) continue;
69
+ listed.set(path, { path, lastModified: item.updatedAt.slice(0, 10) });
70
+ }
71
+ }
72
+ return [...listed.values()].sort((a, b) => a.path.localeCompare(b.path));
73
+ }
74
+
75
+ /**
76
+ * Whether the item at `path` (from `itemPagePath`) has a page. A type with a template has a page per item, in every
77
+ * language. Without one, an item has a page only where the code draws one: `/projects/[slug]`, `/ro/projects/[slug]`
78
+ * or `/[locale]/…`.
79
+ */
80
+ export function itemHasPage(
81
+ type: ContentType,
82
+ item: Pick<Item, "slug" | "data">,
83
+ path: string,
84
+ routes: SiteRoutes,
85
+ ): boolean {
86
+ if (type.component) return true;
87
+ const own = fillItemPath(type, item);
88
+ const prefix = path.slice(0, path.length - own.length);
89
+ const hasPages = (start: string) => routes.patterns.some((pattern) => drawsItems(type, pattern, start));
90
+ return hasPages(prefix) || (prefix !== "" && (hasPages("/[locale]") || hasPages("/[lang]")));
91
+ }
92
+
93
+ /**
94
+ * Whether a route of the code draws a type's items: `/projects/[slug]` for `/projects/<item>`, and for a `path`
95
+ * like `/produse/[category]/[slug]` a route with the same fixed segments and a parameter at each of its own.
96
+ */
97
+ function drawsItems(type: ContentType, pattern: string, prefix: string): boolean {
98
+ if (!pattern.startsWith(`${prefix}/`)) return false;
99
+ const segments = itemPathSegments(type);
100
+ if (type.path === undefined) return pattern.startsWith(`${prefix}/${type.slug}/[`);
101
+ const parts = pattern.slice(prefix.length).split("/").slice(1);
102
+ return (
103
+ parts.length === segments.length &&
104
+ segments.every((segment, index) => {
105
+ const part = parts[index] ?? "";
106
+ return "fixed" in segment ? part === segment.fixed : part.startsWith("[") && !part.startsWith("[...");
107
+ })
108
+ );
109
+ }
110
+
111
+ /**
112
+ * Whether a dynamic route of the code draws the items of one of the types, with or without a language in front: a
113
+ * route that draws none is a set of pages the sitemap cannot list, since only the route knows its addresses.
114
+ */
115
+ export function routeDrawsItems(types: ContentType[], pattern: string): boolean {
116
+ return types.some((type) => ["", "/[locale]", "/[lang]"].some((prefix) => drawsItems(type, pattern, prefix)));
117
+ }
118
+
119
+ /** A page whose canonical address is another page's is that page's duplicate: search engines list the other. */
120
+ function pointsHere(path: string, canonical: string | undefined): boolean {
121
+ if (!canonical) return true;
122
+ if (!canonical.startsWith("/")) return false;
123
+ return normalizePagePath(new URL(canonical, "https://site.invalid").pathname) === path;
124
+ }
125
+
126
+ /** The sitemap protocol's XML (sitemaps.org). `site` is the public address, e.g. `https://example.com`. */
127
+ export function sitemapXml(entries: SitemapEntry[], site: string | URL): string {
128
+ const urls = entries.map(({ path, lastModified }) => {
129
+ const location = escapeXml(new URL(path, site).href);
130
+ return ` <url><loc>${location}</loc>${lastModified ? `<lastmod>${lastModified}</lastmod>` : ""}</url>`;
131
+ });
132
+ return [
133
+ '<?xml version="1.0" encoding="UTF-8"?>',
134
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
135
+ ...urls,
136
+ "</urlset>",
137
+ "",
138
+ ].join("\n");
139
+ }
140
+
141
+ export function escapeXml(text: string): string {
142
+ return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
143
+ }
@@ -0,0 +1,225 @@
1
+ import type { Database, Row } from "../db/database.ts";
2
+ import { assertNodeId, normalizePagePath, pageScope } from "./ids.ts";
3
+ import type { Redirect } from "./redirects.ts";
4
+ import type { PageRecord, SeoSettings, StoredNode, Visibility } from "./types.ts";
5
+
6
+ /** Kept in brim_meta, as one JSON value: a short list read on every visit. */
7
+ const REDIRECTS_KEY = "redirects";
8
+
9
+ /** Reads and writes the owner's content. Source code is never touched. */
10
+ export class ContentStore {
11
+ readonly #db: Database;
12
+
13
+ constructor(db: Database) {
14
+ this.#db = db;
15
+ }
16
+
17
+ async loadNodes(scopes: string[]): Promise<StoredNode[]> {
18
+ if (scopes.length === 0) return [];
19
+ const placeholders = scopes.map(() => "?").join(", ");
20
+ const rows = await this.#db.query(
21
+ `SELECT scope, node_id, kind, value FROM brim_nodes WHERE scope IN (${placeholders})`,
22
+ scopes,
23
+ );
24
+ return rows.map((row) => ({
25
+ scope: String(row.scope),
26
+ nodeId: String(row.node_id),
27
+ kind: String(row.kind),
28
+ value: JSON.parse(String(row.value)) as unknown,
29
+ }));
30
+ }
31
+
32
+ /** Every saved node of the site, in every scope: what a check of the whole content reads. */
33
+ async allNodes(): Promise<StoredNode[]> {
34
+ const rows = await this.#db.query("SELECT scope, node_id, kind, value FROM brim_nodes", []);
35
+ return rows.map((row) => ({
36
+ scope: String(row.scope),
37
+ nodeId: String(row.node_id),
38
+ kind: String(row.kind),
39
+ value: JSON.parse(String(row.value)) as unknown,
40
+ }));
41
+ }
42
+
43
+ /** `value` must already be validated: see `parseNodeValue` and `parseSettings`. */
44
+ async saveNode(scope: string, nodeId: string, kind: string, value: unknown): Promise<void> {
45
+ assertNodeId(nodeId);
46
+ await this.#db.query(
47
+ `INSERT INTO brim_nodes (scope, node_id, kind, value, updated_at) VALUES (?, ?, ?, ?, ?)
48
+ ON CONFLICT (scope, node_id) DO UPDATE SET kind = excluded.kind, value = excluded.value, updated_at = excluded.updated_at`,
49
+ [scope, nodeId, kind, JSON.stringify(value), now()],
50
+ );
51
+ }
52
+
53
+ /** Removes the owner's value, so the page falls back to what the source says. */
54
+ async resetNode(scope: string, nodeId: string): Promise<void> {
55
+ await this.#db.query("DELETE FROM brim_nodes WHERE scope = ? AND node_id = ?", [scope, nodeId]);
56
+ }
57
+
58
+ /** Moves everything saved on one page to another address, e.g. when an item's address changes. */
59
+ async moveNodes(fromScope: string, toScope: string): Promise<void> {
60
+ await this.#db.batch([
61
+ // What was already saved at the new address gives way to what moves there.
62
+ { sql: "DELETE FROM brim_nodes WHERE scope = ?", args: [toScope] },
63
+ { sql: "UPDATE brim_nodes SET scope = ? WHERE scope = ?", args: [toScope, fromScope] },
64
+ ]);
65
+ }
66
+
67
+ /**
68
+ * Copies what was saved on one page to another, leaving alone what the other page already has: a translation
69
+ * starts from the original's words and never loses what was already translated. Returns how many were copied.
70
+ */
71
+ async copyNodes(fromScope: string, toScope: string): Promise<number> {
72
+ const count = async (): Promise<number> =>
73
+ Number((await this.#db.query("SELECT COUNT(*) AS n FROM brim_nodes WHERE scope = ?", [toScope]))[0]?.n ?? 0);
74
+ const before = await count();
75
+ await this.#db.query(
76
+ `INSERT INTO brim_nodes (scope, node_id, kind, value, updated_at)
77
+ SELECT ?, node_id, kind, value, ? FROM brim_nodes WHERE scope = ?
78
+ ON CONFLICT (scope, node_id) DO NOTHING`,
79
+ [toScope, now(), fromScope],
80
+ );
81
+ return (await count()) - before;
82
+ }
83
+
84
+ async removeNodes(scope: string): Promise<void> {
85
+ await this.#db.query("DELETE FROM brim_nodes WHERE scope = ?", [scope]);
86
+ }
87
+
88
+ /** A page nobody has touched is published and has no SEO settings: pages come from source. */
89
+ async page(pathname: string): Promise<PageRecord> {
90
+ const path = normalizePagePath(pathname);
91
+ const rows = await this.#db.query("SELECT * FROM brim_pages WHERE path = ?", [path]);
92
+ return rows[0] ? toPage(rows[0]) : { path, visibility: "published", seo: {} };
93
+ }
94
+
95
+ /** The search settings of every page that has some, by address (pages of items included). */
96
+ async pageSeoSettings(): Promise<Map<string, SeoSettings>> {
97
+ const rows = await this.#db.query("SELECT path, seo FROM brim_pages WHERE seo IS NOT NULL AND seo != '{}'");
98
+ return new Map(rows.map((row) => [String(row.path), JSON.parse(String(row.seo)) as SeoSettings]));
99
+ }
100
+
101
+ /** Pages the owner added from a template, by address. The public build asks for published ones only. */
102
+ async templatePages(options: { publishedOnly?: boolean } = {}): Promise<PageRecord[]> {
103
+ const rows = await this.#db.query(
104
+ `SELECT * FROM brim_pages WHERE template IS NOT NULL${options.publishedOnly ? " AND visibility = 'published'" : ""}
105
+ ORDER BY path`,
106
+ );
107
+ return rows.map(toPage);
108
+ }
109
+
110
+ /**
111
+ * Adds a page made from a template. It starts private, so the owner can fill it in before anyone sees it.
112
+ * The caller checks that the address belongs to no other page.
113
+ */
114
+ async createPage(pathname: string, template: string, title: string, visibility: Visibility): Promise<PageRecord> {
115
+ const path = normalizePagePath(pathname);
116
+ // A row left by a page that was removed from the code is taken over.
117
+ await this.#db.query(
118
+ `INSERT INTO brim_pages (path, visibility, seo, template, title, updated_at) VALUES (?, ?, '{}', ?, ?, ?)
119
+ ON CONFLICT (path) DO UPDATE SET visibility = excluded.visibility, seo = '{}', template = excluded.template,
120
+ title = excluded.title, updated_at = excluded.updated_at`,
121
+ [path, visibility, template, title, now()],
122
+ );
123
+ return { path, visibility, seo: {}, template, title };
124
+ }
125
+
126
+ async setPageTitle(pathname: string, title: string): Promise<void> {
127
+ await this.#db.query("UPDATE brim_pages SET title = ?, updated_at = ? WHERE path = ?", [
128
+ title,
129
+ now(),
130
+ normalizePagePath(pathname),
131
+ ]);
132
+ }
133
+
134
+ /** Removes a page added from a template together with everything the owner wrote on it. */
135
+ async deletePage(pathname: string): Promise<void> {
136
+ const path = normalizePagePath(pathname);
137
+ await this.#db.batch([
138
+ { sql: "DELETE FROM brim_nodes WHERE scope = ?", args: [pageScope(path)] },
139
+ { sql: "DELETE FROM brim_pages WHERE path = ? AND template IS NOT NULL", args: [path] },
140
+ ]);
141
+ }
142
+
143
+ async setPageVisibility(pathname: string, visibility: Visibility): Promise<void> {
144
+ await this.#db.query(
145
+ `INSERT INTO brim_pages (path, visibility, updated_at) VALUES (?, ?, ?)
146
+ ON CONFLICT (path) DO UPDATE SET visibility = excluded.visibility, updated_at = excluded.updated_at`,
147
+ [normalizePagePath(pathname), visibility, now()],
148
+ );
149
+ }
150
+
151
+ /**
152
+ * Moves a page added from a template to a new address, with everything the owner wrote on it. The caller checks
153
+ * that the new address is free and adds the redirect from the old one.
154
+ */
155
+ async movePage(fromPath: string, toPath: string): Promise<void> {
156
+ const from = normalizePagePath(fromPath);
157
+ const to = normalizePagePath(toPath);
158
+ await this.#db.batch([
159
+ { sql: "DELETE FROM brim_nodes WHERE scope = ?", args: [pageScope(to)] },
160
+ { sql: "UPDATE brim_nodes SET scope = ? WHERE scope = ?", args: [pageScope(to), pageScope(from)] },
161
+ { sql: "DELETE FROM brim_pages WHERE path = ?", args: [to] },
162
+ { sql: "UPDATE brim_pages SET path = ?, updated_at = ? WHERE path = ?", args: [to, now(), from] },
163
+ ]);
164
+ }
165
+
166
+ /**
167
+ * Carries a page's search settings to its new address, for a page whose address follows something else (an item's
168
+ * slug or category): they are kept by address, so without this a page hidden from search engines would be listed
169
+ * when its address changed.
170
+ */
171
+ async movePageSettings(fromPath: string, toPath: string): Promise<void> {
172
+ const from = normalizePagePath(fromPath);
173
+ const to = normalizePagePath(toPath);
174
+ if (from === to) return;
175
+ const { seo } = await this.page(from);
176
+ if (Object.keys(seo).length > 0) {
177
+ await this.setPageSeo(to, seo);
178
+ await this.setPageSeo(from, {});
179
+ }
180
+ }
181
+
182
+ /** The site's redirects, in the order the owner keeps them. */
183
+ async redirects(): Promise<Redirect[]> {
184
+ return (await this.#meta<Redirect[]>(REDIRECTS_KEY)) ?? [];
185
+ }
186
+
187
+ /** `redirects` must already be checked: see `parseRedirects`. */
188
+ async setRedirects(redirects: Redirect[]): Promise<void> {
189
+ await this.#setMeta(REDIRECTS_KEY, redirects);
190
+ }
191
+
192
+ async #meta<T>(key: string): Promise<T | undefined> {
193
+ const rows = await this.#db.query("SELECT value FROM brim_meta WHERE key = ?", [key]);
194
+ return rows[0] ? (JSON.parse(String(rows[0].value)) as T) : undefined;
195
+ }
196
+
197
+ async #setMeta(key: string, value: unknown): Promise<void> {
198
+ await this.#db.query(
199
+ "INSERT INTO brim_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
200
+ [key, JSON.stringify(value)],
201
+ );
202
+ }
203
+
204
+ /** `seo` must already be validated: see `parseSeo`. */
205
+ async setPageSeo(pathname: string, seo: SeoSettings): Promise<void> {
206
+ await this.#db.query(
207
+ `INSERT INTO brim_pages (path, visibility, seo, updated_at) VALUES (?, 'published', ?, ?)
208
+ ON CONFLICT (path) DO UPDATE SET seo = excluded.seo, updated_at = excluded.updated_at`,
209
+ [normalizePagePath(pathname), JSON.stringify(seo), now()],
210
+ );
211
+ }
212
+ }
213
+
214
+ function toPage(row: Row): PageRecord {
215
+ return {
216
+ path: String(row.path),
217
+ visibility: row.visibility === "private" ? "private" : "published",
218
+ seo: JSON.parse(String(row.seo)) as SeoSettings,
219
+ ...(row.template != null && { template: String(row.template), title: String(row.title ?? "") }),
220
+ };
221
+ }
222
+
223
+ function now(): string {
224
+ return new Date().toISOString();
225
+ }
@@ -0,0 +1,67 @@
1
+ import { ValidationError } from "./validation-error.ts";
2
+
3
+ /** How many tags an item's field or a page holds at most. */
4
+ export const MAX_TAGS = 50;
5
+ const MAX_TAG_LENGTH = 60;
6
+
7
+ /**
8
+ * Turns untrusted input into tags: short words or phrases, trimmed, each once whatever its case, in the order
9
+ * given. `options` limits them to a fixed list, spelled as it spells them; `label` names the field in what the
10
+ * owner reads when one is refused.
11
+ */
12
+ export function parseTags(value: unknown, label: string, options?: readonly string[]): string[] {
13
+ const fail = (problem: string): never => {
14
+ throw new ValidationError(`"${label}" ${problem}.`);
15
+ };
16
+ if (!Array.isArray(value)) return fail("must be a list of tags");
17
+ if (value.length > MAX_TAGS) return fail(`can hold at most ${MAX_TAGS} tags`);
18
+ const tags: string[] = [];
19
+ for (const entry of value) {
20
+ if (typeof entry !== "string") return fail("must be a list of tags");
21
+ const typed = cleanTag(entry);
22
+ if (typed === "") continue;
23
+ if (typed.length > MAX_TAG_LENGTH) return fail(`has a tag longer than ${MAX_TAG_LENGTH} characters`);
24
+ // A field with a list of its own keeps each tag as the list spells it.
25
+ const tag = options ? options.find((option) => sameTag(option, typed)) : typed;
26
+ if (tag === undefined) return fail(`does not offer the tag "${typed}"`);
27
+ if (!hasTag(tags, tag)) tags.push(tag);
28
+ }
29
+ return tags;
30
+ }
31
+
32
+ /** A tag as it is kept: trimmed, with one space between its words. */
33
+ export function cleanTag(text: string): string {
34
+ return text.trim().replace(/\s+/g, " ");
35
+ }
36
+
37
+ /** Whether two tags are the same, whatever their case. */
38
+ export function sameTag(a: string, b: string): boolean {
39
+ return a.toLocaleLowerCase() === b.toLocaleLowerCase();
40
+ }
41
+
42
+ /** The tags in a stored value, whatever it holds: a list of text, or nothing. */
43
+ export function tagsOf(value: unknown): string[] {
44
+ return Array.isArray(value) ? value.filter((tag): tag is string => typeof tag === "string") : [];
45
+ }
46
+
47
+ /**
48
+ * The tags used across several lists, most used first, then alphabetically, each once with the spelling it was
49
+ * first given: what the editor offers while a tag is typed, and the tags it filters content by.
50
+ */
51
+ export function rankTags(lists: unknown[]): { tag: string; count: number }[] {
52
+ const counts = new Map<string, { tag: string; count: number }>();
53
+ for (const list of lists) {
54
+ for (const tag of new Set(tagsOf(list))) {
55
+ const key = tag.toLocaleLowerCase();
56
+ const known = counts.get(key);
57
+ if (known) known.count += 1;
58
+ else counts.set(key, { tag, count: 1 });
59
+ }
60
+ }
61
+ return [...counts.values()].sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag));
62
+ }
63
+
64
+ /** Whether a list of tags has this one, whatever its case. */
65
+ export function hasTag(tags: readonly string[], wanted: string): boolean {
66
+ return tags.some((tag) => sameTag(tag, wanted));
67
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Checks the default content a site author wrote inside `<Text>`, before the owner edits it.
3
+ *
4
+ * The editor starts from what the page shows and saves it as the inline formatting `TextValue.rich` can hold. What
5
+ * that cannot hold would be dropped without a word on the owner's first edit: a nested Brim element (and every
6
+ * later edit to it), a paragraph or a list, a picture, an element's class. So it is named here instead, while
7
+ * the author can still change the code.
8
+ */
9
+
10
+ /** Elements `rich` keeps, and the attributes each may carry. `b`, `i`, `strike` and `del` are saved under their usual names. */
11
+ const KEPT_ELEMENTS: Record<string, readonly string[]> = {
12
+ br: [],
13
+ strong: [],
14
+ b: [],
15
+ em: [],
16
+ i: [],
17
+ u: [],
18
+ s: [],
19
+ strike: [],
20
+ del: [],
21
+ sub: [],
22
+ sup: [],
23
+ a: ["href"],
24
+ span: ["style"],
25
+ };
26
+
27
+ /** Elements that make a block of their own: a `Text` is one element of words, so they belong in a `RichText`. */
28
+ const BLOCK_ELEMENTS = new Set([
29
+ "address",
30
+ "article",
31
+ "aside",
32
+ "blockquote",
33
+ "dd",
34
+ "details",
35
+ "dialog",
36
+ "div",
37
+ "dl",
38
+ "dt",
39
+ "fieldset",
40
+ "figcaption",
41
+ "figure",
42
+ "footer",
43
+ "form",
44
+ "h1",
45
+ "h2",
46
+ "h3",
47
+ "h4",
48
+ "h5",
49
+ "h6",
50
+ "header",
51
+ "hgroup",
52
+ "hr",
53
+ "li",
54
+ "main",
55
+ "nav",
56
+ "ol",
57
+ "p",
58
+ "pre",
59
+ "section",
60
+ "table",
61
+ "ul",
62
+ ]);
63
+
64
+ /** Colors the editor reads back from a `span`: the ones it would write itself. */
65
+ const KEPT_COLOR = /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,/%]+\))$/i;
66
+
67
+ // Opening tags only: a closing tag carries nothing that could be lost. Comments are skipped whole.
68
+ const TAG =
69
+ /<!--[\s\S]*?-->|<([a-zA-Z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*\/?>/g;
70
+ const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
71
+
72
+ /**
73
+ * What in a `Text`'s default HTML its saved value could not keep, said for the site author, or `undefined` when an
74
+ * edit keeps it all. Spaces and Astro's own `data-astro-*` attributes (scoped styles, the dev toolbar) do not count.
75
+ */
76
+ export function unkeptTextMarkup(html: string): string | undefined {
77
+ for (const match of html.matchAll(TAG)) {
78
+ const [whole, name, attributeText = ""] = match;
79
+ if (name === undefined) continue;
80
+ const tag = name.toLowerCase();
81
+ const attributes = parseAttributes(attributeText);
82
+ const shown = openingTag(whole);
83
+
84
+ const nested = attributes.get("data-brim-node");
85
+ if (nested !== undefined) return `another Brim element, "${nested}" (${shown})`;
86
+ if (BLOCK_ELEMENTS.has(tag)) return `a block element, ${shown}`;
87
+
88
+ const allowed = KEPT_ELEMENTS[tag];
89
+ if (!allowed) return shown;
90
+ for (const [attribute, value] of attributes) {
91
+ if (attribute.startsWith("data-astro-")) continue;
92
+ if (!allowed.includes(attribute)) return `${shown}, with its "${attribute}" attribute`;
93
+ if (attribute === "style" && !keepsStyle(value)) return `${shown}, with a style other than a color`;
94
+ }
95
+ if (tag === "a" && !attributes.get("href")) return `${shown}, a link without an address`;
96
+ }
97
+ return undefined;
98
+ }
99
+
100
+ /** The error for a `Text` whose default content an edit would not keep, naming the node and the way out. */
101
+ export function textDefaultError(nodeId: string, html: string): string | undefined {
102
+ const unkept = unkeptTextMarkup(html);
103
+ if (!unkept) return undefined;
104
+ return (
105
+ `Brim: the content of <Text nodeId="${nodeId}"> in the code holds ${unkept}, ` +
106
+ "which the owner's first edit would lose. " +
107
+ "A Text keeps words, line breaks, bold, italic, underline, strikethrough, sub- and superscript, colors and links " +
108
+ '(<br>, <strong>, <em>, <u>, <s>, <sub>, <sup>, <span style="color">, <a href>), with no other attributes. ' +
109
+ "Use <RichText> for paragraphs and lists, move other elements out of the Text, or split it into several Text " +
110
+ "elements, each with its own nodeId, and style the Text element itself."
111
+ );
112
+ }
113
+
114
+ function parseAttributes(text: string): Map<string, string> {
115
+ const attributes = new Map<string, string>();
116
+ for (const [, name = "", double, single, bare] of text.matchAll(ATTRIBUTE)) {
117
+ attributes.set(name.toLowerCase(), double ?? single ?? bare ?? "");
118
+ }
119
+ return attributes;
120
+ }
121
+
122
+ /** Only `color` and `background-color`, as the editor writes them, survive being read back. */
123
+ function keepsStyle(style: string): boolean {
124
+ return style
125
+ .split(";")
126
+ .map((declaration) => declaration.trim())
127
+ .filter(Boolean)
128
+ .every((declaration) => {
129
+ const [property = "", ...rest] = declaration.split(":");
130
+ const value = rest.join(":").trim();
131
+ return ["color", "background-color"].includes(property.trim().toLowerCase()) && KEPT_COLOR.test(value);
132
+ });
133
+ }
134
+
135
+ /** The tag as the author would recognise it: without Astro's attributes or the editor's, but its nodeId, and short. */
136
+ function openingTag(tag: string): string {
137
+ const cleaned = tag.replace(/\s+data-(?:astro-[\w-]+|brim-(?!node\b)[\w-]+)(?:="[^"]*"|='[^']*')?/g, "");
138
+ return cleaned.length > 80 ? `${cleaned.slice(0, 77)}...` : cleaned;
139
+ }