@sinnstack/ui 0.0.0-stage → 0.2.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 (280) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +373 -0
  3. package/README.md +186 -2
  4. package/docs/blocks.md +364 -0
  5. package/docs/data.md +128 -0
  6. package/docs/motion.md +166 -0
  7. package/docs/primitives.md +510 -0
  8. package/docs/seo.md +187 -0
  9. package/docs/tokens.md +122 -0
  10. package/package.json +141 -3
  11. package/scripts/check-contrast.mjs +180 -0
  12. package/src/blocks/BlockRenderer.astro +54 -0
  13. package/src/blocks/CTABanner.astro +121 -0
  14. package/src/blocks/CTAPair.astro +110 -0
  15. package/src/blocks/CardGrid.astro +167 -0
  16. package/src/blocks/ConsentEmbed.astro +125 -0
  17. package/src/blocks/ConsentManager.astro +147 -0
  18. package/src/blocks/ConsentScript.astro +47 -0
  19. package/src/blocks/ContactCard.astro +164 -0
  20. package/src/blocks/ContactForm.astro +224 -0
  21. package/src/blocks/ErrorPage.astro +242 -0
  22. package/src/blocks/FAQ.astro +135 -0
  23. package/src/blocks/FeatureGrid.astro +148 -0
  24. package/src/blocks/Hero.astro +171 -0
  25. package/src/blocks/HeroCarousel.astro +220 -0
  26. package/src/blocks/HighlightCards.astro +107 -0
  27. package/src/blocks/LocationHours.astro +311 -0
  28. package/src/blocks/LogoCloud.astro +135 -0
  29. package/src/blocks/MaintenancePage.astro +168 -0
  30. package/src/blocks/MediaText.astro +177 -0
  31. package/src/blocks/PageHeader.astro +126 -0
  32. package/src/blocks/ProseSection.astro +98 -0
  33. package/src/blocks/Reviews.astro +194 -0
  34. package/src/blocks/RichText.astro +57 -0
  35. package/src/blocks/StatsBand.astro +117 -0
  36. package/src/blocks/Steps.astro +141 -0
  37. package/src/blocks/Testimonials.astro +144 -0
  38. package/src/blocks/Topbar.astro +158 -0
  39. package/src/blocks/cms/card-grid.ts +80 -0
  40. package/src/blocks/cms/consent.ts +45 -0
  41. package/src/blocks/cms/contact-card.ts +88 -0
  42. package/src/blocks/cms/contact-form.ts +55 -0
  43. package/src/blocks/cms/cta-banner.ts +48 -0
  44. package/src/blocks/cms/cta-pair.ts +63 -0
  45. package/src/blocks/cms/data-base.ts +7 -0
  46. package/src/blocks/cms/data.ts +257 -0
  47. package/src/blocks/cms/faq.ts +70 -0
  48. package/src/blocks/cms/feature-grid.ts +80 -0
  49. package/src/blocks/cms/fixtures.ts +599 -0
  50. package/src/blocks/cms/hero-carousel.ts +80 -0
  51. package/src/blocks/cms/hero.ts +77 -0
  52. package/src/blocks/cms/highlight-cards.ts +76 -0
  53. package/src/blocks/cms/images.ts +38 -0
  54. package/src/blocks/cms/index.ts +87 -0
  55. package/src/blocks/cms/location-hours.ts +149 -0
  56. package/src/blocks/cms/logo-cloud.ts +62 -0
  57. package/src/blocks/cms/media-text.ts +44 -0
  58. package/src/blocks/cms/page-header.ts +49 -0
  59. package/src/blocks/cms/pages.ts +81 -0
  60. package/src/blocks/cms/prose-section.ts +45 -0
  61. package/src/blocks/cms/reviews.ts +101 -0
  62. package/src/blocks/cms/shared.ts +115 -0
  63. package/src/blocks/cms/stats-band.ts +61 -0
  64. package/src/blocks/cms/steps.ts +67 -0
  65. package/src/blocks/cms/testimonials.ts +80 -0
  66. package/src/blocks/cms/topbar.ts +64 -0
  67. package/src/blocks/cms/types.ts +63 -0
  68. package/src/blocks/consent.ts +14 -0
  69. package/src/blocks/icons.ts +47 -0
  70. package/src/blocks/index.ts +42 -0
  71. package/src/blocks/internal/Actions.astro +29 -0
  72. package/src/blocks/internal/BlockHeader.astro +45 -0
  73. package/src/blocks/internal/BlockShell.astro +58 -0
  74. package/src/blocks/internal/CarouselScript.astro +7 -0
  75. package/src/blocks/internal/ConsentEmbedScript.astro +7 -0
  76. package/src/blocks/internal/ConsentManagerScript.astro +7 -0
  77. package/src/blocks/internal/HoursScript.astro +7 -0
  78. package/src/blocks/internal/Placeholder.astro +13 -0
  79. package/src/blocks/internal/RichTextNode.astro +133 -0
  80. package/src/blocks/internal/StandaloneDocument.astro +53 -0
  81. package/src/blocks/internal/tina.ts +19 -0
  82. package/src/blocks/internal/util.ts +23 -0
  83. package/src/blocks/lib/consent.ts +96 -0
  84. package/src/blocks/lib/contact.ts +86 -0
  85. package/src/blocks/lib/error-pages.ts +119 -0
  86. package/src/blocks/lib/faq.ts +37 -0
  87. package/src/blocks/lib/hours.ts +201 -0
  88. package/src/blocks/lib/maintenance.ts +129 -0
  89. package/src/blocks/lib/reviews.ts +22 -0
  90. package/src/blocks/lib/rich-text.ts +143 -0
  91. package/src/blocks/lib/slug.ts +12 -0
  92. package/src/blocks/registry.ts +79 -0
  93. package/src/blocks/scripts/carousel.ts +218 -0
  94. package/src/blocks/scripts/consent-embed.ts +105 -0
  95. package/src/blocks/scripts/consent-manager.ts +112 -0
  96. package/src/blocks/scripts/consent-store.ts +86 -0
  97. package/src/blocks/scripts/error-page.ts +71 -0
  98. package/src/blocks/scripts/hours.ts +106 -0
  99. package/src/blocks/scripts/maintenance.ts +109 -0
  100. package/src/blocks/styles/blocks.css +1320 -0
  101. package/src/blocks/styles/consent.css +102 -0
  102. package/src/blocks/styles/faq.css +28 -0
  103. package/src/blocks/styles/location.css +92 -0
  104. package/src/blocks/styles/prose-section.css +13 -0
  105. package/src/blocks/styles/quotes.css +123 -0
  106. package/src/blocks/styles/rich-text.css +14 -0
  107. package/src/blocks/types.ts +283 -0
  108. package/src/data/ChartAxis.astro +19 -0
  109. package/src/data/ChartContainer.astro +151 -0
  110. package/src/data/ChartLegend.astro +25 -0
  111. package/src/data/ChartSeries.astro +14 -0
  112. package/src/data/ChartTable.astro +17 -0
  113. package/src/data/ChartTooltip.astro +20 -0
  114. package/src/data/Sparkline.astro +55 -0
  115. package/src/data/cms.ts +190 -0
  116. package/src/data/index.ts +10 -0
  117. package/src/data/lib/chart.ts +450 -0
  118. package/src/data/lib/render.ts +219 -0
  119. package/src/data/lib/scale.ts +107 -0
  120. package/src/data/lib/sparkline.ts +117 -0
  121. package/src/data/scripts/chart.ts +324 -0
  122. package/src/data/styles/chart.css +392 -0
  123. package/src/motion/Marquee.astro +90 -0
  124. package/src/motion/MotionProvider.astro +50 -0
  125. package/src/motion/PageTransitions.astro +61 -0
  126. package/src/motion/Parallax.astro +44 -0
  127. package/src/motion/ParallaxLayer.astro +31 -0
  128. package/src/motion/RevealOnScroll.astro +59 -0
  129. package/src/motion/SceneRegistry.astro +38 -0
  130. package/src/motion/ScrollScene.astro +81 -0
  131. package/src/motion/index.ts +12 -0
  132. package/src/motion/integration.ts +48 -0
  133. package/src/motion/runtime/page-transitions.ts +68 -0
  134. package/src/motion/runtime/runtime.ts +180 -0
  135. package/src/motion/runtime/scenes.ts +248 -0
  136. package/src/motion/runtime/types.ts +103 -0
  137. package/src/motion/styles/motion.css +332 -0
  138. package/src/motion/transitions.ts +74 -0
  139. package/src/motion/virtual.d.ts +4 -0
  140. package/src/primitives/Accordion.astro +129 -0
  141. package/src/primitives/Breadcrumbs.astro +50 -0
  142. package/src/primitives/BulletList.astro +69 -0
  143. package/src/primitives/Button.astro +73 -0
  144. package/src/primitives/ButtonGroup.astro +54 -0
  145. package/src/primitives/Callout.astro +137 -0
  146. package/src/primitives/Caption.astro +35 -0
  147. package/src/primitives/Card.astro +72 -0
  148. package/src/primitives/CardContent.astro +24 -0
  149. package/src/primitives/CardFooter.astro +36 -0
  150. package/src/primitives/CardHeader.astro +86 -0
  151. package/src/primitives/Checkbox.astro +38 -0
  152. package/src/primitives/ChoiceGroup.astro +23 -0
  153. package/src/primitives/Cluster.astro +49 -0
  154. package/src/primitives/Container.astro +44 -0
  155. package/src/primitives/DescriptionList.astro +83 -0
  156. package/src/primitives/Dialog.astro +38 -0
  157. package/src/primitives/Disclosure.astro +67 -0
  158. package/src/primitives/Divider.astro +93 -0
  159. package/src/primitives/Drawer.astro +33 -0
  160. package/src/primitives/Fieldset.astro +80 -0
  161. package/src/primitives/Flex.astro +64 -0
  162. package/src/primitives/FocusRing.astro +63 -0
  163. package/src/primitives/FocusTrap.astro +64 -0
  164. package/src/primitives/Footer.astro +155 -0
  165. package/src/primitives/Form.astro +68 -0
  166. package/src/primitives/FormDescription.astro +26 -0
  167. package/src/primitives/FormError.astro +106 -0
  168. package/src/primitives/FormField.astro +72 -0
  169. package/src/primitives/Grid.astro +64 -0
  170. package/src/primitives/Heading.astro +45 -0
  171. package/src/primitives/IconButton.astro +48 -0
  172. package/src/primitives/Image.astro +125 -0
  173. package/src/primitives/Input.astro +84 -0
  174. package/src/primitives/Label.astro +50 -0
  175. package/src/primitives/Link.astro +81 -0
  176. package/src/primitives/LinkButton.astro +66 -0
  177. package/src/primitives/List.astro +39 -0
  178. package/src/primitives/ListItem.astro +178 -0
  179. package/src/primitives/MediaObject.astro +66 -0
  180. package/src/primitives/MetricCard.astro +276 -0
  181. package/src/primitives/NavLink.astro +81 -0
  182. package/src/primitives/NavMenu.astro +109 -0
  183. package/src/primitives/Navbar.astro +197 -0
  184. package/src/primitives/Panel.astro +153 -0
  185. package/src/primitives/Picture.astro +167 -0
  186. package/src/primitives/Popover.astro +95 -0
  187. package/src/primitives/Prose.astro +45 -0
  188. package/src/primitives/Radio.astro +21 -0
  189. package/src/primitives/Rating.astro +135 -0
  190. package/src/primitives/ReducedMotion.astro +90 -0
  191. package/src/primitives/SegmentedControl.astro +132 -0
  192. package/src/primitives/Select.astro +107 -0
  193. package/src/primitives/Sheet.astro +45 -0
  194. package/src/primitives/SkipLink.astro +31 -0
  195. package/src/primitives/Slider.astro +186 -0
  196. package/src/primitives/Spacer.astro +35 -0
  197. package/src/primitives/Stack.astro +51 -0
  198. package/src/primitives/Surface.astro +70 -0
  199. package/src/primitives/Switch.astro +22 -0
  200. package/src/primitives/Table.astro +382 -0
  201. package/src/primitives/Tabs.astro +126 -0
  202. package/src/primitives/Text.astro +56 -0
  203. package/src/primitives/Textarea.astro +73 -0
  204. package/src/primitives/Thumbnail.astro +154 -0
  205. package/src/primitives/Toggle.astro +99 -0
  206. package/src/primitives/Tooltip.astro +50 -0
  207. package/src/primitives/VisuallyHidden.astro +29 -0
  208. package/src/primitives/index.ts +103 -0
  209. package/src/primitives/internal/AccordionScript.astro +7 -0
  210. package/src/primitives/internal/ChoiceField.astro +89 -0
  211. package/src/primitives/internal/FocusTrapScript.astro +8 -0
  212. package/src/primitives/internal/FormValidationScript.astro +10 -0
  213. package/src/primitives/internal/IndeterminateScript.astro +13 -0
  214. package/src/primitives/internal/ModalPanel.astro +114 -0
  215. package/src/primitives/internal/OverlayScript.astro +7 -0
  216. package/src/primitives/internal/ReducedMotionScript.astro +7 -0
  217. package/src/primitives/internal/SliderScript.astro +7 -0
  218. package/src/primitives/internal/SparklineScript.astro +7 -0
  219. package/src/primitives/internal/TableSortScript.astro +7 -0
  220. package/src/primitives/internal/TabsScript.astro +7 -0
  221. package/src/primitives/internal/TooltipScript.astro +7 -0
  222. package/src/primitives/lib/deprecate.ts +47 -0
  223. package/src/primitives/lib/focus-trap.ts +197 -0
  224. package/src/primitives/lib/focus.ts +60 -0
  225. package/src/primitives/lib/image-plan.ts +82 -0
  226. package/src/primitives/lib/image.ts +129 -0
  227. package/src/primitives/lib/motion.ts +68 -0
  228. package/src/primitives/lib/slider.ts +170 -0
  229. package/src/primitives/scripts/accordion.ts +123 -0
  230. package/src/primitives/scripts/form-validation.ts +225 -0
  231. package/src/primitives/scripts/overlay.ts +71 -0
  232. package/src/primitives/scripts/reduced-motion.ts +59 -0
  233. package/src/primitives/scripts/slider.ts +150 -0
  234. package/src/primitives/scripts/sparkline.ts +131 -0
  235. package/src/primitives/scripts/table-sort.ts +68 -0
  236. package/src/primitives/scripts/tabs.ts +151 -0
  237. package/src/primitives/scripts/tooltip.ts +28 -0
  238. package/src/primitives/styles/a11y.css +104 -0
  239. package/src/primitives/styles/accordion.css +53 -0
  240. package/src/primitives/styles/breadcrumbs.css +59 -0
  241. package/src/primitives/styles/bullet-list.css +89 -0
  242. package/src/primitives/styles/button.css +237 -0
  243. package/src/primitives/styles/choice.css +164 -0
  244. package/src/primitives/styles/cluster.css +24 -0
  245. package/src/primitives/styles/container.css +19 -0
  246. package/src/primitives/styles/data.css +849 -0
  247. package/src/primitives/styles/disclosure.css +140 -0
  248. package/src/primitives/styles/divider.css +50 -0
  249. package/src/primitives/styles/flex.css +42 -0
  250. package/src/primitives/styles/form.css +241 -0
  251. package/src/primitives/styles/grid.css +36 -0
  252. package/src/primitives/styles/media.css +247 -0
  253. package/src/primitives/styles/nav.css +792 -0
  254. package/src/primitives/styles/overlay.css +362 -0
  255. package/src/primitives/styles/prose.css +146 -0
  256. package/src/primitives/styles/scale.css +175 -0
  257. package/src/primitives/styles/segmented.css +165 -0
  258. package/src/primitives/styles/slider.css +170 -0
  259. package/src/primitives/styles/spacer.css +17 -0
  260. package/src/primitives/styles/stack.css +25 -0
  261. package/src/primitives/styles/surface.css +403 -0
  262. package/src/primitives/styles/tabs.css +223 -0
  263. package/src/primitives/styles/typography.css +144 -0
  264. package/src/primitives/styles/utilities.css +24 -0
  265. package/src/primitives/types.ts +385 -0
  266. package/src/primitives/utils.ts +254 -0
  267. package/src/seo/JSONLD.astro +35 -0
  268. package/src/seo/SEOHead.astro +47 -0
  269. package/src/seo/cms.ts +80 -0
  270. package/src/seo/index.ts +10 -0
  271. package/src/seo/integration.ts +231 -0
  272. package/src/seo/lib/jsonld.ts +334 -0
  273. package/src/seo/lib/meta.ts +205 -0
  274. package/src/seo/lib/redirects.ts +283 -0
  275. package/src/seo/lib/robots.ts +33 -0
  276. package/src/seo/lib/rss.ts +98 -0
  277. package/src/seo/lib/sitemap.ts +105 -0
  278. package/src/seo/lib/url.ts +68 -0
  279. package/src/tokens/base.css +71 -0
  280. package/src/tokens/tokens.css +210 -0
@@ -0,0 +1,254 @@
1
+ import type { FieldContext, FormatSpec, ValidationMessages, ValueFormat } from './types';
2
+
3
+ let counter = 0;
4
+
5
+ /**
6
+ * Server-side unique id for label/description wiring when the caller passes no `id`.
7
+ * Pass your own `id` when you need it stable across builds (e.g. for tests or anchors).
8
+ */
9
+ export function uid(prefix = 'sinn'): string {
10
+ counter = (counter + 1) % Number.MAX_SAFE_INTEGER;
11
+ return `${prefix}-${counter.toString(36)}`;
12
+ }
13
+
14
+ /** Join space-separated id lists, dropping empties. */
15
+ export function idList(...ids: Array<string | undefined | null | false>): string | undefined {
16
+ const out = ids.filter(Boolean).join(' ').trim();
17
+ return out || undefined;
18
+ }
19
+
20
+
21
+ const kebab = (s: string) => s.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
22
+
23
+ /**
24
+ * Builds the ids and attributes that connect a control to its label, description and error.
25
+ * The error element always exists (hidden while empty) so inline validation has somewhere to write;
26
+ * aria-describedby only points at it while it has content.
27
+ */
28
+ export function fieldContext(opts: {
29
+ id: string;
30
+ description?: string;
31
+ error?: string;
32
+ required?: boolean;
33
+ messages?: ValidationMessages;
34
+ describedBy?: string;
35
+ /** Set false when no error element will be rendered for this control. */
36
+ hasErrorElement?: boolean;
37
+ }): FieldContext {
38
+ const { id, description, error, required = false, messages = {}, describedBy, hasErrorElement = true } = opts;
39
+ const descriptionId = description ? `${id}-desc` : undefined;
40
+ const errorId = `${id}-error`;
41
+ const invalid = Boolean(error);
42
+
43
+ const attrs: FieldContext['attrs'] = {
44
+ id,
45
+ 'aria-describedby': idList(describedBy, descriptionId, invalid && hasErrorElement ? errorId : undefined),
46
+ 'aria-invalid': invalid ? 'true' : undefined,
47
+ required: required || undefined,
48
+ 'data-sinn-error-id': hasErrorElement ? errorId : undefined,
49
+ };
50
+ for (const [key, message] of Object.entries(messages)) {
51
+ if (message) attrs[`data-msg-${kebab(key)}`] = message;
52
+ }
53
+
54
+ return { id, descriptionId, errorId, invalid, required, attrs };
55
+ }
56
+
57
+ const normalizePath = (p: string) => {
58
+ const path = p.split(/[?#]/)[0] || '/';
59
+ return path.length > 1 ? path.replace(/\/+$/, '') : '/';
60
+ };
61
+
62
+ /**
63
+ * Compares a link's href with the current URL.
64
+ * Returns 'page' for the current page, 'true' for an ancestor section (prefix match), or undefined.
65
+ * Off-site links never match. "/" only ever matches exactly.
66
+ */
67
+ export function currentFor(
68
+ href: string,
69
+ current: URL,
70
+ match: 'exact' | 'prefix' = 'exact',
71
+ ): 'page' | 'true' | undefined {
72
+ let url: URL;
73
+ try {
74
+ url = new URL(href, current);
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ if (url.origin !== current.origin) return undefined;
79
+ const target = normalizePath(url.pathname);
80
+ const here = normalizePath(current.pathname);
81
+ if (target === here) return 'page';
82
+ if (match === 'prefix' && target !== '/' && here.startsWith(`${target}/`)) return 'true';
83
+ return undefined;
84
+ }
85
+
86
+ /* ---------- Data formatting ---------- */
87
+
88
+ const MINUS = '−';
89
+ /** Typographic minus for negative numbers (screen readers announce "minus"). */
90
+ const withMinus = (s: string) => s.replace(/^-/, MINUS).replace(/(\s)-(\d)/, `$1${MINUS}$2`);
91
+
92
+ export function escapeHtml(value: unknown): string {
93
+ return String(value)
94
+ .replace(/&/g, '&amp;')
95
+ .replace(/</g, '&lt;')
96
+ .replace(/>/g, '&gt;')
97
+ .replace(/"/g, '&quot;')
98
+ .replace(/'/g, '&#39;');
99
+ }
100
+
101
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
102
+
103
+ /**
104
+ * Formats a value for display with Intl, at render time (no client JS).
105
+ * Empty values (null, undefined, '') render as an em dash.
106
+ */
107
+ export function formatValue(value: unknown, format: ValueFormat = 'text', locale = 'en-US'): string {
108
+ if (value === null || value === undefined || value === '') return '—';
109
+ const spec: FormatSpec = typeof format === 'string' ? { kind: format } : format;
110
+ const { kind, currency = 'USD', digits } = spec;
111
+
112
+ if (kind === 'text') return String(value);
113
+
114
+ if (kind === 'date' || kind === 'datetime') {
115
+ const isDateOnly = typeof value === 'string' && ISO_DATE.test(value);
116
+ const d = value instanceof Date ? value : new Date(value as string | number);
117
+ if (Number.isNaN(d.getTime())) return String(value);
118
+ return new Intl.DateTimeFormat(locale, {
119
+ dateStyle: 'medium',
120
+ ...(kind === 'datetime' ? { timeStyle: 'short' } : {}),
121
+ // A bare YYYY-MM-DD is a calendar date: don't let the server's time zone shift it a day.
122
+ ...(isDateOnly ? { timeZone: 'UTC' } : {}),
123
+ }).format(d);
124
+ }
125
+
126
+ const n = typeof value === 'number' ? value : Number(value);
127
+ if (!Number.isFinite(n)) return String(value);
128
+
129
+ const compactMode = spec.compact ?? (kind === 'compact' ? 'auto' : false);
130
+ const compact = compactMode === true || (compactMode === 'auto' && Math.abs(n) >= 10_000);
131
+ const compactOpts: Intl.NumberFormatOptions = compact
132
+ ? // Minimum 0 so currency drops padded zeros ("$400K", not "$400.0K"); digits is a maximum.
133
+ { notation: 'compact', minimumFractionDigits: 0, maximumFractionDigits: digits ?? 1 }
134
+ : {};
135
+
136
+ switch (kind) {
137
+ case 'integer':
138
+ return withMinus(new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(n));
139
+ case 'number':
140
+ case 'compact':
141
+ return withMinus(
142
+ new Intl.NumberFormat(locale, { maximumFractionDigits: digits ?? 2, ...compactOpts }).format(n),
143
+ );
144
+ case 'currency':
145
+ return withMinus(
146
+ new Intl.NumberFormat(locale, {
147
+ style: 'currency',
148
+ currency,
149
+ ...(digits !== undefined ? { minimumFractionDigits: digits, maximumFractionDigits: digits } : {}),
150
+ ...compactOpts,
151
+ }).format(n),
152
+ );
153
+ case 'percent':
154
+ return withMinus(
155
+ new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: digits ?? 1 }).format(n),
156
+ );
157
+ case 'delta':
158
+ return withMinus(
159
+ new Intl.NumberFormat(locale, { signDisplay: 'exceptZero', maximumFractionDigits: digits ?? 2, ...compactOpts }).format(n),
160
+ );
161
+ case 'unit':
162
+ try {
163
+ return withMinus(
164
+ new Intl.NumberFormat(locale, {
165
+ style: 'unit',
166
+ unit: spec.unit ?? 'percent',
167
+ unitDisplay: spec.unitDisplay ?? 'short',
168
+ maximumFractionDigits: digits ?? 2,
169
+ }).format(n),
170
+ );
171
+ } catch {
172
+ // Unsupported unit identifier: fall back to the plain number rather than throwing at render.
173
+ return withMinus(new Intl.NumberFormat(locale, { maximumFractionDigits: digits ?? 2 }).format(n));
174
+ }
175
+ case 'delta-percent':
176
+ return withMinus(
177
+ new Intl.NumberFormat(locale, { style: 'percent', signDisplay: 'exceptZero', maximumFractionDigits: digits ?? 1 }).format(n),
178
+ );
179
+ default:
180
+ return String(value);
181
+ }
182
+ }
183
+
184
+ /** Raw value as a string for data-value attributes (client-side sorting). */
185
+ export function sortKey(value: unknown): string {
186
+ if (value === null || value === undefined) return '';
187
+ if (value instanceof Date) return value.toISOString();
188
+ return String(value);
189
+ }
190
+
191
+ /** Stable comparison: numbers numerically, strings naturally, empties last in either direction. */
192
+ export function compareValues(a: unknown, b: unknown, locale = 'en-US'): number {
193
+ const empty = (v: unknown) => v === null || v === undefined || v === '';
194
+ if (empty(a) && empty(b)) return 0;
195
+ if (empty(a)) return 1;
196
+ if (empty(b)) return -1;
197
+ const na = typeof a === 'number' ? a : a instanceof Date ? a.getTime() : NaN;
198
+ const nb = typeof b === 'number' ? b : b instanceof Date ? b.getTime() : NaN;
199
+ if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb;
200
+ return String(a).localeCompare(String(b), locale, { numeric: true, sensitivity: 'base' });
201
+ }
202
+
203
+ /** Whole-number percent 0–100 for data-pct (bars, meters). */
204
+ export function pct(value: number, max: number): number {
205
+ if (!Number.isFinite(value) || !Number.isFinite(max) || max <= 0) return 0;
206
+ return Math.round(Math.min(1, Math.max(0, value / max)) * 100);
207
+ }
208
+
209
+ /** Arrow for deltas. Returned as markup so string-built cells (Table) can use it too. */
210
+ export function deltaIconSvg(direction: 'up' | 'down' | 'flat'): string {
211
+ const d =
212
+ direction === 'up'
213
+ ? 'M8 13V3.5M3.75 7.5 8 3.25l4.25 4.25'
214
+ : direction === 'down'
215
+ ? 'M8 3v9.5M3.75 8.5 8 12.75l4.25-4.25'
216
+ : 'M3 8h10';
217
+ return `<svg class="sinn-delta__icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="${d}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
218
+ }
219
+
220
+ /** Tone for a change: success or danger depending on which direction is better; zero is muted. */
221
+ export function deltaTone(n: number, higherIsBetter = true): 'success' | 'danger' | 'muted' {
222
+ if (!n || !Number.isFinite(n)) return 'muted';
223
+ return n > 0 === higherIsBetter ? 'success' : 'danger';
224
+ }
225
+
226
+ /** Deprecated value-tone names → the shared status scale (`good` → `success`, `bad` → `danger`). */
227
+ export const LEGACY_VALUE_TONES: Readonly<Record<string, 'success' | 'danger'>> = { good: 'success', bad: 'danger' };
228
+
229
+ /** Map a value tone to the current vocabulary (`good`/`bad` → `success`/`danger`). */
230
+ export function valueToneOf<T extends string | undefined>(tone: T): T | 'success' | 'danger' {
231
+ return tone && Object.prototype.hasOwnProperty.call(LEGACY_VALUE_TONES, tone) ? LEGACY_VALUE_TONES[tone] : tone;
232
+ }
233
+
234
+ export function deltaDirection(n: number): 'up' | 'down' | 'flat' {
235
+ return !n || !Number.isFinite(n) ? 'flat' : n > 0 ? 'up' : 'down';
236
+ }
237
+
238
+ /** Initials from a name: "Ana María Ruiz" → "AR". */
239
+ export function initialsOf(name: string): string {
240
+ const parts = name.trim().split(/\s+/).filter(Boolean);
241
+ if (!parts.length) return '';
242
+ const first = parts[0][0] ?? '';
243
+ const last = parts.length > 1 ? parts[parts.length - 1][0] ?? '' : '';
244
+ return (first + last).toUpperCase();
245
+ }
246
+
247
+ /** Small status glyph for flagged values: check for success, alert for warning and danger. */
248
+ export function statusIconSvg(tone: 'success' | 'warning' | 'danger' | 'good' | 'bad'): string {
249
+ const inner =
250
+ tone === 'success' || tone === 'good'
251
+ ? '<circle cx="8" cy="8" r="6.25"/><path d="M5.5 8.25 7.25 10l3.25-3.75"/>'
252
+ : '<circle cx="8" cy="8" r="6.25"/><path d="M8 4.75v3.75"/><path d="M8 11.1v.15"/>';
253
+ return `<svg class="sinn-status-value__icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">${inner}</svg>`;
254
+ }
@@ -0,0 +1,35 @@
1
+ ---
2
+ /**
3
+ * JSONLD — structured data so search engines understand the page (organization, local business,
4
+ * breadcrumbs, articles, FAQs, events…). Pass one node, several (combined into an @graph), or a
5
+ * finished document:
6
+ *
7
+ * import { organization, website, breadcrumbList } from '@sinnstack/ui/seo/jsonld';
8
+ * <JSONLD data={[organization({...}), website({...}), breadcrumbList([...], { site: Astro.site })]} />
9
+ *
10
+ * - Serialized safely: `<`, `>` and `&` are escaped, so CMS text containing "</script>" can't
11
+ * break out of the element.
12
+ * - `type="application/ld+json"` is a data block: browsers never execute it, so CSP's script-src
13
+ * doesn't apply and no nonce or hash is needed.
14
+ * - In development, checks Google's required/recommended properties and logs warnings.
15
+ */
16
+ import { graph, serializeJsonLd, validateJsonLd, withContext, type Thing } from './lib/jsonld';
17
+
18
+ type Props = { data: Thing | Thing[] | Record<string, unknown>; warn?: boolean; pretty?: boolean };
19
+ const { data, warn = Boolean(import.meta.env?.DEV), pretty = Boolean(import.meta.env?.DEV) } = Astro.props;
20
+
21
+ const doc = Array.isArray(data)
22
+ ? data.length === 1
23
+ ? withContext(data[0])
24
+ : graph(data)
25
+ : '@context' in data
26
+ ? data
27
+ : withContext(data as Thing);
28
+ if (warn) {
29
+ const warnings = validateJsonLd(doc);
30
+ if (warnings.length) console.warn(`[JSONLD] ${Astro.url.pathname}\n - ${warnings.join('\n - ')}`);
31
+ }
32
+ const json = serializeJsonLd(doc, pretty);
33
+ ---
34
+
35
+ <script is:inline type="application/ld+json" set:html={json} />
@@ -0,0 +1,47 @@
1
+ ---
2
+ /**
3
+ * SEOHead — the page's title, meta description, canonical URL, robots, hreflang alternates,
4
+ * Open Graph and Twitter/X tags. Put it inside <head> in your layout:
5
+ *
6
+ * <SEOHead title={title} description={description} siteName="Sinnstack"
7
+ * titleTemplate="%s | Sinnstack" image={{ src: cover, alt: 'A team reviewing a website launch' }} />
8
+ *
9
+ * - Canonical: the current URL on the production origin (`site` in astro.config), without hash
10
+ * and tracking parameters (keep content params with `keepQuery`), following `trailingSlash`.
11
+ * Preview deploys and query-string variants all point at the one real URL.
12
+ * - Share image: an imported image is cropped to 1200×630 JPEG (what Facebook, LinkedIn, Slack and
13
+ * X show large). A URL string is used as-is (give width/height).
14
+ * - noindex pages are also left out of the sitemap generated by the `sinnSeo` integration.
15
+ * - In development, likely mistakes are logged (missing description, title too long, no share
16
+ * image, image too small, conflicting noindex + canonical…). Turn off with `warn={false}`.
17
+ * - All values are escaped; nothing here runs JavaScript, so it works under a strict CSP.
18
+ */
19
+ import { getImage } from 'astro:assets';
20
+ import type { ImageMetadata } from 'astro';
21
+ import { buildHead, renderHead, type SeoInput } from './lib/meta';
22
+
23
+ type Props = Omit<SeoInput, 'url' | 'site' | 'image' | 'trailingSlash'> & {
24
+ image?: { src: ImageMetadata | string; alt: string; width?: number; height?: number };
25
+ /** Overrides astro.config `trailingSlash` (read from the integration when installed). */
26
+ trailingSlash?: SeoInput['trailingSlash'];
27
+ warn?: boolean;
28
+ };
29
+
30
+ const { image, warn = Boolean(import.meta.env?.DEV), trailingSlash, ...rest } = Astro.props;
31
+
32
+ let shareImage: SeoInput['image'];
33
+ if (image) {
34
+ if (typeof image.src === 'string') {
35
+ shareImage = { url: image.src, alt: image.alt, width: image.width, height: image.height };
36
+ } else {
37
+ const img = await getImage({ src: image.src, width: 1200, height: 630, fit: 'cover', format: 'jpg', quality: 82 });
38
+ shareImage = { url: img.src, alt: image.alt, width: 1200, height: 630, type: 'image/jpeg' };
39
+ }
40
+ }
41
+
42
+ const policy = trailingSlash ?? ((import.meta.env?.SINN_TRAILING_SLASH as SeoInput['trailingSlash']) || 'ignore');
43
+ const head = buildHead({ ...rest, image: shareImage, url: Astro.url, site: Astro.site, trailingSlash: policy });
44
+ if (warn && head.warnings.length) console.warn(`[SEOHead] ${Astro.url.pathname}\n - ${head.warnings.join('\n - ')}`);
45
+ ---
46
+
47
+ <Fragment set:html={renderHead(head.tags)} />
package/src/seo/cms.ts ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Tina fields for SEO: a per-page `seo` object and a site-wide redirect list. Structural (no
3
+ * tinacms dependency), same shape as Tina's field definitions.
4
+ *
5
+ * // page collection
6
+ * fields: [ ...pageFields, seoField ]
7
+ * // site settings singleton
8
+ * fields: [ redirectsField ]
9
+ *
10
+ * In the page: <SEOHead {...seoProps(page.seo, { title: page.title, description: page.summary })} />
11
+ * In config: sinnSeo({ redirects: redirectMapFromCms(settings.redirects) })
12
+ */
13
+ import { RedirectMap, type RedirectStatus } from './lib/redirects';
14
+
15
+ type Field = Record<string, unknown>;
16
+
17
+ export const seoField: Field = {
18
+ type: 'object',
19
+ name: 'seo',
20
+ label: 'Search & sharing',
21
+ fields: [
22
+ { type: 'string', name: 'title', label: 'Search title', description: 'Shown in search results and browser tabs. About 50–60 characters. Leave empty to use the page title.' },
23
+ { type: 'string', name: 'description', label: 'Search description', description: 'One or two sentences, about 120–160 characters.', ui: { component: 'textarea' } },
24
+ { type: 'image', name: 'image', label: 'Share image', description: 'Shown when the page is shared. At least 1200×630.' },
25
+ { type: 'string', name: 'imageAlt', label: 'Share image description' },
26
+ { type: 'boolean', name: 'noindex', label: 'Hide from search engines', description: 'Also removes the page from the sitemap.' },
27
+ { type: 'string', name: 'canonical', label: 'Canonical URL (advanced)', description: 'Only if this page duplicates another one. Full URL.' },
28
+ ],
29
+ };
30
+
31
+ export const redirectsField: Field = {
32
+ type: 'object',
33
+ name: 'redirects',
34
+ label: 'Redirects',
35
+ list: true,
36
+ ui: { itemProps: (item: { from?: string; to?: string }) => ({ label: item?.from ? `${item.from} → ${item.to ?? ''}` : 'Redirect' }) },
37
+ fields: [
38
+ { type: 'string', name: 'from', label: 'Old address', required: true, description: 'A path like /old-page (a full old URL works too).' },
39
+ { type: 'string', name: 'to', label: 'New address', required: true, description: 'A path on this site or a full URL.' },
40
+ {
41
+ type: 'string',
42
+ name: 'status',
43
+ label: 'Type',
44
+ options: [
45
+ { value: '301', label: 'Permanent (301)' },
46
+ { value: '302', label: 'Temporary (302)' },
47
+ ],
48
+ },
49
+ ],
50
+ };
51
+
52
+ export interface CmsSeo {
53
+ title?: string | null;
54
+ description?: string | null;
55
+ image?: string | null;
56
+ imageAlt?: string | null;
57
+ noindex?: boolean | null;
58
+ canonical?: string | null;
59
+ }
60
+
61
+ /** SEOHead props from a page's `seo` object, falling back to page-level values. */
62
+ export function seoProps(seo: CmsSeo | null | undefined, fallback: { title?: string; description?: string; image?: { src: string; alt: string; width?: number; height?: number } } = {}) {
63
+ const s = seo ?? {};
64
+ const t = (v?: string | null) => (v && v.trim() ? v.trim() : undefined);
65
+ return {
66
+ title: t(s.title) ?? fallback.title,
67
+ description: t(s.description) ?? fallback.description,
68
+ image: t(s.image) ? { src: t(s.image)!, alt: t(s.imageAlt) ?? '' } : fallback.image,
69
+ noindex: Boolean(s.noindex),
70
+ canonical: t(s.canonical),
71
+ };
72
+ }
73
+
74
+ /** A RedirectMap from the CMS list (empty rows skipped). Check `.errors` before using it. */
75
+ export function redirectMapFromCms(rows: Array<{ from?: string | null; to?: string | null; status?: string | null }> | null | undefined, options?: ConstructorParameters<typeof RedirectMap>[1]) {
76
+ return new RedirectMap(
77
+ (rows ?? []).filter((r) => r?.from?.trim() && r?.to?.trim()).map((r) => ({ from: r.from!, to: r.to!, status: r.status ? (Number(r.status) as RedirectStatus) : undefined })),
78
+ options,
79
+ );
80
+ }
@@ -0,0 +1,10 @@
1
+ // @sinnstack/ui/seo
2
+ export { default as SEOHead } from './SEOHead.astro';
3
+ export { default as JSONLD } from './JSONLD.astro';
4
+ export { buildHead, renderHead, type SeoInput, type SeoImage, type HeadTag } from './lib/meta';
5
+ export * as jsonld from './lib/jsonld';
6
+ export { RedirectMap, createRedirectMiddleware, type RedirectRule, type RedirectStatus } from './lib/redirects';
7
+ export { buildSitemap, buildSitemapIndex, sitemapEndpoint, type SitemapEntry } from './lib/sitemap';
8
+ export { buildRss, rssEndpoint, type RssFeed, type RssItem } from './lib/rss';
9
+ export { buildRobotsTxt } from './lib/robots';
10
+ export { canonicalize } from './lib/url';
@@ -0,0 +1,231 @@
1
+ /**
2
+ * sinnSeo — Astro integration: sitemap(s) and robots.txt from the built site, and redirects.
3
+ *
4
+ * // astro.config.mjs
5
+ * import sinnSeo from '@sinnstack/ui/seo/integration';
6
+ * export default defineConfig({
7
+ * site: 'https://example.com',
8
+ * integrations: [sinnSeo({ redirects, robots: { production: process.env.DEPLOY_ENV === 'production' } })],
9
+ * });
10
+ *
11
+ * The sitemap is read from the HTML Astro actually wrote, so it agrees with each page's SEOHead:
12
+ * pages marked noindex, pages whose canonical points elsewhere, redirect stubs and error pages
13
+ * are left out; hreflang alternates and article:modified_time (as lastmod) are carried over.
14
+ * On-demand (SSR) pages aren't files: add them with `extraEntries` or a `sitemapEndpoint` route
15
+ * listed in `extraSitemaps`.
16
+ */
17
+ import { readFile, readdir, writeFile, access } from 'node:fs/promises';
18
+ import { join, relative, sep } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { buildSitemap, buildSitemapIndex, chunkEntries, type SitemapEntry } from './lib/sitemap';
21
+ import { buildRobotsTxt, type RobotsRule } from './lib/robots';
22
+ import { RedirectMap, type RedirectRule } from './lib/redirects';
23
+ import { applyTrailingSlash, canonicalize, type TrailingSlash } from './lib/url';
24
+
25
+ export interface SinnSeoOptions {
26
+ sitemap?:
27
+ | false
28
+ | {
29
+ /** Return false to leave a URL out. */
30
+ filter?: (url: string) => boolean;
31
+ /** Paths or patterns to leave out ("/thank-you", /^\/drafts\//). */
32
+ exclude?: Array<string | RegExp>;
33
+ /** Entries for pages that aren't built files (SSR / CMS records). */
34
+ extraEntries?: () => SitemapEntry[] | Promise<SitemapEntry[]>;
35
+ /** Other sitemaps to list in the index (absolute or site-relative), e.g. "/sitemap-records.xml". */
36
+ extraSitemaps?: string[];
37
+ /** lastmod source: from the page (article:modified_time / sinn:lastmod meta, default), build time, or none. */
38
+ lastmod?: 'page' | 'build' | 'none';
39
+ /** Add each page's og:image as an image entry. */
40
+ images?: boolean;
41
+ };
42
+ robots?: false | { production?: boolean; rules?: RobotsRule[] };
43
+ redirects?: RedirectMap | RedirectRule[];
44
+ }
45
+
46
+ interface PageInfo {
47
+ url: string;
48
+ noindex: boolean;
49
+ canonical?: string;
50
+ refresh: boolean;
51
+ alternates: Array<{ hreflang: string; href: string }>;
52
+ lastmod?: string;
53
+ image?: string;
54
+ }
55
+
56
+ const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'" };
57
+ const decode = (s: string) => s.replace(/&(#\d+|#x[\da-f]+|\w+);/gi, (m, e: string) => (e[0] === '#' ? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : (ENTITIES[e] ?? m)));
58
+ function attrsOf(tag: string): Record<string, string> {
59
+ const out: Record<string, string> = {};
60
+ for (const m of tag.matchAll(/([\w:-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g)) out[m[1].toLowerCase()] = decode(m[2] ?? m[3] ?? m[4] ?? '');
61
+ return out;
62
+ }
63
+
64
+ /** Reads the SEO signals from a built page's <head>. Exported for tests. */
65
+ export function readHead(html: string, url: string): PageInfo {
66
+ const head = /<head[\s>][\s\S]*?<\/head>/i.exec(html)?.[0] ?? html.slice(0, 20000);
67
+ const info: PageInfo = { url, noindex: false, refresh: false, alternates: [] };
68
+ for (const m of head.matchAll(/<(meta|link)\b([^>]*)>/gi)) {
69
+ const a = attrsOf(m[2]);
70
+ if (m[1].toLowerCase() === 'meta') {
71
+ if ((a.name === 'robots' || a.name === 'googlebot') && /\bnoindex\b|\bnone\b/i.test(a.content ?? '')) info.noindex = true;
72
+ if ((a['http-equiv'] ?? '').toLowerCase() === 'refresh') info.refresh = true;
73
+ if (a.property === 'article:modified_time' || a.name === 'sinn:lastmod') info.lastmod = a.content;
74
+ if (a.property === 'og:image' && !info.image) info.image = a.content;
75
+ } else {
76
+ const rel = (a.rel ?? '').toLowerCase().split(/\s+/);
77
+ if (rel.includes('canonical')) info.canonical = a.href;
78
+ if (rel.includes('alternate') && a.hreflang && a.href) info.alternates.push({ hreflang: a.hreflang, href: a.href });
79
+ }
80
+ }
81
+ return info;
82
+ }
83
+
84
+ async function* htmlFiles(dir: string): AsyncGenerator<string> {
85
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
86
+ const p = join(dir, entry.name);
87
+ if (entry.isDirectory()) {
88
+ if (entry.name === '_astro' || entry.name.startsWith('.')) continue;
89
+ yield* htmlFiles(p);
90
+ } else if (entry.name.endsWith('.html')) yield p;
91
+ }
92
+ }
93
+
94
+ /** URL path for a built file: about/index.html → /about/, about.html → /about. */
95
+ export function pathForFile(file: string, base: string, trailingSlash: TrailingSlash): string {
96
+ const rel = file.split(sep).join('/');
97
+ let p = `/${rel}`.replace(/\/index\.html$/, '/').replace(/\.html$/, '');
98
+ p = `${base.replace(/\/$/, '')}${p}` || '/';
99
+ return applyTrailingSlash(p, trailingSlash);
100
+ }
101
+
102
+ export interface SitemapReport {
103
+ included: number;
104
+ excluded: Record<'noindex' | 'canonical' | 'redirect' | 'error' | 'filtered', string[]>;
105
+ files: string[];
106
+ }
107
+
108
+ /** The build step, separated from the hook so it can be tested on any folder. */
109
+ export async function writeSitemaps(args: {
110
+ dir: string;
111
+ site: string;
112
+ base?: string;
113
+ trailingSlash?: TrailingSlash;
114
+ options: Exclude<SinnSeoOptions['sitemap'], false | undefined> | undefined;
115
+ robots?: SinnSeoOptions['robots'];
116
+ redirects?: RedirectMap;
117
+ warn?: (msg: string) => void;
118
+ }): Promise<SitemapReport> {
119
+ const { dir, site, base = '/', trailingSlash = 'ignore', options = {}, warn = () => {} } = args;
120
+ const report: SitemapReport = { included: 0, excluded: { noindex: [], canonical: [], redirect: [], error: [], filtered: [] }, files: [] };
121
+ const entries: SitemapEntry[] = [];
122
+ const builtPaths = new Set<string>();
123
+ const now = new Date().toISOString();
124
+ const excluded = (path: string) => (options.exclude ?? []).some((e) => (typeof e === 'string' ? path === e || path.startsWith(e.endsWith('/') ? e : `${e}/`) || path === `${e}/` : e.test(path)));
125
+
126
+ for await (const file of htmlFiles(dir)) {
127
+ const rel = relative(dir, file);
128
+ const path = pathForFile(rel, base, trailingSlash);
129
+ const url = new URL(path, site).href;
130
+ if (/^(404|500)(\.html|\/index\.html)$/.test(rel.split(sep).join('/'))) {
131
+ report.excluded.error.push(path);
132
+ continue;
133
+ }
134
+ const info = readHead(await readFile(file, 'utf8'), url);
135
+ if (info.refresh) {
136
+ report.excluded.redirect.push(path);
137
+ continue;
138
+ }
139
+ builtPaths.add(path.replace(/(.)\/$/, '$1'));
140
+ if (info.noindex) {
141
+ report.excluded.noindex.push(path);
142
+ continue;
143
+ }
144
+ if (info.canonical && canonicalize(info.canonical, { trailingSlash }) !== canonicalize(url, { trailingSlash })) {
145
+ report.excluded.canonical.push(path);
146
+ continue;
147
+ }
148
+ if (excluded(path) || (options.filter && !options.filter(url))) {
149
+ report.excluded.filtered.push(path);
150
+ continue;
151
+ }
152
+ entries.push({
153
+ loc: url,
154
+ lastmod: options.lastmod === 'none' ? undefined : options.lastmod === 'build' ? now : info.lastmod,
155
+ alternates: info.alternates.length ? info.alternates : undefined,
156
+ images: options.images && info.image ? [{ loc: info.image }] : undefined,
157
+ });
158
+ }
159
+ if (options.extraEntries) entries.push(...(await options.extraEntries()));
160
+
161
+ const chunks = chunkEntries(entries);
162
+ const sitemapUrls: Array<{ loc: string; lastmod?: string }> = [];
163
+ for (const [i, chunk] of chunks.entries()) {
164
+ const name = `sitemap-${i}.xml`;
165
+ await writeFile(join(dir, name), buildSitemap(chunk));
166
+ report.files.push(name);
167
+ sitemapUrls.push({ loc: new URL(`${base.replace(/\/$/, '')}/${name}`, site).href });
168
+ report.included += chunk.length;
169
+ }
170
+ for (const extra of options.extraSitemaps ?? []) sitemapUrls.push({ loc: new URL(extra, site).href });
171
+ await writeFile(join(dir, 'sitemap-index.xml'), buildSitemapIndex(sitemapUrls));
172
+ report.files.push('sitemap-index.xml');
173
+
174
+ if (args.robots !== false) {
175
+ const robotsPath = join(dir, 'robots.txt');
176
+ const exists = await access(robotsPath).then(() => true, () => false);
177
+ if (exists) warn('robots.txt already exists (from public/); not overwritten. Make sure it lists the sitemap.');
178
+ else {
179
+ const r = args.robots ?? {};
180
+ await writeFile(robotsPath, buildRobotsTxt({ production: r.production ?? true, rules: r.rules, sitemaps: [new URL(`${base.replace(/\/$/, '')}/sitemap-index.xml`, site).href] }));
181
+ report.files.push('robots.txt');
182
+ }
183
+ }
184
+
185
+ // Redirect sources that are also real pages never redirect on most hosts.
186
+ for (const rule of args.redirects?.rules ?? []) {
187
+ if (!rule.from.includes('[') && builtPaths.has(rule.from.replace(/(.)\/$/, '$1'))) warn(`Redirect source "${rule.from}" is also a page in the build; one of them is unreachable.`);
188
+ }
189
+ return report;
190
+ }
191
+
192
+ export default function sinnSeo(options: SinnSeoOptions = {}) {
193
+ let site: string | undefined;
194
+ let base = '/';
195
+ let trailingSlash: TrailingSlash = 'ignore';
196
+ let redirects: RedirectMap | undefined;
197
+
198
+ return {
199
+ name: '@sinnstack/ui/seo',
200
+ hooks: {
201
+ 'astro:config:setup': ({ config, updateConfig, logger }: any) => {
202
+ if (options.redirects) {
203
+ redirects = options.redirects instanceof RedirectMap ? options.redirects : new RedirectMap(options.redirects);
204
+ for (const w of redirects.warnings) logger.warn(w);
205
+ redirects.assertValid();
206
+ updateConfig({ redirects: { ...redirects.toAstro(), ...(config.redirects ?? {}) } });
207
+ logger.info(`${redirects.rules.length} redirects added.`);
208
+ }
209
+ // SEOHead reads the trailing-slash policy from here, so canonicals match your routes.
210
+ updateConfig({ vite: { define: { 'import.meta.env.SINN_TRAILING_SLASH': JSON.stringify(config.trailingSlash ?? 'ignore') } } });
211
+ },
212
+ 'astro:config:done': ({ config }: any) => {
213
+ site = config.site;
214
+ base = config.base ?? '/';
215
+ trailingSlash = config.trailingSlash ?? 'ignore';
216
+ },
217
+ 'astro:build:done': async ({ dir, logger }: any) => {
218
+ if (options.sitemap === false) return;
219
+ if (!site) {
220
+ logger.warn('No `site` in astro.config: skipping the sitemap and robots.txt (they need absolute URLs).');
221
+ return;
222
+ }
223
+ const report = await writeSitemaps({ dir: fileURLToPath(dir), site, base, trailingSlash, options: options.sitemap || {}, robots: options.robots, redirects, warn: (m) => logger.warn(m) });
224
+ const ex = report.excluded;
225
+ logger.info(
226
+ `Sitemap: ${report.included} URLs in ${report.files.filter((f) => f.startsWith('sitemap-') && f !== 'sitemap-index.xml').length} file(s). Left out: ${ex.noindex.length} noindex, ${ex.canonical.length} non-canonical, ${ex.redirect.length} redirects, ${ex.error.length} error pages, ${ex.filtered.length} filtered.`,
227
+ );
228
+ },
229
+ },
230
+ };
231
+ }