@grove-dev/astro 0.10.0 → 0.12.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grove-dev/astro",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Astro integration + server view-models for Grove directories. UI ships from @grove-dev/registry, not from this package.",
6
6
  "license": "MIT",
@@ -48,17 +48,17 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "marked": "^18.0.0",
51
- "sanitize-html": "^2.17.5",
51
+ "sanitize-html": "^2.17.7",
52
52
  "shiki": "^1.29.2",
53
53
  "yaml": "^2.9.0",
54
- "@grove-dev/core": "0.10.0"
54
+ "@grove-dev/core": "0.12.0"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "astro": "^6.0.0 || ^7.0.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/sanitize-html": "^2.16.0",
61
- "astro": "^7.1.3"
61
+ "astro": "^7.3.3"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
@@ -1,5 +1,11 @@
1
- import type { Collection, CollectionEntry } from '@grove-dev/core';
2
- import { collectionSchema, findRelated, runCollection } from '@grove-dev/core';
1
+ import type { Collection, CollectionEntry, CollectionSourceRecord } from '@grove-dev/core';
2
+ import {
3
+ collectionSchema,
4
+ faqSchema,
5
+ findRelated,
6
+ runCollection,
7
+ toCollectionEntries,
8
+ } from '@grove-dev/core';
3
9
  import { absoluteUrl, ogPath, type PageSeo, seoDescription, seoTitle } from './seo.js';
4
10
 
5
11
  // Collection YAML loading lives in @grove-dev/core (it also feeds the
@@ -11,94 +17,21 @@ interface RouteHint {
11
17
  blueprintConfig?: { routeSlug?: string };
12
18
  }
13
19
 
14
- interface RawRecord {
15
- slug?: string;
16
- name?: string;
17
- title?: string;
18
- description?: string;
19
- stack?: string;
20
- stacks?: string[];
21
- platforms?: string[];
22
- license?: string;
23
- licenses?: string[];
24
- visibility?: string;
25
- /** GitHub stargazers count. Stored on `github.repository.stargazers_count`
26
- * in the full payload; read explicitly because the index payload
27
- * does not flatten it. */
28
- stars?: number;
29
- /** GitHub fork count. Stored on `github.repository.forks_count`. */
30
- forks?: number;
31
- pushedAt?: string;
32
- lastCommitAt?: string;
33
- category?: string;
34
- tags?: string[];
35
- scores?: { curation?: number; activity?: number };
36
- repoUrl?: string;
37
- links?: { github?: string; website?: string };
38
- /** GitHub metadata block on the full record. The star / fork counts
39
- * are read from `github.repository.stargazers_count` /
40
- * `github.repository.forks_count` here. */
41
- github?: {
42
- repository?: {
43
- stargazers_count?: number;
44
- forks_count?: number;
45
- };
46
- };
47
- }
48
-
49
20
  /**
50
21
  * Map a list of full records (shape produced by `records.json`) to
51
22
  * the lightweight `CollectionEntry` shape consumed by `runCollection`.
52
23
  *
53
- * - Skips records with `visibility === "hide"` — they should never
54
- * appear in any collection.
55
- * - Combines `category` and `tags` into a `categories` array (deduplicated).
56
- * - Falls back to `stacks[0]` when `stack` is missing.
57
- * - Prefers `pushedAt`; falls back to `lastCommitAt`.
58
- * - Constructs `url` as `${routeSlug}/${slug}/` so the value points
59
- * back to the consumer's detail page.
60
- * - Populates `repoHref` (from `repoUrl` or `links.github`) and
61
- * `homepageHref` (from `links.website`) so the row component
62
- * can render "View repo" / "Visit site" footer links.
24
+ * The projection itself is `toCollectionEntries` in `@grove-dev/core` —
25
+ * shared with the OG-image pipeline so both count a collection the same
26
+ * way. This wrapper only resolves the directory route slug from the
27
+ * site payload, so an entry's `url` points at the consumer's detail page.
63
28
  */
64
29
  export function recordsToCollectionEntries(
65
- records: RawRecord[],
30
+ records: CollectionSourceRecord[],
66
31
  site: RouteHint,
67
32
  ): CollectionEntry[] {
68
33
  const routeSlug = site.routeSlug ?? site.blueprintConfig?.routeSlug ?? 'projects';
69
- const out: CollectionEntry[] = [];
70
- for (const r of records) {
71
- if (r.visibility === 'hide') continue;
72
- if (!r.slug) continue;
73
- const categories = [...(r.category ? [r.category] : []), ...(r.tags ?? [])].filter(
74
- (value, index, self) => self.indexOf(value) === index,
75
- );
76
- out.push({
77
- slug: r.slug,
78
- title: r.name ?? r.title ?? r.slug,
79
- description: r.description ?? '',
80
- url: `/${routeSlug}/${r.slug}/`,
81
- repoHref: r.repoUrl ?? r.links?.github,
82
- homepageHref: r.links?.website,
83
- stack: r.stack ?? r.stacks?.[0],
84
- platform: r.platforms,
85
- license: r.license,
86
- // Pass through the curated `licenses` array so the collection
87
- // engine can match both curated SPDX ids and the GitHub fallback.
88
- // If only `license` (singular, GitHub-synced) is present, mirror
89
- // it into the array so the filter still matches it.
90
- licenses:
91
- r.licenses && r.licenses.length > 0 ? r.licenses : r.license ? [r.license] : undefined,
92
- status: r.visibility,
93
- stars: r.stars ?? r.github?.repository?.stargazers_count,
94
- forks: r.forks ?? r.github?.repository?.forks_count,
95
- pushedAt: r.pushedAt ?? r.lastCommitAt,
96
- curationScore: r.scores?.curation,
97
- activityScore: r.scores?.activity,
98
- categories: categories.length > 0 ? categories : undefined,
99
- });
100
- }
101
- return out;
34
+ return toCollectionEntries(records, { routeSlug });
102
35
  }
103
36
 
104
37
  // ── Collection view-models ──────────────────────────────────────
@@ -116,7 +49,12 @@ export interface CollectionPageModel {
116
49
  kind: 'curated' | 'generated';
117
50
  selectionNote?: string;
118
51
  introduction?: string;
52
+ lastReviewedAt?: string;
53
+ /** Path of the Markdown body; render it with `getCollectionBodyHtml`. */
54
+ content?: string;
119
55
  };
56
+ /** Questions rendered on the page and emitted as `FAQPage` JSON-LD. */
57
+ faq: Array<{ q: string; a: string }>;
120
58
  total: number;
121
59
  isEmpty: boolean;
122
60
  entries: CollectionEntry[];
@@ -170,9 +108,9 @@ export function getCollectionPageModel(
170
108
  const siteName = site?.name ?? '';
171
109
  const plural = site?.blueprintConfig?.labelPlural ?? 'items';
172
110
  const pageUrl = absoluteUrl(siteUrl, `collections/${collection.slug}/`);
173
- // CollectionPage + ItemList + BreadcrumbList. The ItemList is capped
174
- // at 50 entries to keep the payload bounded; search engines don't
175
- // index list markup beyond that anyway.
111
+ // CollectionPage + ItemList + BreadcrumbList. `itemListElement` is
112
+ // capped at 50 entries to keep the payload bounded; `numberOfItems`
113
+ // still reports the full list so it matches what the page renders.
176
114
  const jsonLd = collectionSchema({
177
115
  url: pageUrl,
178
116
  name: collection.seo?.title ?? collection.title,
@@ -180,14 +118,26 @@ export function getCollectionPageModel(
180
118
  items: result.entries.slice(0, 50).map((entry) => ({
181
119
  url: entry.url.startsWith('http') ? entry.url : absoluteUrl(siteUrl, entry.url),
182
120
  name: entry.title,
183
- ...(entry.description ? { description: entry.description } : {}),
121
+ // The curator's note is what the page shows for a hand-picked
122
+ // entry, so it is what the markup describes it with too.
123
+ ...(entry.note || entry.description ? { description: entry.note ?? entry.description } : {}),
184
124
  })),
125
+ totalItems: result.entries.length,
185
126
  crumbs: [
186
127
  { url: `${siteUrl}/`, name: 'Home' },
187
128
  { url: absoluteUrl(siteUrl, 'collections/'), name: 'Collections' },
188
129
  { url: pageUrl, name: collection.title },
189
130
  ],
190
131
  });
132
+ const faq = collection.faq ?? [];
133
+ if (faq.length > 0) {
134
+ jsonLd.push(
135
+ faqSchema({
136
+ url: pageUrl,
137
+ items: faq.map((item) => ({ question: item.q, answer: item.a })),
138
+ }),
139
+ );
140
+ }
191
141
  // The curator's `seo.title` / `seo.description` overrides win
192
142
  // verbatim; the fallback pattern advertises the list size. A
193
143
  // collection marked `seo.index: false` renders with noindex.
@@ -199,7 +149,9 @@ export function getCollectionPageModel(
199
149
  image: ogPath('collection', collection.slug),
200
150
  ...(siteName ? { imageAlt: `${collection.title} — ${siteName}` } : {}),
201
151
  jsonLd: jsonLd as unknown as Record<string, unknown>[],
202
- noindex: collection.seo?.index === false,
152
+ // An empty collection has nothing to rank for; it also stays out of
153
+ // the sitemap (see `prepareDirectory`).
154
+ noindex: collection.seo?.index === false || result.isEmpty,
203
155
  };
204
156
  return {
205
157
  collection: {
@@ -209,7 +161,10 @@ export function getCollectionPageModel(
209
161
  kind: collection.kind,
210
162
  selectionNote: collection.editorial?.selectionNote,
211
163
  introduction: collection.editorial?.introduction,
164
+ lastReviewedAt: collection.editorial?.lastReviewedAt,
165
+ content: collection.content,
212
166
  },
167
+ faq,
213
168
  total: result.entries.length,
214
169
  isEmpty: result.isEmpty,
215
170
  entries: result.entries,
@@ -329,3 +284,169 @@ export function findCollectionsFor(
329
284
  }
330
285
  return result;
331
286
  }
287
+
288
+ // ── Record context: relations, related records, membership ──────
289
+
290
+ const RELATION_LABELS: Record<string, string> = {
291
+ 'alternative-to': 'Alternative to',
292
+ };
293
+
294
+ export interface RecordContextSubject {
295
+ id: string;
296
+ name: string;
297
+ /** The subject's own page (e.g. the vendor's), when the vocabulary has one. */
298
+ url?: string;
299
+ }
300
+
301
+ export interface RecordContextModel {
302
+ /** The record's relations, resolved against the subject vocabulary. */
303
+ relations: Array<{
304
+ type: string;
305
+ /** Human label for the relation type, e.g. "Alternative to". */
306
+ label: string;
307
+ subject: RecordContextSubject;
308
+ note?: string;
309
+ evidence?: { type: string; url?: string; quote?: string; checkedAt?: string };
310
+ /** The collection that declares `subject: <id>`, if there is one. */
311
+ hub?: { title: string; url: string };
312
+ }>;
313
+ /** Other visible records that share one of the record's subjects. */
314
+ relatedRecords: Array<{
315
+ subject: RecordContextSubject;
316
+ label: string;
317
+ hub?: { title: string; url: string };
318
+ records: Array<{ slug: string; title: string; url: string; description: string }>;
319
+ }>;
320
+ /** Collections whose resolved entries include the record. */
321
+ collectionMembership: Array<{ slug: string; title: string; url: string }>;
322
+ }
323
+
324
+ interface RecordContextInput {
325
+ collections: Collection[];
326
+ entries: CollectionEntry[];
327
+ /** `site-config.json` → `taxonomy.subjects`. */
328
+ subjects?: Array<{ id: string; name: string; url?: unknown }>;
329
+ /** Cap on related records listed per subject (default 6). */
330
+ relatedLimit?: number;
331
+ }
332
+
333
+ /**
334
+ * A detail page is rendered once per record, and each render needs every
335
+ * collection resolved. Cache the resolved slug sets per entry stream so a
336
+ * 100-record, 20-collection site runs 20 collections, not 2,000.
337
+ */
338
+ const membershipCache = new WeakMap<CollectionEntry[], Map<string, Set<string>>>();
339
+
340
+ function membersOf(collection: Collection, entries: CollectionEntry[]): Set<string> {
341
+ let bySlug = membershipCache.get(entries);
342
+ if (!bySlug) {
343
+ bySlug = new Map();
344
+ membershipCache.set(entries, bySlug);
345
+ }
346
+ let members = bySlug.get(collection.slug);
347
+ if (!members) {
348
+ members = new Set(runCollection(collection, entries).entries.map((entry) => entry.slug));
349
+ bySlug.set(collection.slug, members);
350
+ }
351
+ return members;
352
+ }
353
+
354
+ /**
355
+ * Everything a record page links *out* to: the subjects it relates to
356
+ * (and the hub collection for each), sibling records that share a
357
+ * subject, and the collections it appears in. Pure — the caller passes
358
+ * the collections, the entry stream and the subject vocabulary.
359
+ */
360
+ export function getRecordContextModel(
361
+ record: {
362
+ slug: string;
363
+ relations?: Array<{
364
+ type: string;
365
+ to: string;
366
+ note?: string | undefined;
367
+ evidence?:
368
+ | {
369
+ type: string;
370
+ url?: string | undefined;
371
+ quote?: string | undefined;
372
+ checkedAt?: string | undefined;
373
+ }
374
+ | undefined;
375
+ }>;
376
+ },
377
+ input: RecordContextInput,
378
+ ): RecordContextModel {
379
+ const { collections, entries } = input;
380
+ const limit = input.relatedLimit ?? 6;
381
+ const subjects = new Map(
382
+ (input.subjects ?? []).map((subject) => [
383
+ subject.id,
384
+ {
385
+ id: subject.id,
386
+ name: subject.name,
387
+ ...(typeof subject.url === 'string' ? { url: subject.url } : {}),
388
+ } satisfies RecordContextSubject,
389
+ ]),
390
+ );
391
+ const hubFor = (subjectId: string) => {
392
+ const hub = collections.find((collection) => collection.subject === subjectId);
393
+ return hub ? { title: hub.title, url: `/collections/${hub.slug}/` } : undefined;
394
+ };
395
+
396
+ const relations: RecordContextModel['relations'] = [];
397
+ const relatedRecords: RecordContextModel['relatedRecords'] = [];
398
+ const seenSubjects = new Set<string>();
399
+ for (const relation of record.relations ?? []) {
400
+ const subject = subjects.get(relation.to);
401
+ if (!subject) continue;
402
+ const label = RELATION_LABELS[relation.type] ?? relation.type;
403
+ const hub = hubFor(subject.id);
404
+ const evidence = relation.evidence
405
+ ? {
406
+ type: relation.evidence.type,
407
+ ...(relation.evidence.url ? { url: relation.evidence.url } : {}),
408
+ ...(relation.evidence.quote ? { quote: relation.evidence.quote } : {}),
409
+ ...(relation.evidence.checkedAt ? { checkedAt: relation.evidence.checkedAt } : {}),
410
+ }
411
+ : undefined;
412
+ relations.push({
413
+ type: relation.type,
414
+ label,
415
+ subject,
416
+ ...(relation.note ? { note: relation.note } : {}),
417
+ ...(evidence ? { evidence } : {}),
418
+ ...(hub ? { hub } : {}),
419
+ });
420
+
421
+ const key = `${relation.type}:${subject.id}`;
422
+ if (seenSubjects.has(key)) continue;
423
+ seenSubjects.add(key);
424
+ const siblings = entries
425
+ .filter(
426
+ (entry) =>
427
+ entry.slug !== record.slug &&
428
+ (entry.relations ?? []).some((r) => r.to === subject.id && r.type === relation.type),
429
+ )
430
+ .sort((a, b) => (b.stars ?? 0) - (a.stars ?? 0))
431
+ .slice(0, limit)
432
+ .map((entry) => ({
433
+ slug: entry.slug,
434
+ title: entry.title,
435
+ url: entry.url,
436
+ description: entry.description,
437
+ }));
438
+ if (siblings.length > 0) {
439
+ relatedRecords.push({ subject, label, ...(hub ? { hub } : {}), records: siblings });
440
+ }
441
+ }
442
+
443
+ const collectionMembership = collections
444
+ .filter((collection) => membersOf(collection, entries).has(record.slug))
445
+ .map((collection) => ({
446
+ slug: collection.slug,
447
+ title: collection.title,
448
+ url: `/collections/${collection.slug}/`,
449
+ }));
450
+
451
+ return { relations, relatedRecords, collectionMembership };
452
+ }
@@ -47,7 +47,13 @@ import type {
47
47
  Resource,
48
48
  ResourceRecord,
49
49
  } from '@grove-dev/core';
50
- import { headingSlug, readContentFile, stripFrontmatter, uniqueSlug } from '@grove-dev/core';
50
+ import {
51
+ headingSlug,
52
+ readContentFile,
53
+ stripFrontmatter,
54
+ stripLeadingH1,
55
+ uniqueSlug,
56
+ } from '@grove-dev/core';
51
57
  import { marked } from 'marked';
52
58
  import sanitizeHtml from 'sanitize-html';
53
59
  import { getSingletonHighlighter } from 'shiki';
@@ -444,12 +450,21 @@ const COMMON_BODY_ATTRIBUTES = {
444
450
  const SHIKI_VALUE = /.+/;
445
451
  const COLOR_VALUE = /^(?:#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\))$/i;
446
452
 
447
- /** `<a>` tag normalization — open in a new tab, no opener. */
448
- const ANCHOR_TRANSFORM = sanitizeHtml.simpleTransform(
449
- 'a',
450
- { rel: 'noopener noreferrer', target: '_blank' },
451
- true,
452
- );
453
+ /**
454
+ * `<a>` tag normalization. External links open in a new tab with no
455
+ * opener. Links that stay on the site — root-relative paths, relative
456
+ * paths and `#fragment` anchors — keep the default same-tab behaviour:
457
+ * a new tab per internal link breaks the back button and tells
458
+ * crawlers nothing the href doesn't.
459
+ */
460
+ const ANCHOR_TRANSFORM = (tagName: string, attribs: Record<string, string>) => {
461
+ const href = attribs.href ?? '';
462
+ const external = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(href);
463
+ return {
464
+ tagName,
465
+ attribs: external ? { ...attribs, rel: 'noopener noreferrer', target: '_blank' } : attribs,
466
+ };
467
+ };
453
468
 
454
469
  /** Hardens `<img>` to lazy-load + async-decode. */
455
470
  const IMG_TRANSFORM = (tagName: string, attribs: Record<string, string>) => ({
@@ -729,7 +744,9 @@ for (const r of fullRecords) {
729
744
  // loop would inherit the first record's counters and duplicate-
730
745
  // heading IDs would collide across records.
731
746
  try {
732
- contentHtmlBySlug.set(r.slug, renderMarkdownToSafeHtml(read.body));
747
+ // The detail page renders the record name as its `<h1>`; a sidecar
748
+ // that opens with its own `# Title` would add a second one.
749
+ contentHtmlBySlug.set(r.slug, renderMarkdownToSafeHtml(stripLeadingH1(read.body)));
733
750
  } catch {
734
751
  // Missing / unreadable / parse-failed content: skip the record
735
752
  // rather than render broken HTML. The page treats `null` as
@@ -748,6 +765,32 @@ export function getContentHtml(slug: string): string | null {
748
765
  return contentHtmlBySlug.get(slug) ?? null;
749
766
  }
750
767
 
768
+ const collectionBodyHtmlByPath = new Map<string, string | null>();
769
+
770
+ /**
771
+ * Sanitized HTML for a collection's long-form body — the Markdown file
772
+ * its `content` field points at (convention:
773
+ * `content/collections/<slug>.md`). Uses the record-body allowlist, so
774
+ * comparison tables render. An opening `# Title` is dropped: the page
775
+ * already renders the collection title as its `<h1>`. Returns `null`
776
+ * when the collection has no `content`, the file is missing, or the
777
+ * render fails.
778
+ */
779
+ export function getCollectionBodyHtml(contentPath: string | undefined): string | null {
780
+ if (!contentPath) return null;
781
+ const cached = collectionBodyHtmlByPath.get(contentPath);
782
+ if (cached !== undefined) return cached;
783
+ let html: string | null = null;
784
+ try {
785
+ const read = readContentFile(contentPath);
786
+ if (read) html = renderMarkdownToSafeHtml(stripLeadingH1(read.body));
787
+ } catch {
788
+ html = null;
789
+ }
790
+ collectionBodyHtmlByPath.set(contentPath, html);
791
+ return html;
792
+ }
793
+
751
794
  /**
752
795
  * Sanitized Markdown for a consumer-authored page under
753
796
  * `content/pages/<page>.md`. Default template pages use this to