@clarusjs/content 0.0.1 → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Felix Orinda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
1
  # @clarusjs/content
2
2
 
3
- Reserved. Markdown pages for clarusjs: https://github.com/forinda/clarusjs
3
+ Markdown pages for [clarusjs](https://github.com/forinda/clarusjs). Every `.md` file under `src/pages` becomes a page: its Markdown is rendered to static HTML inside your layout at build time.
4
+
5
+ ```ts
6
+ // vite.config.ts
7
+ import { defineConfig } from 'vite'
8
+ import clarusjs from 'clarusjs/vite'
9
+ import markdown from '@clarusjs/content'
10
+
11
+ export default defineConfig({
12
+ plugins: [clarusjs({ sources: [markdown({ layout: '/src/layouts/docs.tscl' })] })],
13
+ })
14
+ ```
15
+
16
+ - **Frontmatter:** `title`, `description` and `layout` (a root-relative path, or `false` for none).
17
+ - **Components in Markdown:** `@import name from '…'` lines at the top, then use the component like HTML.
18
+ - **Headings** get ids and anchor links.
19
+ - **Static output:** `{{ }}` and `@` in your prose are text, never template code.
20
+
21
+ Build-time only: nothing here ships to the browser. See the [Markdown pages guide](https://clarusjs.com/guide/markdown).
22
+
23
+ MIT licensed.
@@ -0,0 +1,2 @@
1
+ /** Highlighted <pre> for `code` in `lang` (unknown languages are plain text); `meta` carries `{1,3-5}`. */
2
+ export declare function highlight(code: string, lang: string, meta: string): string;
@@ -0,0 +1,44 @@
1
+ import { createHighlighterCoreSync } from 'shiki/core';
2
+ import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
3
+ import { transformerMetaHighlight, transformerNotationDiff, transformerNotationErrorLevel, transformerNotationFocus, transformerNotationHighlight, } from '@shikijs/transformers';
4
+ import angularHtml from 'shiki/langs/angular-html.mjs';
5
+ import bash from 'shiki/langs/bash.mjs';
6
+ import css from 'shiki/langs/css.mjs';
7
+ import diff from 'shiki/langs/diff.mjs';
8
+ import html from 'shiki/langs/html.mjs';
9
+ import javascript from 'shiki/langs/javascript.mjs';
10
+ import json from 'shiki/langs/json.mjs';
11
+ import markdown from 'shiki/langs/markdown.mjs';
12
+ import toml from 'shiki/langs/toml.mjs';
13
+ import tsx from 'shiki/langs/tsx.mjs';
14
+ import typescript from 'shiki/langs/typescript.mjs';
15
+ import yaml from 'shiki/langs/yaml.mjs';
16
+ import githubDark from 'shiki/themes/github-dark-default.mjs';
17
+ import githubLight from 'shiki/themes/github-light-default.mjs';
18
+ const ALIASES = { tscl: 'angular-html', ts: 'typescript', js: 'javascript', sh: 'bash', shell: 'bash', zsh: 'bash', md: 'markdown', yml: 'yaml' };
19
+ const light = JSON.parse(JSON.stringify(githubLight).replace(/#6e7781/gi, '#59636e'));
20
+ let highlighter;
21
+ const get = () => (highlighter ??= createHighlighterCoreSync({
22
+ themes: [light, githubDark],
23
+ langs: [angularHtml, bash, css, diff, html, javascript, json, markdown, toml, tsx, typescript, yaml],
24
+ engine: createJavaScriptRegexEngine(),
25
+ }));
26
+ const transformers = [
27
+ transformerNotationDiff(),
28
+ transformerNotationFocus(),
29
+ transformerNotationHighlight(),
30
+ transformerNotationErrorLevel(),
31
+ transformerMetaHighlight(),
32
+ ];
33
+ export function highlight(code, lang, meta) {
34
+ const hl = get();
35
+ const id = ALIASES[lang] ?? lang;
36
+ const known = hl.getLoadedLanguages().includes(id);
37
+ return hl.codeToHtml(code, {
38
+ lang: known ? id : 'text',
39
+ themes: { light: 'github-light-default', dark: 'github-dark-default' },
40
+ defaultColor: false,
41
+ meta: { __raw: meta },
42
+ transformers,
43
+ });
44
+ }
@@ -0,0 +1,33 @@
1
+ import type { Source } from 'clarusjs/vite';
2
+ export type MarkdownOptions = {
3
+ /** The layout every page renders in, root-relative (`/src/layouts/docs.tscl`). Frontmatter `layout` overrides it; `false` means none. */
4
+ layout?: string | false;
5
+ /**
6
+ * Render `::: tip` blocks (and alerts) through your own component: `<tag [type]="'tip'">`, with a custom title in its
7
+ * `title` slot. Without it they are plain HTML: `<div class="custom-block tip">`.
8
+ */
9
+ container?: {
10
+ tag: string;
11
+ from: string;
12
+ };
13
+ /** Block titles, to localize them: { tip: 'Astuce', note: 'Remarque', … }. */
14
+ titles?: Partial<Record<string, string>>;
15
+ /** Put your copy component in every code block: `<tag attach="interaction" />` (it finds the code itself). */
16
+ copy?: {
17
+ tag: string;
18
+ from: string;
19
+ };
20
+ /**
21
+ * Render `::: quiz` blocks through your quiz component (an island): `<tag [name] [question] [options] [answer]>`
22
+ * with the explanation as its content. Without it they are static HTML that works without JavaScript.
23
+ */
24
+ quiz?: {
25
+ tag: string;
26
+ from: string;
27
+ };
28
+ /** `::: quiz` is for lessons (frontmatter `steps: true`); 'everywhere' allows it on any page. */
29
+ quizzes?: 'lessons' | 'everywhere';
30
+ };
31
+ /** 'Hello, World!' → 'hello-world'. Shared by heading ids and (later) link checking. */
32
+ export declare function slugify(text: string): string;
33
+ export default function markdown(options?: MarkdownOptions): Source;
package/dist/index.js ADDED
@@ -0,0 +1,358 @@
1
+ import { dirname, relative, resolve, sep } from 'node:path';
2
+ import MarkdownIt from 'markdown-it';
3
+ import { parse as parseYaml } from 'yaml';
4
+ import { highlight } from './highlight.js';
5
+ import { expand } from './snippets.js';
6
+ const TYPES = ['tip', 'info', 'warning', 'danger', 'details', 'code-group', 'quiz'];
7
+ const TITLES = { tip: 'Tip', info: 'Info', warning: 'Warning', danger: 'Danger', details: 'Details', note: 'Note', important: 'Important', caution: 'Caution' };
8
+ const ALERTS = { note: 'info', tip: 'tip', important: 'info', warning: 'warning', caution: 'danger' };
9
+ const inert = (s) => escapeHtml(s).replace(/\{/g, '&#123;').replace(/\}/g, '&#125;').replace(/@/g, '&#64;');
10
+ export function slugify(text) {
11
+ return text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\w\s-]/g, '').trim().replace(/[\s_-]+/g, '-') || 'section';
12
+ }
13
+ const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\u0022').replace(/\n/g, '\\n')}'`;
14
+ const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
15
+ function renderer(options) {
16
+ const md = new MarkdownIt({ html: true, linkify: true });
17
+ const titles = { ...TITLES, ...options.titles };
18
+ md.block.ruler.before('fence', 'cl_container', (state, startLine, endLine, silent) => {
19
+ const line = state.src.slice(state.bMarks[startLine] + state.tShift[startLine], state.eMarks[startLine]).trim();
20
+ const m = /^(:{3,})\s*([a-z-]+)(?:\s+(.*))?$/.exec(line);
21
+ if (!m || !TYPES.includes(m[2]))
22
+ return false;
23
+ if (silent)
24
+ return true;
25
+ let close = startLine + 1;
26
+ let fence = '';
27
+ for (; close < endLine; close++) {
28
+ const text = state.src.slice(state.bMarks[close] + state.tShift[close], state.eMarks[close]).trim();
29
+ const marker = /^(`{3,}|~{3,})/.exec(text)?.[1];
30
+ if (fence) {
31
+ if (marker && marker[0] === fence[0] && marker.length >= fence.length && text === marker)
32
+ fence = '';
33
+ continue;
34
+ }
35
+ if (marker) {
36
+ fence = marker;
37
+ continue;
38
+ }
39
+ if (text === m[1])
40
+ break;
41
+ }
42
+ const open = state.push(m[2] === 'code-group' ? 'cl_group_open' : 'cl_container_open', 'div', 1);
43
+ open.info = m[2];
44
+ open.meta = { title: m[3]?.trim() || titles[m[2]] };
45
+ const oldMax = state.lineMax;
46
+ state.lineMax = close;
47
+ state.md.block.tokenize(state, startLine + 1, close);
48
+ state.lineMax = oldMax;
49
+ state.push(m[2] === 'code-group' ? 'cl_group_close' : 'cl_container_close', 'div', -1).info = m[2];
50
+ state.line = Math.min(close + 1, endLine);
51
+ return true;
52
+ });
53
+ md.core.ruler.after('block', 'cl_alerts', (state) => {
54
+ const t = state.tokens;
55
+ for (let i = 0; i < t.length - 2; i++) {
56
+ if (t[i].type !== 'blockquote_open' || t[i + 1].type !== 'paragraph_open' || t[i + 2].type !== 'inline')
57
+ continue;
58
+ const m = /^\[!(note|tip|important|warning|caution)\][ \t]*(?:\n|$)/i.exec(t[i + 2].content);
59
+ if (!m)
60
+ continue;
61
+ const name = m[1].toLowerCase();
62
+ t[i + 2].content = t[i + 2].content.slice(m[0].length);
63
+ let depth = 0;
64
+ for (let j = i; j < t.length; j++) {
65
+ if (t[j].type === 'blockquote_open')
66
+ depth++;
67
+ else if (t[j].type === 'blockquote_close' && --depth === 0) {
68
+ Object.assign(t[j], { type: 'cl_container_close', tag: 'div', info: ALERTS[name] });
69
+ break;
70
+ }
71
+ }
72
+ Object.assign(t[i], { type: 'cl_container_open', tag: 'div', info: ALERTS[name], meta: { title: titles[name] } });
73
+ if (!t[i + 2].content.trim())
74
+ t.splice(i + 1, 3);
75
+ }
76
+ });
77
+ const plain = (src) => (md.parseInline(src, {})[0]?.children ?? []).filter((c) => c.type === 'text' || c.type === 'code_inline').map((c) => c.content).join('');
78
+ md.core.ruler.after('cl_alerts', 'cl_quiz', (state) => {
79
+ const t = state.tokens;
80
+ const env = state.env;
81
+ for (let i = 0; i < t.length; i++) {
82
+ if (t[i].type !== 'cl_container_open' || t[i].info !== 'quiz')
83
+ continue;
84
+ if (!env.quizAllowed)
85
+ throw new Error(`${env.file}: ::: quiz is for lessons (frontmatter steps: true); markdown({ quizzes: 'everywhere' }) allows it on any page`);
86
+ let close = i + 1;
87
+ for (let depth = 1; close < t.length; close++) {
88
+ if (t[close].type === 'cl_container_open')
89
+ depth++;
90
+ else if (t[close].type === 'cl_container_close' && --depth === 0)
91
+ break;
92
+ }
93
+ const start = t.findIndex((tok, j) => j > i && j < close && tok.type === 'bullet_list_open');
94
+ if (start === -1)
95
+ throw new Error(`${env.file}: a quiz needs exactly one right answer (- [x]) in its list of options`);
96
+ let end = start;
97
+ for (let depth = 0; end < t.length; end++) {
98
+ if (t[end].type === 'bullet_list_open')
99
+ depth++;
100
+ else if (t[end].type === 'bullet_list_close' && --depth === 0)
101
+ break;
102
+ }
103
+ const options = [];
104
+ let answer = -1;
105
+ let right = 0;
106
+ for (let j = start; j < end; j++) {
107
+ if (t[j].type !== 'inline' || t[j].level !== t[start].level + 3)
108
+ continue;
109
+ const m = /^\[([ xX])\]\s+/.exec(t[j].content);
110
+ if (m && m[1] !== ' ') {
111
+ answer = options.length;
112
+ right++;
113
+ }
114
+ options.push(plain(t[j].content.replace(/^\[[ xX]\]\s+/, '')));
115
+ }
116
+ if (right !== 1)
117
+ throw new Error(`${env.file}: a quiz needs exactly one right answer (- [x]) in its list of options`);
118
+ const question = t[i].meta.title;
119
+ t[i].meta = { title: plain(question), name: `quiz-${env.quizzes++}`, options, answer, html: md.renderInline(question) };
120
+ const token = new state.Token('cl_quiz', '', 0);
121
+ token.meta = t[i].meta;
122
+ t.splice(start, end - start + 1, token);
123
+ }
124
+ });
125
+ md.renderer.rules.cl_container_open = (tokens, i, _o, env) => {
126
+ const tags = env.tags;
127
+ const { info: type, meta } = tokens[i];
128
+ const { title } = meta;
129
+ if (type === 'details')
130
+ return `<details class="custom-block details"><summary>${escapeHtml(title)}</summary>\n`;
131
+ if (type === 'quiz') {
132
+ const q = meta;
133
+ if (!options.quiz)
134
+ return `<div class="quiz" data-quiz="${q.name}">`;
135
+ tags.push(`<${options.quiz.tag} [name]="${quote(q.name)}" [question]="${escapeHtml(quote(title))}" [options]="[${q.options.map((o) => escapeHtml(quote(o))).join(', ')}]" [answer]="${q.answer}">`);
136
+ return `<!--cl-tag-${tags.length - 1}-->`;
137
+ }
138
+ if (options.container) {
139
+ tags.push(`<${options.container.tag} [type]="'${type}'">@slot('title') {${inert(title)}}`);
140
+ return `<!--cl-tag-${tags.length - 1}-->\n`;
141
+ }
142
+ return `<div class="custom-block ${type}"><p class="custom-block-title">${escapeHtml(title)}</p>\n`;
143
+ };
144
+ md.renderer.rules.cl_quiz = (tokens, i) => {
145
+ if (options.quiz)
146
+ return '';
147
+ const { name, html, options: choices, answer } = tokens[i].meta;
148
+ const labels = choices.map((text, n) => `<label><input type="radio" name="${name}" value="${n}"> ${escapeHtml(text)}</label>`).join('');
149
+ return `<p class="quiz-question" id="${name}-q">${html}</p><div class="quiz-options" role="radiogroup" aria-labelledby="${name}-q">${labels}</div>`
150
+ + `<details class="quiz-answer"><summary>Show the answer</summary><p class="quiz-correct">Answer: ${escapeHtml(choices[answer])}</p>\n`;
151
+ };
152
+ md.renderer.rules.cl_group_open = (_t, _i, _o, env) => {
153
+ const e = env;
154
+ e.group = { id: e.groups++, n: 0 };
155
+ return '<div class="code-group">';
156
+ };
157
+ md.renderer.rules.cl_group_close = (_t, _i, _o, env) => {
158
+ delete env.group;
159
+ return '</div>\n';
160
+ };
161
+ md.renderer.rules.fence = (tokens, i, _o, env) => {
162
+ const e = env;
163
+ const info = tokens[i].info.trim();
164
+ const lang = /^[^\s{[:]+/.exec(info)?.[0] ?? 'text';
165
+ const title = /\[([^\]]+)\]/.exec(info)?.[1];
166
+ const lineNumbers = /(^|\s):line-numbers\b/.test(info);
167
+ const code = tokens[i].content;
168
+ let out = '';
169
+ if (e.group) {
170
+ const id = `cl-group-${e.group.id}-${e.group.n}`;
171
+ out += `<input type="radio" name="cl-group-${e.group.id}" id="${id}"${e.group.n === 0 ? ' checked' : ''}><label for="${id}">${escapeHtml(title ?? lang)}</label>`;
172
+ e.group.n++;
173
+ }
174
+ out += `<div class="code-block language-${escapeHtml(lang)}${lineNumbers ? ' line-numbers' : ''}">`;
175
+ if (title && !e.group)
176
+ out += `<p class="code-title">${escapeHtml(title)}</p>`;
177
+ out += `<span class="lang">${escapeHtml(lang)}</span>${highlight(code.replace(/\n$/, ''), lang, info.slice(lang.length))}`;
178
+ if (lineNumbers) {
179
+ const count = code.replace(/\n$/, '').split('\n').length;
180
+ out += `<div class="line-numbers-column" aria-hidden="true">${Array.from({ length: count }, (_, n) => `<span>${n + 1}</span>`).join('')}</div>`;
181
+ }
182
+ if (options.copy) {
183
+ e.tags.push(`<${options.copy.tag} attach="interaction" />`);
184
+ out += `<!--cl-tag-${e.tags.length - 1}-->`;
185
+ }
186
+ return `${out}</div>${e.group ? '' : '\n'}`;
187
+ };
188
+ md.renderer.rules.cl_container_close = (tokens, i, _o, env) => {
189
+ const tags = env.tags;
190
+ if (tokens[i].info === 'details')
191
+ return '</details>\n';
192
+ if (tokens[i].info === 'quiz') {
193
+ if (!options.quiz)
194
+ return '</details></div>\n';
195
+ tags.push(`</${options.quiz.tag}>`);
196
+ return `<!--cl-tag-${tags.length - 1}-->\n`;
197
+ }
198
+ if (options.container) {
199
+ tags.push(`</${options.container.tag}>`);
200
+ return `<!--cl-tag-${tags.length - 1}-->\n`;
201
+ }
202
+ return '</div>\n';
203
+ };
204
+ md.core.ruler.push('cl_page_links', (state) => {
205
+ const { file, root } = state.env;
206
+ if (!file || !root)
207
+ return;
208
+ const pages = resolve(root, 'src/pages') + sep;
209
+ for (const block of state.tokens) {
210
+ for (const token of block.children ?? []) {
211
+ if (token.type !== 'link_open')
212
+ continue;
213
+ const m = /^(?![a-z][\w+.-]*:|\/|#)([^?#]+\.(?:md|tscl))([?#].*)?$/i.exec(String(token.attrGet('href') ?? ''));
214
+ if (!m)
215
+ continue;
216
+ const target = resolve(dirname(file), m[1]);
217
+ if (!target.startsWith(pages))
218
+ continue;
219
+ const route = `/${relative(pages, target).split(sep).join('/').replace(/\.(md|tscl)$/i, '').replace(/(^|\/)index$/, '')}`;
220
+ token.attrSet('href', (route.length > 1 ? route.replace(/\/$/, '') : route) + (m[2] ?? ''));
221
+ }
222
+ }
223
+ });
224
+ md.core.ruler.push('cl_anchors', (state) => {
225
+ const used = new Set();
226
+ state.tokens.forEach((token, i) => {
227
+ if (token.type !== 'heading_open')
228
+ return;
229
+ const inline = state.tokens[i + 1];
230
+ const text = (inline.children ?? []).filter((t) => t.type === 'text' || t.type === 'code_inline').map((t) => t.content).join('');
231
+ const base = slugify(text);
232
+ let id = base;
233
+ for (let n = 1; used.has(id); n++)
234
+ id = `${base}-${n}`;
235
+ used.add(id);
236
+ token.attrSet('id', id);
237
+ token.attrSet('tabindex', '-1');
238
+ if (token.tag === 'h1')
239
+ return;
240
+ const anchor = new state.Token('html_inline', '', 0);
241
+ anchor.content = ` <a class="header-anchor" href="#${id}" aria-label="Permalink to ${escapeHtml(text)}">#</a>`;
242
+ inline.children = [...(inline.children ?? []), anchor];
243
+ });
244
+ });
245
+ return md;
246
+ }
247
+ function pageHead(data, title) {
248
+ const tags = [];
249
+ if (data.titleTemplate === false && title !== undefined)
250
+ tags.push(`<title>${escapeHtml(title)}</title>`);
251
+ if (data.sitemap === false)
252
+ tags.push('<meta name="sitemap" content="false">');
253
+ if (typeof data.image === 'string')
254
+ tags.push(`<meta property="og:image" content="${escapeHtml(data.image)}">`);
255
+ const raws = [];
256
+ for (const entry of Array.isArray(data.head) ? data.head : []) {
257
+ const [tag, attrs = {}, content] = entry;
258
+ if (typeof tag !== 'string' || !/^[a-z]+$/.test(tag))
259
+ continue;
260
+ const a = staticHtml(Object.entries(attrs).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escapeHtml(String(v))}"`)).join(''));
261
+ if (tag === 'script') {
262
+ const raw = content ?? '';
263
+ raws.push(attrs.type === 'application/ld+json' ? `<script${a}>${raw.replace(/\{\{/g, '{\\u007b')}</script>` : `<script inline${a}>${raw}</script>`);
264
+ continue;
265
+ }
266
+ tags.push(['meta', 'link', 'base'].includes(tag) && content === undefined ? `<${tag}${a}>` : `<${tag}${a}>${escapeHtml(content ?? '')}</${tag}>`);
267
+ }
268
+ const ld = [data.jsonLd ?? []].flat().map((value) => `<script type="application/ld+json">${JSON.stringify(value)
269
+ .replace(/[<>&\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`).replace(/\{\{/g, '{\\u007b')}</script>`);
270
+ return tags.length || raws.length || ld.length ? `<cl-head>${staticHtml(tags.join(''))}${raws.join('')}${ld.join('')}</cl-head>` : '';
271
+ }
272
+ function staticHtml(html) {
273
+ return html.replace(/\{\{/g, '&#123;&#123;').replace(/@/g, '&#64;');
274
+ }
275
+ function protectTags(body, components, saved) {
276
+ const code = /(?:^|\n)[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n[ \t]*\1[`~]*[ \t\r]*(?=\n|$)|$)|(`+)[\s\S]*?[^`]\2(?!`)/;
277
+ const tag = /<\/?([A-Za-z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/;
278
+ const out = body.replace(new RegExp(`${code.source}|${tag.source}`, 'g'), (match, _fence, _ticks, name, attrs) => {
279
+ if (name === undefined)
280
+ return match;
281
+ const tag = match;
282
+ if (!components.has(name) && !/\s[[(]/.test(attrs))
283
+ return tag;
284
+ saved.push(tag);
285
+ return `<!--cl-tag-${saved.length - 1}-->`;
286
+ });
287
+ return { body: out, restore: (html) => html.replace(/<!--cl-tag-(\d+)-->/g, (_, i) => saved[Number(i)]) };
288
+ }
289
+ export default function markdown(options = {}) {
290
+ const md = renderer(options);
291
+ return {
292
+ extension: '.md',
293
+ toTscl(code, file, context) {
294
+ const { route } = context;
295
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(code);
296
+ const data = (front ? parseYaml(front[1]) : null) ?? {};
297
+ let body = expand(front ? code.slice(front[0].length) : code, file, context);
298
+ const imports = [];
299
+ for (;;) {
300
+ const line = /^[ \t]*(@import\b[^\n]*)\n|^[ \t]*\n/.exec(body);
301
+ if (!line)
302
+ break;
303
+ if (line[1])
304
+ imports.push(line[1].trim());
305
+ body = body.slice(line[0].length);
306
+ }
307
+ if (options.container && !imports.some((line) => new RegExp(`^@import\\s+${options.container.tag}\\s+from`).test(line))) {
308
+ imports.unshift(`@import ${options.container.tag} from '${options.container.from}'`);
309
+ }
310
+ const components = new Set(imports.map((line) => /^@import\s+([A-Za-z_$][\w-]*)\s+from/.exec(line)?.[1]).filter((n) => !!n));
311
+ if (components.has('cl-layout'))
312
+ throw new Error(`${file}: cl-layout is reserved for the page's layout; import the component under another name`);
313
+ if (options.quiz && /^\s*:{3,}\s*quiz\b/m.test(body) && !imports.some((line) => new RegExp(`^@import\\s+${options.quiz.tag}\\s+from`).test(line))) {
314
+ imports.unshift(`@import ${options.quiz.tag} from '${options.quiz.from}'`);
315
+ }
316
+ if (options.copy && !imports.some((line) => new RegExp(`^@import\\s+${options.copy.tag}\\s+from`).test(line))) {
317
+ imports.unshift(`@import ${options.copy.tag} from '${options.copy.from}'`);
318
+ }
319
+ const env = { tags: [], groups: 0, file, root: context.root, quizzes: 0, quizAllowed: data.steps === true || options.quizzes === 'everywhere' };
320
+ const tags = protectTags(body, components, env.tags);
321
+ let tokens = md.parse(tags.body, env);
322
+ if (data.steps === true && tokens.length) {
323
+ const Token = tokens[0].constructor;
324
+ const html = (content) => Object.assign(new Token('html_block', '', 0), { content });
325
+ let open = false;
326
+ tokens = tokens.flatMap((t) => {
327
+ if (t.type !== 'heading_open' || t.tag !== 'h2' || t.level !== 0)
328
+ return [t];
329
+ const before = open ? [html('</section>\n')] : [];
330
+ open = true;
331
+ return [...before, html(`<section class="step" aria-labelledby="${escapeHtml(String(t.attrGet('id') ?? ''))}">\n`), t];
332
+ });
333
+ if (open)
334
+ tokens.push(html('</section>\n'));
335
+ }
336
+ const headings = tokens.flatMap((t, i) => {
337
+ if (t.type !== 'heading_open' || (t.tag !== 'h2' && t.tag !== 'h3') || t.level !== 0)
338
+ return [];
339
+ const text = (tokens[i + 1].children ?? []).filter((c) => c.type === 'text' || c.type === 'code_inline').map((c) => c.content).join('');
340
+ return [{ id: String(t.attrGet('id') ?? ''), text, level: t.tag === 'h2' ? 2 : 3 }];
341
+ });
342
+ const h1 = tokens.findIndex((t) => t.type === 'heading_open' && t.tag === 'h1');
343
+ const firstHeading = h1 === -1 ? undefined : (tokens[h1 + 1].children ?? []).filter((t) => t.type === 'text' || t.type === 'code_inline').map((t) => t.content).join('');
344
+ const title = typeof data.title === 'string' ? data.title : firstHeading;
345
+ const html = pageHead(data, title) + tags.restore(staticHtml(md.renderer.render(tokens, md.options, env)));
346
+ const layout = data.layout === false ? undefined : (typeof data.layout === 'string' ? data.layout : options.layout);
347
+ if (!layout)
348
+ return [...imports, html].join('\n');
349
+ const props = [
350
+ title !== undefined ? `[title]="${quote(title)}"` : '',
351
+ typeof data.description === 'string' ? `[description]="${quote(data.description)}"` : '',
352
+ `[path]="${quote(route)}"`,
353
+ headings.length ? `[headings]="[${headings.map((h) => `{ id: ${quote(h.id)}, text: ${quote(h.text)}, level: ${h.level} }`).join(', ')}]"` : '',
354
+ ].filter(Boolean).join(' ');
355
+ return [`@import cl-layout from '${layout}'`, ...imports, `<cl-layout ${props}>${html}</cl-layout>`, ''].join('\n');
356
+ },
357
+ };
358
+ }
@@ -0,0 +1,3 @@
1
+ import type { SourceContext } from 'clarusjs/vite';
2
+ /** Expand snippets and includes in `text` (from `file`; `stack` is the include chain, page first). */
3
+ export declare function expand(text: string, file: string, ctx: SourceContext, stack?: string[]): string;
@@ -0,0 +1,89 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, relative, resolve, sep } from 'node:path';
3
+ const SNIPPET = /^[ \t]*<<<[ \t]+(\S+?)(?:#([\w-]+))?(\{[^}]*\})?(?:[ \t]+\[([^\]]+)\])?[ \t]*$/;
4
+ const INCLUDE = /^[ \t]*<!--[ \t]*@include:[ \t]*(\S+?)(?:#([\w-]+))?[ \t]*-->[ \t]*$/;
5
+ const posix = (p) => p.split(sep).join('/');
6
+ const MARKER = /^[ \t]*(?:\/\/|\/\*|<!--|#|--|;)?[ \t]*#(end)?region(?:[ \t]+([A-Za-z0-9_][\w-]*))?[ \t]*(?:\*\/|-->)?[ \t]*$/;
7
+ function region(text, name) {
8
+ let lines = text.replace(/\n$/, '').split('\n');
9
+ if (name) {
10
+ const start = lines.findIndex((l) => { const m = MARKER.exec(l); return !!m && !m[1] && m[2] === name; });
11
+ if (start === -1)
12
+ return undefined;
13
+ let depth = 0;
14
+ let end = -1;
15
+ for (let i = start + 1; i < lines.length && end === -1; i++) {
16
+ const m = MARKER.exec(lines[i]);
17
+ if (!m)
18
+ continue;
19
+ if (!m[1])
20
+ depth++;
21
+ else if (m[2] === name || (!m[2] && depth === 0))
22
+ end = i;
23
+ else
24
+ depth--;
25
+ }
26
+ lines = lines.slice(start + 1, end === -1 ? undefined : end);
27
+ }
28
+ lines = lines.filter((l) => !MARKER.test(l));
29
+ const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => /^[ \t]*/.exec(l)[0].length));
30
+ return lines.map((l) => l.slice(Number.isFinite(indent) ? indent : 0)).join('\n');
31
+ }
32
+ function outsideFences(text, fn) {
33
+ let fence = null;
34
+ return text.split('\n').map((line) => {
35
+ if (fence) {
36
+ const close = /^([ \t]*)(`{3,}|~{3,})[ \t\r]*$/.exec(line);
37
+ if (close && close[2][0] === fence.marker[0] && close[2].length >= fence.marker.length && close[1].length <= fence.indent + 3)
38
+ fence = null;
39
+ return line;
40
+ }
41
+ const open = /^([ \t]*(?:(?:[-*+]|\d+[.)])[ \t]+)*)(`{3,}|~{3,})/.exec(line);
42
+ if (open) {
43
+ fence = { marker: open[2], indent: open[1].length };
44
+ return line;
45
+ }
46
+ return fn(line);
47
+ }).join('\n');
48
+ }
49
+ export function expand(text, file, ctx, stack = [file]) {
50
+ if (!/<<<|@include:/.test(text))
51
+ return text;
52
+ const page = posix(relative(ctx.root, stack[0]));
53
+ const fail = (what) => { throw new Error(`${page}: ${what}`); };
54
+ const locate = (spec, directive) => {
55
+ const path = spec.startsWith('@/') ? resolve(ctx.root, spec.slice(2)) : resolve(dirname(file), spec);
56
+ if (path !== ctx.root && !path.startsWith(ctx.root + sep))
57
+ fail(`${directive} ${spec}: outside the project`);
58
+ if (!existsSync(path))
59
+ fail(`${directive} ${spec}: file not found`);
60
+ ctx.addDependency(path);
61
+ return path;
62
+ };
63
+ return outsideFences(text, (line) => {
64
+ let m = SNIPPET.exec(line);
65
+ if (m) {
66
+ const [, spec, name, lines, title] = m;
67
+ const path = locate(spec, '<<<');
68
+ const code = region(readFileSync(path, 'utf8'), name) ?? fail(`<<< ${spec}: region "${name}" not found`);
69
+ const ticks = '`'.repeat(Math.max(3, ...(code.match(/`{3,}/g) ?? []).map((t) => t.length + 1)));
70
+ const lang = /\.([\w-]+)$/.exec(path)?.[1] ?? 'text';
71
+ return [`${ticks}${lang}${lines ? ` ${lines}` : ''}${title ? ` [${title}]` : ''}`, code, ticks].join('\n');
72
+ }
73
+ m = INCLUDE.exec(line);
74
+ if (m) {
75
+ const [, spec, name] = m;
76
+ const path = locate(spec, '@include:');
77
+ if (stack.includes(path))
78
+ fail(`include cycle: ${[...stack, path].map((p) => posix(relative(ctx.root, p))).join(' → ')}`);
79
+ let included = readFileSync(path, 'utf8').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
80
+ included = region(included, name) ?? fail(`@include: ${spec}: region "${name}" not found`);
81
+ const rebase = (href) => (/^([a-z][\w+.-]*:|\/|#)/i.test(href) ? href : posix(relative(dirname(stack[0]), resolve(dirname(path), href))));
82
+ included = outsideFences(included, (l) => l
83
+ .replace(/(\]\()([^)\s]+)/g, (_, open, href) => open + rebase(href))
84
+ .replace(/^([ \t]{0,3}\[[^\]]+\]:[ \t]*)(\S+)/, (_, def, href) => def + rebase(href)));
85
+ return expand(included, path, ctx, [...stack, path]);
86
+ }
87
+ return line;
88
+ });
89
+ }
package/package.json CHANGED
@@ -1,11 +1,63 @@
1
1
  {
2
2
  "name": "@clarusjs/content",
3
- "version": "0.0.1",
4
- "description": "Reserved for @clarusjs/content: Markdown pages for clarusjs.",
3
+ "version": "0.2.0",
4
+ "description": "Markdown pages for clarusjs: frontmatter, layouts, components in Markdown, rendered to static HTML at build time.",
5
+ "type": "module",
5
6
  "license": "MIT",
7
+ "files": [
8
+ "dist",
9
+ "LICENSE",
10
+ "README.md"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "peerDependencies": {
22
+ "clarusjs": "^0.8.0"
23
+ },
24
+ "engines": {
25
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
26
+ },
6
27
  "repository": {
7
28
  "type": "git",
8
29
  "url": "git+https://github.com/forinda/clarusjs.git",
9
30
  "directory": "packages/content"
31
+ },
32
+ "keywords": [
33
+ "clarusjs",
34
+ "markdown",
35
+ "content",
36
+ "docs",
37
+ "ssg",
38
+ "vite"
39
+ ],
40
+ "homepage": "https://clarusjs.com",
41
+ "bugs": {
42
+ "url": "https://github.com/forinda/clarusjs/issues"
43
+ },
44
+ "dependencies": {
45
+ "@shikijs/transformers": "^4.6.0",
46
+ "markdown-it": "^15.0.3",
47
+ "shiki": "^4.6.0",
48
+ "yaml": "^2.9.1"
49
+ },
50
+ "devDependencies": {
51
+ "@types/markdown-it": "^14.2.0",
52
+ "@types/node": "^26.6.6",
53
+ "clarusjs": "^0.8.0",
54
+ "typescript": "^7.0.2",
55
+ "vite": "^8.3.8",
56
+ "vitest": "^5.1.1"
57
+ },
58
+ "scripts": {
59
+ "build": "node ../../scripts/build-package.mjs",
60
+ "test": "vitest run",
61
+ "typecheck": "tsc --noEmit"
10
62
  }
11
- }
63
+ }