@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.
- package/LICENSE +110 -0
- package/README.md +22 -2
- package/bin/brim.js +5 -0
- package/dist/cli.js +3802 -0
- package/editor-dist/editor.css +1 -0
- package/editor-dist/editor.js +91 -0
- package/package.json +71 -3
- package/skills/brim-convert/SKILL.md +256 -0
- package/skills/brim-hosting/SKILL.md +221 -0
- package/src/astro-shim.d.ts +5 -0
- package/src/auth/accounts.ts +341 -0
- package/src/auth/password.ts +34 -0
- package/src/auth/permissions.ts +44 -0
- package/src/blocks/accordion/Accordion.astro +48 -0
- package/src/blocks/accordion/accordion.css +63 -0
- package/src/blocks/analytics/Analytics.astro +45 -0
- package/src/blocks/analytics/ConsentBanner.astro +41 -0
- package/src/blocks/analytics/analytics.client.ts +125 -0
- package/src/blocks/analytics/analytics.css +51 -0
- package/src/blocks/analytics/consent.ts +51 -0
- package/src/blocks/button/Button.astro +64 -0
- package/src/blocks/button/button.css +100 -0
- package/src/blocks/carousel/Carousel.astro +140 -0
- package/src/blocks/carousel/carousel.client.ts +153 -0
- package/src/blocks/carousel/carousel.css +181 -0
- package/src/blocks/data/icons.ts +285 -0
- package/src/blocks/data/image-shapes.ts +91 -0
- package/src/blocks/data/social-icons.ts +41 -0
- package/src/blocks/data/social-networks.ts +256 -0
- package/src/blocks/divider/Divider.astro +27 -0
- package/src/blocks/divider/divider.css +17 -0
- package/src/blocks/form/Captcha.astro +27 -0
- package/src/blocks/form/Form.astro +250 -0
- package/src/blocks/form/FormField.astro +138 -0
- package/src/blocks/form/Newsletter.astro +80 -0
- package/src/blocks/form/form.client.ts +339 -0
- package/src/blocks/form/form.css +271 -0
- package/src/blocks/gallery/ImageGallery.astro +126 -0
- package/src/blocks/gallery/gallery.css +43 -0
- package/src/blocks/gallery/lightbox.client.ts +178 -0
- package/src/blocks/gallery/lightbox.css +134 -0
- package/src/blocks/icon/Icon.astro +41 -0
- package/src/blocks/icon/icon.css +16 -0
- package/src/blocks/image/Image.astro +158 -0
- package/src/blocks/image/image.css +42 -0
- package/src/blocks/images.ts +64 -0
- package/src/blocks/in-editor.client.ts +8 -0
- package/src/blocks/listing/Listing.astro +288 -0
- package/src/blocks/listing/ListingCards.astro +48 -0
- package/src/blocks/listing/listing.css +136 -0
- package/src/blocks/listing/query.ts +363 -0
- package/src/blocks/map/Map.astro +75 -0
- package/src/blocks/map/map.css +32 -0
- package/src/blocks/schemas/accordion.ts +118 -0
- package/src/blocks/schemas/button.ts +78 -0
- package/src/blocks/schemas/carousel.ts +133 -0
- package/src/blocks/schemas/divider.ts +29 -0
- package/src/blocks/schemas/form-field-types.ts +29 -0
- package/src/blocks/schemas/form.ts +350 -0
- package/src/blocks/schemas/icon.ts +24 -0
- package/src/blocks/schemas/image-gallery.ts +54 -0
- package/src/blocks/schemas/image.ts +87 -0
- package/src/blocks/schemas/index.ts +33 -0
- package/src/blocks/schemas/listing.ts +14 -0
- package/src/blocks/schemas/map.ts +81 -0
- package/src/blocks/schemas/newsletter.ts +324 -0
- package/src/blocks/schemas/social-media.ts +348 -0
- package/src/blocks/schemas/text.ts +151 -0
- package/src/blocks/schemas/video.ts +57 -0
- package/src/blocks/search/Search.astro +147 -0
- package/src/blocks/search/search.css +69 -0
- package/src/blocks/search/state.ts +28 -0
- package/src/blocks/settings.ts +94 -0
- package/src/blocks/social/SocialMedia.astro +102 -0
- package/src/blocks/social/social-links.ts +16 -0
- package/src/blocks/social/social.css +31 -0
- package/src/blocks/theme.ts +35 -0
- package/src/blocks/types.ts +52 -0
- package/src/blocks/video/Video.astro +90 -0
- package/src/blocks/video/video-source.ts +77 -0
- package/src/blocks/video/video.client.ts +43 -0
- package/src/blocks/video/video.css +29 -0
- package/src/check.ts +1119 -0
- package/src/cli.ts +493 -0
- package/src/components/Blocks.astro +68 -0
- package/src/components/Field.astro +61 -0
- package/src/components/Footer.astro +36 -0
- package/src/components/Link.astro +18 -0
- package/src/components/MobileMenu.astro +77 -0
- package/src/components/Navbar.astro +42 -0
- package/src/components/RichText.astro +32 -0
- package/src/components/Seo.astro +202 -0
- package/src/components/Setting.astro +46 -0
- package/src/components/Shared.astro +17 -0
- package/src/components/Text.astro +91 -0
- package/src/components/blocks.css +86 -0
- package/src/components/index.ts +27 -0
- package/src/components/mobile-menu.client.ts +21 -0
- package/src/components/mobile-menu.css +52 -0
- package/src/components/text.css +48 -0
- package/src/config.ts +413 -0
- package/src/content/block-layout.ts +63 -0
- package/src/content/block-values.ts +48 -0
- package/src/content/content-check.ts +174 -0
- package/src/content/content-types.ts +408 -0
- package/src/content/drafts.ts +115 -0
- package/src/content/feed.ts +237 -0
- package/src/content/field-types.ts +107 -0
- package/src/content/history.ts +140 -0
- package/src/content/ids.ts +50 -0
- package/src/content/image-size.ts +212 -0
- package/src/content/image-sizes.ts +126 -0
- package/src/content/item-fields.ts +110 -0
- package/src/content/item-head.ts +126 -0
- package/src/content/item-image.ts +26 -0
- package/src/content/item-path.ts +122 -0
- package/src/content/items.ts +580 -0
- package/src/content/language-scopes.ts +40 -0
- package/src/content/media.ts +271 -0
- package/src/content/menus.ts +51 -0
- package/src/content/page-templates.ts +52 -0
- package/src/content/redirects.ts +112 -0
- package/src/content/references.ts +165 -0
- package/src/content/rich-text.ts +63 -0
- package/src/content/search.ts +167 -0
- package/src/content/seed.ts +229 -0
- package/src/content/site-settings.ts +111 -0
- package/src/content/sitemap.ts +143 -0
- package/src/content/store.ts +225 -0
- package/src/content/tags.ts +67 -0
- package/src/content/text-default.ts +139 -0
- package/src/content/types.ts +137 -0
- package/src/content/validate.ts +253 -0
- package/src/content/validation-error.ts +2 -0
- package/src/db/cached.ts +140 -0
- package/src/db/database.ts +15 -0
- package/src/db/libsql.ts +29 -0
- package/src/db/schema.ts +189 -0
- package/src/db/url.ts +44 -0
- package/src/editor/client/BlockSettings.tsx +1063 -0
- package/src/editor/client/Chrome.tsx +284 -0
- package/src/editor/client/ContentBrowser.tsx +1299 -0
- package/src/editor/client/Editor.tsx +1756 -0
- package/src/editor/client/HistoryPanel.tsx +114 -0
- package/src/editor/client/ImagesWidget.tsx +113 -0
- package/src/editor/client/Inspector.tsx +127 -0
- package/src/editor/client/ItemForm.tsx +535 -0
- package/src/editor/client/LinkWidget.tsx +440 -0
- package/src/editor/client/ListingPanel.tsx +99 -0
- package/src/editor/client/Login.tsx +338 -0
- package/src/editor/client/Menu.tsx +64 -0
- package/src/editor/client/PageSettings.tsx +270 -0
- package/src/editor/client/RedirectsSettings.tsx +130 -0
- package/src/editor/client/Resize.tsx +204 -0
- package/src/editor/client/Sidebar.tsx +51 -0
- package/src/editor/client/SiteMap.tsx +568 -0
- package/src/editor/client/SiteSettings.tsx +409 -0
- package/src/editor/client/TextTools.tsx +391 -0
- package/src/editor/client/Toolbar.tsx +449 -0
- package/src/editor/client/VideoUpload.tsx +251 -0
- package/src/editor/client/api.ts +417 -0
- package/src/editor/client/brand.ts +20 -0
- package/src/editor/client/connection.ts +98 -0
- package/src/editor/client/context.ts +19 -0
- package/src/editor/client/css.d.ts +2 -0
- package/src/editor/client/editor.css +4656 -0
- package/src/editor/client/fields.tsx +812 -0
- package/src/editor/client/icons.tsx +174 -0
- package/src/editor/client/keys.ts +15 -0
- package/src/editor/client/kinds.ts +289 -0
- package/src/editor/client/languages.ts +32 -0
- package/src/editor/client/main.tsx +100 -0
- package/src/editor/client/responses.ts +26 -0
- package/src/editor/client/rich-text.ts +326 -0
- package/src/editor/client/site-tree.ts +239 -0
- package/src/editor/client/theme.ts +55 -0
- package/src/editor/client/tsconfig.json +18 -0
- package/src/editor/client/tus.ts +137 -0
- package/src/editor/client/use-rect.ts +50 -0
- package/src/editor/client/widgets.tsx +1218 -0
- package/src/forms/captcha.ts +83 -0
- package/src/forms/define.ts +166 -0
- package/src/forms/fields.ts +197 -0
- package/src/forms/file-types.ts +108 -0
- package/src/forms/files.ts +216 -0
- package/src/forms/form-page.ts +9 -0
- package/src/forms/handler.ts +622 -0
- package/src/forms/spec.ts +89 -0
- package/src/forms/store.ts +96 -0
- package/src/forms/work.ts +50 -0
- package/src/icons/library.ts +144 -0
- package/src/icons/load.ts +63 -0
- package/src/index.ts +99 -0
- package/src/init.ts +257 -0
- package/src/integration.ts +469 -0
- package/src/mail/mailer.ts +197 -0
- package/src/mail/notify.ts +272 -0
- package/src/mail/settings.ts +173 -0
- package/src/mail/templates.ts +191 -0
- package/src/mcp/page-nodes.ts +209 -0
- package/src/mcp/server.ts +111 -0
- package/src/mcp/tools.ts +637 -0
- package/src/runtime/TemplatePage.astro +39 -0
- package/src/runtime/TemplatePageStatic.astro +13 -0
- package/src/runtime/admin-route.ts +80 -0
- package/src/runtime/connect.ts +53 -0
- package/src/runtime/content.ts +188 -0
- package/src/runtime/context.ts +131 -0
- package/src/runtime/form-files.ts +18 -0
- package/src/runtime/forms-route.ts +33 -0
- package/src/runtime/forms.ts +28 -0
- package/src/runtime/icons.ts +5 -0
- package/src/runtime/media.ts +175 -0
- package/src/runtime/middleware.ts +186 -0
- package/src/runtime/nav.ts +13 -0
- package/src/runtime/query-reads.ts +49 -0
- package/src/runtime/query-store.ts +16 -0
- package/src/runtime/request-state.ts +69 -0
- package/src/runtime/robots.ts +29 -0
- package/src/runtime/rss-static.ts +16 -0
- package/src/runtime/rss.ts +29 -0
- package/src/runtime/server.ts +29 -0
- package/src/runtime/sitemap.ts +34 -0
- package/src/runtime/template-paths.ts +34 -0
- package/src/runtime/uploads-route.ts +13 -0
- package/src/seed-cli.ts +253 -0
- package/src/server/auth.ts +31 -0
- package/src/server/fetch-image.ts +219 -0
- package/src/server/handler.ts +2106 -0
- package/src/server/http.ts +162 -0
- package/src/server/locales.ts +73 -0
- package/src/server/node.ts +57 -0
- package/src/server/query-params.ts +249 -0
- package/src/server/rate-limit.ts +72 -0
- package/src/server/video-host.ts +162 -0
- package/src/starter.ts +70 -0
- package/src/version.ts +4 -0
- package/src/virtual.d.ts +65 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import config from "virtual:brim/config";
|
|
5
|
+
import { type MediaConfig, resolveMedia } from "../config.ts";
|
|
6
|
+
import {
|
|
7
|
+
copyOf,
|
|
8
|
+
knownImageSize,
|
|
9
|
+
loadImageSizes,
|
|
10
|
+
measureImageSizes,
|
|
11
|
+
srcsetOf,
|
|
12
|
+
widestOf,
|
|
13
|
+
} from "../content/image-sizes.ts";
|
|
14
|
+
import { MAX_UPLOAD_BYTES } from "../content/media.ts";
|
|
15
|
+
import type { Database } from "../db/database.ts";
|
|
16
|
+
|
|
17
|
+
/** The upload settings, read once per server: the environment does not change while it runs. */
|
|
18
|
+
let resolved: MediaConfig | undefined;
|
|
19
|
+
function media(): MediaConfig {
|
|
20
|
+
resolved ??= resolveMedia(config.media);
|
|
21
|
+
return resolved;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const UPLOADS = "/uploads/";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Where visitors get an image: an upload (`/uploads/…`, as content stores it) at `media.publicUrl` when the site
|
|
28
|
+
* serves its images from elsewhere, anything else as it is. Use it in the site's own markup for images it reads
|
|
29
|
+
* from items: `<img src={mediaUrl(item.data.cover.src)} />`.
|
|
30
|
+
*/
|
|
31
|
+
export function mediaUrl(url: string): string {
|
|
32
|
+
const { publicUrl } = media();
|
|
33
|
+
return publicUrl && url.startsWith(UPLOADS) ? `${publicUrl}${url}` : url;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The attributes `imageSources` gives an `<img>`. */
|
|
37
|
+
export interface ImageSources {
|
|
38
|
+
src: string;
|
|
39
|
+
srcset?: string;
|
|
40
|
+
sizes?: string;
|
|
41
|
+
/** An upload's size in pixels, so the browser keeps the image's place before it arrives. */
|
|
42
|
+
width?: number;
|
|
43
|
+
height?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The attributes of an `<img>` for an image: its address, its `width` and `height` when it is an upload the media
|
|
48
|
+
* library measured and, when `media.resize` says how the CDN makes smaller copies, a `srcset` of them with `sizes`,
|
|
49
|
+
* so the browser downloads the copy the layout needs. Only uploads get a `srcset`: images from other sites are not
|
|
50
|
+
* the CDN's to resize. Copies wider than the image are left out (the CDN does not enlarge it); the image itself is
|
|
51
|
+
* the widest, unless it is wider than the widest copy: then the file as it was uploaded is never sent.
|
|
52
|
+
*
|
|
53
|
+
* <img {...imageSources(item.data.cover.src, "(max-width: 768px) 100vw, 33vw")} alt={item.data.cover.alt} />
|
|
54
|
+
*
|
|
55
|
+
* With `width` and `height` given, the browser reserves the image's shape while it loads; a site whose CSS sets an
|
|
56
|
+
* image's width (`width: 100%`) also sets `height: auto`, so the height follows the width rather than the attribute.
|
|
57
|
+
*/
|
|
58
|
+
export function imageSources(url: string, sizes = "100vw"): ImageSources {
|
|
59
|
+
const src = mediaUrl(url);
|
|
60
|
+
if (!url.startsWith(UPLOADS)) return siteImage(url, sizes) ?? { src };
|
|
61
|
+
const size = knownImageSize(url);
|
|
62
|
+
const { resize, widths } = media();
|
|
63
|
+
if (!resize || /\.(svg|gif)$/i.test(url)) return { src, ...size };
|
|
64
|
+
return {
|
|
65
|
+
src: widestOf(src, resize, widths, size?.width),
|
|
66
|
+
srcset: srcsetOf(src, resize, widths, size?.width),
|
|
67
|
+
sizes,
|
|
68
|
+
...size,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** How wide the picture of a shared link is asked for: what chats and social networks draw a large card from. */
|
|
73
|
+
const SHARED_IMAGE_WIDTH = 1200;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The address of an image for a shared link's card (`og:image`): a copy 1200 pixels wide where the CDN makes copies
|
|
77
|
+
* (`media.resize`), so a network downloads a card's worth and not the photo as it was uploaded; an image narrower
|
|
78
|
+
* than that, one the CDN does not resize (SVG, GIF, another site's) and any image without a CDN, as it is.
|
|
79
|
+
*/
|
|
80
|
+
export function sharedImageUrl(url: string): string {
|
|
81
|
+
const { resize, siteUrl } = media();
|
|
82
|
+
if (!resize || /\.(svg|gif)$/i.test(url)) return mediaUrl(url);
|
|
83
|
+
if (url.startsWith(UPLOADS)) {
|
|
84
|
+
const own = knownImageSize(url)?.width;
|
|
85
|
+
return own && own <= SHARED_IMAGE_WIDTH ? mediaUrl(url) : copyOf(mediaUrl(url), resize, SHARED_IMAGE_WIDTH);
|
|
86
|
+
}
|
|
87
|
+
return siteUrl && SITE_IMAGE.test(url) ? copyOf(`${siteUrl}${url}`, resize, SHARED_IMAGE_WIDTH) : url;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let makesCopies: boolean | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* Whether Astro's image endpoint can make copies here, for a site that asked for them (`media.sharp`): it needs
|
|
93
|
+
* `sharp`, which the built server looks for from the site's own folder (its bundle sits in it). A site installed
|
|
94
|
+
* with pnpm (strict node_modules, sharp not a dependency of its own) or without sharp has none, and every copy would
|
|
95
|
+
* answer 500, so its pictures go as they are instead and the server's log says so.
|
|
96
|
+
*/
|
|
97
|
+
function serverMakesCopies(): boolean {
|
|
98
|
+
if (makesCopies !== undefined) return makesCopies;
|
|
99
|
+
try {
|
|
100
|
+
createRequire(join(process.cwd(), "package.json")).resolve("sharp");
|
|
101
|
+
makesCopies = true;
|
|
102
|
+
} catch {
|
|
103
|
+
makesCopies = false;
|
|
104
|
+
console.warn(
|
|
105
|
+
"[brim] media.sharp is on but sharp is not installed: pictures in public/ are sent without smaller copies " +
|
|
106
|
+
"(npm install sharp).",
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
return makesCopies;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A picture of the site's own code, in `public/` (`/images/hero.jpg`): not an upload, not another site's. */
|
|
113
|
+
const SITE_IMAGE = /^\/(?!\/)(?!uploads\/)[^?#]+\.(?:jpe?g|png|webp|avif)$/i;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Smaller copies of a picture of the site's own code: from the host's CDN when it copies `public/` there
|
|
117
|
+
* (`media.siteUrl` with `resize`, as Brimsites does), else, for a site that asked for it (`media.sharp`), from Astro's
|
|
118
|
+
* image endpoint on the server (`/_image`, sharp, WebP at quality 75: a third of a JPEG's bytes, alike to the eye),
|
|
119
|
+
* never wider than the picture. Without either, and in a static build without a CDN, they are sent as they were
|
|
120
|
+
* saved. Each copy has its own address, kept for a year.
|
|
121
|
+
*/
|
|
122
|
+
function siteImage(url: string, sizes: string): ImageSources | undefined {
|
|
123
|
+
if (!SITE_IMAGE.test(url)) return undefined;
|
|
124
|
+
const { siteUrl, resize, widths, sharp } = media();
|
|
125
|
+
if (siteUrl && resize) {
|
|
126
|
+
const src = `${siteUrl}${url}`;
|
|
127
|
+
return { src, srcset: srcsetOf(src, resize, widths), sizes };
|
|
128
|
+
}
|
|
129
|
+
if (!sharp || (config.mode !== "server" && config.mode !== "dev") || !serverMakesCopies()) return undefined;
|
|
130
|
+
const href = encodeURIComponent(url);
|
|
131
|
+
const srcset = widths.map((width) => `/_image?href=${href}&w=${width}&f=webp&q=75 ${width}w`).join(", ");
|
|
132
|
+
return { src: url, srcset, sizes };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Reads an upload's file, to measure an image uploaded before sizes were kept: from the uploads folder of this
|
|
137
|
+
* server, or from where the site serves its images (`media.publicUrl`).
|
|
138
|
+
*/
|
|
139
|
+
async function readUpload(url: string): Promise<Uint8Array | undefined> {
|
|
140
|
+
const file = url.slice(UPLOADS.length);
|
|
141
|
+
if (!/^[\w.-]+(\/[\w.-]+)*$/.test(file) || file.split("/").some((part) => part.startsWith("."))) return undefined;
|
|
142
|
+
try {
|
|
143
|
+
return new Uint8Array(await readFile(join(config.mediaDirectory, file)));
|
|
144
|
+
} catch {
|
|
145
|
+
// Not on this server's disk: kept in a storage, or uploaded to another server of the site.
|
|
146
|
+
}
|
|
147
|
+
const { publicUrl } = media();
|
|
148
|
+
if (!publicUrl) return undefined;
|
|
149
|
+
const response = await fetch(`${publicUrl}${url}`);
|
|
150
|
+
if (!response.ok) return undefined;
|
|
151
|
+
if (Number(response.headers.get("content-length") ?? 0) > MAX_UPLOAD_BYTES) return undefined;
|
|
152
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let measuring: Promise<unknown> | undefined;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Makes the sizes of the uploads known before a page is drawn: loads them (at most once a minute) and, once per
|
|
159
|
+
* server, measures the images uploaded before sizes were kept. A page drawn at build time (`wait`) waits for that,
|
|
160
|
+
* since it is drawn once; a running server draws its pages meanwhile and gives those images their sizes as they are
|
|
161
|
+
* measured.
|
|
162
|
+
*/
|
|
163
|
+
export async function prepareImageSizes(db: Database, wait: boolean): Promise<void> {
|
|
164
|
+
await loadImageSizes(db);
|
|
165
|
+
measuring ??= measureImageSizes(db, readUpload).then(
|
|
166
|
+
(report) => {
|
|
167
|
+
if (report.measured > 0) console.info(`[brim] Measured ${report.measured} uploaded images.`);
|
|
168
|
+
if (report.unreadable.length > 0) {
|
|
169
|
+
console.warn(`[brim] ${report.unreadable.length} uploaded images could not be read to measure them.`);
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
(error: unknown) => console.warn("[brim] Uploaded images could not be measured:", error),
|
|
173
|
+
);
|
|
174
|
+
if (wait) await measuring;
|
|
175
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "astro";
|
|
2
|
+
import config from "virtual:brim/config";
|
|
3
|
+
import { itemPageOf } from "../content/content-types.ts";
|
|
4
|
+
import { normalizePagePath, pageScope, requestedPage, siteScope, typeScope } from "../content/ids.ts";
|
|
5
|
+
import { itemHead } from "../content/item-head.ts";
|
|
6
|
+
import { redirectFor } from "../content/redirects.ts";
|
|
7
|
+
import { requestUser } from "../server/auth.ts";
|
|
8
|
+
import { BrimContext } from "./context.ts";
|
|
9
|
+
import { connect } from "./connect.ts";
|
|
10
|
+
import { withKeptReads } from "../db/cached.ts";
|
|
11
|
+
import { upgradeFieldValues } from "../content/block-values.ts";
|
|
12
|
+
import { adoptLanguageScopes } from "../content/language-scopes.ts";
|
|
13
|
+
import { prepareImageSizes } from "./media.ts";
|
|
14
|
+
import { withEditing } from "./request-state.ts";
|
|
15
|
+
import { QueryCollector, collectingQueryReads } from "./query-reads.ts";
|
|
16
|
+
import { queryReads } from "./query-store.ts";
|
|
17
|
+
|
|
18
|
+
/** Brim's own routes (`/admin`, forms, uploads) check who is asking themselves and show no page content. */
|
|
19
|
+
const OWN_ROUTES = /^\/(admin|_brim|uploads)(\/|$)/;
|
|
20
|
+
/** The route Brim adds for pages added from templates and the pages of items. */
|
|
21
|
+
const TEMPLATE_ROUTE = "/[...page]";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Reads every content type's items once when the server starts, while the first visitor's page is drawn, so the
|
|
25
|
+
* listings after it find them in memory (see `ItemStore.listCached`) instead of reading hundreds of items each.
|
|
26
|
+
*/
|
|
27
|
+
let warming: Promise<void> | undefined;
|
|
28
|
+
async function warmItems(brim: Awaited<ReturnType<typeof connect>>): Promise<void> {
|
|
29
|
+
// Texts of fields that became `blocks` are written as blocks first, so the lists read them as they now are.
|
|
30
|
+
await upgradeFieldValues(brim.db, config.contentTypes);
|
|
31
|
+
for (const type of config.contentTypes) {
|
|
32
|
+
await brim.items.listCached(type.key).catch(() => undefined);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Gives every page its content and decides who sees private pages and the editor's markers:
|
|
38
|
+
* everyone in dev, signed-in users on the server, nobody in a static build.
|
|
39
|
+
*/
|
|
40
|
+
export const onRequest: MiddlewareHandler = async (context, next) => {
|
|
41
|
+
const { pathname } = context.url;
|
|
42
|
+
if (config.mode === "server" && OWN_ROUTES.test(pathname)) return next();
|
|
43
|
+
|
|
44
|
+
// Ways into the editor nobody has to remember: `?edit` on any page opens that page in it, and `/edit` (unless the
|
|
45
|
+
// site has a page of its own there) opens it on the home page. A static build has no editor to open.
|
|
46
|
+
if (config.mode !== "static" && !context.isPrerendered && !OWN_ROUTES.test(pathname)) {
|
|
47
|
+
if (context.url.searchParams.has("edit")) return editorRedirect(pathname);
|
|
48
|
+
if (normalizePagePath(pathname) === "/edit" && context.routePattern !== "/edit") return editorRedirect("/");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return withKeptReads(() => drawPage(context, next), context.request);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Draws a visitor's page. Each read below is a round trip on a remote database: they are asked together, and kept
|
|
56
|
+
* between visits until the content changes (see `withKeptReads`), so a visit usually costs one small query.
|
|
57
|
+
*/
|
|
58
|
+
async function drawPage(context: Parameters<MiddlewareHandler>[0], next: Parameters<MiddlewareHandler>[1]) {
|
|
59
|
+
const { pathname } = context.url;
|
|
60
|
+
const address = requestedPage(pathname, context.routePattern);
|
|
61
|
+
const brim = await connect(config.databaseUrl, config.authToken);
|
|
62
|
+
// A site that just turned languages on reads what was saved before as its default language's.
|
|
63
|
+
if (config.locales) await adoptLanguageScopes(brim.db, config.locales.defaultLocale);
|
|
64
|
+
if (config.mode === "server" && !warming) warming = warmItems(brim);
|
|
65
|
+
if (config.mode === "dev") await upgradeFieldValues(brim.db, config.contentTypes);
|
|
66
|
+
// A page rendered at build time has no visitor, and so no headers to read; a static build has no server to answer
|
|
67
|
+
// a redirect.
|
|
68
|
+
const live = config.mode !== "static" && !context.isPrerendered;
|
|
69
|
+
const signedIn = config.mode === "server" && !context.isPrerendered;
|
|
70
|
+
|
|
71
|
+
// What the owner changes on an item's page belongs to its type's template, shared by every item. A page written
|
|
72
|
+
// in code keeps its own, even at an address under the type's slug. The item's visibility decides who sees it.
|
|
73
|
+
const itemPage =
|
|
74
|
+
context.routePattern === TEMPLATE_ROUTE ? itemPageOf(config.contentTypes, address, config.locales) : undefined;
|
|
75
|
+
const locale = context.currentLocale;
|
|
76
|
+
const scope = itemPage ? typeScope(itemPage.type.key, locale) : pageScope(address);
|
|
77
|
+
const scopes = [siteScope(locale), scope];
|
|
78
|
+
|
|
79
|
+
const [redirects, user, page, saved, item] = await Promise.all([
|
|
80
|
+
live ? brim.content.redirects() : undefined,
|
|
81
|
+
signedIn ? requestUser(brim, context.request) : undefined,
|
|
82
|
+
brim.content.page(address),
|
|
83
|
+
brim.content.loadNodes(scopes),
|
|
84
|
+
itemPage ? brim.items.bySlug(itemPage.type.key, itemPage.slug, { locale: itemPage.locale }) : undefined,
|
|
85
|
+
// `imageSources` gives uploads their width and height from what the media library measured.
|
|
86
|
+
prepareImageSizes(brim.db, config.mode === "static" || context.isPrerendered),
|
|
87
|
+
]);
|
|
88
|
+
|
|
89
|
+
// An old address the owner redirected answers before any page.
|
|
90
|
+
const redirect = redirects && redirectFor(redirects, pathname, context.url.search);
|
|
91
|
+
if (redirect) return redirect;
|
|
92
|
+
const editing = config.mode === "dev" || (signedIn && user !== undefined);
|
|
93
|
+
|
|
94
|
+
// The editor draws the page in a frame, with the changes nobody has saved yet; on the server any other visit shows
|
|
95
|
+
// what is saved. In dev a page has no headers to tell (it is prerendered), and only its developer visits it.
|
|
96
|
+
const preview =
|
|
97
|
+
config.mode === "dev" || (signedIn && editing && context.request.headers.get("sec-fetch-dest") === "iframe");
|
|
98
|
+
if (!editing && !itemPage && page.visibility === "private") {
|
|
99
|
+
return new Response(null, { status: 404 });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const nodes = preview ? await brim.drafts.overlayNodes(saved, scopes) : saved;
|
|
103
|
+
const seo = preview ? await brim.drafts.overlaySeo(page.path, page.seo) : page.seo;
|
|
104
|
+
// What search engines and shared links are told of an item, unless the owner or the page's code says otherwise.
|
|
105
|
+
const shown = item && preview ? await brim.drafts.overlayItem(item) : item;
|
|
106
|
+
const head =
|
|
107
|
+
shown && itemPage
|
|
108
|
+
? await itemHead(itemPage.type, shown, {
|
|
109
|
+
types: config.contentTypes,
|
|
110
|
+
publishedItems: (type) => brim.items.listCached(type, { publishedOnly: true }),
|
|
111
|
+
locales: config.locales,
|
|
112
|
+
})
|
|
113
|
+
: undefined;
|
|
114
|
+
context.locals.brim = new BrimContext(scope, locale, nodes, editing, seo, head, preview);
|
|
115
|
+
// What the page reads of its address's query, noted while it is drawn (its blocks, `readsQuery`), so the server
|
|
116
|
+
// can tell a host which parameters each page reads (see `QueryReads`). Only for pages a visitor gets on the server.
|
|
117
|
+
const reads = signedIn && context.request.method === "GET" ? new QueryCollector() : undefined;
|
|
118
|
+
const draw = () => withEditing(editing, next, locale, preview);
|
|
119
|
+
const drawn = reads ? await collectingQueryReads(reads, draw) : await draw();
|
|
120
|
+
// Whoever may edit gets the button: everyone on the dev server, signed-in users on the live site (whose pages are
|
|
121
|
+
// never cached for others, see below). Visitors and a static copy never have it.
|
|
122
|
+
const response = editing && !context.isPrerendered ? await withEditButton(drawn, context.request, address) : drawn;
|
|
123
|
+
// What an editor sees must never be stored and shown to visitors.
|
|
124
|
+
if (signedIn && editing) response.headers.set("cache-control", "private, no-store");
|
|
125
|
+
return reads ? learnWhenDrawn(response, pathname, reads, brim.db) : response;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Remembers what a page read once it is drawn whole: Astro streams a page, and the blocks further down it run as it
|
|
130
|
+
* is sent. Only a page a host would keep (200, not private) teaches anything, and only when no code of the site
|
|
131
|
+
* reads the query without saying so, unless the page itself said what it reads (`readsQuery`).
|
|
132
|
+
*/
|
|
133
|
+
function learnWhenDrawn(
|
|
134
|
+
response: Response,
|
|
135
|
+
pathname: string,
|
|
136
|
+
reads: QueryCollector,
|
|
137
|
+
db: Parameters<typeof queryReads>[0],
|
|
138
|
+
): Response {
|
|
139
|
+
if (response.status !== 200 || /private|no-store/i.test(response.headers.get("cache-control") ?? "")) return response;
|
|
140
|
+
const learn = () => {
|
|
141
|
+
if (!config.learnQuery && !reads.bySite) return;
|
|
142
|
+
void queryReads(db)
|
|
143
|
+
.record(pathname, reads.read)
|
|
144
|
+
.catch(() => undefined);
|
|
145
|
+
};
|
|
146
|
+
if (!response.body) {
|
|
147
|
+
learn();
|
|
148
|
+
return response;
|
|
149
|
+
}
|
|
150
|
+
const body = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({ flush: learn }));
|
|
151
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The editor, opened on a page of the site. */
|
|
155
|
+
function editorRedirect(pathname: string): Response {
|
|
156
|
+
const page = normalizePagePath(pathname);
|
|
157
|
+
return new Response(null, {
|
|
158
|
+
status: 302,
|
|
159
|
+
headers: { location: `/admin/edit${page === "/" ? "" : page}`, "cache-control": "no-store" },
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A floating "Edit this page" button on every page someone who may edit opens in the browser (anyone on the dev
|
|
165
|
+
* server, a signed-in user on the live site), so nobody has to know the editor's address. Not inside the editor's
|
|
166
|
+
* own frame (the browser says it draws a frame), and never for visitors or in a static copy.
|
|
167
|
+
*/
|
|
168
|
+
async function withEditButton(response: Response, request: Request, pathname: string): Promise<Response> {
|
|
169
|
+
const type = response.headers.get("content-type") ?? "";
|
|
170
|
+
if (!type.includes("text/html") || response.status !== 200) return response;
|
|
171
|
+
if (request.headers.get("sec-fetch-dest") === "iframe") return response;
|
|
172
|
+
const html = await response.text();
|
|
173
|
+
const page = normalizePagePath(pathname);
|
|
174
|
+
const button =
|
|
175
|
+
`<a href="/admin/edit${page === "/" ? "" : page}" data-brim-edit-button ` +
|
|
176
|
+
`style="position:fixed;right:20px;bottom:20px;z-index:2147483647;display:inline-flex;align-items:center;gap:8px;` +
|
|
177
|
+
`padding:10px 16px;border-radius:999px;background:#18181b;color:#fff;font:600 14px/1 system-ui,sans-serif;` +
|
|
178
|
+
`text-decoration:none;box-shadow:0 6px 24px rgba(0,0,0,.25)" title="Only you see this: open this page in the editor">` +
|
|
179
|
+
`<span aria-hidden="true">✎</span> Edit this page</a>`;
|
|
180
|
+
const body = html.includes("</body>")
|
|
181
|
+
? html.replace(/<\/body>(?![\s\S]*<\/body>)/, `${button}</body>`)
|
|
182
|
+
: html + button;
|
|
183
|
+
const headers = new Headers(response.headers);
|
|
184
|
+
headers.delete("content-length");
|
|
185
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers });
|
|
186
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { imageField } from "../content/item-image.ts";
|
|
2
|
+
import { type ItemLinks, itemLink } from "../content/menus.ts";
|
|
3
|
+
import { type ContentItem, getContentType, getItems } from "./content.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A type's items as menu links, for `from` in `Navbar` and `Footer`: in the owner's order for an `ordered` type,
|
|
7
|
+
* else newest first, in the page's language; visitors see published items only.
|
|
8
|
+
*/
|
|
9
|
+
export const itemLinks: ItemLinks = async (key) => {
|
|
10
|
+
const type = getContentType(key);
|
|
11
|
+
const image = imageField(type);
|
|
12
|
+
return ((await getItems(key)) as ContentItem[]).map((item) => itemLink(item, image ? [image] : []));
|
|
13
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { ALWAYS_READ } from "../server/query-params.ts";
|
|
3
|
+
|
|
4
|
+
/** What one page read of its address's query while it was drawn. */
|
|
5
|
+
export class QueryCollector {
|
|
6
|
+
readonly names = new Set<string>(ALWAYS_READ);
|
|
7
|
+
all = false;
|
|
8
|
+
/** The site's own code said what it reads (`readsQuery`), not only Brim's blocks. */
|
|
9
|
+
bySite = false;
|
|
10
|
+
|
|
11
|
+
get read(): string[] | "all" {
|
|
12
|
+
return this.all ? "all" : [...this.names];
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const collectors = new AsyncLocalStorage<QueryCollector>();
|
|
17
|
+
|
|
18
|
+
/** Draws a page (`run`) noting the query parameters its parts read. */
|
|
19
|
+
export function collectingQueryReads<T>(collector: QueryCollector, run: () => T): T {
|
|
20
|
+
return collectors.run(collector, run);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Brim's own blocks note what they read here (the Listing's search, facets and pages; the Search's words). */
|
|
24
|
+
export function noteQueryReads(names: readonly string[] | "all", bySite = false): void {
|
|
25
|
+
const collector = collectors.getStore();
|
|
26
|
+
if (!collector) return;
|
|
27
|
+
if (bySite) collector.bySite = true;
|
|
28
|
+
if (names === "all") collector.all = true;
|
|
29
|
+
else for (const name of names) collector.names.add(name);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Says which query parameters of the address the page or endpoint being drawn reads, so a host that keeps pages in
|
|
34
|
+
* a CDN (Brimsites) keeps those, and only those, in its cache key: `?ref=newsletter` on a page that reads none is
|
|
35
|
+
* the same cached page, and a page reading `?sort=` gets one copy per sort. `"all"` keeps every parameter.
|
|
36
|
+
*
|
|
37
|
+
* ---
|
|
38
|
+
* import { readsQuery } from "@brimsites/brimjs/server";
|
|
39
|
+
* readsQuery(["sort", "color"]);
|
|
40
|
+
* const sort = Astro.url.searchParams.get("sort");
|
|
41
|
+
* ---
|
|
42
|
+
*
|
|
43
|
+
* Call it each time the page is drawn, wherever it reads them (a component of the page may call it too). Brim's
|
|
44
|
+
* own blocks (Listing, Search) declare what they read by themselves. A route whose address is known ahead can be
|
|
45
|
+
* declared in the config instead: `brim({ query: { "/api/products": ["sort", "id"] } })`.
|
|
46
|
+
*/
|
|
47
|
+
export function readsQuery(names: readonly string[] | "all"): void {
|
|
48
|
+
noteQueryReads(names, true);
|
|
49
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import config from "virtual:brim/config";
|
|
2
|
+
import type { Database } from "../db/database.ts";
|
|
3
|
+
import { type QueryRules, QueryReads, composeQueryRules } from "../server/query-params.ts";
|
|
4
|
+
|
|
5
|
+
let reads: QueryReads | undefined;
|
|
6
|
+
|
|
7
|
+
/** What the pages of this build were seen reading, one store for the process (the pages and /admin share it). */
|
|
8
|
+
export function queryReads(db: Database): QueryReads {
|
|
9
|
+
reads ??= new QueryReads(db, config.build);
|
|
10
|
+
return reads;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The `query` /admin/api/info answers: the config's declarations and what pages were seen reading. */
|
|
14
|
+
export async function siteQueryRules(db: Database): Promise<QueryRules> {
|
|
15
|
+
return composeQueryRules(config.query ?? {}, await queryReads(db).learned());
|
|
16
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import config from "virtual:brim/config";
|
|
3
|
+
|
|
4
|
+
/** What one request may see. Set by the middleware, read by helpers that have no request at hand. */
|
|
5
|
+
const requests = new AsyncLocalStorage<{
|
|
6
|
+
editing: boolean;
|
|
7
|
+
locale?: string | undefined;
|
|
8
|
+
preview?: boolean;
|
|
9
|
+
/** What helpers already read for this request (see `perRequest`). */
|
|
10
|
+
memo: Map<string, Promise<unknown>>;
|
|
11
|
+
}>();
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `locale`: the language of the page being drawn (Astro's `currentLocale`), when the site has languages.
|
|
15
|
+
* `preview`: the page is drawn inside the editor, with the changes nobody has saved yet.
|
|
16
|
+
*/
|
|
17
|
+
export function withEditing<T>(editing: boolean, run: () => T, locale?: string, preview = false): T {
|
|
18
|
+
return requests.run({ editing, locale, preview, memo: new Map() }, run);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Reads once per request what several parts of a page ask for (the site's settings in the header, the footer and a
|
|
23
|
+
* button; the same list in a menu and a listing): each read is a round trip to a remote database. Outside a request
|
|
24
|
+
* it just reads.
|
|
25
|
+
*/
|
|
26
|
+
export function perRequest<T>(key: string, read: () => Promise<T>): Promise<T> {
|
|
27
|
+
const memo = requests.getStore()?.memo;
|
|
28
|
+
if (!memo) return read();
|
|
29
|
+
let found = memo.get(key) as Promise<T> | undefined;
|
|
30
|
+
if (!found) {
|
|
31
|
+
found = read();
|
|
32
|
+
memo.set(key, found);
|
|
33
|
+
}
|
|
34
|
+
return found;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** True while the page is drawn in the editor's preview, which shows the unsaved drafts (see `DraftStore`). */
|
|
38
|
+
export function isPreviewing(): boolean {
|
|
39
|
+
return requests.getStore()?.preview ?? false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The language of the page being drawn; `undefined` outside a request (a static build's `getStaticPaths`). */
|
|
43
|
+
export function currentLocale(): string | undefined {
|
|
44
|
+
return requests.getStore()?.locale;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* True when the request comes from someone who may edit: everyone in dev, a signed-in user on the server,
|
|
49
|
+
* nobody in a static build. Private pages and items are shown only then.
|
|
50
|
+
*/
|
|
51
|
+
export function isEditing(): boolean {
|
|
52
|
+
return requests.getStore()?.editing ?? config.mode === "dev";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The elements being drawn inside `<Shared>`: their content is saved once for the whole site. */
|
|
56
|
+
const shared = new AsyncLocalStorage<true>();
|
|
57
|
+
|
|
58
|
+
/** Draws `run` (a `<Shared>` section's content) with "site" as the scope its elements take unless they name one. */
|
|
59
|
+
export function withSharedScope<T>(run: () => T): T {
|
|
60
|
+
return shared.run(true, run);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The scope an element takes when its code names none: "site" inside `<Shared>`, else "page". Every primitive and
|
|
65
|
+
* block uses it as the default of its `scope` prop.
|
|
66
|
+
*/
|
|
67
|
+
export function defaultScope(): "page" | "site" {
|
|
68
|
+
return shared.getStore() ? "site" : "page";
|
|
69
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
import config from "virtual:brim/config";
|
|
3
|
+
import { givenOrigin, requestOrigin } from "../server/http.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `/robots.txt`, added by Brim: everything may be crawled except the editor. It names the sitemap at the site's
|
|
7
|
+
* address, or at the address the server was asked at; a static build without `site` has neither, and no sitemap.
|
|
8
|
+
*/
|
|
9
|
+
export const prerender = true;
|
|
10
|
+
|
|
11
|
+
export const GET: APIRoute = ({ site, request }) => {
|
|
12
|
+
// Behind the CDN the server is asked at its own internal address: the visitor's is in `X-Forwarded-Host`.
|
|
13
|
+
const given = site ?? givenOrigin();
|
|
14
|
+
const origin =
|
|
15
|
+
given ??
|
|
16
|
+
(config.mode === "server"
|
|
17
|
+
? requestOrigin(request)
|
|
18
|
+
: config.mode === "dev"
|
|
19
|
+
? new URL(request.url).origin
|
|
20
|
+
: undefined);
|
|
21
|
+
const sitemap = origin ? `\nSitemap: ${new URL("/sitemap.xml", origin).href}\n` : "";
|
|
22
|
+
return new Response(`User-agent: *\nAllow: /\nDisallow: /admin\n${sitemap}`, {
|
|
23
|
+
headers: {
|
|
24
|
+
"content-type": "text/plain; charset=utf-8",
|
|
25
|
+
// The address asked at is the asker's to write: a cache must not hand this answer to anyone else.
|
|
26
|
+
...(!given && config.mode === "server" && { "cache-control": "no-store" }),
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { GetStaticPaths } from "astro";
|
|
2
|
+
import config from "virtual:brim/config";
|
|
3
|
+
import { FEED_PREFIX, feedAddresses } from "../content/feed.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The feeds of a static build: the same route as `rss.ts`, with the list of feeds the build writes. The server's
|
|
7
|
+
* route has no list, so a server build does not warn that it ignores one.
|
|
8
|
+
*/
|
|
9
|
+
export const prerender = true;
|
|
10
|
+
|
|
11
|
+
export const getStaticPaths: GetStaticPaths = () =>
|
|
12
|
+
feedAddresses(config.contentTypes, config.locales).map(({ path }) => ({
|
|
13
|
+
params: { feed: path.slice(FEED_PREFIX.length) },
|
|
14
|
+
}));
|
|
15
|
+
|
|
16
|
+
export { GET } from "./rss.ts";
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
import config from "virtual:brim/config";
|
|
3
|
+
import routes from "virtual:brim/routes";
|
|
4
|
+
import { buildFeed, feedAt, rssXml } from "../content/feed.ts";
|
|
5
|
+
import { connect } from "./connect.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `/rss/<slug>.xml` and `/rss/<locale>/<slug>.xml`, added by Brim: the RSS feed of every content type that has
|
|
9
|
+
* `feed` set. The server and dev make them on every request; a static build writes them through `rss-static.ts`.
|
|
10
|
+
*/
|
|
11
|
+
export const prerender = false;
|
|
12
|
+
|
|
13
|
+
export const GET: APIRoute = async ({ params, site, url }) => {
|
|
14
|
+
const address = feedAt(params.feed ?? "", config.contentTypes, config.locales);
|
|
15
|
+
if (!address) return new Response(null, { status: 404 });
|
|
16
|
+
const { content, items } = await connect(config.databaseUrl, config.authToken);
|
|
17
|
+
const feed = await buildFeed(address, {
|
|
18
|
+
types: config.contentTypes,
|
|
19
|
+
content,
|
|
20
|
+
items,
|
|
21
|
+
routes,
|
|
22
|
+
locales: config.locales,
|
|
23
|
+
siteName: config.identity?.name,
|
|
24
|
+
});
|
|
25
|
+
// Brim only adds this route to a build when the site's address is set; dev falls back to its own.
|
|
26
|
+
return new Response(rssXml(feed, site ?? url.origin), {
|
|
27
|
+
headers: { "content-type": "application/rss+xml; charset=utf-8" },
|
|
28
|
+
});
|
|
29
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import config from "virtual:brim/config";
|
|
2
|
+
import type { User } from "../auth/accounts.ts";
|
|
3
|
+
import type { Database, Row, SqlValue, Statement } from "../db/database.ts";
|
|
4
|
+
import { requestUser } from "../server/auth.ts";
|
|
5
|
+
import { connect } from "./connect.ts";
|
|
6
|
+
|
|
7
|
+
export { readsQuery } from "./query-reads.ts";
|
|
8
|
+
|
|
9
|
+
export type { Row, SqlValue, Statement, User };
|
|
10
|
+
|
|
11
|
+
/** The site's database as the site's own code uses it. Brim keeps the connection, so there is nothing to close. */
|
|
12
|
+
export type SiteDatabase = Pick<Database, "query" | "batch">;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The site's SQLite database, for tables of the site's own: the same database Brim keeps the content in, so it
|
|
16
|
+
* is backed up and moved with it. Name your tables without the `brim_` prefix, which is Brim's.
|
|
17
|
+
*/
|
|
18
|
+
export async function getDatabase(): Promise<SiteDatabase> {
|
|
19
|
+
const { db } = await connect(config.databaseUrl, config.authToken);
|
|
20
|
+
return { query: (sql, args) => db.query(sql, args), batch: (statements) => db.batch(statements) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Who is signed in to the editor behind a request, or `undefined` for a visitor: the editor's session cookie,
|
|
25
|
+
* or an access token from `brim token add`. For endpoints only the site's owner may call.
|
|
26
|
+
*/
|
|
27
|
+
export async function getUser(request: Request): Promise<User | undefined> {
|
|
28
|
+
return requestUser(await connect(config.databaseUrl, config.authToken), request);
|
|
29
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
import config from "virtual:brim/config";
|
|
3
|
+
import routes from "virtual:brim/routes";
|
|
4
|
+
import { sitemapEntries, sitemapXml } from "../content/sitemap.ts";
|
|
5
|
+
import { givenOrigin, requestOrigin } from "../server/http.ts";
|
|
6
|
+
import { connect } from "./connect.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `/sitemap.xml`, added by Brim. The build writes it from the content as it is then; in dev it is made on
|
|
10
|
+
* every request, so a page or item just published shows up at once.
|
|
11
|
+
*/
|
|
12
|
+
export const prerender = true;
|
|
13
|
+
|
|
14
|
+
export const GET: APIRoute = async ({ site, request }) => {
|
|
15
|
+
const { content, items } = await connect(config.databaseUrl, config.authToken);
|
|
16
|
+
const entries = await sitemapEntries({
|
|
17
|
+
content,
|
|
18
|
+
items,
|
|
19
|
+
contentTypes: config.contentTypes,
|
|
20
|
+
pageTemplates: config.pageTemplates,
|
|
21
|
+
routes,
|
|
22
|
+
locales: config.locales,
|
|
23
|
+
});
|
|
24
|
+
// A static build adds this route only when the site's address is set; a server whose address is not set answers
|
|
25
|
+
// with the one it was asked at, which is the asker's to write: a cache must not hand that answer to anyone else.
|
|
26
|
+
const given = site ?? givenOrigin();
|
|
27
|
+
const asked = config.mode === "server" ? requestOrigin(request) : new URL(request.url).origin;
|
|
28
|
+
return new Response(sitemapXml(entries, given ?? asked), {
|
|
29
|
+
headers: {
|
|
30
|
+
"content-type": "application/xml; charset=utf-8",
|
|
31
|
+
...(!given && config.mode === "server" && { "cache-control": "no-store" }),
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
};
|