@jay-framework/markdown 0.22.2 → 0.24.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/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ import * as _jay_framework_component from '@jay-framework/component';
5
5
  interface MarkdownPagesProps {
6
6
  contentDir: string;
7
7
  slug: string;
8
+ mediaMap?: string;
8
9
  }
9
10
  declare const markdownPages: _jay_framework_fullstack_component.JayStackComponentDefinition<any, any, any, any, [{}], [], MarkdownPagesProps & {
10
11
  slug: string;
@@ -33,7 +34,7 @@ declare const markdownPages: _jay_framework_fullstack_component.JayStackComponen
33
34
  slug: string;
34
35
  }, _jay_framework_component.JayComponentCore<MarkdownPagesProps & {
35
36
  slug: string;
36
- }, any>> & any;
37
+ }, any>> & /*elided*/ any;
37
38
  withInteractive(comp: _jay_framework_component.ComponentConstructor<MarkdownPagesProps & {
38
39
  slug: string;
39
40
  }, any, any, [_jay_framework_fullstack_component.Signals<any>, NewCarryForward], _jay_framework_component.JayComponentCore<MarkdownPagesProps & {
@@ -67,7 +68,7 @@ declare const markdownContent: _jay_framework_fullstack_component.JayStackCompon
67
68
  withClientDefaults(fn: (props: MarkdownContentProps) => {
68
69
  viewState: any;
69
70
  carryForward?: any;
70
- }): _jay_framework_fullstack_component.JayStackComponentDefinition<any, any, any, any, [{}], [_jay_framework_fullstack_component.Signals<any>, NewCarryForward], MarkdownContentProps, {}, _jay_framework_component.JayComponentCore<MarkdownContentProps, any>> & any;
71
+ }): _jay_framework_fullstack_component.JayStackComponentDefinition<any, any, any, any, [{}], [_jay_framework_fullstack_component.Signals<any>, NewCarryForward], MarkdownContentProps, {}, _jay_framework_component.JayComponentCore<MarkdownContentProps, any>> & /*elided*/ any;
71
72
  withInteractive(comp: _jay_framework_component.ComponentConstructor<MarkdownContentProps, any, any, [_jay_framework_fullstack_component.Signals<any>, NewCarryForward], _jay_framework_component.JayComponentCore<MarkdownContentProps, any>>): _jay_framework_fullstack_component.JayStackComponentDefinition<any, any, any, any, [{}], [_jay_framework_fullstack_component.Signals<any>, NewCarryForward], MarkdownContentProps, {}, _jay_framework_component.JayComponentCore<MarkdownContentProps, any>>;
72
73
  };
73
74
  withInteractive(comp: _jay_framework_component.ComponentConstructor<MarkdownContentProps, any, any, [], _jay_framework_component.JayComponentCore<MarkdownContentProps, any>>): _jay_framework_fullstack_component.JayStackComponentDefinition<any, any, any, any, [{}], [], MarkdownContentProps, {}, _jay_framework_component.JayComponentCore<MarkdownContentProps, any>>;
@@ -86,10 +87,23 @@ declare function extractFrontmatter(content: string): {
86
87
  frontmatter: Record<string, any>;
87
88
  body: string;
88
89
  };
89
- declare function parseMarkdownBody(markdown: string): string;
90
- declare function parseMarkdownBodyWithMermaid(markdown: string): Promise<string>;
91
- declare function parseMarkdown(content: string): ParsedMarkdown;
92
- declare function parseMarkdownWithMermaid(content: string): Promise<ParsedMarkdown>;
90
+ interface MediaMapEntry {
91
+ src: string;
92
+ width?: number;
93
+ height?: number;
94
+ srcset?: Array<{
95
+ url: string;
96
+ width: number;
97
+ }>;
98
+ }
99
+ interface MarkdownImageOptions {
100
+ imageBaseUrl?: string;
101
+ mediaMap?: Record<string, MediaMapEntry>;
102
+ }
103
+ declare function parseMarkdownBody(markdown: string, imageOptions?: MarkdownImageOptions): string;
104
+ declare function parseMarkdownBodyWithMermaid(markdown: string, imageOptions?: MarkdownImageOptions): Promise<string>;
105
+ declare function parseMarkdown(content: string, imageOptions?: MarkdownImageOptions): ParsedMarkdown;
106
+ declare function parseMarkdownWithMermaid(content: string, imageOptions?: MarkdownImageOptions): Promise<ParsedMarkdown>;
93
107
 
94
108
  declare function highlightCode(code: string, lang: string): string;
95
109
 
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { makeJayStackComponent, phaseOutput } from "@jay-framework/fullstack-component";
1
+ import { makeJayStackComponent, notFound, phaseOutput } from "@jay-framework/fullstack-component";
2
2
  import { Marked } from "marked";
3
3
  import yaml from "js-yaml";
4
4
  import { renderMermaidSVGAsync } from "beautiful-mermaid";
5
5
  import fs from "node:fs/promises";
6
+ import fsSync from "node:fs";
6
7
  import path from "node:path";
7
8
  const ESCAPE_MAP = {
8
9
  "&": "&amp;",
@@ -99,8 +100,7 @@ const LANG_RULES = {
99
100
  };
100
101
  function highlightCode(code, lang) {
101
102
  const rules = LANG_RULES[lang.toLowerCase()];
102
- if (!rules)
103
- return esc(code);
103
+ if (!rules) return esc(code);
104
104
  const tokens = [];
105
105
  for (const rule of rules) {
106
106
  const re = new RegExp(rule.re.source, rule.re.flags);
@@ -118,20 +118,24 @@ function highlightCode(code, lang) {
118
118
  const result = [];
119
119
  let pos = 0;
120
120
  for (const token of tokens) {
121
- if (token.start < pos)
122
- continue;
123
- if (token.start > pos)
124
- result.push(esc(code.slice(pos, token.start)));
121
+ if (token.start < pos) continue;
122
+ if (token.start > pos) result.push(esc(code.slice(pos, token.start)));
125
123
  result.push(wrap(token.cls, token.text));
126
124
  pos = token.end;
127
125
  }
128
- if (pos < code.length)
129
- result.push(esc(code.slice(pos)));
126
+ if (pos < code.length) result.push(esc(code.slice(pos)));
130
127
  return result.join("");
131
128
  }
129
+ function cleanSvg(svg) {
130
+ let cleaned = svg.replace(/(<svg[^>]*)\s+style="[^"]*"/, "$1");
131
+ cleaned = cleaned.replace(/@import\s+url\([^)]*\)\s*;?\s*/g, "");
132
+ cleaned = cleaned.replace(/text\s*\{[^}]*font-family[^}]*\}\s*/g, "");
133
+ return cleaned;
134
+ }
132
135
  async function renderMermaidToSvg(code) {
133
136
  try {
134
- return await renderMermaidSVGAsync(code);
137
+ const svg = await renderMermaidSVGAsync(code);
138
+ return cleanSvg(svg);
135
139
  } catch {
136
140
  const escaped = code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
137
141
  return `<pre class="md-mermaid-error">Failed to render mermaid diagram:
@@ -145,8 +149,7 @@ async function renderMermaidBlock(code) {
145
149
  }
146
150
  function extractFrontmatter(content) {
147
151
  const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/);
148
- if (!match)
149
- return { frontmatter: {}, body: content };
152
+ if (!match) return { frontmatter: {}, body: content };
150
153
  const raw = yaml.load(match[1]);
151
154
  return {
152
155
  frontmatter: raw && typeof raw === "object" ? raw : {},
@@ -159,8 +162,7 @@ function mermaidFallback(code) {
159
162
  }
160
163
  const MERMAID_FENCE_RE = /```mermaid\s*\n([\s\S]*?)```/g;
161
164
  async function preprocessMermaid(body, renderSvg) {
162
- if (!body.includes("```mermaid"))
163
- return body;
165
+ if (!body.includes("```mermaid")) return body;
164
166
  const fences = [];
165
167
  let m;
166
168
  const re = new RegExp(MERMAID_FENCE_RE.source, "g");
@@ -169,7 +171,7 @@ async function preprocessMermaid(body, renderSvg) {
169
171
  }
170
172
  let result = body;
171
173
  for (const fence of fences) {
172
- const replacement = renderSvg ? await renderMermaidBlock(fence.code) : mermaidFallback(fence.code);
174
+ const replacement = await renderMermaidBlock(fence.code);
173
175
  result = result.replace(fence.match, replacement);
174
176
  }
175
177
  return result;
@@ -177,8 +179,7 @@ async function preprocessMermaid(body, renderSvg) {
177
179
  function createCodeRenderer() {
178
180
  return {
179
181
  code({ text, lang }) {
180
- if (lang === "mermaid")
181
- return mermaidFallback(text) + "\n";
182
+ if (lang === "mermaid") return mermaidFallback(text) + "\n";
182
183
  const language = lang || "";
183
184
  const highlighted = highlightCode(text, language);
184
185
  const langClass = language ? ` language-${language}` : "";
@@ -187,29 +188,99 @@ function createCodeRenderer() {
187
188
  }
188
189
  };
189
190
  }
191
+ function stripMdExtension(href) {
192
+ if (href.startsWith("http://") || href.startsWith("https://")) return href;
193
+ return href.replace(/\.md(#|$)/, "$1");
194
+ }
195
+ function createLinkRenderer() {
196
+ return {
197
+ link({
198
+ href,
199
+ title,
200
+ tokens
201
+ }) {
202
+ const resolved = stripMdExtension(href);
203
+ const titleAttr = title ? ` title="${title}"` : "";
204
+ const text = this.parser.parseInline(tokens);
205
+ return `<a href="${resolved}"${titleAttr}>${text}</a>`;
206
+ }
207
+ };
208
+ }
190
209
  let sharedMarked;
191
210
  function getMarked() {
192
211
  if (!sharedMarked) {
193
212
  sharedMarked = new Marked();
194
- sharedMarked.use({ renderer: createCodeRenderer() });
213
+ sharedMarked.use({ renderer: { ...createCodeRenderer(), ...createLinkRenderer() } });
195
214
  }
196
215
  return sharedMarked;
197
216
  }
198
- function parseMarkdownBody(markdown) {
199
- return getMarked().parse(markdown);
217
+ function createImageRenderer(options) {
218
+ return {
219
+ image({
220
+ href,
221
+ title,
222
+ text
223
+ }) {
224
+ const alt = text || "";
225
+ const isRelative = href && !href.startsWith("http://") && !href.startsWith("https://") && !href.startsWith("/");
226
+ const filename = isRelative ? decodeURIComponent(href) : "";
227
+ if (options.mediaMap && filename && options.mediaMap[filename]) {
228
+ const entry = options.mediaMap[filename];
229
+ const attrs = [`src="${entry.src}"`, `alt="${alt}"`];
230
+ if (entry.width) attrs.push(`width="${entry.width}"`);
231
+ if (entry.height) attrs.push(`height="${entry.height}"`);
232
+ if (entry.srcset && entry.srcset.length > 0) {
233
+ const srcsetStr = entry.srcset.map((s) => `${s.url} ${s.width}w`).join(", ");
234
+ attrs.push(`srcset="${srcsetStr}"`);
235
+ const sizes = generateSizes(entry.srcset.map((s) => s.width));
236
+ attrs.push(`sizes="${sizes}"`);
237
+ }
238
+ attrs.push('loading="lazy"');
239
+ if (title) attrs.push(`title="${title}"`);
240
+ return `<img ${attrs.join(" ")} />`;
241
+ }
242
+ if (isRelative && options.imageBaseUrl) {
243
+ const resolved = `${options.imageBaseUrl}/${encodeURIComponent(filename)}`;
244
+ const titleAttr2 = title ? ` title="${title}"` : "";
245
+ return `<img src="${resolved}" alt="${alt}" loading="lazy"${titleAttr2} />`;
246
+ }
247
+ const titleAttr = title ? ` title="${title}"` : "";
248
+ return `<img src="${href}" alt="${alt}" loading="lazy"${titleAttr} />`;
249
+ }
250
+ };
251
+ }
252
+ function generateSizes(widths) {
253
+ const sorted = [...widths].sort((a, b) => a - b);
254
+ if (sorted.length <= 1) return `${sorted[0] || 800}px`;
255
+ const parts = [];
256
+ for (let i = 0; i < sorted.length - 1; i++) {
257
+ parts.push(`(max-width: ${sorted[i] + 200}px) ${sorted[i]}px`);
258
+ }
259
+ parts.push(`${sorted[sorted.length - 1]}px`);
260
+ return parts.join(", ");
261
+ }
262
+ function parseMarkdownBody(markdown, imageOptions) {
263
+ const marked = getMarked();
264
+ if (imageOptions?.imageBaseUrl || imageOptions?.mediaMap) {
265
+ const perParse = new Marked();
266
+ perParse.use({ renderer: { ...createCodeRenderer(), ...createLinkRenderer() } });
267
+ perParse.use({ renderer: createImageRenderer(imageOptions) });
268
+ return perParse.parse(markdown);
269
+ }
270
+ return marked.parse(markdown);
200
271
  }
201
- async function parseMarkdownBodyWithMermaid(markdown) {
202
- const processed = await preprocessMermaid(markdown, true);
203
- return getMarked().parse(processed);
272
+ async function parseMarkdownBodyWithMermaid(markdown, imageOptions) {
273
+ const processed = await preprocessMermaid(markdown);
274
+ return parseMarkdownBody(processed, imageOptions);
204
275
  }
205
- function parseMarkdown(content) {
276
+ function parseMarkdown(content, imageOptions) {
206
277
  const { frontmatter, body } = extractFrontmatter(content);
207
- const html = parseMarkdownBody(body);
278
+ const html = parseMarkdownBody(body, imageOptions);
208
279
  return { frontmatter, html };
209
280
  }
210
- async function parseMarkdownWithMermaid(content) {
281
+ async function parseMarkdownWithMermaid(content, imageOptions) {
211
282
  const { frontmatter, body } = extractFrontmatter(content);
212
- const html = await parseMarkdownBodyWithMermaid(body);
283
+ const html = await parseMarkdownBodyWithMermaid(body, imageOptions);
213
284
  return { frontmatter, html };
214
285
  }
215
286
  const KNOWN_FIELDS = /* @__PURE__ */ new Set([
@@ -247,18 +318,77 @@ function frontmatterToHeadTags(fm) {
247
318
  });
248
319
  }
249
320
  for (const [key, value] of Object.entries(fm)) {
250
- if (KNOWN_FIELDS.has(key))
251
- continue;
321
+ if (KNOWN_FIELDS.has(key)) continue;
252
322
  if (typeof value === "string" || typeof value === "number") {
253
323
  tags.push({ tag: "meta", attrs: { name: key, content: String(value) } });
254
324
  }
255
325
  }
256
326
  return tags;
257
327
  }
328
+ function readPublicFolder() {
329
+ try {
330
+ const configPath = path.resolve(".jay");
331
+ if (fsSync.existsSync(configPath)) {
332
+ const config = yaml.load(fsSync.readFileSync(configPath, "utf-8"));
333
+ return config?.devServer?.publicFolder || "./public";
334
+ }
335
+ } catch {
336
+ }
337
+ return "./public";
338
+ }
339
+ const MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
340
+ ".png",
341
+ ".jpg",
342
+ ".jpeg",
343
+ ".gif",
344
+ ".svg",
345
+ ".webp",
346
+ ".avif",
347
+ ".ico",
348
+ ".mp4",
349
+ ".webm",
350
+ ".ogg",
351
+ ".mp3",
352
+ ".wav",
353
+ ".pdf"
354
+ ]);
355
+ async function copyMediaToPublic(contentDir, publicFolder) {
356
+ const publicSubDir = path.join(publicFolder, contentDir);
357
+ await fs.mkdir(publicSubDir, { recursive: true });
358
+ try {
359
+ const files = await fs.readdir(contentDir);
360
+ for (const file of files) {
361
+ const ext = path.extname(file).toLowerCase();
362
+ if (!MEDIA_EXTENSIONS.has(ext)) continue;
363
+ const src = path.join(contentDir, file);
364
+ const dest = path.join(publicSubDir, file);
365
+ try {
366
+ const srcStat = await fs.stat(src);
367
+ let needsCopy = true;
368
+ try {
369
+ const destStat = await fs.stat(dest);
370
+ if (destStat.mtimeMs >= srcStat.mtimeMs) needsCopy = false;
371
+ } catch {
372
+ }
373
+ if (needsCopy) await fs.copyFile(src, dest);
374
+ } catch {
375
+ }
376
+ }
377
+ } catch {
378
+ }
379
+ return "/" + contentDir.replace(/\\/g, "/");
380
+ }
381
+ async function loadMediaMap(mapPath) {
382
+ try {
383
+ const content = await fs.readFile(mapPath, "utf-8");
384
+ return yaml.load(content) || {};
385
+ } catch {
386
+ return {};
387
+ }
388
+ }
258
389
  const markdownPages = makeJayStackComponent().withProps().withLoadParams(async function* (_services, props) {
259
390
  const dir = props?.contentDir;
260
- if (!dir)
261
- return;
391
+ if (!dir) return;
262
392
  try {
263
393
  const files = await fs.readdir(dir);
264
394
  const slugs = files.filter((f) => f.endsWith(".md")).map((f) => ({ slug: f.replace(/\.md$/, "") }));
@@ -268,12 +398,31 @@ const markdownPages = makeJayStackComponent().withProps().withLoadParams(async f
268
398
  }
269
399
  }).withSlowlyRender(async (props) => {
270
400
  const filePath = path.join(props.contentDir, `${props.slug}.md`);
271
- const content = await fs.readFile(filePath, "utf-8");
272
- const { frontmatter, html } = await parseMarkdownWithMermaid(content);
401
+ let content;
402
+ try {
403
+ content = await fs.readFile(filePath, "utf-8");
404
+ } catch (err) {
405
+ if (err?.code === "ENOENT") return notFound();
406
+ throw err;
407
+ }
408
+ let imageOptions = {};
409
+ if (props.mediaMap) {
410
+ const mediaMap = await loadMediaMap(props.mediaMap);
411
+ const publicFolder = readPublicFolder();
412
+ const imageBaseUrl = await copyMediaToPublic(props.contentDir, publicFolder);
413
+ imageOptions = { mediaMap, imageBaseUrl };
414
+ } else {
415
+ const publicFolder = readPublicFolder();
416
+ const imageBaseUrl = await copyMediaToPublic(props.contentDir, publicFolder);
417
+ imageOptions = { imageBaseUrl };
418
+ }
419
+ const { frontmatter, body } = extractFrontmatter(content);
420
+ const title = frontmatter.title ?? body.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? "";
421
+ const html = await parseMarkdownBodyWithMermaid(body, imageOptions);
273
422
  const tags = Array.isArray(frontmatter.tags) ? frontmatter.tags.map((name) => ({ name: String(name) })) : [];
274
423
  return phaseOutput(
275
424
  {
276
- title: frontmatter.title ?? "",
425
+ title,
277
426
  content: html,
278
427
  description: frontmatter.description ?? "",
279
428
  date: frontmatter.date ? new Date(frontmatter.date).toISOString() : "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jay-framework/markdown",
3
- "version": "0.22.2",
3
+ "version": "0.24.0",
4
4
  "type": "module",
5
5
  "description": "Markdown rendering plugin for Jay Framework — pages from directories, inline content, code highlighting, mermaid diagrams",
6
6
  "license": "Apache-2.0",
@@ -34,19 +34,19 @@
34
34
  "test": "vitest run"
35
35
  },
36
36
  "dependencies": {
37
- "@jay-framework/component": "^0.22.2",
38
- "@jay-framework/fullstack-component": "^0.22.2",
39
- "@jay-framework/reactive": "^0.22.2",
40
- "@jay-framework/runtime": "^0.22.2",
41
- "@jay-framework/stack-client-runtime": "^0.22.2",
42
- "@jay-framework/stack-server-runtime": "^0.22.2",
37
+ "@jay-framework/component": "^0.24.0",
38
+ "@jay-framework/fullstack-component": "^0.24.0",
39
+ "@jay-framework/reactive": "^0.24.0",
40
+ "@jay-framework/runtime": "^0.24.0",
41
+ "@jay-framework/stack-client-runtime": "^0.24.0",
42
+ "@jay-framework/stack-server-runtime": "^0.24.0",
43
43
  "beautiful-mermaid": "^1.1.3",
44
44
  "js-yaml": "^4.1.0",
45
45
  "marked": "^15.0.0"
46
46
  },
47
47
  "devDependencies": {
48
- "@jay-framework/dev-environment": "^0.22.2",
49
- "@jay-framework/jay-stack-cli": "^0.22.2",
48
+ "@jay-framework/dev-environment": "^0.24.0",
49
+ "@jay-framework/jay-stack-cli": "^0.24.0",
50
50
  "@types/js-yaml": "^4.0.9",
51
51
  "@types/node": "^22.15.21",
52
52
  "rimraf": "^5.0.5",