@blogmcp/mdx-schema 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.
Files changed (41) hide show
  1. package/dist/checkPin.d.ts +48 -0
  2. package/dist/checkPin.js +139 -0
  3. package/dist/checkPin.js.map +1 -0
  4. package/dist/composables/useMdxParsing.d.ts +71 -0
  5. package/dist/composables/useMdxParsing.js +239 -0
  6. package/dist/composables/useMdxParsing.js.map +1 -0
  7. package/dist/index.d.ts +21 -0
  8. package/dist/index.js +22 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/metadata/customComponents.d.ts +128 -0
  11. package/dist/metadata/customComponents.js +301 -0
  12. package/dist/metadata/customComponents.js.map +1 -0
  13. package/dist/metadata/index.d.ts +24 -0
  14. package/dist/metadata/index.js +427 -0
  15. package/dist/metadata/index.js.map +1 -0
  16. package/dist/metadata/validate.d.ts +46 -0
  17. package/dist/metadata/validate.js +95 -0
  18. package/dist/metadata/validate.js.map +1 -0
  19. package/dist/prepareProps.d.ts +42 -0
  20. package/dist/prepareProps.js +177 -0
  21. package/dist/prepareProps.js.map +1 -0
  22. package/dist/styles/index.d.ts +203 -0
  23. package/dist/styles/index.js +162 -0
  24. package/dist/styles/index.js.map +1 -0
  25. package/dist/types/index.d.ts +421 -0
  26. package/dist/types/index.js +25 -0
  27. package/dist/types/index.js.map +1 -0
  28. package/dist/version.d.ts +23 -0
  29. package/dist/version.js +23 -0
  30. package/dist/version.js.map +1 -0
  31. package/package.json +80 -0
  32. package/src/checkPin.ts +163 -0
  33. package/src/composables/useMdxParsing.ts +248 -0
  34. package/src/index.ts +22 -0
  35. package/src/metadata/customComponents.ts +360 -0
  36. package/src/metadata/index.ts +437 -0
  37. package/src/metadata/validate.ts +153 -0
  38. package/src/prepareProps.ts +219 -0
  39. package/src/styles/index.ts +196 -0
  40. package/src/types/index.ts +469 -0
  41. package/src/version.ts +24 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Write-time pin enforcement.
3
+ *
4
+ * Walks parsed MDX components (including nested MDX-in-MDX children),
5
+ * returns a `PinViolation` for each component whose `addedIn > pinVersion`
6
+ * and for each prop whose effective `addedIn` (prop-level if set,
7
+ * otherwise the parent component's) is `> pinVersion`.
8
+ *
9
+ * Called by `article.service.ts` before save. When `pinVersion` is
10
+ * `null` (no tenant pin set), returns `[]` immediately — the common
11
+ * case.
12
+ *
13
+ * Uses the canonical framework-neutral parser at
14
+ * `src/composables/useMdxParsing.ts` — no new AST dependency. The
15
+ * parser only walks top-level component tags, so this module recurses
16
+ * into `children` strings to cover the `<Tooltip><Button/></Tooltip>`
17
+ * attack vector flagged in review.
18
+ *
19
+ * Comparison uses node-semver named imports (`gt` / `valid` / `lt`).
20
+ * Pre-release identifiers follow standard semver precedence:
21
+ * `0.2.0-beta.1 < 0.2.0`.
22
+ *
23
+ * **addedIn validity:** every `addedIn` we encounter in metadata MUST be
24
+ * a valid semver — these are programmer-error conditions and we throw.
25
+ *
26
+ * **pinVersion validity:** the pin lives in the tenants table, written
27
+ * by humans / migrations / a future UI. We DO NOT throw on a malformed
28
+ * pin at save time (would block every save until ops fixes the DB).
29
+ * Instead we log once and treat the pin as `null` (no enforcement). The
30
+ * write path that SETS `mdx_schema_version_pin` is the right place to
31
+ * validate; we degrade safely here.
32
+ */
33
+
34
+ import { gt, lt, valid } from 'semver'
35
+ import { extractMdxComponents, stripFrontmatter, HAS_MDX_RE } from './composables/useMdxParsing.js'
36
+ import { getComponentMetadata } from './metadata/index.js'
37
+ import type { ParsedContent } from './types/index.js'
38
+
39
+ export interface PinViolation {
40
+ kind: 'componentNewerThanPin' | 'propNewerThanPin'
41
+ /** Component name as it appears in MDX (e.g. "Callout"). */
42
+ component: string
43
+ /** Prop name — set ONLY when `kind === 'propNewerThanPin'`. */
44
+ prop?: string
45
+ /** The `addedIn` SCHEMA_VERSION of the offending element. */
46
+ addedIn: string
47
+ /** The pin set on the tenant. */
48
+ pinVersion: string
49
+ }
50
+
51
+ /** Module-level dedupe so we don't spam the log on a malformed pin. */
52
+ const malformedPinSeen = new Set<string>()
53
+
54
+ function assertValidAddedIn(label: string, version: string): void {
55
+ if (!valid(version)) {
56
+ throw new Error(`[mdx-schema/checkPin] ${label} is not a valid semver string: "${version}"`)
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Recursive walker. Returns violations for the given parsed item AND
62
+ * its children (when children contain further MDX components).
63
+ */
64
+ function walkItem(item: ParsedContent, pinVersion: string, out: PinViolation[]): void {
65
+ if (item.type !== 'component') return
66
+
67
+ const meta = getComponentMetadata(item.name)
68
+ if (!meta) {
69
+ // Unknown component — validateComponent surfaces this as a hard
70
+ // error already; checkPin's contract is pin-only.
71
+ // We still recurse into children in case they exist.
72
+ if ('children' in item && typeof item.children === 'string' && HAS_MDX_RE.test(item.children)) {
73
+ const childItems = extractMdxComponents(item.children)
74
+ for (const child of childItems) walkItem(child, pinVersion, out)
75
+ }
76
+ return
77
+ }
78
+
79
+ assertValidAddedIn(`${meta.name}.addedIn`, meta.addedIn)
80
+
81
+ // Component-level violation: if the component itself is newer
82
+ // than the pin, every prop violation would be redundant — emit
83
+ // ONLY the component violation and skip per-prop checks. Still
84
+ // recurse into children so a nested violation is reported.
85
+ if (gt(meta.addedIn, pinVersion)) {
86
+ out.push({
87
+ kind: 'componentNewerThanPin',
88
+ component: meta.name,
89
+ addedIn: meta.addedIn,
90
+ pinVersion,
91
+ })
92
+ } else {
93
+ // Prop-level violations: each prop's effective `addedIn` (defaults
94
+ // to component's `addedIn` when prop-level is unset).
95
+ for (const propName of Object.keys(item.props)) {
96
+ const propMeta = meta.props.find(p => p.name === propName)
97
+ if (!propMeta) {
98
+ // Unknown prop — validateComponent already surfaces this; pin
99
+ // check has nothing to say.
100
+ continue
101
+ }
102
+ const effectiveAddedIn = propMeta.addedIn ?? meta.addedIn
103
+ assertValidAddedIn(`${meta.name}.${propName}.addedIn`, effectiveAddedIn)
104
+
105
+ if (gt(effectiveAddedIn, pinVersion)) {
106
+ out.push({
107
+ kind: 'propNewerThanPin',
108
+ component: meta.name,
109
+ prop: propName,
110
+ addedIn: effectiveAddedIn,
111
+ pinVersion,
112
+ })
113
+ }
114
+ }
115
+ }
116
+
117
+ // Recurse: children string may itself contain MDX components.
118
+ if (typeof item.children === 'string' && HAS_MDX_RE.test(item.children)) {
119
+ const childItems = extractMdxComponents(item.children)
120
+ for (const child of childItems) walkItem(child, pinVersion, out)
121
+ }
122
+ }
123
+
124
+ export function checkPin(content: string, pinVersion: string | null): PinViolation[] {
125
+ if (pinVersion === null) return []
126
+
127
+ if (!valid(pinVersion)) {
128
+ // Operational-safety: malformed pin in the tenants table must not
129
+ // block every save. Log once per process per offending string and
130
+ // degrade to "no pin" so saves proceed. Validate at WRITE-of-pin
131
+ // time, not READ-of-pin time.
132
+ if (!malformedPinSeen.has(pinVersion)) {
133
+ malformedPinSeen.add(pinVersion)
134
+ const isProd = typeof process !== 'undefined'
135
+ && typeof process.env !== 'undefined'
136
+ && process.env.NODE_ENV === 'production'
137
+ if (!isProd) {
138
+ // eslint-disable-next-line no-console
139
+ console.warn(
140
+ `[mdx-schema/checkPin] pinVersion "${pinVersion}" is not valid semver; treating as no pin. Fix the tenants.mdx_schema_version_pin column.`,
141
+ )
142
+ }
143
+ }
144
+ return []
145
+ }
146
+
147
+ const stripped = stripFrontmatter(content)
148
+ const parsed = extractMdxComponents(stripped)
149
+ const violations: PinViolation[] = []
150
+
151
+ for (const item of parsed) walkItem(item, pinVersion, violations)
152
+
153
+ return violations
154
+ }
155
+
156
+ /** Test-only — clear the malformed-pin dedupe so specs don't poison each other. */
157
+ export function _resetMalformedPinDedupeForTests(): void {
158
+ malformedPinSeen.clear()
159
+ }
160
+
161
+ // Re-export semver helpers we use, so consumers of this module don't
162
+ // need an extra dependency just to round-trip versions:
163
+ export { gt as semverGt, lt as semverLt, valid as semverValid }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * MDX Parsing & Serialization Utilities
3
+ *
4
+ * Shared parsing for JSX-style component syntax used in MDX content.
5
+ * Used by md-editor (compilation), blog (rendering), and Tiptap (roundtripping).
6
+ *
7
+ * Pure TS — no framework dependencies.
8
+ */
9
+
10
+ import type { ParsedContent } from '../types/index.js'
11
+
12
+ /** Regex to detect whether content contains MDX components (uppercase JSX tags). */
13
+ export const HAS_MDX_RE = /<[A-Z][a-zA-Z]*[\s/>]/
14
+
15
+ /**
16
+ * Regex pattern for matching JSX-style components in MDX content.
17
+ * Matches both opening+closing tags and self-closing tags.
18
+ *
19
+ * Group layout:
20
+ * - Opening+closing: match[1]=name, match[2]=props, match[3]=children
21
+ * - Self-closing: match[4]=name, match[5]=props
22
+ *
23
+ * NOTE: Create a new RegExp instance per call (g-flag + exec requires fresh lastIndex).
24
+ */
25
+ export const MDX_COMPONENT_PATTERN =
26
+ /<([A-Z][a-zA-Z]*)\s*([^>]*)>([\s\S]*?)<\/\1>|<([A-Z][a-zA-Z]*)\s*((?:[^/]|\/(?!>))*)\/>/g
27
+
28
+ /**
29
+ * Extract a brace-delimited expression from a string, handling nested braces and quoted strings.
30
+ * Returns the content between the outer braces and the index after the closing brace.
31
+ */
32
+ export function extractBraceExpression(str: string, startIndex: number): { content: string; endIndex: number } | null {
33
+ if (str[startIndex] !== '{') return null
34
+
35
+ let depth = 0
36
+ let inString: string | null = null
37
+
38
+ for (let i = startIndex; i < str.length; i++) {
39
+ const ch = str[i]
40
+
41
+ if (inString) {
42
+ if (ch === '\\') { i++; continue }
43
+ if (ch === inString) inString = null
44
+ continue
45
+ }
46
+
47
+ if (ch === '"' || ch === "'") { inString = ch; continue }
48
+ if (ch === '{') { depth++; continue }
49
+ if (ch === '}') {
50
+ depth--
51
+ if (depth === 0) {
52
+ return { content: str.slice(startIndex + 1, i), endIndex: i + 1 }
53
+ }
54
+ }
55
+ }
56
+ return null
57
+ }
58
+
59
+ /**
60
+ * Parse a JSX props string into a key-value record.
61
+ * Supports: prop="value", prop={expression}, prop (boolean), and nested braces.
62
+ */
63
+ export function parseJsxProps(propsString: string): Record<string, unknown> {
64
+ const result: Record<string, unknown> = {}
65
+ if (!propsString.trim()) return result
66
+
67
+ let i = 0
68
+ const s = propsString
69
+
70
+ while (i < s.length) {
71
+ while (i < s.length && /\s/.test(s[i])) i++
72
+ if (i >= s.length) break
73
+
74
+ const nameMatch = s.slice(i).match(/^(\w+)/)
75
+ if (!nameMatch) { i++; continue }
76
+ const name = nameMatch[1]
77
+ i += name.length
78
+
79
+ while (i < s.length && /\s/.test(s[i])) i++
80
+
81
+ if (s[i] !== '=') {
82
+ result[name] = true
83
+ continue
84
+ }
85
+ i++ // skip '='
86
+
87
+ while (i < s.length && /\s/.test(s[i])) i++
88
+
89
+ if (s[i] === '"') {
90
+ const endQuote = s.indexOf('"', i + 1)
91
+ if (endQuote === -1) { result[name] = ''; break }
92
+ result[name] = s.slice(i + 1, endQuote)
93
+ i = endQuote + 1
94
+ } else if (s[i] === '{') {
95
+ const expr = extractBraceExpression(s, i)
96
+ if (expr) {
97
+ try {
98
+ result[name] = JSON.parse(expr.content.replace(/'/g, '"'))
99
+ } catch {
100
+ result[name] = expr.content
101
+ }
102
+ i = expr.endIndex
103
+ } else {
104
+ i++
105
+ }
106
+ } else {
107
+ i++
108
+ }
109
+ }
110
+
111
+ return result
112
+ }
113
+
114
+ /**
115
+ * Serialize a props object back to JSX-style props string.
116
+ * Reverses parseJsxProps().
117
+ *
118
+ * Rules:
119
+ * - string → prop="value"
120
+ * - boolean true → prop (shorthand)
121
+ * - number → prop={value}
122
+ * - array/object → prop={JSON}
123
+ */
124
+ export function serializeProps(props: Record<string, unknown>): string {
125
+ const parts: string[] = []
126
+
127
+ for (const [key, value] of Object.entries(props)) {
128
+ if (value === undefined || value === null) continue
129
+
130
+ if (value === true) {
131
+ parts.push(key)
132
+ } else if (typeof value === 'string') {
133
+ parts.push(`${key}="${value}"`)
134
+ } else if (typeof value === 'number') {
135
+ parts.push(`${key}={${value}}`)
136
+ } else if (typeof value === 'boolean') {
137
+ parts.push(`${key}={${value}}`)
138
+ } else {
139
+ // Arrays and objects → JSON
140
+ parts.push(`${key}={${JSON.stringify(value)}}`)
141
+ }
142
+ }
143
+
144
+ return parts.join(' ')
145
+ }
146
+
147
+ /**
148
+ * Serialize a component back to JSX-style MDX syntax.
149
+ *
150
+ * @param name - Component name (e.g., "Callout")
151
+ * @param props - Component props object
152
+ * @param children - Inner content (if any). If empty/undefined, produces self-closing tag.
153
+ */
154
+ export function serializeComponent(
155
+ name: string,
156
+ props: Record<string, unknown>,
157
+ children?: string,
158
+ ): string {
159
+ const propsStr = serializeProps(props)
160
+ const propsWithSpace = propsStr ? ` ${propsStr}` : ''
161
+
162
+ if (!children) {
163
+ return `<${name}${propsWithSpace} />`
164
+ }
165
+
166
+ return `<${name}${propsWithSpace}>\n${children}\n</${name}>`
167
+ }
168
+
169
+ /**
170
+ * Strip YAML frontmatter from MDX content.
171
+ */
172
+ export function stripFrontmatter(source: string): string {
173
+ if (source.startsWith('---')) {
174
+ const endIndex = source.indexOf('---', 3)
175
+ if (endIndex !== -1) {
176
+ return source.substring(endIndex + 3).trim()
177
+ }
178
+ }
179
+ return source
180
+ }
181
+
182
+ /**
183
+ * Extract frontmatter string from MDX content.
184
+ * Returns the frontmatter block (without delimiters) or null if none.
185
+ */
186
+ export function extractFrontmatter(source: string): string | null {
187
+ if (source.startsWith('---')) {
188
+ const endIndex = source.indexOf('---', 3)
189
+ if (endIndex !== -1) {
190
+ return source.substring(3, endIndex).trim()
191
+ }
192
+ }
193
+ return null
194
+ }
195
+
196
+ /**
197
+ * Extract MDX components from content, splitting into html chunks and component definitions.
198
+ * Does NOT process markdown → HTML (caller handles that).
199
+ *
200
+ * @param content - MDX content (frontmatter should already be stripped)
201
+ * @returns Array of parsed content items
202
+ */
203
+ export function extractMdxComponents(content: string): ParsedContent[] {
204
+ if (!HAS_MDX_RE.test(content)) {
205
+ return [{ type: 'html', content }]
206
+ }
207
+
208
+ const componentRe = new RegExp(MDX_COMPONENT_PATTERN.source, 'g')
209
+ const items: ParsedContent[] = []
210
+ let lastIndex = 0
211
+ let match
212
+
213
+ while ((match = componentRe.exec(content)) !== null) {
214
+ if (match.index > lastIndex) {
215
+ const raw = content.slice(lastIndex, match.index)
216
+ if (raw.trim()) {
217
+ items.push({ type: 'html', content: raw })
218
+ }
219
+ }
220
+
221
+ const name = match[1] || match[4] || ''
222
+ const propsStr = match[1] ? (match[2] || '') : (match[5] || '')
223
+ const children = match[3]
224
+
225
+ items.push({
226
+ type: 'component',
227
+ name,
228
+ props: parseJsxProps(propsStr),
229
+ children: children?.trim(),
230
+ })
231
+
232
+ lastIndex = match.index + match[0].length
233
+ }
234
+
235
+ if (lastIndex < content.length) {
236
+ const remaining = content.slice(lastIndex)
237
+ if (remaining.trim()) {
238
+ items.push({ type: 'html', content: remaining })
239
+ }
240
+ }
241
+
242
+ // Fallback: regex found no components despite HAS_MDX_RE match
243
+ if (items.length === 0 && content.trim()) {
244
+ return [{ type: 'html', content }]
245
+ }
246
+
247
+ return items
248
+ }
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @blogmcp/mdx-schema
3
+ *
4
+ * Framework-agnostic contract for MDX components. Pure TypeScript — no Vue, no React.
5
+ *
6
+ * Three concerns:
7
+ * - Types: prop shapes + blog config
8
+ * - Metadata: hand-curated component descriptions (drives MCP + agent UX)
9
+ * - Parsing: JSX-style component extraction/serialization
10
+ *
11
+ * Framework renderer packages (@blogmcp/mdx-render-vue, future mdx-render-react)
12
+ * import schemas from here and attach their own component implementations.
13
+ */
14
+
15
+ export * from './types/index.js'
16
+ export * from './metadata/index.js'
17
+ export * from './composables/useMdxParsing.js'
18
+ export * from './metadata/validate.js'
19
+ export * from './styles/index.js'
20
+ export * from './version.js'
21
+ export * from './prepareProps.js'
22
+ export * from './checkPin.js'