@markdoc/markdoc 0.5.11 → 0.5.13

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 (48) hide show
  1. package/README.md +43 -13
  2. package/dist/index.d.ts +21 -20
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +86 -62
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.mjs +86 -62
  7. package/dist/index.mjs.map +4 -4
  8. package/dist/react.js +5 -4
  9. package/dist/react.js.map +2 -2
  10. package/dist/src/ast/base.d.ts.map +1 -1
  11. package/dist/src/parser.d.ts.map +1 -1
  12. package/dist/src/renderers/react/react.d.ts.map +1 -1
  13. package/dist/src/tokenizer/index.d.ts +16 -7
  14. package/dist/src/tokenizer/index.d.ts.map +1 -1
  15. package/dist/src/tokenizer/plugins/annotations.d.ts +2 -2
  16. package/dist/src/tokenizer/plugins/annotations.d.ts.map +1 -1
  17. package/dist/src/tokenizer/plugins/comments.d.ts +2 -2
  18. package/dist/src/tokenizer/plugins/comments.d.ts.map +1 -1
  19. package/dist/src/tokenizer/plugins/frontmatter.d.ts +2 -2
  20. package/dist/src/tokenizer/plugins/frontmatter.d.ts.map +1 -1
  21. package/dist/src/tokenizer/plugins/link.d.ts +3 -3
  22. package/dist/src/tokenizer/plugins/link.d.ts.map +1 -1
  23. package/dist/src/transformer.d.ts.map +1 -1
  24. package/dist/src/validator.d.ts.map +1 -1
  25. package/index.ts +1 -0
  26. package/package.json +35 -44
  27. package/src/ast/base.ts +19 -4
  28. package/src/ast/node.test.ts +76 -0
  29. package/src/ast/node.ts +1 -1
  30. package/src/grammar/tag.d.ts +1 -3
  31. package/src/grammar/tag.js +4 -4
  32. package/src/grammar/tag.pegjs +4 -4
  33. package/src/grammar/tag.test.ts +28 -0
  34. package/src/parser.test.ts +35 -0
  35. package/src/parser.ts +10 -1
  36. package/src/renderers/react/react.test.ts +11 -0
  37. package/src/renderers/react/react.ts +12 -10
  38. package/src/renderers/react/static.ts +4 -4
  39. package/src/tag.ts +1 -1
  40. package/src/tokenizer/index.ts +22 -9
  41. package/src/tokenizer/plugins/annotations.ts +11 -7
  42. package/src/tokenizer/plugins/comments.ts +4 -4
  43. package/src/tokenizer/plugins/frontmatter.ts +5 -5
  44. package/src/tokenizer/plugins/link.ts +4 -7
  45. package/src/transformer.ts +4 -2
  46. package/src/validator.test.ts +174 -1
  47. package/src/validator.ts +10 -4
  48. package/spec/marktest/index.ts +0 -136
@@ -1,5 +1,5 @@
1
1
  import Tag from '../../tag';
2
- import { RenderableTreeNodes, Scalar } from '../../types';
2
+ import { RenderableTreeNodes } from '../../types';
3
3
 
4
4
  import type { createElement, ComponentType, Fragment, ReactNode } from 'react';
5
5
 
@@ -17,10 +17,10 @@ function tagName(
17
17
  return typeof name !== 'string'
18
18
  ? name // This can be an object, e.g. when React.forwardRef is used
19
19
  : name[0] !== name[0].toUpperCase()
20
- ? name
21
- : components instanceof Function
22
- ? components(name)
23
- : components[name];
20
+ ? name
21
+ : components instanceof Function
22
+ ? components(name)
23
+ : components[name];
24
24
  }
25
25
 
26
26
  export type RenderOpts = {
@@ -41,17 +41,19 @@ export default function dynamic(
41
41
 
42
42
  if (typeof value !== 'object') return value;
43
43
 
44
- const output: Record<string, Scalar> = {};
45
- for (const [k, v] of Object.entries(value)) output[k] = deepRender(v);
46
- return output;
44
+ return Object.fromEntries(
45
+ Object.entries(value).map(([k, v]) => [k, deepRender(v)])
46
+ );
47
47
  }
48
48
 
49
49
  function render(node: RenderableTreeNodes): ReactNode {
50
50
  if (Array.isArray(node))
51
51
  return React.createElement(React.Fragment, null, ...node.map(render));
52
52
 
53
- if (node === null || typeof node !== 'object' || !Tag.isTag(node))
54
- return node;
53
+ if (node === null || typeof node !== 'object' || !Tag.isTag(node)) {
54
+ // Preserve passthrough values from custom transforms, including React elements.
55
+ return node as ReactNode;
56
+ }
55
57
 
56
58
  const {
57
59
  name,
@@ -12,10 +12,10 @@ function tagName(
12
12
  return typeof name !== 'string'
13
13
  ? 'Fragment'
14
14
  : name[0] !== name[0].toUpperCase()
15
- ? name
16
- : components instanceof Function
17
- ? components(name)
18
- : components[name];
15
+ ? name
16
+ : components instanceof Function
17
+ ? components(name)
18
+ : components[name];
19
19
  }
20
20
 
21
21
  function renderArray(children: RenderableTreeNode[]): string {
package/src/tag.ts CHANGED
@@ -2,7 +2,7 @@ import type { RenderableTreeNode } from './types';
2
2
 
3
3
  export default class Tag<
4
4
  N extends string = string,
5
- A extends Record<string, any> = Record<string, any>
5
+ A extends Record<string, any> = Record<string, any>,
6
6
  > {
7
7
  readonly $$mdtype = 'Tag' as const;
8
8
 
@@ -1,4 +1,5 @@
1
1
  import MarkdownIt from 'markdown-it';
2
+ import type { MarkdownIt as MarkdownItParser } from 'markdown-it';
2
3
  import annotations from './plugins/annotations';
3
4
  import frontmatter from './plugins/frontmatter';
4
5
  import comments from './plugins/comments';
@@ -7,17 +8,29 @@ import type { Token } from '../types';
7
8
 
8
9
  export type LinkPluginOptions = { validatedProtocols: string[] };
9
10
 
11
+ // Keep public options independent of the bundled parser's type dependencies.
12
+ // spec/types/tokenizer-options.ts checks compatibility with markdown-it.
13
+ export type TokenizerOptions = {
14
+ html?: boolean;
15
+ xhtmlOut?: boolean;
16
+ breaks?: boolean;
17
+ langPrefix?: string;
18
+ linkify?: boolean;
19
+ typographer?: boolean;
20
+ quotes?: string | string[];
21
+ highlight?:
22
+ ((content: string, language: string, attributes: string) => string) | null;
23
+ maxNesting?: number;
24
+ allowIndentation?: boolean;
25
+ allowComments?: boolean;
26
+ allowLinkValidation?: boolean;
27
+ linkValidationOptions?: LinkPluginOptions;
28
+ };
29
+
10
30
  export default class Tokenizer {
11
- private parser: MarkdownIt.MarkdownIt;
31
+ private parser: MarkdownItParser;
12
32
 
13
- constructor(
14
- config: MarkdownIt.MarkdownItOptions & {
15
- allowIndentation?: boolean;
16
- allowComments?: boolean;
17
- allowLinkValidation?: boolean;
18
- linkValidationOptions?: LinkPluginOptions;
19
- } = {}
20
- ) {
33
+ constructor(config: TokenizerOptions = {}) {
21
34
  this.parser = new MarkdownIt(config);
22
35
  this.parser.use(annotations);
23
36
  this.parser.use(frontmatter);
@@ -4,13 +4,17 @@ import Variable from '../../ast/variable';
4
4
  import Function from '../../ast/function';
5
5
 
6
6
  import type { AttributeValue, Token } from '../../types';
7
- import type MarkdownIt from 'markdown-it';
7
+ import type {
8
+ Delimiter,
9
+ MarkdownIt,
10
+ StateBlock,
11
+ StateInline,
12
+ StateCore,
13
+ Token as MarkdownItToken,
14
+ } from 'markdown-it';
8
15
 
9
- type StateBlock = MarkdownIt.StateBlock;
10
- type StateInline = MarkdownIt.StateInline;
11
- type StateCore = MarkdownIt.StateCore;
12
16
  type StateWithDelimiters = (StateBlock | StateInline) & {
13
- delimiters?: MarkdownIt.Delimiter[];
17
+ delimiters?: Delimiter[];
14
18
  };
15
19
  // FenceToken combines markdown-it and Markdoc token types, using the more
16
20
  // specific markdown-it type for fields it defines (e.g. `info`, `content`,
@@ -18,7 +22,7 @@ type StateWithDelimiters = (StateBlock | StateInline) & {
18
22
  // (`errors`, `children`, `meta`). Previously we used module augmentation
19
23
  // (global.d.ts) to extend markdown-it's Token directly, but markdown-it 15
20
24
  // no longer exposes an augmentable module path for it.
21
- type FenceToken = Omit<MarkdownIt.Token, 'children' | 'meta'> &
25
+ type FenceToken = Omit<MarkdownItToken, 'children' | 'meta'> &
22
26
  Pick<Token, 'errors' | 'children' | 'meta'>;
23
27
 
24
28
  function createToken(
@@ -147,7 +151,7 @@ function core(state: StateCore) {
147
151
  }
148
152
  }
149
153
 
150
- export default function plugin(md: MarkdownIt.MarkdownIt /* options */) {
154
+ export default function plugin(md: MarkdownIt /* options */) {
151
155
  md.block.ruler.before('paragraph', 'annotations', block, {
152
156
  alt: ['paragraph', 'blockquote'],
153
157
  });
@@ -1,10 +1,10 @@
1
- import type MarkdownIt from 'markdown-it';
1
+ import type { MarkdownIt, StateBlock, StateInline } from 'markdown-it';
2
2
 
3
3
  const OPEN = '<!--';
4
4
  const CLOSE = '-->';
5
5
 
6
6
  function block(
7
- state: MarkdownIt.StateBlock,
7
+ state: StateBlock,
8
8
  startLine: number,
9
9
  endLine: number,
10
10
  silent: boolean
@@ -27,7 +27,7 @@ function block(
27
27
  return true;
28
28
  }
29
29
 
30
- function inline(state: MarkdownIt.StateInline, silent: boolean): boolean {
30
+ function inline(state: StateInline, silent: boolean): boolean {
31
31
  if (!state.src.startsWith(OPEN, state.pos)) return false;
32
32
 
33
33
  const close = state.src.indexOf(CLOSE, state.pos);
@@ -43,7 +43,7 @@ function inline(state: MarkdownIt.StateInline, silent: boolean): boolean {
43
43
  return true;
44
44
  }
45
45
 
46
- export default function plugin(md: MarkdownIt.MarkdownIt) {
46
+ export default function plugin(md: MarkdownIt) {
47
47
  md.block.ruler.before('table', 'comment', block, { alt: ['paragraph'] });
48
48
  md.inline.ruler.push('comment', inline);
49
49
  }
@@ -1,18 +1,18 @@
1
- import type MarkdownIt from 'markdown-it';
1
+ import type { MarkdownIt, StateBlock } from 'markdown-it';
2
2
 
3
3
  const fence = '---';
4
4
 
5
- function getLine(state: MarkdownIt.StateBlock, n: number) {
5
+ function getLine(state: StateBlock, n: number) {
6
6
  return state.src.slice(state.bMarks[n], state.eMarks[n]).trim();
7
7
  }
8
8
 
9
- function findClose(state: MarkdownIt.StateBlock, endLine: number) {
9
+ function findClose(state: StateBlock, endLine: number) {
10
10
  for (let line = 1; line < endLine; line++)
11
11
  if (getLine(state, line) === fence) return line;
12
12
  }
13
13
 
14
14
  function block(
15
- state: MarkdownIt.StateBlock,
15
+ state: StateBlock,
16
16
  startLine: number,
17
17
  endLine: number,
18
18
  silent: boolean
@@ -33,6 +33,6 @@ function block(
33
33
  return true;
34
34
  }
35
35
 
36
- export default function plugin(md: MarkdownIt.MarkdownIt /* options */) {
36
+ export default function plugin(md: MarkdownIt /* options */) {
37
37
  md.block.ruler.before('hr', 'frontmatter', block);
38
38
  }
@@ -1,8 +1,8 @@
1
- import type MarkdownIt from 'markdown-it';
1
+ import type { MarkdownIt, StateCore } from 'markdown-it';
2
2
  import type { Token } from '../../types';
3
3
 
4
4
  import { containsMarkdocTagInUrl } from '../../utils';
5
- import { LinkPluginOptions } from '..';
5
+ import type { LinkPluginOptions } from '..';
6
6
 
7
7
  const INVALID_HREF_MESSAGE =
8
8
  "The 'href' format cannot contain Markdoc tag or variable. URLs must be static strings.";
@@ -16,7 +16,7 @@ function pushHrefError(token: Token) {
16
16
  });
17
17
  }
18
18
 
19
- function core(state: MarkdownIt.StateCore, options: LinkPluginOptions) {
19
+ function core(state: StateCore, options: LinkPluginOptions) {
20
20
  let token: Token;
21
21
  for (token of state.tokens) {
22
22
  if (token.type !== 'inline' || typeof token.content !== 'string') continue;
@@ -27,9 +27,6 @@ function core(state: MarkdownIt.StateCore, options: LinkPluginOptions) {
27
27
  }
28
28
  }
29
29
 
30
- export default function plugin(
31
- md: MarkdownIt.MarkdownIt,
32
- options: LinkPluginOptions
33
- ) {
30
+ export default function plugin(md: MarkdownIt, options: LinkPluginOptions) {
34
31
  md.core.ruler.push('link_url_validation', (state) => core(state, options));
35
32
  }
@@ -26,7 +26,7 @@ export default {
26
26
 
27
27
  attributes(node: Node, config: Config = {}) {
28
28
  const schema = this.findSchema(node, config) ?? {};
29
- const output: Record<string, any> = {};
29
+ const output: Record<string, any> = Object.create(null);
30
30
 
31
31
  const attrs = { ...globalAttributes, ...schema.attributes };
32
32
  for (const [key, attr] of Object.entries(attrs)) {
@@ -34,7 +34,9 @@ export default {
34
34
 
35
35
  const name = typeof attr.render === 'string' ? attr.render : key;
36
36
 
37
- let value = node.attributes[key];
37
+ let value = Object.prototype.hasOwnProperty.call(node.attributes, key)
38
+ ? node.attributes[key]
39
+ : undefined;
38
40
  if (typeof attr.type === 'function') {
39
41
  const instance: any = new attr.type();
40
42
  if (instance.transform) {
@@ -1,4 +1,4 @@
1
- import Markdoc, { nodes } from '../index';
1
+ import Markdoc, { Node, Tag, nodes } from '../index';
2
2
  import type { Config, ValidationError } from './types';
3
3
 
4
4
  function validate(string, config) {
@@ -6,6 +6,179 @@ function validate(string, config) {
6
6
  }
7
7
 
8
8
  describe('validate', function () {
9
+ describe('prototype-safe attributes', function () {
10
+ let config: Config;
11
+ let customValidate: jasmine.Spy;
12
+ const unsafe = 'javascript:alert(1)';
13
+ const trusted = 'https://trusted.example/embed';
14
+ const React = {
15
+ Fragment: 'fragment',
16
+ createElement(name, attributes, ...children) {
17
+ return { name, attributes, children };
18
+ },
19
+ };
20
+
21
+ beforeEach(function () {
22
+ customValidate = jasmine.createSpy('validate').and.callFake((value) =>
23
+ value === trusted
24
+ ? []
25
+ : [
26
+ {
27
+ id: 'untrusted-src',
28
+ level: 'critical',
29
+ message: 'Untrusted URL',
30
+ },
31
+ ]
32
+ );
33
+ config = {
34
+ tags: {
35
+ embed: {
36
+ render: 'iframe',
37
+ selfClosing: true,
38
+ attributes: {
39
+ src: {
40
+ type: String,
41
+ required: true,
42
+ matches: /^https:\/\/trusted\.example\//,
43
+ errorLevel: 'critical',
44
+ validate: customValidate,
45
+ },
46
+ },
47
+ },
48
+ },
49
+ };
50
+ });
51
+
52
+ it('validates direct values with the pattern and custom validator', function () {
53
+ const ast = Markdoc.parse(`{% embed src="${unsafe}" /%}`);
54
+ expect(Markdoc.validate(ast, config)).toDeepEqualSubset([
55
+ { error: { id: 'attribute-value-invalid', level: 'critical' } },
56
+ { error: { id: 'untrusted-src', level: 'critical' } },
57
+ ]);
58
+ expect(customValidate).toHaveBeenCalledWith(
59
+ unsafe,
60
+ jasmine.anything(),
61
+ 'src'
62
+ );
63
+ });
64
+
65
+ it('enforces the URL schema when only errors and critical findings block rendering', function () {
66
+ delete config.tags!.embed.attributes!.src.validate;
67
+ const render = (source: string) => {
68
+ const ast = Markdoc.parse(source);
69
+ const findings = Markdoc.validate(ast, config);
70
+ if (
71
+ findings.some(({ error }) =>
72
+ ['error', 'critical'].includes(error.level)
73
+ )
74
+ )
75
+ return null;
76
+ return Markdoc.renderers.html(Markdoc.transform(ast, config));
77
+ };
78
+
79
+ expect(render(`{% embed src="${unsafe}" /%}`)).toBeNull();
80
+ expect(render(`{% embed __proto__={src:"${unsafe}"} /%}`)).toBeNull();
81
+ expect(render(`{% embed src="${trusted}" /%}`)).toBe(
82
+ `<article><iframe src="${trusted}"></iframe></article>`
83
+ );
84
+ });
85
+
86
+ it('blocks prototype attribute smuggling before rendering', function () {
87
+ const ast = Markdoc.parse(`{% embed __proto__={src:"${unsafe}"} /%}`);
88
+ expect(Markdoc.validate(ast, config)).toDeepEqualSubset([
89
+ { error: { id: 'attribute-name-invalid', level: 'critical' } },
90
+ { error: { id: 'attribute-missing-required', level: 'error' } },
91
+ ]);
92
+ expect(customValidate).not.toHaveBeenCalled();
93
+ expect(Object.keys(ast.children[0].attributes)).toEqual([]);
94
+ const output = Markdoc.transform(ast.children[0], config);
95
+ expect(Markdoc.renderers.html(output)).toBe('<iframe></iframe>');
96
+ expect(Markdoc.renderers.react(output, React)).toDeepEqual({
97
+ name: 'iframe',
98
+ attributes: null,
99
+ children: [],
100
+ });
101
+ });
102
+
103
+ it('still applies type validation to own values', function () {
104
+ const ast = Markdoc.parse('{% embed src=42 /%}');
105
+ expect(Markdoc.validate(ast, config)).toDeepEqualSubset([
106
+ { error: { id: 'attribute-type-invalid', level: 'critical' } },
107
+ { error: { id: 'attribute-value-invalid', level: 'critical' } },
108
+ { error: { id: 'untrusted-src', level: 'critical' } },
109
+ ]);
110
+ });
111
+
112
+ it('validates an unsafe own value despite a smuggling attempt', function () {
113
+ const ast = Markdoc.parse(
114
+ `{% embed __proto__={src:"${trusted}"} src="${unsafe}" /%}`
115
+ );
116
+ expect(Markdoc.validate(ast, config)).toDeepEqualSubset([
117
+ { error: { id: 'attribute-name-invalid', level: 'critical' } },
118
+ { error: { id: 'attribute-value-invalid', level: 'critical' } },
119
+ { error: { id: 'untrusted-src', level: 'critical' } },
120
+ ]);
121
+ expect(customValidate).toHaveBeenCalledWith(
122
+ unsafe,
123
+ jasmine.anything(),
124
+ 'src'
125
+ );
126
+ });
127
+
128
+ it('validates and renders an own value despite a smuggling attempt', function () {
129
+ const ast = Markdoc.parse(
130
+ `{% embed __proto__={src:"${unsafe}"} src="${trusted}" /%}`
131
+ );
132
+ expect(Markdoc.validate(ast, config)).toDeepEqualSubset([
133
+ { error: { id: 'attribute-name-invalid', level: 'critical' } },
134
+ ]);
135
+ expect(customValidate).toHaveBeenCalledWith(
136
+ trusted,
137
+ jasmine.anything(),
138
+ 'src'
139
+ );
140
+ expect(
141
+ Markdoc.renderers.html(Markdoc.transform(ast.children[0], config))
142
+ ).toBe(`<iframe src="${trusted}"></iframe>`);
143
+ });
144
+
145
+ it('ignores inherited attributes on a programmatically modified node', function () {
146
+ const node = new Node('tag', {}, [], 'embed');
147
+ node.attributes = Object.create({ src: unsafe });
148
+ expect(Markdoc.validate(node, config)).toDeepEqualSubset([
149
+ { error: { id: 'attribute-missing-required', level: 'error' } },
150
+ ]);
151
+ expect(node.transformAttributes(config).src).toBeUndefined();
152
+ expect(Markdoc.renderers.html(Markdoc.transform(node, config))).toBe(
153
+ '<iframe></iframe>'
154
+ );
155
+ });
156
+
157
+ it('applies defaults instead of inherited values', function () {
158
+ config.tags!.embed.attributes!.src.default = trusted;
159
+ const node = new Node('tag', {}, [], 'embed');
160
+ node.attributes = Object.create({ src: unsafe });
161
+ expect(node.transformAttributes(config).src).toBe(trusted);
162
+ });
163
+
164
+ it('rejects undeclared attributes whose names exist on Object.prototype', function () {
165
+ const ast = Markdoc.parse('{% embed toString="value" /%}');
166
+ expect(Markdoc.validate(ast, config)).toDeepEqualSubset([
167
+ { error: { id: 'attribute-undefined', level: 'error' } },
168
+ { error: { id: 'attribute-missing-required', level: 'error' } },
169
+ ]);
170
+ });
171
+
172
+ it('resolves variables in prototype-free attribute dictionaries', function () {
173
+ config.variables = { url: trusted };
174
+ const ast = Markdoc.parse('{% embed src=$url /%}');
175
+ expect(Markdoc.validate(ast.resolve(config), config)).toEqual([]);
176
+ expect(Markdoc.transform(ast.children[0], config)).toDeepEqual(
177
+ new Tag('iframe', { src: trusted })
178
+ );
179
+ });
180
+ });
181
+
9
182
  describe('function validation', function () {
10
183
  it('ensures that function exists', function () {
11
184
  const example = '{% foo bar=baz() /%}';
package/src/validator.ts CHANGED
@@ -36,8 +36,8 @@ export function validateType(
36
36
  return !schema?.returns
37
37
  ? true
38
38
  : Array.isArray(schema.returns)
39
- ? schema.returns.find((t) => t === type) !== undefined
40
- : schema.returns === type;
39
+ ? schema.returns.find((t) => t === type) !== undefined
40
+ : schema.returns === type;
41
41
  }
42
42
 
43
43
  if (Ast.isAst(value)) return true;
@@ -178,7 +178,9 @@ export default function validator(node: Node, config: Config) {
178
178
  }
179
179
 
180
180
  for (let [key, value] of Object.entries(node.attributes)) {
181
- const attrib = attributes[key];
181
+ const attrib = Object.prototype.hasOwnProperty.call(attributes, key)
182
+ ? attributes[key]
183
+ : undefined;
182
184
 
183
185
  if (!attrib) {
184
186
  errors.push({
@@ -259,7 +261,11 @@ export default function validator(node: Node, config: Config) {
259
261
  }
260
262
 
261
263
  for (const [key, { required }] of Object.entries(attributes))
262
- if (required && node.attributes[key] === undefined)
264
+ if (
265
+ required &&
266
+ (!Object.prototype.hasOwnProperty.call(node.attributes, key) ||
267
+ node.attributes[key] === undefined)
268
+ )
263
269
  errors.push({
264
270
  id: 'attribute-missing-required',
265
271
  level: 'error',
@@ -1,136 +0,0 @@
1
- import { promises as fs } from 'fs';
2
- import { resolve } from 'path';
3
- import { diffJson, diffChars } from 'diff';
4
- import yaml from 'yaml-js';
5
-
6
- import markdoc from '../../index';
7
- import React from './react-shim';
8
-
9
- class Loader extends yaml.loader.Loader {
10
- construct_mapping(node) {
11
- return {
12
- ...super.construct_mapping(node),
13
- $$lines: {
14
- start: node.start_mark.line,
15
- end: node.end_mark.line,
16
- },
17
- };
18
- }
19
- }
20
-
21
- const tokenizer = new markdoc.Tokenizer({
22
- allowIndentation: true,
23
- allowComments: true,
24
- });
25
-
26
- function parse(content: string, slots?: boolean, file?: string) {
27
- const tokens = tokenizer.tokenize(content);
28
- return markdoc.parse(tokens, { file, slots });
29
- }
30
-
31
- function stripLines(object) {
32
- const removeLines = (key, value) => (key === '$$lines' ? undefined : value);
33
- return JSON.parse(JSON.stringify(object, removeLines));
34
- }
35
-
36
- function render(code, config, dynamic) {
37
- const partials = {};
38
- for (const [file, content] of Object.entries(config.partials ?? {}))
39
- partials[file] = parse(content as string, false, file);
40
-
41
- const { react, reactStatic } = markdoc.renderers;
42
- const transformed = markdoc.transform(code, { ...config, partials });
43
- return dynamic ? react(transformed, React) : eval(reactStatic(transformed));
44
- }
45
-
46
- function checkMatch(diffs) {
47
- return diffs.find((diff) => diff.added || diff.removed);
48
- }
49
-
50
- function run(
51
- { code = null, renderer = 'react', config = {}, expected = undefined } = {},
52
- dynamic
53
- ) {
54
- if (renderer === 'html') {
55
- const transformed = markdoc.transform(code, config);
56
- const output = markdoc.renderers.html(transformed);
57
- const diff = diffChars((expected || '').trim(), (output || '').trim());
58
- return checkMatch(diff) ? diff : false;
59
- }
60
-
61
- const output = render(code, config, dynamic) || {};
62
- const diff = diffJson(expected || {}, output.children || []);
63
- return checkMatch(diff) ? diff : false;
64
- }
65
-
66
- function formatter(filename, { $$lines: lines, name, code }, diff) {
67
- const prettyDiff = diff
68
- .flatMap((part) => [
69
- part.added ? '\x1b[32m' : part.removed ? '\x1b[31m' : '\x1b[0m',
70
- part.added || part.removed ? part.value.replace(/ /g, '⎵') : part.value,
71
- ])
72
- .join('');
73
-
74
- return [
75
- `\x1b[31mFAILED:\x1b[0m ${filename}:${lines.start}`,
76
- name,
77
- code,
78
- prettyDiff,
79
- ].join('\n\n');
80
- }
81
-
82
- function formatValidation(filename, test, validation) {
83
- const { $$lines: lines, name, code } = test;
84
-
85
- let output = '';
86
- for (const {
87
- lines,
88
- error: { message },
89
- } of validation)
90
- output += `${lines ? lines[0] : '?'}:${message}\n`;
91
-
92
- return [
93
- `\x1b[31mINVALID:\x1b[0m ${filename}:${lines.start}`,
94
- name,
95
- code,
96
- output,
97
- ].join('\n\n');
98
- }
99
-
100
- (async () => {
101
- const [filename, line] = process.argv.slice(2).join('').split(':');
102
- const path = resolve(filename);
103
- const file = await fs.readFile(path);
104
- const tests = yaml.load(file, Loader);
105
-
106
- let exitCode = 0;
107
- for (const test of tests) {
108
- const code = parse(test.code || '', test.slots);
109
-
110
- const { start, end } = test.$$lines;
111
- if (line && (Number(line) - 1 < start || Number(line) - 1 > end)) continue;
112
-
113
- const validation = markdoc.validate(code, test.config);
114
-
115
- let result;
116
- if (test.expectedError) {
117
- const output = validation.map((v) => v.error.message).join('\n');
118
- const diff = diffChars(
119
- (test.expectedError || '').trim(),
120
- (output || '').trim()
121
- );
122
-
123
- result = checkMatch(diff) ? diff : false;
124
- } else {
125
- if (validation.length && test.validation != false)
126
- console.log(formatValidation(path, test, validation));
127
-
128
- result = run({ ...stripLines(test), code }, true);
129
- }
130
-
131
- if (!result) continue;
132
- console.log(formatter(path, test, result));
133
- exitCode = 1;
134
- }
135
- process.exit(exitCode);
136
- })();