@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,63 @@
1
+ import type { InlineNode, RichTextBlock, TextAlign, TextTag } from "./types.ts";
2
+
3
+ export const TEXT_TAGS: readonly TextTag[] = [
4
+ "p",
5
+ "span",
6
+ "h1",
7
+ "h2",
8
+ "h3",
9
+ "h4",
10
+ "h5",
11
+ "h6",
12
+ "blockquote",
13
+ "label",
14
+ "strong",
15
+ "em",
16
+ "small",
17
+ ];
18
+
19
+ const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
20
+
21
+ function escapeHtml(text: string): string {
22
+ return text.replace(/[&<>"]/g, (character) => ESCAPES[character] ?? character);
23
+ }
24
+
25
+ /** Turns validated formatting into HTML. Every string is escaped, so the result is safe to inline. */
26
+ export function renderInline(nodes: InlineNode[]): string {
27
+ return nodes
28
+ .map((node) => {
29
+ if (typeof node === "string") return escapeHtml(node);
30
+ if (node.tag === "br") return "<br>";
31
+ const children = renderInline(node.children);
32
+ if (node.tag === "a") return `<a href="${escapeHtml(node.href)}">${children}</a>`;
33
+ if (node.tag === "span") return `<span${styleAttribute(spanStyle(node))}>${children}</span>`;
34
+ return `<${node.tag}>${children}</${node.tag}>`;
35
+ })
36
+ .join("");
37
+ }
38
+
39
+ export function renderBlocks(blocks: RichTextBlock[]): string {
40
+ return blocks
41
+ .map((block) => {
42
+ if ("items" in block) {
43
+ const items = block.items.map((item) => `<li>${renderInline(item)}</li>`).join("");
44
+ return `<${block.tag}>${items}</${block.tag}>`;
45
+ }
46
+ return `<${block.tag}${styleAttribute(alignStyle(block.align))}>${renderInline(block.children)}</${block.tag}>`;
47
+ })
48
+ .join("");
49
+ }
50
+
51
+ export function alignStyle(align: TextAlign | undefined): string {
52
+ return align ? `text-align:${align}` : "";
53
+ }
54
+
55
+ function spanStyle(node: { color?: string; background?: string }): string {
56
+ return [node.color && `color:${node.color}`, node.background && `background-color:${node.background}`]
57
+ .filter(Boolean)
58
+ .join(";");
59
+ }
60
+
61
+ function styleAttribute(style: string): string {
62
+ return style ? ` style="${escapeHtml(style)}"` : "";
63
+ }
@@ -0,0 +1,167 @@
1
+ import type { Item } from "./items.ts";
2
+
3
+ /**
4
+ * Search across the items of several content types, for a site's search page: the words of every text a visitor
5
+ * reads on an item's page (its title, its texts, its rich text and the blocks of its body), whatever their case and
6
+ * accents. Each result carries the sentence the words were found in.
7
+ */
8
+
9
+ /** Fields whose words are searched: what a visitor reads, not addresses, numbers or pictures. */
10
+ const SEARCHED_FIELDS = new Set(["text", "textarea", "richtext", "blocks", "select", "tags", "keyvalue"]);
11
+ /** Keys of a block's value that hold no words a visitor reads. */
12
+ const SKIPPED_KEYS = new Set([
13
+ "@type",
14
+ "id",
15
+ "presetId",
16
+ "type",
17
+ "url",
18
+ "src",
19
+ "href",
20
+ "link",
21
+ "layout",
22
+ "variant",
23
+ "variation",
24
+ "icon",
25
+ "posterUrl",
26
+ "imageFocus",
27
+ "tag",
28
+ ]);
29
+ const MAX_QUERY = 200;
30
+ const EXCERPT = 180;
31
+
32
+ export interface SearchedType {
33
+ key: string;
34
+ /** The type's fields; their `type` says which hold words. */
35
+ fields: readonly { name: string; type: string }[];
36
+ }
37
+
38
+ export interface SearchHit<T extends Item = Item> {
39
+ item: T;
40
+ /** Key of the item's content type. */
41
+ type: string;
42
+ /** The sentence the words were found in, or the start of the item's text; plain text. */
43
+ excerpt: string;
44
+ /** Higher first: words in the title count most. */
45
+ score: number;
46
+ }
47
+
48
+ /** The words of a query as compared: lowercase, without accents, at most 200 characters. */
49
+ export function searchWords(query: string): string[] {
50
+ return fold(query.trim().slice(0, MAX_QUERY))
51
+ .split(/[^\p{L}\p{N}]+/u)
52
+ .filter((word) => word.length > 0);
53
+ }
54
+
55
+ /**
56
+ * The items, of all the types given, that hold every word of the query, best first. An empty query finds nothing:
57
+ * a search page shows its results only once something is asked.
58
+ */
59
+ export function searchItems<T extends Item>(
60
+ groups: { type: SearchedType; items: readonly T[] }[],
61
+ query: string,
62
+ ): SearchHit<T>[] {
63
+ const words = searchWords(query);
64
+ if (words.length === 0) return [];
65
+ const hits: SearchHit<T>[] = [];
66
+ for (const { type, items } of groups) {
67
+ const fields = type.fields.filter((field) => SEARCHED_FIELDS.has(field.type) && !/^seo_/.test(field.name));
68
+ for (const item of items) {
69
+ const title = fold(item.title);
70
+ const texts = fields.map((field) => textOf(item.data[field.name])).filter(Boolean);
71
+ const body = fold(texts.join(" \n "));
72
+ if (!words.every((word) => title.includes(word) || body.includes(word))) continue;
73
+ const score = words.reduce(
74
+ (total, word) => total + (title.includes(word) ? 10 : 0) + Math.min(5, count(body, word)),
75
+ 0,
76
+ );
77
+ hits.push({ item, type: type.key, excerpt: excerptOf(texts, words), score });
78
+ }
79
+ }
80
+ return hits.sort((a, b) => b.score - a.score || b.item.updatedAt.localeCompare(a.item.updatedAt));
81
+ }
82
+
83
+ /** The words a value holds as plain text: rich text without its tags, a block's texts without its settings. */
84
+ export function textOf(value: unknown): string {
85
+ if (value === undefined || value === null || typeof value === "boolean" || typeof value === "number") return "";
86
+ if (typeof value === "string") {
87
+ if (/^(https?:|mailto:|tel:|\/|#)\S*$/i.test(value.trim())) return "";
88
+ return decode(value.replace(/<\/(p|div|h[1-6]|li|blockquote)>|<br\s*\/?>/gi, "\n").replace(/<[^>]*>/g, " "))
89
+ .replace(/[ \t\r\f]+/g, " ")
90
+ .replace(/\s*\n\s*/g, "\n")
91
+ .trim();
92
+ }
93
+ if (Array.isArray(value)) return value.map(textOf).filter(Boolean).join("\n");
94
+ if (typeof value === "object") {
95
+ return Object.entries(value as Record<string, unknown>)
96
+ .filter(([key]) => !SKIPPED_KEYS.has(key))
97
+ .map(([, one]) => textOf(one))
98
+ .filter(Boolean)
99
+ .join("\n");
100
+ }
101
+ return "";
102
+ }
103
+
104
+ /** The sentence around the first word found, cut to a line; else the start of the first text. */
105
+ function excerptOf(texts: string[], words: string[]): string {
106
+ for (const text of texts) {
107
+ const { folded, at } = foldWithPlaces(text);
108
+ const found = words.map((word) => folded.indexOf(word)).filter((index) => index !== -1);
109
+ if (found.length === 0) continue;
110
+ const start = at[Math.min(...found)] ?? 0;
111
+ // From the start of its sentence or line, unless that is too far back.
112
+ const before = text.slice(0, start);
113
+ const sentence = Math.max(before.lastIndexOf(". "), before.lastIndexOf("\n"), before.lastIndexOf("? "));
114
+ const atSentence = sentence !== -1 && start - sentence < EXCERPT * 0.6;
115
+ const from = atSentence ? sentence + 1 : Math.max(0, start - 60);
116
+ // "…" where the excerpt starts within a sentence.
117
+ // To the end of the paragraph or block it is in, not into the next one.
118
+ const lineEnd = text.indexOf("\n", start);
119
+ const passage = text.slice(from, lineEnd === -1 ? undefined : lineEnd);
120
+ return clip(passage.replace(/\s+/g, " ").trim(), from > 0 && !atSentence);
121
+ }
122
+ return clip((texts[0] ?? "").split("\n")[0]?.replace(/\s+/g, " ").trim() ?? "", false);
123
+ }
124
+
125
+ function clip(text: string, cut: boolean): string {
126
+ const head = cut ? "…" : "";
127
+ if (text.length <= EXCERPT) return head + text;
128
+ const end = text.lastIndexOf(" ", EXCERPT);
129
+ return `${head}${text.slice(0, end > EXCERPT / 2 ? end : EXCERPT)}…`;
130
+ }
131
+
132
+ function count(text: string, word: string): number {
133
+ let total = 0;
134
+ for (let index = text.indexOf(word); index !== -1; index = text.indexOf(word, index + word.length)) total++;
135
+ return total;
136
+ }
137
+
138
+ /** Text as compared: lowercase, without accents, so "ceramica" finds "Ceramică". */
139
+ export function fold(text: string): string {
140
+ return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLocaleLowerCase();
141
+ }
142
+
143
+ /** The folded text, and for each of its characters the place in the original it comes from. */
144
+ function foldWithPlaces(text: string): { folded: string; at: number[] } {
145
+ let folded = "";
146
+ const at: number[] = [];
147
+ for (let index = 0; index < text.length;) {
148
+ const character = String.fromCodePoint(text.codePointAt(index) ?? 0);
149
+ const one = fold(character);
150
+ folded += one;
151
+ for (let n = 0; n < one.length; n++) at.push(index);
152
+ index += character.length;
153
+ }
154
+ return { folded, at };
155
+ }
156
+
157
+ const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
158
+
159
+ function decode(text: string): string {
160
+ return text.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, name: string) => {
161
+ if (name[0] === "#") {
162
+ const code = name[1]?.toLowerCase() === "x" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
163
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
164
+ }
165
+ return ENTITIES[name.toLowerCase()] ?? whole;
166
+ });
167
+ }
@@ -0,0 +1,229 @@
1
+ import type { ContentType } from "./content-types.ts";
2
+ import type { Item, ItemDraft, ItemStore } from "./items.ts";
3
+ import { parseItem } from "./items.ts";
4
+ import { referenceFields, referencedSlugs } from "./references.ts";
5
+ import { ValidationError } from "./validation-error.ts";
6
+
7
+ /**
8
+ * A site's starting content, kept in git next to its code: `seed/<type>.json` files that `brim seed` adds to the
9
+ * database. Content lives in the database, which is not in git, so without it a fresh clone, another developer's
10
+ * machine or a new preview starts empty.
11
+ *
12
+ * Seeding only ever adds: an item that already exists (same type, slug and language) is left exactly as it is,
13
+ * whatever the seed says, so running it again, or against a site whose owner has changed things, never undoes their
14
+ * work. The whole seed is checked before anything is written; one mistake and nothing is added.
15
+ */
16
+ export interface SeedEntry {
17
+ type: string;
18
+ title: string;
19
+ /** From the title when left out. */
20
+ slug?: string;
21
+ /** "published" unless the seed says otherwise: starting content is meant to be seen. */
22
+ visibility?: "published" | "private";
23
+ /** A language of the site other than the default one: a translation of the entry with the same slug. */
24
+ locale?: string;
25
+ /**
26
+ * For a translation: the slug of the item it translates, in the default language, when its own slug differs
27
+ * (`primavara` translating `spring`). Left out, it translates the item with its own slug.
28
+ */
29
+ translates?: string;
30
+ data?: Record<string, unknown>;
31
+ }
32
+
33
+ export interface SeedPlan {
34
+ /** What would be added, in the order it is added: a vocabulary's terms before what points at them. */
35
+ create: { index: number; type: ContentType; draft: ItemDraft; locale: string; translates: string }[];
36
+ /** What is already there, and stays as it is. */
37
+ existing: { type: string; slug: string; locale: string }[];
38
+ }
39
+
40
+ const keyOf = (type: string, slug: string, locale: string) => `${type}\u0000${locale}\u0000${slug}`;
41
+
42
+ /**
43
+ * Reads and checks a seed against the site's types and what its database holds. Throws one `ValidationError`
44
+ * listing every mistake, so a seed is fixed in one go; nothing is written here.
45
+ */
46
+ export async function planSeed(
47
+ types: ContentType[],
48
+ items: ItemStore,
49
+ input: unknown,
50
+ localeOf: (value: unknown) => string,
51
+ ): Promise<SeedPlan> {
52
+ if (!Array.isArray(input)) throw new ValidationError('The seed must be a list of items: [{ "type", "title", … }].');
53
+ const errors: string[] = [];
54
+ const parsed: SeedPlan["create"] = [];
55
+ input.forEach((raw: unknown, index) => {
56
+ const where = `Item ${index + 1}`;
57
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
58
+ errors.push(`${where}: must be an object.`);
59
+ return;
60
+ }
61
+ const entry = raw as Record<string, unknown>;
62
+ const type = types.find((candidate) => candidate.key === entry.type);
63
+ if (!type) {
64
+ errors.push(`${where}: "${String(entry.type)}" is not one of the site's content types.`);
65
+ return;
66
+ }
67
+ try {
68
+ const locale = localeOf(entry.locale);
69
+ const draft = parseItem(type, { ...entry, visibility: entry.visibility ?? "published" });
70
+ if (entry.translates !== undefined && (typeof entry.translates !== "string" || entry.translates === "")) {
71
+ throw new ValidationError('"translates" is the slug of the item it translates.');
72
+ }
73
+ if (entry.translates !== undefined && locale === "") {
74
+ throw new ValidationError('"translates" is for a translation: give its "locale" too.');
75
+ }
76
+ const translates = typeof entry.translates === "string" ? entry.translates : draft.slug;
77
+ parsed.push({ index, type, draft, locale, translates });
78
+ } catch (error) {
79
+ errors.push(`${where} (${type.singular} "${String(entry.title ?? "")}"): ${messageOf(error)}`);
80
+ }
81
+ });
82
+
83
+ // What the database holds, per type: its slugs in each language.
84
+ const stored = new Map<string, Item[]>();
85
+ const storedOf = async (type: string) => {
86
+ let list = stored.get(type);
87
+ if (!list) stored.set(type, (list = await items.list(type)));
88
+ return list;
89
+ };
90
+ const known = new Set<string>();
91
+ for (const type of new Set(parsed.map((entry) => entry.type.key)).add("")) {
92
+ if (!type) continue;
93
+ for (const item of await storedOf(type)) known.add(keyOf(type, item.slug, item.locale));
94
+ }
95
+
96
+ const plan: SeedPlan = { create: [], existing: [] };
97
+ const seen = new Set<string>();
98
+ for (const entry of parsed) {
99
+ const key = keyOf(entry.type.key, entry.draft.slug, entry.locale);
100
+ if (seen.has(key)) {
101
+ errors.push(`Item ${entry.index + 1}: the seed has "${entry.draft.slug}" twice in ${entry.type.label}.`);
102
+ continue;
103
+ }
104
+ seen.add(key);
105
+ if (known.has(key)) plan.existing.push({ type: entry.type.key, slug: entry.draft.slug, locale: entry.locale });
106
+ else plan.create.push(entry);
107
+ }
108
+
109
+ // References may name terms the database holds or the seed adds; translations need their original.
110
+ const creating = new Set(plan.create.map((entry) => keyOf(entry.type.key, entry.draft.slug, entry.locale)));
111
+ const exists = async (type: string, slug: string, locale: string) =>
112
+ creating.has(keyOf(type, slug, locale)) ||
113
+ (await storedOf(type)).some((item) => item.slug === slug && item.locale === locale);
114
+ for (const entry of plan.create) {
115
+ for (const field of referenceFields(entry.type)) {
116
+ for (const slug of referencedSlugs(entry.draft, field.name)) {
117
+ // A translation keeps the slugs its terms have in the default language.
118
+ if (!(await exists(field.to, slug, "")) && !(await exists(field.to, slug, entry.locale))) {
119
+ const target = types.find((candidate) => candidate.key === field.to);
120
+ errors.push(
121
+ `${entry.type.singular} "${entry.draft.title}": "${field.label}" names "${slug}", which is neither in the ` +
122
+ `site nor in the seed (${target?.label ?? field.to}).`,
123
+ );
124
+ }
125
+ }
126
+ }
127
+ if (entry.locale !== "" && !(await exists(entry.type.key, entry.translates, ""))) {
128
+ errors.push(
129
+ `${entry.type.singular} "${entry.draft.title}" (${entry.locale}) translates "${entry.translates}", which is ` +
130
+ "neither in the site nor in the seed in the default language.",
131
+ );
132
+ }
133
+ }
134
+ if (errors.length > 0)
135
+ throw new ValidationError(`The seed has ${errors.length} mistake(s):\n- ${errors.join("\n- ")}`);
136
+
137
+ plan.create = orderForCreation(types, plan.create);
138
+ return plan;
139
+ }
140
+
141
+ /** Adds what the plan says, in its order, and answers the items added. */
142
+ export async function applySeed(items: ItemStore, plan: SeedPlan): Promise<Item[]> {
143
+ const added: Item[] = [];
144
+ // The originals of each type by slug, read once per type and kept up to date as items are added (reading the whole
145
+ // type again for every translation made a large seed slow).
146
+ const originals = new Map<string, Map<string, string>>();
147
+ const originalsOf = async (type: string) => {
148
+ let bySlug = originals.get(type);
149
+ if (!bySlug) {
150
+ bySlug = new Map(
151
+ (await items.list(type)).filter((item) => item.locale === "").map((item) => [item.slug, item.id]),
152
+ );
153
+ originals.set(type, bySlug);
154
+ }
155
+ return bySlug;
156
+ };
157
+ for (const entry of plan.create) {
158
+ const bySlug = await originalsOf(entry.type.key);
159
+ const translationOf = entry.locale !== "" ? (bySlug.get(entry.translates) ?? null) : null;
160
+ const item = await items.create(entry.type.key, entry.draft, { locale: entry.locale, translationOf });
161
+ if (entry.locale === "") bySlug.set(item.slug, item.id);
162
+ added.push(item);
163
+ }
164
+ return added;
165
+ }
166
+
167
+ /**
168
+ * The order to add a seed in: a type after the types its references point at (categories before products), and an
169
+ * item in the default language before its translations. Types that point at each other keep the seed's order.
170
+ */
171
+ function orderForCreation<T extends { type: ContentType; locale: string }>(types: ContentType[], entries: T[]): T[] {
172
+ const depth = new Map<string, number>();
173
+ const depthOf = (key: string, path: Set<string> = new Set()): number => {
174
+ const cached = depth.get(key);
175
+ if (cached !== undefined) return cached;
176
+ if (path.has(key)) return 0;
177
+ path.add(key);
178
+ const type = types.find((candidate) => candidate.key === key);
179
+ const targets = type
180
+ ? referenceFields(type)
181
+ .map((field) => field.to)
182
+ .filter((to) => to !== key)
183
+ : [];
184
+ const value = targets.length === 0 ? 0 : 1 + Math.max(...targets.map((to) => depthOf(to, path)));
185
+ depth.set(key, value);
186
+ return value;
187
+ };
188
+ return entries
189
+ .map((entry, index) => ({ entry, index }))
190
+ .sort(
191
+ (a, b) =>
192
+ depthOf(a.entry.type.key) - depthOf(b.entry.type.key) ||
193
+ Number(a.entry.locale !== "") - Number(b.entry.locale !== "") ||
194
+ a.index - b.index,
195
+ )
196
+ .map(({ entry }) => entry);
197
+ }
198
+
199
+ /** Every item of the site as seed entries, the default language first: what `brim seed --export` writes. */
200
+ export function exportSeed(types: ContentType[], all: Item[]): SeedEntry[] {
201
+ const order = new Map(types.map((type, index) => [type.key, index]));
202
+ const byId = new Map(all.map((item) => [item.id, item]));
203
+ return [...all]
204
+ .filter((item) => order.has(item.type))
205
+ .sort(
206
+ (a, b) =>
207
+ (order.get(a.type) ?? 0) - (order.get(b.type) ?? 0) ||
208
+ Number(a.locale !== "") - Number(b.locale !== "") ||
209
+ // In the owner's order, which the seed keeps: items are added in the order the file lists them.
210
+ a.position - b.position ||
211
+ a.createdAt.localeCompare(b.createdAt),
212
+ )
213
+ .map((item) => ({
214
+ type: item.type,
215
+ title: item.title,
216
+ slug: item.slug,
217
+ ...(item.visibility === "private" && { visibility: "private" as const }),
218
+ ...(item.locale !== "" && { locale: item.locale }),
219
+ // A translation names its original when their slugs differ, so the seed links them again.
220
+ ...(item.translationOf &&
221
+ byId.get(item.translationOf) &&
222
+ byId.get(item.translationOf)!.slug !== item.slug && { translates: byId.get(item.translationOf)!.slug }),
223
+ data: item.data,
224
+ }));
225
+ }
226
+
227
+ function messageOf(error: unknown): string {
228
+ return error instanceof Error ? error.message : String(error);
229
+ }
@@ -0,0 +1,111 @@
1
+ import { type ContentFieldInput, type ContentType, type SiteSettingField, defineContentType } from "./content-types.ts";
2
+ import type { SettingsData, Typed } from "./field-types.ts";
3
+ import { parseItem } from "./items.ts";
4
+ import { ValidationError } from "./validation-error.ts";
5
+
6
+ /**
7
+ * The site's own settings: what is true of the whole site and the owner changes now and then, such as the phone
8
+ * number, the email address, WhatsApp, social profiles, the address and opening hours, the links to legal pages.
9
+ * The site declares them in `src/site-settings.ts`, with the same fields as a content type; the owner edits them in
10
+ * Site Settings (or an agent through the MCP), and every page reads them with `getSiteSettings()`, so a number
11
+ * changes in one place instead of in every page that shows it.
12
+ *
13
+ * export const siteSettings = defineSiteSettings({
14
+ * fields: [
15
+ * { name: "phone", label: "Telefon", type: "text", group: "Contact", default: "+40 700 000 000" },
16
+ * { name: "email", label: "E-mail", type: "email", group: "Contact" },
17
+ * { name: "instagram", label: "Instagram", type: "url", group: "Rețele sociale" },
18
+ * ],
19
+ * });
20
+ */
21
+ export type SiteSettingFieldInput = ContentFieldInput & {
22
+ /** The section of Site Settings the field is shown in, e.g. "Contact"; fields without one go under "Site". */
23
+ group?: string;
24
+ /** The value until the owner sets one: what the site shows on a fresh copy, before any content. */
25
+ default?: unknown;
26
+ };
27
+
28
+ export type { SiteSettingField } from "./content-types.ts";
29
+
30
+ export interface SiteSettings {
31
+ fields: SiteSettingField[];
32
+ /** The fields' starting values, checked like saved ones. */
33
+ defaults: Record<string, unknown>;
34
+ }
35
+
36
+ /** The node the owner's values are saved as, in the site's shared content (one per language). */
37
+ export const SITE_SETTINGS_NODE = "site-settings";
38
+
39
+ /** Declares the site's own settings. Mistakes fail here, when the site starts, like a content type's. */
40
+ export function defineSiteSettings<const Fields extends readonly SiteSettingFieldInput[]>(input: {
41
+ fields: Fields;
42
+ }): SiteSettings & Typed<SettingsData<Fields>> {
43
+ const declared = input.fields.map(({ group, default: _default, ...field }) => field as ContentFieldInput);
44
+ const type = settingsType(declared);
45
+ for (const field of type.fields) {
46
+ if (field.type === "blocks")
47
+ throw new Error(`Site setting "${field.name}" cannot be a blocks field: it has no page.`);
48
+ }
49
+ const fields: SiteSettingField[] = type.fields.map((field, index) => {
50
+ const { group, default: value } = input.fields[index] ?? {};
51
+ return { ...field, ...(group && { group }), ...(value !== undefined && { default: value }) };
52
+ });
53
+ const starting = Object.fromEntries(
54
+ fields.flatMap((field) => (field.default === undefined ? [] : [[field.name, field.default]])),
55
+ );
56
+ let defaults: Record<string, unknown>;
57
+ try {
58
+ defaults = parseSettings(fields, starting, false);
59
+ } catch (error) {
60
+ throw new Error(
61
+ `The defaults of the site settings are not valid: ${error instanceof Error ? error.message : error}`,
62
+ );
63
+ }
64
+ return { fields, defaults };
65
+ }
66
+
67
+ /**
68
+ * Turns untrusted values into the site settings to save, checked exactly like an item's fields. `strict` asks for
69
+ * the required ones; the defaults of a declaration may leave them for the owner to fill in.
70
+ */
71
+ export function parseSettings(fields: SiteSettingField[], input: unknown, strict = true): Record<string, unknown> {
72
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
73
+ throw new ValidationError("The site settings must be an object of values.");
74
+ }
75
+ const type = settingsType(strict ? fields : fields.map((field) => ({ ...field, required: false })));
76
+ const values = parseItem(type, { title: "Site settings", visibility: "published", data: input }).data;
77
+ // A field the owner emptied stays empty (null) instead of falling back to the code's default.
78
+ for (const field of fields) {
79
+ const given = (input as Record<string, unknown>)[field.name];
80
+ const empty = given === null || given === "" || (Array.isArray(given) && given.length === 0);
81
+ if (empty && !(field.name in values)) values[field.name] = null;
82
+ }
83
+ return values;
84
+ }
85
+
86
+ /** What the site shows: the saved values over the defaults, a value cleared by the owner staying cleared. */
87
+ export function settingsValues(settings: SiteSettings | null | undefined, saved: unknown): Record<string, unknown> {
88
+ const values = typeof saved === "object" && saved !== null ? (saved as Record<string, unknown>) : undefined;
89
+ return { ...(settings?.defaults ?? {}), ...(values ?? {}) };
90
+ }
91
+
92
+ /** The declared settings as a content type, for what checks an item's fields (references to vocabularies). */
93
+ export function settingsAsType(settings: SiteSettings): ContentType {
94
+ return settingsType(settings.fields.map(({ group: _group, default: _default, ...field }) => field));
95
+ }
96
+
97
+ /** The fields as a content type, so they are declared, checked and edited exactly like an item's. */
98
+ function settingsType(fields: ContentFieldInput[]): ContentType {
99
+ return defineContentType({
100
+ key: "site_settings",
101
+ label: "Site settings",
102
+ singular: "Site settings",
103
+ slug: "site-settings",
104
+ author: false,
105
+ tags: false,
106
+ fields: fields.map(
107
+ ({ group: _group, default: _default, ...field }: ContentFieldInput & { group?: unknown; default?: unknown }) =>
108
+ field as ContentFieldInput,
109
+ ),
110
+ });
111
+ }