@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,212 @@
1
+ /** How large an image is drawn: its pixels, turned the way the browser turns it (a photo's EXIF orientation). */
2
+ export interface ImageSize {
3
+ width: number;
4
+ height: number;
5
+ }
6
+
7
+ /**
8
+ * Reads an image's size from its bytes, without decoding it: JPEG, PNG, GIF, WebP and AVIF. A photo taken sideways
9
+ * is stored sideways with a note to turn it (EXIF orientation 5–8, or AVIF's `irot`); browsers turn it, so the size
10
+ * returned is the turned one, the size the `<img>` is drawn at. `undefined` when the bytes are none of these, or
11
+ * too damaged to say.
12
+ */
13
+ export function imageSize(bytes: Uint8Array): ImageSize | undefined {
14
+ try {
15
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
16
+ const size = png(bytes, view) ?? gif(bytes, view) ?? jpeg(bytes, view) ?? webp(bytes, view) ?? avif(bytes, view);
17
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
18
+ } catch {
19
+ // A read past the end: the file stops before its size.
20
+ return undefined;
21
+ }
22
+ }
23
+
24
+ function ascii(bytes: Uint8Array, start: number, length: number): string {
25
+ return String.fromCharCode(...bytes.subarray(start, start + length));
26
+ }
27
+
28
+ function turned(size: ImageSize, sideways: boolean): ImageSize {
29
+ return sideways ? { width: size.height, height: size.width } : size;
30
+ }
31
+
32
+ function png(bytes: Uint8Array, view: DataView): ImageSize | undefined {
33
+ if (bytes[0] !== 0x89 || ascii(bytes, 1, 3) !== "PNG" || ascii(bytes, 12, 4) !== "IHDR") return undefined;
34
+ const size = { width: view.getUint32(16), height: view.getUint32(20) };
35
+ // A PNG may carry an EXIF chunk too, which browsers honour; it comes before the image data.
36
+ let offset = 8;
37
+ while (offset + 8 <= bytes.length) {
38
+ const length = view.getUint32(offset);
39
+ const type = ascii(bytes, offset + 4, 4);
40
+ if (type === "IDAT" || type === "IEND") break;
41
+ if (type === "eXIf") return turned(size, exifSideways(bytes, offset + 8, length));
42
+ offset += 12 + length;
43
+ }
44
+ return size;
45
+ }
46
+
47
+ function gif(bytes: Uint8Array, view: DataView): ImageSize | undefined {
48
+ if (ascii(bytes, 0, 4) !== "GIF8") return undefined;
49
+ return { width: view.getUint16(6, true), height: view.getUint16(8, true) };
50
+ }
51
+
52
+ /** The markers that start a frame, and say its size: SOF0–SOF15 but DHT (C4), JPG (C8) and DAC (CC). */
53
+ const START_OF_FRAME = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
54
+
55
+ function jpeg(bytes: Uint8Array, view: DataView): ImageSize | undefined {
56
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return undefined;
57
+ let sideways = false;
58
+ let offset = 2;
59
+ while (offset + 4 <= bytes.length) {
60
+ if (bytes[offset] !== 0xff) return undefined;
61
+ const marker = bytes[offset + 1] ?? 0;
62
+ // Fill bytes, and markers without a length.
63
+ if (marker === 0xff) {
64
+ offset += 1;
65
+ continue;
66
+ }
67
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
68
+ offset += 2;
69
+ continue;
70
+ }
71
+ const length = view.getUint16(offset + 2);
72
+ if (marker === 0xe1 && ascii(bytes, offset + 4, 6) === "Exif\0\0") {
73
+ sideways = exifSideways(bytes, offset + 10, length - 8);
74
+ }
75
+ if (START_OF_FRAME.has(marker)) {
76
+ return turned({ width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) }, sideways);
77
+ }
78
+ offset += 2 + length;
79
+ }
80
+ return undefined;
81
+ }
82
+
83
+ function webp(bytes: Uint8Array, view: DataView): ImageSize | undefined {
84
+ if (ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") return undefined;
85
+ const chunk = ascii(bytes, 12, 4);
86
+ if (chunk === "VP8 ") {
87
+ return { width: view.getUint16(26, true) & 0x3fff, height: view.getUint16(28, true) & 0x3fff };
88
+ }
89
+ if (chunk === "VP8L") {
90
+ const bits = view.getUint32(21, true);
91
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
92
+ }
93
+ if (chunk !== "VP8X") return undefined;
94
+ const size = {
95
+ width: 1 + (view.getUint16(24, true) | ((bytes[26] ?? 0) << 16)),
96
+ height: 1 + (view.getUint16(27, true) | ((bytes[29] ?? 0) << 16)),
97
+ };
98
+ // Bit 3 of the flags: an EXIF chunk follows, after the image data.
99
+ if (((bytes[20] ?? 0) & 0x08) === 0) return size;
100
+ let offset = 12;
101
+ while (offset + 8 <= bytes.length) {
102
+ const length = view.getUint32(offset + 4, true);
103
+ if (ascii(bytes, offset, 4) === "EXIF") {
104
+ const start = ascii(bytes, offset + 8, 6) === "Exif\0\0" ? offset + 14 : offset + 8;
105
+ return turned(size, exifSideways(bytes, start, length));
106
+ }
107
+ offset += 8 + length + (length % 2);
108
+ }
109
+ return size;
110
+ }
111
+
112
+ /**
113
+ * AVIF (and HEIF): the primary item (`pitm`) is the image; its `ispe` property gives the size and an `irot` of 90° or
114
+ * 270° turns it. Properties are listed once (`ipco`) and given to items by number (`ipma`): a large image is often a
115
+ * grid of tiles, each tile an item with an `ispe` of its own, so the first `ispe` is not necessarily the image's.
116
+ */
117
+ function avif(bytes: Uint8Array, view: DataView): ImageSize | undefined {
118
+ const brand = ascii(bytes, 8, 4);
119
+ if (ascii(bytes, 4, 4) !== "ftyp" || !["avif", "avis", "heic", "heix", "mif1"].includes(brand)) return undefined;
120
+ let primary: number | undefined;
121
+ const properties: { type: string; body: number }[] = [];
122
+ const associations = new Map<number, number[]>();
123
+ const walk = (start: number, end: number): void => {
124
+ let offset = start;
125
+ while (offset + 8 <= end) {
126
+ let length = view.getUint32(offset);
127
+ const type = ascii(bytes, offset + 4, 4);
128
+ let header = 8;
129
+ if (length === 1) {
130
+ length = Number(view.getBigUint64(offset + 8));
131
+ header = 16;
132
+ } else if (length === 0) {
133
+ length = end - offset;
134
+ }
135
+ if (length < header) return;
136
+ const body = offset + header;
137
+ // Boxes that hold others: `meta` has 4 bytes of version and flags first.
138
+ if (type === "meta") walk(body + 4, offset + length);
139
+ else if (type === "iprp") walk(body, offset + length);
140
+ else if (type === "ipco") collectProperties(body, offset + length);
141
+ else if (type === "pitm") primary = bytes[body] === 0 ? view.getUint16(body + 4) : view.getUint32(body + 4);
142
+ else if (type === "ipma") collectAssociations(body);
143
+ offset += length;
144
+ }
145
+ };
146
+ const collectProperties = (start: number, end: number): void => {
147
+ let offset = start;
148
+ while (offset + 8 <= end) {
149
+ const length = view.getUint32(offset);
150
+ if (length < 8) return;
151
+ properties.push({ type: ascii(bytes, offset + 4, 4), body: offset + 8 });
152
+ offset += length;
153
+ }
154
+ };
155
+ const collectAssociations = (body: number): void => {
156
+ const version = bytes[body] ?? 0;
157
+ const wide = ((bytes[body + 3] ?? 0) & 1) === 1;
158
+ let offset = body + 4;
159
+ const count = view.getUint32(offset);
160
+ offset += 4;
161
+ for (let entry = 0; entry < count; entry++) {
162
+ const item = version < 1 ? view.getUint16(offset) : view.getUint32(offset);
163
+ offset += version < 1 ? 2 : 4;
164
+ const many = bytes[offset] ?? 0;
165
+ offset += 1;
166
+ const indexes: number[] = [];
167
+ for (let index = 0; index < many; index++) {
168
+ // The top bit marks a property as essential; the rest is its number in `ipco`, from 1.
169
+ indexes.push(wide ? view.getUint16(offset) & 0x7fff : (bytes[offset] ?? 0) & 0x7f);
170
+ offset += wide ? 2 : 1;
171
+ }
172
+ associations.set(item, indexes);
173
+ }
174
+ };
175
+ walk(0, bytes.length);
176
+
177
+ const own = primary === undefined ? undefined : associations.get(primary);
178
+ const of = (type: string) =>
179
+ own
180
+ ? own.map((index) => properties[index - 1]).find((property) => property?.type === type)
181
+ : properties.find((property) => property.type === type);
182
+ const extent = of("ispe");
183
+ if (!extent) return undefined;
184
+ const rotation = of("irot");
185
+ const sideways = rotation ? ((bytes[rotation.body] ?? 0) & 0x03) % 2 === 1 : false;
186
+ return turned({ width: view.getUint32(extent.body + 4), height: view.getUint32(extent.body + 8) }, sideways);
187
+ }
188
+
189
+ /**
190
+ * Whether an EXIF block (a TIFF header at `start`) turns the image a quarter: orientations 5 to 8. Only the first
191
+ * directory is read, where the orientation is.
192
+ */
193
+ function exifSideways(bytes: Uint8Array, start: number, length: number): boolean {
194
+ const end = Math.min(bytes.length, start + length);
195
+ if (start + 8 > end) return false;
196
+ const order = ascii(bytes, start, 2);
197
+ if (order !== "II" && order !== "MM") return false;
198
+ const little = order === "II";
199
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
200
+ const directory = start + view.getUint32(start + 4, little);
201
+ if (directory + 2 > end) return false;
202
+ const entries = view.getUint16(directory, little);
203
+ for (let index = 0; index < entries; index++) {
204
+ const entry = directory + 2 + index * 12;
205
+ if (entry + 12 > end) return false;
206
+ if (view.getUint16(entry, little) === 0x0112) {
207
+ const orientation = view.getUint16(entry + 8, little);
208
+ return orientation >= 5 && orientation <= 8;
209
+ }
210
+ }
211
+ return false;
212
+ }
@@ -0,0 +1,126 @@
1
+ import type { Database } from "../db/database.ts";
2
+ import { type ImageSize, imageSize } from "./image-size.ts";
3
+
4
+ /**
5
+ * The sizes of the uploaded images, by address (`/uploads/…`), so `imageSources` can give an `<img>` its `width` and
6
+ * `height` without asking the database while a page is drawn. The middleware loads them before each page, at most
7
+ * once a minute; an upload made by this server is known at once, one made by another server of the same site within
8
+ * the minute.
9
+ */
10
+ const known = new Map<string, ImageSize>();
11
+ let loadedAt = Number.NEGATIVE_INFINITY;
12
+ let loading: Promise<void> | undefined;
13
+
14
+ /** How long the sizes loaded are trusted before the next page reloads them. */
15
+ export const IMAGE_SIZES_REFRESH_MS = 60_000;
16
+
17
+ export function rememberImageSize(url: string, size: ImageSize): void {
18
+ known.set(url, size);
19
+ }
20
+
21
+ /** The size of an uploaded image, when the media library knows it. */
22
+ export function knownImageSize(url: string): ImageSize | undefined {
23
+ return known.get(url);
24
+ }
25
+
26
+ /** Forgets every size, so the next page loads them again: for tests, and after the library changed under it. */
27
+ export function forgetImageSizes(): void {
28
+ known.clear();
29
+ loadedAt = Number.NEGATIVE_INFINITY;
30
+ loading = undefined;
31
+ }
32
+
33
+ /** Loads the sizes the media library keeps, unless they were loaded within the last minute. */
34
+ export function loadImageSizes(db: Database, now = Date.now()): Promise<void> {
35
+ if (now - loadedAt < IMAGE_SIZES_REFRESH_MS) return Promise.resolve();
36
+ loading ??= (async () => {
37
+ try {
38
+ const rows = await db.query("SELECT url, width, height FROM brim_media WHERE width > 0 AND height > 0");
39
+ for (const row of rows) known.set(String(row.url), { width: Number(row.width), height: Number(row.height) });
40
+ loadedAt = now;
41
+ } finally {
42
+ loading = undefined;
43
+ }
44
+ })();
45
+ return loading;
46
+ }
47
+
48
+ /** The address of the copy of `src` that is `width` pixels wide, as the CDN's `resize` writes it. */
49
+ export function copyOf(src: string, resize: string, width: number): string {
50
+ return resize.replaceAll("{url}", src).replaceAll("{width}", String(width));
51
+ }
52
+
53
+ /**
54
+ * The `srcset` of an upload served at `src`: a copy at each of `widths` the CDN makes with `resize`
55
+ * (`"{url}?width={width}"`). When the image's own width is known, copies as wide or wider are left out (the CDN does
56
+ * not enlarge it, so they would be the same file under other addresses) and the image itself is the widest, unless
57
+ * it is wider than the widest copy: a photo straight from a camera is megabytes, so the list stops at that copy.
58
+ */
59
+ export function srcsetOf(src: string, resize: string, widths: number[], ownWidth?: number): string {
60
+ const smaller = ownWidth ? widths.filter((width) => width < ownWidth) : widths;
61
+ const candidates = smaller.map((width) => `${copyOf(src, resize, width)} ${width}w`);
62
+ if (ownWidth && ownWidth <= Math.max(...widths)) candidates.push(`${src} ${ownWidth}w`);
63
+ return candidates.join(", ");
64
+ }
65
+
66
+ /**
67
+ * The address an `<img>` falls back on (its `src`) and whoever reads it instead of the `srcset` gets: the image
68
+ * itself, or the widest copy when the image is known to be wider than it.
69
+ */
70
+ export function widestOf(src: string, resize: string, widths: number[], ownWidth?: number): string {
71
+ const widest = Math.max(...widths);
72
+ return ownWidth && ownWidth > widest ? copyOf(src, resize, widest) : src;
73
+ }
74
+
75
+ /** What measuring the images uploaded before sizes were kept did. */
76
+ export interface MeasureReport {
77
+ measured: number;
78
+ /** Files that could not be read (missing, or the storage did not answer): they are tried again next time. */
79
+ unreadable: string[];
80
+ /** Files read but not understood as an image: marked, so they are not read again. */
81
+ unknown: string[];
82
+ }
83
+
84
+ /**
85
+ * Measures the images of the media library that have no size yet (uploaded before brimjs kept it): reads each file
86
+ * with `read`, saves its size and makes it known. Four files are read at a time.
87
+ */
88
+ export async function measureImageSizes(
89
+ db: Database,
90
+ read: (url: string) => Promise<Uint8Array | undefined>,
91
+ ): Promise<MeasureReport> {
92
+ const rows = await db.query(
93
+ "SELECT id, url FROM brim_media WHERE width IS NULL AND mime <> 'image/svg+xml' ORDER BY created_at",
94
+ );
95
+ const report: MeasureReport = { measured: 0, unreadable: [], unknown: [] };
96
+ const queue = rows.map((row) => ({ id: String(row.id), url: String(row.url) }));
97
+ const worker = async (): Promise<void> => {
98
+ for (let next = queue.shift(); next; next = queue.shift()) {
99
+ let bytes: Uint8Array | undefined;
100
+ try {
101
+ bytes = await read(next.url);
102
+ } catch {
103
+ bytes = undefined;
104
+ }
105
+ if (!bytes) {
106
+ report.unreadable.push(next.url);
107
+ continue;
108
+ }
109
+ const size = imageSize(bytes);
110
+ // 0 × 0 marks a file read but not understood, so it is not fetched again on every start.
111
+ await db.query("UPDATE brim_media SET width = ?, height = ? WHERE id = ?", [
112
+ size?.width ?? 0,
113
+ size?.height ?? 0,
114
+ next.id,
115
+ ]);
116
+ if (size) {
117
+ known.set(next.url, size);
118
+ report.measured += 1;
119
+ } else {
120
+ report.unknown.push(next.url);
121
+ }
122
+ }
123
+ };
124
+ await Promise.all(Array.from({ length: 4 }, worker));
125
+ return report;
126
+ }
@@ -0,0 +1,110 @@
1
+ import { type ContentField, type ContentType, type FieldType, optionLabel } from "./content-types.ts";
2
+ import { type Item, type ItemDraft, parseItem } from "./items.ts";
3
+ import type { InlineNode } from "./types.ts";
4
+ import { ValidationError } from "./validation-error.ts";
5
+
6
+ /**
7
+ * An element on an item's page that shows one of the item's fields (`title` or a field the type declares).
8
+ * Editing the element in place writes the field, so the form and the page always agree.
9
+ */
10
+ export interface ItemBinding {
11
+ item: Pick<Item, "id" | "type" | "title" | "data">;
12
+ field: string;
13
+ }
14
+
15
+ /** What the bound element shows: the item's title, or the value of one of its fields. */
16
+ export function boundValue({ item, field }: ItemBinding): unknown {
17
+ return field === "title" ? item.title : item.data[field];
18
+ }
19
+
20
+ /**
21
+ * The fields `<Field>` shows: values the owner picks rather than writes (a date, a number, a choice, yes or no, a
22
+ * link, an email). On the page they are set in the side panel with the same widget as in the item form.
23
+ */
24
+ export const METADATA_FIELDS: readonly FieldType[] = ["date", "number", "select", "boolean", "url", "email"];
25
+
26
+ /** The node kind of an element that shows one of the `METADATA_FIELDS`. */
27
+ export const FIELD_KIND = "field";
28
+
29
+ /**
30
+ * How `<Field>` writes a value when the site's code does not: a date and a number in the item's language, a yes as
31
+ * the field's label (a "Featured" field reads "Featured" when set), a choice as its label, the rest as it is.
32
+ * Empty is "".
33
+ */
34
+ export function fieldText(
35
+ field: Pick<ContentField, "type" | "label" | "options">,
36
+ value: unknown,
37
+ locale?: string,
38
+ ): string {
39
+ if (value === undefined || value === null || value === "") return "";
40
+ const locales = locale ? [locale] : undefined;
41
+ try {
42
+ if (field.type === "date" && typeof value === "string") {
43
+ // Kept as YYYY-MM-DD with no time of day: read and written in UTC, so no time zone moves it by a day.
44
+ const date = new Date(`${value}T00:00:00Z`);
45
+ if (!Number.isNaN(date.getTime())) {
46
+ return new Intl.DateTimeFormat(locales, { dateStyle: "long", timeZone: "UTC" }).format(date);
47
+ }
48
+ }
49
+ // Grouped from five digits on: a price reads 12,500, a year stays 2024.
50
+ if (field.type === "number" && typeof value === "number") {
51
+ return new Intl.NumberFormat(locales, { useGrouping: "min2" }).format(value);
52
+ }
53
+ } catch (error) {
54
+ // A language code Intl does not know is written in the default language rather than breaking the page.
55
+ if (!(error instanceof RangeError)) throw error;
56
+ return fieldText(field, value);
57
+ }
58
+ if (field.type === "boolean") return value === true ? field.label : "";
59
+ if (field.type === "select") return optionLabel(field, String(value), locale);
60
+ return String(value);
61
+ }
62
+
63
+ /**
64
+ * Turns what the editor saved for a bound element into the item's new values, checked exactly like the item form:
65
+ * text and rich text become the field, an image block gives its address and description, a gallery or carousel
66
+ * its images' addresses and descriptions, in order. Everything else in the value is how the element looks, which
67
+ * belongs to the page's template and is saved there on its own. A `field` element sends `{ value }`: the field's
68
+ * new value, checked like the item form ("" or none empties it).
69
+ */
70
+ export function applyToItem(
71
+ type: ContentType,
72
+ item: Item,
73
+ field: string,
74
+ kind: string,
75
+ value: Record<string, unknown>,
76
+ ): ItemDraft {
77
+ const declared = field === "title" ? undefined : type.fields.find((candidate) => candidate.name === field);
78
+ if (field !== "title" && !declared) throw new ValidationError(`"${type.label}" has no field "${field}".`);
79
+ const fieldType = declared?.type ?? "text";
80
+
81
+ let fieldValue: unknown;
82
+ if (kind === "text" && (fieldType === "text" || fieldType === "textarea")) {
83
+ // Line breaks typed on the page are the field's new lines; other formatting has no place in a text field.
84
+ fieldValue = Array.isArray(value.rich) ? plainText(value.rich as InlineNode[]) : String(value.text ?? "");
85
+ } else if (kind === "richtext" && fieldType === "richtext") {
86
+ fieldValue = value;
87
+ } else if (kind === "image" && fieldType === "image") {
88
+ fieldValue = value.url ? { src: value.url, alt: value.alt ?? "" } : undefined;
89
+ } else if ((kind === "image-gallery" || kind === "carousel") && fieldType === "gallery") {
90
+ // The images, in their order: a gallery field keeps each one's address and description.
91
+ fieldValue = (Array.isArray(value.images) ? (value.images as Record<string, unknown>[]) : [])
92
+ .filter((image) => typeof image.url === "string" && image.url !== "")
93
+ .map((image) => ({ src: image.url, alt: typeof image.alt === "string" ? image.alt : "" }));
94
+ } else if (kind === FIELD_KIND && METADATA_FIELDS.includes(fieldType)) {
95
+ fieldValue = value.value;
96
+ } else {
97
+ throw new ValidationError(`A ${kind} element cannot show the ${fieldType} field "${field}".`);
98
+ }
99
+
100
+ const input =
101
+ field === "title" ? { ...item, title: fieldValue } : { ...item, data: { ...item.data, [field]: fieldValue } };
102
+ return parseItem(type, input);
103
+ }
104
+
105
+ function plainText(nodes: InlineNode[]): string {
106
+ return nodes
107
+ .map((node) => (typeof node === "string" ? node : node.tag === "br" ? "\n" : plainText(node.children)))
108
+ .join("")
109
+ .trim();
110
+ }
@@ -0,0 +1,126 @@
1
+ import { type LocaleConfig, itemPagePath } from "../server/locales.ts";
2
+ import { type ContentType, optionLabel, standardField } from "./content-types.ts";
3
+ import { itemImage } from "./item-image.ts";
4
+ import type { Item } from "./items.ts";
5
+ import { referencedSlugs, termsBySlug } from "./references.ts";
6
+
7
+ /** Who wrote an item: a name as readers see it, with the page about them when there is one. */
8
+ export interface ItemAuthor {
9
+ name: string;
10
+ /** A path of the site, or a full address. */
11
+ url?: string;
12
+ }
13
+
14
+ /**
15
+ * What an item's page says about itself in its head when neither the owner (Page Settings) nor the page's code does:
16
+ * read from the item's standard fields, whatever their labels.
17
+ */
18
+ export interface ItemHead {
19
+ title: string;
20
+ description?: string;
21
+ /** As stored: a file of the site or a full address. */
22
+ image?: string;
23
+ authors: ItemAuthor[];
24
+ /** On an item of an `article` type; its dates as `YYYY-MM-DD`, when it has them. */
25
+ article?: { published?: string; modified?: string };
26
+ }
27
+
28
+ interface Sources {
29
+ types: ContentType[];
30
+ /** The published items of a type, in every language. */
31
+ publishedItems: (type: string) => Promise<Item[]>;
32
+ locales?: LocaleConfig | undefined;
33
+ now?: Date;
34
+ }
35
+
36
+ export async function itemHead(
37
+ type: ContentType,
38
+ item: Pick<Item, "title" | "data" | "locale">,
39
+ sources: Sources,
40
+ ): Promise<ItemHead> {
41
+ const description = itemDescription(type, item);
42
+ const image = itemImage(type, item);
43
+ return {
44
+ title: item.title,
45
+ ...(description && { description }),
46
+ ...(image && { image }),
47
+ authors: await itemAuthors(type, item, sources),
48
+ ...(type.article && { article: articleDates(type, item, sources.now) }),
49
+ };
50
+ }
51
+
52
+ /** The item's `description`, when it has one filled in. */
53
+ export function itemDescription(type: ContentType, item: Pick<Item, "data">): string | undefined {
54
+ return standardField(type, "description") ? words(item.data.description) : undefined;
55
+ }
56
+
57
+ /**
58
+ * Who wrote the item: the `author` field's text, its chosen label, or the published items it points at (an author
59
+ * nobody can see is not named). Each comes with a link when the term has a page, or a link of its own in a `url`
60
+ * field.
61
+ */
62
+ export async function itemAuthors(
63
+ type: ContentType,
64
+ item: Pick<Item, "data" | "locale">,
65
+ { types, publishedItems, locales }: Pick<Sources, "types" | "publishedItems" | "locales">,
66
+ ): Promise<ItemAuthor[]> {
67
+ const field = standardField(type, "author");
68
+ if (!field) return [];
69
+ const value = item.data.author;
70
+ if (field.type === "reference") {
71
+ const slugs = referencedSlugs(item, "author");
72
+ const target = types.find((candidate) => candidate.key === field.to);
73
+ if (slugs.length === 0 || !target) return [];
74
+ const all = await publishedItems(target.key);
75
+ const terms = termsBySlug(
76
+ all.filter((term) => term.locale === item.locale),
77
+ all,
78
+ );
79
+ return slugs.flatMap((slug) => {
80
+ const term = terms.get(slug);
81
+ if (!term) return [];
82
+ const url = target.component ? itemPagePath(target, term, locales) : linkOf(target, term);
83
+ return [{ name: term.title, ...(url && { url }) }];
84
+ });
85
+ }
86
+ const names = Array.isArray(value) ? value.map(words) : [words(value)];
87
+ return names
88
+ .filter((name) => name !== undefined)
89
+ .map((name) => ({ name: field.type === "select" ? optionLabel(field, name, item.locale || undefined) : name }));
90
+ }
91
+
92
+ /**
93
+ * An article's dates for search engines: those the item says, which are the ones its page can show. When it was
94
+ * created or last saved is not one of them (an import, a corrected comma), nor is a date still to come.
95
+ */
96
+ function articleDates(
97
+ type: ContentType,
98
+ item: Pick<Item, "data">,
99
+ now = new Date(),
100
+ ): { published?: string; modified?: string } {
101
+ // The latest date it is anywhere in the world.
102
+ const latest = new Date(now.getTime() + 14 * 60 * 60 * 1000).toISOString().slice(0, 10);
103
+ const dateOf = (name: "published" | "modified"): string | undefined => {
104
+ const value = standardField(type, name) ? item.data[name] : undefined;
105
+ return typeof value === "string" && value !== "" && value <= latest ? value : undefined;
106
+ };
107
+ const published = dateOf("published");
108
+ const modified = dateOf("modified");
109
+ return {
110
+ ...(published && { published }),
111
+ ...(modified && (!published || modified >= published) && { modified }),
112
+ };
113
+ }
114
+
115
+ /** A term's own link: the first `url` field it has filled in with a full address. */
116
+ function linkOf(type: ContentType, term: Pick<Item, "data">): string | undefined {
117
+ for (const field of type.fields) {
118
+ const value = field.type === "url" ? term.data[field.name] : undefined;
119
+ if (typeof value === "string" && /^https?:\/\//i.test(value)) return value;
120
+ }
121
+ return undefined;
122
+ }
123
+
124
+ function words(value: unknown): string | undefined {
125
+ return typeof value === "string" ? value.trim() || undefined : undefined;
126
+ }
@@ -0,0 +1,26 @@
1
+ import { type ContentField, standardField } from "./content-types.ts";
2
+ import type { ImageValue } from "./types.ts";
3
+
4
+ interface WithFields {
5
+ fields: ContentField[];
6
+ }
7
+
8
+ /** The field with a type's main picture: `image`, or on a type without one, the first image field it declares. */
9
+ export function imageField(type: WithFields): string | undefined {
10
+ return (standardField(type, "image") ?? type.fields.find((field) => field.type === "image"))?.name;
11
+ }
12
+
13
+ /** The item's own picture, when it has one. */
14
+ export function itemPicture(type: WithFields, item: { data: Record<string, unknown> }): ImageValue | undefined {
15
+ const name = imageField(type);
16
+ const value = name ? (item.data[name] as Partial<ImageValue> | undefined) : undefined;
17
+ return typeof value?.src === "string" && value.src ? { ...value, src: value.src, alt: value.alt ?? "" } : undefined;
18
+ }
19
+
20
+ /**
21
+ * The address of the item's own picture. It stands in for the page's preview image when the owner set none, so a
22
+ * shared link shows the item, not the site's default image.
23
+ */
24
+ export function itemImage(type: WithFields, item: { data: Record<string, unknown> }): string | undefined {
25
+ return itemPicture(type, item)?.src;
26
+ }