@clarusjs/content 0.0.0-stage → 0.1.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
- # Temporary Holding Version
1
+ # @clarusjs/content
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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,47 @@
1
+ // Build-time code highlighting with Shiki. Synchronous (the JavaScript regex engine, grammars imported up front),
2
+ // because a page source turns Markdown into .tscl synchronously. Nothing here reaches the browser.
3
+ import { createHighlighterCoreSync } from 'shiki/core';
4
+ import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
5
+ import { transformerMetaHighlight, transformerNotationDiff, transformerNotationErrorLevel, transformerNotationFocus, transformerNotationHighlight, } from '@shikijs/transformers';
6
+ import angularHtml from 'shiki/langs/angular-html.mjs';
7
+ import bash from 'shiki/langs/bash.mjs';
8
+ import css from 'shiki/langs/css.mjs';
9
+ import diff from 'shiki/langs/diff.mjs';
10
+ import html from 'shiki/langs/html.mjs';
11
+ import javascript from 'shiki/langs/javascript.mjs';
12
+ import json from 'shiki/langs/json.mjs';
13
+ import markdown from 'shiki/langs/markdown.mjs';
14
+ import toml from 'shiki/langs/toml.mjs';
15
+ import tsx from 'shiki/langs/tsx.mjs';
16
+ import typescript from 'shiki/langs/typescript.mjs';
17
+ import yaml from 'shiki/langs/yaml.mjs';
18
+ import githubDark from 'shiki/themes/github-dark.mjs';
19
+ import githubLight from 'shiki/themes/github-light.mjs';
20
+ // .tscl templates read like Angular's: {{ }}, [prop], (event) and @if/@for, so they borrow its grammar.
21
+ const ALIASES = { tscl: 'angular-html', ts: 'typescript', js: 'javascript', sh: 'bash', shell: 'bash', zsh: 'bash', md: 'markdown', yml: 'yaml' };
22
+ let highlighter;
23
+ const get = () => (highlighter ??= createHighlighterCoreSync({
24
+ themes: [githubLight, githubDark],
25
+ langs: [angularHtml, bash, css, diff, html, javascript, json, markdown, toml, tsx, typescript, yaml],
26
+ engine: createJavaScriptRegexEngine(),
27
+ }));
28
+ const transformers = [
29
+ transformerNotationDiff(),
30
+ transformerNotationFocus(),
31
+ transformerNotationHighlight(),
32
+ transformerNotationErrorLevel(),
33
+ transformerMetaHighlight(),
34
+ ];
35
+ /** Highlighted <pre> for `code` in `lang` (unknown languages are plain text); `meta` carries `{1,3-5}`. */
36
+ export function highlight(code, lang, meta) {
37
+ const hl = get();
38
+ const id = ALIASES[lang] ?? lang;
39
+ const known = hl.getLoadedLanguages().includes(id);
40
+ return hl.codeToHtml(code, {
41
+ lang: known ? id : 'text',
42
+ themes: { light: 'github-light', dark: 'github-dark' },
43
+ defaultColor: false, // colours only as --shiki-light/--shiki-dark: the page's theme picks one with CSS
44
+ meta: { __raw: meta },
45
+ transformers,
46
+ });
47
+ }
@@ -0,0 +1,23 @@
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
+ /** 'Hello, World!' → 'hello-world'. Shared by heading ids and (later) link checking. */
22
+ export declare function slugify(text: string): string;
23
+ export default function markdown(options?: MarkdownOptions): Source;
package/dist/index.js ADDED
@@ -0,0 +1,269 @@
1
+ // Markdown pages for clarusjs. A page source: each .md file under src/pages becomes .tscl text (its HTML inside
2
+ // the layout), then compiles like any page. Build-time only: nothing here reaches the browser.
3
+ import { dirname, relative, resolve, sep } from 'node:path';
4
+ import MarkdownIt from 'markdown-it';
5
+ import { parse as parseYaml } from 'yaml';
6
+ import { highlight } from './highlight.js';
7
+ import { expand } from './snippets.js';
8
+ const TYPES = ['tip', 'info', 'warning', 'danger', 'details', 'code-group'];
9
+ const TITLES = { tip: 'Tip', info: 'Info', warning: 'Warning', danger: 'Danger', details: 'Details', note: 'Note', important: 'Important', caution: 'Caution' };
10
+ // GitHub alerts → container type (the alert's name stays its title).
11
+ const ALERTS = { note: 'info', tip: 'tip', important: 'info', warning: 'warning', caution: 'danger' };
12
+ /** Text safe inside generated .tscl markup: HTML escaped, and nothing a template would read ({ } @). */
13
+ const inert = (s) => escapeHtml(s).replace(/\{/g, '&#123;').replace(/\}/g, '&#125;').replace(/@/g, '&#64;');
14
+ /** 'Hello, World!' → 'hello-world'. Shared by heading ids and (later) link checking. */
15
+ export function slugify(text) {
16
+ return text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\w\s-]/g, '').trim().replace(/[\s_-]+/g, '-') || 'section';
17
+ }
18
+ /** A JavaScript string literal that is safe inside a double-quoted .tscl attribute. */
19
+ const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\u0022').replace(/\n/g, '\\n')}'`;
20
+ const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
21
+ function renderer(options) {
22
+ const md = new MarkdownIt({ html: true, linkify: true });
23
+ const titles = { ...TITLES, ...options.titles };
24
+ // ::: type [title] … ::: (a longer fence, such as ::::, nests around a shorter one).
25
+ md.block.ruler.before('fence', 'cl_container', (state, startLine, endLine, silent) => {
26
+ const line = state.src.slice(state.bMarks[startLine] + state.tShift[startLine], state.eMarks[startLine]).trim();
27
+ const m = /^(:{3,})\s*([a-z-]+)(?:\s+(.*))?$/.exec(line);
28
+ if (!m || !TYPES.includes(m[2]))
29
+ return false;
30
+ if (silent)
31
+ return true;
32
+ // The closing ::: is the first one outside fenced code (an example may show ::: itself).
33
+ let close = startLine + 1;
34
+ let fence = '';
35
+ for (; close < endLine; close++) {
36
+ const text = state.src.slice(state.bMarks[close] + state.tShift[close], state.eMarks[close]).trim();
37
+ const marker = /^(`{3,}|~{3,})/.exec(text)?.[1];
38
+ if (fence) {
39
+ if (marker && marker[0] === fence[0] && marker.length >= fence.length && text === marker)
40
+ fence = '';
41
+ continue;
42
+ }
43
+ if (marker) {
44
+ fence = marker;
45
+ continue;
46
+ }
47
+ if (text === m[1])
48
+ break;
49
+ }
50
+ const open = state.push(m[2] === 'code-group' ? 'cl_group_open' : 'cl_container_open', 'div', 1);
51
+ open.info = m[2];
52
+ open.meta = { title: m[3]?.trim() || titles[m[2]] };
53
+ const oldMax = state.lineMax;
54
+ state.lineMax = close;
55
+ state.md.block.tokenize(state, startLine + 1, close);
56
+ state.lineMax = oldMax;
57
+ state.push(m[2] === 'code-group' ? 'cl_group_close' : 'cl_container_close', 'div', -1).info = m[2];
58
+ state.line = Math.min(close + 1, endLine);
59
+ return true;
60
+ });
61
+ // > [!NOTE] … becomes the same block as ::: info, titled with the alert's name.
62
+ md.core.ruler.after('block', 'cl_alerts', (state) => {
63
+ const t = state.tokens;
64
+ for (let i = 0; i < t.length - 2; i++) {
65
+ if (t[i].type !== 'blockquote_open' || t[i + 1].type !== 'paragraph_open' || t[i + 2].type !== 'inline')
66
+ continue;
67
+ const m = /^\[!(note|tip|important|warning|caution)\][ \t]*(?:\n|$)/i.exec(t[i + 2].content);
68
+ if (!m)
69
+ continue;
70
+ const name = m[1].toLowerCase();
71
+ t[i + 2].content = t[i + 2].content.slice(m[0].length);
72
+ let depth = 0;
73
+ for (let j = i; j < t.length; j++) {
74
+ if (t[j].type === 'blockquote_open')
75
+ depth++;
76
+ else if (t[j].type === 'blockquote_close' && --depth === 0) {
77
+ Object.assign(t[j], { type: 'cl_container_close', tag: 'div', info: ALERTS[name] });
78
+ break;
79
+ }
80
+ }
81
+ Object.assign(t[i], { type: 'cl_container_open', tag: 'div', info: ALERTS[name], meta: { title: titles[name] } });
82
+ // The marker's own paragraph is gone if nothing else was on its line.
83
+ if (!t[i + 2].content.trim())
84
+ t.splice(i + 1, 3);
85
+ }
86
+ });
87
+ // env carries the page's placeholder list (see protectTags).
88
+ md.renderer.rules.cl_container_open = (tokens, i, _o, env) => {
89
+ const tags = env.tags;
90
+ const { info: type, meta } = tokens[i];
91
+ const { title } = meta;
92
+ if (type === 'details')
93
+ return `<details class="custom-block details"><summary>${escapeHtml(title)}</summary>\n`;
94
+ if (options.container) {
95
+ tags.push(`<${options.container.tag} [type]="'${type}'">@slot('title') {${inert(title)}}`);
96
+ return `<!--cl-tag-${tags.length - 1}-->\n`;
97
+ }
98
+ return `<div class="custom-block ${type}"><p class="custom-block-title">${escapeHtml(title)}</p>\n`;
99
+ };
100
+ // ::: code-group: radio inputs and labels, each followed by its block. CSS shows the checked one's block, so the
101
+ // tabs work without JavaScript.
102
+ md.renderer.rules.cl_group_open = (_t, _i, _o, env) => {
103
+ const e = env;
104
+ e.group = { id: e.groups++, n: 0 };
105
+ return '<div class="code-group">';
106
+ };
107
+ md.renderer.rules.cl_group_close = (_t, _i, _o, env) => {
108
+ delete env.group;
109
+ return '</div>\n';
110
+ };
111
+ // ```lang {1,3} [title] :line-numbers
112
+ md.renderer.rules.fence = (tokens, i, _o, env) => {
113
+ const e = env;
114
+ const info = tokens[i].info.trim();
115
+ const lang = /^[^\s{[:]+/.exec(info)?.[0] ?? 'text';
116
+ const title = /\[([^\]]+)\]/.exec(info)?.[1];
117
+ const lineNumbers = /(^|\s):line-numbers\b/.test(info);
118
+ const code = tokens[i].content;
119
+ let out = '';
120
+ if (e.group) {
121
+ const id = `cl-group-${e.group.id}-${e.group.n}`;
122
+ out += `<input type="radio" name="cl-group-${e.group.id}" id="${id}"${e.group.n === 0 ? ' checked' : ''}><label for="${id}">${escapeHtml(title ?? lang)}</label>`;
123
+ e.group.n++;
124
+ }
125
+ out += `<div class="code-block language-${escapeHtml(lang)}${lineNumbers ? ' line-numbers' : ''}">`;
126
+ if (title && !e.group)
127
+ out += `<p class="code-title">${escapeHtml(title)}</p>`;
128
+ out += `<span class="lang">${escapeHtml(lang)}</span>${highlight(code.replace(/\n$/, ''), lang, info.slice(lang.length))}`;
129
+ if (lineNumbers) {
130
+ const count = code.replace(/\n$/, '').split('\n').length;
131
+ out += `<div class="line-numbers-column" aria-hidden="true">${Array.from({ length: count }, (_, n) => `<span>${n + 1}</span>`).join('')}</div>`;
132
+ }
133
+ if (options.copy) {
134
+ e.tags.push(`<${options.copy.tag} attach="interaction" />`);
135
+ out += `<!--cl-tag-${e.tags.length - 1}-->`;
136
+ }
137
+ return `${out}</div>${e.group ? '' : '\n'}`;
138
+ };
139
+ md.renderer.rules.cl_container_close = (tokens, i, _o, env) => {
140
+ const tags = env.tags;
141
+ if (tokens[i].info === 'details')
142
+ return '</details>\n';
143
+ if (options.container) {
144
+ tags.push(`</${options.container.tag}>`);
145
+ return `<!--cl-tag-${tags.length - 1}-->\n`;
146
+ }
147
+ return '</div>\n';
148
+ };
149
+ // [text](./other.md): relative links to page source files become their routes, so authors link by file.
150
+ md.core.ruler.push('cl_page_links', (state) => {
151
+ const { file, root } = state.env;
152
+ if (!file || !root)
153
+ return;
154
+ const pages = resolve(root, 'src/pages') + sep;
155
+ for (const block of state.tokens) {
156
+ for (const token of block.children ?? []) {
157
+ if (token.type !== 'link_open')
158
+ continue;
159
+ const m = /^(?![a-z][\w+.-]*:|\/|#)([^?#]+\.(?:md|tscl))([?#].*)?$/i.exec(String(token.attrGet('href') ?? ''));
160
+ if (!m)
161
+ continue;
162
+ const target = resolve(dirname(file), m[1]);
163
+ if (!target.startsWith(pages))
164
+ continue; // not a page: left for the link checker
165
+ const route = `/${relative(pages, target).split(sep).join('/').replace(/\.(md|tscl)$/i, '').replace(/(^|\/)index$/, '')}`;
166
+ token.attrSet('href', (route.length > 1 ? route.replace(/\/$/, '') : route) + (m[2] ?? ''));
167
+ }
168
+ }
169
+ });
170
+ // Headings get an id and an anchor link; ids are unique within the page.
171
+ md.core.ruler.push('cl_anchors', (state) => {
172
+ const used = new Set();
173
+ state.tokens.forEach((token, i) => {
174
+ if (token.type !== 'heading_open')
175
+ return;
176
+ const inline = state.tokens[i + 1];
177
+ const text = (inline.children ?? []).filter((t) => t.type === 'text' || t.type === 'code_inline').map((t) => t.content).join('');
178
+ const base = slugify(text);
179
+ let id = base;
180
+ for (let n = 1; used.has(id); n++)
181
+ id = `${base}-${n}`;
182
+ used.add(id);
183
+ token.attrSet('id', id);
184
+ token.attrSet('tabindex', '-1');
185
+ // The page title keeps its id, but no anchor link: it would only repeat the heading for screen readers.
186
+ if (token.tag === 'h1')
187
+ return;
188
+ const anchor = new state.Token('html_inline', '', 0);
189
+ anchor.content = ` <a class="header-anchor" href="#${id}" aria-label="Permalink to ${escapeHtml(text)}">#</a>`;
190
+ inline.children = [...(inline.children ?? []), anchor];
191
+ });
192
+ });
193
+ return md;
194
+ }
195
+ /** Markdown output is static HTML: anything a .tscl template would read as syntax ({{ }}, @if …) is escaped. */
196
+ function staticHtml(html) {
197
+ return html.replace(/\{\{/g, '&#123;&#123;').replace(/@/g, '&#64;');
198
+ }
199
+ /**
200
+ * Component tags (and any tag with [prop] or (event) bindings) aren't valid CommonMark HTML, so markdown-it would
201
+ * escape them. They are swapped for HTML comments, which it passes through, and put back after rendering.
202
+ */
203
+ function protectTags(body, components, saved) {
204
+ // Code (fences, then inline spans) is matched first and kept as written: a tag in an example stays text.
205
+ // ponytail: indented code blocks aren't recognised; use a fence to show a component tag in code.
206
+ const code = /(?:^|\n)[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n[ \t]*\1[`~]*[ \t\r]*(?=\n|$)|$)|(`+)[\s\S]*?[^`]\2(?!`)/;
207
+ const tag = /<\/?([A-Za-z][\w-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/;
208
+ const out = body.replace(new RegExp(`${code.source}|${tag.source}`, 'g'), (match, _fence, _ticks, name, attrs) => {
209
+ if (name === undefined)
210
+ return match;
211
+ const tag = match;
212
+ if (!components.has(name) && !/\s[[(]/.test(attrs))
213
+ return tag;
214
+ saved.push(tag);
215
+ return `<!--cl-tag-${saved.length - 1}-->`;
216
+ });
217
+ return { body: out, restore: (html) => html.replace(/<!--cl-tag-(\d+)-->/g, (_, i) => saved[Number(i)]) };
218
+ }
219
+ export default function markdown(options = {}) {
220
+ const md = renderer(options);
221
+ return {
222
+ extension: '.md',
223
+ toTscl(code, file, context) {
224
+ const { route } = context;
225
+ // ---\nyaml\n---: the page's frontmatter.
226
+ const front = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(code);
227
+ const data = (front ? parseYaml(front[1]) : null) ?? {};
228
+ // Snippets and includes first: what they bring in is Markdown like the rest of the page.
229
+ let body = expand(front ? code.slice(front[0].length) : code, file, context);
230
+ // @import lines at the top pass through, so components can be used in the Markdown.
231
+ const imports = [];
232
+ for (;;) {
233
+ const line = /^[ \t]*(@import\b[^\n]*)\n|^[ \t]*\n/.exec(body);
234
+ if (!line)
235
+ break;
236
+ if (line[1])
237
+ imports.push(line[1].trim());
238
+ body = body.slice(line[0].length);
239
+ }
240
+ // Blocks rendered through a component need it imported.
241
+ if (options.container && !imports.some((line) => new RegExp(`^@import\\s+${options.container.tag}\\s+from`).test(line))) {
242
+ imports.unshift(`@import ${options.container.tag} from '${options.container.from}'`);
243
+ }
244
+ const components = new Set(imports.map((line) => /^@import\s+([A-Za-z_$][\w-]*)\s+from/.exec(line)?.[1]).filter((n) => !!n));
245
+ // cl-layout names the generated layout import (tag names must start with a letter, so not __cl_).
246
+ if (components.has('cl-layout'))
247
+ throw new Error(`${file}: cl-layout is reserved for the page's layout; import the component under another name`);
248
+ if (options.copy && !imports.some((line) => new RegExp(`^@import\\s+${options.copy.tag}\\s+from`).test(line))) {
249
+ imports.unshift(`@import ${options.copy.tag} from '${options.copy.from}'`);
250
+ }
251
+ const env = { tags: [], groups: 0, file, root: context.root };
252
+ const tags = protectTags(body, components, env.tags);
253
+ const tokens = md.parse(tags.body, env);
254
+ const h1 = tokens.findIndex((t) => t.type === 'heading_open' && t.tag === 'h1');
255
+ const firstHeading = h1 === -1 ? undefined : (tokens[h1 + 1].children ?? []).filter((t) => t.type === 'text' || t.type === 'code_inline').map((t) => t.content).join('');
256
+ const html = tags.restore(staticHtml(md.renderer.render(tokens, md.options, env)));
257
+ const layout = data.layout === false ? undefined : (typeof data.layout === 'string' ? data.layout : options.layout);
258
+ if (!layout)
259
+ return [...imports, html].join('\n');
260
+ const title = typeof data.title === 'string' ? data.title : firstHeading;
261
+ const props = [
262
+ title !== undefined ? `[title]="${quote(title)}"` : '',
263
+ typeof data.description === 'string' ? `[description]="${quote(data.description)}"` : '',
264
+ `[path]="${quote(route)}"`,
265
+ ].filter(Boolean).join(' ');
266
+ return [`@import cl-layout from '${layout}'`, ...imports, `<cl-layout ${props}>${html}</cl-layout>`, ''].join('\n');
267
+ },
268
+ };
269
+ }
@@ -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,104 @@
1
+ // <<< code snippets and <!-- @include: --> Markdown includes, expanded before the Markdown is parsed. Lines inside
2
+ // code fences are left alone, so documentation can show the syntax itself.
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { dirname, relative, resolve, sep } from 'node:path';
5
+ const SNIPPET = /^[ \t]*<<<[ \t]+(\S+?)(?:#([\w-]+))?(\{[^}]*\})?(?:[ \t]+\[([^\]]+)\])?[ \t]*$/;
6
+ const INCLUDE = /^[ \t]*<!--[ \t]*@include:[ \t]*(\S+?)(?:#([\w-]+))?[ \t]*-->[ \t]*$/;
7
+ const posix = (p) => p.split(sep).join('/');
8
+ // A region marker is a comment line of its own: // #region name, /* #endregion */, <!-- #region name -->, # #region.
9
+ const MARKER = /^[ \t]*(?:\/\/|\/\*|<!--|#|--|;)?[ \t]*#(end)?region(?:[ \t]+([A-Za-z0-9_][\w-]*))?[ \t]*(?:\*\/|-->)?[ \t]*$/;
10
+ /**
11
+ * The lines between `#region name` and its `#endregion`, without markers, dedented. Regions nest: an inner region's
12
+ * unnamed `#endregion` closes the inner one, and the outer selection keeps everything up to its own ending.
13
+ */
14
+ function region(text, name) {
15
+ let lines = text.replace(/\n$/, '').split('\n');
16
+ if (name) {
17
+ const start = lines.findIndex((l) => { const m = MARKER.exec(l); return !!m && !m[1] && m[2] === name; });
18
+ if (start === -1)
19
+ return undefined;
20
+ let depth = 0;
21
+ let end = -1;
22
+ for (let i = start + 1; i < lines.length && end === -1; i++) {
23
+ const m = MARKER.exec(lines[i]);
24
+ if (!m)
25
+ continue;
26
+ if (!m[1])
27
+ depth++;
28
+ else if (m[2] === name || (!m[2] && depth === 0))
29
+ end = i;
30
+ else
31
+ depth--;
32
+ }
33
+ lines = lines.slice(start + 1, end === -1 ? undefined : end);
34
+ }
35
+ lines = lines.filter((l) => !MARKER.test(l));
36
+ const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => /^[ \t]*/.exec(l)[0].length));
37
+ return lines.map((l) => l.slice(Number.isFinite(indent) ? indent : 0)).join('\n');
38
+ }
39
+ /**
40
+ * Apply `fn` to every line outside fenced code, so examples stay as written. A fence may open after list markers;
41
+ * a closing fence uses the same character, is at least as long, has nothing after it, and is indented at most three
42
+ * spaces past where the fence opened (more is code).
43
+ */
44
+ function outsideFences(text, fn) {
45
+ let fence = null;
46
+ return text.split('\n').map((line) => {
47
+ if (fence) {
48
+ const close = /^([ \t]*)(`{3,}|~{3,})[ \t\r]*$/.exec(line);
49
+ if (close && close[2][0] === fence.marker[0] && close[2].length >= fence.marker.length && close[1].length <= fence.indent + 3)
50
+ fence = null;
51
+ return line;
52
+ }
53
+ const open = /^([ \t]*(?:(?:[-*+]|\d+[.)])[ \t]+)*)(`{3,}|~{3,})/.exec(line);
54
+ if (open) {
55
+ fence = { marker: open[2], indent: open[1].length };
56
+ return line;
57
+ }
58
+ return fn(line);
59
+ }).join('\n');
60
+ }
61
+ /** Expand snippets and includes in `text` (from `file`; `stack` is the include chain, page first). */
62
+ export function expand(text, file, ctx, stack = [file]) {
63
+ if (!/<<<|@include:/.test(text))
64
+ return text;
65
+ const page = posix(relative(ctx.root, stack[0]));
66
+ const fail = (what) => { throw new Error(`${page}: ${what}`); };
67
+ const locate = (spec, directive) => {
68
+ const path = spec.startsWith('@/') ? resolve(ctx.root, spec.slice(2)) : resolve(dirname(file), spec);
69
+ if (path !== ctx.root && !path.startsWith(ctx.root + sep))
70
+ fail(`${directive} ${spec}: outside the project`);
71
+ if (!existsSync(path))
72
+ fail(`${directive} ${spec}: file not found`);
73
+ ctx.addDependency(path);
74
+ return path;
75
+ };
76
+ return outsideFences(text, (line) => {
77
+ let m = SNIPPET.exec(line);
78
+ if (m) {
79
+ const [, spec, name, lines, title] = m;
80
+ const path = locate(spec, '<<<');
81
+ const code = region(readFileSync(path, 'utf8'), name) ?? fail(`<<< ${spec}: region "${name}" not found`);
82
+ const ticks = '`'.repeat(Math.max(3, ...(code.match(/`{3,}/g) ?? []).map((t) => t.length + 1)));
83
+ const lang = /\.([\w-]+)$/.exec(path)?.[1] ?? 'text';
84
+ return [`${ticks}${lang}${lines ? ` ${lines}` : ''}${title ? ` [${title}]` : ''}`, code, ticks].join('\n');
85
+ }
86
+ m = INCLUDE.exec(line);
87
+ if (m) {
88
+ const [, spec, name] = m;
89
+ const path = locate(spec, '@include:');
90
+ if (stack.includes(path))
91
+ fail(`include cycle: ${[...stack, path].map((p) => posix(relative(ctx.root, p))).join(' → ')}`);
92
+ let included = readFileSync(path, 'utf8').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
93
+ included = region(included, name) ?? fail(`@include: ${spec}: region "${name}" not found`);
94
+ // Relative links (inline and reference definitions) in the included file are rewritten to work from the page
95
+ // that includes it; examples in fences stay as written.
96
+ const rebase = (href) => (/^([a-z][\w+.-]*:|\/|#)/i.test(href) ? href : posix(relative(dirname(stack[0]), resolve(dirname(path), href))));
97
+ included = outsideFences(included, (l) => l
98
+ .replace(/(\]\()([^)\s]+)/g, (_, open, href) => open + rebase(href))
99
+ .replace(/^([ \t]{0,3}\[[^\]]+\]:[ \t]*)(\S+)/, (_, def, href) => def + rebase(href)));
100
+ return expand(included, path, ctx, [...stack, path]);
101
+ }
102
+ return line;
103
+ });
104
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@clarusjs/content",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Markdown pages for clarusjs: frontmatter, layouts, components in Markdown, rendered to static HTML at build time.",
5
+ "type": "module",
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.7.0"
23
+ },
24
+ "engines": {
25
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/forinda/clarusjs.git",
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.7.0",
54
+ "typescript": "^7.0.2",
55
+ "vite": "^8.3.8",
56
+ "vitest": "^5.1.1"
57
+ },
58
+ "scripts": {
59
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
60
+ "test": "vitest run",
61
+ "typecheck": "tsc --noEmit"
62
+ }
6
63
  }