@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
package/dist/cli.js ADDED
@@ -0,0 +1,3802 @@
1
+ // <define:__BRIM_STARTER_MANIFEST__>
2
+ var define_BRIM_STARTER_MANIFEST_default = [{ path: "public/favicon.svg", sha256: "170b4e394ef6796502915a18f70ae4607bcb9a9a23c0ec7045d8f8c592b2a40e" }, { path: "public/images/hero.svg", sha256: "c1ff81e571d052f2db08f25e91d437330182ff42fefea4ba186124f01891e85c" }, { path: "src/components/CallToAction.astro", sha256: "98fca87addb732643a105bcf80479ba13d539ed23f742e5d4d4e14a02668d986" }, { path: "src/components/Features.astro", sha256: "bddbb073863911d51d0ea1cf003a6dd32fed918e16f123b29519ca9922179c88" }, { path: "src/components/Hero.astro", sha256: "5e5f1cc471df9e71bc1795a5c0670678701207ce5bd717f4f00dfe660000938a" }, { path: "src/components/navigation.ts", template: 'import type { NavItem } from "@brimsites/brimjs";\n\nexport const SITE_NAME = "{{siteName}}";\n\n/** The starting navigation. Once the owner reorders or renames links in the editor, their version is used. */\nexport const pages: NavItem[] = [\n { label: "Home", href: "/" },\n { label: "About", href: "/about" },\n { label: "Blog", href: "/blog" },\n { label: "Components", href: "/components" },\n { label: "Contact", href: "/contact" },\n];\n' }, { path: "src/components/SiteFooter.astro", sha256: "f6eca2a5cfae22dc71c1071975595c933604bf16763903657b3eb26186e9d4af" }, { path: "src/components/SiteHeader.astro", sha256: "2c1687e08228c373c367a20513c12b3d4ded85b6e7f1cb0c012e33baf6e0abee" }, { path: "src/content-types/article.ts", sha256: "166df04066ec12c53a4fe16d84b10c5f09c9720fa70caf46e7d1243ec4324ed9" }, { path: "src/content-types/ArticlePage.astro", sha256: "b3045994242025e484d6ac4c03118a8b9209620a16394cbba946f7d3eb9cac00" }, { path: "src/content-types/index.ts", sha256: "9b08142a7f6b0a1da786f11b40592cc2d6ffcea31eee84df267eaaef0990bf2b" }, { path: "src/layouts/Site.astro", sha256: "dc7a3dd160dc7a3a040611753dbc4c2e79a2bd7e72b734e3371fe8f59acccc13" }, { path: "src/page-templates/index.ts", sha256: "4fe86defa5897eaec7844223a6ef21dc360c3efb048cc1b76dbe2f18b1f292d2" }, { path: "src/page-templates/LandingPage.astro", sha256: "af4df862041b57360e2f70d6400bee3d78e778892727f4936b1af8a040a2ed0c" }, { path: "src/pages/about.astro", sha256: "231c4f44f1afa23c6d6c7495dea20f55aa65e8331e4b76aef5baa48acfff7804" }, { path: "src/pages/blog/index.astro", sha256: "89cf3f562a283eb29fbf1716992a9a4494c4cc77dd468dcddb66ef385bc51d72" }, { path: "src/pages/components.astro", sha256: "97938ce169d99cfa2eb5ed04fdb270e4ff23dd40051a62eadcf88ff1a0509361" }, { path: "src/pages/contact.astro", sha256: "bf53db53e2fecc7c2660725962f240679d66927d2cf282f45239a2ee0418cd02" }, { path: "src/pages/index.astro", sha256: "496f2c3d8cc1c4ebc34afcc6a1859e8730c57c119395c40b22bce195a874244c" }, { path: "src/site-settings.ts", sha256: "bdc3f6a59696ea037c076f85a95b737dfcb8a45c6820b848560e71f1af98bdd1" }, { path: "src/styles/global.css", sha256: "7e6ed61348f5a95b843c6f72c5315f9008da9028bf0f6f9669a17d6582a9788f" }];
3
+
4
+ // src/cli.ts
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync as existsSync5 } from "node:fs";
7
+ import { readFile as readFile4 } from "node:fs/promises";
8
+ import { basename as basename2, join as join6 } from "node:path";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { pathToFileURL } from "node:url";
11
+ import { Writable } from "node:stream";
12
+
13
+ // src/auth/permissions.ts
14
+ var ROLES = ["owner", "editor"];
15
+
16
+ // src/check.ts
17
+ import { existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, statSync } from "node:fs";
18
+ import { dirname, extname, join as join2, relative as relative2, resolve, sep as sep2 } from "node:path";
19
+
20
+ // src/starter.ts
21
+ import { createHash } from "node:crypto";
22
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
23
+ import { join, relative, sep } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ var CHECKED_FOLDERS = ["src", "public"];
26
+ var PLACEHOLDER = /\{\{(siteName|packageName|brimVersion)\}\}/;
27
+ function starterManifest() {
28
+ if (typeof define_BRIM_STARTER_MANIFEST_default !== "undefined") return define_BRIM_STARTER_MANIFEST_default;
29
+ const template = fileURLToPath(new URL("../../create-brim/template/", import.meta.url));
30
+ return existsSync(template) ? readStarter(template) : [];
31
+ }
32
+ function readStarter(templateFolder) {
33
+ const files = [];
34
+ for (const folder of CHECKED_FOLDERS) {
35
+ const root = join(templateFolder, folder);
36
+ if (!existsSync(root)) continue;
37
+ for (const entry of readdirSync(root, { withFileTypes: true, recursive: true })) {
38
+ if (!entry.isFile()) continue;
39
+ const file = join(entry.parentPath, entry.name);
40
+ const path = relative(templateFolder, file).split(sep).join("/");
41
+ const text2 = normalize(readFileSync(file, "utf8"));
42
+ files.push(PLACEHOLDER.test(text2) ? { path, template: text2 } : { path, sha256: hash(text2) });
43
+ }
44
+ }
45
+ return files.sort((a, b) => a.path.localeCompare(b.path));
46
+ }
47
+ function isUnchanged(starter, content2) {
48
+ const text2 = normalize(content2);
49
+ if (starter.sha256) return hash(text2) === starter.sha256;
50
+ if (starter.template === void 0) return false;
51
+ const literal = starter.template.split(PLACEHOLDER).filter((_, index) => index % 2 === 0);
52
+ const pattern = literal.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^\\n]*");
53
+ return new RegExp(`^${pattern}$`).test(text2);
54
+ }
55
+ function normalize(text2) {
56
+ return text2.replace(/\r\n/g, "\n");
57
+ }
58
+ function hash(text2) {
59
+ return createHash("sha256").update(text2).digest("hex");
60
+ }
61
+
62
+ // src/server/query-params.ts
63
+ function ruleMatches(pattern, pathname) {
64
+ if (pattern.includes("*")) {
65
+ const source = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
66
+ return new RegExp(`^${source}$`).test(pathname);
67
+ }
68
+ return pattern === pathname || pattern !== "/" && pattern === pathname.replace(/\/+$/, "");
69
+ }
70
+ function ruleFor(rules, pathname) {
71
+ let best;
72
+ for (const pattern of Object.keys(rules)) {
73
+ if (best !== void 0 && pattern.length <= best.length) continue;
74
+ if (ruleMatches(pattern, pathname)) best = pattern;
75
+ }
76
+ return best === void 0 ? void 0 : rules[best];
77
+ }
78
+ var READS_QUERY = /\bsearchParams\b|\bURLSearchParams\b|\burl\.search\b/;
79
+ var BROWSER_ADDRESS = /\blocation\b/;
80
+ var DECLARES = /\breadsQuery\s*\(/;
81
+ function queryReadLines(text2) {
82
+ const lines = [];
83
+ text2.split("\n").forEach((line, index) => {
84
+ const code = line.trimStart();
85
+ if (code.startsWith("//") || code.startsWith("*") || code.startsWith("/*")) return;
86
+ if (READS_QUERY.test(line) && !BROWSER_ADDRESS.test(line)) lines.push(index + 1);
87
+ });
88
+ return lines;
89
+ }
90
+ function pageRouteOf(file) {
91
+ const match = /(?:^|\/)src\/pages\/(.+)\.[a-z]+$/.exec(file.replaceAll("\\", "/"));
92
+ if (!match?.[1]) return void 0;
93
+ const segments = match[1].split("/").map((segment) => segment.replace(/\[[^\]]*\]/g, "_"));
94
+ if (segments.at(-1) === "index") segments.pop();
95
+ return `/${segments.join("/")}`;
96
+ }
97
+ function undeclaredQueryReads(files, declared) {
98
+ const found = [];
99
+ for (const { file, text: text2 } of files) {
100
+ const lines = queryReadLines(text2);
101
+ if (lines.length === 0 || DECLARES.test(text2)) continue;
102
+ const route = pageRouteOf(file);
103
+ if (route !== void 0 && ruleFor(declared, route) !== void 0) continue;
104
+ found.push({ file, line: lines[0] ?? 1 });
105
+ }
106
+ return found;
107
+ }
108
+ function queryPathsInConfig(text2) {
109
+ const start2 = text2.search(/\bquery\s*:\s*\{/);
110
+ if (start2 < 0) return {};
111
+ const rules = {};
112
+ for (const match of text2.slice(start2).matchAll(/["'`](\/[^"'`]*)["'`]\s*:/g)) {
113
+ if (match[1]) rules[match[1]] = "all";
114
+ }
115
+ return rules;
116
+ }
117
+
118
+ // src/check.ts
119
+ var SOURCE_EXTENSIONS = [".astro", ".tsx", ".jsx", ".mdx"];
120
+ var RESOLVE_EXTENSIONS = [".astro", ".tsx", ".ts", ".jsx", ".js", ".mdx"];
121
+ var SKIPPED_FOLDERS = /* @__PURE__ */ new Set(["node_modules", ".git", ".astro", "dist"]);
122
+ var CODE_EXTENSIONS = [...RESOLVE_EXTENSIONS, ".mjs", ".cjs", ".json"];
123
+ var CONTACT_ADDRESS = /(?:mailto:|tel:|wa\.me\/|api\.whatsapp\.com|(?:instagram|facebook|tiktok|linkedin|youtube|pinterest|x|twitter)\.com\/)[^"'`\s]*/g;
124
+ var SETTINGS_MODULE = /(?:^|\/)src\/site-settings\.[cm]?[jt]s$/;
125
+ var UPLOAD_ADDRESS = /["'`](?:https?:\/\/[^"'`\s/]+)?\/uploads\/[^"'`\s]+/g;
126
+ var ALWAYS_SITE = /* @__PURE__ */ new Set(["Navbar", "Footer"]);
127
+ var SITE_BY_DEFAULT = /* @__PURE__ */ new Set(["Newsletter", "SocialMedia"]);
128
+ var TAGS = "div span p a img h1 h2 h3 h4 h5 h6 li ul ol section article header footer nav main aside button figure figcaption picture svg strong em b i small label input form table tr td th blockquote".split(" ");
129
+ var GENERIC_WORDS = "text item block element el elem node component child entry row col column cell box wrapper wrap container group".split(" ");
130
+ var POSITIONAL = new RegExp(`(?:^|-)(?:${[...TAGS, ...GENERIC_WORDS].join("|")})-?\\d+(?:-|$)`);
131
+ var UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
132
+ var LONG_HEX = /(?:^|-)(?=[0-9a-f]*\d)[0-9a-f]{12,}(?:-|$)/;
133
+ var VALID_ID = /^[a-z][a-z0-9-]{0,63}$/;
134
+ function checkSite(siteFolder, options = {}) {
135
+ const root = resolve(siteFolder);
136
+ const sourceFolder = join2(root, "src");
137
+ if (!existsSync2(sourceFolder)) {
138
+ throw new Error(`There is no src folder in ${siteFolder}. Run brim check from the site's folder.`);
139
+ }
140
+ const files = listSources(sourceFolder).map((path) => relative2(root, path).split(sep2).join("/"));
141
+ const sources = new Map(files.map((file) => [file, parseSource(file, readFileSync2(join2(root, file), "utf8"))]));
142
+ const findings = [];
143
+ const add = (finding) => findings.push(finding);
144
+ let literalIds = 0;
145
+ let dynamicIds = 0;
146
+ for (const [file, source] of sources) {
147
+ for (const element of source.elements) {
148
+ const id = element.nodeId;
149
+ if (!id) continue;
150
+ if (id.kind !== "literal") {
151
+ dynamicIds++;
152
+ continue;
153
+ }
154
+ literalIds++;
155
+ checkName(file, element.line, id.value, add);
156
+ }
157
+ }
158
+ const resolved = /* @__PURE__ */ new Set();
159
+ const closures = files.map((file) => ({ file, occurrences: collect(file, sources, resolved) }));
160
+ findDuplicates(closures, add);
161
+ findSiteDuplicates(closures, add);
162
+ const starterStructure = findStarterLeftovers(root, options.starter ?? starterManifest(), add);
163
+ findUploadsInCode(root, sourceFolder, add);
164
+ findContactsInCode(root, sourceFolder, add);
165
+ findSavedPasswords(root, add);
166
+ findVocabularyPages(root, sourceFolder, add);
167
+ findHandDrawnImages(root, sourceFolder, add);
168
+ findFixedImageSizes(root, sourceFolder, add);
169
+ findLargePublicImages(root, add);
170
+ findImagesWithoutSizes(root, sourceFolder, add);
171
+ findMissingSharp(root, add);
172
+ findOrderFields(root, sourceFolder, add);
173
+ findTextOnlyBodies(root, sourceFolder, add);
174
+ findUndeclaredQueryReads(root, sourceFolder, add);
175
+ if (options.git !== false && !insideGit(root)) {
176
+ add({
177
+ file: ".",
178
+ severity: "warning",
179
+ rule: "no-git",
180
+ message: "the site is not in git: run `git init` and commit, so every change can be seen, reviewed and taken back (the local database and uploads stay out, as .gitignore says)"
181
+ });
182
+ }
183
+ findings.sort((a, b) => a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0));
184
+ const errors = findings.filter((finding) => finding.severity === "error").length;
185
+ return {
186
+ files: files.length,
187
+ literalIds,
188
+ dynamicIds,
189
+ resolvedDynamicIds: resolved.size,
190
+ findings,
191
+ starterStructure,
192
+ errors,
193
+ warnings: findings.length - errors
194
+ };
195
+ }
196
+ function formatReport(report) {
197
+ const lines = [];
198
+ let file;
199
+ for (const finding of report.findings) {
200
+ if (finding.file !== file) {
201
+ if (file !== void 0) lines.push("");
202
+ file = finding.file;
203
+ lines.push(file);
204
+ }
205
+ const line = finding.line === void 0 ? "" : String(finding.line);
206
+ lines.push(` ${line.padStart(4)} ${finding.severity.padEnd(7)} ${finding.message}`);
207
+ }
208
+ if (lines.length > 0) lines.push("");
209
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
210
+ lines.push(
211
+ `${plural(report.errors, "error")}, ${plural(report.warnings, "warning")} in ${plural(report.files, "file")} (${plural(report.literalIds, "literal nodeId")}).`
212
+ );
213
+ if (report.dynamicIds > 0) {
214
+ const unchecked = report.dynamicIds - report.resolvedDynamicIds;
215
+ lines.push(
216
+ `${plural(report.dynamicIds, "nodeId")} built at run time (\`\${id}-title\`): ${report.resolvedDynamicIds} checked through the literal props passed to them, ${unchecked} not checked.`
217
+ );
218
+ }
219
+ if (report.starterStructure.length > 0) {
220
+ lines.push(
221
+ `${plural(report.starterStructure.length, "structural starter file")} (layout, styles, content types) unchanged; that is expected.`
222
+ );
223
+ }
224
+ return lines.join("\n");
225
+ }
226
+ function checkName(file, line, id, add) {
227
+ if (!VALID_ID.test(id)) {
228
+ add({
229
+ file,
230
+ line,
231
+ severity: "warning",
232
+ rule: "format",
233
+ nodeId: id,
234
+ message: `nodeId "${id}" should be lowercase letters, digits and dashes, start with a letter, at most 64 characters`
235
+ });
236
+ }
237
+ if (UUID.test(id) || LONG_HEX.test(id)) {
238
+ add({
239
+ file,
240
+ line,
241
+ severity: "warning",
242
+ rule: "positional",
243
+ nodeId: id,
244
+ message: `nodeId "${id}" contains a generated id; name it for what the element is (hero-title)`
245
+ });
246
+ } else if (POSITIONAL.test(id.toLowerCase())) {
247
+ add({
248
+ file,
249
+ line,
250
+ severity: "warning",
251
+ rule: "positional",
252
+ nodeId: id,
253
+ message: `nodeId "${id}" names a position, not what the element is (hero-title rather than text-3)`
254
+ });
255
+ }
256
+ }
257
+ var NOTE_FILE = /\.(txt|md|json|ya?ml|csv|ini|cfg|conf)$|^[^.]+$/i;
258
+ var SKIPPED_NOTES = /* @__PURE__ */ new Set(["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "package.json", "tsconfig.json"]);
259
+ var PASSWORD_LINE = new RegExp(`(?<!\\p{L})(?:pass(?:word)?|parol[a\u0103]|pwd|passwd|mot de passe|contrase\xF1a)(?!\\p{L})["']?\\s*[:=]\\s*["']?[^\\s"',{}]{4,}`, "iu");
260
+ function findSavedPasswords(root, add) {
261
+ const walk = (folder) => {
262
+ for (const entry of readdirSync2(folder, { withFileTypes: true })) {
263
+ const path = join2(folder, entry.name);
264
+ if (entry.isDirectory()) {
265
+ if (!SKIPPED_FOLDERS.has(entry.name) && entry.name !== "uploads" && entry.name !== "src") walk(path);
266
+ continue;
267
+ }
268
+ if (!NOTE_FILE.test(entry.name) || SKIPPED_NOTES.has(entry.name) || entry.name.startsWith(".env")) continue;
269
+ if (statSync(path).size > 2e5) continue;
270
+ const lines = readFileSync2(path, "utf8").split("\n");
271
+ const line = lines.findIndex((text2) => PASSWORD_LINE.test(text2));
272
+ if (line === -1) continue;
273
+ add({
274
+ file: relative2(root, path).split(sep2).join("/"),
275
+ line: line + 1,
276
+ severity: "error",
277
+ rule: "saved-password",
278
+ message: "a password written in a file: whoever gets the folder (a zip, a deploy, a repository) gets it too. Delete it, change that password, and sign in with a one-time link instead: npx brim user link <email>"
279
+ });
280
+ }
281
+ };
282
+ walk(root);
283
+ }
284
+ function insideGit(root) {
285
+ let folder = root;
286
+ for (; ; ) {
287
+ if (existsSync2(join2(folder, ".git"))) return true;
288
+ const parent = dirname(folder);
289
+ if (parent === folder) return false;
290
+ folder = parent;
291
+ }
292
+ }
293
+ function findContactsInCode(root, sourceFolder, add) {
294
+ for (const path of listSources(sourceFolder, CODE_EXTENSIONS)) {
295
+ const file = relative2(root, path).split(sep2).join("/");
296
+ if (SETTINGS_MODULE.test(file)) continue;
297
+ const found = [];
298
+ readFileSync2(path, "utf8").split("\n").forEach((line, index) => {
299
+ const code = line.trimStart();
300
+ if (code.startsWith("//") || code.startsWith("*")) return;
301
+ for (const match of line.matchAll(CONTACT_ADDRESS)) {
302
+ const before = line.slice(0, match.index);
303
+ const example = /placeholder\s*[:=]\s*\{?\s*["'`][^"'`]*$/.test(before) || /(\.\.\.|…)$/.test(match[0]);
304
+ if (!/\$\{/.test(match[0]) && match[0].length > 7 && !example) found.push(index + 1);
305
+ }
306
+ });
307
+ if (found.length === 0) continue;
308
+ add({
309
+ file,
310
+ line: found[0] ?? 1,
311
+ severity: "warning",
312
+ rule: "contact-in-code",
313
+ message: `${found.length === 1 ? "a contact detail" : `${found.length} contact details`} (email, phone, WhatsApp, social profile) written in the code: the owner cannot change them. Declare them in src/site-settings.ts and read them with getSiteSettings(), or show them with <Setting name="\u2026" />`
314
+ });
315
+ }
316
+ }
317
+ function findUploadsInCode(root, sourceFolder, add) {
318
+ for (const path of listSources(sourceFolder, CODE_EXTENSIONS)) {
319
+ const lines = readFileSync2(path, "utf8").split("\n");
320
+ const found = [];
321
+ lines.forEach((line, index) => {
322
+ const code = line.trimStart();
323
+ if (code.startsWith("//") || code.startsWith("*")) return;
324
+ for (const _match of line.matchAll(UPLOAD_ADDRESS)) found.push(index + 1);
325
+ });
326
+ if (found.length === 0) continue;
327
+ add({
328
+ file: relative2(root, path).split(sep2).join("/"),
329
+ line: found[0] ?? 1,
330
+ severity: "warning",
331
+ rule: "uploads-in-code",
332
+ message: `${found.length === 1 ? "an address" : `${found.length} addresses`} of the media library (/uploads/\u2026) in the code: uploads are not in git, so a fresh clone or a deploy without the content has none of them. Keep them in the content (an item's field, an element's saved value) and give the code a starting picture of its own (public/ or src/assets/)`
333
+ });
334
+ }
335
+ }
336
+ var HAND_DRAWN_IMAGE = /<img\b[^>]*?\ssrc=\{\s*mediaUrl\(/g;
337
+ function findHandDrawnImages(root, sourceFolder, add) {
338
+ for (const path of listSources(sourceFolder)) {
339
+ const text2 = readFileSync2(path, "utf8");
340
+ const lines = [...text2.matchAll(HAND_DRAWN_IMAGE)].map((match) => text2.slice(0, match.index).split("\n").length);
341
+ if (lines.length === 0) continue;
342
+ add({
343
+ file: relative2(root, path).split(sep2).join("/"),
344
+ line: lines[0] ?? 1,
345
+ severity: "warning",
346
+ rule: "hand-drawn-image",
347
+ message: `${lines.length === 1 ? "an image" : `${lines.length} images`} of the content drawn as <img src={mediaUrl(\u2026)}>: without a srcset every visitor downloads the full upload, and the owner cannot replace it from the page. Use <Image bare nodeId="\u2026" item={item} field="\u2026" src="" alt="" /> (it takes class, loading and sizes as an <img> does), or {...imageSources(src, sizes)} from brimjs/content where it cannot be a component`
348
+ });
349
+ }
350
+ }
351
+ var IMG_TAG = /<img\b(?:[^>]|(?<==)>)*>/g;
352
+ var BRIM_SOURCES = /imageSources\(|\.img\s*\}/;
353
+ var FIXED_SIZE = /\s(?:width|height)=(?:["']\d+["']|\{\s*\d+\s*\})/;
354
+ function findFixedImageSizes(root, sourceFolder, add) {
355
+ for (const path of listSources(sourceFolder)) {
356
+ const text2 = readFileSync2(path, "utf8");
357
+ const lines = [...text2.matchAll(IMG_TAG)].filter((match) => BRIM_SOURCES.test(match[0]) && FIXED_SIZE.test(match[0])).map((match) => text2.slice(0, match.index).split("\n").length);
358
+ if (lines.length === 0) continue;
359
+ add({
360
+ file: relative2(root, path).split(sep2).join("/"),
361
+ line: lines[0] ?? 1,
362
+ severity: "warning",
363
+ rule: "fixed-image-size",
364
+ message: `${lines.length === 1 ? "an image" : `${lines.length} images`} of the content with a width or height written as a number: every picture gets that shape, so portrait photos jump as they load. Leave width and height out: imageSources and image.img give each upload its own size (and set height: auto in the CSS)`
365
+ });
366
+ }
367
+ }
368
+ var BRIM_IMAGE_IMPORT = /import\s*\{[^}]*\bImage\b(?!\s+as\b)[^}]*\}\s*from\s*["']@brimsites\/brimjs\/components["']/;
369
+ var IMAGE_TAG = /<Image\b(?:[^>]|(?<==)>)*>/g;
370
+ function findImagesWithoutSizes(root, sourceFolder, add) {
371
+ for (const path of listSources(sourceFolder)) {
372
+ const text2 = readFileSync2(path, "utf8");
373
+ if (!BRIM_IMAGE_IMPORT.test(text2)) continue;
374
+ const lines = [...text2.matchAll(IMAGE_TAG)].filter(([tag]) => !/\ssizes[=\s/>]/.test(tag) && !tag.includes("{...")).map((match) => text2.slice(0, match.index).split("\n").length);
375
+ if (lines.length === 0) continue;
376
+ add({
377
+ file: relative2(root, path).split(sep2).join("/"),
378
+ line: lines[0] ?? 1,
379
+ severity: "warning",
380
+ rule: "image-sizes",
381
+ message: `${lines.length === 1 ? "an <Image>" : `${lines.length} <Image> elements`} without sizes: the browser takes the picture to be as wide as the page and downloads a copy that wide. Where it is drawn narrower, say how wide, e.g. sizes="(max-width: 768px) 100vw, 50vw"; a picture that spans the page needs none`
382
+ });
383
+ }
384
+ }
385
+ var ASKS_FOR_SHARP = /\bsharp\s*:\s*true\b/;
386
+ function findMissingSharp(root, add) {
387
+ const config = ["mjs", "ts", "js", "mts", "cjs"].map((extension) => join2(root, `astro.config.${extension}`));
388
+ const asked = config.some((path) => existsSync2(path) && ASKS_FOR_SHARP.test(readFileSync2(path, "utf8")));
389
+ if (!asked || !existsSync2(join2(root, "node_modules")) || existsSync2(join2(root, "node_modules", "sharp"))) return;
390
+ add({
391
+ file: "package.json",
392
+ severity: "warning",
393
+ rule: "no-sharp",
394
+ message: "media.sharp is on but sharp is not installed: the pictures in public/ are sent as they were saved, with no smaller copies for a phone. Add it to the site's dependencies (npm install sharp)"
395
+ });
396
+ }
397
+ var LARGE_PUBLIC_IMAGE = 500 * 1024;
398
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".webp", ".avif", ".gif"]);
399
+ function findLargePublicImages(root, add) {
400
+ const folder = join2(root, "public");
401
+ if (!existsSync2(folder)) return;
402
+ const large = [];
403
+ const walk = (directory) => {
404
+ for (const entry of readdirSync2(directory, { withFileTypes: true })) {
405
+ const path = join2(directory, entry.name);
406
+ if (entry.isDirectory()) {
407
+ if (path !== join2(folder, "uploads") && !SKIPPED_FOLDERS.has(entry.name)) walk(path);
408
+ } else if (IMAGE_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
409
+ const size = statSync(path).size;
410
+ if (size > LARGE_PUBLIC_IMAGE) large.push({ file: relative2(root, path).split(sep2).join("/"), size });
411
+ }
412
+ }
413
+ };
414
+ walk(folder);
415
+ if (large.length === 0) return;
416
+ large.sort((a, b) => b.size - a.size);
417
+ const listed = large.slice(0, 5).map(({ file, size }) => `${file} (${(size / 1024 / 1024).toFixed(1)} MB)`).join(", ");
418
+ add({
419
+ file: large[0]?.file ?? "public",
420
+ severity: "warning",
421
+ rule: "large-public-image",
422
+ message: `${large.length === 1 ? "an image" : `${large.length} images`} in public/ larger than 500 KB: ${listed}${large.length > 5 ? ", \u2026" : ""}. A server sends visitors smaller copies, but each copy is made from this file, every clone and deploy carries it, and a static build sends it whole: save it once at most 2560 px wide (about 2000 px is enough for a full-width photo). Pictures of items belong in the media library instead`
423
+ });
424
+ }
425
+ var RICHTEXT_FIELD = /\{[^{}\n]*?\btype\s*:\s*["'`]richtext["'`][^\n]*/g;
426
+ function findTextOnlyBodies(root, sourceFolder, add) {
427
+ const folder = join2(sourceFolder, "content-types");
428
+ if (!existsSync2(folder)) return;
429
+ for (const path of listSources(folder, CODE_EXTENSIONS)) {
430
+ const text2 = readFileSync2(path, "utf8");
431
+ if (!/\bcomponent\s*[:,}]/.test(text2) || /\btype\s*:\s*["'`]blocks["'`]/.test(text2)) continue;
432
+ const match = [...text2.matchAll(RICHTEXT_FIELD)].find((found) => !/\/\/\s*text only/i.test(found[0]));
433
+ if (!match) continue;
434
+ const name = /\bname\s*:\s*["'`]([^"'`]+)["'`]/.exec(match[0])?.[1] ?? "a field";
435
+ add({
436
+ file: relative2(root, path).split(sep2).join("/"),
437
+ line: text2.slice(0, match.index).split("\n").length,
438
+ severity: "warning",
439
+ rule: "text-only-body",
440
+ message: `"${name}" is rich text and the type has no blocks field: on its pages the owner can only write text, never add an image, gallery, button or video between paragraphs. For a body, make it type: "blocks" (texts already saved become its first block when the site starts, and <Blocks> draws it); if text is all it should hold, add // text only on its line`
441
+ });
442
+ }
443
+ }
444
+ var ORDER_FIELD = /\{[^{}]*?\bname\s*:\s*["'`](order|ordine|ordinea|position|pozitie|poziție|sort|sort_order|rank|weight)["'`][^{}]*?\btype\s*:\s*["'`]number["'`][^{}]*\}|\{[^{}]*?\btype\s*:\s*["'`]number["'`][^{}]*?\bname\s*:\s*["'`](order|ordine|ordinea|position|pozitie|poziție|sort|sort_order|rank|weight)["'`][^{}]*\}/g;
445
+ function findOrderFields(root, sourceFolder, add) {
446
+ const folder = join2(sourceFolder, "content-types");
447
+ if (!existsSync2(folder)) return;
448
+ for (const path of listSources(folder, CODE_EXTENSIONS)) {
449
+ const text2 = readFileSync2(path, "utf8");
450
+ for (const match of text2.matchAll(ORDER_FIELD)) {
451
+ add({
452
+ file: relative2(root, path).split(sep2).join("/"),
453
+ line: text2.slice(0, match.index).split("\n").length,
454
+ severity: "warning",
455
+ rule: "order-field",
456
+ message: `the number field "${match[1] ?? match[2]}" keeps the order of the items: the owner has to type a number into each one to move it. Declare the type ordered: true and delete the field; the owner then drags the items into order in the editor, and Listing and getItems list them that way (sort="position")`
457
+ });
458
+ }
459
+ }
460
+ }
461
+ function findVocabularyPages(root, sourceFolder, add) {
462
+ const vocabularies = /* @__PURE__ */ new Map();
463
+ for (const path of listSources(sourceFolder, CODE_EXTENSIONS)) {
464
+ const text2 = readFileSync2(path, "utf8");
465
+ for (const match of text2.matchAll(/defineVocabulary\s*\(/g)) {
466
+ const call2 = balanced(text2, (match.index ?? 0) + match[0].length - 1);
467
+ const key = /\bkey\s*:\s*["'`]([a-z][a-z0-9_]*)["'`]/.exec(call2)?.[1];
468
+ if (!key) continue;
469
+ const route = /\bpath\s*:\s*["'`]([^"'`]+)["'`]/.exec(call2)?.[1];
470
+ vocabularies.set(key, { component: /\bcomponent\s*[:,}]/.test(call2), ...route && { path: route } });
471
+ }
472
+ }
473
+ if (vocabularies.size === 0) return;
474
+ const pagesFolder = join2(sourceFolder, "pages");
475
+ if (!existsSync2(pagesFolder)) return;
476
+ for (const path of listSources(pagesFolder, [".astro", ".ts", ".js", ".mdx"])) {
477
+ const file = relative2(root, path).split(sep2).join("/");
478
+ const name = /\[([a-z][a-z0-9_]*)\]\.[a-z]+$/.exec(file)?.[1];
479
+ if (!name) continue;
480
+ const vocabulary = vocabularies.get(name);
481
+ if (!vocabulary) continue;
482
+ const route = `/${relative2(pagesFolder, path).split(sep2).join("/")}`.replace(/\.[a-z]+$/, "");
483
+ const address = route.replace(`[${name}]`, "[slug]");
484
+ if (!vocabulary.component) {
485
+ add({
486
+ file,
487
+ line: 1,
488
+ severity: "warning",
489
+ rule: "vocabulary-page",
490
+ message: `this page draws the terms of the "${name}" vocabulary by hand. Give the vocabulary path: "${address}" and this page as its component (it gets the term as \`item\`, like an item's page), then delete this file: the terms then have pages the editor knows (their fields, the site map), in the sitemap, without getStaticPaths`
491
+ });
492
+ } else if (vocabulary.path === address) {
493
+ add({
494
+ file,
495
+ line: 1,
496
+ severity: "error",
497
+ rule: "vocabulary-page",
498
+ message: `this page takes the addresses of the "${name}" vocabulary's pages (${address}): the site's own pages come first, so its component is never used. Delete this file`
499
+ });
500
+ }
501
+ }
502
+ }
503
+ function balanced(text2, open) {
504
+ let depth = 0;
505
+ for (let index = open; index < text2.length; index++) {
506
+ const char = text2[index];
507
+ if (char === '"' || char === "'" || char === "`") {
508
+ index = skipString(text2, index, char) - 1;
509
+ continue;
510
+ }
511
+ if (char === "(") depth++;
512
+ else if (char === ")" && --depth === 0) return text2.slice(open, index + 1);
513
+ }
514
+ return text2.slice(open);
515
+ }
516
+ function collect(file, sources, resolved) {
517
+ const occurrences = [];
518
+ const visit = (current, props, stack, entry) => {
519
+ const source = sources.get(current);
520
+ if (!source) return;
521
+ for (const element of source.elements) {
522
+ const component = source.imports.get(element.name);
523
+ const target = component && resolveImport(current, component, sources);
524
+ if (target) {
525
+ if (!stack.includes(target) && stack.length < 20) {
526
+ visit(target, element.props, [...stack, target], entry ?? { line: element.line, through: element.name });
527
+ }
528
+ continue;
529
+ }
530
+ const id = element.nodeId && idValue(element.nodeId, props);
531
+ if (!id || element.scope === "unknown") continue;
532
+ if (element.nodeId?.kind === "prefixed") resolved.add(`${current}:${element.line}`);
533
+ occurrences.push({
534
+ id,
535
+ scope: element.scope,
536
+ file: current,
537
+ line: element.line,
538
+ entryLine: entry?.line ?? element.line,
539
+ ...entry && { through: entry.through },
540
+ ...element.binding && { binding: `${current}|${element.binding}` }
541
+ });
542
+ }
543
+ };
544
+ visit(file, void 0, [file], void 0);
545
+ return occurrences;
546
+ }
547
+ function idValue(id, props) {
548
+ if (id.kind === "literal") return id.value;
549
+ if (id.kind === "prefixed") {
550
+ const prefix = props?.get(id.prop);
551
+ return prefix === void 0 ? void 0 : `${prefix}${id.suffix}`;
552
+ }
553
+ return void 0;
554
+ }
555
+ function findDuplicates(closures, add) {
556
+ const reported = /* @__PURE__ */ new Set();
557
+ const bySize = [...closures].sort((a, b) => a.occurrences.length - b.occurrences.length);
558
+ for (const { file, occurrences } of bySize) {
559
+ const byId = /* @__PURE__ */ new Map();
560
+ for (const occurrence of occurrences) {
561
+ if (occurrence.scope !== "page") continue;
562
+ byId.set(occurrence.id, [...byId.get(occurrence.id) ?? [], occurrence]);
563
+ }
564
+ for (const [id, same] of byId) {
565
+ if (same.length < 2) continue;
566
+ const binding = same[0]?.binding;
567
+ if (binding !== void 0 && same.every((occurrence) => occurrence.binding === binding)) continue;
568
+ const key = `${id}|${same.map((occurrence) => `${occurrence.file}:${occurrence.line}`).sort().join(",")}`;
569
+ if (reported.has(key)) continue;
570
+ reported.add(key);
571
+ const places = same.map(
572
+ (occurrence) => occurrence.file === file && !occurrence.through ? `line ${occurrence.line}` : `${occurrence.file}:${occurrence.line} (through <${occurrence.through}> at line ${occurrence.entryLine})`
573
+ );
574
+ const where = file.startsWith("src/pages/") ? "on this page" : "in what this file draws";
575
+ add({
576
+ file,
577
+ line: Math.max(...same.map((occurrence) => occurrence.entryLine)),
578
+ severity: "error",
579
+ rule: "duplicate",
580
+ nodeId: id,
581
+ message: `nodeId "${id}" is used ${same.length} times ${where}: ${places.join(", ")}`
582
+ });
583
+ }
584
+ }
585
+ }
586
+ function findSiteDuplicates(closures, add) {
587
+ const places = /* @__PURE__ */ new Map();
588
+ for (const { occurrences } of closures) {
589
+ for (const occurrence of occurrences) {
590
+ if (occurrence.scope !== "site") continue;
591
+ const byPlace = places.get(occurrence.id) ?? /* @__PURE__ */ new Map();
592
+ byPlace.set(`${occurrence.file}:${occurrence.line}`, occurrence);
593
+ places.set(occurrence.id, byPlace);
594
+ }
595
+ }
596
+ for (const [id, byPlace] of places) {
597
+ if (byPlace.size < 2) continue;
598
+ const sorted = [...byPlace.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
599
+ const [first, ...others] = sorted;
600
+ add({
601
+ file: first.file,
602
+ line: first.line,
603
+ severity: "error",
604
+ rule: "site-duplicate",
605
+ nodeId: id,
606
+ message: `site-wide nodeId "${id}" is also used by ${others.map((other) => `${other.file}:${other.line}`).join(", ")}; they would share one edit`
607
+ });
608
+ }
609
+ }
610
+ var STARTER_STRUCTURE = /^src\/(layouts|styles|content-types)\/|^src\/page-templates\/index\.ts$|^src\/site-settings\.ts$/;
611
+ function findStarterLeftovers(root, starter, add) {
612
+ const structure = [];
613
+ for (const file of starter) {
614
+ const path = join2(root, file.path);
615
+ if (!existsSync2(path)) continue;
616
+ const unchanged = isUnchanged(file, readFileSync2(path, "utf8"));
617
+ if (file.path === "src/pages/components.astro") {
618
+ add({
619
+ file: file.path,
620
+ severity: "warning",
621
+ rule: "starter",
622
+ message: `the starter's component showcase${unchanged ? "" : " (changed)"}: delete it, and its links in the navigation and the home page`
623
+ });
624
+ } else if (unchanged && STARTER_STRUCTURE.test(file.path)) {
625
+ structure.push(file.path);
626
+ } else if (unchanged) {
627
+ const content2 = file.path.startsWith("src/pages/") || file.path.startsWith("public/");
628
+ add({
629
+ file: file.path,
630
+ severity: "warning",
631
+ rule: "starter",
632
+ message: content2 ? "unchanged from the create-brim starter: replace it with the site's own content or delete it" : "unchanged from the create-brim starter: keep it only if the site uses it as it is"
633
+ });
634
+ }
635
+ }
636
+ return structure;
637
+ }
638
+ function parseSource(file, text2) {
639
+ const extension = extname(file);
640
+ let start2 = 0;
641
+ let code = text2;
642
+ if (extension === ".astro") {
643
+ const frontmatter = /^\s*---\r?\n([\s\S]*?)\r?\n---/.exec(text2);
644
+ code = frontmatter?.[1] ?? "";
645
+ start2 = frontmatter ? frontmatter[0].length : 0;
646
+ }
647
+ return { elements: parseElements(text2, start2, extension), imports: parseImports(code) };
648
+ }
649
+ function parseImports(code) {
650
+ const imports = /* @__PURE__ */ new Map();
651
+ const statement = /\bimport\s+(?!type\s)([^;'"]*?)\s+from\s+["']([^"']+)["']/g;
652
+ for (const [, clause = "", specifier = ""] of code.matchAll(statement)) {
653
+ if (!specifier.startsWith(".")) continue;
654
+ const defaultName = /^([\w$]+)/.exec(clause.trim())?.[1];
655
+ if (defaultName) imports.set(defaultName, specifier);
656
+ const named = /\{([^}]*)\}/.exec(clause)?.[1] ?? "";
657
+ for (const part of named.split(",")) {
658
+ const name = part.trim().replace(/^type\s+/, "");
659
+ if (!name || part.trim().startsWith("type ")) continue;
660
+ imports.set(name.split(/\s+as\s+/).pop() ?? name, specifier);
661
+ }
662
+ }
663
+ return imports;
664
+ }
665
+ function resolveImport(from, specifier, sources) {
666
+ const base = join2(dirname(from), specifier).split(sep2).join("/");
667
+ const bare = base.replace(/\.(m?js|jsx)$/, "");
668
+ const candidates = [
669
+ base,
670
+ ...RESOLVE_EXTENSIONS.map((extension) => bare + extension),
671
+ ...RESOLVE_EXTENSIONS.map((extension) => `${base}/index${extension}`)
672
+ ];
673
+ return candidates.find((candidate) => sources.has(candidate));
674
+ }
675
+ function parseElements(text2, start2, extension) {
676
+ const elements = [];
677
+ const lineStarts = [0];
678
+ for (let index2 = 0; index2 < text2.length; index2++) if (text2[index2] === "\n") lineStarts.push(index2 + 1);
679
+ const lineOf = (position) => {
680
+ let low = 0;
681
+ let high = lineStarts.length - 1;
682
+ while (low < high) {
683
+ const middle = Math.ceil((low + high) / 2);
684
+ if ((lineStarts[middle] ?? 0) <= position) low = middle;
685
+ else high = middle - 1;
686
+ }
687
+ return low + 1;
688
+ };
689
+ const isScript = extension === ".tsx" || extension === ".jsx";
690
+ let index = start2;
691
+ while (index < text2.length) {
692
+ if (text2.startsWith("<!--", index)) {
693
+ index = after(text2, "-->", index + 4);
694
+ } else if (text2.startsWith("/*", index)) {
695
+ index = after(text2, "*/", index + 2);
696
+ } else if (isScript && text2.startsWith("//", index)) {
697
+ index = after(text2, "\n", index + 2);
698
+ } else if (text2[index] === "<" && /[A-Za-z]/.test(text2[index + 1] ?? "")) {
699
+ const tag = parseTag(text2, index + 1);
700
+ elements.push(toElement(tag.name, tag.attributes, lineOf(index)));
701
+ index = tag.end;
702
+ if (!tag.selfClosing && (tag.name === "script" || tag.name === "style")) {
703
+ index = after(text2, `</${tag.name}`, index);
704
+ }
705
+ } else {
706
+ index++;
707
+ }
708
+ }
709
+ return elements;
710
+ }
711
+ function after(text2, marker, from) {
712
+ const found = text2.indexOf(marker, from);
713
+ return found === -1 ? text2.length : found + marker.length;
714
+ }
715
+ function parseTag(text2, from) {
716
+ const name = /^[A-Za-z][\w.:-]*/.exec(text2.slice(from, from + 200))?.[0] ?? "";
717
+ const attributes = /* @__PURE__ */ new Map();
718
+ let index = from + name.length;
719
+ while (index < text2.length) {
720
+ const char = text2[index] ?? "";
721
+ if (char === ">") return { name, attributes, end: index + 1, selfClosing: false };
722
+ if (text2.startsWith("/>", index)) return { name, attributes, end: index + 2, selfClosing: true };
723
+ if (char === "{") {
724
+ index = skipExpression(text2, index);
725
+ continue;
726
+ }
727
+ const attributeName = /^[\w:@$.-]+/.exec(text2.slice(index, index + 100))?.[0];
728
+ if (!attributeName) {
729
+ index++;
730
+ continue;
731
+ }
732
+ index += attributeName.length;
733
+ while (/\s/.test(text2[index] ?? "")) index++;
734
+ if (text2[index] !== "=") {
735
+ attributes.set(attributeName, { kind: "bare" });
736
+ continue;
737
+ }
738
+ index++;
739
+ while (/\s/.test(text2[index] ?? "")) index++;
740
+ const quote = text2[index];
741
+ if (quote === '"' || quote === "'") {
742
+ const end = text2.indexOf(quote, index + 1);
743
+ const close = end === -1 ? text2.length : end;
744
+ attributes.set(attributeName, { kind: "string", value: text2.slice(index + 1, close) });
745
+ index = close + 1;
746
+ } else if (quote === "{") {
747
+ const end = skipExpression(text2, index);
748
+ attributes.set(attributeName, { kind: "expression", value: text2.slice(index + 1, end - 1).trim() });
749
+ index = end;
750
+ } else {
751
+ const value = /^[^\s>]*/.exec(text2.slice(index))?.[0] ?? "";
752
+ attributes.set(attributeName, { kind: "string", value: value.replace(/\/$/, "") });
753
+ index += value.length;
754
+ }
755
+ }
756
+ return { name, attributes, end: text2.length, selfClosing: false };
757
+ }
758
+ function skipExpression(text2, from) {
759
+ let depth = 0;
760
+ let index = from;
761
+ while (index < text2.length) {
762
+ const char = text2[index];
763
+ if (char === '"' || char === "'") {
764
+ index = skipString(text2, index, char);
765
+ continue;
766
+ }
767
+ if (char === "`") {
768
+ index = skipTemplate(text2, index);
769
+ continue;
770
+ }
771
+ if (text2.startsWith("//", index)) {
772
+ index = after(text2, "\n", index + 2);
773
+ continue;
774
+ }
775
+ if (text2.startsWith("/*", index)) {
776
+ index = after(text2, "*/", index + 2);
777
+ continue;
778
+ }
779
+ if (char === "{") depth++;
780
+ if (char === "}") {
781
+ depth--;
782
+ if (depth === 0) return index + 1;
783
+ }
784
+ index++;
785
+ }
786
+ return text2.length;
787
+ }
788
+ function skipString(text2, from, quote) {
789
+ let index = from + 1;
790
+ while (index < text2.length && text2[index] !== quote && text2[index] !== "\n") {
791
+ index += text2[index] === "\\" ? 2 : 1;
792
+ }
793
+ return index + 1;
794
+ }
795
+ function skipTemplate(text2, from) {
796
+ let index = from + 1;
797
+ while (index < text2.length && text2[index] !== "`") {
798
+ if (text2[index] === "\\") index += 2;
799
+ else if (text2.startsWith("${", index)) index = skipExpression(text2, index + 1);
800
+ else index++;
801
+ }
802
+ return index + 1;
803
+ }
804
+ function toElement(name, attributes, line) {
805
+ const props = /* @__PURE__ */ new Map();
806
+ for (const [key, attribute] of attributes) {
807
+ const value = literalOf(attribute);
808
+ if (value !== void 0) props.set(key, value);
809
+ }
810
+ const element = { name, line, scope: scopeOf(name, attributes.get("scope")), props };
811
+ const nodeId = attributes.get("nodeId");
812
+ if (nodeId && nodeId.kind !== "bare") element.nodeId = nodeIdOf(nodeId);
813
+ const item = attributes.get("item");
814
+ const field = literalOf(attributes.get("field"));
815
+ if (item?.kind === "expression" && field !== void 0) element.binding = `${item.value.trim()}|${field}`;
816
+ return element;
817
+ }
818
+ function literalOf(attribute) {
819
+ if (!attribute || attribute.kind === "bare") return void 0;
820
+ if (attribute.kind === "string") return attribute.value;
821
+ const quoted = /^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/.exec(attribute.value);
822
+ return quoted ? quoted[1] ?? quoted[2] ?? quoted[3] : void 0;
823
+ }
824
+ function nodeIdOf(attribute) {
825
+ const literal = literalOf(attribute);
826
+ if (literal !== void 0) return { kind: "literal", value: literal };
827
+ if (attribute.kind !== "expression") return { kind: "dynamic" };
828
+ const prefixed = /^`\$\{\s*([\w$]+)\s*\}([^`$\\]*)`$/.exec(attribute.value);
829
+ if (prefixed) return { kind: "prefixed", prop: prefixed[1] ?? "", suffix: prefixed[2] ?? "" };
830
+ if (/^[A-Za-z_$][\w$]*$/.test(attribute.value)) return { kind: "prefixed", prop: attribute.value, suffix: "" };
831
+ return { kind: "dynamic" };
832
+ }
833
+ function scopeOf(name, attribute) {
834
+ if (ALWAYS_SITE.has(name)) return "site";
835
+ if (!attribute) return SITE_BY_DEFAULT.has(name) ? "site" : "page";
836
+ const value = literalOf(attribute);
837
+ if (value === "site") return "site";
838
+ return value === "page" ? "page" : "unknown";
839
+ }
840
+ function findUndeclaredQueryReads(root, sourceFolder, add) {
841
+ const configFile = ["mjs", "ts", "js", "mts", "cjs"].map((extension) => join2(root, `astro.config.${extension}`)).find((file) => existsSync2(file));
842
+ const declared = configFile ? queryPathsInConfig(readFileSync2(configFile, "utf8")) : {};
843
+ const files = listSources(sourceFolder, CODE_EXTENSIONS.filter((extension) => extension !== ".json")).filter((path) => !path.endsWith(".d.ts")).map((path) => ({ file: relative2(root, path).split(sep2).join("/"), text: readFileSync2(path, "utf8") }));
844
+ for (const { file, line } of undeclaredQueryReads(files, declared)) {
845
+ add({
846
+ file,
847
+ line,
848
+ severity: "warning",
849
+ rule: "undeclared-query",
850
+ message: `reads the request's query without saying which parameters: call readsQuery(["name", \u2026]) from "@brimsites/brimjs/server" where it reads them (or declare its route in brim({ query })), so a host caching pages keeps exactly those. Until then pages are cached less precisely`
851
+ });
852
+ }
853
+ }
854
+ function listSources(folder, extensions = SOURCE_EXTENSIONS) {
855
+ const found = [];
856
+ for (const entry of readdirSync2(folder, { withFileTypes: true })) {
857
+ const path = join2(folder, entry.name);
858
+ if (entry.isDirectory()) {
859
+ if (!SKIPPED_FOLDERS.has(entry.name)) found.push(...listSources(path, extensions));
860
+ } else if (extensions.includes(extname(entry.name)) && statSync(path).isFile()) {
861
+ found.push(path);
862
+ }
863
+ }
864
+ return found.sort();
865
+ }
866
+
867
+ // src/content/ids.ts
868
+ function siteScope(locale) {
869
+ return locale ? `site:${locale}` : "site";
870
+ }
871
+ var NODE_ID = /^[a-z][a-z0-9-]{0,63}$/;
872
+ function isNodeId(value) {
873
+ return NODE_ID.test(value);
874
+ }
875
+ function assertNodeId(value) {
876
+ if (!isNodeId(value)) {
877
+ throw new Error(
878
+ `Invalid nodeId "${value}": use lowercase letters, digits and dashes, starting with a letter (max 64 characters).`
879
+ );
880
+ }
881
+ }
882
+ function normalizePagePath(pathname) {
883
+ const withoutIndex = pathname.replace(/\/index\.html$/, "/");
884
+ const trimmed = withoutIndex.replace(/\/+$/, "");
885
+ return trimmed === "" ? "/" : trimmed;
886
+ }
887
+ function pageScope(pathname) {
888
+ return `page:${normalizePagePath(pathname)}`;
889
+ }
890
+
891
+ // src/content/media.ts
892
+ import { randomUUID } from "node:crypto";
893
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
894
+
895
+ // src/content/image-size.ts
896
+ function imageSize(bytes) {
897
+ try {
898
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
899
+ const size = png(bytes, view) ?? gif(bytes, view) ?? jpeg(bytes, view) ?? webp(bytes, view) ?? avif(bytes, view);
900
+ return size && size.width > 0 && size.height > 0 ? size : void 0;
901
+ } catch {
902
+ return void 0;
903
+ }
904
+ }
905
+ function ascii(bytes, start2, length) {
906
+ return String.fromCharCode(...bytes.subarray(start2, start2 + length));
907
+ }
908
+ function turned(size, sideways) {
909
+ return sideways ? { width: size.height, height: size.width } : size;
910
+ }
911
+ function png(bytes, view) {
912
+ if (bytes[0] !== 137 || ascii(bytes, 1, 3) !== "PNG" || ascii(bytes, 12, 4) !== "IHDR") return void 0;
913
+ const size = { width: view.getUint32(16), height: view.getUint32(20) };
914
+ let offset = 8;
915
+ while (offset + 8 <= bytes.length) {
916
+ const length = view.getUint32(offset);
917
+ const type = ascii(bytes, offset + 4, 4);
918
+ if (type === "IDAT" || type === "IEND") break;
919
+ if (type === "eXIf") return turned(size, exifSideways(bytes, offset + 8, length));
920
+ offset += 12 + length;
921
+ }
922
+ return size;
923
+ }
924
+ function gif(bytes, view) {
925
+ if (ascii(bytes, 0, 4) !== "GIF8") return void 0;
926
+ return { width: view.getUint16(6, true), height: view.getUint16(8, true) };
927
+ }
928
+ var START_OF_FRAME = /* @__PURE__ */ new Set([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207]);
929
+ function jpeg(bytes, view) {
930
+ if (bytes[0] !== 255 || bytes[1] !== 216) return void 0;
931
+ let sideways = false;
932
+ let offset = 2;
933
+ while (offset + 4 <= bytes.length) {
934
+ if (bytes[offset] !== 255) return void 0;
935
+ const marker = bytes[offset + 1] ?? 0;
936
+ if (marker === 255) {
937
+ offset += 1;
938
+ continue;
939
+ }
940
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
941
+ offset += 2;
942
+ continue;
943
+ }
944
+ const length = view.getUint16(offset + 2);
945
+ if (marker === 225 && ascii(bytes, offset + 4, 6) === "Exif\0\0") {
946
+ sideways = exifSideways(bytes, offset + 10, length - 8);
947
+ }
948
+ if (START_OF_FRAME.has(marker)) {
949
+ return turned({ width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) }, sideways);
950
+ }
951
+ offset += 2 + length;
952
+ }
953
+ return void 0;
954
+ }
955
+ function webp(bytes, view) {
956
+ if (ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") return void 0;
957
+ const chunk = ascii(bytes, 12, 4);
958
+ if (chunk === "VP8 ") {
959
+ return { width: view.getUint16(26, true) & 16383, height: view.getUint16(28, true) & 16383 };
960
+ }
961
+ if (chunk === "VP8L") {
962
+ const bits = view.getUint32(21, true);
963
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
964
+ }
965
+ if (chunk !== "VP8X") return void 0;
966
+ const size = {
967
+ width: 1 + (view.getUint16(24, true) | (bytes[26] ?? 0) << 16),
968
+ height: 1 + (view.getUint16(27, true) | (bytes[29] ?? 0) << 16)
969
+ };
970
+ if (((bytes[20] ?? 0) & 8) === 0) return size;
971
+ let offset = 12;
972
+ while (offset + 8 <= bytes.length) {
973
+ const length = view.getUint32(offset + 4, true);
974
+ if (ascii(bytes, offset, 4) === "EXIF") {
975
+ const start2 = ascii(bytes, offset + 8, 6) === "Exif\0\0" ? offset + 14 : offset + 8;
976
+ return turned(size, exifSideways(bytes, start2, length));
977
+ }
978
+ offset += 8 + length + length % 2;
979
+ }
980
+ return size;
981
+ }
982
+ function avif(bytes, view) {
983
+ const brand = ascii(bytes, 8, 4);
984
+ if (ascii(bytes, 4, 4) !== "ftyp" || !["avif", "avis", "heic", "heix", "mif1"].includes(brand)) return void 0;
985
+ let primary;
986
+ const properties = [];
987
+ const associations = /* @__PURE__ */ new Map();
988
+ const walk = (start2, end) => {
989
+ let offset = start2;
990
+ while (offset + 8 <= end) {
991
+ let length = view.getUint32(offset);
992
+ const type = ascii(bytes, offset + 4, 4);
993
+ let header = 8;
994
+ if (length === 1) {
995
+ length = Number(view.getBigUint64(offset + 8));
996
+ header = 16;
997
+ } else if (length === 0) {
998
+ length = end - offset;
999
+ }
1000
+ if (length < header) return;
1001
+ const body = offset + header;
1002
+ if (type === "meta") walk(body + 4, offset + length);
1003
+ else if (type === "iprp") walk(body, offset + length);
1004
+ else if (type === "ipco") collectProperties(body, offset + length);
1005
+ else if (type === "pitm") primary = bytes[body] === 0 ? view.getUint16(body + 4) : view.getUint32(body + 4);
1006
+ else if (type === "ipma") collectAssociations(body);
1007
+ offset += length;
1008
+ }
1009
+ };
1010
+ const collectProperties = (start2, end) => {
1011
+ let offset = start2;
1012
+ while (offset + 8 <= end) {
1013
+ const length = view.getUint32(offset);
1014
+ if (length < 8) return;
1015
+ properties.push({ type: ascii(bytes, offset + 4, 4), body: offset + 8 });
1016
+ offset += length;
1017
+ }
1018
+ };
1019
+ const collectAssociations = (body) => {
1020
+ const version = bytes[body] ?? 0;
1021
+ const wide = ((bytes[body + 3] ?? 0) & 1) === 1;
1022
+ let offset = body + 4;
1023
+ const count = view.getUint32(offset);
1024
+ offset += 4;
1025
+ for (let entry = 0; entry < count; entry++) {
1026
+ const item = version < 1 ? view.getUint16(offset) : view.getUint32(offset);
1027
+ offset += version < 1 ? 2 : 4;
1028
+ const many = bytes[offset] ?? 0;
1029
+ offset += 1;
1030
+ const indexes = [];
1031
+ for (let index = 0; index < many; index++) {
1032
+ indexes.push(wide ? view.getUint16(offset) & 32767 : (bytes[offset] ?? 0) & 127);
1033
+ offset += wide ? 2 : 1;
1034
+ }
1035
+ associations.set(item, indexes);
1036
+ }
1037
+ };
1038
+ walk(0, bytes.length);
1039
+ const own = primary === void 0 ? void 0 : associations.get(primary);
1040
+ const of = (type) => own ? own.map((index) => properties[index - 1]).find((property) => property?.type === type) : properties.find((property) => property.type === type);
1041
+ const extent = of("ispe");
1042
+ if (!extent) return void 0;
1043
+ const rotation = of("irot");
1044
+ const sideways = rotation ? ((bytes[rotation.body] ?? 0) & 3) % 2 === 1 : false;
1045
+ return turned({ width: view.getUint32(extent.body + 4), height: view.getUint32(extent.body + 8) }, sideways);
1046
+ }
1047
+ function exifSideways(bytes, start2, length) {
1048
+ const end = Math.min(bytes.length, start2 + length);
1049
+ if (start2 + 8 > end) return false;
1050
+ const order = ascii(bytes, start2, 2);
1051
+ if (order !== "II" && order !== "MM") return false;
1052
+ const little = order === "II";
1053
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1054
+ const directory = start2 + view.getUint32(start2 + 4, little);
1055
+ if (directory + 2 > end) return false;
1056
+ const entries = view.getUint16(directory, little);
1057
+ for (let index = 0; index < entries; index++) {
1058
+ const entry = directory + 2 + index * 12;
1059
+ if (entry + 12 > end) return false;
1060
+ if (view.getUint16(entry, little) === 274) {
1061
+ const orientation = view.getUint16(entry + 8, little);
1062
+ return orientation >= 5 && orientation <= 8;
1063
+ }
1064
+ }
1065
+ return false;
1066
+ }
1067
+
1068
+ // src/content/image-sizes.ts
1069
+ var known = /* @__PURE__ */ new Map();
1070
+ var loadedAt = Number.NEGATIVE_INFINITY;
1071
+ function rememberImageSize(url, size) {
1072
+ known.set(url, size);
1073
+ }
1074
+
1075
+ // src/content/validation-error.ts
1076
+ var ValidationError = class extends Error {
1077
+ };
1078
+
1079
+ // src/content/media.ts
1080
+ var MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
1081
+ var FORMATS = [
1082
+ { mime: "image/jpeg", extension: "jpg", matches: (bytes) => startsWith(bytes, [255, 216, 255]) },
1083
+ { mime: "image/png", extension: "png", matches: (bytes) => startsWith(bytes, [137, 80, 78, 71]) },
1084
+ { mime: "image/gif", extension: "gif", matches: (bytes) => ascii2(bytes, 0, 4) === "GIF8" },
1085
+ {
1086
+ mime: "image/webp",
1087
+ extension: "webp",
1088
+ matches: (bytes) => ascii2(bytes, 0, 4) === "RIFF" && ascii2(bytes, 8, 12) === "WEBP"
1089
+ },
1090
+ { mime: "image/avif", extension: "avif", matches: (bytes) => ascii2(bytes, 4, 12) === "ftypavif" }
1091
+ ];
1092
+ function startsWith(bytes, signature) {
1093
+ return signature.every((byte, index) => bytes[index] === byte);
1094
+ }
1095
+ function ascii2(bytes, start2, end) {
1096
+ return String.fromCharCode(...bytes.subarray(start2, end));
1097
+ }
1098
+ var DiskFiles = class {
1099
+ #directory;
1100
+ constructor(directory) {
1101
+ this.#directory = directory;
1102
+ }
1103
+ async write(path, bytes) {
1104
+ const file = new URL(path, this.#directory);
1105
+ await mkdir(new URL(".", file), { recursive: true });
1106
+ await writeFile(file, bytes);
1107
+ }
1108
+ };
1109
+ var MediaStore = class {
1110
+ #db;
1111
+ #files;
1112
+ #publicPath;
1113
+ /**
1114
+ * `files` is where files are written (a folder of the server, or a storage); `publicPath` is the address prefix
1115
+ * the database lists them under, the same wherever they are kept.
1116
+ */
1117
+ constructor(db, files, publicPath = "/uploads") {
1118
+ this.#db = db;
1119
+ this.#files = files instanceof URL ? new DiskFiles(files) : files;
1120
+ this.#publicPath = publicPath;
1121
+ }
1122
+ /** Every image, newest first. A library of thousands is read a page at a time with `page`. */
1123
+ async list() {
1124
+ const rows = await this.#db.query("SELECT * FROM brim_media ORDER BY created_at DESC, id DESC");
1125
+ return rows.map(toMediaFile);
1126
+ }
1127
+ /**
1128
+ * One page of the library, newest first: the images whose name holds `search` (any case), in `folder` when it is
1129
+ * given ("" is the gallery), after the one `after` names (the `next` of the page before). `next` is absent on the
1130
+ * last page. The picker reads it this way, so every image of a library of thousands is reachable and searched.
1131
+ */
1132
+ async page(options = {}) {
1133
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 120), 1), 500);
1134
+ const where = [];
1135
+ const args = [];
1136
+ const search = options.search?.trim();
1137
+ if (search) {
1138
+ where.push("name LIKE ? ESCAPE '\\'");
1139
+ args.push(`%${search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`);
1140
+ }
1141
+ if (options.folder !== void 0) {
1142
+ where.push("folder = ?");
1143
+ args.push(options.folder);
1144
+ }
1145
+ const [createdAt, id] = (options.after ?? "").split("|");
1146
+ if (createdAt && id) {
1147
+ where.push("(created_at < ? OR (created_at = ? AND id < ?))");
1148
+ args.push(createdAt, createdAt, id);
1149
+ }
1150
+ const rows = await this.#db.query(
1151
+ `SELECT * FROM brim_media${where.length > 0 ? ` WHERE ${where.join(" AND ")}` : ""}
1152
+ ORDER BY created_at DESC, id DESC LIMIT ?`,
1153
+ [...args, limit + 1]
1154
+ );
1155
+ const files = rows.slice(0, limit).map(toMediaFile);
1156
+ const last = files.at(-1);
1157
+ return rows.length > limit && last ? { files, next: `${last.createdAt}|${last.id}` } : { files };
1158
+ }
1159
+ /**
1160
+ * `folder` is "" for the gallery or `<type>/<item id>`, checked by the caller against existing items;
1161
+ * files of a folder are written to a subfolder of the same path.
1162
+ */
1163
+ async upload(bytes, name, folder = "") {
1164
+ if (folder !== "" && !/^[a-z][a-z0-9_]*\/[\w-]{1,64}$/.test(folder)) {
1165
+ throw new ValidationError("This folder does not exist.");
1166
+ }
1167
+ if (bytes.byteLength > MAX_UPLOAD_BYTES) throw new ValidationError("The image is larger than 10 MB.");
1168
+ const format = FORMATS.find((candidate) => candidate.matches(bytes));
1169
+ if (!format) throw new ValidationError("Only JPEG, PNG, GIF, WebP and AVIF images can be uploaded.");
1170
+ const id = randomUUID();
1171
+ const fileName = `${folder ? `${folder}/` : ""}${id}.${format.extension}`;
1172
+ await this.#files.write(fileName, bytes, format.mime);
1173
+ const size = imageSize(bytes);
1174
+ const file = {
1175
+ id,
1176
+ url: `${this.#publicPath}/${fileName}`,
1177
+ name: name.slice(0, 200) || fileName,
1178
+ mime: format.mime,
1179
+ size: bytes.byteLength,
1180
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1181
+ folder,
1182
+ ...size
1183
+ };
1184
+ await this.#db.query(
1185
+ "INSERT INTO brim_media (id, url, name, mime, size, created_at, folder, width, height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
1186
+ [
1187
+ file.id,
1188
+ file.url,
1189
+ file.name,
1190
+ file.mime,
1191
+ file.size,
1192
+ file.createdAt,
1193
+ file.folder,
1194
+ size?.width ?? 0,
1195
+ size?.height ?? 0
1196
+ ]
1197
+ );
1198
+ if (size) rememberImageSize(file.url, size);
1199
+ return file;
1200
+ }
1201
+ };
1202
+ function toMediaFile(row) {
1203
+ return {
1204
+ folder: String(row.folder ?? ""),
1205
+ id: String(row.id),
1206
+ url: String(row.url),
1207
+ name: String(row.name),
1208
+ mime: String(row.mime),
1209
+ size: Number(row.size),
1210
+ createdAt: String(row.created_at),
1211
+ ...Number(row.width) > 0 && Number(row.height) > 0 && { width: Number(row.width), height: Number(row.height) }
1212
+ };
1213
+ }
1214
+
1215
+ // src/init.ts
1216
+ import { spawnSync } from "node:child_process";
1217
+ import { existsSync as existsSync3 } from "node:fs";
1218
+ import { mkdir as mkdir2, readFile as readFile2, readdir, writeFile as writeFile2 } from "node:fs/promises";
1219
+ import { dirname as dirname2, join as join3, relative as relative3 } from "node:path";
1220
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
1221
+
1222
+ // package.json
1223
+ var package_default = {
1224
+ name: "@brimsites/brimjs",
1225
+ version: "1.0.0",
1226
+ description: "Makes Astro sites editable: primitives with stable node ids, content in SQLite, static output.",
1227
+ license: "FSL-1.1-MIT",
1228
+ author: "Brimsites",
1229
+ homepage: "https://brimjs.com",
1230
+ repository: {
1231
+ type: "git",
1232
+ url: "git+https://github.com/Brimsites-com/brimjs.git",
1233
+ directory: "packages/brim"
1234
+ },
1235
+ publishConfig: {
1236
+ access: "public",
1237
+ registry: "https://registry.npmjs.org/"
1238
+ },
1239
+ type: "module",
1240
+ engines: {
1241
+ node: ">=22.23.4"
1242
+ },
1243
+ exports: {
1244
+ ".": "./src/index.ts",
1245
+ "./components": "./src/components/index.ts",
1246
+ "./middleware": "./src/runtime/middleware.ts",
1247
+ "./content": "./src/runtime/content.ts",
1248
+ "./server": "./src/runtime/server.ts",
1249
+ "./template-page": "./src/runtime/TemplatePage.astro",
1250
+ "./template-page-static": "./src/runtime/TemplatePageStatic.astro",
1251
+ "./rss-static": "./src/runtime/rss-static.ts",
1252
+ "./sitemap": "./src/runtime/sitemap.ts",
1253
+ "./robots": "./src/runtime/robots.ts",
1254
+ "./rss": "./src/runtime/rss.ts",
1255
+ "./admin-route": "./src/runtime/admin-route.ts",
1256
+ "./forms-route": "./src/runtime/forms-route.ts",
1257
+ "./uploads-route": "./src/runtime/uploads-route.ts"
1258
+ },
1259
+ files: [
1260
+ "src",
1261
+ "bin",
1262
+ "dist",
1263
+ "editor-dist",
1264
+ "skills"
1265
+ ],
1266
+ scripts: {
1267
+ "build:editor": "node scripts/build-editor.mjs",
1268
+ "build:cli": "node scripts/build-cli.mjs",
1269
+ prepack: "node scripts/build-editor.mjs && node scripts/build-cli.mjs",
1270
+ test: "vitest run --no-file-parallelism",
1271
+ "check-types": "tsc --noEmit && tsc --noEmit -p src/editor/client"
1272
+ },
1273
+ peerDependencies: {
1274
+ astro: "^7.0.0"
1275
+ },
1276
+ dependencies: {
1277
+ "@astrojs/node": "^11.1.13",
1278
+ "@libsql/client": "^0.18.0",
1279
+ "hls.js": "^1.7.4",
1280
+ nodemailer: "^10.3.1"
1281
+ },
1282
+ devDependencies: {
1283
+ "@types/node": "^24.0.0",
1284
+ "@types/nodemailer": "^8.0.2",
1285
+ "@types/react": "^19.3.0",
1286
+ "@types/react-dom": "^19.3.0",
1287
+ astro: "^7.4.11",
1288
+ esbuild: "^0.25.12",
1289
+ react: "^19.3.1",
1290
+ "react-dom": "^19.3.1",
1291
+ typescript: "^7.0.2",
1292
+ vitest: "^5.1.0"
1293
+ },
1294
+ bin: {
1295
+ brim: "bin/brim.js"
1296
+ }
1297
+ };
1298
+
1299
+ // src/version.ts
1300
+ var VERSION = package_default.version;
1301
+
1302
+ // src/init.ts
1303
+ var SKILL = new URL("../skills/brim-convert/SKILL.md", import.meta.url);
1304
+ var CONFIG_FILES = ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts"];
1305
+ var IGNORED = [
1306
+ "# Brim.js: the local database (content, users, form responses) and images uploaded in the editor.",
1307
+ ".brim",
1308
+ "public/uploads"
1309
+ ];
1310
+ var PACKAGE = "@brimsites/brimjs";
1311
+ var AGENTS_MARK = "<!-- brimjs -->";
1312
+ var AGENTS_NOTE = `${AGENTS_MARK}
1313
+ ## Brim.js
1314
+
1315
+ This Astro site is editable with Brim.js: texts, images, links and navigation wrapped in Brim's components carry a
1316
+ stable \`nodeId\`, and the owner's edits (stored in SQLite) replace what the code says. Never rename or reuse a
1317
+ \`nodeId\`. To make more of the site editable, follow \`.claude/skills/brim-convert/SKILL.md\`; the components and
1318
+ their props are documented in \`node_modules/@brimsites/brimjs/README.md\`. While the dev server runs, the site's MCP is at
1319
+ \`/admin/mcp\` (token: \`npx brim token add <email>\`): use it to read and change content instead of the database.
1320
+ To show the person the editor, run \`npx brim open\` with the dev server running (or open \`/admin/edit\`).
1321
+ Never write a password or a token into a file of the project; to let someone sign in, use \`npx brim user link <email>\`.
1322
+ Facts about the whole site (email, phone, WhatsApp, social profiles, address) are site settings, declared in
1323
+ \`src/site-settings.ts\` and read with \`getSiteSettings()\` or \`<Setting name="\u2026" />\`: never constants in the code.
1324
+ The body of an item with a page (article, project, service) is a \`blocks\` field drawn with \`<Blocks>\`, so the
1325
+ owner adds images, galleries and buttons between paragraphs; \`richtext\` is for text that stays text (\`// text only\`).
1326
+ The emails the site sends (a form message's) are written in \`src/emails.ts\` with \`defineEmails\` and \`html\` from
1327
+ \`brimjs\`; see one at \`/admin/api/emails/form\`.
1328
+ Pictures: the site's own (what the design starts with: hero, sections, a gallery it ships with, logo, icons) are
1329
+ files in \`public/\`, at most 2560 px wide; Brim sends smaller copies of them and the owner replaces them in the editor.
1330
+ Pictures of items (products, projects, articles) and anything filled in bulk are uploads (MCP \`brim_upload_image\`
1331
+ or \`npx brim media add <files\u2026>\`) saved in the item's image field; never write an \`/uploads/\u2026\` address in the code.
1332
+ What the site is filled from (photos, catalogues, data for an import) stays out of git: keep it in \`import/\` or
1333
+ outside the project; the live site gets the uploads with the content (\`brimsites restore\`), never with a deploy.
1334
+ To deploy, host or move the site (Brimsites first, or a server of its own), follow
1335
+ \`node_modules/@brimsites/brimjs/skills/brim-hosting/SKILL.md\`; a deploy never carries the local \`.brim/data.db\`.
1336
+ Working on the site once it is online, ask once whether to download its live content first (\`brimsites export\`,
1337
+ local \`.brim\` moved outside the project first), so you work on the site as it is now.
1338
+ After the first deploy, offer once to save the live site's MCP (\`brimsites tokens create <site>\`, then
1339
+ \`claude mcp add\`), so its content can be changed without the editor; the token never goes into a file.
1340
+ `;
1341
+ async function init(directory, options = {}) {
1342
+ const result = { done: [], manual: [] };
1343
+ const packagePath = join3(directory, "package.json");
1344
+ if (!existsSync3(packagePath)) {
1345
+ throw new Error("There is no package.json here. Run this in the folder of an Astro project.");
1346
+ }
1347
+ const packageSource = await readFile2(packagePath, "utf8");
1348
+ const manifest = JSON.parse(packageSource);
1349
+ if (!manifest.dependencies?.astro && !manifest.devDependencies?.astro) {
1350
+ throw new Error(
1351
+ "This project does not depend on astro. Brim.js makes Astro sites editable; start a new one with `npm create brim`."
1352
+ );
1353
+ }
1354
+ let changed = false;
1355
+ if (!manifest.dependencies?.[PACKAGE] && !manifest.devDependencies?.[PACKAGE]) {
1356
+ manifest.dependencies = { ...manifest.dependencies, [PACKAGE]: options.brim ?? `^${VERSION}` };
1357
+ changed = true;
1358
+ result.done.push(`Added ${PACKAGE} ${manifest.dependencies[PACKAGE]} to package.json.`);
1359
+ }
1360
+ for (const [name, command] of Object.entries({ start: "brim start", brim: "brim" })) {
1361
+ if (manifest.scripts?.[name] === void 0) {
1362
+ manifest.scripts = { ...manifest.scripts, [name]: command };
1363
+ changed = true;
1364
+ result.done.push(`Added the "${name}" script (${command}).`);
1365
+ }
1366
+ }
1367
+ if (changed) {
1368
+ const indent = /^(\s+)"/m.exec(packageSource)?.[1] ?? " ";
1369
+ await writeFile2(packagePath, `${JSON.stringify(manifest, null, indent)}
1370
+ `);
1371
+ }
1372
+ const lang = options.lang ?? await layoutLanguage(directory) ?? "en";
1373
+ if (!LANGUAGE.test(lang)) throw new Error(`"${lang}" is not a language code, e.g. ro, en or pt-BR.`);
1374
+ const configName = CONFIG_FILES.find((name) => existsSync3(join3(directory, name)));
1375
+ if (!configName) {
1376
+ await writeFile2(
1377
+ join3(directory, "astro.config.mjs"),
1378
+ `import { defineConfig } from "astro/config";
1379
+ import brim from "@brimsites/brimjs";
1380
+
1381
+ export default defineConfig({
1382
+ ${languageLine(lang)}
1383
+ integrations: [brim()],
1384
+ });
1385
+ `
1386
+ );
1387
+ result.done.push(`Created astro.config.mjs with the brim() integration and the site's language (${lang}).`);
1388
+ } else {
1389
+ const source = await readFile2(join3(directory, configName), "utf8");
1390
+ const integrated = addIntegration(source);
1391
+ const patched = integrated === void 0 ? void 0 : addLanguage(integrated, lang);
1392
+ if (patched === void 0) {
1393
+ result.manual.push(
1394
+ `Add Brim to ${configName} yourself: \`import brim from "@brimsites/brimjs";\` and \`brim()\` in \`integrations\`.`
1395
+ );
1396
+ } else if (patched !== source) {
1397
+ await writeFile2(join3(directory, configName), patched);
1398
+ result.done.push(`Added the brim() integration to ${configName}.`);
1399
+ if (patched !== integrated) result.done.push(`Declared the site's language (${lang}) in ${configName}.`);
1400
+ }
1401
+ if (/\badapter\s*:/.test(source)) {
1402
+ result.manual.push(
1403
+ `${configName} sets an adapter. Brim keeps it, but its editor, forms and MCP need a Node server: see "Deploy" in the brimjs README.`
1404
+ );
1405
+ }
1406
+ }
1407
+ const ignorePath = join3(directory, ".gitignore");
1408
+ const ignore = existsSync3(ignorePath) ? await readFile2(ignorePath, "utf8") : "";
1409
+ const lines = ignore.split(/\r?\n/).map((line) => line.trim().replace(/^\/|\/$/g, ""));
1410
+ const missing = IGNORED.filter((line) => !line.startsWith("#") && !lines.includes(line));
1411
+ if (missing.length > 0) {
1412
+ const block = [IGNORED[0], ...missing].join("\n");
1413
+ await writeFile2(ignorePath, `${ignore}${ignore === "" || ignore.endsWith("\n") ? "" : "\n"}${block}
1414
+ `);
1415
+ result.done.push(`Added ${missing.join(" and ")} to .gitignore.`);
1416
+ }
1417
+ const skillPath = join3(directory, ".claude", "skills", "brim-convert", "SKILL.md");
1418
+ const skill = await readFile2(fileURLToPath2(SKILL), "utf8");
1419
+ if (!existsSync3(skillPath) || await readFile2(skillPath, "utf8") !== skill) {
1420
+ await mkdir2(dirname2(skillPath), { recursive: true });
1421
+ await writeFile2(skillPath, skill);
1422
+ result.done.push(`Wrote the conversion guide for AI agents to ${relative3(directory, skillPath)}.`);
1423
+ }
1424
+ const agentsPath = join3(directory, "AGENTS.md");
1425
+ const agents = existsSync3(agentsPath) ? await readFile2(agentsPath, "utf8") : "";
1426
+ if (!agents.includes(AGENTS_MARK)) {
1427
+ await writeFile2(
1428
+ agentsPath,
1429
+ `${agents}${agents === "" || agents.endsWith("\n\n") ? "" : agents.endsWith("\n") ? "\n" : "\n\n"}${AGENTS_NOTE}`
1430
+ );
1431
+ result.done.push(`${agents === "" ? "Created" : "Added a Brim.js section to"} AGENTS.md.`);
1432
+ }
1433
+ if (!existsSync3(join3(directory, "CLAUDE.md"))) {
1434
+ await writeFile2(join3(directory, "CLAUDE.md"), "@AGENTS.md\n");
1435
+ result.done.push("Created CLAUDE.md, pointing at AGENTS.md.");
1436
+ }
1437
+ if (options.git !== false && !insideGit(directory)) {
1438
+ const made = spawnSync("git", ["init", "--quiet"], { cwd: directory, stdio: "ignore" });
1439
+ if (made.status === 0) {
1440
+ result.done.push("Put the project in git (git init). Commit once you have checked what it holds.");
1441
+ } else {
1442
+ result.manual.push("Put the project in git (git init), so every change can be seen and taken back.");
1443
+ }
1444
+ }
1445
+ return result;
1446
+ }
1447
+ function addIntegration(source) {
1448
+ if (/from\s+["']@brimsites\/brimjs["']/.test(source)) return source;
1449
+ const list = /\bintegrations\s*:\s*\[/.exec(source);
1450
+ const config = /\bdefineConfig\s*\(\s*\{|export\s+default\s*\{/.exec(source);
1451
+ let patched;
1452
+ if (list) {
1453
+ const at = list.index + list[0].length;
1454
+ const rest = source.slice(at);
1455
+ const space = /^\s*/.exec(rest)?.[0] ?? "";
1456
+ const added = rest.trimStart().startsWith("]") ? "brim()" : space.includes("\n") ? `${space}brim(),` : "brim(), ";
1457
+ patched = source.slice(0, at) + added + rest;
1458
+ } else if (config) {
1459
+ const at = config.index + config[0].length;
1460
+ patched = `${source.slice(0, at)}
1461
+ integrations: [brim()],${source.slice(at)}`;
1462
+ } else {
1463
+ return void 0;
1464
+ }
1465
+ return `import brim from "@brimsites/brimjs";
1466
+ ${patched}`;
1467
+ }
1468
+ var LANGUAGE = /^[a-z]{2,3}(-[A-Za-z]{2,4})?$/;
1469
+ function languageLine(lang) {
1470
+ return `i18n: { defaultLocale: ${JSON.stringify(lang)}, locales: [${JSON.stringify(lang)}] },`;
1471
+ }
1472
+ function addLanguage(source, lang) {
1473
+ if (/\bi18n\s*:/.test(source)) return source;
1474
+ const config = /\bdefineConfig\s*\(\s*\{|export\s+default\s*\{/.exec(source);
1475
+ if (!config) return source;
1476
+ const at = config.index + config[0].length;
1477
+ return `${source.slice(0, at)}
1478
+ ${languageLine(lang)}${source.slice(at)}`;
1479
+ }
1480
+ async function layoutLanguage(directory) {
1481
+ const folder = join3(directory, "src", "layouts");
1482
+ if (!existsSync3(folder)) return void 0;
1483
+ for (const name of await readdir(folder)) {
1484
+ if (!name.endsWith(".astro")) continue;
1485
+ const match = /<html[^>]*\blang=["']([A-Za-z-]+)["']/.exec(await readFile2(join3(folder, name), "utf8"));
1486
+ if (match?.[1] && LANGUAGE.test(match[1])) return match[1];
1487
+ }
1488
+ return void 0;
1489
+ }
1490
+ function initReport(result, runner) {
1491
+ const exec = runner === "npm" ? "npx" : runner;
1492
+ return [
1493
+ ...result.done.length > 0 ? result.done : ["Brim.js is already set up here; nothing to change."],
1494
+ ...result.manual.length > 0 ? ["", "Left to you:", ...result.manual.map((line) => ` - ${line}`)] : [],
1495
+ "",
1496
+ "Next:",
1497
+ ` ${runner} install`,
1498
+ ` ${exec} brim user add you@example.com # the account that edits the site`,
1499
+ ` ${runner} run dev # the editor is at /admin/edit`,
1500
+ "",
1501
+ "Nothing on the site is editable yet. Ask your AI coding agent to make it so:",
1502
+ ' "Convert this site to Brim.js, following the brim-convert skill."',
1503
+ "or wrap elements yourself, one at a time:",
1504
+ ' <Text nodeId="hero-title" as="h1">Your heading</Text>',
1505
+ "",
1506
+ "When it is ready, deploy it in one click on Brimsites, the managed hosting for Brim.js:",
1507
+ " https://dashboard.brimsites.com"
1508
+ ].join("\n");
1509
+ }
1510
+
1511
+ // src/config.ts
1512
+ import { mkdirSync } from "node:fs";
1513
+ import { join as join4 } from "node:path";
1514
+
1515
+ // src/db/url.ts
1516
+ function splitDatabaseUrl(address) {
1517
+ const at = address.indexOf("?");
1518
+ if (at < 0 || address.startsWith("file:") || address.startsWith(":memory:")) {
1519
+ return { url: address, authToken: void 0 };
1520
+ }
1521
+ let authToken;
1522
+ const kept = address.slice(at + 1).split("&").filter((pair) => {
1523
+ if (!/^authToken=/.test(pair)) return true;
1524
+ authToken = decodeURIComponent(pair.slice("authToken=".length).replace(/\+/g, " "));
1525
+ return false;
1526
+ });
1527
+ return { url: address.slice(0, at) + (kept.length > 0 ? `?${kept.join("&")}` : ""), authToken };
1528
+ }
1529
+ function assertSecureDatabaseUrl(address) {
1530
+ const plain = /^(?:http|ws):\/\//i.test(address) || /^libsql:\/\//i.test(address) && /[?&]tls=0(?:&|$)/.test(address);
1531
+ if (!plain) return;
1532
+ let host;
1533
+ try {
1534
+ host = new URL(address.replace(/^[a-z]+:/i, "http:")).hostname;
1535
+ } catch {
1536
+ throw new Error("The database address is not a valid URL.");
1537
+ }
1538
+ if (isPrivateHost(host)) return;
1539
+ throw new Error(
1540
+ `The database at ${host} would be reached unencrypted, its token included. Use its https:// or libsql:// address; http:// is only for a database on this computer or in a private network.`
1541
+ );
1542
+ }
1543
+ function isPrivateHost(host) {
1544
+ if (host.startsWith("[")) return host === "[::1]" || /^\[f[cd][0-9a-f]{2}:/i.test(host);
1545
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) {
1546
+ return /^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/.test(host);
1547
+ }
1548
+ return !host.includes(".") || /\.(localhost|local|internal)$/i.test(host);
1549
+ }
1550
+
1551
+ // src/config.ts
1552
+ function resolveDatabase(options, projectRoot) {
1553
+ const { url, authToken } = splitDatabaseUrl(
1554
+ options.database ?? process.env.BRIM_DATABASE_URL ?? localDatabaseUrl(projectRoot)
1555
+ );
1556
+ return {
1557
+ databaseUrl: url,
1558
+ // betterleaks:allow
1559
+ authToken: options.authToken ?? authToken ?? process.env.BRIM_DATABASE_TOKEN
1560
+ // betterleaks:allow
1561
+ };
1562
+ }
1563
+ function localDatabaseUrl(projectRoot) {
1564
+ const directory = join4(projectRoot, ".brim");
1565
+ mkdirSync(directory, { recursive: true });
1566
+ return `file:${join4(directory, "data.db")}`;
1567
+ }
1568
+
1569
+ // src/auth/accounts.ts
1570
+ import { createHash as createHash2, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
1571
+
1572
+ // src/auth/password.ts
1573
+ import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
1574
+ var KEY_LENGTH = 64;
1575
+ var MIN_PASSWORD_LENGTH = 10;
1576
+ function derive(password, salt) {
1577
+ return new Promise((resolve3, reject) => {
1578
+ scrypt(password.normalize("NFKC"), salt, KEY_LENGTH, (error, key) => error ? reject(error) : resolve3(key));
1579
+ });
1580
+ }
1581
+ async function hashPassword(password) {
1582
+ const salt = randomBytes(16);
1583
+ const key = await derive(password, salt);
1584
+ return `scrypt$${salt.toString("base64url")}$${key.toString("base64url")}`;
1585
+ }
1586
+ async function verifyPassword(password, stored) {
1587
+ const [scheme, salt, key] = stored.split("$");
1588
+ if (scheme !== "scrypt" || !salt || !key) return false;
1589
+ const expected = Buffer.from(key, "base64url");
1590
+ const actual = await derive(password, Buffer.from(salt, "base64url"));
1591
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
1592
+ }
1593
+ function generatePassword() {
1594
+ const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
1595
+ const characters = [...randomBytes(20)].map((byte) => alphabet[byte % alphabet.length]);
1596
+ return [0, 5, 10, 15].map((start2) => characters.slice(start2, start2 + 5).join("")).join("-");
1597
+ }
1598
+
1599
+ // src/auth/accounts.ts
1600
+ var ROLE_NAMES = ["owner", "editor"];
1601
+ var SESSION_SECONDS = 60 * 60 * 24 * 14;
1602
+ var SIGN_IN_LINK_SECONDS = 120;
1603
+ var RESET_LINK_SECONDS = 60 * 60;
1604
+ var TOKEN_PREFIX = "brim_";
1605
+ var TOKEN_NAME = /^[\w .-]{1,64}$/;
1606
+ var DECOY_HASH = await hashPassword(randomBytes2(16).toString("hex"));
1607
+ var Accounts = class {
1608
+ #db;
1609
+ constructor(db) {
1610
+ this.#db = db;
1611
+ }
1612
+ async createUser(email, password, role) {
1613
+ const normalized = normalizeEmail(email);
1614
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized)) throw new Error("Enter a valid email address.");
1615
+ if (password.length < MIN_PASSWORD_LENGTH) {
1616
+ throw new Error(`The password needs at least ${MIN_PASSWORD_LENGTH} characters.`);
1617
+ }
1618
+ assertRole(role);
1619
+ const existing = await this.#db.query("SELECT id FROM brim_users WHERE email = ?", [normalized]);
1620
+ if (existing.length > 0) throw new Error(`A user with the email ${normalized} already exists.`);
1621
+ const user = { id: randomUUID2(), email: normalized, role };
1622
+ await this.#db.query("INSERT INTO brim_users (id, email, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?)", [
1623
+ user.id,
1624
+ user.email,
1625
+ await hashPassword(password),
1626
+ role,
1627
+ (/* @__PURE__ */ new Date()).toISOString()
1628
+ ]);
1629
+ return user;
1630
+ }
1631
+ async authenticate(email, password) {
1632
+ const rows = await this.#db.query("SELECT id, email, role, password_hash FROM brim_users WHERE email = ?", [
1633
+ normalizeEmail(email)
1634
+ ]);
1635
+ const row = rows[0];
1636
+ const valid = await verifyPassword(password, row ? String(row.password_hash) : DECOY_HASH);
1637
+ return row && valid ? { id: String(row.id), email: String(row.email), role: row.role } : void 0;
1638
+ }
1639
+ /** Returns the token to hand to the browser. Only its hash is stored. */
1640
+ async startSession(userId) {
1641
+ const token = randomBytes2(32).toString("base64url");
1642
+ await this.#db.batch([
1643
+ { sql: "DELETE FROM brim_sessions WHERE expires_at < ?", args: [nowSeconds()] },
1644
+ {
1645
+ sql: "INSERT INTO brim_sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)",
1646
+ args: [hashToken(token), userId, nowSeconds() + SESSION_SECONDS]
1647
+ }
1648
+ ]);
1649
+ return { token, maxAgeSeconds: SESSION_SECONDS };
1650
+ }
1651
+ async sessionUser(token) {
1652
+ const rows = await this.#db.query(
1653
+ `SELECT u.id, u.email, u.role FROM brim_sessions s JOIN brim_users u ON u.id = s.user_id
1654
+ WHERE s.token_hash = ? AND s.expires_at >= ?`,
1655
+ [hashToken(token), nowSeconds()]
1656
+ );
1657
+ const row = rows[0];
1658
+ return row ? { id: String(row.id), email: String(row.email), role: row.role } : void 0;
1659
+ }
1660
+ /**
1661
+ * A token that signs the user in once, within two minutes, with nothing to type: whoever runs the site hands
1662
+ * it over in a link (`brim user link`), the way a host's dashboard opens the editor for someone it already knows.
1663
+ * It is kept beside the sessions under a hash no session cookie can have, so it is never a session itself.
1664
+ */
1665
+ async createSignInToken(email) {
1666
+ const user = await this.#userByEmail(email);
1667
+ const token = randomBytes2(32).toString("base64url");
1668
+ await this.#db.batch([
1669
+ { sql: "DELETE FROM brim_sessions WHERE expires_at < ?", args: [nowSeconds()] },
1670
+ {
1671
+ sql: "INSERT INTO brim_sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)",
1672
+ args: [hashSignInToken(token), user.id, nowSeconds() + SIGN_IN_LINK_SECONDS]
1673
+ }
1674
+ ]);
1675
+ return { token, maxAgeSeconds: SIGN_IN_LINK_SECONDS };
1676
+ }
1677
+ /** The user a sign-in token was made for. The token stops working here, used or expired. */
1678
+ async redeemSignInToken(token) {
1679
+ const rows = await this.#db.query(
1680
+ "DELETE FROM brim_sessions WHERE token_hash = ? AND expires_at >= ? RETURNING user_id",
1681
+ [hashSignInToken(token), nowSeconds()]
1682
+ );
1683
+ if (!rows[0]) return void 0;
1684
+ const users = await this.#db.query("SELECT id, email, role FROM brim_users WHERE id = ?", [
1685
+ String(rows[0].user_id)
1686
+ ]);
1687
+ const row = users[0];
1688
+ return row ? { id: String(row.id), email: String(row.email), role: row.role } : void 0;
1689
+ }
1690
+ /**
1691
+ * A one-time token for setting a new password, emailed when someone says they forgot theirs; `undefined` when no
1692
+ * user has that email (the caller answers the same either way). Kept beside the sessions under a hash no session
1693
+ * or sign-in link can have, and ended by the new password, which ends every session of the user.
1694
+ */
1695
+ async createResetToken(email, maxAgeSeconds = RESET_LINK_SECONDS) {
1696
+ const rows = await this.#db.query("SELECT id FROM brim_users WHERE email = ?", [normalizeEmail(email)]);
1697
+ const userId = rows[0] ? String(rows[0].id) : void 0;
1698
+ if (!userId) return void 0;
1699
+ const token = randomBytes2(32).toString("base64url");
1700
+ await this.#db.batch([
1701
+ { sql: "DELETE FROM brim_sessions WHERE expires_at < ?", args: [nowSeconds()] },
1702
+ {
1703
+ sql: "INSERT INTO brim_sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)",
1704
+ args: [hashResetToken(token), userId, nowSeconds() + maxAgeSeconds]
1705
+ }
1706
+ ]);
1707
+ return { token, maxAgeSeconds };
1708
+ }
1709
+ /**
1710
+ * Sets a new password with a reset token, which works once: every session, sign-in link, reset link and access
1711
+ * token of the user ends (see `setPassword`). Answers the user, or `undefined` for a token wrong, used or too old.
1712
+ */
1713
+ async resetPassword(token, password) {
1714
+ if (password.length < MIN_PASSWORD_LENGTH) {
1715
+ throw new Error(`The password needs at least ${MIN_PASSWORD_LENGTH} characters.`);
1716
+ }
1717
+ const rows = await this.#db.query(
1718
+ "DELETE FROM brim_sessions WHERE token_hash = ? AND expires_at >= ? RETURNING user_id",
1719
+ [hashResetToken(token), nowSeconds()]
1720
+ );
1721
+ if (!rows[0]) return void 0;
1722
+ const users = await this.#db.query("SELECT id, email, role FROM brim_users WHERE id = ?", [String(rows[0].user_id)]);
1723
+ const row = users[0];
1724
+ if (!row) return void 0;
1725
+ await this.setPassword(String(row.email), password);
1726
+ return { id: String(row.id), email: String(row.email), role: row.role };
1727
+ }
1728
+ async endSession(token) {
1729
+ await this.#db.query("DELETE FROM brim_sessions WHERE token_hash = ?", [hashToken(token)]);
1730
+ }
1731
+ /**
1732
+ * A long-lived token that acts as the user, for tools such as an AI client using the site's MCP.
1733
+ * Returns the token to show once; only its hash is stored.
1734
+ */
1735
+ async createToken(email, name) {
1736
+ if (!TOKEN_NAME.test(name)) throw new Error("A token name is 1 to 64 letters, digits, spaces, dots or dashes.");
1737
+ const user = await this.#userByEmail(email);
1738
+ const taken = await this.#db.query("SELECT 1 FROM brim_tokens WHERE user_id = ? AND name = ?", [user.id, name]);
1739
+ if (taken.length > 0) throw new Error(`${user.email} already has a token named "${name}".`);
1740
+ const token = TOKEN_PREFIX + randomBytes2(32).toString("base64url");
1741
+ await this.#db.query("INSERT INTO brim_tokens (token_hash, user_id, name, created_at) VALUES (?, ?, ?, ?)", [
1742
+ hashToken(token),
1743
+ user.id,
1744
+ name,
1745
+ (/* @__PURE__ */ new Date()).toISOString()
1746
+ ]);
1747
+ return token;
1748
+ }
1749
+ async tokenUser(token) {
1750
+ if (!token.startsWith(TOKEN_PREFIX)) return void 0;
1751
+ const hash2 = hashToken(token);
1752
+ const rows = await this.#db.query(
1753
+ "SELECT u.id, u.email, u.role FROM brim_tokens t JOIN brim_users u ON u.id = t.user_id WHERE t.token_hash = ?",
1754
+ [hash2]
1755
+ );
1756
+ const row = rows[0];
1757
+ if (!row) return void 0;
1758
+ await this.#db.query("UPDATE brim_tokens SET last_used_at = ? WHERE token_hash = ?", [
1759
+ (/* @__PURE__ */ new Date()).toISOString(),
1760
+ hash2
1761
+ ]);
1762
+ return { id: String(row.id), email: String(row.email), role: row.role };
1763
+ }
1764
+ async listTokens(email) {
1765
+ const user = await this.#userByEmail(email);
1766
+ const rows = await this.#db.query(
1767
+ "SELECT name, created_at, last_used_at FROM brim_tokens WHERE user_id = ? ORDER BY created_at",
1768
+ [user.id]
1769
+ );
1770
+ return rows.map((row) => ({
1771
+ name: String(row.name),
1772
+ createdAt: String(row.created_at),
1773
+ lastUsedAt: row.last_used_at === null ? null : String(row.last_used_at)
1774
+ }));
1775
+ }
1776
+ /** Returns whether a token by that name existed. */
1777
+ async revokeToken(email, name) {
1778
+ const user = await this.#userByEmail(email);
1779
+ const before = await this.#db.query("SELECT 1 FROM brim_tokens WHERE user_id = ? AND name = ?", [user.id, name]);
1780
+ await this.#db.query("DELETE FROM brim_tokens WHERE user_id = ? AND name = ?", [user.id, name]);
1781
+ return before.length > 0;
1782
+ }
1783
+ /** Everyone who can sign in, owners first, with when they joined and how many tokens they hold. */
1784
+ async listUsers() {
1785
+ const rows = await this.#db.query(
1786
+ `SELECT u.id, u.email, u.role, u.created_at, COUNT(t.token_hash) AS tokens
1787
+ FROM brim_users u LEFT JOIN brim_tokens t ON t.user_id = u.id
1788
+ GROUP BY u.id ORDER BY u.role = 'owner' DESC, u.email`
1789
+ );
1790
+ return rows.map((row) => ({
1791
+ id: String(row.id),
1792
+ email: String(row.email),
1793
+ role: row.role,
1794
+ createdAt: String(row.created_at),
1795
+ tokens: Number(row.tokens)
1796
+ }));
1797
+ }
1798
+ async setRole(email, role) {
1799
+ assertRole(role);
1800
+ const user = await this.#userByEmail(email);
1801
+ if (user.role === "owner" && role !== "owner") await this.#assertAnotherOwner(user);
1802
+ await this.#db.query("UPDATE brim_users SET role = ? WHERE id = ?", [role, user.id]);
1803
+ return { ...user, role };
1804
+ }
1805
+ /** Signs the user out everywhere: sessions and access tokens go with them. */
1806
+ async removeUser(email) {
1807
+ const user = await this.#userByEmail(email);
1808
+ if (user.role === "owner") await this.#assertAnotherOwner(user);
1809
+ await this.#db.batch([
1810
+ { sql: "DELETE FROM brim_sessions WHERE user_id = ?", args: [user.id] },
1811
+ { sql: "DELETE FROM brim_tokens WHERE user_id = ?", args: [user.id] },
1812
+ { sql: "DELETE FROM brim_users WHERE id = ?", args: [user.id] }
1813
+ ]);
1814
+ }
1815
+ /**
1816
+ * A new password signs the user out everywhere: open sessions and access tokens both end. A password is changed
1817
+ * when someone else may know it, and they may have made themselves a token with it.
1818
+ */
1819
+ async setPassword(email, password) {
1820
+ if (password.length < MIN_PASSWORD_LENGTH) {
1821
+ throw new Error(`The password needs at least ${MIN_PASSWORD_LENGTH} characters.`);
1822
+ }
1823
+ const user = await this.#userByEmail(email);
1824
+ await this.#db.batch([
1825
+ { sql: "UPDATE brim_users SET password_hash = ? WHERE id = ?", args: [await hashPassword(password), user.id] },
1826
+ // betterleaks:allow
1827
+ { sql: "DELETE FROM brim_sessions WHERE user_id = ?", args: [user.id] },
1828
+ { sql: "DELETE FROM brim_tokens WHERE user_id = ?", args: [user.id] }
1829
+ ]);
1830
+ }
1831
+ /**
1832
+ * "Reset access", for someone who lost their password or may have shared it: a new password (handed back once),
1833
+ * every session and link of theirs ends, and their access tokens too when asked (a tool they connected stops).
1834
+ */
1835
+ async resetAccess(email, options = {}) {
1836
+ const user = await this.#userByEmail(email);
1837
+ const password = generatePassword();
1838
+ const tokens = options.revokeTokens ? Number((await this.#db.query("SELECT COUNT(*) AS count FROM brim_tokens WHERE user_id = ?", [user.id]))[0]?.count ?? 0) : 0;
1839
+ await this.#db.batch([
1840
+ { sql: "UPDATE brim_users SET password_hash = ? WHERE id = ?", args: [await hashPassword(password), user.id] },
1841
+ // betterleaks:allow
1842
+ { sql: "DELETE FROM brim_sessions WHERE user_id = ?", args: [user.id] },
1843
+ ...options.revokeTokens ? [{ sql: "DELETE FROM brim_tokens WHERE user_id = ?", args: [user.id] }] : []
1844
+ ]);
1845
+ return { password, revokedTokens: tokens };
1846
+ }
1847
+ /** A site always keeps an owner, so someone can still manage its users. */
1848
+ async #assertAnotherOwner(user) {
1849
+ const owners = await this.#db.query("SELECT COUNT(*) AS count FROM brim_users WHERE role = 'owner' AND id != ?", [
1850
+ user.id
1851
+ ]);
1852
+ if (Number(owners[0]?.count ?? 0) === 0)
1853
+ throw new Error(`${user.email} is the only owner; make someone else owner first.`);
1854
+ }
1855
+ async #userByEmail(email) {
1856
+ const rows = await this.#db.query("SELECT id, email, role FROM brim_users WHERE email = ?", [
1857
+ normalizeEmail(email)
1858
+ ]);
1859
+ const row = rows[0];
1860
+ if (!row) throw new Error(`There is no user with the email ${normalizeEmail(email)}.`);
1861
+ return { id: String(row.id), email: String(row.email), role: row.role };
1862
+ }
1863
+ };
1864
+ function assertRole(role) {
1865
+ if (!ROLE_NAMES.includes(role)) throw new Error('The role is "owner" or "editor".');
1866
+ }
1867
+ function normalizeEmail(email) {
1868
+ return email.trim().toLowerCase();
1869
+ }
1870
+ function hashToken(token) {
1871
+ return createHash2("sha256").update(token).digest("base64url");
1872
+ }
1873
+ function hashSignInToken(token) {
1874
+ return hashToken(`sign-in:${token}`);
1875
+ }
1876
+ function hashResetToken(token) {
1877
+ return hashToken(`reset:${token}`);
1878
+ }
1879
+ function nowSeconds() {
1880
+ return Math.floor(Date.now() / 1e3);
1881
+ }
1882
+
1883
+ // src/content/history.ts
1884
+ import { randomUUID as randomUUID3 } from "node:crypto";
1885
+ var SAME_EDIT_SECONDS = 10 * 60;
1886
+ var KEEP_DAYS = 90;
1887
+ var KEEP_ENTRIES = 5e3;
1888
+ var HistoryStore = class {
1889
+ #db;
1890
+ constructor(db) {
1891
+ this.#db = db;
1892
+ }
1893
+ /** Call before the change is made, with the content as it is now. */
1894
+ async record(entry) {
1895
+ const now2 = /* @__PURE__ */ new Date();
1896
+ if (!entry.always && entry.action === "changed") {
1897
+ const rows = await this.#db.query(
1898
+ "SELECT user_email, action, created_at FROM brim_history WHERE target = ? AND key = ? ORDER BY created_at DESC LIMIT 1",
1899
+ [entry.target, entry.key]
1900
+ );
1901
+ const last = rows[0];
1902
+ if (last && last.action === "changed" && last.user_email === entry.user && now2.getTime() - Date.parse(String(last.created_at)) < SAME_EDIT_SECONDS * 1e3) {
1903
+ return;
1904
+ }
1905
+ }
1906
+ await this.#db.batch([
1907
+ {
1908
+ sql: `INSERT INTO brim_history (id, target, key, action, page, title, before, user_email, created_at)
1909
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1910
+ args: [
1911
+ randomUUID3(),
1912
+ entry.target,
1913
+ entry.key,
1914
+ entry.action,
1915
+ entry.page,
1916
+ entry.title,
1917
+ entry.before === null || entry.before === void 0 ? null : JSON.stringify(entry.before),
1918
+ entry.user,
1919
+ now2.toISOString()
1920
+ ]
1921
+ },
1922
+ {
1923
+ sql: "DELETE FROM brim_history WHERE created_at < ?",
1924
+ args: [new Date(now2.getTime() - KEEP_DAYS * 24 * 60 * 60 * 1e3).toISOString()]
1925
+ },
1926
+ {
1927
+ sql: `DELETE FROM brim_history WHERE id IN (SELECT id FROM brim_history ORDER BY created_at DESC LIMIT -1 OFFSET ${KEEP_ENTRIES})`
1928
+ }
1929
+ ]);
1930
+ }
1931
+ /** Newest first; `page` narrows the list to the changes made on one page. */
1932
+ async list(options = {}) {
1933
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 100) || 100, 1), 500);
1934
+ const rows = options.page === void 0 ? await this.#db.query(`${SELECT} ORDER BY created_at DESC, id LIMIT ${limit}`) : await this.#db.query(`${SELECT} WHERE page = ? ORDER BY created_at DESC, id LIMIT ${limit}`, [options.page]);
1935
+ return rows.map(toEntry);
1936
+ }
1937
+ async get(id) {
1938
+ const rows = await this.#db.query("SELECT * FROM brim_history WHERE id = ?", [id]);
1939
+ const row = rows[0];
1940
+ if (!row) return void 0;
1941
+ return {
1942
+ ...toEntry(row),
1943
+ key: String(row.key),
1944
+ before: row.before === null ? null : JSON.parse(String(row.before))
1945
+ };
1946
+ }
1947
+ async remove(id) {
1948
+ await this.#db.query("DELETE FROM brim_history WHERE id = ?", [id]);
1949
+ }
1950
+ };
1951
+ var SELECT = "SELECT id, target, action, page, title, user_email, created_at FROM brim_history";
1952
+ function toEntry(row) {
1953
+ return {
1954
+ id: String(row.id),
1955
+ target: String(row.target),
1956
+ action: String(row.action),
1957
+ page: String(row.page),
1958
+ title: String(row.title),
1959
+ user: String(row.user_email),
1960
+ at: String(row.created_at)
1961
+ };
1962
+ }
1963
+
1964
+ // src/content/items.ts
1965
+ import { randomUUID as randomUUID4 } from "node:crypto";
1966
+
1967
+ // src/blocks/schemas/carousel.ts
1968
+ function imagesProperty(title) {
1969
+ return {
1970
+ title,
1971
+ type: "array",
1972
+ widget: "carousel-images",
1973
+ description: "Upload several at once, drag them into order, open one to describe it.",
1974
+ items: {
1975
+ type: "object",
1976
+ properties: {
1977
+ id: { type: "string" },
1978
+ url: { type: "string" },
1979
+ alt: { type: "string" },
1980
+ caption: { type: "string" },
1981
+ link: { type: "string" },
1982
+ width: { type: "number", exclusiveMinimum: 0 },
1983
+ height: { type: "number", exclusiveMinimum: 0 }
1984
+ }
1985
+ }
1986
+ };
1987
+ }
1988
+ var carousel = {
1989
+ type: "carousel",
1990
+ label: "Carousel",
1991
+ description: "Slides the visitor swipes through, or a strip of logos that rolls by itself",
1992
+ schema: {
1993
+ fieldsets: [
1994
+ { id: "carousel_content", title: "Content", fields: ["images"] },
1995
+ { id: "carousel_layout", title: "Layout", fields: ["variant", "slidesPerView", "gap", "showArrows", "showDots"] },
1996
+ {
1997
+ id: "carousel_behavior",
1998
+ title: "Behavior",
1999
+ fields: ["start", "autoplay", "autoplaySpeed", "pauseOnHover", "loop", "continuousSpeed"]
2000
+ }
2001
+ ],
2002
+ properties: {
2003
+ images: imagesProperty("Slides"),
2004
+ variant: {
2005
+ title: "Variation",
2006
+ type: "string",
2007
+ widget: "select",
2008
+ default: "slider",
2009
+ options: [
2010
+ { value: "slider", label: "Slider" },
2011
+ { value: "center-peek", label: "Peek: the neighbours show on each side" },
2012
+ { value: "continuous", label: "Rolling strip (logos)" }
2013
+ ]
2014
+ },
2015
+ slidesPerView: {
2016
+ title: "Slides per view",
2017
+ type: "number",
2018
+ widget: "range",
2019
+ min: 1,
2020
+ max: 6,
2021
+ step: 1,
2022
+ default: 1,
2023
+ description: "On a phone, one.",
2024
+ showWhen: { variant: "slider" }
2025
+ },
2026
+ gap: {
2027
+ title: "Gap",
2028
+ type: "number",
2029
+ widget: "range",
2030
+ min: 0,
2031
+ max: 96,
2032
+ step: 2,
2033
+ default: 0
2034
+ },
2035
+ showArrows: { title: "Arrows", type: "boolean", widget: "checkbox", default: true },
2036
+ showDots: { title: "Dots", type: "boolean", widget: "checkbox", default: false },
2037
+ start: {
2038
+ title: "Opens on slide",
2039
+ type: "number",
2040
+ widget: "range",
2041
+ min: 1,
2042
+ max: 20,
2043
+ step: 1,
2044
+ default: 1
2045
+ },
2046
+ autoplay: { title: "Autoplay", type: "boolean", widget: "checkbox", default: false },
2047
+ autoplaySpeed: {
2048
+ title: "Time per slide (ms)",
2049
+ type: "number",
2050
+ widget: "range",
2051
+ min: 1e3,
2052
+ max: 15e3,
2053
+ step: 500,
2054
+ default: 4e3,
2055
+ showWhen: { autoplay: true }
2056
+ },
2057
+ pauseOnHover: {
2058
+ title: "Pause under the pointer",
2059
+ type: "boolean",
2060
+ widget: "checkbox",
2061
+ default: true,
2062
+ showWhen: { autoplay: true }
2063
+ },
2064
+ loop: { title: "Loop", type: "boolean", widget: "checkbox", default: true },
2065
+ continuousSpeed: {
2066
+ title: "Rolling time (s)",
2067
+ type: "number",
2068
+ widget: "range",
2069
+ min: 5,
2070
+ max: 120,
2071
+ step: 1,
2072
+ default: 24,
2073
+ description: "How long the strip takes to roll once round.",
2074
+ showWhen: { variant: "continuous" }
2075
+ }
2076
+ }
2077
+ },
2078
+ defaults: {
2079
+ "@type": "carousel",
2080
+ presetId: "default-theme",
2081
+ images: [],
2082
+ variant: "slider",
2083
+ slidesPerView: 1,
2084
+ gap: 0,
2085
+ showArrows: true,
2086
+ showDots: false,
2087
+ start: 1,
2088
+ autoplay: false,
2089
+ autoplaySpeed: 4e3,
2090
+ pauseOnHover: true,
2091
+ loop: true,
2092
+ continuousSpeed: 24
2093
+ }
2094
+ };
2095
+
2096
+ // src/blocks/schemas/image-gallery.ts
2097
+ var imageGallery = {
2098
+ type: "image-gallery",
2099
+ label: "Gallery",
2100
+ description: "Images the owner adds and orders; the site lays them out",
2101
+ schema: {
2102
+ fieldsets: [
2103
+ { id: "content", title: "Content", fields: ["images", "lightbox"] },
2104
+ { id: "image_gallery_layout", title: "Layout", fields: ["columns", "gap"] }
2105
+ ],
2106
+ properties: {
2107
+ images: imagesProperty("Images"),
2108
+ lightbox: {
2109
+ title: "Open full screen",
2110
+ type: "boolean",
2111
+ widget: "checkbox",
2112
+ default: true,
2113
+ description: "A click on an image opens it over the whole screen, as a slideshow. Images with a link keep it."
2114
+ },
2115
+ columns: {
2116
+ title: "Columns",
2117
+ type: "number",
2118
+ widget: "range",
2119
+ min: 1,
2120
+ max: 6,
2121
+ step: 1,
2122
+ default: 3,
2123
+ description: "On a phone, the images stack as they need to."
2124
+ },
2125
+ gap: {
2126
+ title: "Gap",
2127
+ type: "number",
2128
+ widget: "range",
2129
+ min: 0,
2130
+ max: 64,
2131
+ step: 2,
2132
+ default: 16,
2133
+ description: "Space between the images (px)"
2134
+ }
2135
+ }
2136
+ },
2137
+ defaults: {
2138
+ "@type": "image-gallery",
2139
+ presetId: "default-theme",
2140
+ images: [],
2141
+ lightbox: true,
2142
+ columns: 3,
2143
+ gap: 16
2144
+ }
2145
+ };
2146
+
2147
+ // src/blocks/data/social-networks.ts
2148
+ var SOCIAL_NETWORKS = [
2149
+ {
2150
+ key: "facebook",
2151
+ label: "Facebook",
2152
+ icon: "facebook",
2153
+ profileField: "facebookUrl",
2154
+ allowedHosts: ["facebook.com", "fb.com"],
2155
+ share: ({ url }) => `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`
2156
+ },
2157
+ {
2158
+ key: "x",
2159
+ label: "X",
2160
+ icon: "x",
2161
+ profileField: "xUrl",
2162
+ allowedHosts: ["x.com", "twitter.com"],
2163
+ share: ({ url, text: text2 }) => `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text2)}`
2164
+ },
2165
+ {
2166
+ key: "linkedin",
2167
+ label: "LinkedIn",
2168
+ icon: "linkedin",
2169
+ profileField: "linkedinUrl",
2170
+ allowedHosts: ["linkedin.com"],
2171
+ share: ({ url }) => `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`
2172
+ },
2173
+ {
2174
+ key: "whatsapp",
2175
+ label: "WhatsApp",
2176
+ icon: "whatsapp",
2177
+ profileField: "whatsappUrl",
2178
+ allowedHosts: ["wa.me", "whatsapp.com", "api.whatsapp.com"],
2179
+ share: ({ url, text: text2 }) => `https://wa.me/?text=${encodeURIComponent(`${text2} ${url}`)}`
2180
+ },
2181
+ {
2182
+ key: "telegram",
2183
+ label: "Telegram",
2184
+ icon: "telegram",
2185
+ profileField: "telegramUrl",
2186
+ allowedHosts: ["t.me", "telegram.me", "telegram.org"],
2187
+ share: ({ url, text: text2 }) => `https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text2)}`
2188
+ },
2189
+ {
2190
+ key: "pinterest",
2191
+ label: "Pinterest",
2192
+ icon: "pinterest",
2193
+ profileField: "pinterestUrl",
2194
+ allowedHosts: ["pinterest.com"],
2195
+ share: ({ url, text: text2 }) => `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(url)}&description=${encodeURIComponent(text2)}`
2196
+ },
2197
+ {
2198
+ key: "reddit",
2199
+ label: "Reddit",
2200
+ icon: "reddit",
2201
+ profileField: "redditUrl",
2202
+ allowedHosts: ["reddit.com"],
2203
+ share: ({ url, text: text2 }) => `https://www.reddit.com/submit?url=${encodeURIComponent(url)}&title=${encodeURIComponent(text2)}`
2204
+ },
2205
+ {
2206
+ key: "instagram",
2207
+ label: "Instagram",
2208
+ icon: "instagram",
2209
+ profileField: "instagramUrl",
2210
+ allowedHosts: ["instagram.com"]
2211
+ },
2212
+ {
2213
+ key: "youtube",
2214
+ label: "YouTube",
2215
+ icon: "youtube",
2216
+ profileField: "youtubeUrl",
2217
+ allowedHosts: ["youtube.com", "youtu.be"]
2218
+ },
2219
+ {
2220
+ key: "tiktok",
2221
+ label: "TikTok",
2222
+ icon: "tiktok",
2223
+ profileField: "tiktokUrl",
2224
+ allowedHosts: ["tiktok.com"]
2225
+ },
2226
+ {
2227
+ key: "github",
2228
+ label: "GitHub",
2229
+ icon: "github",
2230
+ profileField: "githubUrl",
2231
+ allowedHosts: ["github.com"]
2232
+ },
2233
+ {
2234
+ key: "discord",
2235
+ label: "Discord",
2236
+ icon: "discord",
2237
+ profileField: "discordUrl",
2238
+ allowedHosts: ["discord.gg", "discord.com"]
2239
+ },
2240
+ {
2241
+ key: "twitch",
2242
+ label: "Twitch",
2243
+ icon: "twitch",
2244
+ profileField: "twitchUrl",
2245
+ allowedHosts: ["twitch.tv"]
2246
+ },
2247
+ {
2248
+ key: "vimeo",
2249
+ label: "Vimeo",
2250
+ icon: "vimeo",
2251
+ profileField: "vimeoUrl",
2252
+ allowedHosts: ["vimeo.com"]
2253
+ },
2254
+ {
2255
+ key: "dribbble",
2256
+ label: "Dribbble",
2257
+ icon: "dribbble",
2258
+ profileField: "dribbbleUrl",
2259
+ allowedHosts: ["dribbble.com"]
2260
+ },
2261
+ {
2262
+ key: "email",
2263
+ label: "Email",
2264
+ icon: "email",
2265
+ profileField: "emailUrl",
2266
+ allowedProtocols: ["mailto"]
2267
+ },
2268
+ {
2269
+ key: "phone",
2270
+ label: "Phone",
2271
+ icon: "phone",
2272
+ profileField: "phoneUrl",
2273
+ allowedProtocols: ["tel"]
2274
+ }
2275
+ ];
2276
+ var DEFAULT_SOCIAL_NETWORK_ORDER = SOCIAL_NETWORKS.map((network) => network.key);
2277
+
2278
+ // src/content/items.ts
2279
+ var PLACE = "COALESCE((SELECT original.position FROM brim_items AS original WHERE original.id = brim_items.translation_of), position)";
2280
+ var ORDER = {
2281
+ newest: "created_at DESC",
2282
+ oldest: "created_at ASC",
2283
+ title: "title COLLATE NOCASE ASC",
2284
+ position: `${PLACE} ASC, created_at ASC`
2285
+ };
2286
+ var nocase = (text2) => text2.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
2287
+ var byText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
2288
+ var COMPARE = {
2289
+ newest: (a, b) => byText(b.createdAt, a.createdAt) || byText(a.id, b.id),
2290
+ oldest: (a, b) => byText(a.createdAt, b.createdAt) || byText(a.id, b.id),
2291
+ title: (a, b) => byText(nocase(a.title), nocase(b.title)) || byText(a.id, b.id),
2292
+ position: (a, b) => a.position - b.position || byText(a.createdAt, b.createdAt) || byText(a.id, b.id)
2293
+ };
2294
+ var ItemStore = class {
2295
+ #db;
2296
+ constructor(db) {
2297
+ this.#db = db;
2298
+ }
2299
+ /** `locale`: only the items in that language ("" is the default one); without it, all languages. */
2300
+ async list(type, options = {}) {
2301
+ const { publishedOnly = false, sort = "newest", limit, locale } = options;
2302
+ const args = [type];
2303
+ if (locale !== void 0) args.push(locale);
2304
+ if (limit) args.push(limit);
2305
+ const rows = await this.#db.query(
2306
+ `SELECT *, ${PLACE} AS place FROM brim_items WHERE type = ?${locale !== void 0 ? " AND locale = ?" : ""}${publishedOnly ? " AND visibility = 'published'" : ""}
2307
+ ORDER BY ${ORDER[sort]}${limit ? " LIMIT ?" : ""}`,
2308
+ args
2309
+ );
2310
+ return rows.map(toItem);
2311
+ }
2312
+ /**
2313
+ * The items of a type as `list` answers them, kept in memory between requests. Each call asks the database one
2314
+ * small question (`#fingerprint`): whether an item of the type was added, edited, shown or hidden, moved or removed
2315
+ * since, by whoever. Only then are the items read again, and only the ones that changed: on a remote database a
2316
+ * type with hundreds of items takes seconds to read whole, and most pages need the same list every time.
2317
+ */
2318
+ async listCached(type, options = {}) {
2319
+ const { publishedOnly = false, sort = "newest", limit, locale } = options;
2320
+ const kept = await this.#kept(type);
2321
+ const listed = kept.items.filter(
2322
+ (item) => (locale === void 0 || item.locale === locale) && (!publishedOnly || item.visibility === "published")
2323
+ );
2324
+ listed.sort(COMPARE[sort]);
2325
+ return limit ? listed.slice(0, limit) : listed;
2326
+ }
2327
+ /**
2328
+ * One item by its address (`slug`) in a language ("" is the default one), with the place `list` gives it.
2329
+ * Without `locale`, the first of any language.
2330
+ */
2331
+ async bySlug(type, slug, options = {}) {
2332
+ const { publishedOnly = false, locale } = options;
2333
+ const args = [type, slug];
2334
+ if (locale !== void 0) args.push(locale);
2335
+ const rows = await this.#db.query(
2336
+ `SELECT *, ${PLACE} AS place FROM brim_items WHERE type = ? AND slug = ?${locale !== void 0 ? " AND locale = ?" : ""}${publishedOnly ? " AND visibility = 'published'" : ""} ORDER BY locale LIMIT 1`,
2337
+ args
2338
+ );
2339
+ return rows[0] ? toItem(rows[0]) : void 0;
2340
+ }
2341
+ /** Per type: its items as last read, with what the database said about them then. */
2342
+ #cache = /* @__PURE__ */ new Map();
2343
+ async #kept(type) {
2344
+ const fingerprint = await this.#fingerprint(type);
2345
+ const previous = this.#cache.get(type);
2346
+ const before = previous ? await previous.catch(() => void 0) : void 0;
2347
+ if (before && before.fingerprint === fingerprint) return before;
2348
+ const current = this.#cache.get(type);
2349
+ if (current && current !== previous) return current;
2350
+ const reading = this.#read(type, fingerprint, before);
2351
+ this.#cache.set(type, reading);
2352
+ reading.catch(() => {
2353
+ if (this.#cache.get(type) === reading) this.#cache.delete(type);
2354
+ });
2355
+ return reading;
2356
+ }
2357
+ async #read(type, fingerprint, before) {
2358
+ let rows;
2359
+ if (!before) {
2360
+ rows = (await this.#db.query("SELECT * FROM brim_items WHERE type = ?", [type])).map(toItem);
2361
+ } else {
2362
+ const now2 = await this.#db.query(
2363
+ "SELECT id, updated_at, position, translation_of, visibility FROM brim_items WHERE type = ?",
2364
+ [type]
2365
+ );
2366
+ const known2 = new Map(before.rows.map((item) => [item.id, item]));
2367
+ const changed = now2.filter((row) => known2.get(String(row.id))?.updatedAt !== String(row.updated_at)).map((row) => String(row.id));
2368
+ const fresh = /* @__PURE__ */ new Map();
2369
+ for (let start2 = 0; start2 < changed.length; start2 += 100) {
2370
+ const ids = changed.slice(start2, start2 + 100);
2371
+ const read = await this.#db.query(
2372
+ `SELECT * FROM brim_items WHERE id IN (${ids.map(() => "?").join(", ")})`,
2373
+ ids
2374
+ );
2375
+ for (const row of read) fresh.set(String(row.id), toItem(row));
2376
+ }
2377
+ rows = now2.flatMap((row) => {
2378
+ const id = String(row.id);
2379
+ const item = fresh.get(id) ?? known2.get(id);
2380
+ if (!item) return [];
2381
+ return [
2382
+ {
2383
+ ...item,
2384
+ position: Number(row.position ?? 0),
2385
+ translationOf: row.translation_of == null ? null : String(row.translation_of),
2386
+ visibility: row.visibility === "private" ? "private" : "published"
2387
+ }
2388
+ ];
2389
+ });
2390
+ }
2391
+ const byId = new Map(rows.map((item) => [item.id, item.position]));
2392
+ const items = rows.map((item) => ({
2393
+ ...item,
2394
+ position: (item.translationOf !== null ? byId.get(item.translationOf) : void 0) ?? item.position
2395
+ }));
2396
+ return { fingerprint, rows, items };
2397
+ }
2398
+ /**
2399
+ * Changes whenever an item of the type is added, removed, edited (`updated_at`), shown or hidden, or moved
2400
+ * (positions weighted by a hash of each id, so swapping two items changes the sum).
2401
+ */
2402
+ async #fingerprint(type) {
2403
+ const rows = await this.#db.query(
2404
+ `SELECT COUNT(*) AS n, MAX(updated_at) AS changed,
2405
+ SUM(position * ((unicode(substr(id, 1, 1)) * 65599 + unicode(substr(id, 2, 1)) * 257
2406
+ + unicode(substr(id, 3, 1)) * 31 + unicode(substr(id, 4, 1))) % 1000003)) AS places,
2407
+ SUM(length(COALESCE(translation_of, ''))) AS links,
2408
+ SUM(visibility = 'published') AS shown
2409
+ FROM brim_items WHERE type = ?`,
2410
+ [type]
2411
+ );
2412
+ const row = rows[0] ?? {};
2413
+ return `${row.n}|${row.changed}|${row.places}|${row.links}|${row.shown}`;
2414
+ }
2415
+ /** The item and its translations: everything written first as `item` or its original, in every language. */
2416
+ async translations(item) {
2417
+ const original = item.translationOf ?? item.id;
2418
+ const rows = await this.#db.query("SELECT * FROM brim_items WHERE id = ? OR translation_of = ? ORDER BY locale", [
2419
+ original,
2420
+ original
2421
+ ]);
2422
+ return rows.map(toItem);
2423
+ }
2424
+ async get(id) {
2425
+ const rows = await this.#db.query("SELECT * FROM brim_items WHERE id = ?", [id]);
2426
+ return rows[0] ? toItem(rows[0]) : void 0;
2427
+ }
2428
+ /**
2429
+ * `draft` must already be validated: see `parseItem`. `locale` and `translationOf` are checked by the caller:
2430
+ * a language of the site, and an item of the same type written first.
2431
+ */
2432
+ async create(type, draft, options = {}) {
2433
+ const locale = options.locale ?? "";
2434
+ await this.#assertSlugFree(type, locale, draft.slug, void 0);
2435
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
2436
+ const last = await this.#db.query(
2437
+ "SELECT COALESCE(MAX(position), 0) AS last FROM brim_items WHERE type = ? AND locale = ?",
2438
+ [type, locale]
2439
+ );
2440
+ const item = {
2441
+ id: randomUUID4(),
2442
+ type,
2443
+ ...draft,
2444
+ locale,
2445
+ translationOf: options.translationOf ?? null,
2446
+ position: Number(last[0]?.last ?? 0) + 1,
2447
+ createdAt: now2,
2448
+ updatedAt: now2
2449
+ };
2450
+ await this.#db.query(
2451
+ `INSERT INTO brim_items (id, type, locale, translation_of, slug, title, visibility, data, position, created_at, updated_at)
2452
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2453
+ [
2454
+ item.id,
2455
+ type,
2456
+ locale,
2457
+ item.translationOf,
2458
+ item.slug,
2459
+ item.title,
2460
+ item.visibility,
2461
+ JSON.stringify(item.data),
2462
+ item.position,
2463
+ now2,
2464
+ now2
2465
+ ]
2466
+ );
2467
+ return item;
2468
+ }
2469
+ /** `draft` must already be validated: see `parseItem`. */
2470
+ async update(existing, draft) {
2471
+ await this.#assertSlugFree(existing.type, existing.locale, draft.slug, existing.id);
2472
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2473
+ await this.#db.query(
2474
+ "UPDATE brim_items SET slug = ?, title = ?, visibility = ?, data = ?, updated_at = ? WHERE id = ?",
2475
+ [draft.slug, draft.title, draft.visibility, JSON.stringify(draft.data), updatedAt, existing.id]
2476
+ );
2477
+ return { ...existing, ...draft, updatedAt };
2478
+ }
2479
+ /**
2480
+ * Puts back an item that was deleted, as it was (see the site's history). Its address must still be free; a
2481
+ * translation whose original is gone too comes back as an item of its own.
2482
+ */
2483
+ async restore(item) {
2484
+ await this.#assertSlugFree(item.type, item.locale, item.slug, void 0);
2485
+ const original = item.translationOf ? await this.get(item.translationOf) : void 0;
2486
+ const restored = {
2487
+ ...item,
2488
+ translationOf: original ? original.id : null,
2489
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2490
+ };
2491
+ await this.#db.query(
2492
+ `INSERT INTO brim_items (id, type, locale, translation_of, slug, title, visibility, data, position, created_at, updated_at)
2493
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2494
+ [
2495
+ restored.id,
2496
+ restored.type,
2497
+ restored.locale,
2498
+ restored.translationOf,
2499
+ restored.slug,
2500
+ restored.title,
2501
+ restored.visibility,
2502
+ JSON.stringify(restored.data),
2503
+ restored.position ?? 0,
2504
+ restored.createdAt,
2505
+ restored.updatedAt
2506
+ ]
2507
+ );
2508
+ return restored;
2509
+ }
2510
+ /**
2511
+ * Puts the items of a type in the order given: `ids` are its items written first (not translations, which follow
2512
+ * their original), first to last. Items left out keep their places after those given.
2513
+ */
2514
+ async reorder(type, ids) {
2515
+ const items = (await this.list(type, { sort: "position" })).filter((item) => item.translationOf === null);
2516
+ const byId = new Map(items.map((item) => [item.id, item]));
2517
+ const unknown = ids.filter((id) => !byId.has(id));
2518
+ if (unknown.length > 0) {
2519
+ throw new ValidationError(`Not items of "${type}" written first: ${unknown.slice(0, 5).join(", ")}.`);
2520
+ }
2521
+ if (new Set(ids).size !== ids.length) throw new ValidationError("An item is listed twice.");
2522
+ const given = new Set(ids);
2523
+ const order = [...ids, ...items.filter((item) => !given.has(item.id)).map((item) => item.id)];
2524
+ await this.#db.batch(
2525
+ order.map((id, index) => ({ sql: "UPDATE brim_items SET position = ? WHERE id = ?", args: [index + 1, id] }))
2526
+ );
2527
+ return order.map((id, index) => ({ ...byId.get(id), position: index + 1 }));
2528
+ }
2529
+ /**
2530
+ * Makes `originalId` the original of the items `translationIds` names again (those that still exist and are not
2531
+ * the original itself). An original that is put back after being removed takes back the translations it had
2532
+ * handed to one of them.
2533
+ */
2534
+ async relink(originalId, translationIds) {
2535
+ const ids = translationIds.filter((id) => id !== originalId);
2536
+ if (ids.length === 0) return;
2537
+ await this.#db.batch(
2538
+ ids.map((id) => ({ sql: "UPDATE brim_items SET translation_of = ? WHERE id = ?", args: [originalId, id] }))
2539
+ );
2540
+ }
2541
+ /** The ids of the items that are translations of `id`. */
2542
+ async translationIds(id) {
2543
+ const rows = await this.#db.query("SELECT id FROM brim_items WHERE translation_of = ?", [id]);
2544
+ return rows.map((row) => String(row.id));
2545
+ }
2546
+ /** An original that is removed hands its translations to the first of them, so they stay linked. */
2547
+ async remove(id) {
2548
+ const rows = await this.#db.query("SELECT id FROM brim_items WHERE translation_of = ? ORDER BY created_at", [id]);
2549
+ const heir = rows[0] ? String(rows[0].id) : void 0;
2550
+ await this.#db.batch([
2551
+ { sql: "DELETE FROM brim_items WHERE id = ?", args: [id] },
2552
+ ...heir ? [
2553
+ { sql: "UPDATE brim_items SET translation_of = NULL WHERE id = ?", args: [heir] },
2554
+ { sql: "UPDATE brim_items SET translation_of = ? WHERE translation_of = ?", args: [heir, id] }
2555
+ ] : []
2556
+ ]);
2557
+ }
2558
+ async #assertSlugFree(type, locale, slug, exceptId) {
2559
+ const rows = await this.#db.query("SELECT id FROM brim_items WHERE type = ? AND locale = ? AND slug = ?", [
2560
+ type,
2561
+ locale,
2562
+ slug
2563
+ ]);
2564
+ if (rows[0] && rows[0].id !== exceptId) throw new ValidationError(`The address "${slug}" is already used.`);
2565
+ }
2566
+ };
2567
+ function toItem(row) {
2568
+ return {
2569
+ id: String(row.id),
2570
+ type: String(row.type),
2571
+ slug: String(row.slug),
2572
+ title: String(row.title),
2573
+ visibility: row.visibility === "private" ? "private" : "published",
2574
+ data: JSON.parse(String(row.data)),
2575
+ locale: String(row.locale ?? ""),
2576
+ translationOf: row.translation_of == null ? null : String(row.translation_of),
2577
+ // Listed, a translation answers its original's place (see `PLACE`).
2578
+ position: Number(row.place ?? row.position ?? 0),
2579
+ createdAt: String(row.created_at),
2580
+ updatedAt: String(row.updated_at)
2581
+ };
2582
+ }
2583
+
2584
+ // src/content/store.ts
2585
+ var REDIRECTS_KEY = "redirects";
2586
+ var ContentStore = class {
2587
+ #db;
2588
+ constructor(db) {
2589
+ this.#db = db;
2590
+ }
2591
+ async loadNodes(scopes2) {
2592
+ if (scopes2.length === 0) return [];
2593
+ const placeholders = scopes2.map(() => "?").join(", ");
2594
+ const rows = await this.#db.query(
2595
+ `SELECT scope, node_id, kind, value FROM brim_nodes WHERE scope IN (${placeholders})`,
2596
+ scopes2
2597
+ );
2598
+ return rows.map((row) => ({
2599
+ scope: String(row.scope),
2600
+ nodeId: String(row.node_id),
2601
+ kind: String(row.kind),
2602
+ value: JSON.parse(String(row.value))
2603
+ }));
2604
+ }
2605
+ /** Every saved node of the site, in every scope: what a check of the whole content reads. */
2606
+ async allNodes() {
2607
+ const rows = await this.#db.query("SELECT scope, node_id, kind, value FROM brim_nodes", []);
2608
+ return rows.map((row) => ({
2609
+ scope: String(row.scope),
2610
+ nodeId: String(row.node_id),
2611
+ kind: String(row.kind),
2612
+ value: JSON.parse(String(row.value))
2613
+ }));
2614
+ }
2615
+ /** `value` must already be validated: see `parseNodeValue` and `parseSettings`. */
2616
+ async saveNode(scope, nodeId, kind, value) {
2617
+ assertNodeId(nodeId);
2618
+ await this.#db.query(
2619
+ `INSERT INTO brim_nodes (scope, node_id, kind, value, updated_at) VALUES (?, ?, ?, ?, ?)
2620
+ ON CONFLICT (scope, node_id) DO UPDATE SET kind = excluded.kind, value = excluded.value, updated_at = excluded.updated_at`,
2621
+ [scope, nodeId, kind, JSON.stringify(value), now()]
2622
+ );
2623
+ }
2624
+ /** Removes the owner's value, so the page falls back to what the source says. */
2625
+ async resetNode(scope, nodeId) {
2626
+ await this.#db.query("DELETE FROM brim_nodes WHERE scope = ? AND node_id = ?", [scope, nodeId]);
2627
+ }
2628
+ /** Moves everything saved on one page to another address, e.g. when an item's address changes. */
2629
+ async moveNodes(fromScope, toScope) {
2630
+ await this.#db.batch([
2631
+ // What was already saved at the new address gives way to what moves there.
2632
+ { sql: "DELETE FROM brim_nodes WHERE scope = ?", args: [toScope] },
2633
+ { sql: "UPDATE brim_nodes SET scope = ? WHERE scope = ?", args: [toScope, fromScope] }
2634
+ ]);
2635
+ }
2636
+ /**
2637
+ * Copies what was saved on one page to another, leaving alone what the other page already has: a translation
2638
+ * starts from the original's words and never loses what was already translated. Returns how many were copied.
2639
+ */
2640
+ async copyNodes(fromScope, toScope) {
2641
+ const count = async () => Number((await this.#db.query("SELECT COUNT(*) AS n FROM brim_nodes WHERE scope = ?", [toScope]))[0]?.n ?? 0);
2642
+ const before = await count();
2643
+ await this.#db.query(
2644
+ `INSERT INTO brim_nodes (scope, node_id, kind, value, updated_at)
2645
+ SELECT ?, node_id, kind, value, ? FROM brim_nodes WHERE scope = ?
2646
+ ON CONFLICT (scope, node_id) DO NOTHING`,
2647
+ [toScope, now(), fromScope]
2648
+ );
2649
+ return await count() - before;
2650
+ }
2651
+ async removeNodes(scope) {
2652
+ await this.#db.query("DELETE FROM brim_nodes WHERE scope = ?", [scope]);
2653
+ }
2654
+ /** A page nobody has touched is published and has no SEO settings: pages come from source. */
2655
+ async page(pathname) {
2656
+ const path = normalizePagePath(pathname);
2657
+ const rows = await this.#db.query("SELECT * FROM brim_pages WHERE path = ?", [path]);
2658
+ return rows[0] ? toPage(rows[0]) : { path, visibility: "published", seo: {} };
2659
+ }
2660
+ /** The search settings of every page that has some, by address (pages of items included). */
2661
+ async pageSeoSettings() {
2662
+ const rows = await this.#db.query("SELECT path, seo FROM brim_pages WHERE seo IS NOT NULL AND seo != '{}'");
2663
+ return new Map(rows.map((row) => [String(row.path), JSON.parse(String(row.seo))]));
2664
+ }
2665
+ /** Pages the owner added from a template, by address. The public build asks for published ones only. */
2666
+ async templatePages(options = {}) {
2667
+ const rows = await this.#db.query(
2668
+ `SELECT * FROM brim_pages WHERE template IS NOT NULL${options.publishedOnly ? " AND visibility = 'published'" : ""}
2669
+ ORDER BY path`
2670
+ );
2671
+ return rows.map(toPage);
2672
+ }
2673
+ /**
2674
+ * Adds a page made from a template. It starts private, so the owner can fill it in before anyone sees it.
2675
+ * The caller checks that the address belongs to no other page.
2676
+ */
2677
+ async createPage(pathname, template, title, visibility) {
2678
+ const path = normalizePagePath(pathname);
2679
+ await this.#db.query(
2680
+ `INSERT INTO brim_pages (path, visibility, seo, template, title, updated_at) VALUES (?, ?, '{}', ?, ?, ?)
2681
+ ON CONFLICT (path) DO UPDATE SET visibility = excluded.visibility, seo = '{}', template = excluded.template,
2682
+ title = excluded.title, updated_at = excluded.updated_at`,
2683
+ [path, visibility, template, title, now()]
2684
+ );
2685
+ return { path, visibility, seo: {}, template, title };
2686
+ }
2687
+ async setPageTitle(pathname, title) {
2688
+ await this.#db.query("UPDATE brim_pages SET title = ?, updated_at = ? WHERE path = ?", [
2689
+ title,
2690
+ now(),
2691
+ normalizePagePath(pathname)
2692
+ ]);
2693
+ }
2694
+ /** Removes a page added from a template together with everything the owner wrote on it. */
2695
+ async deletePage(pathname) {
2696
+ const path = normalizePagePath(pathname);
2697
+ await this.#db.batch([
2698
+ { sql: "DELETE FROM brim_nodes WHERE scope = ?", args: [pageScope(path)] },
2699
+ { sql: "DELETE FROM brim_pages WHERE path = ? AND template IS NOT NULL", args: [path] }
2700
+ ]);
2701
+ }
2702
+ async setPageVisibility(pathname, visibility) {
2703
+ await this.#db.query(
2704
+ `INSERT INTO brim_pages (path, visibility, updated_at) VALUES (?, ?, ?)
2705
+ ON CONFLICT (path) DO UPDATE SET visibility = excluded.visibility, updated_at = excluded.updated_at`,
2706
+ [normalizePagePath(pathname), visibility, now()]
2707
+ );
2708
+ }
2709
+ /**
2710
+ * Moves a page added from a template to a new address, with everything the owner wrote on it. The caller checks
2711
+ * that the new address is free and adds the redirect from the old one.
2712
+ */
2713
+ async movePage(fromPath, toPath) {
2714
+ const from = normalizePagePath(fromPath);
2715
+ const to = normalizePagePath(toPath);
2716
+ await this.#db.batch([
2717
+ { sql: "DELETE FROM brim_nodes WHERE scope = ?", args: [pageScope(to)] },
2718
+ { sql: "UPDATE brim_nodes SET scope = ? WHERE scope = ?", args: [pageScope(to), pageScope(from)] },
2719
+ { sql: "DELETE FROM brim_pages WHERE path = ?", args: [to] },
2720
+ { sql: "UPDATE brim_pages SET path = ?, updated_at = ? WHERE path = ?", args: [to, now(), from] }
2721
+ ]);
2722
+ }
2723
+ /**
2724
+ * Carries a page's search settings to its new address, for a page whose address follows something else (an item's
2725
+ * slug or category): they are kept by address, so without this a page hidden from search engines would be listed
2726
+ * when its address changed.
2727
+ */
2728
+ async movePageSettings(fromPath, toPath) {
2729
+ const from = normalizePagePath(fromPath);
2730
+ const to = normalizePagePath(toPath);
2731
+ if (from === to) return;
2732
+ const { seo } = await this.page(from);
2733
+ if (Object.keys(seo).length > 0) {
2734
+ await this.setPageSeo(to, seo);
2735
+ await this.setPageSeo(from, {});
2736
+ }
2737
+ }
2738
+ /** The site's redirects, in the order the owner keeps them. */
2739
+ async redirects() {
2740
+ return await this.#meta(REDIRECTS_KEY) ?? [];
2741
+ }
2742
+ /** `redirects` must already be checked: see `parseRedirects`. */
2743
+ async setRedirects(redirects) {
2744
+ await this.#setMeta(REDIRECTS_KEY, redirects);
2745
+ }
2746
+ async #meta(key) {
2747
+ const rows = await this.#db.query("SELECT value FROM brim_meta WHERE key = ?", [key]);
2748
+ return rows[0] ? JSON.parse(String(rows[0].value)) : void 0;
2749
+ }
2750
+ async #setMeta(key, value) {
2751
+ await this.#db.query(
2752
+ "INSERT INTO brim_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
2753
+ [key, JSON.stringify(value)]
2754
+ );
2755
+ }
2756
+ /** `seo` must already be validated: see `parseSeo`. */
2757
+ async setPageSeo(pathname, seo) {
2758
+ await this.#db.query(
2759
+ `INSERT INTO brim_pages (path, visibility, seo, updated_at) VALUES (?, 'published', ?, ?)
2760
+ ON CONFLICT (path) DO UPDATE SET seo = excluded.seo, updated_at = excluded.updated_at`,
2761
+ [normalizePagePath(pathname), JSON.stringify(seo), now()]
2762
+ );
2763
+ }
2764
+ };
2765
+ function toPage(row) {
2766
+ return {
2767
+ path: String(row.path),
2768
+ visibility: row.visibility === "private" ? "private" : "published",
2769
+ seo: JSON.parse(String(row.seo)),
2770
+ ...row.template != null && { template: String(row.template), title: String(row.title ?? "") }
2771
+ };
2772
+ }
2773
+ function now() {
2774
+ return (/* @__PURE__ */ new Date()).toISOString();
2775
+ }
2776
+
2777
+ // src/content/drafts.ts
2778
+ var DraftStore = class {
2779
+ #db;
2780
+ constructor(db) {
2781
+ this.#db = db;
2782
+ }
2783
+ async all() {
2784
+ const rows = await this.#db.query("SELECT * FROM brim_drafts ORDER BY updated_at");
2785
+ return rows.map((row) => ({
2786
+ target: String(row.target),
2787
+ key: String(row.key),
2788
+ value: JSON.parse(String(row.value)),
2789
+ page: String(row.page),
2790
+ updatedAt: String(row.updated_at)
2791
+ }));
2792
+ }
2793
+ async count() {
2794
+ return Number((await this.#db.query("SELECT COUNT(*) AS n FROM brim_drafts"))[0]?.n ?? 0);
2795
+ }
2796
+ /** The draft of one thing; `undefined` when it has none, so the live content stands. */
2797
+ async get(target, key) {
2798
+ const rows = await this.#db.query("SELECT value FROM brim_drafts WHERE target = ? AND key = ?", [target, key]);
2799
+ return rows[0] ? JSON.parse(String(rows[0].value)) : void 0;
2800
+ }
2801
+ /** `undefined` removes the draft. The value must already be validated. */
2802
+ async set(target, key, value, page) {
2803
+ if (value === void 0) {
2804
+ await this.#db.query("DELETE FROM brim_drafts WHERE target = ? AND key = ?", [target, key]);
2805
+ return;
2806
+ }
2807
+ await this.#db.query(
2808
+ `INSERT INTO brim_drafts (target, key, value, page, updated_at) VALUES (?, ?, ?, ?, ?)
2809
+ ON CONFLICT (target, key) DO UPDATE SET value = excluded.value, page = excluded.page,
2810
+ updated_at = excluded.updated_at`,
2811
+ [target, key, JSON.stringify(value), page, (/* @__PURE__ */ new Date()).toISOString()]
2812
+ );
2813
+ }
2814
+ async clear() {
2815
+ await this.#db.query("DELETE FROM brim_drafts");
2816
+ }
2817
+ /** The elements of these scopes as the preview shows them: saved values with the drafts over them. */
2818
+ async overlayNodes(nodes, scopes2) {
2819
+ const drafts = (await this.#rows("node")).filter((row) => scopes2.includes(row.key.split("\n")[0] ?? ""));
2820
+ if (drafts.length === 0) return nodes;
2821
+ const byKey = new Map(nodes.map((node) => [`${node.scope}
2822
+ ${node.nodeId}`, node]));
2823
+ for (const { key, value } of drafts) {
2824
+ const [scope = "", nodeId = ""] = key.split("\n");
2825
+ const draft = value;
2826
+ if ("reset" in draft) byKey.delete(key);
2827
+ else byKey.set(key, { scope, nodeId, kind: draft.kind, value: draft.value });
2828
+ }
2829
+ return [...byKey.values()];
2830
+ }
2831
+ /** Items as the preview shows them: their drafted content over what is saved. */
2832
+ async overlayItems(items) {
2833
+ if (items.length === 0) return items;
2834
+ const drafts = new Map((await this.#rows("item")).map((row) => [row.key, row.value]));
2835
+ if (drafts.size === 0) return items;
2836
+ return items.map((item) => {
2837
+ const draft = drafts.get(item.id);
2838
+ return draft ? { ...item, slug: draft.slug, title: draft.title, data: draft.data } : item;
2839
+ });
2840
+ }
2841
+ async overlayItem(item) {
2842
+ return (await this.overlayItems([item]))[0] ?? item;
2843
+ }
2844
+ /** A page's SEO settings as the preview shows them. */
2845
+ async overlaySeo(path, seo) {
2846
+ const draft = await this.get("seo", path);
2847
+ return draft === void 0 ? seo : draft;
2848
+ }
2849
+ async #rows(target) {
2850
+ const rows = await this.#db.query("SELECT key, value FROM brim_drafts WHERE target = ?", [target]);
2851
+ return rows.map((row) => ({ key: String(row.key), value: JSON.parse(String(row.value)) }));
2852
+ }
2853
+ };
2854
+
2855
+ // src/forms/store.ts
2856
+ import { randomBytes as randomBytes3, randomUUID as randomUUID5 } from "node:crypto";
2857
+ var SECRET_KEY = "form_secret";
2858
+ var FormStore = class {
2859
+ #db;
2860
+ #secret;
2861
+ constructor(db) {
2862
+ this.#db = db;
2863
+ }
2864
+ /** Made on first use and kept in the database, so the build and the server sign with the same one. */
2865
+ secret() {
2866
+ this.#secret ??= (async () => {
2867
+ await this.#db.query("INSERT INTO brim_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING", [
2868
+ SECRET_KEY,
2869
+ randomBytes3(32).toString("base64url")
2870
+ ]);
2871
+ const rows = await this.#db.query("SELECT value FROM brim_meta WHERE key = ?", [SECRET_KEY]);
2872
+ return String(rows[0]?.value);
2873
+ })();
2874
+ return this.#secret;
2875
+ }
2876
+ /**
2877
+ * Keeps a response and answers its id, which the editor opens it by (`/admin/edit?response=<id>`). `id` is given
2878
+ * when the message has files, which are stored under it before the message is.
2879
+ */
2880
+ async save(form2, title, answers, files = [], id = randomUUID5()) {
2881
+ await this.#db.query(
2882
+ "INSERT INTO brim_form_responses (id, form, title, answers, files, created_at) VALUES (?, ?, ?, ?, ?, ?)",
2883
+ [id, form2, title, JSON.stringify(answers), JSON.stringify(files), (/* @__PURE__ */ new Date()).toISOString()]
2884
+ );
2885
+ return id;
2886
+ }
2887
+ async list() {
2888
+ const rows = await this.#db.query("SELECT * FROM brim_form_responses ORDER BY created_at DESC LIMIT 1000");
2889
+ return rows.map(toResponse);
2890
+ }
2891
+ async get(id) {
2892
+ const rows = await this.#db.query("SELECT * FROM brim_form_responses WHERE id = ?", [id]);
2893
+ return rows[0] && toResponse(rows[0]);
2894
+ }
2895
+ /** Deletes a message and gives back what it was, so its files can be deleted too. */
2896
+ async remove(id) {
2897
+ const response = await this.get(id);
2898
+ await this.#db.query("DELETE FROM brim_form_responses WHERE id = ?", [id]);
2899
+ return response;
2900
+ }
2901
+ };
2902
+ function toResponse(row) {
2903
+ return {
2904
+ id: String(row.id),
2905
+ form: String(row.form),
2906
+ title: String(row.title),
2907
+ answers: JSON.parse(String(row.answers)),
2908
+ files: JSON.parse(String(row.files ?? "[]")),
2909
+ createdAt: String(row.created_at)
2910
+ };
2911
+ }
2912
+
2913
+ // src/db/cached.ts
2914
+ import { AsyncLocalStorage } from "node:async_hooks";
2915
+ var CONTENT_TABLES = /* @__PURE__ */ new Set(["brim_nodes", "brim_pages", "brim_items", "brim_meta", "brim_media", "brim_drafts"]);
2916
+ var TABLE = /\bbrim_\w+/g;
2917
+ var READ = /^\s*SELECT\b/i;
2918
+ var WRITE = /^\s*(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER|WITH)\b/i;
2919
+ var MAX_KEPT = 5e3;
2920
+ var VERSION_SQL = "SELECT version FROM brim_changes WHERE id = 1";
2921
+ async function ensureChangeTracking(db) {
2922
+ const triggers = [...CONTENT_TABLES].flatMap(
2923
+ (table) => ["INSERT", "UPDATE", "DELETE"].map((event) => ({
2924
+ sql: `CREATE TRIGGER IF NOT EXISTS ${table}_changed_${event.toLowerCase()} AFTER ${event} ON ${table}
2925
+ BEGIN UPDATE brim_changes SET version = version + 1 WHERE id = 1; END`
2926
+ }))
2927
+ );
2928
+ await db.batch([
2929
+ {
2930
+ sql: "CREATE TABLE IF NOT EXISTS brim_changes (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL)"
2931
+ },
2932
+ { sql: "INSERT OR IGNORE INTO brim_changes (id, version) VALUES (1, 0)" },
2933
+ ...triggers
2934
+ ]);
2935
+ }
2936
+ var scopes = new AsyncLocalStorage();
2937
+ function tablesOf(sql) {
2938
+ return sql.match(TABLE) ?? [];
2939
+ }
2940
+ function readsOnlyContent(sql) {
2941
+ if (!READ.test(sql)) return false;
2942
+ const tables = tablesOf(sql);
2943
+ return tables.length > 0 && tables.every((table) => CONTENT_TABLES.has(table));
2944
+ }
2945
+ function writesContent(sql) {
2946
+ return WRITE.test(sql) && tablesOf(sql).some((table) => CONTENT_TABLES.has(table));
2947
+ }
2948
+ var copy = (rows) => rows.map((row) => ({ ...row }));
2949
+ function keepingReads(db) {
2950
+ let keptVersion;
2951
+ const kept = /* @__PURE__ */ new Map();
2952
+ const forget = () => {
2953
+ kept.clear();
2954
+ keptVersion = void 0;
2955
+ const scope = scopes.getStore();
2956
+ if (scope) delete scope.version;
2957
+ };
2958
+ const version = (scope) => {
2959
+ scope.version ??= db.query(VERSION_SQL).then(
2960
+ (rows) => rows[0] ? Number(rows[0].version) : void 0,
2961
+ // A database without the table (made before it, and not writable to add it): nothing is kept.
2962
+ () => void 0
2963
+ );
2964
+ return scope.version;
2965
+ };
2966
+ return {
2967
+ async query(sql, args = []) {
2968
+ const scope = scopes.getStore();
2969
+ if (!scope || !readsOnlyContent(sql)) {
2970
+ const rows = await db.query(sql, args);
2971
+ if (writesContent(sql)) forget();
2972
+ return rows;
2973
+ }
2974
+ const current = await version(scope);
2975
+ if (current === void 0) return db.query(sql, args);
2976
+ if (current !== keptVersion) {
2977
+ kept.clear();
2978
+ keptVersion = current;
2979
+ }
2980
+ if (kept.size >= MAX_KEPT) kept.clear();
2981
+ const key = `${sql}\0${JSON.stringify(args)}`;
2982
+ let reading = kept.get(key);
2983
+ if (!reading) {
2984
+ reading = db.query(sql, args);
2985
+ kept.set(key, reading);
2986
+ reading.catch(() => {
2987
+ if (kept.get(key) === reading) kept.delete(key);
2988
+ });
2989
+ }
2990
+ return copy(await reading);
2991
+ },
2992
+ async batch(statements) {
2993
+ await db.batch(statements);
2994
+ if (statements.some((statement) => writesContent(statement.sql))) forget();
2995
+ },
2996
+ close() {
2997
+ kept.clear();
2998
+ db.close();
2999
+ }
3000
+ };
3001
+ }
3002
+
3003
+ // src/db/libsql.ts
3004
+ import { createClient } from "@libsql/client";
3005
+ function openDatabase(url, authToken) {
3006
+ assertSecureDatabaseUrl(url);
3007
+ const client = createClient(authToken ? { url, authToken } : { url });
3008
+ return {
3009
+ async query(sql, args = []) {
3010
+ const result = await client.execute({ sql, args });
3011
+ return result.rows.map((row) => {
3012
+ const record = {};
3013
+ for (const column of result.columns) record[column] = row[column];
3014
+ return record;
3015
+ });
3016
+ },
3017
+ async batch(statements) {
3018
+ await client.batch(
3019
+ statements.map(({ sql, args = [] }) => ({ sql, args })),
3020
+ "write"
3021
+ );
3022
+ },
3023
+ close() {
3024
+ client.close();
3025
+ }
3026
+ };
3027
+ }
3028
+
3029
+ // src/db/schema.ts
3030
+ var MIGRATIONS = [
3031
+ [
3032
+ `CREATE TABLE brim_nodes (
3033
+ scope TEXT NOT NULL,
3034
+ node_id TEXT NOT NULL,
3035
+ kind TEXT NOT NULL,
3036
+ value TEXT NOT NULL,
3037
+ updated_at TEXT NOT NULL,
3038
+ PRIMARY KEY (scope, node_id)
3039
+ ) WITHOUT ROWID`,
3040
+ `CREATE TABLE brim_pages (
3041
+ path TEXT PRIMARY KEY,
3042
+ visibility TEXT NOT NULL CHECK (visibility IN ('private', 'published')),
3043
+ updated_at TEXT NOT NULL
3044
+ ) WITHOUT ROWID`
3045
+ ],
3046
+ [
3047
+ `CREATE TABLE brim_users (
3048
+ id TEXT PRIMARY KEY,
3049
+ email TEXT NOT NULL UNIQUE,
3050
+ password_hash TEXT NOT NULL,
3051
+ role TEXT NOT NULL CHECK (role IN ('owner', 'editor')),
3052
+ created_at TEXT NOT NULL
3053
+ ) WITHOUT ROWID`,
3054
+ `CREATE TABLE brim_sessions (
3055
+ token_hash TEXT PRIMARY KEY,
3056
+ user_id TEXT NOT NULL,
3057
+ expires_at INTEGER NOT NULL
3058
+ ) WITHOUT ROWID`,
3059
+ `CREATE TABLE brim_rate_limits (
3060
+ key TEXT PRIMARY KEY,
3061
+ window_start INTEGER NOT NULL,
3062
+ count INTEGER NOT NULL
3063
+ ) WITHOUT ROWID`
3064
+ ],
3065
+ [
3066
+ `ALTER TABLE brim_pages ADD COLUMN seo TEXT NOT NULL DEFAULT '{}'`,
3067
+ `CREATE TABLE brim_items (
3068
+ id TEXT PRIMARY KEY,
3069
+ type TEXT NOT NULL,
3070
+ slug TEXT NOT NULL,
3071
+ title TEXT NOT NULL,
3072
+ visibility TEXT NOT NULL CHECK (visibility IN ('private', 'published')),
3073
+ data TEXT NOT NULL,
3074
+ created_at TEXT NOT NULL,
3075
+ updated_at TEXT NOT NULL,
3076
+ UNIQUE (type, slug)
3077
+ ) WITHOUT ROWID`
3078
+ ],
3079
+ [
3080
+ `CREATE TABLE brim_media (
3081
+ id TEXT PRIMARY KEY,
3082
+ url TEXT NOT NULL,
3083
+ name TEXT NOT NULL,
3084
+ mime TEXT NOT NULL,
3085
+ size INTEGER NOT NULL,
3086
+ created_at TEXT NOT NULL
3087
+ ) WITHOUT ROWID`
3088
+ ],
3089
+ [
3090
+ `CREATE TABLE brim_form_responses (
3091
+ id TEXT PRIMARY KEY,
3092
+ form TEXT NOT NULL,
3093
+ title TEXT NOT NULL,
3094
+ answers TEXT NOT NULL,
3095
+ created_at TEXT NOT NULL
3096
+ ) WITHOUT ROWID`
3097
+ ],
3098
+ [
3099
+ `CREATE TABLE brim_tokens (
3100
+ token_hash TEXT PRIMARY KEY,
3101
+ user_id TEXT NOT NULL,
3102
+ name TEXT NOT NULL,
3103
+ created_at TEXT NOT NULL,
3104
+ last_used_at TEXT,
3105
+ UNIQUE (user_id, name)
3106
+ ) WITHOUT ROWID`
3107
+ ],
3108
+ [
3109
+ // Pages the owner adds from a template; pages written in code keep both empty.
3110
+ `ALTER TABLE brim_pages ADD COLUMN template TEXT`,
3111
+ `ALTER TABLE brim_pages ADD COLUMN title TEXT`
3112
+ ],
3113
+ [`ALTER TABLE brim_media ADD COLUMN folder TEXT NOT NULL DEFAULT ''`],
3114
+ [
3115
+ // Items in languages: "" is the site's default language (and every item of a site with one language);
3116
+ // a translation points at the item it translates. The same address may be used once per language.
3117
+ `CREATE TABLE brim_items_v10 (
3118
+ id TEXT PRIMARY KEY,
3119
+ type TEXT NOT NULL,
3120
+ locale TEXT NOT NULL DEFAULT '',
3121
+ translation_of TEXT,
3122
+ slug TEXT NOT NULL,
3123
+ title TEXT NOT NULL,
3124
+ visibility TEXT NOT NULL CHECK (visibility IN ('private', 'published')),
3125
+ data TEXT NOT NULL,
3126
+ created_at TEXT NOT NULL,
3127
+ updated_at TEXT NOT NULL,
3128
+ UNIQUE (type, locale, slug)
3129
+ ) WITHOUT ROWID`,
3130
+ `INSERT INTO brim_items_v10 (id, type, locale, translation_of, slug, title, visibility, data, created_at, updated_at)
3131
+ SELECT id, type, '', NULL, slug, title, visibility, data, created_at, updated_at FROM brim_items`,
3132
+ `DROP TABLE brim_items`,
3133
+ `ALTER TABLE brim_items_v10 RENAME TO brim_items`
3134
+ ],
3135
+ [
3136
+ // A third role, "writer"; and what content was before each change, so a change can be taken back.
3137
+ `CREATE TABLE brim_users_v11 (
3138
+ id TEXT PRIMARY KEY,
3139
+ email TEXT NOT NULL UNIQUE,
3140
+ password_hash TEXT NOT NULL,
3141
+ role TEXT NOT NULL CHECK (role IN ('owner', 'editor', 'writer')),
3142
+ created_at TEXT NOT NULL
3143
+ ) WITHOUT ROWID`,
3144
+ `INSERT INTO brim_users_v11 (id, email, password_hash, role, created_at)
3145
+ SELECT id, email, password_hash, role, created_at FROM brim_users`,
3146
+ `DROP TABLE brim_users`,
3147
+ `ALTER TABLE brim_users_v11 RENAME TO brim_users`,
3148
+ `CREATE TABLE brim_history (
3149
+ id TEXT PRIMARY KEY,
3150
+ target TEXT NOT NULL CHECK (target IN ('node', 'item', 'page')),
3151
+ key TEXT NOT NULL,
3152
+ action TEXT NOT NULL CHECK (action IN ('changed', 'reset', 'deleted')),
3153
+ page TEXT NOT NULL,
3154
+ title TEXT NOT NULL,
3155
+ before TEXT,
3156
+ user_email TEXT NOT NULL,
3157
+ created_at TEXT NOT NULL
3158
+ ) WITHOUT ROWID`,
3159
+ `CREATE INDEX brim_history_recent ON brim_history (created_at)`,
3160
+ `CREATE INDEX brim_history_key ON brim_history (target, key, created_at)`
3161
+ ],
3162
+ [
3163
+ // Each item's place among the items of its type, for the types the owner puts in order by hand. Items that
3164
+ // exist keep the order they were added in.
3165
+ `ALTER TABLE brim_items ADD COLUMN position INTEGER NOT NULL DEFAULT 0`,
3166
+ `UPDATE brim_items SET position = (
3167
+ SELECT COUNT(*) FROM brim_items AS earlier
3168
+ WHERE earlier.type = brim_items.type AND earlier.locale = brim_items.locale
3169
+ AND (earlier.created_at < brim_items.created_at
3170
+ OR (earlier.created_at = brim_items.created_at AND earlier.id < brim_items.id))
3171
+ ) + 1`
3172
+ ],
3173
+ [
3174
+ // An image's size, read from its file when it is uploaded, so pages give each <img> its width and height and the
3175
+ // browser keeps its place before it arrives. Images uploaded before are measured later (see image-sizes.ts).
3176
+ `ALTER TABLE brim_media ADD COLUMN width INTEGER`,
3177
+ `ALTER TABLE brim_media ADD COLUMN height INTEGER`
3178
+ ],
3179
+ [
3180
+ // Changes made in the editor that visitors do not see until someone saves them.
3181
+ `CREATE TABLE brim_drafts (
3182
+ target TEXT NOT NULL CHECK (target IN ('node', 'item', 'seo')),
3183
+ key TEXT NOT NULL,
3184
+ value TEXT NOT NULL,
3185
+ page TEXT NOT NULL,
3186
+ updated_at TEXT NOT NULL,
3187
+ PRIMARY KEY (target, key)
3188
+ ) WITHOUT ROWID`
3189
+ ],
3190
+ [
3191
+ // The files a visitor attached to a form message: what they are (id, field, name, type, size). Their bytes are
3192
+ // kept outside the database, in a private place.
3193
+ `ALTER TABLE brim_form_responses ADD COLUMN files TEXT NOT NULL DEFAULT '[]'`
3194
+ ]
3195
+ ];
3196
+ var SCHEMA_VERSION = MIGRATIONS.length;
3197
+ async function migrate(db) {
3198
+ await db.query("CREATE TABLE IF NOT EXISTS brim_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID");
3199
+ const rows = await db.query("SELECT value FROM brim_meta WHERE key = 'schema_version'");
3200
+ const current = Number(rows[0]?.value ?? 0);
3201
+ for (let version = current; version < MIGRATIONS.length; version++) {
3202
+ const statements = MIGRATIONS[version] ?? [];
3203
+ await db.batch([
3204
+ ...statements.map((sql) => ({ sql })),
3205
+ {
3206
+ sql: "INSERT INTO brim_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
3207
+ args: [String(version + 1)]
3208
+ }
3209
+ ]);
3210
+ }
3211
+ }
3212
+
3213
+ // src/runtime/connect.ts
3214
+ var connections = /* @__PURE__ */ new Map();
3215
+ function connect(url, authToken) {
3216
+ let connection = connections.get(url);
3217
+ if (!connection) {
3218
+ connection = (async () => {
3219
+ const opened = openDatabase(url, authToken);
3220
+ await migrate(opened);
3221
+ await ensureChangeTracking(opened);
3222
+ const db = keepingReads(opened);
3223
+ return {
3224
+ db,
3225
+ content: new ContentStore(db),
3226
+ items: new ItemStore(db),
3227
+ forms: new FormStore(db),
3228
+ history: new HistoryStore(db),
3229
+ drafts: new DraftStore(db),
3230
+ accounts: new Accounts(db)
3231
+ };
3232
+ })();
3233
+ connections.set(url, connection);
3234
+ const failed = connection;
3235
+ failed.catch(() => {
3236
+ if (connections.get(url) === failed) connections.delete(url);
3237
+ });
3238
+ }
3239
+ return connection;
3240
+ }
3241
+
3242
+ // src/seed-cli.ts
3243
+ import { existsSync as existsSync4 } from "node:fs";
3244
+ import { mkdir as mkdir3, readFile as readFile3, readdir as readdir2, writeFile as writeFile3 } from "node:fs/promises";
3245
+ import { basename, extname as extname2, join as join5, resolve as resolve2 } from "node:path";
3246
+ var IMAGE_EXTENSIONS2 = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".webp", ".avif", ".gif", ".svg"]);
3247
+ function isLocalSite(url) {
3248
+ try {
3249
+ const { hostname } = new URL(url);
3250
+ return ["localhost", "127.0.0.1", "[::1]", "::1"].includes(hostname) || hostname.endsWith(".localhost");
3251
+ } catch {
3252
+ return false;
3253
+ }
3254
+ }
3255
+ async function readSeed(folder) {
3256
+ if (!existsSync4(folder)) throw new Error(`There is no ${folder} folder. Write the seed as ${folder}/<type>.json.`);
3257
+ const files = (await readdir2(folder)).filter((name) => name.endsWith(".json")).sort();
3258
+ if (files.length === 0) throw new Error(`${folder} has no .json files: write the seed as ${folder}/<type>.json.`);
3259
+ const entries = [];
3260
+ for (const file of files) {
3261
+ let parsed;
3262
+ try {
3263
+ parsed = JSON.parse(await readFile3(join5(folder, file), "utf8"));
3264
+ } catch (error) {
3265
+ throw new Error(`${folder}/${file} is not valid JSON: ${error instanceof Error ? error.message : error}`);
3266
+ }
3267
+ if (!Array.isArray(parsed)) throw new Error(`${folder}/${file} must be a list of items.`);
3268
+ const type = basename(file, ".json");
3269
+ for (const entry of parsed) {
3270
+ entries.push(
3271
+ typeof entry === "object" && entry !== null && !("type" in entry) ? { type, ...entry } : entry
3272
+ );
3273
+ }
3274
+ }
3275
+ return entries;
3276
+ }
3277
+ function isLocalFile(src) {
3278
+ return !/^(\/|[a-z][a-z0-9+.-]*:)/i.test(src) && IMAGE_EXTENSIONS2.has(extname2(src).toLowerCase());
3279
+ }
3280
+ function mapSources(value, change) {
3281
+ if (Array.isArray(value)) return value.map((entry) => mapSources(entry, change));
3282
+ if (typeof value !== "object" || value === null) return value;
3283
+ return Object.fromEntries(
3284
+ Object.entries(value).map(([key, entry]) => [
3285
+ key,
3286
+ key === "src" && typeof entry === "string" ? change(entry) : mapSources(entry, change)
3287
+ ])
3288
+ );
3289
+ }
3290
+ async function call(target, method, path, body) {
3291
+ const response = await fetch(`${target.url}/admin/api${path}`, {
3292
+ method,
3293
+ headers: {
3294
+ authorization: `Bearer ${target.token}`,
3295
+ ...body !== void 0 && { "content-type": "application/json" }
3296
+ },
3297
+ ...body !== void 0 && { body: JSON.stringify(body) }
3298
+ }).catch((error) => {
3299
+ throw new Error(
3300
+ `Could not reach ${target.url} (${error instanceof Error ? error.message : error}). Start the site first (npm run dev), or give its address with --url.`
3301
+ );
3302
+ });
3303
+ const data = await response.json().catch(() => ({}));
3304
+ if (!response.ok) throw new Error(data.error ?? `${method} ${path} answered ${response.status}.`);
3305
+ return data;
3306
+ }
3307
+ async function runSeed(folder, target, dryRun) {
3308
+ const root = resolve2(folder);
3309
+ const entries = await readSeed(root);
3310
+ for (const entry of entries) {
3311
+ mapSources(entry.data, (src) => {
3312
+ if (isLocalFile(src) && !existsSync4(join5(root, src))) throw new Error(`${folder}/${src} does not exist.`);
3313
+ return src;
3314
+ });
3315
+ }
3316
+ const standIns = entries.map((entry) => ({
3317
+ ...entry,
3318
+ data: mapSources(entry.data, (src) => isLocalFile(src) ? `/uploads/seed/${basename(src)}` : src)
3319
+ }));
3320
+ const plan = await call(target, "POST", "/seed", {
3321
+ items: standIns,
3322
+ dryRun: true
3323
+ });
3324
+ if (dryRun || plan.create.length === 0) return { ...plan, uploaded: 0 };
3325
+ const uploaded = /* @__PURE__ */ new Map();
3326
+ const ready = [];
3327
+ for (const { index } of plan.create) {
3328
+ const entry = entries[index];
3329
+ const files = /* @__PURE__ */ new Set();
3330
+ mapSources(entry.data, (src) => (isLocalFile(src) && files.add(src), src));
3331
+ for (const src of files) {
3332
+ if (uploaded.has(src)) continue;
3333
+ const response = await fetch(`${target.url}/admin/api/media`, {
3334
+ method: "POST",
3335
+ headers: {
3336
+ authorization: `Bearer ${target.token}`,
3337
+ "content-type": "application/octet-stream",
3338
+ "x-file-name": encodeURIComponent(basename(src))
3339
+ },
3340
+ body: await readFile3(join5(root, src))
3341
+ });
3342
+ const data = await response.json().catch(() => ({}));
3343
+ if (!response.ok || !data.file) throw new Error(`${folder}/${src}: ${data.error ?? response.status}`);
3344
+ uploaded.set(src, data.file.url);
3345
+ }
3346
+ ready.push({
3347
+ ...entry,
3348
+ data: mapSources(entry.data, (src) => uploaded.get(src) ?? src)
3349
+ });
3350
+ }
3351
+ const result = await call(target, "POST", "/seed", {
3352
+ items: ready
3353
+ });
3354
+ return {
3355
+ create: plan.create,
3356
+ existing: plan.existing,
3357
+ ...result.added && { added: result.added },
3358
+ uploaded: uploaded.size
3359
+ };
3360
+ }
3361
+ async function exportSeedFiles(folder, target, force) {
3362
+ const root = resolve2(folder);
3363
+ const { items } = await call(target, "GET", "/seed");
3364
+ const byType = /* @__PURE__ */ new Map();
3365
+ for (const { type, ...entry } of items) byType.set(type, [...byType.get(type) ?? [], entry]);
3366
+ const files = [...byType.keys()].map((type) => `${type}.json`);
3367
+ const taken = files.filter((file) => existsSync4(join5(root, file)));
3368
+ if (taken.length > 0 && !force) {
3369
+ throw new Error(`${folder} already has ${taken.join(", ")}: add --force to write over them.`);
3370
+ }
3371
+ await mkdir3(join5(root, "images"), { recursive: true });
3372
+ const saved = /* @__PURE__ */ new Map();
3373
+ const names = /* @__PURE__ */ new Set();
3374
+ const copy2 = async (src, name) => {
3375
+ if (!src.startsWith("/uploads/") || saved.has(src)) return;
3376
+ const response = await fetch(`${target.url}${src}`);
3377
+ if (!response.ok) return;
3378
+ const extension = extname2(src).toLowerCase();
3379
+ let file = `${name}${extension}`;
3380
+ for (let count = 2; names.has(file) || existsSync4(join5(root, "images", file)) && !force; count++) {
3381
+ file = `${name}-${count}${extension}`;
3382
+ }
3383
+ names.add(file);
3384
+ await writeFile3(join5(root, "images", file), new Uint8Array(await response.arrayBuffer()));
3385
+ saved.set(src, `images/${file}`);
3386
+ };
3387
+ for (const [type, entries] of byType) {
3388
+ const written = [];
3389
+ for (const entry of entries) {
3390
+ const sources = /* @__PURE__ */ new Set();
3391
+ mapSources(entry.data, (src) => (sources.add(src), src));
3392
+ let count = 0;
3393
+ for (const src of sources)
3394
+ await copy2(src, count++ === 0 ? entry.slug ?? type : `${entry.slug ?? type}-${count}`);
3395
+ written.push({
3396
+ ...entry,
3397
+ data: mapSources(entry.data, (src) => saved.get(src) ?? src)
3398
+ });
3399
+ }
3400
+ await writeFile3(join5(root, `${type}.json`), `${JSON.stringify(written, null, 2)}
3401
+ `);
3402
+ }
3403
+ return { files, items: items.length, images: saved.size };
3404
+ }
3405
+ async function contentFindings(target) {
3406
+ return (await call(target, "GET", "/check/content")).findings;
3407
+ }
3408
+ function formatContentFindings(findings) {
3409
+ if (findings.length === 0) return "Content: nothing left from testing, no unused terms, every page in the sitemap.";
3410
+ const titles = {
3411
+ placeholder: "Values left from testing or a template",
3412
+ "empty-term": "Terms nothing uses",
3413
+ "unlisted-pages": "Pages missing from the sitemap"
3414
+ };
3415
+ const lines = [`Content: ${findings.length} warning(s).`];
3416
+ for (const rule of Object.keys(titles)) {
3417
+ const group = findings.filter((finding) => finding.rule === rule);
3418
+ if (group.length === 0) continue;
3419
+ lines.push("", `${titles[rule]}:`);
3420
+ for (const finding of group) lines.push(` ${finding.where}`, ` ${finding.message}`);
3421
+ }
3422
+ return lines.join("\n");
3423
+ }
3424
+
3425
+ // src/cli.ts
3426
+ var USAGE = `Usage:
3427
+ brim init [--brim <version>] [--lang <code>] [--no-git]
3428
+ Set up Brim.js in an Astro project that already exists: the
3429
+ dependency, the integration, the site's language (--lang, else the
3430
+ layout's <html lang>, else en), the conversion guide for AI agents,
3431
+ and git (git init, nothing committed) unless it is in git already.
3432
+ brim start Run the site built by \`astro build\`: pages, /admin and forms.
3433
+ Listens on HOST and PORT (default 0.0.0.0:4321).
3434
+ brim check [folder] [--json] Read the site's source for duplicate or positional nodeIds and files
3435
+ left unchanged from the starter. Exits with 1 when there are errors.
3436
+ brim check --content Also read the running site's content: values left from testing
3437
+ (lorem ipsum, example.com, 0000000), terms nothing uses, and
3438
+ dynamic pages missing from the sitemap. Warnings only.
3439
+ brim info [--json] What the site's database holds: users, pages, items, media.
3440
+ brim seed [folder] [--dry-run] Add the site's starting content from seed/<type>.json (pictures in
3441
+ seed/images/) to the running dev server. Only adds what the site
3442
+ does not have yet; never changes or deletes anything. Everything is
3443
+ checked first, and one mistake adds nothing.
3444
+ brim seed --export [folder] [--force] Write the site's items into seed/<type>.json, with their pictures,
3445
+ to keep in git as its starting content.
3446
+ Both take --url <site> --token <token> for a site elsewhere.
3447
+ brim content [path] [--json] What the owner saved on a page (/ by default) and on the whole
3448
+ site (header, footer, settings): each element's nodeId, kind and
3449
+ value. Read it before changing a page's code. On Brimsites:
3450
+ brimsites content <site> [path].
3451
+ brim content --all [--json] Every place with saved content (pages, templates of item pages,
3452
+ the site), with how many elements each.
3453
+ brim media add <file>... [--item <type>/<id>] Put images into the site's media library (public/uploads), where
3454
+ the owner finds them, and print their /uploads addresses.
3455
+ brim open [email] [--page /path] [--url <site>]
3456
+ Open the editor in the browser, already signed in (a one-time link),
3457
+ on the dev server (http://localhost:4321) unless --url names the site.
3458
+ brim user add <email> [--role <role>] Create a user who can sign in at /admin.
3459
+ The password is asked for, or read from stdin.
3460
+ brim user list [--json] List users with their role and number of tokens.
3461
+ brim user role <email> <role> Change a user's role: owner (everything) or editor (writes, publishes,
3462
+ adds pages, reads forms).
3463
+ brim user password <email> Set a new password (asked for, or read from stdin).
3464
+ Ends their sessions and access tokens.
3465
+ brim user link <email> Print a link that signs the user in once, within two minutes,
3466
+ without their password.
3467
+ brim user remove <email> Delete a user with their sessions and tokens.
3468
+ brim token add <email> [--name <name>] Create an access token for the site's MCP (/admin/mcp).
3469
+ It acts as that user and is shown only once.
3470
+ brim token list <email> List a user's tokens.
3471
+ brim token revoke <email> <name> Delete a token; clients using it stop working.`;
3472
+ async function main(args) {
3473
+ const [group, command] = args;
3474
+ const takesValue = (arg) => !!arg?.startsWith("--") && arg !== "--json";
3475
+ const email = args.slice(2).find((arg, index, rest) => !arg.startsWith("--") && !takesValue(rest[index - 1]));
3476
+ const json = args.includes("--json");
3477
+ if (group === "start") return start();
3478
+ if (group === "init") return setUp(option(args, "--brim"), !args.includes("--no-git"), option(args, "--lang"));
3479
+ if (group === "check") return check(command && !command.startsWith("--") ? command : ".", json, args);
3480
+ if (group === "info") return info(json);
3481
+ if (group === "content") return content(command && !command.startsWith("--") ? command : "/", args, json);
3482
+ if (group === "user" && command === "list") return listUsers(json);
3483
+ if (group === "media" && command === "add") return addMedia(args.slice(2), json);
3484
+ if (group === "open") return openEditor(args.slice(1));
3485
+ if (group === "seed") return seed(args.slice(1));
3486
+ if (!email) throw new Error(USAGE);
3487
+ if (group === "user" && command === "add") return addUser(email, args);
3488
+ if (group === "user" && command === "role" && args[3]) return setRole(email, args[3]);
3489
+ if (group === "user" && command === "password") return setPassword(email);
3490
+ if (group === "user" && command === "link") return signInLink(email);
3491
+ if (group === "user" && command === "remove") return removeUser(email);
3492
+ if (group === "token" && command === "add") return addToken(email, option(args, "--name") ?? "mcp");
3493
+ if (group === "token" && command === "list") return listTokens(email);
3494
+ if (group === "token" && command === "revoke" && args[3]) return revokeToken(email, args[3]);
3495
+ throw new Error(USAGE);
3496
+ }
3497
+ async function setUp(brim, git, lang) {
3498
+ const agent = process.env.npm_config_user_agent ?? "";
3499
+ const runner = agent.startsWith("pnpm") ? "pnpm" : agent.startsWith("yarn") ? "yarn" : agent.startsWith("bun") ? "bun" : "npm";
3500
+ console.log(initReport(await init(process.cwd(), { brim, git, lang }), runner));
3501
+ }
3502
+ async function start() {
3503
+ const entry = join6(process.cwd(), "dist", "server", "entry.mjs");
3504
+ if (!existsSync5(entry)) {
3505
+ throw new Error(
3506
+ "There is no built server in dist/server. Run `astro build` first; a static build (BRIM_OUTPUT=static) has no server to start."
3507
+ );
3508
+ }
3509
+ process.env.HOST ??= "0.0.0.0";
3510
+ await import(pathToFileURL(entry).href);
3511
+ console.log(`Editor: http://localhost:${process.env.PORT ?? 4321}/admin/edit (or npx brim open, already signed in)`);
3512
+ }
3513
+ async function check(folder, json, args) {
3514
+ const report = checkSite(folder);
3515
+ if (!args.includes("--content")) {
3516
+ console.log(json ? JSON.stringify(report, null, 2) : formatReport(report));
3517
+ if (report.errors > 0) process.exitCode = 1;
3518
+ return;
3519
+ }
3520
+ const url = (option(args, "--url") ?? `http://localhost:${process.env.PORT ?? 4321}`).replace(/\/+$/, "");
3521
+ await asSiteOwner(args, url, option(args, "--token") ?? process.env.BRIM_TOKEN, "check --content", async (target) => {
3522
+ const content2 = await contentFindings(target);
3523
+ if (json) {
3524
+ console.log(JSON.stringify({ ...report, content: content2 }, null, 2));
3525
+ } else {
3526
+ console.log(formatReport(report));
3527
+ console.log("");
3528
+ console.log(formatContentFindings(content2));
3529
+ }
3530
+ if (report.errors > 0) process.exitCode = 1;
3531
+ });
3532
+ }
3533
+ async function info(json) {
3534
+ await withSite(async ({ db, accounts }) => {
3535
+ const count = async (table) => Number((await db.query(`SELECT COUNT(*) AS n FROM ${table}`))[0]?.n ?? 0);
3536
+ const items = await db.query("SELECT type, COUNT(*) AS n FROM brim_items GROUP BY type ORDER BY type");
3537
+ const summary = {
3538
+ users: (await accounts.listUsers()).map(({ email, role, createdAt, tokens }) => ({
3539
+ email,
3540
+ role,
3541
+ createdAt,
3542
+ tokens
3543
+ })),
3544
+ pages: await count("brim_pages"),
3545
+ editedElements: await count("brim_nodes"),
3546
+ items: Object.fromEntries(items.map((row) => [String(row.type), Number(row.n)])),
3547
+ media: await count("brim_media"),
3548
+ formResponses: await count("brim_form_responses")
3549
+ };
3550
+ if (json) return console.log(JSON.stringify(summary, null, 2));
3551
+ console.log(`Users ${summary.users.map((user) => `${user.email} (${user.role})`).join(", ") || "none"}`);
3552
+ console.log(`Pages ${summary.pages}`);
3553
+ console.log(`Edited elements ${summary.editedElements}`);
3554
+ console.log(
3555
+ `Items ${Object.entries(summary.items).map(([type, n]) => `${type} ${n}`).join(", ") || "none"}`
3556
+ );
3557
+ console.log(`Uploaded images ${summary.media}`);
3558
+ console.log(`Form responses ${summary.formResponses}`);
3559
+ });
3560
+ }
3561
+ async function content(path, args, json) {
3562
+ await withSite(async (brim) => {
3563
+ if (args.includes("--all")) {
3564
+ const rows = await brim.db.query("SELECT scope, COUNT(*) AS n FROM brim_nodes GROUP BY scope ORDER BY scope");
3565
+ const places = rows.map((row) => ({ scope: String(row.scope), elements: Number(row.n) }));
3566
+ if (json) return console.log(JSON.stringify(places, null, 2));
3567
+ if (places.length === 0) return console.log("Nothing saved in the editor yet: every page shows its code's words.");
3568
+ for (const { scope, elements } of places) console.log(`${scope.padEnd(48)} ${elements}`);
3569
+ return;
3570
+ }
3571
+ const page = pageScope(path);
3572
+ const nodes = await brim.content.loadNodes([page, siteScope()]);
3573
+ const of = (scope) => nodes.filter((node) => node.scope === scope).map(({ nodeId, kind, value }) => ({ nodeId, kind, value })).sort((a, b) => a.nodeId.localeCompare(b.nodeId));
3574
+ const saved = { path: normalizePagePath(path), page: of(page), site: of(siteScope()) };
3575
+ if (json) return console.log(JSON.stringify(saved, null, 2));
3576
+ const show = (value) => {
3577
+ const text2 = typeof value === "string" ? value : JSON.stringify(value);
3578
+ return text2.length > 100 ? `${text2.slice(0, 97)}\u2026` : text2;
3579
+ };
3580
+ for (const [title, list] of [[`Page ${saved.path}`, saved.page], ["Whole site", saved.site]]) {
3581
+ console.log(`${title}: ${list.length === 0 ? "nothing saved" : `${list.length} saved`}`);
3582
+ for (const node of list) console.log(` ${node.nodeId.padEnd(32)} ${node.kind.padEnd(10)} ${show(node.value)}`);
3583
+ }
3584
+ });
3585
+ }
3586
+ async function listUsers(json) {
3587
+ await withSite(async ({ accounts }) => {
3588
+ const users = await accounts.listUsers();
3589
+ if (json)
3590
+ return console.log(
3591
+ JSON.stringify(
3592
+ users.map(({ id: _id, ...user }) => user),
3593
+ null,
3594
+ 2
3595
+ )
3596
+ );
3597
+ if (users.length === 0) return console.log("No users yet. Add one with: brim user add <email>");
3598
+ for (const user of users) {
3599
+ console.log(
3600
+ `${user.email.padEnd(32)} ${user.role.padEnd(7)} tokens ${user.tokens} since ${user.createdAt.slice(0, 10)}`
3601
+ );
3602
+ }
3603
+ });
3604
+ }
3605
+ async function setRole(email, role) {
3606
+ if (!ROLES.includes(role)) throw new Error(USAGE);
3607
+ await withSite(async ({ accounts }) => {
3608
+ const user = await accounts.setRole(email, role);
3609
+ console.log(`${user.email} is now ${user.role}.`);
3610
+ });
3611
+ }
3612
+ async function signInLink(email) {
3613
+ await withSite(async ({ accounts }) => {
3614
+ const { token, maxAgeSeconds } = await accounts.createSignInToken(email);
3615
+ console.log(`Open this on the site within ${maxAgeSeconds / 60} minutes; it works once:`);
3616
+ console.log(`/admin/api/session/link?token=${token}`);
3617
+ });
3618
+ }
3619
+ async function setPassword(email) {
3620
+ const password = await readPassword();
3621
+ await withSite(async ({ accounts }) => {
3622
+ await accounts.setPassword(email, password);
3623
+ console.log(
3624
+ `Changed the password of ${email}; their open sessions were signed out and their access tokens revoked.`
3625
+ );
3626
+ });
3627
+ }
3628
+ async function removeUser(email) {
3629
+ await withSite(async ({ accounts }) => {
3630
+ await accounts.removeUser(email);
3631
+ console.log(`Removed ${email} with their sessions and tokens.`);
3632
+ });
3633
+ }
3634
+ async function addUser(email, args) {
3635
+ const role = option(args, "--role") ?? "owner";
3636
+ if (!ROLES.includes(role)) throw new Error(USAGE);
3637
+ const password = await readPassword();
3638
+ await withSite(async ({ accounts }) => {
3639
+ const user = await accounts.createUser(email, password, role);
3640
+ console.log(`Created ${user.role} ${user.email}.`);
3641
+ console.log(`Open the editor, signed in: npx brim open ${user.email} (with the dev server running)`);
3642
+ console.log(`To let them in without passing the password around: npx brim user link ${user.email}`);
3643
+ });
3644
+ }
3645
+ async function addToken(email, name) {
3646
+ await withSite(async ({ accounts }) => {
3647
+ const token = await accounts.createToken(email, name);
3648
+ console.log(`Created the token "${name}" for ${email}. It is shown only this once:
3649
+
3650
+ ${token}
3651
+
3652
+ Give it to an MCP client as a bearer token for <site>/admin/mcp, for example:
3653
+
3654
+ claude mcp add --transport http my-site http://localhost:4321/admin/mcp \\
3655
+ --header "Authorization: Bearer ${token}"`);
3656
+ });
3657
+ }
3658
+ async function listTokens(email) {
3659
+ await withSite(async ({ accounts }) => {
3660
+ const tokens = await accounts.listTokens(email);
3661
+ if (tokens.length === 0) return console.log(`${email} has no tokens.`);
3662
+ for (const token of tokens) {
3663
+ console.log(`${token.name} created ${token.createdAt} last used ${token.lastUsedAt ?? "never"}`);
3664
+ }
3665
+ });
3666
+ }
3667
+ async function revokeToken(email, name) {
3668
+ await withSite(async ({ accounts }) => {
3669
+ const removed = await accounts.revokeToken(email, name);
3670
+ console.log(removed ? `Revoked the token "${name}".` : `${email} has no token named "${name}".`);
3671
+ });
3672
+ }
3673
+ async function addMedia(args, json) {
3674
+ const folder = option(args, "--item") ?? "";
3675
+ const files = args.filter((arg, index) => !arg.startsWith("--") && args[index - 1] !== "--item");
3676
+ if (files.length === 0) throw new Error(USAGE);
3677
+ await withSite(async (brim) => {
3678
+ if (folder) {
3679
+ const [type, id, ...rest] = folder.split("/");
3680
+ const item = id && rest.length === 0 ? await brim.items.get(id) : void 0;
3681
+ if (!item || item.type !== type) throw new Error(`There is no ${type ?? "item"} with the id ${id ?? folder}.`);
3682
+ }
3683
+ const store = new MediaStore(brim.db, pathToFileURL(join6(process.cwd(), "public", "uploads") + "/"));
3684
+ const added = [];
3685
+ for (const file of files) {
3686
+ const uploaded = await store.upload(new Uint8Array(await readFile4(file)), basename2(file), folder);
3687
+ added.push({ file, url: uploaded.url });
3688
+ if (!json) console.log(`${file} \u2192 ${uploaded.url}`);
3689
+ }
3690
+ if (json) console.log(JSON.stringify(added, null, 2));
3691
+ });
3692
+ }
3693
+ async function openEditor(args) {
3694
+ const page = option(args, "--page") ?? "/";
3695
+ const base = (option(args, "--url") ?? `http://localhost:${process.env.PORT ?? 4321}`).replace(/\/+$/, "");
3696
+ const given = args.find(
3697
+ (arg, index) => !arg.startsWith("--") && !["--page", "--url"].includes(args[index - 1] ?? "")
3698
+ );
3699
+ await withSite(async ({ accounts }) => {
3700
+ const email = given ?? (await accounts.listUsers()).find((user) => user.role === "owner")?.email;
3701
+ if (!email) throw new Error("The site has no user yet: npx brim user add you@example.com, then npx brim open.");
3702
+ const { token } = await accounts.createSignInToken(email);
3703
+ const editor = `/admin/edit${page === "/" ? "" : `/${page.replace(/^\/+/, "")}`}`;
3704
+ const link = `${base}/admin/api/session/link?token=${token}&to=${encodeURIComponent(editor)}`;
3705
+ console.log(`Opening the editor as ${email}. If no browser opens, open this within 2 minutes (it works once):`);
3706
+ console.log(link);
3707
+ openInBrowser(link);
3708
+ });
3709
+ }
3710
+ async function seed(args) {
3711
+ const values = ["--url", "--token"];
3712
+ const folder = args.find((arg, index) => !arg.startsWith("--") && !values.includes(args[index - 1] ?? "")) ?? "seed";
3713
+ const url = (option(args, "--url") ?? `http://localhost:${process.env.PORT ?? 4321}`).replace(/\/+$/, "");
3714
+ const token = option(args, "--token") ?? process.env.BRIM_TOKEN;
3715
+ const exporting = args.includes("--export");
3716
+ const work = async (target) => {
3717
+ if (exporting) {
3718
+ const done = await exportSeedFiles(folder, target, args.includes("--force"));
3719
+ console.log(
3720
+ `Wrote ${done.items} item(s) into ${done.files.map((file) => `${folder}/${file}`).join(", ") || "nothing"}, with ${done.images} picture(s) in ${folder}/images/.`
3721
+ );
3722
+ return;
3723
+ }
3724
+ const dryRun = args.includes("--dry-run");
3725
+ const result = await runSeed(folder, target, dryRun);
3726
+ const label = (entry) => `${entry.type}/${entry.slug}${entry.locale ? ` (${entry.locale})` : ""}`;
3727
+ if (result.create.length === 0) {
3728
+ console.log(`Nothing to add: the site already has all ${result.existing.length} item(s) of ${folder}/.`);
3729
+ return;
3730
+ }
3731
+ console.log(
3732
+ `${dryRun ? "Would add" : "Added"} ${result.create.length} item(s)` + (dryRun ? "" : `, with ${result.uploaded} picture(s)`) + `; ${result.existing.length} already there, left as they are.`
3733
+ );
3734
+ for (const entry of result.create) console.log(` + ${label(entry)} ${entry.title}`);
3735
+ if (dryRun) console.log("Nothing was written. Run it without --dry-run to add them.");
3736
+ };
3737
+ await asSiteOwner(args, url, token, "seed", work);
3738
+ }
3739
+ async function asSiteOwner(args, url, token, command, work) {
3740
+ if (token) return work({ url, token });
3741
+ if (!isLocalSite(url)) {
3742
+ throw new Error(
3743
+ `${url} is not on this computer: give a token for it with --token (npx brim token add <email> on that site).`
3744
+ );
3745
+ }
3746
+ const database = resolveDatabase({}, process.cwd());
3747
+ if (!database.databaseUrl.startsWith("file:") && !args.includes("--remote")) {
3748
+ throw new Error(
3749
+ `The database set up here (BRIM_DATABASE_URL) is not on this computer, so it may be the live site's. Add --remote if you mean brim ${command} to use it.`
3750
+ );
3751
+ }
3752
+ await withSite(async ({ accounts }) => {
3753
+ const owner = (await accounts.listUsers()).find((user) => user.role === "owner");
3754
+ if (!owner)
3755
+ throw new Error(`The site has no owner yet: npx brim user add you@example.com, then npx brim ${command}.`);
3756
+ const name = `brim ${command} ${Date.now()}`;
3757
+ const created = await accounts.createToken(owner.email, name);
3758
+ try {
3759
+ await work({ url, token: created });
3760
+ } finally {
3761
+ await accounts.revokeToken(owner.email, name);
3762
+ }
3763
+ });
3764
+ }
3765
+ function openInBrowser(address) {
3766
+ const [command, ...args] = process.platform === "darwin" ? ["open", address] : process.platform === "win32" ? ["cmd", "/c", "start", "", address] : ["xdg-open", address];
3767
+ try {
3768
+ spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => void 0).unref();
3769
+ } catch {
3770
+ }
3771
+ }
3772
+ async function withSite(run) {
3773
+ const database = resolveDatabase({}, process.cwd());
3774
+ const brim = await connect(database.databaseUrl, database.authToken);
3775
+ try {
3776
+ await run(brim);
3777
+ } finally {
3778
+ brim.db.close();
3779
+ }
3780
+ }
3781
+ function option(args, name) {
3782
+ const index = args.indexOf(name);
3783
+ return index === -1 ? void 0 : args[index + 1];
3784
+ }
3785
+ async function readPassword() {
3786
+ if (!process.stdin.isTTY) {
3787
+ let piped = "";
3788
+ for await (const chunk of process.stdin) piped += chunk;
3789
+ return piped.replace(/\r?\n$/, "");
3790
+ }
3791
+ const silent = new Writable({ write: (_chunk, _encoding, done) => done() });
3792
+ const prompt = createInterface({ input: process.stdin, output: silent, terminal: true });
3793
+ process.stdout.write("Password: ");
3794
+ const password = await prompt.question("");
3795
+ prompt.close();
3796
+ process.stdout.write("\n");
3797
+ return password;
3798
+ }
3799
+ main(process.argv.slice(2)).catch((error) => {
3800
+ console.error(error instanceof Error ? error.message : error);
3801
+ process.exitCode = 1;
3802
+ });