@markdoc/markdoc 0.2.1 → 0.3.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.
@@ -9,12 +9,50 @@ describe('Markdown parser', function () {
9
9
  const fence = '```';
10
10
  const tokenizer = new Tokenizer({ allowComments: true });
11
11
 
12
- function convert(example) {
12
+ function convert(example, options?) {
13
13
  const content = example.replace(/\n\s+/gm, '\n').trim();
14
14
  const tokens = tokenizer.tokenize(content);
15
- return parser(tokens);
15
+ return parser(tokens, options);
16
16
  }
17
17
 
18
+ describe('handling options', function () {
19
+ it('no args', function () {
20
+ const example = convert(`# This is a test`);
21
+ expect(example.children[0]).toDeepEqual({
22
+ ...any(),
23
+ type: 'heading',
24
+ location: {
25
+ ...any(),
26
+ file: undefined,
27
+ },
28
+ });
29
+ });
30
+
31
+ it('filename as string', function () {
32
+ const example = convert(`# This is a test`, 'foo.md');
33
+ expect(example.children[0]).toDeepEqual({
34
+ ...any(),
35
+ type: 'heading',
36
+ location: {
37
+ ...any(),
38
+ file: 'foo.md',
39
+ },
40
+ });
41
+ });
42
+
43
+ it('filename as property', function () {
44
+ const example = convert(`# This is a test`, { file: 'foo.md' });
45
+ expect(example.children[0]).toDeepEqual({
46
+ ...any(),
47
+ type: 'heading',
48
+ location: {
49
+ ...any(),
50
+ file: 'foo.md',
51
+ },
52
+ });
53
+ });
54
+ });
55
+
18
56
  describe('handling frontmatter', function () {
19
57
  it('simple frontmatter', function () {
20
58
  const example = convert(`
@@ -55,6 +93,29 @@ describe('Markdown parser', function () {
55
93
  });
56
94
 
57
95
  describe('handling attributes', function () {
96
+ it('for emphasis', function () {
97
+ const items = (doc, n = 0) =>
98
+ doc.children[0].children[0].children[n].attributes.marker;
99
+
100
+ const example1 = convert(`a*b*c`);
101
+ expect(items(example1, 1)).toEqual('*');
102
+
103
+ const example1a = convert(`a**b**c`);
104
+ expect(items(example1a, 1)).toEqual('**');
105
+
106
+ const example2 = convert(`_foo_ bar`);
107
+ expect(items(example2)).toEqual('_');
108
+
109
+ const example2a = convert(`__foo__ bar`);
110
+ expect(items(example2a)).toEqual('__');
111
+
112
+ const example3 = convert(`foo *bar* baz`);
113
+ expect(items(example3, 1)).toEqual('*');
114
+
115
+ const example3a = convert(`foo **bar** baz`);
116
+ expect(items(example3a, 1)).toEqual('**');
117
+ });
118
+
58
119
  it('for heading', function () {
59
120
  const document = convert(`# Sample Heading`);
60
121
  expect(document.children[0].attributes).toDeepEqual({ level: 1 });
@@ -77,6 +138,32 @@ describe('Markdown parser', function () {
77
138
  expect(ordered.children[0].attributes.ordered).toEqual(true);
78
139
  });
79
140
 
141
+ it('for ordered list start', function () {
142
+ const unordered = convert(`
143
+ * Example 1
144
+ * Example 2
145
+ * Example 3
146
+ `);
147
+
148
+ const numbered = convert(`
149
+ 3. Example 1
150
+ 4. Example 2
151
+ 5. Example 3
152
+ `);
153
+
154
+ const numberedStartAtOne = convert(`
155
+ 1. Example 1
156
+ 4. Example 2
157
+ 5. Example 3
158
+ `);
159
+
160
+ const start = (list) => list.children[0].attributes.start;
161
+
162
+ expect(start(unordered)).toEqual(undefined);
163
+ expect(start(numbered)).toEqual(3);
164
+ expect(start(numberedStartAtOne)).toEqual(undefined);
165
+ });
166
+
80
167
  it('for link with one word', function () {
81
168
  const document = convert(`
82
169
  [foo](/bar)
@@ -652,4 +739,34 @@ describe('Markdown parser', function () {
652
739
  ],
653
740
  });
654
741
  });
742
+
743
+ describe('handles structural errors correctly', function () {
744
+ it('with unmatched closing tag', function () {
745
+ const example = convert(`
746
+ {% foo %}
747
+ Test
748
+ {% /bar %}
749
+ `);
750
+
751
+ expect(example.children[0].errors[0].id).toEqual('missing-closing');
752
+ });
753
+
754
+ it('missing opening', function () {
755
+ const example = convert(`
756
+ This a test
757
+ {% /foo %}
758
+ `);
759
+
760
+ expect(example.children[1].errors[0].id).toEqual('missing-opening');
761
+ });
762
+
763
+ it('with missing closing tag', function () {
764
+ const example = convert(`
765
+ {% foo %}
766
+ Test
767
+ `);
768
+
769
+ expect(example.children[0].errors[0].id).toEqual('missing-closing');
770
+ });
771
+ });
655
772
  });
package/src/parser.ts CHANGED
@@ -2,7 +2,7 @@ import Node from './ast/node';
2
2
  import transforms from './transforms/index';
3
3
  import { OPEN } from './utils';
4
4
 
5
- import type { AttributeValue } from './types';
5
+ import type { AttributeValue, ParserArgs } from './types';
6
6
 
7
7
  import type Token from 'markdown-it/lib/token';
8
8
 
@@ -30,8 +30,13 @@ function handleAttrs(token: Token, type: string) {
30
30
  switch (type) {
31
31
  case 'heading':
32
32
  return { level: Number(token.tag.replace('h', '')) };
33
- case 'list':
34
- return { ordered: token.type.startsWith('ordered') };
33
+ case 'list': {
34
+ const attrs = token.attrs ? Object.fromEntries(token.attrs) : undefined;
35
+ const ordered = token.type.startsWith('ordered');
36
+ return ordered && attrs?.start
37
+ ? { ordered: true, start: attrs.start, marker: token.markup }
38
+ : { ordered, marker: token.markup };
39
+ }
35
40
  case 'link': {
36
41
  const attrs = Object.fromEntries(token.attrs);
37
42
  return attrs.title
@@ -44,6 +49,9 @@ function handleAttrs(token: Token, type: string) {
44
49
  ? { alt: token.content, src: attrs.src, title: attrs.title }
45
50
  : { alt: token.content, src: attrs.src };
46
51
  }
52
+ case 'em':
53
+ case 'strong':
54
+ return { marker: token.markup };
47
55
  case 'text':
48
56
  case 'code':
49
57
  case 'comment':
@@ -85,6 +93,7 @@ function handleToken(
85
93
  token: Token,
86
94
  nodes: Node[],
87
95
  file?: string,
96
+ handleSlots?: boolean,
88
97
  inlineParent?: Node
89
98
  ) {
90
99
  if (token.type === 'frontmatter') {
@@ -117,7 +126,7 @@ function handleToken(
117
126
  }
118
127
 
119
128
  if (token.nesting < 0) {
120
- if (parent.type === typeName) {
129
+ if (parent.type === typeName && parent.tag === tag) {
121
130
  if (parent.lines && token.map) parent.lines.push(...token.map);
122
131
  return nodes.pop();
123
132
  }
@@ -152,7 +161,14 @@ function handleToken(
152
161
  if (attributes && ['tag', 'fence', 'image'].includes(typeName))
153
162
  annotate(node, attributes);
154
163
 
155
- parent.push(node);
164
+ if (
165
+ handleSlots &&
166
+ tag === 'slot' &&
167
+ typeof node.attributes.primary === 'string'
168
+ )
169
+ parent.slots[node.attributes.primary] = node;
170
+ else parent.push(node);
171
+
156
172
  if (token.nesting > 0) nodes.push(node);
157
173
 
158
174
  if (!Array.isArray(token.children)) return;
@@ -164,17 +180,20 @@ function handleToken(
164
180
  const isLeafNode = typeName === 'image';
165
181
  if (!isLeafNode) {
166
182
  for (const child of token.children)
167
- handleToken(child, nodes, file, inlineParent);
183
+ handleToken(child, nodes, file, handleSlots, inlineParent);
168
184
  }
169
185
 
170
186
  nodes.pop();
171
187
  }
172
188
 
173
- export default function parser(tokens: Token[], file?: string) {
189
+ export default function parser(tokens: Token[], args?: string | ParserArgs) {
174
190
  const doc = new Node('document');
175
191
  const nodes = [doc];
176
192
 
177
- for (const token of tokens) handleToken(token, nodes, file);
193
+ if (typeof args === 'string') args = { file: args };
194
+
195
+ for (const token of tokens)
196
+ handleToken(token, nodes, args?.file, args?.slots);
178
197
 
179
198
  if (nodes.length > 1)
180
199
  for (const node of nodes.slice(1))
package/src/schema.ts CHANGED
@@ -101,6 +101,8 @@ export const list: Schema = {
101
101
  children: ['item'],
102
102
  attributes: {
103
103
  ordered: { type: Boolean, render: false, required: true },
104
+ start: { type: Number },
105
+ marker: { type: String, render: false },
104
106
  },
105
107
  transform(node, config) {
106
108
  return new Tag(
@@ -166,11 +168,17 @@ export const thead: Schema = {
166
168
  export const strong: Schema = {
167
169
  render: 'strong',
168
170
  children: ['em', 's', 'link', 'code', 'text', 'tag'],
171
+ attributes: {
172
+ marker: { type: String, render: false },
173
+ },
169
174
  };
170
175
 
171
176
  export const em: Schema = {
172
177
  render: 'em',
173
178
  children: ['strong', 's', 'link', 'code', 'text', 'tag'],
179
+ attributes: {
180
+ marker: { type: String, render: false },
181
+ },
174
182
  };
175
183
 
176
184
  export const s: Schema = {
package/src/tags/index.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { tagIf, tagElse } from './conditional';
2
2
  import { partial } from './partial';
3
3
  import { table } from './table';
4
+ import { slot } from './slot';
4
5
 
5
6
  export default {
6
- if: tagIf,
7
7
  else: tagElse,
8
+ if: tagIf,
8
9
  partial,
10
+ slot,
9
11
  table,
10
12
  };
@@ -0,0 +1,7 @@
1
+ import type { Schema } from '../types';
2
+
3
+ export const slot: Schema = {
4
+ attributes: {
5
+ primary: { type: String, required: true },
6
+ },
7
+ };
@@ -47,6 +47,13 @@ export default {
47
47
  output[name] = value;
48
48
  }
49
49
 
50
+ if (schema.slots) {
51
+ for (const [key, slot] of Object.entries(schema.slots)) {
52
+ const name = typeof slot.render === 'string' ? slot.render : key;
53
+ if (node.slots[key]) output[name] = this.node(node.slots[key], config);
54
+ }
55
+ }
56
+
50
57
  return output;
51
58
  },
52
59
 
package/src/types.ts CHANGED
@@ -102,10 +102,12 @@ export type Schema<C extends Config = Config, R = string> = {
102
102
  render?: R;
103
103
  children?: string[];
104
104
  attributes?: Record<string, SchemaAttribute>;
105
+ slots?: Record<string, SchemaSlot>;
105
106
  selfClosing?: boolean;
106
107
  inline?: boolean;
107
108
  transform?(node: Node, config: C): MaybePromise<RenderableTreeNodes>;
108
109
  validate?(node: Node, config: C): MaybePromise<ValidationError[]>;
110
+ description?: string;
109
111
  };
110
112
 
111
113
  export type SchemaAttribute = {
@@ -114,11 +116,18 @@ export type SchemaAttribute = {
114
116
  default?: any;
115
117
  required?: boolean;
116
118
  matches?: SchemaMatches | ((config: Config) => SchemaMatches);
119
+ validate?(value: any, config: Config): ValidationError[];
117
120
  errorLevel?: ValidationError['level'];
121
+ description?: string;
118
122
  };
119
123
 
120
124
  export type SchemaMatches = RegExp | string[] | null;
121
125
 
126
+ export type SchemaSlot = {
127
+ render?: boolean | string;
128
+ required?: boolean;
129
+ };
130
+
122
131
  export interface Transformer {
123
132
  findSchema(node: Node, config: Config): Schema | undefined;
124
133
  node(node: Node, config: Config): MaybePromise<RenderableTreeNodes>;
@@ -154,3 +163,8 @@ export type ValidationType =
154
163
  | 'Array';
155
164
 
156
165
  export type Value = AstType | Scalar;
166
+
167
+ export type ParserArgs = {
168
+ file?: string;
169
+ slots?: boolean;
170
+ };
@@ -289,6 +289,44 @@ bar
289
289
  });
290
290
 
291
291
  describe('attribute validation', () => {
292
+ describe('with a validate function', () => {
293
+ it('using simple conditional', () => {
294
+ const schema = {
295
+ tags: {
296
+ foo: {
297
+ attributes: {
298
+ bar: {
299
+ type: Number,
300
+ validate(value, _config) {
301
+ return value > 10
302
+ ? []
303
+ : [
304
+ {
305
+ id: 'attribute-should-be-greater-than-ten',
306
+ message:
307
+ 'Attribute "bar" must have value greater than 10.',
308
+ },
309
+ ];
310
+ },
311
+ },
312
+ },
313
+ },
314
+ },
315
+ };
316
+
317
+ expect(validate(`{% foo bar=20 /%}`, schema)).toEqual([]);
318
+ expect(validate(`{% foo bar=5 /%}`, schema)).toDeepEqualSubset([
319
+ {
320
+ type: 'tag',
321
+ error: {
322
+ id: 'attribute-should-be-greater-than-ten',
323
+ message: 'Attribute "bar" must have value greater than 10.',
324
+ },
325
+ },
326
+ ]);
327
+ });
328
+ });
329
+
292
330
  it('should return error on failure to match array', () => {
293
331
  const example = '{% foo jawn="cat" /%}';
294
332
  const schema = {
@@ -315,6 +353,33 @@ bar
315
353
  ]);
316
354
  });
317
355
 
356
+ it('Elides excess values in matches check', () => {
357
+ const example = '{% foo jawn="cat" /%}';
358
+ const schema = {
359
+ tags: {
360
+ foo: {
361
+ attributes: {
362
+ jawn: {
363
+ type: String,
364
+ matches: Array.from('foobarbazqux'),
365
+ },
366
+ },
367
+ },
368
+ },
369
+ };
370
+
371
+ const output = validate(example, schema);
372
+ expect(output).toDeepEqualSubset([
373
+ {
374
+ type: 'tag',
375
+ error: {
376
+ id: 'attribute-value-invalid',
377
+ message: `Attribute 'jawn' must match one of ["f","o","o","b","a","r","b","a", ... 4 more]. Got 'cat' instead.`,
378
+ },
379
+ },
380
+ ]);
381
+ });
382
+
318
383
  // https://github.com/markdoc/markdoc/issues/122
319
384
  it('should validate partial file attributes', () => {
320
385
  const example = `{% partial file="non-existent.md" /%}`;
package/src/validator.ts CHANGED
@@ -121,6 +121,12 @@ function validateFunction(fn: Function, config: Config): ValidationError[] {
121
121
  return errors;
122
122
  }
123
123
 
124
+ function displayMatches(matches: any[], n: number) {
125
+ if (matches.length <= n) return JSON.stringify(matches);
126
+ const items = matches.slice(0, n).map((item) => JSON.stringify(item));
127
+ return `[${items.join(',')}, ... ${matches.length - n} more]`;
128
+ }
129
+
124
130
  export default function validator(node: Node, config: Config) {
125
131
  const schema = node.findSchema(config);
126
132
  const errors: ValidationError[] = [...(node.errors || [])];
@@ -158,6 +164,16 @@ export default function validator(node: Node, config: Config) {
158
164
  ...schema.attributes,
159
165
  };
160
166
 
167
+ for (const key of Object.keys(node.slots)) {
168
+ const slot = schema.slots?.[key];
169
+ if (!slot)
170
+ errors.push({
171
+ id: 'slot-undefined',
172
+ level: 'error',
173
+ message: `Invalid slot: '${key}'`,
174
+ });
175
+ }
176
+
161
177
  for (let [key, value] of Object.entries(node.attributes)) {
162
178
  const attrib = attributes[key];
163
179
 
@@ -220,8 +236,9 @@ export default function validator(node: Node, config: Config) {
220
236
  errors.push({
221
237
  id: 'attribute-value-invalid',
222
238
  level: errorLevel || 'error',
223
- message: `Attribute '${key}' must match one of ${JSON.stringify(
224
- matches
239
+ message: `Attribute '${key}' must match one of ${displayMatches(
240
+ matches,
241
+ 8
225
242
  )}. Got '${value}' instead.`,
226
243
  });
227
244
 
@@ -231,6 +248,11 @@ export default function validator(node: Node, config: Config) {
231
248
  level: errorLevel || 'error',
232
249
  message: `Attribute '${key}' must match ${matches}. Got '${value}' instead.`,
233
250
  });
251
+
252
+ if (typeof attrib.validate === 'function') {
253
+ const attribErrors = attrib.validate(value, config);
254
+ if (Array.isArray(attribErrors)) errors.push(...attribErrors);
255
+ }
234
256
  }
235
257
 
236
258
  for (const [key, { required }] of Object.entries(attributes))
@@ -241,6 +263,15 @@ export default function validator(node: Node, config: Config) {
241
263
  message: `Missing required attribute: '${key}'`,
242
264
  });
243
265
 
266
+ if (schema.slots)
267
+ for (const [key, { required }] of Object.entries(schema.slots))
268
+ if (required && node.slots[key] === undefined)
269
+ errors.push({
270
+ id: 'slot-missing-required',
271
+ level: 'error',
272
+ message: `Missing required slot: '${key}'`,
273
+ });
274
+
244
275
  for (const { type } of node.children) {
245
276
  if (schema.children && type !== 'error' && !schema.children.includes(type))
246
277
  errors.push({