bearminion 1.20.0 → 1.22.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 (47) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +3 -3
  3. package/dist/astro.d.ts +16 -7
  4. package/dist/astro.js +212 -93
  5. package/dist/cli.js +903 -4
  6. package/dist/content-types-46XqPaW4.js +505 -0
  7. package/dist/content.d.ts +24 -3
  8. package/dist/content.js +83 -6
  9. package/dist/{editor-context-DzRwKENi.d.ts → editor-context-D1yfPp21.d.ts} +95 -8
  10. package/dist/{github-store-Dt_YuOPD.js → github-store-B2folBeq.js} +551 -206
  11. package/dist/{github-store-DsLCe5MR.d.ts → github-store-CuhvbFCh.d.ts} +1 -1
  12. package/dist/hosted-astro.js +1 -1
  13. package/dist/{hosted-middleware-CsROahka.js → hosted-middleware-DHLIedeV.js} +1 -1
  14. package/dist/hosted-overlay.js +1 -1
  15. package/dist/hosted.d.ts +10 -4
  16. package/dist/hosted.js +68 -9
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +11 -6
  19. package/dist/{migrate-b408EaLp.js → migrate-Cm30puW8.js} +2 -2
  20. package/dist/{page-wlcQJAA-.js → page-C7zE_HD1.js} +5 -1
  21. package/dist/{page-BGSTL63-.d.ts → page-CpVElMPH.d.ts} +193 -37
  22. package/dist/{request-guards-BcSUj8Gc.js → request-guards-DtNVdqQ7.js} +1 -1
  23. package/dist/{collections-Bm3RWg2K.js → routing-jKeq4LwO.js} +213 -57
  24. package/dist/routing-yPy8hEfZ.d.ts +137 -0
  25. package/dist/{theme-BvqJ8UnS.js → theme-DTVVNMlr.js} +1 -1
  26. package/dist/ui/mount.js +3294 -1259
  27. package/package.json +2 -2
  28. package/registry/default/files/src/components/organisms/EntryList.astro +83 -0
  29. package/registry/default/files/src/components/organisms/Pagination.astro +56 -0
  30. package/registry/default/files/src/components/sections/contact/definition.ts +6 -2
  31. package/registry/default/files/src/components/sections/faq/definition.ts +2 -2
  32. package/registry/default/files/src/components/sections/media/Media.astro +2 -2
  33. package/registry/default/files/src/components/sections/media/MediaPlayer.astro +2 -2
  34. package/registry/default/files/src/components/sections/pricing/definition.ts +16 -1
  35. package/registry/default/files/src/components/sections/shared.ts +3 -0
  36. package/registry/default/files/src/components/sections/stats/definition.ts +6 -1
  37. package/registry/default/files/src/components/sections/testimonials/definition.ts +13 -1
  38. package/registry/default/files/src/components/sections/text-image/definition.ts +1 -1
  39. package/registry/default/files/src/components/seo/Seo.astro +3 -1
  40. package/registry/default/files/src/content.config.ts +21 -0
  41. package/registry/default/files/src/env.d.ts +2 -0
  42. package/registry/default/files/src/lib/content.ts +81 -0
  43. package/registry/default/files/src/lib/editing.ts +6 -0
  44. package/registry/default/files/src/lib/sitemap.ts +48 -0
  45. package/registry/default/files/src/pages/[...slug].astro +30 -16
  46. package/registry/default/registry.json +77 -21
  47. package/dist/preview-DFLna-Be.d.ts +0 -42
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.22.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 6656dcd: The editor is now a shell around the page: a navigation on the left (Pages, every content type, Media, Navigation, Footer, Site, Design, SEO) that collapses to an icon rail with Ctrl/Cmd+\, a top bar with the breadcrumb, undo and redo, version history, the unsaved changes, Preview and Save, and a resizable inspector on the right with the Page and Section tabs. The page itself is still where you edit.
8
+
9
+ - Content listings: every page and every entry of a content type in a table with search, Published, Draft and Unsaved tabs, sorting, bulk delete, duplicate, view and ten rows a page. `GET /pages` and the entries of a type also return `draft`, `noindex` and `updatedAt`.
10
+ - Media: the image library with where each image is used, upload and delete. `GET /images?usage=1` returns the uses.
11
+ - Navigation, Footer, Site, Design and SEO are full screens with a card per group. Search defaults moved from Site to SEO.
12
+ - SEO: the site's structured data is edited inline, one card per JSON-LD block, instead of in a dialog. New Indexing switches turn search engines (`site.seo.robots`) and `sitemap.xml` (`site.seo.sitemap`) off for the whole site. A site created earlier needs three small edits to its own `Seo.astro`, `robots.txt.ts` and `astro.config.ts` for them to take effect: see the editor docs.
13
+ - Pages have a status: a draft (`"status": "draft"`) is left out of the build, the listings and the sitemap, and still shows in `astro dev`. Files without a status stay published, and no file of your site needs to change for this.
14
+ - Tablet and mobile frames show the unsaved draft at 820px and 390px.
15
+ - The dock and the Save menu are gone: undo, redo, history, discard and commit live in the top bar.
16
+
17
+ ### Patch Changes
18
+
19
+ - 8fa088c: Shorter npm description for `bearminion`, and `create-bearminion` no longer carries the `withastro` keyword, so the Astro integrations library lists BearMinion once.
20
+
21
+ ## 1.21.0
22
+
23
+ ### Minor Changes
24
+
25
+ - 4cc33c5: Content types: declare a blog, a news list or a fixed page in the content model, and get entries with their own fields, a sort order, a paginated listing page and lists in the editor. Guide: [Content types](https://docs.bearminion.com/content-types/). A site that declares no types builds the same HTML as before with the files it has.
26
+
27
+ - **The home page is a fixed page.** "Home page" is gone from the page form, and so are `POST /pages/:slug/set-home` and `previousHomeSlug` in `POST /save`. No page can be renamed to `index`. Nothing in your content changes: `content/pages/index.json` is still the home page. To change what visitors see first, edit the home page's sections. If you really want another page's content there, swap the two files in git and set each file's `slug`.
28
+ - **Content types in the editor API.** `types: defineTypes({ blog: multi({ path: '/blog/{slug}', fields, sort, listing }), about: single({ path: '/about' }) })` in the content model declares the site's own types next to the built-in home page, 404 page and `pages`. New routes: `GET /types`, `/types/:id/entries` (list, create, read, save, rename, delete), `/types/:id/listing` and `/types/:id/document`. `/pages` works as before. Deleting an image or video now also checks entries, listing pages and singles, and a page cannot take a slug that is the address of a type.
29
+ - **Migrations are told the type.** A `ContentMigration` receives the content type's id as a third argument. Existing migrations need no change.
30
+ - **Routing for types.** `siteRoutes(model, content)` lists every address of the site with what it shows (pages, singles, entries, and each listing page with its entries and pagination), `findRoute` picks one, and the hosted editor's `content.getRoute(pathname)` answers the same for one address from the repository. `loadContent()` also returns `entries`, `listings` and `singles`, and `contentCollections()` returns the extra collections under `types`. A site without `types` gets what it got before: two collections, the same pages.
31
+ - **The starter publishes declared types.** `src/pages/[...slug].astro` draws pages, entries, singles and listing pages from one route list, with two new components for a listing: `EntryList.astro` (a card per entry: title, and `date`, `excerpt` and `cover` when the type has fields by those names) and `Pagination.astro`. Listing page 2 and later is at `/blog/page/2`, has its own title and canonical address, and is in the sitemap. An entry whose `draft` field is on shows in `astro dev` and is left out of a build. A site without types builds the same HTML as before.
32
+ - **A build says when the site's files are too old for its types.** A site that declares a type but still has the route file from before content types fails `astro build` with the list of addresses that were not written and the fix (`npx bearminion add type --files-only`); `astro dev` warns. A site that declares no types is never checked.
33
+ - **`npx bearminion add type --files-only`** updates the files of a site made before 1.21 to the ones that publish content types: the page route, the collections, the content readers and the two listing components. Files you did not change are replaced, files you changed stop the command, and your `astro.config.ts` and content model are never edited. Only a site that declares a type needs it.
34
+ - **Content types in the editor.** Each declared type has its own list under Pages, in its sort order, with a New entry form; a title is enough to create an entry, and a required date starts as today. An entry opens at its own address. Its fields (date, excerpt, cover, a switch, a choice, a list) are edited in a Fields group drawn from the type's schema, and the section picker offers only the sections the type allows. Listing pages and singles are listed and edited like pages, with a fixed address. Links to entries are offered in the link picker and checked like links to pages. Drafts, undo and saved versions are kept per document.
35
+ - **`npx bearminion add type`** declares a content type. In a terminal it asks for the id, many entries or one page, the address, the fields (text, paragraph, date, number, switch, choice, image, list), a listing page and the order; scripts and assistants pass `--kind`, `--path`, `--label`, `--field name:kind`, `--sort` and `--listing` instead. Each type is its own file in `src/lib/types/`, gathered by `src/lib/types/index.ts` and passed to the content model as `types: siteTypes`, so a second and third type are a new file and one line each. It checks the type as `astro dev` would, and that no page or other type has its address, before writing anything, and it updates the site's own files first, like `--files-only`. **`npx bearminion add blog`** is `add type` with the blog answered: posts at `/blog/<slug>` with a date, an excerpt, a cover and a draft switch, newest first, listed at `/blog`. A new site starts with pages only.
36
+ - **A new site starts lean.** It has nine sections: Hero, Steps, Gallery, Features, Text, Text + Image, Media, FAQ and Call to action. Logo strip, Stats, Testimonials and Pricing are one `npx bearminion add <name>` away. The Contact section is not in a new site, because its form needs a handler and host glue to send anything: **`npx bearminion add form`** now adds the section along with them when the site has none. The sample pages link to `mailto:hello@example.com` where they linked to the Contact section. Existing sites keep every section they have.
37
+
3
38
  ## 1.20.0
4
39
 
5
40
  ### Minor Changes
package/README.md CHANGED
@@ -28,13 +28,13 @@ npm run dev
28
28
  It asks for the site's name and web address. Open the address `npm run dev` prints, press **Ctrl+E** (**Cmd+E** on a Mac), click any text to change it, and press **Ctrl/Cmd+S** to save. Push the folder to GitHub and import it in Vercel, Netlify or Cloudflare Pages to put it online.
29
29
 
30
30
  <p align="center">
31
- <img src="https://raw.githubusercontent.com/langehelp-software/bearminion/main/.github/assets/editor.png" alt="The BearMinion editor: a section toolbar on the hero, a heading being edited, and the Pages tab in the sidebar" width="100%" />
31
+ <img src="https://raw.githubusercontent.com/langehelp-software/bearminion/main/.github/assets/editor.png" alt="The BearMinion editor: the navigation, the page with a section toolbar on the hero, and the inspector" width="100%" />
32
32
  </p>
33
33
 
34
34
  ## What you can change
35
35
 
36
36
  - **Text** right on the page, with bold, italic, code, links and lists
37
- - **Sections**: fourteen ready-made types, each with two or three layouts, added from a visual picker
37
+ - **Sections**: fourteen ready-made types, each with two or three layouts, added from a visual picker. A new site has nine; `npx bearminion add` brings the rest
38
38
  - **Pages, menus and footer**, with titles and descriptions for search and sharing
39
39
  - **Images**: upload, choose how they fill their frame and which part stays in view
40
40
  - **Colors**: pick three, and the editor builds a full light and dark palette that stays readable
@@ -44,7 +44,7 @@ Content is plain JSON in your project, validated on every save and kept in your
44
44
  **Editing online is opt-in.** `npx bearminion add hosted` sets up a second deployment where people sign in with GitHub and edit in the browser. Whoever may push to the repository may edit, and every save is a commit under their name. See [Edit online](https://docs.bearminion.com/hosted-editor/).
45
45
 
46
46
  <p align="center">
47
- <img src="https://raw.githubusercontent.com/langehelp-software/bearminion/main/.github/assets/design.png" alt="The Design tab: color mode, brand, neutral and link colors, and a preview of every section tone in light and dark mode" width="100%" />
47
+ <img src="https://raw.githubusercontent.com/langehelp-software/bearminion/main/.github/assets/design.png" alt="The Design screen: color mode, brand, neutral and link colors, and a preview of every section tone in light and dark mode" width="100%" />
48
48
  </p>
49
49
 
50
50
  ## Learn more
package/dist/astro.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { _ as CollectionOptions, b as StoreOperation, n as ImageConvertOptions, t as EditorContext, x as UploadStore, y as ContentStore } from "./editor-context-DzRwKENi.js";
2
- import { i as StoreKeyError, n as githubStore, r as StoreError, t as GithubStoreOptions } from "./github-store-DsLCe5MR.js";
3
- import { _ as SectionRegistry, d as SectionOf, g as ContentModel, gt as SiteOf, ht as SiteDefinition, n as PageRules, t as Page, w as ContentMigrator } from "./page-BGSTL63-.js";
1
+ import { E as UploadStore, S as CollectionOptions, T as StoreOperation, n as ImageConvertOptions, t as EditorContext, w as ContentStore } from "./editor-context-D1yfPp21.js";
2
+ import { i as StoreKeyError, n as githubStore, r as StoreError, t as GithubStoreOptions } from "./github-store-CuhvbFCh.js";
3
+ import { D as Entry, Ft as SiteDefinition, G as SectionOf, It as SiteOf, T as ContentType, b as ContentMigrator, f as ContentModel, k as ListingDocument, n as PageRules, p as SectionRegistry, t as Page } from "./page-CpVElMPH.js";
4
4
  import { AstroIntegration } from "astro";
5
5
  //#region src/store.d.ts
6
6
  interface FileStoreOptions {
@@ -38,8 +38,7 @@ interface BearminionOptions extends ContentModel {
38
38
  /**
39
39
  * Which page operations the editor allows: `{ rename: false, delete: false }` for a site whose addresses must not
40
40
  * change (they carry search ranking or are the target of redirects). Both default to true. A locked operation is
41
- * refused by the API as well as hidden in the editor. `rename: false` also blocks making another page the home page,
42
- * because that moves the old home page to a new address.
41
+ * refused by the API as well as hidden in the editor.
43
42
  */
44
43
  pages?: Partial<PageRules>;
45
44
  /**
@@ -88,7 +87,8 @@ interface BearminionIntegration extends AstroIntegration {
88
87
  /**
89
88
  * Dev-only Astro integration. `astro build`, `astro preview`, and `astro sync`
90
89
  * return before any plugin, route, or script is registered. `astro:server:setup`
91
- * runs only while `astro dev` is serving.
90
+ * runs only while `astro dev` is serving. A build adds nothing to the site either; it only checks, once the pages
91
+ * are written, that every declared content type got its pages.
92
92
  */
93
93
  export declare function bearminion(options: BearminionOptions): BearminionIntegration;
94
94
  //#endregion
@@ -105,7 +105,14 @@ interface LoadOptions {
105
105
  }
106
106
  interface LoadedContent<TModel extends ContentModel = ContentModel> {
107
107
  site: SiteOf<TModel['site']>;
108
+ /** Everything in `pages/`: the home page (`index`), the 404 page and the pages. */
108
109
  pages: Page<SectionOf<TModel['sections']>>[];
110
+ /** The entries of each type the model declares, by type id, in file name order. Empty for a model with no types. */
111
+ entries: Record<string, Entry[]>;
112
+ /** The listing page document of each type that has one saved, by type id. */
113
+ listings: Record<string, ListingDocument>;
114
+ /** The document of each declared single that has been saved, by type id. */
115
+ singles: Record<string, Entry>;
109
116
  }
110
117
  /**
111
118
  * Load `site.json` and `pages/*.json` from a content directory.
@@ -118,7 +125,9 @@ export declare function loadSite<TDefinition extends SiteDefinition>(contentDir:
118
125
  * Validate every `contentDir/pages/*.json` file.
119
126
  * Pages are returned in filename order. Slugs must be unique.
120
127
  */
121
- export declare function loadPages<TRegistry extends SectionRegistry>(contentDir: string, registry: TRegistry, { migrator, tolerateOrphans }?: LoadOptions): Page<SectionOf<TRegistry>>[];
128
+ export declare function loadPages<TRegistry extends SectionRegistry>(contentDir: string, registry: TRegistry, { migrator, tolerateOrphans, typeOf }?: LoadOptions & {
129
+ typeOf?: (slug: string) => ContentType;
130
+ }): Page<SectionOf<TRegistry>>[];
122
131
  //#endregion
123
132
  //#region src/hosted-integration.d.ts
124
133
  interface HostedEditorIntegrationOptions {
package/dist/astro.js CHANGED
@@ -1,12 +1,13 @@
1
- import { O as ContentReadError, S as loadThemePreview, _ as parseKey, b as PreviewUnavailableError, c as resolveCollections, k as ContentValidationError, v as StoreError, y as StoreKeyError } from "./collections-Bm3RWg2K.js";
2
- import { t as defaultTheme } from "./theme-BvqJ8UnS.js";
3
- import { a as resolvePageRules, n as createPageSchema, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
4
- import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
1
+ import { A as ContentValidationError, C as loadThemePreview, c as siteRoutes, g as resolveCollections, k as ContentReadError, s as normalizePath, x as PreviewUnavailableError } from "./routing-jKeq4LwO.js";
2
+ import { t as defaultTheme } from "./theme-DTVVNMlr.js";
3
+ import { i as createTolerantPageSchema, r as createPageSchema, s as resolvePageRules } from "./page-C7zE_HD1.js";
4
+ import { D as StoreKeyError, E as StoreError, i as LISTING_MIGRATION_TYPE, l as createEntrySchema, r as LISTING_FILE, u as createListingSchema, w as parseKey, y as resolveTypes } from "./content-types-46XqPaW4.js";
5
+ import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, t as SCHEMA_VERSION_KEY } from "./migrate-Cm30puW8.js";
5
6
  import { i as resolveMaxImageBytes, n as formatBytes, r as resolveConvert } from "./upload-rules-Cao9uY5K.js";
6
- import { n as isLocalRequest, t as JSON_BODY_LIMIT } from "./request-guards-BcSUj8Gc.js";
7
+ import { n as isLocalRequest, t as JSON_BODY_LIMIT } from "./request-guards-DtNVdqQ7.js";
7
8
  import { i as resolveInside, n as isInside, r as resolveDir, t as asDirectory } from "./security-CBiOYdVE.js";
8
9
  import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CzUHR7oS.js";
9
- import { a as isHistoryId, c as imageBodyLimit, d as stableStringify, i as historyId, l as IMAGE_EXTENSION, n as missingImageSvg, o as COMMIT_MESSAGE_LIMIT, p as videoBodyLimit, r as handleEditorRequest, s as GitError, t as githubStore, u as uploadStem } from "./github-store-Dt_YuOPD.js";
10
+ import { a as isHistoryId, c as imageBodyLimit, d as stableStringify, i as historyId, l as IMAGE_EXTENSION, n as missingImageSvg, o as COMMIT_MESSAGE_LIMIT, p as videoBodyLimit, r as handleEditorRequest, s as GitError, t as githubStore, u as uploadStem } from "./github-store-B2folBeq.js";
10
11
  import { S as isAssetPath } from "./draft-store-DBEfw_Gq.js";
11
12
  import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-BzVw721A.js";
12
13
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
@@ -245,6 +246,14 @@ function createFileStore({ root, contentDir, uploadsDir, videosDir }) {
245
246
  const filePath = resolve(key);
246
247
  return access(filePath).then(() => true, () => false);
247
248
  },
249
+ async modified(key) {
250
+ try {
251
+ return (await stat(resolve(key))).mtimeMs;
252
+ } catch (error) {
253
+ if (isErrno$1(error) && (error.code === "ENOENT" || error.code === "ENOTDIR")) return void 0;
254
+ throw error;
255
+ }
256
+ },
248
257
  async list(dir) {
249
258
  const directory = resolve(dir);
250
259
  let entries;
@@ -453,7 +462,9 @@ function idToIso(id) {
453
462
  return `${id.slice(0, 4)}-${id.slice(4, 6)}-${id.slice(6, 8)}T${id.slice(9, 11)}:${id.slice(11, 13)}:${id.slice(13, 15)}.${id.slice(15, 18)}Z`;
454
463
  }
455
464
  function directory(context, scope, slug) {
456
- return scope === "site" ? path.join(context.root, HISTORY_DIR, "site") : path.join(context.root, HISTORY_DIR, "pages", slug);
465
+ if (scope === "site") return path.join(context.root, HISTORY_DIR, "site");
466
+ if (scope === "entry") return path.join(context.root, HISTORY_DIR, "types", ...slug.split("/"));
467
+ return path.join(context.root, HISTORY_DIR, "pages", slug);
457
468
  }
458
469
  async function ids(dir) {
459
470
  try {
@@ -526,6 +537,7 @@ function resolveEditorContext(options, rootInput) {
526
537
  const contentDir = resolveDir(root, options?.contentDir, DEFAULT_CONTENT_DIR);
527
538
  const uploadsDir = resolveDir(root, options?.uploadsDir, DEFAULT_UPLOADS_DIR);
528
539
  const videosDir = resolveDir(root, options?.videosDir, DEFAULT_VIDEOS_DIR);
540
+ const pageRules = resolvePageRules(options?.pages);
529
541
  const context = {
530
542
  root,
531
543
  contentDir,
@@ -533,9 +545,10 @@ function resolveEditorContext(options, rootInput) {
533
545
  videosDir,
534
546
  maxVideoBytes: options?.maxVideoBytes ?? 52428800,
535
547
  maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
536
- pageRules: resolvePageRules(options?.pages),
548
+ pageRules,
537
549
  imageConvert: resolveConvert(options?.imageConvert),
538
550
  sections: options.sections,
551
+ types: resolveTypes(options, pageRules),
539
552
  site: options.site,
540
553
  theme: options.theme ?? defaultTheme,
541
554
  store: options.store ?? createFileStore({
@@ -744,13 +757,190 @@ function stripTrailingSlash(pathname) {
744
757
  return pathname;
745
758
  }
746
759
  //#endregion
760
+ //#region src/load.ts
761
+ /**
762
+ * Load `site.json` and `pages/*.json` from a content directory.
763
+ * Throws {@link ContentReadError} or {@link ContentValidationError} with the file path.
764
+ */
765
+ function loadContent(contentDir, model, options = {}) {
766
+ const migrator = createMigrator(model);
767
+ const types = resolveTypes(model);
768
+ const tolerateOrphans = options.tolerateOrphans === true;
769
+ const entries = {};
770
+ const listings = {};
771
+ const singles = {};
772
+ for (const type of types.multi) {
773
+ if (type === types.pages) continue;
774
+ const dir = path.join(contentDir, type.dir);
775
+ const schema = createEntrySchema(model.sections, type, { tolerateOrphans });
776
+ const files = jsonFiles(dir, { missing: "empty" }).filter((name) => !name.startsWith("_"));
777
+ entries[type.id] = uniqueSlugs(dir, files, files.map((name) => parseFile(path.join(dir, name), schema, migrator, "page", type.id)));
778
+ const listingFile = path.join(dir, LISTING_FILE);
779
+ if (type.listing && fs.existsSync(listingFile)) listings[type.id] = parseFile(listingFile, createListingSchema(model.sections, { tolerateOrphans }), migrator, "page", LISTING_MIGRATION_TYPE);
780
+ }
781
+ for (const type of types.singles) {
782
+ const file = path.join(contentDir, type.key);
783
+ if (type.builtIn || !fs.existsSync(file)) continue;
784
+ singles[type.id] = parseFile(file, createEntrySchema(model.sections, type, { tolerateOrphans }), migrator, "page", type.id);
785
+ }
786
+ return {
787
+ site: loadSite(contentDir, model.site, { migrator }),
788
+ pages: loadPages(contentDir, model.sections, {
789
+ migrator,
790
+ ...options,
791
+ typeOf: (slug) => slug === types.home.slug ? types.home : slug === types.notFound.slug ? types.notFound : types.pages
792
+ }),
793
+ entries,
794
+ listings,
795
+ singles
796
+ };
797
+ }
798
+ /** Names of the `.json` files directly inside `dir`, sorted. */
799
+ function jsonFiles(dir, options) {
800
+ let entries;
801
+ try {
802
+ entries = fs.readdirSync(dir, { withFileTypes: true });
803
+ } catch (error) {
804
+ if (isErrno(error) && error.code === "ENOENT") {
805
+ if (options.missing === "empty") return [];
806
+ throw new ContentReadError(dir, `Pages directory not found: ${dir}`);
807
+ }
808
+ const message = error instanceof Error ? error.message : String(error);
809
+ throw new ContentReadError(dir, `Unable to read pages directory ${dir}: ${message}`);
810
+ }
811
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
812
+ }
813
+ function uniqueSlugs(dir, files, documents) {
814
+ const seen = /* @__PURE__ */ new Map();
815
+ for (const [index, document] of documents.entries()) {
816
+ const filePath = path.join(dir, files[index] ?? "");
817
+ const previous = seen.get(document.slug);
818
+ if (previous !== void 0) throw new ContentValidationError(filePath, [{
819
+ path: ["slug"],
820
+ message: `Duplicate slug "${document.slug}" (also defined in ${previous})`
821
+ }]);
822
+ seen.set(document.slug, filePath);
823
+ }
824
+ return documents;
825
+ }
826
+ /** Validate and return `contentDir/site.json`. */
827
+ function loadSite(contentDir, site, { migrator = createMigrator() } = {}) {
828
+ return parseFile(path.join(contentDir, "site.json"), site.schema, migrator, "site");
829
+ }
830
+ /**
831
+ * Validate every `contentDir/pages/*.json` file.
832
+ * Pages are returned in filename order. Slugs must be unique.
833
+ */
834
+ function loadPages(contentDir, registry, { migrator = createMigrator(), tolerateOrphans = false, typeOf } = {}) {
835
+ const pagesDir = path.join(contentDir, "pages");
836
+ const files = jsonFiles(pagesDir, { missing: "throw" });
837
+ const pageSchema = tolerateOrphans ? createTolerantPageSchema(registry) : createPageSchema(registry);
838
+ return uniqueSlugs(pagesDir, files, files.map((name) => {
839
+ const filePath = path.join(pagesDir, name);
840
+ if (!typeOf) return parseFile(filePath, pageSchema, migrator, "page");
841
+ const raw = readJsonFile(filePath);
842
+ const type = typeOf(typeof raw === "object" && raw !== null && "slug" in raw && typeof raw.slug === "string" ? raw.slug : "");
843
+ return parseFile(filePath, createEntrySchema(registry, type, { tolerateOrphans }), migrator, "page", type.id);
844
+ }));
845
+ }
846
+ function parseFile(filePath, schema, migrator, kind, type) {
847
+ const upgraded = migrator.upgrade(readJsonFile(filePath), kind, type);
848
+ if (!upgraded.ok) throw new ContentValidationError(filePath, [{
849
+ path: [SCHEMA_VERSION_KEY],
850
+ message: upgraded.message
851
+ }]);
852
+ const result = schema.safeParse(upgraded.value);
853
+ if (!result.success) throw new ContentValidationError(filePath, toIssues(result.error.issues));
854
+ return result.data;
855
+ }
856
+ function readJsonFile(filePath) {
857
+ let raw;
858
+ try {
859
+ raw = fs.readFileSync(filePath, "utf8");
860
+ } catch (error) {
861
+ if (isErrno(error) && error.code === "ENOENT") throw new ContentReadError(filePath, `Content file not found: ${filePath}`);
862
+ const message = error instanceof Error ? error.message : String(error);
863
+ throw new ContentReadError(filePath, `Unable to read ${filePath}: ${message}`);
864
+ }
865
+ try {
866
+ return JSON.parse(raw);
867
+ } catch (error) {
868
+ const message = error instanceof Error ? error.message : String(error);
869
+ throw new ContentReadError(filePath, `Invalid JSON in ${filePath}: ${message}`);
870
+ }
871
+ }
872
+ function toIssues(issues) {
873
+ return issues.map((issue) => ({
874
+ path: [...issue.path],
875
+ message: issue.message
876
+ }));
877
+ }
878
+ function isErrno(error) {
879
+ return error instanceof Error && "code" in error;
880
+ }
881
+ //#endregion
882
+ //#region src/route-check.ts
883
+ const TYPES_UPGRADE_DOCS = "https://docs.bearminion.com/content-types/#upgrading-from-120";
884
+ const ROUTE_FILE = "src/pages/[...slug].astro";
885
+ /** True when the model declares something beyond the built-in home page, 404 page and pages. */
886
+ function declaresTypes(model) {
887
+ const types = resolveTypes(model);
888
+ return types.multi.length > 1 || types.singles.some((type) => !type.builtIn);
889
+ }
890
+ /** `blog/first/`, `/blog/first/index.html` and `blog/first.html` are all the address `/blog/first`. */
891
+ function emittedPath(pathname) {
892
+ const trimmed = pathname.replace(/(^|\/)index\.html$/, "").replace(/\.html$/, "");
893
+ return normalizePath(`/${trimmed.replace(/^\/+/, "")}`);
894
+ }
895
+ /**
896
+ * The addresses of declared types, singles and listings that the build should have written and did not. `emitted` is
897
+ * the `pathname` of every page Astro built. Empty for a model that declares nothing of its own.
898
+ */
899
+ function missingRoutes(model, contentDir, emitted) {
900
+ if (!declaresTypes(model)) return [];
901
+ const types = resolveTypes(model);
902
+ const builtIn = /* @__PURE__ */ new Set([
903
+ types.home.id,
904
+ types.notFound.id,
905
+ types.pages.id
906
+ ]);
907
+ const content = loadContent(contentDir, model);
908
+ const lang = content.site.lang;
909
+ const built = new Set(emitted.map(emittedPath));
910
+ return siteRoutes(model, content, typeof lang === "string" ? { locale: lang } : {}).filter((route) => !builtIn.has(route.type)).map((route) => route.path).filter((routePath) => !built.has(routePath));
911
+ }
912
+ function missingRoutesMessage(missing) {
913
+ return `The content model declares content types, but the build wrote no page for: ${missing.slice(0, 10).join(", ")}${missing.length > 10 ? ` and ${missing.length - 10} more` : ""}. ${ROUTE_FILE} is the starter's file from before content types and knows only pages. Update the site's files with \`npx bearminion add type --files-only\`, then build again. ${TYPES_UPGRADE_DOCS}`;
914
+ }
915
+ /**
916
+ * Why the route file of the project at `root` cannot serve declared types, or undefined when it can, when the model
917
+ * declares none, or when the site has its own routes. For `astro dev`, where pages are drawn one request at a time
918
+ * and there is no list of built pages to compare.
919
+ */
920
+ function staleRouteFile(model, root) {
921
+ if (!declaresTypes(model)) return void 0;
922
+ const file = path.join(root, ROUTE_FILE);
923
+ let source;
924
+ try {
925
+ if (!existsSync(file)) return void 0;
926
+ source = readFileSync(file, "utf8");
927
+ } catch {
928
+ return;
929
+ }
930
+ if (source.includes("getRoute")) return void 0;
931
+ return `The content model declares content types, but ${ROUTE_FILE} is the starter's file from before content types: entries, singles and listing pages will answer 404. Update the site's files with \`npx bearminion add type --files-only\`. ${TYPES_UPGRADE_DOCS}`;
932
+ }
933
+ //#endregion
747
934
  //#region src/integration.ts
748
935
  /**
749
936
  * Dev-only Astro integration. `astro build`, `astro preview`, and `astro sync`
750
937
  * return before any plugin, route, or script is registered. `astro:server:setup`
751
- * runs only while `astro dev` is serving.
938
+ * runs only while `astro dev` is serving. A build adds nothing to the site either; it only checks, once the pages
939
+ * are written, that every declared content type got its pages.
752
940
  */
753
941
  function bearminion(options) {
942
+ /** Set once the config is final: the project root, and whether every page is written at build time. */
943
+ let project;
754
944
  return {
755
945
  name: "bearminion",
756
946
  hooks: {
@@ -763,6 +953,8 @@ function bearminion(options) {
763
953
  }
764
954
  }
765
955
  if (command !== "dev") return;
956
+ const stale = staleRouteFile(options, rootPath(config.root));
957
+ if (stale) logger.warn(stale);
766
958
  const context = resolveEditorContext(options, rootInput(config.root));
767
959
  updateConfig({ vite: {
768
960
  server: { watch: { ignored: [
@@ -774,6 +966,17 @@ function bearminion(options) {
774
966
  } });
775
967
  injectScript("page", "import \"virtual:bearminion-editor\"");
776
968
  },
969
+ "astro:config:done"({ config }) {
970
+ project = {
971
+ root: rootPath(config.root),
972
+ static: config.output === "static"
973
+ };
974
+ },
975
+ "astro:build:done"({ pages }) {
976
+ if (!project?.static) return;
977
+ const missing = missingRoutes(options, resolveDir(project.root, options.contentDir, DEFAULT_CONTENT_DIR), pages.map((page) => page.pathname));
978
+ if (missing.length > 0) throw new Error(missingRoutesMessage(missing));
979
+ },
777
980
  "astro:server:setup"({ server, logger }) {
778
981
  const context = resolveEditorContext(options, server.config.root);
779
982
  const previewModule = options.previewModule ?? "/src/lib/render-preview.ts";
@@ -860,90 +1063,6 @@ function rootInput(root) {
860
1063
  return process.cwd();
861
1064
  }
862
1065
  //#endregion
863
- //#region src/load.ts
864
- /**
865
- * Load `site.json` and `pages/*.json` from a content directory.
866
- * Throws {@link ContentReadError} or {@link ContentValidationError} with the file path.
867
- */
868
- function loadContent(contentDir, model, options = {}) {
869
- const migrator = createMigrator(model);
870
- return {
871
- site: loadSite(contentDir, model.site, { migrator }),
872
- pages: loadPages(contentDir, model.sections, {
873
- migrator,
874
- ...options
875
- })
876
- };
877
- }
878
- /** Validate and return `contentDir/site.json`. */
879
- function loadSite(contentDir, site, { migrator = createMigrator() } = {}) {
880
- return parseFile(path.join(contentDir, "site.json"), site.schema, migrator, "site");
881
- }
882
- /**
883
- * Validate every `contentDir/pages/*.json` file.
884
- * Pages are returned in filename order. Slugs must be unique.
885
- */
886
- function loadPages(contentDir, registry, { migrator = createMigrator(), tolerateOrphans = false } = {}) {
887
- const pagesDir = path.join(contentDir, "pages");
888
- let entries;
889
- try {
890
- entries = fs.readdirSync(pagesDir, { withFileTypes: true });
891
- } catch (error) {
892
- if (isErrno(error) && error.code === "ENOENT") throw new ContentReadError(pagesDir, `Pages directory not found: ${pagesDir}`);
893
- const message = error instanceof Error ? error.message : String(error);
894
- throw new ContentReadError(pagesDir, `Unable to read pages directory ${pagesDir}: ${message}`);
895
- }
896
- const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
897
- const pageSchema = tolerateOrphans ? createTolerantPageSchema(registry) : createPageSchema(registry);
898
- const pages = files.map((name) => parseFile(path.join(pagesDir, name), pageSchema, migrator, "page"));
899
- const seen = /* @__PURE__ */ new Map();
900
- for (const [index, page] of pages.entries()) {
901
- const filePath = path.join(pagesDir, files[index] ?? "");
902
- const previous = seen.get(page.slug);
903
- if (previous !== void 0) throw new ContentValidationError(filePath, [{
904
- path: ["slug"],
905
- message: `Duplicate slug "${page.slug}" (also defined in ${previous})`
906
- }]);
907
- seen.set(page.slug, filePath);
908
- }
909
- return pages;
910
- }
911
- function parseFile(filePath, schema, migrator, kind) {
912
- const upgraded = migrator.upgrade(readJsonFile(filePath), kind);
913
- if (!upgraded.ok) throw new ContentValidationError(filePath, [{
914
- path: [SCHEMA_VERSION_KEY],
915
- message: upgraded.message
916
- }]);
917
- const result = schema.safeParse(upgraded.value);
918
- if (!result.success) throw new ContentValidationError(filePath, toIssues(result.error.issues));
919
- return result.data;
920
- }
921
- function readJsonFile(filePath) {
922
- let raw;
923
- try {
924
- raw = fs.readFileSync(filePath, "utf8");
925
- } catch (error) {
926
- if (isErrno(error) && error.code === "ENOENT") throw new ContentReadError(filePath, `Content file not found: ${filePath}`);
927
- const message = error instanceof Error ? error.message : String(error);
928
- throw new ContentReadError(filePath, `Unable to read ${filePath}: ${message}`);
929
- }
930
- try {
931
- return JSON.parse(raw);
932
- } catch (error) {
933
- const message = error instanceof Error ? error.message : String(error);
934
- throw new ContentReadError(filePath, `Invalid JSON in ${filePath}: ${message}`);
935
- }
936
- }
937
- function toIssues(issues) {
938
- return issues.map((issue) => ({
939
- path: [...issue.path],
940
- message: issue.message
941
- }));
942
- }
943
- function isErrno(error) {
944
- return error instanceof Error && "code" in error;
945
- }
946
- //#endregion
947
1066
  //#region src/hosted-template-check.ts
948
1067
  const TEMPLATE_DOCS = "https://docs.bearminion.com/integration/#keeping-the-sites-files-current";
949
1068
  /** Reads a file, or `undefined` when it is not there. */