@onderwijsin/nuxt-markdown-renderer 0.0.0-stage → 0.2.1

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +325 -2
  3. package/dist/metadata/runtime/app/components/renderer/MarkdownButton.vue +67 -0
  4. package/dist/metadata/runtime/app/components/renderer/MarkdownCallout.vue +115 -0
  5. package/dist/metadata/runtime/app/components/renderer/MarkdownReference.vue +33 -0
  6. package/dist/metadata/runtime/app/utils/define-editor-component-schema.ts +12 -0
  7. package/dist/metadata/schema/editor-component-schema.ts +262 -0
  8. package/dist/module.d.mts +22 -0
  9. package/dist/module.json +12 -0
  10. package/dist/module.mjs +268 -0
  11. package/dist/runtime/app/comark-plugins/video-source.d.ts +8 -0
  12. package/dist/runtime/app/comark-plugins/video-source.js +31 -0
  13. package/dist/runtime/app/components/MarkdownRenderer.d.vue.ts +12 -0
  14. package/dist/runtime/app/components/MarkdownRenderer.vue +41 -0
  15. package/dist/runtime/app/components/MarkdownRenderer.vue.d.ts +12 -0
  16. package/dist/runtime/app/components/renderer/MarkdownButton.d.vue.ts +26 -0
  17. package/dist/runtime/app/components/renderer/MarkdownButton.vue +47 -0
  18. package/dist/runtime/app/components/renderer/MarkdownButton.vue.d.ts +26 -0
  19. package/dist/runtime/app/components/renderer/MarkdownCallout.d.vue.ts +49 -0
  20. package/dist/runtime/app/components/renderer/MarkdownCallout.vue +80 -0
  21. package/dist/runtime/app/components/renderer/MarkdownCallout.vue.d.ts +49 -0
  22. package/dist/runtime/app/components/renderer/MarkdownReference.d.vue.ts +17 -0
  23. package/dist/runtime/app/components/renderer/MarkdownReference.vue +24 -0
  24. package/dist/runtime/app/components/renderer/MarkdownReference.vue.d.ts +17 -0
  25. package/dist/runtime/app/utils/component-manifest.d.ts +13 -0
  26. package/dist/runtime/app/utils/component-manifest.js +17 -0
  27. package/dist/runtime/app/utils/define-editor-component-schema.d.ts +9 -0
  28. package/dist/runtime/app/utils/define-editor-component-schema.js +3 -0
  29. package/dist/runtime/app/utils/resolve-reference-path.d.ts +7 -0
  30. package/dist/runtime/app/utils/resolve-reference-path.js +2 -0
  31. package/dist/runtime/index.css +1 -0
  32. package/dist/runtime/index.d.ts +1 -0
  33. package/dist/runtime/index.js +0 -0
  34. package/dist/runtime/server/utils/component-metadata-handler.d.ts +61 -0
  35. package/dist/runtime/server/utils/component-metadata-handler.js +17 -0
  36. package/dist/runtime/server/utils/metadata.d.ts +22 -0
  37. package/dist/runtime/server/utils/metadata.js +186 -0
  38. package/dist/runtime/shared/types.d.ts +1 -0
  39. package/dist/runtime/shared/types.js +0 -0
  40. package/dist/runtime/types/markdown-renderer.d.ts +20 -0
  41. package/dist/schema/editor-component-schema.d.ts +223 -0
  42. package/dist/schema/editor-component-schema.js +151 -0
  43. package/dist/types.d.mts +7 -0
  44. package/package.json +71 -3
@@ -0,0 +1,262 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * To add a special editor input:
5
+ * 1. Define its name, supported prop type, and strict config schema with `defineSpecialInput`.
6
+ * 2. Add the definition to the three unions below (validation, names, and macro syntax).
7
+ * 3. Cover its shorthand or required options, inferred type, and emitted tag in the contract tests.
8
+ */
9
+
10
+ /** String choices shown by the editor for a literal union or explicit override. */
11
+ const choices = z.array(z.string());
12
+ /** Primitive and structural categories understood by the editor endpoint. */
13
+ const propertyType = z.enum(["array", "boolean", "number", "object", "string"]);
14
+ /** Markdown insertion behavior for an editor component. */
15
+ const nodeType = z.enum(["block", "inline"]);
16
+ /** Human-readable help text shared by input, enrichment, and output. */
17
+ const description = z.string().optional();
18
+ /** An optional author or Vue prop default, retained without coercion. */
19
+ const defaultValue = z.unknown().optional();
20
+ /** Whether the editor requires a prop or nested property. */
21
+ const required = z.boolean().optional();
22
+ /** Human-readable component label supplied by the macro. */
23
+ const label = z.string();
24
+
25
+ /**
26
+ * Derives endpoint validation and macro object syntax from one special-input definition.
27
+ * @param definition Editor name, accepted Vue prop type, and strict options schema.
28
+ * @returns Linked endpoint, macro, name, and shorthand schemas.
29
+ */
30
+ function defineSpecialInput<
31
+ const Name extends string,
32
+ const Property extends z.infer<typeof propertyType>,
33
+ Config extends z.ZodRawShape
34
+ >(definition: { inputType: Name; propertyType: Property; config: z.ZodObject<Config> }) {
35
+ const { inputType, propertyType: supportedType, config } = definition;
36
+ const nameSchema = z.literal(inputType);
37
+ const canUseShorthand = config?.safeParse({}).success;
38
+ // Keep the macro's TypeScript shorthand type aligned with the same empty-config rule.
39
+ const shorthandSchema = z.custom<{} extends z.infer<typeof config> ? Name : never>(
40
+ (value) => canUseShorthand && value === inputType
41
+ );
42
+ return {
43
+ name: nameSchema,
44
+ endpoint: z.object({
45
+ inputType: nameSchema,
46
+ propertyType: z.literal(supportedType),
47
+ config: canUseShorthand ? config.optional() : config
48
+ }),
49
+ macro: z.strictObject({ type: nameSchema, ...config?.shape }),
50
+ shorthand: shorthandSchema
51
+ };
52
+ }
53
+
54
+ /** URL editor control, with optional empty configuration. */
55
+ const urlInput = defineSpecialInput({
56
+ inputType: "url",
57
+ propertyType: "string",
58
+ config: z.strictObject({})
59
+ });
60
+ /** Image editor control, with optional empty configuration. */
61
+ const imageInput = defineSpecialInput({
62
+ inputType: "image",
63
+ propertyType: "string",
64
+ config: z.strictObject({})
65
+ });
66
+ /** Icon editor control, requiring at least one Iconify collection. */
67
+ const iconInput = defineSpecialInput({
68
+ inputType: "icon",
69
+ propertyType: "string",
70
+ config: z.strictObject({ collections: z.array(z.string().min(1)).min(1) })
71
+ });
72
+
73
+ /**
74
+ * Special input types for one of the primitive property types, for which the
75
+ * editor needs to render a specialized input interface.
76
+ */
77
+ export const specialInputs = z.discriminatedUnion("inputType", [
78
+ urlInput.endpoint,
79
+ imageInput.endpoint,
80
+ iconInput.endpoint
81
+ ]);
82
+
83
+ /** Accepted macro input names, derived from the special-input definitions. */
84
+ export const SpecialInputNameSchema = z.union([urlInput.name, imageInput.name, iconInput.name]);
85
+
86
+ /**
87
+ * Macro syntax for controls. Every control accepts an object form; controls without required
88
+ * configuration also accept their name as shorthand.
89
+ */
90
+ export const SpecialInputMacroSchema = z.union([
91
+ urlInput.shorthand,
92
+ imageInput.shorthand,
93
+ iconInput.shorthand,
94
+ z.discriminatedUnion("type", [urlInput.macro, imageInput.macro, iconInput.macro])
95
+ ]);
96
+
97
+ /** Tag name used by the endpoint to identify a validated special editor input. */
98
+ export const SPECIAL_INPUT_TAG_NAME = "specialInputType";
99
+
100
+ /** Named JSDoc or editor hint transported in endpoint metadata. */
101
+ export const EditorTagSchema = z.object({
102
+ name: z.string(),
103
+ text: z.string().optional(),
104
+ config: z.unknown().optional()
105
+ });
106
+ /** Optional tags attached to a component or property. */
107
+ const tags = z.array(EditorTagSchema).optional();
108
+ /** Author-supplied deprecation marker or migration guidance. */
109
+ const deprecation = z.union([z.boolean(), z.object({ text: z.string() }), z.string().min(1)]);
110
+
111
+ /** Non-recursive property overrides accepted by the authoring macro. */
112
+ const inputFields = z.strictObject({
113
+ values: choices.optional(),
114
+ input: SpecialInputMacroSchema.optional(),
115
+ deprecated: deprecation.optional(),
116
+ type: propertyType.optional(),
117
+ description,
118
+ default: defaultValue,
119
+ required
120
+ });
121
+
122
+ /** Macro field shape with recursive object properties and array items. */
123
+ type RecursiveInput = z.infer<typeof inputFields> & {
124
+ properties?: Record<string, RecursiveInput>;
125
+ items?: RecursiveInput;
126
+ };
127
+
128
+ /** One macro prop override, recursively covering object properties and array items. */
129
+ export const EditorPropertyInputSchema: z.ZodType<RecursiveInput> = z.strictObject({
130
+ ...inputFields.shape,
131
+ get properties() {
132
+ return z.record(z.string(), EditorPropertyInputSchema).optional();
133
+ },
134
+ get items() {
135
+ return EditorPropertyInputSchema.optional();
136
+ }
137
+ });
138
+
139
+ /** Complete author-written argument to `defineEditorComponentSchema`. */
140
+ export const EditorComponentInputSchema = z.strictObject({
141
+ label,
142
+ description,
143
+ type: nodeType,
144
+ deprecated: deprecation.optional(),
145
+ properties: z.record(z.string(), EditorPropertyInputSchema).optional()
146
+ });
147
+
148
+ /** Macro property fields after `input` and `deprecated` become endpoint tags. */
149
+ const enrichmentFields = z.object({
150
+ ...inputFields.omit({ input: true, deprecated: true }).shape,
151
+ tags
152
+ });
153
+
154
+ /** Normalized macro property shape before inference from Vue props is merged. */
155
+ type RecursiveEnrichment = z.infer<typeof enrichmentFields> & {
156
+ properties?: Record<string, RecursiveEnrichment>;
157
+ items?: RecursiveEnrichment;
158
+ };
159
+
160
+ /** One normalized macro prop override stored in namespaced component metadata. */
161
+ export const EditorPropertyEnrichmentSchema: z.ZodType<RecursiveEnrichment> = z.object({
162
+ ...enrichmentFields.shape,
163
+ get properties() {
164
+ return z.record(z.string(), EditorPropertyEnrichmentSchema).optional();
165
+ },
166
+ get items() {
167
+ return EditorPropertyEnrichmentSchema.optional();
168
+ }
169
+ });
170
+
171
+ /** Complete namespaced macro enrichment before Vue prop inference is merged. */
172
+ export const EditorComponentEnrichmentSchema = z.object({
173
+ ...EditorComponentInputSchema.omit({ type: true, deprecated: true, properties: true }).shape,
174
+ nodeType,
175
+ props: z.record(z.string(), EditorPropertyEnrichmentSchema).optional(),
176
+ tags
177
+ });
178
+
179
+ /** Partial namespaced enrichment allowed for direct `extendComponentMeta` usage. */
180
+ export const EditorComponentPartialEnrichmentSchema = EditorComponentEnrichmentSchema.partial();
181
+
182
+ /** Editor property fields after inference supplies a required name and type. */
183
+ const outputFields = z.object({
184
+ ...enrichmentFields.omit({ type: true }).shape,
185
+ name: z.string(),
186
+ type: propertyType
187
+ });
188
+
189
+ /** Endpoint property shape with recursive object properties and array items. */
190
+ type RecursiveOutput = z.infer<typeof outputFields> & {
191
+ properties?: Record<string, RecursiveOutput>;
192
+ items?: RecursiveOutput;
193
+ };
194
+
195
+ /** One inferred and enriched prop in the component metadata response. */
196
+ export const EditorPropertyOutputSchema: z.ZodType<RecursiveOutput> = z
197
+ .object({
198
+ ...outputFields.shape,
199
+ get properties() {
200
+ return z.record(z.string(), EditorPropertyOutputSchema).optional();
201
+ },
202
+ get items() {
203
+ return EditorPropertyOutputSchema.optional();
204
+ }
205
+ })
206
+ .superRefine((property, context) => {
207
+ for (const [index, tag] of (property.tags ?? []).entries()) {
208
+ if (tag.name !== SPECIAL_INPUT_TAG_NAME) continue;
209
+ if (!SpecialInputNameSchema.safeParse(tag.text).success) {
210
+ context.addIssue({
211
+ code: "custom",
212
+ path: ["tags", index, "text"],
213
+ message: "Unknown special input type."
214
+ });
215
+ continue;
216
+ }
217
+ if (
218
+ specialInputs.safeParse({
219
+ inputType: tag.text,
220
+ propertyType: property.type,
221
+ config: tag.config
222
+ }).success
223
+ ) {
224
+ continue;
225
+ }
226
+ context.addIssue({
227
+ code: "custom",
228
+ path: ["tags", index],
229
+ message: `Editor input ${JSON.stringify(tag.text)} has invalid options or is incompatible with property type ${JSON.stringify(property.type)}.`
230
+ });
231
+ }
232
+ });
233
+
234
+ /** One component returned to the Directus editor after inference and enrichment. */
235
+ export const EditorComponentOutputSchema = z.object({
236
+ ...EditorComponentEnrichmentSchema.omit({ props: true }).shape,
237
+ name: z.string(),
238
+ props: z.record(z.string(), EditorPropertyOutputSchema),
239
+ slots: z.array(z.string())
240
+ });
241
+
242
+ /** Array payload returned by the component metadata HTTP endpoint. */
243
+ export const EditorComponentResponseSchema = z.array(EditorComponentOutputSchema);
244
+
245
+ /** Tag inferred from JSDoc or generated from an editor-specific macro field. */
246
+ export type EditorTag = z.infer<typeof EditorTagSchema>;
247
+ /** TypeScript input for one recursive macro prop override. */
248
+ export type EditorPropertyInput = z.infer<typeof EditorPropertyInputSchema>;
249
+ /** TypeScript argument accepted by `defineEditorComponentSchema`. */
250
+ export type EditorComponentInput = z.infer<typeof EditorComponentInputSchema>;
251
+ /** TypeScript shape of one normalized macro prop override. */
252
+ export type EditorPropertyEnrichment = z.infer<typeof EditorPropertyEnrichmentSchema>;
253
+ /** TypeScript shape of the normalized namespaced macro payload. */
254
+ export type EditorComponentEnrichment = z.infer<typeof EditorComponentEnrichmentSchema>;
255
+ /** TypeScript shape for partial `extendComponentMeta` enrichment. */
256
+ export type EditorComponentPartialEnrichment = z.infer<
257
+ typeof EditorComponentPartialEnrichmentSchema
258
+ >;
259
+ /** TypeScript shape of one inferred and enriched endpoint prop. */
260
+ export type EditorPropertyOutput = z.infer<typeof EditorPropertyOutputSchema>;
261
+ /** TypeScript shape of one component in the endpoint response. */
262
+ export type EditorComponentOutput = z.infer<typeof EditorComponentOutputSchema>;
@@ -0,0 +1,22 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+
3
+ /** Registers the MarkdownRenderer component for Nuxt applications. */
4
+ declare const _default: _nuxt_schema.NuxtModule<{
5
+ enabled?: boolean | undefined;
6
+ scopeComponentMeta?: boolean | undefined;
7
+ componentsDir?: string | undefined;
8
+ componentSets?: Record<string, string[]> | undefined;
9
+ resolveReferencePath?: string | undefined;
10
+ videoBaseUrl?: string | undefined;
11
+ corsOrigin?: string | string[] | undefined;
12
+ }, {
13
+ enabled?: boolean | undefined;
14
+ scopeComponentMeta?: boolean | undefined;
15
+ componentsDir?: string | undefined;
16
+ componentSets?: Record<string, string[]> | undefined;
17
+ resolveReferencePath?: string | undefined;
18
+ videoBaseUrl?: string | undefined;
19
+ corsOrigin?: string | string[] | undefined;
20
+ }, false>;
21
+
22
+ export { _default as default };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@onderwijsin/nuxt-markdown-renderer",
3
+ "configKey": "markdownRenderer",
4
+ "version": "0.2.1",
5
+ "compatibility": {
6
+ "nuxt": "^4.0.0"
7
+ },
8
+ "builder": {
9
+ "@nuxt/module-builder": "1.0.3",
10
+ "unbuild": "3.6.1"
11
+ }
12
+ }
@@ -0,0 +1,268 @@
1
+ import { resolve, dirname, basename, extname } from 'pathe';
2
+ import { useLogger, defineNuxtModule, createResolver, addTypeTemplate, findPath, addTemplate, resolvePath, addImports, addComponent, addComponentsDir, addServerHandler } from '@nuxt/kit';
3
+ import { enabled, resolveModuleName, moduleSetup, validateModuleOptions, transpileRuntime, moduleDependenciesWhenEnabled } from '@onderwijsin/nuxt-module-utils/build';
4
+ import { existsSync } from 'node:fs';
5
+ import { isRecord, isString, fromEntries, toEntries } from '@onderwijsin/nuxt-module-utils/shared';
6
+ import { z } from 'zod';
7
+ import { EditorComponentInputSchema, EditorComponentEnrichmentSchema, SPECIAL_INPUT_TAG_NAME } from '../dist/schema/editor-component-schema.js';
8
+
9
+ const version = "0.2.1";
10
+
11
+ function resolveRendererNodeName(filePath) {
12
+ const fileName = basename(filePath, extname(filePath));
13
+ return fileName === "MarkdownReference" ? "Reference" : fileName;
14
+ }
15
+ function selectRendererComponents(components, directories) {
16
+ const rendererDirectories = new Set(directories.map((directory) => resolve(directory)));
17
+ return components.filter((component) => rendererDirectories.has(resolve(dirname(component.filePath)))).map((component) => ({
18
+ name: resolveRendererNodeName(component.filePath),
19
+ componentName: component.pascalName,
20
+ filePath: component.filePath
21
+ })).sort((left, right) => left.name.localeCompare(right.name));
22
+ }
23
+ function mergeRendererComponents(builtIns, consumers) {
24
+ const components = new Map(builtIns.map((component) => [component.name, component]));
25
+ for (const component of consumers) components.set(component.name, component);
26
+ return [...components.values()].sort((left, right) => left.name.localeCompare(right.name));
27
+ }
28
+ function generateRendererManifest(components, componentSets) {
29
+ const loaders = components.map(
30
+ ({ name, filePath }) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(filePath)})`
31
+ ).join(",\n");
32
+ return `import { createRendererManifest } from "#markdown-renderer/manifest-factory";
33
+
34
+ const componentLoaders = {
35
+ ${loaders}
36
+ };
37
+
38
+ export const { componentSets, rendererComponentNames, resolveRendererComponent } =
39
+ createRendererManifest(componentLoaders, ${JSON.stringify(componentSets)});
40
+ `;
41
+ }
42
+
43
+ function useBuiltInComponentSources(options, builtInDirectory, metadataSourceDirectory) {
44
+ options.components = options.components.map((component) => {
45
+ const source = resolve(component.filePath);
46
+ if (resolve(dirname(source)) !== resolve(builtInDirectory) || !source.endsWith(".vue")) {
47
+ return component;
48
+ }
49
+ const metadataSource = resolve(metadataSourceDirectory, basename(source));
50
+ if (!existsSync(metadataSource)) return component;
51
+ return { ...component, filePath: metadataSource };
52
+ });
53
+ }
54
+
55
+ function resolveDeprecatedTag(value) {
56
+ if (value === true) return { name: "deprecated" };
57
+ if (!value) return void 0;
58
+ return { name: "deprecated", text: isString(value) ? value : value.text };
59
+ }
60
+ function resolveEditorTag(input) {
61
+ if (!input) return void 0;
62
+ if (isString(input)) return { name: SPECIAL_INPUT_TAG_NAME, text: input };
63
+ const { type, ...config } = input;
64
+ return {
65
+ name: SPECIAL_INPUT_TAG_NAME,
66
+ text: type,
67
+ ...Object.keys(config).length ? { config } : {}
68
+ };
69
+ }
70
+ function transformProperty(value) {
71
+ const { deprecated, input, properties, items, ...metadata } = value;
72
+ const deprecatedTag = resolveDeprecatedTag(deprecated);
73
+ const editorTag = resolveEditorTag(input);
74
+ const tags = [...editorTag ? [editorTag] : [], ...deprecatedTag ? [deprecatedTag] : []];
75
+ return {
76
+ ...metadata,
77
+ ...properties ? {
78
+ properties: fromEntries(
79
+ toEntries(properties).map(([name, prop]) => [name, transformProperty(prop)])
80
+ )
81
+ } : {},
82
+ ...items ? { items: transformProperty(items) } : {},
83
+ ...tags.length ? { tags } : {}
84
+ };
85
+ }
86
+ function transformMarkdownComponentMeta(extracted) {
87
+ const parsed = EditorComponentInputSchema.safeParse(extracted);
88
+ if (!parsed.success) {
89
+ const label = isRecord(extracted) && isString(extracted.label) ? ` ${JSON.stringify(extracted.label)}` : "";
90
+ useLogger("markdownRenderer").warn(
91
+ `Invalid defineEditorComponentSchema metadata${label}:
92
+ ${z.prettifyError(parsed.error)}`
93
+ );
94
+ return { markdownRenderer: {} };
95
+ }
96
+ const { deprecated, properties, type, ...metadata } = parsed.data;
97
+ const deprecatedTag = resolveDeprecatedTag(deprecated);
98
+ const transformedProps = properties ? fromEntries(toEntries(properties).map(([name, value]) => [name, transformProperty(value)])) : void 0;
99
+ return {
100
+ markdownRenderer: EditorComponentEnrichmentSchema.parse({
101
+ ...metadata,
102
+ nodeType: type,
103
+ ...transformedProps ? { props: transformedProps } : {},
104
+ ...deprecatedTag ? { tags: [deprecatedTag] } : {}
105
+ })
106
+ };
107
+ }
108
+
109
+ const origin = z.string().trim().min(1);
110
+ const markdownRendererOptionsSchema = z.strictObject({
111
+ enabled: enabled.default(true),
112
+ /** Scope the global component-meta parser to renderer sources; disable for application metadata. */
113
+ scopeComponentMeta: z.boolean().default(true),
114
+ componentsDir: z.string().trim().min(1).default("renderer"),
115
+ componentSets: z.record(z.string(), z.array(z.string().trim().min(1))).default({}),
116
+ resolveReferencePath: z.string().trim().min(1).optional(),
117
+ videoBaseUrl: z.url().optional(),
118
+ corsOrigin: z.union([
119
+ z.literal("*"),
120
+ z.literal("null"),
121
+ z.array(origin).min(1),
122
+ origin.transform((value) => [value])
123
+ ]).default("*")
124
+ });
125
+
126
+ const MODULE_KEY = "markdownRenderer";
127
+ const MODULE_NAME = resolveModuleName(MODULE_KEY);
128
+ const module$1 = defineNuxtModule({
129
+ meta: {
130
+ name: MODULE_NAME,
131
+ configKey: MODULE_KEY,
132
+ version,
133
+ compatibility: { nuxt: "^4.0.0" }
134
+ },
135
+ defaults: {
136
+ enabled: true,
137
+ scopeComponentMeta: true,
138
+ componentsDir: "renderer",
139
+ componentSets: {},
140
+ corsOrigin: "*"
141
+ },
142
+ moduleDependencies: (nuxt) => moduleDependenciesWhenEnabled(nuxt.options.markdownRenderer, {
143
+ "@comark/nuxt": { version: ">=0.7.0" },
144
+ "@nuxt/ui": { version: ">=4.0.0" },
145
+ "nuxt-component-meta": {
146
+ version: ">=0.18.0",
147
+ defaults: {
148
+ extendMetaFunctions: [
149
+ { name: "extendComponentMeta" },
150
+ { name: "defineEditorComponentSchema", transform: transformMarkdownComponentMeta }
151
+ ]
152
+ }
153
+ }
154
+ }),
155
+ async setup(rawOptions, nuxt) {
156
+ const log = useLogger(MODULE_KEY);
157
+ const { start, end, isEnabled } = moduleSetup(MODULE_NAME, rawOptions, log);
158
+ start();
159
+ const options = validateModuleOptions(rawOptions, markdownRendererOptionsSchema, log);
160
+ const resolver = createResolver(import.meta.url);
161
+ const runtimeDir = resolver.resolve("./runtime");
162
+ addTypeTemplate({
163
+ filename: "types/markdown-renderer.d.ts",
164
+ src: resolver.resolve(runtimeDir, "types", "markdown-renderer.d.ts")
165
+ });
166
+ if (!isEnabled()) return;
167
+ const builtInDirectory = resolver.resolve(runtimeDir, "app", "components", "renderer");
168
+ const metadataSourceDirectory = resolver.resolve("./metadata/runtime/app/components/renderer");
169
+ const consumerDirectory = resolve(nuxt.options.srcDir, "components", options.componentsDir);
170
+ const componentMetaHooks = {
171
+ "component-meta:extend": (parserOptions) => {
172
+ if (options.scopeComponentMeta) {
173
+ const rendererPaths = new Set(
174
+ selectRendererComponents(parserOptions.components, [
175
+ builtInDirectory,
176
+ consumerDirectory
177
+ ]).map(({ filePath }) => filePath)
178
+ );
179
+ parserOptions.components = parserOptions.components.filter(
180
+ ({ filePath }) => rendererPaths.has(filePath)
181
+ );
182
+ }
183
+ useBuiltInComponentSources(parserOptions, builtInDirectory, metadataSourceDirectory);
184
+ if (options.scopeComponentMeta) {
185
+ parserOptions.componentDirs = [
186
+ ...new Set(parserOptions.components.map(({ filePath }) => filePath))
187
+ ];
188
+ }
189
+ }
190
+ };
191
+ nuxt.hooks.addHooks(componentMetaHooks);
192
+ const consumerDirectoryExists = await findPath(consumerDirectory, {}, "dir");
193
+ let components = [];
194
+ nuxt.hook("components:extend", (nuxtComponents) => {
195
+ components = mergeRendererComponents(
196
+ selectRendererComponents(nuxtComponents, [builtInDirectory]),
197
+ selectRendererComponents(nuxtComponents, [consumerDirectory])
198
+ );
199
+ });
200
+ const manifest = addTemplate({
201
+ filename: "markdown-renderer/manifest.mjs",
202
+ write: true,
203
+ getContents: () => generateRendererManifest(components, options.componentSets)
204
+ });
205
+ const metadataHandler = addTemplate({
206
+ filename: "markdown-renderer/metadata-handler.mjs",
207
+ write: true,
208
+ getContents: () => `
209
+ import componentMeta from "#nuxt-component-meta/nitro";
210
+ import { createComponentMetadataHandler } from ${JSON.stringify(
211
+ resolver.resolve(runtimeDir, "server", "utils", "component-metadata-handler")
212
+ )};
213
+
214
+ export default createComponentMetadataHandler(
215
+ componentMeta,
216
+ ${JSON.stringify(components.map(({ name, componentName }) => ({ name, componentName })))},
217
+ ${JSON.stringify(options.componentSets)},
218
+ ${JSON.stringify(options.corsOrigin)}
219
+ );
220
+ `
221
+ });
222
+ const referenceResolver = options.resolveReferencePath ? await resolvePath(options.resolveReferencePath) : resolver.resolve(runtimeDir, "app", "utils", "resolve-reference-path");
223
+ nuxt.options.alias["#markdown-renderer/manifest"] = manifest.dst;
224
+ nuxt.options.alias["#markdown-renderer/manifest-factory"] = resolver.resolve(
225
+ runtimeDir,
226
+ "app",
227
+ "utils",
228
+ "component-manifest"
229
+ );
230
+ nuxt.options.alias["#markdown-renderer/reference-resolver"] = referenceResolver;
231
+ nuxt.options.appConfig.markdownRenderer = {
232
+ videoBaseUrl: options.videoBaseUrl
233
+ };
234
+ transpileRuntime(nuxt, runtimeDir);
235
+ addImports({
236
+ name: "defineEditorComponentSchema",
237
+ from: resolver.resolve(runtimeDir, "app", "utils", "define-editor-component-schema")
238
+ });
239
+ addComponent({
240
+ name: "MarkdownRenderer",
241
+ filePath: resolver.resolve(runtimeDir, "app", "components", "MarkdownRenderer.vue")
242
+ });
243
+ addComponentsDir({
244
+ path: builtInDirectory,
245
+ pathPrefix: false,
246
+ global: false,
247
+ priority: 0
248
+ });
249
+ if (consumerDirectoryExists) {
250
+ addComponentsDir({
251
+ path: consumerDirectory,
252
+ pathPrefix: false,
253
+ global: false,
254
+ priority: 1
255
+ });
256
+ }
257
+ for (const route of [
258
+ "/api/markdown-renderer/components",
259
+ "/api/markdown-renderer/components/:componentSet"
260
+ ]) {
261
+ addServerHandler({ method: "get", route, handler: metadataHandler.dst });
262
+ addServerHandler({ method: "options", route, handler: metadataHandler.dst });
263
+ }
264
+ end();
265
+ }
266
+ });
267
+
268
+ export { module$1 as default };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Prepends the configured video base URL to relative video sources.
3
+ *
4
+ * Absolute URLs are left unchanged.
5
+ *
6
+ * @returns A Comark plugin that transforms video source URLs.
7
+ */
8
+ export declare const videoSourcePlugin: import("comark").ComarkPluginFactory<unknown, {}, {}>;
@@ -0,0 +1,31 @@
1
+ import {
2
+ defineComarkPlugin
3
+ } from "comark";
4
+ import { visit } from "comark/utils";
5
+ import { useAppConfig } from "#app";
6
+ import { hasProtocol, joinURL } from "ufo";
7
+ import { isString, isArray } from "@onderwijsin/nuxt-module-utils/shared";
8
+ function isVideoNode(node) {
9
+ return isArray(node) && node[0] === "video" && isString(node[1]?.src);
10
+ }
11
+ export const videoSourcePlugin = defineComarkPlugin(() => {
12
+ const videoBaseUrl = useAppConfig().markdownRenderer.videoBaseUrl;
13
+ if (!videoBaseUrl) {
14
+ throw new Error("videoBaseUrl is not defined in the app config.");
15
+ }
16
+ return {
17
+ name: "video-source",
18
+ post(state) {
19
+ visit(state.tree, isVideoNode, (node) => {
20
+ if (!isVideoNode(node)) {
21
+ return;
22
+ }
23
+ const src = node[1].src;
24
+ if (hasProtocol(src) || src.startsWith("//")) {
25
+ return;
26
+ }
27
+ node[1].src = joinURL(videoBaseUrl, src);
28
+ });
29
+ }
30
+ };
31
+ });
@@ -0,0 +1,12 @@
1
+ import type { ComarkPlugin } from "comark";
2
+ type __VLS_Props = {
3
+ /** Markdown or MDC source rendered by Comark. */
4
+ value?: string;
5
+ /** Optional configured component set that constrains custom components. */
6
+ componentSet?: string;
7
+ /** Optional array of plugins to enhance the Markdown rendering. */
8
+ plugins?: ComarkPlugin[];
9
+ };
10
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
11
+ declare const _default: typeof __VLS_export;
12
+ export default _default;
@@ -0,0 +1,41 @@
1
+ <script setup>
2
+ import { computed } from "vue";
3
+ import { useAppConfig } from "#app";
4
+ import { resolveRendererComponent } from "#markdown-renderer/manifest";
5
+ const props = defineProps({
6
+ value: { type: String, required: false },
7
+ componentSet: { type: String, required: false },
8
+ plugins: { type: Array, required: false }
9
+ });
10
+ const config = useAppConfig().markdownRenderer;
11
+ const componentsManifest = computed(
12
+ () => (name) => resolveRendererComponent(name, props.componentSet)
13
+ );
14
+ const extendedPlugins = [];
15
+ if (config.videoBaseUrl) {
16
+ const { videoSourcePlugin } = await import("../comark-plugins/video-source");
17
+ extendedPlugins.push(videoSourcePlugin());
18
+ }
19
+ const lazilyExtendedPlugins = computed(() => [
20
+ ...props.plugins ?? [],
21
+ ...extendedPlugins
22
+ ]);
23
+ </script>
24
+
25
+ <template>
26
+ <Markdown
27
+ :value="value"
28
+ :components-manifest="componentsManifest"
29
+ :plugins="lazilyExtendedPlugins"
30
+ />
31
+ </template>
32
+
33
+ <style lang="postcss">
34
+ html.dark .shiki span {
35
+ color: var(--shiki-dark) !important;
36
+ background-color: var(--shiki-dark-bg) !important;
37
+ font-style: var(--shiki-dark-font-style) !important;
38
+ font-weight: var(--shiki-dark-font-weight) !important;
39
+ text-decoration: var(--shiki-dark-text-decoration) !important;
40
+ }
41
+ </style>
@@ -0,0 +1,12 @@
1
+ import type { ComarkPlugin } from "comark";
2
+ type __VLS_Props = {
3
+ /** Markdown or MDC source rendered by Comark. */
4
+ value?: string;
5
+ /** Optional configured component set that constrains custom components. */
6
+ componentSet?: string;
7
+ /** Optional array of plugins to enhance the Markdown rendering. */
8
+ plugins?: ComarkPlugin[];
9
+ };
10
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
11
+ declare const _default: typeof __VLS_export;
12
+ export default _default;