@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,39 @@
1
+ ---
2
+ /**
3
+ * The route Brim adds when a site declares page templates or content types: one page per page the owner added,
4
+ * drawn by its template, and one per item of a content type that has a template (`component`), in every language.
5
+ * Visitors get published pages and items only; while editing, private ones too.
6
+ * The server looks the page up on each request; a static build uses `TemplatePageStatic.astro`, which lists them.
7
+ */
8
+ import config from "virtual:brim/config";
9
+ import { itemPageOf } from "../content/content-types.ts";
10
+ import { normalizePagePath } from "../content/ids.ts";
11
+ import type { PageComponent } from "../content/page-templates.ts";
12
+ import { connect } from "./connect.ts";
13
+ import { getItem } from "./content.ts";
14
+ import { isEditing } from "./request-state.ts";
15
+
16
+ let pageProps: Record<string, unknown>;
17
+ let Template: PageComponent;
18
+ {
19
+ const path = normalizePagePath(`/${Astro.params.page ?? ""}`);
20
+ const itemPage = itemPageOf(config.contentTypes, path, config.locales);
21
+ if (itemPage) {
22
+ const item = await getItem(itemPage.type.key, itemPage.slug, { locale: itemPage.locale });
23
+ if (!item) return new Response(null, { status: 404 });
24
+ // With a `path` like `/produse/[category]/[slug]` the item has one address: an old or mistyped category leads on.
25
+ if (item.url !== path) return Astro.redirect(`${item.url}${Astro.url.search}`, 301);
26
+ pageProps = { item };
27
+ Template = itemPage.type.component;
28
+ } else {
29
+ const { content } = await connect(config.databaseUrl, config.authToken);
30
+ const record = await content.page(path);
31
+ const template = config.pageTemplates.find((candidate) => candidate.key === record.template);
32
+ if (!template || (record.visibility !== "published" && !isEditing())) return new Response(null, { status: 404 });
33
+ pageProps = { page: { path: record.path, title: record.title ?? "", template: template.key } };
34
+ Template = template.component;
35
+ }
36
+ }
37
+ ---
38
+
39
+ <Template {...pageProps} />
@@ -0,0 +1,13 @@
1
+ ---
2
+ /**
3
+ * The route Brim adds in a static build when a site declares page templates or content types: the pages are known
4
+ * at build time (`templateStaticPaths`), each drawn by its template. The server's route is `TemplatePage.astro`.
5
+ */
6
+ import { templateStaticPaths } from "./template-paths.ts";
7
+
8
+ export const getStaticPaths = templateStaticPaths;
9
+
10
+ const { pageProps, component: Template } = Astro.props;
11
+ ---
12
+
13
+ <Template {...pageProps} />
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import type { APIRoute } from "astro";
5
+ import config from "virtual:brim/config";
6
+ import routes from "virtual:brim/routes";
7
+ import { resolveHostSignIn, resolveMail, resolveMedia, resolveVideoUploads } from "../config.ts";
8
+ import { upgradeFieldValues } from "../content/block-values.ts";
9
+ import { adoptLanguageScopes } from "../content/language-scopes.ts";
10
+ import { storageFiles } from "../content/media.ts";
11
+ import { Mailer } from "../mail/mailer.ts";
12
+ import { type AdminHandler, createAdminHandler } from "../server/handler.ts";
13
+ import { clientAddress as visitorAddress } from "../server/http.ts";
14
+ import { connect } from "./connect.ts";
15
+ import { siteFormFiles } from "./form-files.ts";
16
+ import { icons } from "./icons.ts";
17
+ import { siteQueryRules } from "./query-store.ts";
18
+
19
+ /**
20
+ * `/admin` on the built server: the editor, its API and the site's MCP, the same handler the dev server uses.
21
+ * Pages are drawn from the database on each request, so nothing has to be rebuilt after a change.
22
+ */
23
+ export const prerender = false;
24
+
25
+ let handler: Promise<AdminHandler> | undefined;
26
+
27
+ async function create(): Promise<AdminHandler> {
28
+ const brim = await connect(config.databaseUrl, config.authToken);
29
+ await upgradeFieldValues(brim.db, config.contentTypes);
30
+ if (config.locales) await adoptLanguageScopes(brim.db, config.locales.defaultLocale);
31
+ return createAdminHandler({
32
+ brim,
33
+ // Astro gives the site's `site` (from its config, or BRIM_SITE_URL through the integration) here.
34
+ // Written exactly so: Vite replaces the literal `import.meta.env.SITE` when it builds the server.
35
+ // @ts-expect-error Astro's types for import.meta.env are not part of this package's own check.
36
+ siteUrl: import.meta.env.SITE as string | undefined,
37
+ locales: config.locales,
38
+ assetsDirectory: editorAssets(),
39
+ contentTypes: () => config.contentTypes,
40
+ pageTemplates: () => config.pageTemplates,
41
+ siteSettings: () => config.siteSettings,
42
+ emails: () => config.emails,
43
+ mediaDirectory: pathToFileURL(`${config.mediaDirectory}/`),
44
+ mediaFiles: storageFiles(resolveMedia(config.media).storage),
45
+ formFiles: siteFormFiles(),
46
+ thumbnail: mediaThumbnail,
47
+ videoUploads: resolveVideoUploads(config.videoUploads),
48
+ hostSignIn: resolveHostSignIn(),
49
+ mailer: new Mailer(resolveMail(config.mail)),
50
+ icons,
51
+ brandColors: config.brandColors ?? [],
52
+ identity: config.identity ?? {},
53
+ pages: () => routes.pages,
54
+ patterns: () => routes.patterns,
55
+ // The query parameters each page and route reads, for a host that caches pages (Brimsites).
56
+ queryParams: () => siteQueryRules(brim.db),
57
+ });
58
+ }
59
+
60
+ /** A 320 px copy of an upload from the site's CDN (`media.resize`), for the editor's picker. */
61
+ function mediaThumbnail(url: string): string | undefined {
62
+ const { publicUrl, resize } = resolveMedia(config.media);
63
+ if (!resize || !/\.(?:jpe?g|png|webp|avif)$/i.test(url)) return undefined;
64
+ const src = publicUrl && url.startsWith("/uploads/") ? `${publicUrl}${url}` : url;
65
+ return resize.replaceAll("{url}", src).replaceAll("{width}", "320");
66
+ }
67
+
68
+ /** Where brimjs was installed when the site was built, or where it is installed next to the running server. */
69
+ function editorAssets(): URL {
70
+ const installed = join(process.cwd(), "node_modules", "@brimsites/brimjs", "editor-dist");
71
+ return pathToFileURL(`${existsSync(config.editorAssets) ? config.editorAssets : installed}/`);
72
+ }
73
+
74
+ export const ALL: APIRoute = async ({ request, clientAddress }) => {
75
+ handler ??= create();
76
+ return (
77
+ (await (await handler)(request, { clientAddress: visitorAddress(request, clientAddress) })) ??
78
+ new Response("Not found", { status: 404 })
79
+ );
80
+ };
@@ -0,0 +1,53 @@
1
+ import { Accounts } from "../auth/accounts.ts";
2
+ import { HistoryStore } from "../content/history.ts";
3
+ import { ItemStore } from "../content/items.ts";
4
+ import { ContentStore } from "../content/store.ts";
5
+ import { DraftStore } from "../content/drafts.ts";
6
+ import type { Database } from "../db/database.ts";
7
+ import { FormStore } from "../forms/store.ts";
8
+ import { ensureChangeTracking, keepingReads } from "../db/cached.ts";
9
+ import { openDatabase } from "../db/libsql.ts";
10
+ import { migrate } from "../db/schema.ts";
11
+
12
+ export interface Brim {
13
+ db: Database;
14
+ content: ContentStore;
15
+ items: ItemStore;
16
+ forms: FormStore;
17
+ history: HistoryStore;
18
+ drafts: DraftStore;
19
+ accounts: Accounts;
20
+ }
21
+
22
+ const connections = new Map<string, Promise<Brim>>();
23
+
24
+ /** One migrated connection per database for the lifetime of the process. */
25
+ export function connect(url: string, authToken?: string): Promise<Brim> {
26
+ let connection = connections.get(url);
27
+ if (!connection) {
28
+ connection = (async () => {
29
+ const opened = openDatabase(url, authToken);
30
+ await migrate(opened);
31
+ // Pages keep what they read of the content until it changes (see `keepingReads`): one round trip per visit.
32
+ await ensureChangeTracking(opened);
33
+ const db = keepingReads(opened);
34
+ return {
35
+ db,
36
+ content: new ContentStore(db),
37
+ items: new ItemStore(db),
38
+ forms: new FormStore(db),
39
+ history: new HistoryStore(db),
40
+ drafts: new DraftStore(db),
41
+ accounts: new Accounts(db),
42
+ };
43
+ })();
44
+ connections.set(url, connection);
45
+ // A connection that failed (a network error at start, a folder not made yet) is not kept: the next request
46
+ // tries again instead of failing until the server restarts.
47
+ const failed = connection;
48
+ failed.catch(() => {
49
+ if (connections.get(url) === failed) connections.delete(url);
50
+ });
51
+ }
52
+ return connection;
53
+ }
@@ -0,0 +1,188 @@
1
+ import config from "virtual:brim/config";
2
+ import type { DataOf, Typed } from "../content/field-types.ts";
3
+ import { type ContentType, optionLabel } from "../content/content-types.ts";
4
+ import { referencedSlugs, termsBySlug } from "../content/references.ts";
5
+ import { siteScope } from "../content/ids.ts";
6
+ import { SITE_SETTINGS_NODE, settingsValues } from "../content/site-settings.ts";
7
+ import type { Item, ItemSort } from "../content/items.ts";
8
+ import { connect } from "./connect.ts";
9
+ import { itemPagePath, storedLocale } from "../server/locales.ts";
10
+ import { currentLocale, isEditing, isPreviewing, perRequest } from "./request-state.ts";
11
+
12
+ /**
13
+ * An item as pages use it: its fields, plus the address of its own page. `Data` is the type of its fields, inferred
14
+ * from its content type (`ItemOf<typeof product>`), or an open record.
15
+ */
16
+ export type ContentItem<Data = Record<string, unknown>> = Omit<Item, "data"> & {
17
+ data: Data;
18
+ /** `/projects/lake-house`, or `/ro/projects/casa-de-la-lac` for an item in another language. */
19
+ url: string;
20
+ };
21
+
22
+ /** An item of a content type declared with `defineContentType`, with its fields typed: `ItemOf<typeof product>`. */
23
+ export type ItemOf<T> = ContentItem<DataOf<T>>;
24
+
25
+ /**
26
+ * What a content type's template receives: the item whose page it draws. `ItemPageProps<typeof product>` types its
27
+ * fields: `const { item } = Astro.props as ItemPageProps<typeof product>`.
28
+ */
29
+ export interface ItemPageProps<T = unknown> {
30
+ item: ItemOf<T>;
31
+ }
32
+
33
+ /** The values `getSiteSettings` answers: typed by the declaration passed, by an explicit type, or an open record. */
34
+ type SettingsValuesOf<T> = T extends Typed<infer Data> ? Data : unknown extends T ? Record<string, unknown> : T;
35
+
36
+ /** A content type as code names it: by its key (`"product"`), or the declaration itself, which types its items. */
37
+ type TypeRef = string | (ContentType & Typed<unknown>);
38
+ type ItemsOf<T> = T extends string ? ContentItem : ItemOf<T>;
39
+ const keyOf = (type: TypeRef): string => (typeof type === "string" ? type : type.key);
40
+
41
+ export interface ItemQuery {
42
+ sort?: ItemSort;
43
+ limit?: number;
44
+ /**
45
+ * Which language: a code the site declares in Astro's `i18n`, or `"*"` for all of them (for `getStaticPaths`
46
+ * of a page under `[locale]`). By default the language of the page being drawn, else the default one.
47
+ * On a site without languages every item is in "the" language and this is ignored.
48
+ */
49
+ locale?: string;
50
+ }
51
+
52
+ /** How the database stores the language asked for (by default the page's, else the default one). */
53
+ function localeOf(wanted: string | undefined): string {
54
+ const locales = config.locales;
55
+ if (!locales) return "";
56
+ const code = wanted ?? currentLocale() ?? locales.defaultLocale;
57
+ const locale = storedLocale(code, locales);
58
+ if (locale === undefined) throw new Error(`"${code}" is not one of the site's languages (Astro's i18n.locales).`);
59
+ return locale;
60
+ }
61
+
62
+ export function getContentType(key: string): ContentType {
63
+ const type = config.contentTypes.find((candidate) => candidate.key === key);
64
+ if (!type) throw new Error(`Content type "${key}" is not declared. Export it from src/content-types/index.ts.`);
65
+ return type;
66
+ }
67
+
68
+ /**
69
+ * What a page shows for a saved choice of a `select` field: `choiceLabel("product", "category", "ceramica")` is
70
+ * `Ceramică` when the field declares `{ value: "ceramica", label: "Ceramică" }`, else the value itself.
71
+ */
72
+ export function choiceLabel(key: string, field: string, value: unknown): string {
73
+ const declared = getContentType(key).fields.find((candidate) => candidate.name === field);
74
+ const text = value === undefined || value === null ? "" : String(value);
75
+ return declared ? optionLabel(declared, text, currentLocale()) : text;
76
+ }
77
+
78
+ /** The address of an item's page (its type's `path`, else `/<slug>/<item>`), under its language unless that is the default. */
79
+ export function itemPath(type: ContentType, item: Pick<Item, "slug" | "locale" | "data">): string {
80
+ return itemPagePath(type, item, config.locales);
81
+ }
82
+
83
+ /**
84
+ * Items of a content type, for listings and for `getStaticPaths`.
85
+ * Visitors get published items only; while editing, private ones are included too.
86
+ * On a site with languages, the items of the page's language (see `ItemQuery.locale`).
87
+ */
88
+ export async function getItems<T extends TypeRef>(of: T, query: ItemQuery = {}): Promise<ItemsOf<T>[]> {
89
+ const type = getContentType(keyOf(of));
90
+ const { items } = await connect(config.databaseUrl, config.authToken);
91
+ const { locale: wanted, ...rest } = query;
92
+ const locale = config.locales && wanted !== "*" ? localeOf(wanted) : undefined;
93
+ const { drafts } = await connect(config.databaseUrl, config.authToken);
94
+ const options = {
95
+ ...(type.ordered && { sort: "position" as const }),
96
+ ...rest,
97
+ publishedOnly: !isEditing(),
98
+ ...(locale !== undefined && { locale }),
99
+ };
100
+ const preview = isPreviewing();
101
+ const listed = await perRequest(`items|${type.key}|${JSON.stringify(options)}|${preview}`, async () => {
102
+ const saved = await items.listCached(type.key, options);
103
+ return preview ? await drafts.overlayItems(saved) : saved;
104
+ });
105
+ return listed.map((item) => ({ ...item, url: itemPath(type, item) }) as ItemsOf<T>);
106
+ }
107
+
108
+ /**
109
+ * One item by the slug in its address, for the page of an item: `getItem("project", Astro.params.slug)`.
110
+ * In the page's language on a site with languages; `undefined` when there is none, or when it is private and
111
+ * the visitor is not editing.
112
+ */
113
+ export async function getItem<T extends TypeRef>(
114
+ of: T,
115
+ slug: string | undefined,
116
+ query: Pick<ItemQuery, "locale"> = {},
117
+ ): Promise<ItemsOf<T> | undefined> {
118
+ if (!slug) return undefined;
119
+ // The preview shows unsaved drafts, whose address may differ from the saved one: it looks among them all.
120
+ if (isPreviewing()) return (await getItems(of, query)).find((item) => item.slug === slug);
121
+ const type = getContentType(keyOf(of));
122
+ const { items } = await connect(config.databaseUrl, config.authToken);
123
+ const item = await items.bySlug(type.key, slug, {
124
+ publishedOnly: !isEditing(),
125
+ ...(config.locales && query.locale !== "*" && { locale: localeOf(query.locale) }),
126
+ });
127
+ return item ? ({ ...item, url: itemPath(type, item) } as ItemsOf<T>) : undefined;
128
+ }
129
+
130
+ /**
131
+ * The items a reference field of an item points at, in the order it names them, in the page's language: a product's
132
+ * category (`(await getReferences("product", product, "category"))[0]`) or its brands. Visitors get published ones.
133
+ */
134
+ export async function getReferences(of: TypeRef, item: { data: object }, field: string): Promise<ContentItem[]> {
135
+ const key = keyOf(of);
136
+ const declared = getContentType(key).fields.find((candidate) => candidate.name === field);
137
+ if (declared?.type !== "reference" || !declared.to) {
138
+ throw new Error(`"${field}" is not a reference field of the content type "${key}".`);
139
+ }
140
+ const terms = await getTerms(declared.to);
141
+ return referencedSlugs(item as { data: Record<string, unknown> }, field).flatMap((slug) => {
142
+ const term = terms.get(slug);
143
+ return term ? [term] : [];
144
+ });
145
+ }
146
+
147
+ /**
148
+ * The terms of a vocabulary by slug, as the page's language shows them. A term's translations share its slug, so a
149
+ * product in English that points at `faianta` finds the English `faianta`; a term not translated yet is the one in
150
+ * its original language, rather than missing from the page (or shown as its bare slug in a listing's filters).
151
+ */
152
+ export async function getTerms(of: TypeRef): Promise<Map<string, ContentItem>> {
153
+ const key = keyOf(of);
154
+ const own = await getItems(key);
155
+ return config.locales ? termsBySlug(own, await getItems(key, { locale: "*" })) : termsBySlug(own, []);
156
+ }
157
+
158
+ /** The item in every language it is written in, for a language switcher on the item's page. */
159
+ export async function getTranslations(key: string, item: Item): Promise<ContentItem[]> {
160
+ const type = getContentType(key);
161
+ const { items, drafts } = await connect(config.databaseUrl, config.authToken);
162
+ const translations = await items.translations(item);
163
+ const all = isPreviewing() ? await drafts.overlayItems(translations) : translations;
164
+ return all
165
+ .filter((candidate) => isEditing() || candidate.visibility === "published")
166
+ .map((candidate) => ({ ...candidate, url: itemPath(type, candidate) }));
167
+ }
168
+
169
+ export { type ImageSources, imageSources, mediaUrl } from "./media.ts";
170
+
171
+ /**
172
+ * The site's own settings (`src/site-settings.ts`) as the page should show them: what the owner saved in Site
173
+ * Settings, over the code's defaults, in the page's language. A field the owner emptied is `null`.
174
+ *
175
+ * const { phone, email, instagram } = await getSiteSettings();
176
+ */
177
+ export async function getSiteSettings<T = Record<string, unknown>>(
178
+ /** The declaration (`siteSettings` from src/site-settings.ts), which types the values it answers. */
179
+ _declared?: T,
180
+ ): Promise<SettingsValuesOf<T>> {
181
+ type Values = SettingsValuesOf<T>;
182
+ if (!config.siteSettings) return {} as Values;
183
+ const { content } = await connect(config.databaseUrl, config.authToken);
184
+ const scope = siteScope(currentLocale() ?? config.locales?.defaultLocale);
185
+ const nodes = await perRequest(`nodes|${scope}`, () => content.loadNodes([scope]));
186
+ const saved = nodes.find((node) => node.nodeId === SITE_SETTINGS_NODE);
187
+ return settingsValues(config.siteSettings, saved?.value) as Values;
188
+ }
@@ -0,0 +1,131 @@
1
+ import { assertNodeId, isNodeId, siteScope } from "../content/ids.ts";
2
+ import { resolveSettings } from "../blocks/settings.ts";
3
+ import type { BlockDefinition } from "../blocks/types.ts";
4
+ import { type BlockLayout, layoutOf } from "../content/block-layout.ts";
5
+ import { blocksOf } from "../content/block-values.ts";
6
+ import type { ItemBinding } from "../content/item-fields.ts";
7
+ import type { ItemHead } from "../content/item-head.ts";
8
+ import type { NodeKind, NodeValues, SeoSettings, StoredNode } from "../content/types.ts";
9
+
10
+ /**
11
+ * Where a node's value is kept: with its page (on an item's page, its type's template), with the whole site, or in
12
+ * a `blocks` field of an item (`item:…`, handed out by `blocks()`).
13
+ */
14
+ export type NodeScope = "page" | "site" | `item:${string}`;
15
+
16
+ /** What the primitives on one page can read: the owner's values for this page and for the whole site. */
17
+ export class BrimContext {
18
+ /** `page:<path>`, or `type:<key>` on the page of an item, whose nodes belong to its type's template. */
19
+ readonly #pageScope: string;
20
+ readonly #siteScope: string;
21
+ /** True only while the editor can be open; the public build leaves no trace of it. */
22
+ readonly editing: boolean;
23
+ readonly #nodes = new Map<string, StoredNode>();
24
+ /** The item and field behind each `item:…` scope that `blocks()` handed out. */
25
+ readonly #stacks = new Map<string, ItemBinding>();
26
+ /** The owner's SEO settings for this page. */
27
+ readonly seo: SeoSettings;
28
+ /** On an item's page, what the item says about itself: the page's head when neither the owner nor the code does. */
29
+ readonly itemHead: ItemHead | undefined;
30
+ /** True when the values are the editor's preview: the drafts nobody saved yet, over what is saved. */
31
+ readonly preview: boolean;
32
+
33
+ constructor(
34
+ pageScope: string,
35
+ locale: string | undefined,
36
+ nodes: StoredNode[],
37
+ editing = false,
38
+ seo: SeoSettings = {},
39
+ itemHead?: ItemHead,
40
+ preview = false,
41
+ ) {
42
+ this.editing = editing;
43
+ this.seo = seo;
44
+ this.itemHead = itemHead;
45
+ this.preview = preview;
46
+ this.#pageScope = pageScope;
47
+ this.#siteScope = siteScope(locale);
48
+ for (const node of nodes) this.#nodes.set(key(node.scope, node.nodeId), node);
49
+ }
50
+
51
+ /**
52
+ * The owner's value for a node, or `undefined` when the source default applies.
53
+ * A stored value of another kind is ignored: the source changed what the node is.
54
+ */
55
+ read<K extends NodeKind>(kind: K, nodeId: string, scope: NodeScope = "page"): NodeValues[K] | undefined {
56
+ return this.#stored(kind, nodeId, scope) as NodeValues[K] | undefined;
57
+ }
58
+
59
+ /** A block's settings: its defaults, then what the page's code passes, then what the owner saved. */
60
+ settings(
61
+ definition: BlockDefinition,
62
+ nodeId: string,
63
+ scope: NodeScope,
64
+ source: Record<string, unknown>,
65
+ ): Record<string, unknown> {
66
+ const stored = this.#stored(definition.type, nodeId, scope) as Record<string, unknown> | undefined;
67
+ return resolveSettings(definition, source, stored);
68
+ }
69
+
70
+ /**
71
+ * The blocks the owner stacked in a `blocks` field of an item, for `<Blocks>` to draw: each block reads its value
72
+ * through the nodeId and scope given here, like any node, and its edits go back into the item.
73
+ */
74
+ blocks(
75
+ item: ItemBinding["item"],
76
+ field: string,
77
+ ): { nodeId: string; kind: string; scope: NodeScope; layout: BlockLayout }[] {
78
+ const scope = `item:${item.id}:${field}` as const;
79
+ this.#stacks.set(scope, { item, field });
80
+ const entries = blocksOf(item.data[field]);
81
+ // Saved blocks are checked, but one written some other way with an id that is not a nodeId is left out.
82
+ return entries
83
+ .filter((entry) => isNodeId(String(entry?.id)))
84
+ .map(({ id, type, value, layout }) => {
85
+ this.#nodes.set(key(scope, id), { scope, nodeId: id, kind: type, value });
86
+ return { nodeId: id, kind: type, scope, layout: layoutOf(type, layout, value) };
87
+ });
88
+ }
89
+
90
+ #stored(kind: string, nodeId: string, scope: NodeScope): unknown {
91
+ assertNodeId(nodeId);
92
+ const scopeKey = scope === "site" ? this.#siteScope : scope === "page" ? this.#pageScope : scope;
93
+ const node = this.#nodes.get(key(scopeKey, nodeId));
94
+ return node?.kind === kind ? node.value : undefined;
95
+ }
96
+
97
+ /**
98
+ * Attributes that let the editor find a node on the page. Empty on the public site.
99
+ * Pass `value` for kinds whose markup is written by the site author, so the editor can read it back,
100
+ * and `binding` for an element that shows a field of an item, so its edits are saved into the item.
101
+ */
102
+ marker(
103
+ kind: string,
104
+ nodeId: string,
105
+ scope: NodeScope,
106
+ value?: unknown,
107
+ binding?: ItemBinding,
108
+ ): Record<string, string> {
109
+ if (!this.editing) return {};
110
+ // A block of an item's `blocks` field is the item's content, like a field, and names its place in the field.
111
+ const stack = this.#stacks.get(scope);
112
+ if (stack) return { ...this.marker(kind, nodeId, "page", value, stack), "data-brim-entry": nodeId };
113
+ return {
114
+ "data-brim-node": nodeId,
115
+ "data-brim-kind": kind,
116
+ // The editor tells the template's parts from the item's own fields, which also carry `data-brim-item`.
117
+ "data-brim-scope": scope === "page" && this.#pageScope.startsWith("type:") ? "template" : scope,
118
+ ...(value !== undefined && { "data-brim-value": JSON.stringify(value) }),
119
+ ...(binding && {
120
+ "data-brim-item": binding.item.id,
121
+ "data-brim-item-type": binding.item.type,
122
+ "data-brim-item-title": binding.item.title,
123
+ "data-brim-field": binding.field,
124
+ }),
125
+ };
126
+ }
127
+ }
128
+
129
+ function key(scope: string, nodeId: string): string {
130
+ return `${scope}\n${nodeId}`;
131
+ }
@@ -0,0 +1,18 @@
1
+ import config from "virtual:brim/config";
2
+ import { resolveMedia } from "../config.ts";
3
+ import { type PrivateFiles, formFilesDirectory, resolveFormFiles } from "../forms/files.ts";
4
+
5
+ /**
6
+ * Where this site keeps the files visitors attach to forms, or nothing when it has no private place for them: a
7
+ * static build (no server takes them), or a host that keeps uploads in a storage and named no private one. Forms
8
+ * then leave their file fields out.
9
+ */
10
+ export function siteFormFiles(): PrivateFiles | undefined {
11
+ if (config.mode === "static") return undefined;
12
+ return resolveFormFiles({
13
+ storage: config.formFiles.storage,
14
+ mediaInStorage: Boolean(resolveMedia(config.media).storage),
15
+ // Beside the database the server runs with, wherever its host put it.
16
+ directory: formFilesDirectory(config.databaseUrl, process.cwd()),
17
+ });
18
+ }
@@ -0,0 +1,33 @@
1
+ import type { APIRoute } from "astro";
2
+ import config from "virtual:brim/config";
3
+ import { captchaCheck } from "../forms/captcha.ts";
4
+ import { type FormsHandler, createFormsHandler } from "../forms/handler.ts";
5
+ import { resolveMail } from "../config.ts";
6
+ import { siteFormFiles } from "./form-files.ts";
7
+ import { Mailer } from "../mail/mailer.ts";
8
+ import { clientAddress as visitorAddress } from "../server/http.ts";
9
+ import { connect } from "./connect.ts";
10
+
11
+ /** `/_brim/forms` on the built server: the same handler the dev server uses. */
12
+ export const prerender = false;
13
+
14
+ let handler: Promise<FormsHandler> | undefined;
15
+
16
+ export const ALL: APIRoute = async ({ request, clientAddress }) => {
17
+ handler ??= connect(config.databaseUrl, config.authToken).then((brim) =>
18
+ createFormsHandler(brim, {
19
+ mailer: new Mailer(resolveMail(config.mail)),
20
+ emails: () => config.emails,
21
+ captcha: captchaCheck(config.captcha),
22
+ files: siteFormFiles(),
23
+ siteName: config.identity.name,
24
+ // Written exactly so: Vite replaces the literal `import.meta.env.SITE` when it builds the server.
25
+ // @ts-expect-error Astro's types for import.meta.env are not part of this package's own check.
26
+ siteUrl: import.meta.env.SITE as string | undefined,
27
+ }),
28
+ );
29
+ return (
30
+ (await (await handler)(request, { clientAddress: visitorAddress(request, clientAddress) })) ??
31
+ new Response("Not found", { status: 404 })
32
+ );
33
+ };
@@ -0,0 +1,28 @@
1
+ import config from "virtual:brim/config";
2
+ import { type FormSpec, encodeSpec, sealAddress, sign } from "../forms/spec.ts";
3
+ import { connect } from "./connect.ts";
4
+ import { siteFormFiles } from "./form-files.ts";
5
+
6
+ /** Whether this site can take files from visitors; where it cannot, a form leaves its file fields out. */
7
+ export function takesFormFiles(): boolean {
8
+ return siteFormFiles() !== undefined;
9
+ }
10
+
11
+ /**
12
+ * Signs a form as the page renders it, so the server can later recognise it as one of the site's own.
13
+ *
14
+ * A signature never expires, so only what was saved is signed to send email. `preview` says the form was drawn with
15
+ * the drafts nobody saved yet (`BrimContext.preview`): what is signed then carries no confirmation and no
16
+ * notification address, or a draft thrown away a moment later would leave behind a form that emails its words for
17
+ * good. The dev server draws every page with its drafts and is its developer's alone: there the form is signed
18
+ * whole, so its emails can be tried.
19
+ */
20
+ export async function signForm(spec: FormSpec, preview: boolean): Promise<{ spec: string; signature: string }> {
21
+ const { forms } = await connect(config.databaseUrl, config.authToken);
22
+ const secret = await forms.secret();
23
+ const { notify: _notify, confirm: _confirm, ...silent } = spec;
24
+ // The page is public: the form's notification addresses go in it sealed, never as they are.
25
+ const whole = spec.notify ? { ...spec, notify: sealAddress(secret, spec.notify) } : spec;
26
+ const encoded = encodeSpec(preview && config.mode !== "dev" ? silent : whole);
27
+ return { spec: encoded, signature: sign(secret, encoded) };
28
+ }
@@ -0,0 +1,5 @@
1
+ import source from "virtual:brim/icons";
2
+ import { IconLibrary } from "../icons/library.ts";
3
+
4
+ /** The site's icons, as its config names them: Brim's own set and the packs added to it. */
5
+ export const icons = new IconLibrary(source.options, source.packs);