@sarimarcus/content-sites-core 0.32.3 → 0.33.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/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  All packages in the platform release in lockstep; entries are per release version.
4
4
 
5
+ ## 0.33.0 (2026-10-12)
6
+
7
+ - `./text` adds `splitBodySections` and `bodyExtrasHtml` (with the `BodySection`, `BodyContent` and `SplitBodyOptions` types), moved from the tourism sites' `utils/bodySections.ts`; output is unchanged (SLA-3043).
8
+
9
+ ### Breaking
10
+
11
+ - A site's own `utils/bodySections.ts` is now a refused local copy of `splitBodySections`/`bodyExtrasHtml`; `scripts/platform/migrations/core-body-sections.mjs` (after `rewrite-imports.mjs`) deletes it on the tourism sites (SLA-3043).
12
+
5
13
  ## 0.32.3 (2026-10-11)
6
14
 
7
15
  - No changes; lockstep release with ui.
@@ -0,0 +1,48 @@
1
+ export interface BodySection {
2
+ /** Anchor id, unique within the page. */
3
+ id: string;
4
+ /** Raw markdown heading text — the source of truth for label and slug. */
5
+ heading: string;
6
+ /** Plain-text heading, for ToC pills and aria labels. */
7
+ label: string;
8
+ /** Inline-parsed heading, for the rendered `<h2>` (one real heading is a link). */
9
+ headingHtml: string;
10
+ /** `parseMarkdown()` output for this section's body, heading line removed. */
11
+ html: string;
12
+ }
13
+ export interface BodyContent {
14
+ /** HTML for content before the first H2. `''` when the body opens with an H2. */
15
+ lede: string;
16
+ /** `[]` when the body has no top-level H2 at all — then everything is `lede`. */
17
+ sections: BodySection[];
18
+ /** Every HTML fragment produced, for `extractProseHrefs()`. */
19
+ htmlChunks: string[];
20
+ }
21
+ export interface SplitBodyOptions {
22
+ /** Forwarded verbatim to parseMarkdown/parseMarkdownInline. Default '/'. */
23
+ basePath?: string;
24
+ /** Page-level ids the generated slugs must not collide with. */
25
+ reservedIds?: readonly string[];
26
+ }
27
+ /**
28
+ * Splits `markdown` on top-level H2 boundaries and renders each chunk with the
29
+ * existing `parseMarkdown`.
30
+ *
31
+ * Splitting the string before `marked` sees it is safe here because no
32
+ * cross-chunk parser state exists in this corpus: zero reference link
33
+ * definitions and zero footnote markers across all 199 bodies, and
34
+ * `parseMarkdown` deliberately does not convert footnotes anyway.
35
+ *
36
+ * Returns `{ lede, sections, htmlChunks }` rather than a flat list so the
37
+ * no-H2 case degrades for free: `sections` is empty, the whole body lands in
38
+ * `lede`, and a template written against this API renders short items exactly as
39
+ * it does today with no extra conditional in the markup.
40
+ */
41
+ export declare function splitBodySections(markdown: string | null | undefined, options?: SplitBodyOptions): BodyContent;
42
+ /**
43
+ * HTML of the body blocks that sit outside the H2 split (insider tips, authored
44
+ * interludes), so a page can dedupe the related zone against their links too.
45
+ */
46
+ export declare function bodyExtrasHtml(tips?: {
47
+ body: string;
48
+ }[], interludes?: any[], basePath?: string): string[];
@@ -0,0 +1,133 @@
1
+ import { parseMarkdown, parseMarkdownInline, stripMarkdown } from "./markdown.js";
2
+ import { slugify } from "./slugify.js";
3
+ /**
4
+ * Splits an item's `longDescription` markdown into per-H2 sections so a page can
5
+ * render real anchor targets and drive its Table of Contents from the SAME array
6
+ * that renders the markup.
7
+ *
8
+ * Why this exists: entity templates hand-authored their ToC from template-level
9
+ * sections only (`About / Ingredients / FAQ`), while the body markdown carried
10
+ * 3-10 H2s of its own that the ToC never listed. `parseMarkdown()` uses marked
11
+ * v18, which dropped `headerIds`, so those H2s also rendered with no `id` —
12
+ * there was nothing to anchor to even if they had been listed. 199 items across
13
+ * 9 collections were affected (979 H2s). Deriving both the pills and the
14
+ * `<section>`s from one array is the discipline articles/[slug].astro already
15
+ * uses, and it is what makes desync impossible.
16
+ *
17
+ * This module deliberately sits beside `markdown.ts` rather than inside it:
18
+ * that file is a pure `marked` adapter with no domain concepts, imported by
19
+ * nearly every page. Keeping it frozen means this module can only *call*
20
+ * `parseMarkdown`, never alter its behavior.
21
+ */
22
+ /** Page furniture that exists on every page, so a heading slug must never win it. */
23
+ const GLOBAL_RESERVED_IDS = [
24
+ 'main-content',
25
+ 'main-nav',
26
+ 'mobile-menu',
27
+ 'mobile-menu-btn',
28
+ 'mobile-search-btn',
29
+ 'stcm-form',
30
+ ];
31
+ /** Opening/closing fence for a code block: up to 3 leading spaces, then 3+ ` or ~. */
32
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
33
+ /**
34
+ * A top-level ATX H2, with optional closing hashes stripped.
35
+ *
36
+ * `###` cannot match: the `[ \t]+` requires whitespace directly after `##`. The
37
+ * `^` anchor is what makes an indented code block (` ## x`), a blockquoted
38
+ * heading (`> ## x`) and a table row (`| ## x |`) unsplittable, so those keep
39
+ * rendering exactly as they do today.
40
+ */
41
+ const H2_RE = /^##[ \t]+(.+?)[ \t]*#*[ \t]*$/;
42
+ /** Appends `-2`, `-3`, … until the id is free. Order-deterministic within one body. */
43
+ function uniqueId(root, used) {
44
+ let id = root;
45
+ let n = 2;
46
+ while (used.has(id))
47
+ id = `${root}-${n++}`;
48
+ used.add(id);
49
+ return id;
50
+ }
51
+ /**
52
+ * Splits `markdown` on top-level H2 boundaries and renders each chunk with the
53
+ * existing `parseMarkdown`.
54
+ *
55
+ * Splitting the string before `marked` sees it is safe here because no
56
+ * cross-chunk parser state exists in this corpus: zero reference link
57
+ * definitions and zero footnote markers across all 199 bodies, and
58
+ * `parseMarkdown` deliberately does not convert footnotes anyway.
59
+ *
60
+ * Returns `{ lede, sections, htmlChunks }` rather than a flat list so the
61
+ * no-H2 case degrades for free: `sections` is empty, the whole body lands in
62
+ * `lede`, and a template written against this API renders short items exactly as
63
+ * it does today with no extra conditional in the markup.
64
+ */
65
+ export function splitBodySections(markdown, options = {}) {
66
+ const { basePath = '/', reservedIds = [] } = options;
67
+ if (!markdown || !markdown.trim())
68
+ return { lede: '', sections: [], htmlChunks: [] };
69
+ // --- 1. line scan into chunks; chunks[0] is always the lede slot ----------
70
+ const chunks = [{ heading: '', lines: [] }];
71
+ let inFence = false;
72
+ let fenceChar = '';
73
+ let fenceLen = 0;
74
+ for (const line of markdown.split('\n')) {
75
+ const fence = FENCE_RE.exec(line);
76
+ if (fence) {
77
+ const marker = fence[1];
78
+ if (!inFence) {
79
+ inFence = true;
80
+ fenceChar = marker[0];
81
+ fenceLen = marker.length;
82
+ }
83
+ else if (marker[0] === fenceChar && marker.length >= fenceLen) {
84
+ inFence = false;
85
+ }
86
+ chunks[chunks.length - 1].lines.push(line);
87
+ continue;
88
+ }
89
+ if (!inFence) {
90
+ const h2 = H2_RE.exec(line);
91
+ if (h2) {
92
+ chunks.push({ heading: h2[1], lines: [] });
93
+ continue;
94
+ }
95
+ }
96
+ chunks[chunks.length - 1].lines.push(line);
97
+ }
98
+ // --- 2. render ------------------------------------------------------------
99
+ const used = new Set([...GLOBAL_RESERVED_IDS, ...reservedIds]);
100
+ const lede = parseMarkdown(chunks[0].lines.join('\n').trim(), basePath);
101
+ const sections = chunks.slice(1).map((chunk) => {
102
+ // The pill is already an anchor, so it cannot nest the link one heading has.
103
+ const label = stripMarkdown(chunk.heading);
104
+ return {
105
+ // Slug from the STRIPPED label, never the raw markdown: slugifying
106
+ // `[Mazamorra](/dish/mazamorra)` would drag the URL into the id.
107
+ // A heading that slugifies to nothing (emoji- or CJK-only) still gets one.
108
+ id: uniqueId(slugify(label) || 'section', used),
109
+ heading: chunk.heading,
110
+ label,
111
+ headingHtml: parseMarkdownInline(chunk.heading, basePath),
112
+ html: parseMarkdown(chunk.lines.join('\n').trim(), basePath),
113
+ };
114
+ });
115
+ const htmlChunks = [lede, ...sections.flatMap((s) => [s.headingHtml, s.html])].filter(Boolean);
116
+ return { lede, sections, htmlChunks };
117
+ }
118
+ /**
119
+ * HTML of the body blocks that sit outside the H2 split (insider tips, authored
120
+ * interludes), so a page can dedupe the related zone against their links too.
121
+ */
122
+ export function bodyExtrasHtml(tips = [], interludes = [], basePath = '/') {
123
+ const strings = interludes.flatMap((il) => [
124
+ il.content,
125
+ il.caption,
126
+ ...(il.events ?? []).flatMap((e) => [e.label, e.description]),
127
+ ...(il.rows ?? []).flat(),
128
+ ]).filter((s) => typeof s === 'string' && s.length > 0);
129
+ return [
130
+ ...tips.map((t) => parseMarkdown(t.body, basePath)),
131
+ ...strings.map((s) => parseMarkdownInline(s, basePath)),
132
+ ].filter(Boolean);
133
+ }
@@ -4,3 +4,5 @@ export { fitLength } from './fitLength.ts';
4
4
  export { readingTime } from './readingTime.ts';
5
5
  export { parseMarkdown, parseMarkdownInline, parseMarkdownBlock, stripMarkdown } from './markdown.ts';
6
6
  export { formatFromPrice } from './cardCopy.ts';
7
+ export { splitBodySections, bodyExtrasHtml } from './bodySections.ts';
8
+ export type { BodySection, BodyContent, SplitBodyOptions } from './bodySections.ts';
@@ -5,3 +5,4 @@ export { fitLength } from "./fitLength.js";
5
5
  export { readingTime } from "./readingTime.js";
6
6
  export { parseMarkdown, parseMarkdownInline, parseMarkdownBlock, stripMarkdown } from "./markdown.js";
7
7
  export { formatFromPrice } from "./cardCopy.js";
8
+ export { splitBodySections, bodyExtrasHtml } from "./bodySections.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sarimarcus/content-sites-core",
3
- "version": "0.32.3",
3
+ "version": "0.33.0",
4
4
  "description": "Non-visual utilities, Astro config builders and SEO schema assembly shared by the content sites.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,182 @@
1
+ import { parseMarkdown, parseMarkdownInline, stripMarkdown } from './markdown.ts';
2
+ import { slugify } from './slugify.ts';
3
+
4
+ /**
5
+ * Splits an item's `longDescription` markdown into per-H2 sections so a page can
6
+ * render real anchor targets and drive its Table of Contents from the SAME array
7
+ * that renders the markup.
8
+ *
9
+ * Why this exists: entity templates hand-authored their ToC from template-level
10
+ * sections only (`About / Ingredients / FAQ`), while the body markdown carried
11
+ * 3-10 H2s of its own that the ToC never listed. `parseMarkdown()` uses marked
12
+ * v18, which dropped `headerIds`, so those H2s also rendered with no `id` —
13
+ * there was nothing to anchor to even if they had been listed. 199 items across
14
+ * 9 collections were affected (979 H2s). Deriving both the pills and the
15
+ * `<section>`s from one array is the discipline articles/[slug].astro already
16
+ * uses, and it is what makes desync impossible.
17
+ *
18
+ * This module deliberately sits beside `markdown.ts` rather than inside it:
19
+ * that file is a pure `marked` adapter with no domain concepts, imported by
20
+ * nearly every page. Keeping it frozen means this module can only *call*
21
+ * `parseMarkdown`, never alter its behavior.
22
+ */
23
+
24
+ /** Page furniture that exists on every page, so a heading slug must never win it. */
25
+ const GLOBAL_RESERVED_IDS = [
26
+ 'main-content',
27
+ 'main-nav',
28
+ 'mobile-menu',
29
+ 'mobile-menu-btn',
30
+ 'mobile-search-btn',
31
+ 'stcm-form',
32
+ ] as const;
33
+
34
+ export interface BodySection {
35
+ /** Anchor id, unique within the page. */
36
+ id: string;
37
+ /** Raw markdown heading text — the source of truth for label and slug. */
38
+ heading: string;
39
+ /** Plain-text heading, for ToC pills and aria labels. */
40
+ label: string;
41
+ /** Inline-parsed heading, for the rendered `<h2>` (one real heading is a link). */
42
+ headingHtml: string;
43
+ /** `parseMarkdown()` output for this section's body, heading line removed. */
44
+ html: string;
45
+ }
46
+
47
+ export interface BodyContent {
48
+ /** HTML for content before the first H2. `''` when the body opens with an H2. */
49
+ lede: string;
50
+ /** `[]` when the body has no top-level H2 at all — then everything is `lede`. */
51
+ sections: BodySection[];
52
+ /** Every HTML fragment produced, for `extractProseHrefs()`. */
53
+ htmlChunks: string[];
54
+ }
55
+
56
+ export interface SplitBodyOptions {
57
+ /** Forwarded verbatim to parseMarkdown/parseMarkdownInline. Default '/'. */
58
+ basePath?: string;
59
+ /** Page-level ids the generated slugs must not collide with. */
60
+ reservedIds?: readonly string[];
61
+ }
62
+
63
+ /** Opening/closing fence for a code block: up to 3 leading spaces, then 3+ ` or ~. */
64
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
65
+
66
+ /**
67
+ * A top-level ATX H2, with optional closing hashes stripped.
68
+ *
69
+ * `###` cannot match: the `[ \t]+` requires whitespace directly after `##`. The
70
+ * `^` anchor is what makes an indented code block (` ## x`), a blockquoted
71
+ * heading (`> ## x`) and a table row (`| ## x |`) unsplittable, so those keep
72
+ * rendering exactly as they do today.
73
+ */
74
+ const H2_RE = /^##[ \t]+(.+?)[ \t]*#*[ \t]*$/;
75
+
76
+ /** Appends `-2`, `-3`, … until the id is free. Order-deterministic within one body. */
77
+ function uniqueId(root: string, used: Set<string>): string {
78
+ let id = root;
79
+ let n = 2;
80
+ while (used.has(id)) id = `${root}-${n++}`;
81
+ used.add(id);
82
+ return id;
83
+ }
84
+
85
+ /**
86
+ * Splits `markdown` on top-level H2 boundaries and renders each chunk with the
87
+ * existing `parseMarkdown`.
88
+ *
89
+ * Splitting the string before `marked` sees it is safe here because no
90
+ * cross-chunk parser state exists in this corpus: zero reference link
91
+ * definitions and zero footnote markers across all 199 bodies, and
92
+ * `parseMarkdown` deliberately does not convert footnotes anyway.
93
+ *
94
+ * Returns `{ lede, sections, htmlChunks }` rather than a flat list so the
95
+ * no-H2 case degrades for free: `sections` is empty, the whole body lands in
96
+ * `lede`, and a template written against this API renders short items exactly as
97
+ * it does today with no extra conditional in the markup.
98
+ */
99
+ export function splitBodySections(
100
+ markdown: string | null | undefined,
101
+ options: SplitBodyOptions = {},
102
+ ): BodyContent {
103
+ const { basePath = '/', reservedIds = [] } = options;
104
+
105
+ if (!markdown || !markdown.trim()) return { lede: '', sections: [], htmlChunks: [] };
106
+
107
+ // --- 1. line scan into chunks; chunks[0] is always the lede slot ----------
108
+ const chunks: { heading: string; lines: string[] }[] = [{ heading: '', lines: [] }];
109
+ let inFence = false;
110
+ let fenceChar = '';
111
+ let fenceLen = 0;
112
+
113
+ for (const line of markdown.split('\n')) {
114
+ const fence = FENCE_RE.exec(line);
115
+ if (fence) {
116
+ const marker = fence[1];
117
+ if (!inFence) {
118
+ inFence = true;
119
+ fenceChar = marker[0];
120
+ fenceLen = marker.length;
121
+ } else if (marker[0] === fenceChar && marker.length >= fenceLen) {
122
+ inFence = false;
123
+ }
124
+ chunks[chunks.length - 1].lines.push(line);
125
+ continue;
126
+ }
127
+
128
+ if (!inFence) {
129
+ const h2 = H2_RE.exec(line);
130
+ if (h2) {
131
+ chunks.push({ heading: h2[1], lines: [] });
132
+ continue;
133
+ }
134
+ }
135
+
136
+ chunks[chunks.length - 1].lines.push(line);
137
+ }
138
+
139
+ // --- 2. render ------------------------------------------------------------
140
+ const used = new Set<string>([...GLOBAL_RESERVED_IDS, ...reservedIds]);
141
+ const lede = parseMarkdown(chunks[0].lines.join('\n').trim(), basePath);
142
+
143
+ const sections: BodySection[] = chunks.slice(1).map((chunk) => {
144
+ // The pill is already an anchor, so it cannot nest the link one heading has.
145
+ const label = stripMarkdown(chunk.heading);
146
+ return {
147
+ // Slug from the STRIPPED label, never the raw markdown: slugifying
148
+ // `[Mazamorra](/dish/mazamorra)` would drag the URL into the id.
149
+ // A heading that slugifies to nothing (emoji- or CJK-only) still gets one.
150
+ id: uniqueId(slugify(label) || 'section', used),
151
+ heading: chunk.heading,
152
+ label,
153
+ headingHtml: parseMarkdownInline(chunk.heading, basePath),
154
+ html: parseMarkdown(chunk.lines.join('\n').trim(), basePath),
155
+ };
156
+ });
157
+
158
+ const htmlChunks = [lede, ...sections.flatMap((s) => [s.headingHtml, s.html])].filter(Boolean);
159
+
160
+ return { lede, sections, htmlChunks };
161
+ }
162
+
163
+ /**
164
+ * HTML of the body blocks that sit outside the H2 split (insider tips, authored
165
+ * interludes), so a page can dedupe the related zone against their links too.
166
+ */
167
+ export function bodyExtrasHtml(
168
+ tips: { body: string }[] = [],
169
+ interludes: any[] = [],
170
+ basePath = '/',
171
+ ): string[] {
172
+ const strings = interludes.flatMap((il) => [
173
+ il.content,
174
+ il.caption,
175
+ ...(il.events ?? []).flatMap((e: any) => [e.label, e.description]),
176
+ ...(il.rows ?? []).flat(),
177
+ ]).filter((s): s is string => typeof s === 'string' && s.length > 0);
178
+ return [
179
+ ...tips.map((t) => parseMarkdown(t.body, basePath)),
180
+ ...strings.map((s) => parseMarkdownInline(s, basePath)),
181
+ ].filter(Boolean);
182
+ }
package/src/text/index.ts CHANGED
@@ -5,3 +5,5 @@ export { fitLength } from './fitLength.ts';
5
5
  export { readingTime } from './readingTime.ts';
6
6
  export { parseMarkdown, parseMarkdownInline, parseMarkdownBlock, stripMarkdown } from './markdown.ts';
7
7
  export { formatFromPrice } from './cardCopy.ts';
8
+ export { splitBodySections, bodyExtrasHtml } from './bodySections.ts';
9
+ export type { BodySection, BodyContent, SplitBodyOptions } from './bodySections.ts';