@brimsites/brimjs 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +22 -2
  3. package/bin/brim.js +5 -0
  4. package/dist/cli.js +3802 -0
  5. package/editor-dist/editor.css +1 -0
  6. package/editor-dist/editor.js +91 -0
  7. package/package.json +71 -3
  8. package/skills/brim-convert/SKILL.md +256 -0
  9. package/skills/brim-hosting/SKILL.md +221 -0
  10. package/src/astro-shim.d.ts +5 -0
  11. package/src/auth/accounts.ts +341 -0
  12. package/src/auth/password.ts +34 -0
  13. package/src/auth/permissions.ts +44 -0
  14. package/src/blocks/accordion/Accordion.astro +48 -0
  15. package/src/blocks/accordion/accordion.css +63 -0
  16. package/src/blocks/analytics/Analytics.astro +45 -0
  17. package/src/blocks/analytics/ConsentBanner.astro +41 -0
  18. package/src/blocks/analytics/analytics.client.ts +125 -0
  19. package/src/blocks/analytics/analytics.css +51 -0
  20. package/src/blocks/analytics/consent.ts +51 -0
  21. package/src/blocks/button/Button.astro +64 -0
  22. package/src/blocks/button/button.css +100 -0
  23. package/src/blocks/carousel/Carousel.astro +140 -0
  24. package/src/blocks/carousel/carousel.client.ts +153 -0
  25. package/src/blocks/carousel/carousel.css +181 -0
  26. package/src/blocks/data/icons.ts +285 -0
  27. package/src/blocks/data/image-shapes.ts +91 -0
  28. package/src/blocks/data/social-icons.ts +41 -0
  29. package/src/blocks/data/social-networks.ts +256 -0
  30. package/src/blocks/divider/Divider.astro +27 -0
  31. package/src/blocks/divider/divider.css +17 -0
  32. package/src/blocks/form/Captcha.astro +27 -0
  33. package/src/blocks/form/Form.astro +250 -0
  34. package/src/blocks/form/FormField.astro +138 -0
  35. package/src/blocks/form/Newsletter.astro +80 -0
  36. package/src/blocks/form/form.client.ts +339 -0
  37. package/src/blocks/form/form.css +271 -0
  38. package/src/blocks/gallery/ImageGallery.astro +126 -0
  39. package/src/blocks/gallery/gallery.css +43 -0
  40. package/src/blocks/gallery/lightbox.client.ts +178 -0
  41. package/src/blocks/gallery/lightbox.css +134 -0
  42. package/src/blocks/icon/Icon.astro +41 -0
  43. package/src/blocks/icon/icon.css +16 -0
  44. package/src/blocks/image/Image.astro +158 -0
  45. package/src/blocks/image/image.css +42 -0
  46. package/src/blocks/images.ts +64 -0
  47. package/src/blocks/in-editor.client.ts +8 -0
  48. package/src/blocks/listing/Listing.astro +288 -0
  49. package/src/blocks/listing/ListingCards.astro +48 -0
  50. package/src/blocks/listing/listing.css +136 -0
  51. package/src/blocks/listing/query.ts +363 -0
  52. package/src/blocks/map/Map.astro +75 -0
  53. package/src/blocks/map/map.css +32 -0
  54. package/src/blocks/schemas/accordion.ts +118 -0
  55. package/src/blocks/schemas/button.ts +78 -0
  56. package/src/blocks/schemas/carousel.ts +133 -0
  57. package/src/blocks/schemas/divider.ts +29 -0
  58. package/src/blocks/schemas/form-field-types.ts +29 -0
  59. package/src/blocks/schemas/form.ts +350 -0
  60. package/src/blocks/schemas/icon.ts +24 -0
  61. package/src/blocks/schemas/image-gallery.ts +54 -0
  62. package/src/blocks/schemas/image.ts +87 -0
  63. package/src/blocks/schemas/index.ts +33 -0
  64. package/src/blocks/schemas/listing.ts +14 -0
  65. package/src/blocks/schemas/map.ts +81 -0
  66. package/src/blocks/schemas/newsletter.ts +324 -0
  67. package/src/blocks/schemas/social-media.ts +348 -0
  68. package/src/blocks/schemas/text.ts +151 -0
  69. package/src/blocks/schemas/video.ts +57 -0
  70. package/src/blocks/search/Search.astro +147 -0
  71. package/src/blocks/search/search.css +69 -0
  72. package/src/blocks/search/state.ts +28 -0
  73. package/src/blocks/settings.ts +94 -0
  74. package/src/blocks/social/SocialMedia.astro +102 -0
  75. package/src/blocks/social/social-links.ts +16 -0
  76. package/src/blocks/social/social.css +31 -0
  77. package/src/blocks/theme.ts +35 -0
  78. package/src/blocks/types.ts +52 -0
  79. package/src/blocks/video/Video.astro +90 -0
  80. package/src/blocks/video/video-source.ts +77 -0
  81. package/src/blocks/video/video.client.ts +43 -0
  82. package/src/blocks/video/video.css +29 -0
  83. package/src/check.ts +1119 -0
  84. package/src/cli.ts +493 -0
  85. package/src/components/Blocks.astro +68 -0
  86. package/src/components/Field.astro +61 -0
  87. package/src/components/Footer.astro +36 -0
  88. package/src/components/Link.astro +18 -0
  89. package/src/components/MobileMenu.astro +77 -0
  90. package/src/components/Navbar.astro +42 -0
  91. package/src/components/RichText.astro +32 -0
  92. package/src/components/Seo.astro +202 -0
  93. package/src/components/Setting.astro +46 -0
  94. package/src/components/Shared.astro +17 -0
  95. package/src/components/Text.astro +91 -0
  96. package/src/components/blocks.css +86 -0
  97. package/src/components/index.ts +27 -0
  98. package/src/components/mobile-menu.client.ts +21 -0
  99. package/src/components/mobile-menu.css +52 -0
  100. package/src/components/text.css +48 -0
  101. package/src/config.ts +413 -0
  102. package/src/content/block-layout.ts +63 -0
  103. package/src/content/block-values.ts +48 -0
  104. package/src/content/content-check.ts +174 -0
  105. package/src/content/content-types.ts +408 -0
  106. package/src/content/drafts.ts +115 -0
  107. package/src/content/feed.ts +237 -0
  108. package/src/content/field-types.ts +107 -0
  109. package/src/content/history.ts +140 -0
  110. package/src/content/ids.ts +50 -0
  111. package/src/content/image-size.ts +212 -0
  112. package/src/content/image-sizes.ts +126 -0
  113. package/src/content/item-fields.ts +110 -0
  114. package/src/content/item-head.ts +126 -0
  115. package/src/content/item-image.ts +26 -0
  116. package/src/content/item-path.ts +122 -0
  117. package/src/content/items.ts +580 -0
  118. package/src/content/language-scopes.ts +40 -0
  119. package/src/content/media.ts +271 -0
  120. package/src/content/menus.ts +51 -0
  121. package/src/content/page-templates.ts +52 -0
  122. package/src/content/redirects.ts +112 -0
  123. package/src/content/references.ts +165 -0
  124. package/src/content/rich-text.ts +63 -0
  125. package/src/content/search.ts +167 -0
  126. package/src/content/seed.ts +229 -0
  127. package/src/content/site-settings.ts +111 -0
  128. package/src/content/sitemap.ts +143 -0
  129. package/src/content/store.ts +225 -0
  130. package/src/content/tags.ts +67 -0
  131. package/src/content/text-default.ts +139 -0
  132. package/src/content/types.ts +137 -0
  133. package/src/content/validate.ts +253 -0
  134. package/src/content/validation-error.ts +2 -0
  135. package/src/db/cached.ts +140 -0
  136. package/src/db/database.ts +15 -0
  137. package/src/db/libsql.ts +29 -0
  138. package/src/db/schema.ts +189 -0
  139. package/src/db/url.ts +44 -0
  140. package/src/editor/client/BlockSettings.tsx +1063 -0
  141. package/src/editor/client/Chrome.tsx +284 -0
  142. package/src/editor/client/ContentBrowser.tsx +1299 -0
  143. package/src/editor/client/Editor.tsx +1756 -0
  144. package/src/editor/client/HistoryPanel.tsx +114 -0
  145. package/src/editor/client/ImagesWidget.tsx +113 -0
  146. package/src/editor/client/Inspector.tsx +127 -0
  147. package/src/editor/client/ItemForm.tsx +535 -0
  148. package/src/editor/client/LinkWidget.tsx +440 -0
  149. package/src/editor/client/ListingPanel.tsx +99 -0
  150. package/src/editor/client/Login.tsx +338 -0
  151. package/src/editor/client/Menu.tsx +64 -0
  152. package/src/editor/client/PageSettings.tsx +270 -0
  153. package/src/editor/client/RedirectsSettings.tsx +130 -0
  154. package/src/editor/client/Resize.tsx +204 -0
  155. package/src/editor/client/Sidebar.tsx +51 -0
  156. package/src/editor/client/SiteMap.tsx +568 -0
  157. package/src/editor/client/SiteSettings.tsx +409 -0
  158. package/src/editor/client/TextTools.tsx +391 -0
  159. package/src/editor/client/Toolbar.tsx +449 -0
  160. package/src/editor/client/VideoUpload.tsx +251 -0
  161. package/src/editor/client/api.ts +417 -0
  162. package/src/editor/client/brand.ts +20 -0
  163. package/src/editor/client/connection.ts +98 -0
  164. package/src/editor/client/context.ts +19 -0
  165. package/src/editor/client/css.d.ts +2 -0
  166. package/src/editor/client/editor.css +4656 -0
  167. package/src/editor/client/fields.tsx +812 -0
  168. package/src/editor/client/icons.tsx +174 -0
  169. package/src/editor/client/keys.ts +15 -0
  170. package/src/editor/client/kinds.ts +289 -0
  171. package/src/editor/client/languages.ts +32 -0
  172. package/src/editor/client/main.tsx +100 -0
  173. package/src/editor/client/responses.ts +26 -0
  174. package/src/editor/client/rich-text.ts +326 -0
  175. package/src/editor/client/site-tree.ts +239 -0
  176. package/src/editor/client/theme.ts +55 -0
  177. package/src/editor/client/tsconfig.json +18 -0
  178. package/src/editor/client/tus.ts +137 -0
  179. package/src/editor/client/use-rect.ts +50 -0
  180. package/src/editor/client/widgets.tsx +1218 -0
  181. package/src/forms/captcha.ts +83 -0
  182. package/src/forms/define.ts +166 -0
  183. package/src/forms/fields.ts +197 -0
  184. package/src/forms/file-types.ts +108 -0
  185. package/src/forms/files.ts +216 -0
  186. package/src/forms/form-page.ts +9 -0
  187. package/src/forms/handler.ts +622 -0
  188. package/src/forms/spec.ts +89 -0
  189. package/src/forms/store.ts +96 -0
  190. package/src/forms/work.ts +50 -0
  191. package/src/icons/library.ts +144 -0
  192. package/src/icons/load.ts +63 -0
  193. package/src/index.ts +99 -0
  194. package/src/init.ts +257 -0
  195. package/src/integration.ts +469 -0
  196. package/src/mail/mailer.ts +197 -0
  197. package/src/mail/notify.ts +272 -0
  198. package/src/mail/settings.ts +173 -0
  199. package/src/mail/templates.ts +191 -0
  200. package/src/mcp/page-nodes.ts +209 -0
  201. package/src/mcp/server.ts +111 -0
  202. package/src/mcp/tools.ts +637 -0
  203. package/src/runtime/TemplatePage.astro +39 -0
  204. package/src/runtime/TemplatePageStatic.astro +13 -0
  205. package/src/runtime/admin-route.ts +80 -0
  206. package/src/runtime/connect.ts +53 -0
  207. package/src/runtime/content.ts +188 -0
  208. package/src/runtime/context.ts +131 -0
  209. package/src/runtime/form-files.ts +18 -0
  210. package/src/runtime/forms-route.ts +33 -0
  211. package/src/runtime/forms.ts +28 -0
  212. package/src/runtime/icons.ts +5 -0
  213. package/src/runtime/media.ts +175 -0
  214. package/src/runtime/middleware.ts +186 -0
  215. package/src/runtime/nav.ts +13 -0
  216. package/src/runtime/query-reads.ts +49 -0
  217. package/src/runtime/query-store.ts +16 -0
  218. package/src/runtime/request-state.ts +69 -0
  219. package/src/runtime/robots.ts +29 -0
  220. package/src/runtime/rss-static.ts +16 -0
  221. package/src/runtime/rss.ts +29 -0
  222. package/src/runtime/server.ts +29 -0
  223. package/src/runtime/sitemap.ts +34 -0
  224. package/src/runtime/template-paths.ts +34 -0
  225. package/src/runtime/uploads-route.ts +13 -0
  226. package/src/seed-cli.ts +253 -0
  227. package/src/server/auth.ts +31 -0
  228. package/src/server/fetch-image.ts +219 -0
  229. package/src/server/handler.ts +2106 -0
  230. package/src/server/http.ts +162 -0
  231. package/src/server/locales.ts +73 -0
  232. package/src/server/node.ts +57 -0
  233. package/src/server/query-params.ts +249 -0
  234. package/src/server/rate-limit.ts +72 -0
  235. package/src/server/video-host.ts +162 -0
  236. package/src/starter.ts +70 -0
  237. package/src/version.ts +4 -0
  238. package/src/virtual.d.ts +65 -0
@@ -0,0 +1,34 @@
1
+ import config from "virtual:brim/config";
2
+ import type { TemplatePageProps } from "../content/page-templates.ts";
3
+ import { connect } from "./connect.ts";
4
+ import { getItems } from "./content.ts";
5
+ import { isEditing } from "./request-state.ts";
6
+
7
+ /**
8
+ * The pages of a static build's template route: one per page the owner added from a template, and one per item of
9
+ * a content type that has a template, in every language. The server has none: it looks a page up on each request.
10
+ */
11
+ export async function templateStaticPaths() {
12
+ const { content } = await connect(config.databaseUrl, config.authToken);
13
+ const pages = await content.templatePages({ publishedOnly: !isEditing() });
14
+ const added = pages.flatMap((page) => {
15
+ const template = config.pageTemplates.find((candidate) => candidate.key === page.template);
16
+ // A page whose template was removed from the code has nothing to draw it; it waits until it is back.
17
+ if (!template) return [];
18
+ const props: TemplatePageProps = { path: page.path, title: page.title ?? "", template: template.key };
19
+ return [
20
+ { params: { page: page.path.slice(1) }, props: { pageProps: { page: props }, component: template.component } },
21
+ ];
22
+ });
23
+ const items = await Promise.all(
24
+ config.contentTypes
25
+ .filter((type) => type.component)
26
+ .map(async (type) =>
27
+ (await getItems(type.key, { locale: "*" })).map((item) => ({
28
+ params: { page: item.url.slice(1) },
29
+ props: { pageProps: { item }, component: type.component },
30
+ })),
31
+ ),
32
+ );
33
+ return [...added, ...items.flat()];
34
+ }
@@ -0,0 +1,13 @@
1
+ import type { APIRoute } from "astro";
2
+ import config from "virtual:brim/config";
3
+ import { resolveMedia } from "../config.ts";
4
+ import { uploadResponse } from "../content/media.ts";
5
+
6
+ /**
7
+ * `/uploads/...` on the built server, for images uploaded after the build: the build copied the ones that
8
+ * existed then next to the pages, where the server finds them first.
9
+ */
10
+ export const prerender = false;
11
+
12
+ export const GET: APIRoute = ({ params }) =>
13
+ uploadResponse(config.mediaDirectory, params.file ?? "", resolveMedia(config.media).publicUrl);
@@ -0,0 +1,253 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
3
+ import { basename, extname, join, resolve } from "node:path";
4
+ import type { SeedEntry } from "./content/seed.ts";
5
+
6
+ /**
7
+ * `brim seed`: the site's starting content, kept in git as `seed/<type>.json` with its pictures in `seed/images/`,
8
+ * added to a running site through its admin API, which checks it exactly as the editor would and stores the
9
+ * pictures where the site keeps its media (public/uploads, or the CDN it is set up with).
10
+ *
11
+ * It never changes what is there: the site adds only the items it does not have (same type, slug and language).
12
+ * It talks to the dev server on this computer unless told otherwise, signed in with an access token it creates in
13
+ * the local database and deletes when done; a site elsewhere needs its address and a token, given on purpose.
14
+ */
15
+
16
+ export interface SeedTarget {
17
+ /** The site's address, without a trailing slash. */
18
+ url: string;
19
+ token: string;
20
+ }
21
+
22
+ interface Planned {
23
+ index: number;
24
+ type: string;
25
+ slug: string;
26
+ title: string;
27
+ locale: string;
28
+ }
29
+
30
+ const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp", ".avif", ".gif", ".svg"]);
31
+
32
+ /** A site on this computer: the only one `brim seed` signs in to by itself. */
33
+ export function isLocalSite(url: string): boolean {
34
+ try {
35
+ const { hostname } = new URL(url);
36
+ return ["localhost", "127.0.0.1", "[::1]", "::1"].includes(hostname) || hostname.endsWith(".localhost");
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /** Reads `seed/*.json`: each file a list of items, of the type its name says unless an item names its own. */
43
+ export async function readSeed(folder: string): Promise<SeedEntry[]> {
44
+ if (!existsSync(folder)) throw new Error(`There is no ${folder} folder. Write the seed as ${folder}/<type>.json.`);
45
+ const files = (await readdir(folder)).filter((name) => name.endsWith(".json")).sort();
46
+ if (files.length === 0) throw new Error(`${folder} has no .json files: write the seed as ${folder}/<type>.json.`);
47
+ const entries: SeedEntry[] = [];
48
+ for (const file of files) {
49
+ let parsed: unknown;
50
+ try {
51
+ parsed = JSON.parse(await readFile(join(folder, file), "utf8"));
52
+ } catch (error) {
53
+ throw new Error(`${folder}/${file} is not valid JSON: ${error instanceof Error ? error.message : error}`);
54
+ }
55
+ if (!Array.isArray(parsed)) throw new Error(`${folder}/${file} must be a list of items.`);
56
+ const type = basename(file, ".json");
57
+ for (const entry of parsed) {
58
+ entries.push(
59
+ typeof entry === "object" && entry !== null && !("type" in entry) ? { type, ...entry } : (entry as SeedEntry),
60
+ );
61
+ }
62
+ }
63
+ return entries;
64
+ }
65
+
66
+ /** A picture's address in the seed that names a file next to it (`images/arc.webp`), not one on the web. */
67
+ function isLocalFile(src: string): boolean {
68
+ return !/^(\/|[a-z][a-z0-9+.-]*:)/i.test(src) && IMAGE_EXTENSIONS.has(extname(src).toLowerCase());
69
+ }
70
+
71
+ /** Calls `change` on every `src` in a value (image fields, galleries, blocks, rich text) and keeps what it answers. */
72
+ function mapSources(value: unknown, change: (src: string) => string): unknown {
73
+ if (Array.isArray(value)) return value.map((entry) => mapSources(entry, change));
74
+ if (typeof value !== "object" || value === null) return value;
75
+ return Object.fromEntries(
76
+ Object.entries(value).map(([key, entry]) => [
77
+ key,
78
+ key === "src" && typeof entry === "string" ? change(entry) : mapSources(entry, change),
79
+ ]),
80
+ );
81
+ }
82
+
83
+ async function call<T>(target: SeedTarget, method: string, path: string, body?: unknown): Promise<T> {
84
+ const response = await fetch(`${target.url}/admin/api${path}`, {
85
+ method,
86
+ headers: {
87
+ authorization: `Bearer ${target.token}`,
88
+ ...(body !== undefined && { "content-type": "application/json" }),
89
+ },
90
+ ...(body !== undefined && { body: JSON.stringify(body) }),
91
+ }).catch((error: unknown) => {
92
+ throw new Error(
93
+ `Could not reach ${target.url} (${error instanceof Error ? error.message : error}). Start the site first ` +
94
+ "(npm run dev), or give its address with --url.",
95
+ );
96
+ });
97
+ const data = (await response.json().catch(() => ({}))) as T & { error?: string };
98
+ if (!response.ok) throw new Error(data.error ?? `${method} ${path} answered ${response.status}.`);
99
+ return data;
100
+ }
101
+
102
+ export interface SeedResult {
103
+ create: Planned[];
104
+ existing: { type: string; slug: string; locale: string }[];
105
+ /** Missing on a dry run. */
106
+ added?: { id: string; type: string; slug: string }[];
107
+ uploaded: number;
108
+ }
109
+
110
+ /**
111
+ * Adds the seed in `folder` to the site: checks it whole first (pictures stand in by name), then uploads the
112
+ * pictures of the items that will be added, and only then adds them.
113
+ */
114
+ export async function runSeed(folder: string, target: SeedTarget, dryRun: boolean): Promise<SeedResult> {
115
+ const root = resolve(folder);
116
+ const entries = await readSeed(root);
117
+ for (const entry of entries) {
118
+ mapSources(entry.data, (src) => {
119
+ if (isLocalFile(src) && !existsSync(join(root, src))) throw new Error(`${folder}/${src} does not exist.`);
120
+ return src;
121
+ });
122
+ }
123
+ const standIns = entries.map((entry) => ({
124
+ ...entry,
125
+ data: mapSources(entry.data, (src) => (isLocalFile(src) ? `/uploads/seed/${basename(src)}` : src)),
126
+ }));
127
+ const plan = await call<{ create: Planned[]; existing: SeedResult["existing"] }>(target, "POST", "/seed", {
128
+ items: standIns,
129
+ dryRun: true,
130
+ });
131
+ if (dryRun || plan.create.length === 0) return { ...plan, uploaded: 0 };
132
+
133
+ const uploaded = new Map<string, string>();
134
+ const ready: SeedEntry[] = [];
135
+ for (const { index } of plan.create) {
136
+ const entry = entries[index] as SeedEntry;
137
+ const files = new Set<string>();
138
+ mapSources(entry.data, (src) => (isLocalFile(src) && files.add(src), src));
139
+ for (const src of files) {
140
+ if (uploaded.has(src)) continue;
141
+ const response = await fetch(`${target.url}/admin/api/media`, {
142
+ method: "POST",
143
+ headers: {
144
+ authorization: `Bearer ${target.token}`,
145
+ "content-type": "application/octet-stream",
146
+ "x-file-name": encodeURIComponent(basename(src)),
147
+ },
148
+ body: await readFile(join(root, src)),
149
+ });
150
+ const data = (await response.json().catch(() => ({}))) as { file?: { url: string }; error?: string };
151
+ if (!response.ok || !data.file) throw new Error(`${folder}/${src}: ${data.error ?? response.status}`);
152
+ uploaded.set(src, data.file.url);
153
+ }
154
+ ready.push({
155
+ ...entry,
156
+ data: mapSources(entry.data, (src) => uploaded.get(src) ?? src) as Record<string, unknown>,
157
+ });
158
+ }
159
+ // Only what the plan adds is sent again: the site adds it, and would leave the rest as it is anyway.
160
+ const result = await call<{ added: SeedResult["added"]; existing: SeedResult["existing"] }>(target, "POST", "/seed", {
161
+ items: ready,
162
+ });
163
+ return {
164
+ create: plan.create,
165
+ existing: plan.existing,
166
+ ...(result.added && { added: result.added }),
167
+ uploaded: uploaded.size,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * `brim seed --export`: the site's items written to `folder/<type>.json`, with the pictures they use from the
173
+ * media library copied into `folder/images/`, so the content can be kept in git as the site's starting content.
174
+ * Refuses to write over seed files that exist unless `force`.
175
+ */
176
+ export async function exportSeedFiles(
177
+ folder: string,
178
+ target: SeedTarget,
179
+ force: boolean,
180
+ ): Promise<{ files: string[]; items: number; images: number }> {
181
+ const root = resolve(folder);
182
+ const { items } = await call<{ items: (SeedEntry & { type: string })[] }>(target, "GET", "/seed");
183
+ const byType = new Map<string, SeedEntry[]>();
184
+ for (const { type, ...entry } of items) byType.set(type, [...(byType.get(type) ?? []), entry as SeedEntry]);
185
+ const files = [...byType.keys()].map((type) => `${type}.json`);
186
+ const taken = files.filter((file) => existsSync(join(root, file)));
187
+ if (taken.length > 0 && !force) {
188
+ throw new Error(`${folder} already has ${taken.join(", ")}: add --force to write over them.`);
189
+ }
190
+
191
+ await mkdir(join(root, "images"), { recursive: true });
192
+ const saved = new Map<string, string>();
193
+ const names = new Set<string>();
194
+ /** Copies a picture into images/, named after the item that uses it first: `ceramica.webp`, `art-2.webp`. */
195
+ const copy = async (src: string, name: string): Promise<void> => {
196
+ if (!src.startsWith("/uploads/") || saved.has(src)) return;
197
+ const response = await fetch(`${target.url}${src}`);
198
+ if (!response.ok) return;
199
+ const extension = extname(src).toLowerCase();
200
+ let file = `${name}${extension}`;
201
+ for (let count = 2; names.has(file) || (existsSync(join(root, "images", file)) && !force); count++) {
202
+ file = `${name}-${count}${extension}`;
203
+ }
204
+ names.add(file);
205
+ await writeFile(join(root, "images", file), new Uint8Array(await response.arrayBuffer()));
206
+ saved.set(src, `images/${file}`);
207
+ };
208
+
209
+ for (const [type, entries] of byType) {
210
+ const written: SeedEntry[] = [];
211
+ for (const entry of entries) {
212
+ const sources = new Set<string>();
213
+ mapSources(entry.data, (src) => (sources.add(src), src));
214
+ let count = 0;
215
+ for (const src of sources)
216
+ await copy(src, count++ === 0 ? (entry.slug ?? type) : `${entry.slug ?? type}-${count}`);
217
+ written.push({
218
+ ...entry,
219
+ data: mapSources(entry.data, (src) => saved.get(src) ?? src) as Record<string, unknown>,
220
+ });
221
+ }
222
+ await writeFile(join(root, `${type}.json`), `${JSON.stringify(written, null, 2)}\n`);
223
+ }
224
+ return { files, items: items.length, images: saved.size };
225
+ }
226
+
227
+ export interface ContentFindingView {
228
+ rule: string;
229
+ where: string;
230
+ message: string;
231
+ }
232
+
233
+ /** What the running site's content still gets wrong, as `brim check --content` reports it. */
234
+ export async function contentFindings(target: SeedTarget): Promise<ContentFindingView[]> {
235
+ return (await call<{ findings: ContentFindingView[] }>(target, "GET", "/check/content")).findings;
236
+ }
237
+
238
+ export function formatContentFindings(findings: ContentFindingView[]): string {
239
+ if (findings.length === 0) return "Content: nothing left from testing, no unused terms, every page in the sitemap.";
240
+ const titles: Record<string, string> = {
241
+ placeholder: "Values left from testing or a template",
242
+ "empty-term": "Terms nothing uses",
243
+ "unlisted-pages": "Pages missing from the sitemap",
244
+ };
245
+ const lines = [`Content: ${findings.length} warning(s).`];
246
+ for (const rule of Object.keys(titles)) {
247
+ const group = findings.filter((finding) => finding.rule === rule);
248
+ if (group.length === 0) continue;
249
+ lines.push("", `${titles[rule]}:`);
250
+ for (const finding of group) lines.push(` ${finding.where}`, ` ${finding.message}`);
251
+ }
252
+ return lines.join("\n");
253
+ }
@@ -0,0 +1,31 @@
1
+ import type { User } from "../auth/accounts.ts";
2
+ import type { Brim } from "../runtime/connect.ts";
3
+ import { readCookies } from "./http.ts";
4
+
5
+ export const SESSION_COOKIE = "brim_session";
6
+
7
+ /**
8
+ * Every session cookie the browser sent. Usually one; an old one kept under /admin (before the cookie covered the
9
+ * whole site), or one from another Brim site on another port of localhost, comes along with it.
10
+ */
11
+ export function sessionCookies(request: Request): string[] {
12
+ return readCookies(request, SESSION_COOKIE).filter(Boolean);
13
+ }
14
+
15
+ export function bearerToken(request: Request): string | undefined {
16
+ const match = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "");
17
+ return match?.[1];
18
+ }
19
+
20
+ /** The user behind a request: an access token from `brim token add`, or the editor's session cookie. */
21
+ export async function requestUser(brim: Brim, request: Request): Promise<User | undefined> {
22
+ const bearer = bearerToken(request);
23
+ if (bearer) return brim.accounts.tokenUser(bearer);
24
+ // The first cookie that is a live session of this site wins; a stale one sent before it no longer signs the
25
+ // editor out.
26
+ for (const session of sessionCookies(request)) {
27
+ const user = await brim.accounts.sessionUser(session);
28
+ if (user) return user;
29
+ }
30
+ return undefined;
31
+ }
@@ -0,0 +1,219 @@
1
+ import { lookup as lookupCallback, type LookupAddress } from "node:dns";
2
+ import { lookup } from "node:dns/promises";
3
+ import { request as httpRequest } from "node:http";
4
+ import { request as httpsRequest } from "node:https";
5
+ import { isIP } from "node:net";
6
+ import { Readable } from "node:stream";
7
+ import { MAX_UPLOAD_BYTES } from "../content/media.ts";
8
+
9
+ /** An image fetched from the web for the media library: its bytes and the name its address gives it. */
10
+ export interface FetchedImage {
11
+ bytes: Uint8Array;
12
+ name: string;
13
+ }
14
+
15
+ type Lookup = (host: string) => Promise<{ address: string }[]>;
16
+
17
+ const MAX_REDIRECTS = 3;
18
+
19
+ /**
20
+ * Fetches an image from a public web address, for an AI agent moving a site's pictures into its media library.
21
+ * The server does the fetching, so it refuses addresses inside its own network (localhost, private ranges, cloud
22
+ * metadata): a token holder must not reach what only the server can. Redirects are followed by hand, each checked
23
+ * the same way, and the answer must be an image of at most 10 MB.
24
+ */
25
+ export async function fetchImage(
26
+ address: string,
27
+ fetcher: typeof fetch = pinnedFetch,
28
+ resolve: Lookup = (host) => lookup(host, { all: true }),
29
+ ): Promise<FetchedImage> {
30
+ let url = parseAddress(address);
31
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
32
+ await assertPublic(url, resolve);
33
+ const response = await fetcher(url, { redirect: "manual", headers: { accept: "image/*" } });
34
+ const location = response.headers.get("location");
35
+ if (response.status >= 300 && response.status < 400 && location) {
36
+ url = parseAddress(new URL(location, url).href);
37
+ continue;
38
+ }
39
+ if (!response.ok) throw new Error(`${url.href} answered ${response.status}.`);
40
+ const type = response.headers.get("content-type") ?? "";
41
+ if (!type.startsWith("image/")) throw new Error(`${url.href} is not an image (${type || "no content type"}).`);
42
+ if (Number(response.headers.get("content-length") ?? 0) > MAX_UPLOAD_BYTES) throw tooLarge();
43
+ return { bytes: await readLimited(response), name: decodeURIComponent(url.pathname.split("/").pop() || "image") };
44
+ }
45
+ throw new Error(`${address} redirects more than ${MAX_REDIRECTS} times.`);
46
+ }
47
+
48
+ /**
49
+ * A GET that checks the address it actually connects to. Checking the name first and letting `fetch` resolve it
50
+ * again leaves a gap: a name can answer a public address to the check and a private one to the connection (DNS
51
+ * rebinding). Here the connection's own lookup refuses private addresses, so what is checked is what is reached.
52
+ */
53
+ export async function pinnedFetch(input: string | URL | Request, init: RequestInit = {}): Promise<Response> {
54
+ const url = new URL(input instanceof Request ? input.url : String(input));
55
+ const request = url.protocol === "https:" ? httpsRequest : httpRequest;
56
+ const headers = Object.fromEntries(new Headers(init.headers).entries());
57
+ return new Promise((resolvePromise, reject) => {
58
+ const outgoing = request(
59
+ url,
60
+ {
61
+ method: "GET",
62
+ headers,
63
+ timeout: 15_000,
64
+ lookup: (hostname, options, callback) => {
65
+ lookupCallback(hostname, { ...options, all: true }, (error, addresses) => {
66
+ if (error) return callback(error, "", 0);
67
+ const list = addresses as unknown as LookupAddress[];
68
+ const usable = list.filter((entry) => !isPrivate(entry.address));
69
+ if (usable.length === 0 || usable.length !== list.length) {
70
+ return callback(new Error(`${hostname} is not a public address.`), "", 0);
71
+ }
72
+ if ((options as { all?: boolean }).all) return (callback as (e: null, a: LookupAddress[]) => void)(null, usable);
73
+ const first = usable[0]!;
74
+ callback(null, first.address, first.family);
75
+ });
76
+ },
77
+ },
78
+ (incoming) => {
79
+ const responseHeaders = new Headers();
80
+ for (const [name, value] of Object.entries(incoming.headers)) {
81
+ if (value === undefined) continue;
82
+ for (const one of Array.isArray(value) ? value : [value]) responseHeaders.append(name, one);
83
+ }
84
+ const status = incoming.statusCode ?? 502;
85
+ const body = status === 204 || status === 304 ? null : (Readable.toWeb(incoming) as ReadableStream<Uint8Array>);
86
+ resolvePromise(new Response(body, { status, headers: responseHeaders }));
87
+ },
88
+ );
89
+ outgoing.on("timeout", () => outgoing.destroy(new Error(`${url.host} did not answer in time.`)));
90
+ outgoing.on("error", reject);
91
+ outgoing.end();
92
+ });
93
+ }
94
+
95
+ function parseAddress(address: string): URL {
96
+ let url: URL;
97
+ try {
98
+ url = new URL(address);
99
+ } catch {
100
+ throw new Error(`"${address}" is not a web address.`);
101
+ }
102
+ if (url.protocol !== "https:" && url.protocol !== "http:")
103
+ throw new Error("Only http and https addresses can be fetched.");
104
+ if (url.username || url.password) throw new Error("An address with a user name or password cannot be fetched.");
105
+ return url;
106
+ }
107
+
108
+ /** Refuses a host name that is, or resolves to, an address inside the server's own network. */
109
+ export async function assertPublicHost(
110
+ host: string,
111
+ resolve: Lookup = (name) => lookup(name, { all: true }),
112
+ ): Promise<void> {
113
+ const bare = host.replace(/^\[|\]$/g, "");
114
+ if (bare.toLowerCase() === "localhost" || bare.toLowerCase().endsWith(".localhost")) {
115
+ throw new Error(`${host} is not a public address.`);
116
+ }
117
+ const addresses = isIP(bare) ? [bare] : (await resolve(bare)).map((entry) => entry.address);
118
+ if (addresses.length === 0 || addresses.some(isPrivate)) throw new Error(`${host} is not a public address.`);
119
+ }
120
+
121
+ async function assertPublic(url: URL, resolve: Lookup): Promise<void> {
122
+ const host = url.hostname.replace(/^\[|\]$/g, "");
123
+ const addresses = isIP(host) ? [host] : (await resolve(host)).map((entry) => entry.address);
124
+ if (addresses.length === 0 || addresses.some(isPrivate)) {
125
+ throw new Error(`${url.host} is not a public address; upload the file with \`npx brim media add\` instead.`);
126
+ }
127
+ }
128
+
129
+ /** Loopback, private, link-local, carrier-grade NAT and unspecified addresses, in IPv4 and IPv6. */
130
+ export function isPrivate(address: string): boolean {
131
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address)?.[1];
132
+ if (mapped) return isPrivate(mapped);
133
+ // An IPv6 address that carries an IPv4 one (mapped ::ffff:0:0/96, NAT64 64:ff9b::/96, compatible ::/96) reaches
134
+ // that IPv4 address. The URL parser writes them in hex (`[::ffff:127.0.0.1]` becomes `::ffff:7f00:1`), so they are
135
+ // read from the address's bytes, not from its spelling.
136
+ const embedded = isIP(address) === 6 ? embeddedIPv4(address) : undefined;
137
+ if (embedded) return isPrivate(embedded);
138
+ if (isIP(address) === 4) {
139
+ const [a = 0, b = 0] = address.split(".").map(Number);
140
+ return (
141
+ a === 0 ||
142
+ a === 10 ||
143
+ a === 127 ||
144
+ (a === 100 && b >= 64 && b <= 127) ||
145
+ (a === 169 && b === 254) ||
146
+ (a === 172 && b >= 16 && b <= 31) ||
147
+ (a === 192 && b === 168) ||
148
+ a >= 224
149
+ );
150
+ }
151
+ const lower = address.toLowerCase();
152
+ return lower === "::" || lower === "::1" || /^f[cd]/.test(lower) || /^fe[89ab]/.test(lower) || /^ff/.test(lower);
153
+ }
154
+
155
+ /** The IPv4 address inside an IPv4-mapped, NAT64 or IPv4-compatible IPv6 address, as a dotted string. */
156
+ function embeddedIPv4(address: string): string | undefined {
157
+ const bytes = ipv6Bytes(address);
158
+ if (!bytes) return undefined;
159
+ const head = bytes.slice(0, 12);
160
+ const zero = (from: number, to: number) => head.slice(from, to).every((byte) => byte === 0);
161
+ const isMapped = zero(0, 10) && head[10] === 0xff && head[11] === 0xff;
162
+ const isNat64 = head[0] === 0x00 && head[1] === 0x64 && head[2] === 0xff && head[3] === 0x9b && zero(4, 12);
163
+ const isCompatible = zero(0, 12) && bytes.slice(12).some((byte) => byte !== 0);
164
+ if (!isMapped && !isNat64 && !isCompatible) return undefined;
165
+ return bytes.slice(12).join(".");
166
+ }
167
+
168
+ /** The 16 bytes of an IPv6 address (with `::` and a dotted IPv4 tail allowed), or undefined when it is not one. */
169
+ function ipv6Bytes(address: string): number[] | undefined {
170
+ let text = address.replace(/%.*$/, "").toLowerCase();
171
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text)?.[1];
172
+ if (tail) {
173
+ const parts = tail.split(".").map(Number);
174
+ text = `${text.slice(0, -tail.length)}${((parts[0]! << 8) | parts[1]!).toString(16)}:${((parts[2]! << 8) | parts[3]!).toString(16)}`;
175
+ }
176
+ const halves = text.split("::");
177
+ if (halves.length > 2) return undefined;
178
+ const groups = (part: string | undefined) => (part ? part.split(":") : []);
179
+ const left = groups(halves[0]);
180
+ const right = groups(halves[1]);
181
+ const missing = 8 - left.length - right.length;
182
+ if (halves.length === 1 ? missing !== 0 : missing < 0) return undefined;
183
+ const all = [...left, ...Array<string>(halves.length === 2 ? missing : 0).fill("0"), ...right];
184
+ const bytes: number[] = [];
185
+ for (const group of all) {
186
+ if (!/^[0-9a-f]{1,4}$/.test(group)) return undefined;
187
+ const value = parseInt(group, 16);
188
+ bytes.push(value >> 8, value & 0xff);
189
+ }
190
+ return bytes;
191
+ }
192
+
193
+ async function readLimited(response: Response): Promise<Uint8Array> {
194
+ const reader = response.body?.getReader();
195
+ if (!reader) return new Uint8Array();
196
+ const chunks: Uint8Array[] = [];
197
+ let size = 0;
198
+ for (;;) {
199
+ const { done, value } = await reader.read();
200
+ if (done) break;
201
+ size += value.byteLength;
202
+ if (size > MAX_UPLOAD_BYTES) {
203
+ await reader.cancel();
204
+ throw tooLarge();
205
+ }
206
+ chunks.push(value);
207
+ }
208
+ const bytes = new Uint8Array(size);
209
+ let offset = 0;
210
+ for (const chunk of chunks) {
211
+ bytes.set(chunk, offset);
212
+ offset += chunk.byteLength;
213
+ }
214
+ return bytes;
215
+ }
216
+
217
+ function tooLarge(): Error {
218
+ return new Error("The image is larger than 10 MB.");
219
+ }