@mintlify/common 1.0.363 → 1.0.365

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.
@@ -0,0 +1,7 @@
1
+ import type { Root } from 'mdast';
2
+ /**
3
+ * Removes the YAML frontmatter node from an AST (Root) if it exists as the first child.
4
+ * Modifies the tree in place.
5
+ * @param tree The Root node of the document.
6
+ */
7
+ export declare const removeFrontmatterFromAST: (tree: Root) => void;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Removes the YAML frontmatter node from an AST (Root) if it exists as the first child.
3
+ * Modifies the tree in place.
4
+ * @param tree The Root node of the document.
5
+ */
6
+ export const removeFrontmatterFromAST = (tree) => {
7
+ var _a;
8
+ if (tree.children.length > 0 && ((_a = tree.children[0]) === null || _a === void 0 ? void 0 : _a.type) === 'yaml') {
9
+ tree.children.shift();
10
+ }
11
+ };
@@ -4,3 +4,4 @@ export * from './utils.js';
4
4
  export * from './plugins/index.js';
5
5
  export * from './lib/index.js';
6
6
  export * from './getMDXOptions.js';
7
+ export * from './astUtils.js';
package/dist/mdx/index.js CHANGED
@@ -4,3 +4,4 @@ export * from './utils.js';
4
4
  export * from './plugins/index.js';
5
5
  export * from './lib/index.js';
6
6
  export * from './getMDXOptions.js';
7
+ export * from './astUtils.js';
@@ -1,2 +1,2 @@
1
1
  import type { Root } from 'mdast';
2
- export declare const remarkMdxRemoveUnknownJsx: (allowedComponents?: string[]) => (tree: Root) => Root | import("mdast-util-mdxjs-esm").MdxjsEsm | import("mdast-util-mdx-expression").MdxFlowExpression | import("mdast-util-mdx-expression").MdxTextExpression | import("mdast").Link | import("mdast").Delete | import("mdast").Yaml | import("mdast-util-mdx").MdxJsxFlowElement | import("mdast").Blockquote | import("mdast").Break | import("mdast").Code | import("mdast").Definition | import("mdast").Emphasis | import("mdast").FootnoteDefinition | import("mdast").FootnoteReference | import("mdast").Heading | import("mdast").Html | import("mdast").Image | import("mdast").ImageReference | import("mdast").InlineCode | import("mdast").LinkReference | import("mdast").List | import("mdast").ListItem | import("mdast").Paragraph | import("mdast").Strong | import("mdast").Table | import("mdast").TableCell | import("mdast").TableRow | import("mdast").Text | import("mdast").ThematicBreak | import("mdast-util-math").InlineMath | import("mdast-util-math").Math | import("mdast-util-mdx").MdxJsxTextElement;
2
+ export declare const remarkMdxRemoveUnknownJsx: (allowedComponents?: string[]) => (tree: Root) => Root | import("mdast-util-mdxjs-esm").MdxjsEsm | import("mdast-util-mdx-expression").MdxFlowExpression | import("mdast-util-mdx-expression").MdxTextExpression | import("mdast").Link | import("mdast").Delete | import("mdast").Yaml | import("mdast").Emphasis | import("mdast").Strong | import("mdast-util-mdx").MdxJsxFlowElement | import("mdast").Blockquote | import("mdast").Break | import("mdast").Code | import("mdast").Definition | import("mdast").FootnoteDefinition | import("mdast").FootnoteReference | import("mdast").Heading | import("mdast").Html | import("mdast").Image | import("mdast").ImageReference | import("mdast").InlineCode | import("mdast").LinkReference | import("mdast").List | import("mdast").ListItem | import("mdast").Paragraph | import("mdast").Table | import("mdast").TableCell | import("mdast").TableRow | import("mdast").Text | import("mdast").ThematicBreak | import("mdast-util-math").InlineMath | import("mdast-util-math").Math | import("mdast-util-mdx").MdxJsxTextElement;
@@ -1,4 +1,6 @@
1
+ import type { Root } from 'mdast';
1
2
  import type { PluggableList } from 'unified';
2
3
  export declare const coreRemarkMdxPlugins: PluggableList;
3
- export declare const coreRemark: import("unified").Processor<import("mdast").Root, undefined, undefined, import("mdast").Root, string>;
4
- export declare const getAST: (str: string) => import("mdast").Root;
4
+ export declare const coreRemark: import("unified").Processor<Root, undefined, undefined, Root, string>;
5
+ export declare const getAST: (str: string) => Root;
6
+ export declare const stringifyTree: (tree: Root) => string;
@@ -3,6 +3,7 @@ import remarkFrontmatter from 'remark-frontmatter';
3
3
  import remarkGfm from 'remark-gfm';
4
4
  import remarkMath from 'remark-math';
5
5
  import remarkMdx from 'remark-mdx';
6
+ import remarkStringify from 'remark-stringify';
6
7
  export const coreRemarkMdxPlugins = [
7
8
  remarkMdx,
8
9
  remarkGfm,
@@ -11,3 +12,4 @@ export const coreRemarkMdxPlugins = [
11
12
  ];
12
13
  export const coreRemark = remark().use(coreRemarkMdxPlugins).freeze();
13
14
  export const getAST = (str) => coreRemark().parse(str);
15
+ export const stringifyTree = (tree) => coreRemark().use(remarkStringify).stringify(tree);
@@ -1,4 +1,2 @@
1
- export declare const findAndRemoveExports: (content: string) => Promise<{
2
- exportMap: Record<string, string>;
3
- content: string;
4
- }>;
1
+ import type { Root } from 'mdast';
2
+ export declare const findAndRemoveExports: (tree: Root) => Record<string, string>;
@@ -1,32 +1,13 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { remark } from 'remark';
11
1
  import { remove } from 'unist-util-remove';
12
- import { getAST } from '../remark.js';
13
- import { coreRemarkMdxPlugins } from '../remark.js';
14
2
  import { getExportMapFromTree } from './getExportMap.js';
15
3
  import { nodeIncludesExport } from './nodeIncludesExport.js';
16
- export const findAndRemoveExports = (content) => __awaiter(void 0, void 0, void 0, function* () {
17
- let exportMap = {};
18
- const ast = getAST(content);
19
- exportMap = getExportMapFromTree(ast);
20
- const contentWithoutExports = yield remark()
21
- .use(coreRemarkMdxPlugins)
22
- .use(() => (tree) => {
23
- remove(tree, (node) => {
24
- if (!nodeIncludesExport(node))
25
- return false;
26
- node.value = '';
27
- return true;
28
- });
29
- })
30
- .process(content);
31
- return { exportMap, content: String(contentWithoutExports) };
32
- });
4
+ export const findAndRemoveExports = (tree) => {
5
+ const exportMap = getExportMapFromTree(tree);
6
+ remove(tree, (node) => {
7
+ if (!nodeIncludesExport(node))
8
+ return false;
9
+ node.value = '';
10
+ return true;
11
+ });
12
+ return exportMap;
13
+ };
@@ -1,3 +1,4 @@
1
+ import type { Root } from 'mdast';
1
2
  import type { FindAndRemoveImportsResponse } from '../../types/mdx/index.js';
2
3
  /**
3
4
  An import like "import {Chart} from './chart.mdx'" looks like this in the AST:
@@ -23,9 +24,9 @@ import type { FindAndRemoveImportsResponse } from '../../types/mdx/index.js';
23
24
  }
24
25
  }
25
26
  }
26
- * this function takes in a string finds and removes imports in it (by detecting the node with the above characteristics)
27
- * @param content mdx file content
28
- * @returns importPaths - an array of the imports
29
- * content - the mdx file content with stripped imports
27
+ * this function takes in a tree finds and removes imports in it (by detecting the node with the above characteristics)
28
+ * @param tree mdx file tree
29
+ * @returns importMap - an array of the imports
30
+ * tree - the mdx file tree with stripped imports
30
31
  */
31
- export declare const findAndRemoveImports: (content: string) => Promise<FindAndRemoveImportsResponse>;
32
+ export declare const findAndRemoveImports: (tree: Root) => Promise<FindAndRemoveImportsResponse>;
@@ -8,11 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { jsx, toJs } from 'estree-util-to-js';
11
- import { remark } from 'remark';
12
11
  import { remove } from 'unist-util-remove';
13
12
  import { removePosition } from 'unist-util-remove-position';
14
13
  import { MdxImportSpecifier } from '../../types/mdx/index.js';
15
- import { coreRemarkMdxPlugins } from '../remark.js';
16
14
  import { isMdxJsEsm, estreeIsProgram, isImportDeclaration } from '../utils.js';
17
15
  /**
18
16
  An import like "import {Chart} from './chart.mdx'" looks like this in the AST:
@@ -38,58 +36,52 @@ import { isMdxJsEsm, estreeIsProgram, isImportDeclaration } from '../utils.js';
38
36
  }
39
37
  }
40
38
  }
41
- * this function takes in a string finds and removes imports in it (by detecting the node with the above characteristics)
42
- * @param content mdx file content
43
- * @returns importPaths - an array of the imports
44
- * content - the mdx file content with stripped imports
39
+ * this function takes in a tree finds and removes imports in it (by detecting the node with the above characteristics)
40
+ * @param tree mdx file tree
41
+ * @returns importMap - an array of the imports
42
+ * tree - the mdx file tree with stripped imports
45
43
  */
46
- export const findAndRemoveImports = (content) => __awaiter(void 0, void 0, void 0, function* () {
44
+ export const findAndRemoveImports = (tree) => __awaiter(void 0, void 0, void 0, function* () {
47
45
  const importMap = {};
48
- const strippedContent = yield remark()
49
- .use(coreRemarkMdxPlugins)
50
- .use(() => (tree) => {
51
- remove(tree, (node) => {
52
- var _a;
53
- if (isMdxJsEsm(node) && estreeIsProgram(node)) {
54
- const newBody = [];
55
- for (const bodyChild of node.data.estree.body) {
56
- if (isImportDeclaration(bodyChild) && typeof bodyChild.source.value === 'string') {
57
- const importDeclaration = {
58
- source: bodyChild.source.value,
59
- specifiers: bodyChild.specifiers.map((specifier) => {
60
- const isRenamedImportSpecifier = specifier.type === 'ImportSpecifier' &&
61
- specifier.imported.name != specifier.local.name;
62
- return Object.assign({ type: isRenamedImportSpecifier
63
- ? MdxImportSpecifier.RenamedImportSpecifier
64
- : specifier.type, name: isRenamedImportSpecifier ? specifier.imported.name : specifier.local.name }, (isRenamedImportSpecifier && {
65
- renamedName: specifier.local.name,
66
- }));
67
- }),
68
- };
69
- if (importMap[importDeclaration.source] == undefined) {
70
- importMap[importDeclaration.source] = importDeclaration.specifiers;
71
- }
72
- else {
73
- (_a = importMap[importDeclaration.source]) === null || _a === void 0 ? void 0 : _a.push(...importDeclaration.specifiers);
74
- }
46
+ remove(tree, (node) => {
47
+ var _a;
48
+ if (isMdxJsEsm(node) && estreeIsProgram(node)) {
49
+ const newBody = [];
50
+ for (const bodyChild of node.data.estree.body) {
51
+ if (isImportDeclaration(bodyChild) && typeof bodyChild.source.value === 'string') {
52
+ const importDeclaration = {
53
+ source: bodyChild.source.value,
54
+ specifiers: bodyChild.specifiers.map((specifier) => {
55
+ const isRenamedImportSpecifier = specifier.type === 'ImportSpecifier' &&
56
+ specifier.imported.name != specifier.local.name;
57
+ return Object.assign({ type: isRenamedImportSpecifier
58
+ ? MdxImportSpecifier.RenamedImportSpecifier
59
+ : specifier.type, name: isRenamedImportSpecifier ? specifier.imported.name : specifier.local.name }, (isRenamedImportSpecifier && {
60
+ renamedName: specifier.local.name,
61
+ }));
62
+ }),
63
+ };
64
+ if (importMap[importDeclaration.source] == undefined) {
65
+ importMap[importDeclaration.source] = importDeclaration.specifiers;
75
66
  }
76
67
  else {
77
- newBody.push(bodyChild);
68
+ (_a = importMap[importDeclaration.source]) === null || _a === void 0 ? void 0 : _a.push(...importDeclaration.specifiers);
78
69
  }
79
70
  }
80
- if (newBody.length != 0) {
81
- node.data.estree.body = newBody;
82
- node.value = '';
83
- removePosition(node);
84
- const newValue = toJs(node.data.estree, { handlers: jsx }).value;
85
- node.value = newValue;
86
- return false;
71
+ else {
72
+ newBody.push(bodyChild);
87
73
  }
88
- return true;
89
74
  }
90
- });
91
- return tree;
92
- })
93
- .process(content);
94
- return { importMap, content: String(strippedContent) };
75
+ if (newBody.length != 0) {
76
+ node.data.estree.body = newBody;
77
+ node.value = '';
78
+ removePosition(node);
79
+ const newValue = toJs(node.data.estree, { handlers: jsx }).value;
80
+ node.value = newValue;
81
+ return false;
82
+ }
83
+ return true;
84
+ }
85
+ });
86
+ return { importMap, tree };
95
87
  });
@@ -3,5 +3,4 @@ import type { Root } from 'mdast';
3
3
  *
4
4
  * @returns map of export names and their content
5
5
  */
6
- export declare const getExportMap: (content: string) => Record<string, string>;
7
6
  export declare const getExportMapFromTree: (tree: Root) => Record<string, string>;
@@ -1,39 +1,10 @@
1
1
  import { jsx, toJs } from 'estree-util-to-js';
2
2
  import { visit } from 'unist-util-visit';
3
- import { getAST } from '../remark.js';
4
3
  import { nodeIncludesExport } from './nodeIncludesExport.js';
5
4
  /**
6
5
  *
7
6
  * @returns map of export names and their content
8
7
  */
9
- export const getExportMap = (content) => {
10
- const exportMap = {};
11
- const ast = getAST(content);
12
- visit(ast, (node) => {
13
- if (!nodeIncludesExport(node))
14
- return;
15
- for (const bodyChild of node.data.estree.body) {
16
- if (bodyChild.type != 'ExportNamedDeclaration')
17
- continue;
18
- if (bodyChild.declaration == null)
19
- continue;
20
- if (bodyChild.declaration.type != 'VariableDeclaration')
21
- continue;
22
- for (const declaration of bodyChild.declaration.declarations) {
23
- if (declaration.id.type !== 'Identifier')
24
- continue;
25
- if (declaration.init == null)
26
- continue;
27
- // Sometimes when more than one exports are defined next to each other, the body includes multiple exports so we isolate the export we are looking for.
28
- const isolatedExport = structuredClone(node);
29
- isolatedExport.data.estree.body = [bodyChild];
30
- const value = toJs(isolatedExport.data.estree, { handlers: jsx }).value;
31
- exportMap[declaration.id.name] = value;
32
- }
33
- }
34
- });
35
- return exportMap;
36
- };
37
8
  export const getExportMapFromTree = (tree) => {
38
9
  const exportMap = {};
39
10
  visit(tree, (node) => {
@@ -1,5 +1,6 @@
1
+ import type { Root } from 'mdast';
1
2
  import type { FileType, FileWithImports } from '../../types/mdx/index.js';
2
3
  export declare const resolveAllImports: (params: {
3
4
  snippets: FileType[];
4
5
  fileWithImports: FileWithImports;
5
- }) => Promise<string>;
6
+ }) => Promise<Root>;
@@ -7,12 +7,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { getExportMap } from './getExportMap.js';
10
+ import { getExportMapFromTree } from './getExportMap.js';
11
11
  import { resolveImport } from './resolveImport/index.js';
12
12
  export const resolveAllImports = (params) => __awaiter(void 0, void 0, void 0, function* () {
13
13
  const { snippets, fileWithImports } = params;
14
- let content = fileWithImports.content;
15
- const exportMap = getExportMap(content);
14
+ let ast = fileWithImports.tree;
15
+ const exportMap = getExportMapFromTree(ast);
16
16
  for (const source of Object.keys(fileWithImports.importMap)) {
17
17
  if (!source.startsWith('/snippets/')) {
18
18
  console.log(`Invalid import path ${source} in ${fileWithImports.filename}. Import source must start with "/snippets/".`);
@@ -28,11 +28,11 @@ export const resolveAllImports = (params) => __awaiter(void 0, void 0, void 0, f
28
28
  continue;
29
29
  for (const specifier of specifiers) {
30
30
  try {
31
- yield resolveImport(specifier, content, importedSnippet.content, exportMap).then((contentWithResolvedImport) => {
32
- if (contentWithResolvedImport == undefined)
33
- throw new Error('Import failed to resolve');
34
- content = contentWithResolvedImport;
35
- });
31
+ const contentWithResolvedImport = yield resolveImport(specifier, ast, importedSnippet.tree, exportMap);
32
+ if (contentWithResolvedImport == undefined) {
33
+ throw new Error('Import failed to resolve');
34
+ }
35
+ ast = contentWithResolvedImport;
36
36
  }
37
37
  catch (err) {
38
38
  console.log(`Error resolving import "${specifier.name}" in ${fileWithImports.filename}`);
@@ -40,5 +40,5 @@ export const resolveAllImports = (params) => __awaiter(void 0, void 0, void 0, f
40
40
  }
41
41
  }
42
42
  }
43
- return content;
43
+ return ast;
44
44
  });
@@ -1,7 +1,8 @@
1
+ import type { Root } from 'mdast';
1
2
  /**
2
3
  *
3
4
  * @param exportName the name of the export we want to find
4
- * @param content the content we are looking for the export in
5
+ * @param tree the content we are looking for the export in
5
6
  * @returns the export
6
7
  */
7
- export declare const findExport: (exportName: string, content: string, renamedExportName?: string) => string | undefined;
8
+ export declare const findExport: (exportName: string, tree: Root, renamedExportName?: string) => string | undefined;
@@ -1,17 +1,15 @@
1
1
  import { jsx, toJs } from 'estree-util-to-js';
2
2
  import { visit, EXIT } from 'unist-util-visit';
3
- import { getAST } from '../../remark.js';
4
3
  import { nodeIncludesExport } from '../nodeIncludesExport.js';
5
4
  /**
6
5
  *
7
6
  * @param exportName the name of the export we want to find
8
- * @param content the content we are looking for the export in
7
+ * @param tree the content we are looking for the export in
9
8
  * @returns the export
10
9
  */
11
- export const findExport = (exportName, content, renamedExportName) => {
12
- const ast = getAST(content);
10
+ export const findExport = (exportName, tree, renamedExportName) => {
13
11
  let value = undefined;
14
- visit(ast, nodeIncludesExport, (node) => {
12
+ visit(tree, nodeIncludesExport, (node) => {
15
13
  for (const bodyChild of node.data.estree.body) {
16
14
  if (bodyChild.type !== 'ExportNamedDeclaration' ||
17
15
  bodyChild.declaration == null ||
@@ -1,3 +1,4 @@
1
+ import { Root } from 'mdast';
1
2
  import type { ImportSpecifier } from '../../../types/mdx/snippets/import.js';
2
3
  /**
3
4
  *
@@ -6,4 +7,4 @@ import type { ImportSpecifier } from '../../../types/mdx/snippets/import.js';
6
7
  * @param importedFileContent The content of the file we are importing from
7
8
  * @returns
8
9
  */
9
- export declare const resolveImport: (importSpecifier: ImportSpecifier, destinationPageContent: string, importedFileContent: string, exportMap: Record<string, string>) => Promise<string | undefined>;
10
+ export declare const resolveImport: (importSpecifier: ImportSpecifier, destinationPageContent: Root, importedFileContent: Root, exportMap: Record<string, string>) => Promise<Root | undefined>;
@@ -8,8 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { MdxImportSpecifier } from '../../../types/mdx/snippets/import.js';
11
+ import { getAST } from '../../remark.js';
11
12
  import { findExport } from './findExport.js';
12
- import { injectToTopOfFile } from './injectToTopOfFile.js';
13
+ import { injectToTopOfFileOfTree } from './injectToTopOfFile.js';
13
14
  import { resolveComponentWithContent } from './resolveComponentWithContent.js';
14
15
  /**
15
16
  *
@@ -30,7 +31,8 @@ export const resolveImport = (importSpecifier, destinationPageContent, importedF
30
31
  if (exportContent == undefined)
31
32
  throw new Error(`Could not find export ${importSpecifier.name} in snippet`);
32
33
  // Inject "export const Component = `...`" into the top of the destination page
33
- return injectToTopOfFile(destinationPageContent, exportContent);
34
+ injectToTopOfFileOfTree(destinationPageContent, getAST(exportContent).children);
35
+ return destinationPageContent;
34
36
  }
35
37
  else if ([
36
38
  MdxImportSpecifier.ImportDefaultSpecifier,
@@ -1,4 +1,12 @@
1
+ import type { Root, RootContent } from 'mdast';
1
2
  /**
2
3
  * Injects content to the top of a file, but below the frontmatter
3
4
  */
4
5
  export declare const injectToTopOfFile: (content: string, contentToInject: string) => string;
6
+ /**
7
+ * Injects nodes to the top of a MDX/Markdown AST (Root), but below the frontmatter (YAML node).
8
+ * Modifies the tree in place.
9
+ * @param tree The Root node of the document.
10
+ * @param nodesToInject An array of RootContent nodes to inject.
11
+ */
12
+ export declare const injectToTopOfFileOfTree: (tree: Root, nodesToInject: RootContent[]) => void;
@@ -9,3 +9,20 @@ export const injectToTopOfFile = (content, contentToInject) => {
9
9
  const { data: frontmatterData, content: contentWithoutFrontmatter } = matter(content);
10
10
  return matter.stringify(`\n` + contentToInject + `\n` + contentWithoutFrontmatter, frontmatterData);
11
11
  };
12
+ /**
13
+ * Injects nodes to the top of a MDX/Markdown AST (Root), but below the frontmatter (YAML node).
14
+ * Modifies the tree in place.
15
+ * @param tree The Root node of the document.
16
+ * @param nodesToInject An array of RootContent nodes to inject.
17
+ */
18
+ export const injectToTopOfFileOfTree = (tree, nodesToInject) => {
19
+ const firstChild = tree.children[0];
20
+ if ((firstChild === null || firstChild === void 0 ? void 0 : firstChild.type) === 'yaml') {
21
+ // Insert after the frontmatter (yaml node)
22
+ tree.children.splice(1, 0, ...nodesToInject);
23
+ }
24
+ else {
25
+ // Insert at the very beginning
26
+ tree.children.unshift(...nodesToInject);
27
+ }
28
+ };
@@ -1,7 +1,9 @@
1
+ import type { Root } from 'mdast';
1
2
  /**
2
3
  *
3
- * @param content The content to inject into
4
+ * @param tree The tree to inject into
4
5
  * @param componentName The component name we are injecting into
5
- * @param contentToInject The content to inject in place of the component
6
+ * @param snippet The snippet to inject in place of the component
7
+ * @param exportMap The export map of the snippet
6
8
  */
7
- export declare const resolveComponentWithContent: (content: string, componentName: string, snippet: string, exportMap: Record<string, string>) => Promise<string>;
9
+ export declare const resolveComponentWithContent: (tree: Root, componentName: string, snippet: Root, exportMap: Record<string, string>) => Promise<Root>;
@@ -8,40 +8,24 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { walk } from 'estree-walker';
11
- import matter from 'gray-matter';
12
- import { remark } from 'remark';
13
11
  import { visit } from 'unist-util-visit';
14
- import { coreRemarkMdxPlugins, getAST } from '../../remark.js';
12
+ import { removeFrontmatterFromAST } from '../../astUtils.js';
13
+ import { getAST } from '../../remark.js';
15
14
  import { createUniqueVariableName, isMdxJsxFlowElement } from '../../utils.js';
16
15
  import { findAndRemoveExports } from '../findAndRemoveExports.js';
17
- import { injectToTopOfFile } from './injectToTopOfFile.js';
16
+ import { injectToTopOfFileOfTree } from './injectToTopOfFile.js';
18
17
  /**
19
18
  *
20
- * @param content The content to inject into
19
+ * @param tree The tree to inject into
21
20
  * @param componentName The component name we are injecting into
22
- * @param contentToInject The content to inject in place of the component
21
+ * @param snippet The snippet to inject in place of the component
22
+ * @param exportMap The export map of the snippet
23
23
  */
24
- export const resolveComponentWithContent = (content, componentName, snippet, exportMap) => __awaiter(void 0, void 0, void 0, function* () {
25
- const { content: snippetWithoutFrontmatter } = matter(snippet);
26
- const { exportMap: snippetExportMap, content: snippetWithoutExports } = yield findAndRemoveExports(snippetWithoutFrontmatter);
27
- const snippetAST = getAST(snippetWithoutExports);
28
- const convertedContent = yield remark()
29
- .use(coreRemarkMdxPlugins)
30
- .use(remarkMdxResolveComponentWithContent(snippetAST, componentName, exportMap, snippetExportMap))
31
- .process(content);
32
- const convertedContentStr = String(convertedContent);
33
- return reinsertExports(convertedContentStr, exportMap, snippetExportMap);
34
- });
35
- /**
36
- * Everywhere where there is a component with the name `componentName`, replace it with the `treeToInject`.
37
- * New variables are also exported to be used for the variables. Additional mutations are made to support duplicated snippets
38
- *
39
- * This function is used to resolve default imports
40
- * @param treeToInject
41
- * @param componentName
42
- * @returns
43
- */
44
- const remarkMdxResolveComponentWithContent = (treeToInject, componentName, exportMap, snippetExportMap) => () => (tree) => {
24
+ export const resolveComponentWithContent = (tree, componentName, snippet, exportMap) => __awaiter(void 0, void 0, void 0, function* () {
25
+ const clonedSnippet = structuredClone(snippet);
26
+ removeFrontmatterFromAST(clonedSnippet);
27
+ const snippetExportMap = findAndRemoveExports(clonedSnippet);
28
+ let treeToInject = clonedSnippet;
45
29
  visit(tree, isMdxJsxFlowElement, (node, i, parent) => {
46
30
  var _a;
47
31
  if (node.name === componentName && parent && i != null) {
@@ -54,7 +38,9 @@ const remarkMdxResolveComponentWithContent = (treeToInject, componentName, expor
54
38
  treeToInject = treeToInjectClone;
55
39
  }
56
40
  });
57
- };
41
+ reinsertExports(tree, exportMap, snippetExportMap);
42
+ return tree;
43
+ });
58
44
  /**
59
45
  * Replace the variables with value provided from the props by defining the variable before the snippet
60
46
  * Also prevents duplicates by attaching a unique identifier to every variable (var to var_1)
@@ -112,12 +98,16 @@ const replaceVariablesWithProps = (node, treeToInject, exportMap, snippetExportM
112
98
  };
113
99
  };
114
100
  const reinsertExports = (content, exportMap, snippetExportMap) => {
101
+ const nodesToInject = [];
115
102
  for (const [key, value] of Object.entries(snippetExportMap)) {
116
103
  // TODO: handle duplicate exports
117
104
  if (exportMap[key] == undefined) {
118
- content = injectToTopOfFile(content, value);
105
+ const exportAST = getAST(value);
106
+ nodesToInject.push(...exportAST.children);
119
107
  exportMap[key] = value;
120
108
  }
121
109
  }
122
- return content;
110
+ if (nodesToInject.length > 0) {
111
+ injectToTopOfFileOfTree(content, nodesToInject);
112
+ }
123
113
  };