@docusaurus/utils 2.0.0-beta.1 → 2.0.0-beta.10

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 (57) hide show
  1. package/lib/.tsbuildinfo +1 -1
  2. package/lib/constants.d.ts +19 -0
  3. package/lib/constants.js +26 -0
  4. package/lib/globUtils.d.ts +11 -0
  5. package/lib/globUtils.js +47 -0
  6. package/lib/{docuHash.d.ts → hashUtils.d.ts} +2 -0
  7. package/lib/{docuHash.js → hashUtils.js} +15 -5
  8. package/lib/index.d.ts +11 -9
  9. package/lib/index.js +44 -98
  10. package/lib/markdownLinks.js +19 -6
  11. package/lib/markdownParser.js +20 -12
  12. package/lib/mdxUtils.d.ts +16 -0
  13. package/lib/mdxUtils.js +30 -0
  14. package/lib/{getFilePathForRoutePath.d.ts → normalizeUrl.d.ts} +1 -1
  15. package/lib/normalizeUrl.js +66 -0
  16. package/lib/pathUtils.d.ts +0 -1
  17. package/lib/pathUtils.js +4 -11
  18. package/lib/slugger.d.ts +13 -0
  19. package/lib/slugger.js +18 -0
  20. package/lib/tags.d.ts +18 -0
  21. package/lib/tags.js +72 -0
  22. package/lib/webpackUtils.d.ts +29 -0
  23. package/lib/webpackUtils.js +109 -0
  24. package/package.json +23 -7
  25. package/src/__tests__/globUtils.test.ts +109 -0
  26. package/src/__tests__/{docuHash.test.ts → hashUtils.test.ts} +22 -1
  27. package/src/__tests__/index.test.ts +6 -110
  28. package/src/__tests__/markdownParser.test.ts +15 -2
  29. package/src/__tests__/mdxUtils.test.ts +133 -0
  30. package/src/__tests__/normalizeUrl.test.ts +117 -0
  31. package/src/__tests__/pathUtils.test.ts +5 -22
  32. package/src/__tests__/slugger.test.ts +27 -0
  33. package/src/__tests__/tags.test.ts +183 -0
  34. package/src/__tests__/webpackUtils.test.ts +33 -0
  35. package/src/constants.ts +38 -0
  36. package/src/deps.d.ts +14 -0
  37. package/src/globUtils.ts +63 -0
  38. package/src/{docuHash.ts → hashUtils.ts} +10 -1
  39. package/src/index.ts +23 -96
  40. package/src/markdownLinks.ts +19 -8
  41. package/src/markdownParser.ts +24 -17
  42. package/src/mdxUtils.ts +32 -0
  43. package/src/normalizeUrl.ts +80 -0
  44. package/src/pathUtils.ts +2 -9
  45. package/src/slugger.ts +24 -0
  46. package/src/tags.ts +100 -0
  47. package/src/webpackUtils.ts +144 -0
  48. package/lib/codeTranslationsUtils.d.ts +0 -11
  49. package/lib/codeTranslationsUtils.js +0 -50
  50. package/lib/getFilePathForRoutePath.js +0 -40
  51. package/src/__tests__/__fixtures__/defaultCodeTranslations/en.json +0 -4
  52. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr-FR.json +0 -5
  53. package/src/__tests__/__fixtures__/defaultCodeTranslations/fr.json +0 -4
  54. package/src/__tests__/codeTranslationsUtils.test.ts +0 -112
  55. package/src/__tests__/getFilePathForRoutePath.test.ts +0 -87
  56. package/src/codeTranslationsUtils.ts +0 -56
  57. package/src/getFilePathForRoutePath.ts +0 -43
package/lib/index.js CHANGED
@@ -6,29 +6,39 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.parseMarkdownHeadingId = exports.updateTranslationFileMessages = exports.getSwizzledComponent = exports.mergeTranslations = exports.reportMessage = exports.getFolderContainingFile = exports.findFolderContainingFile = exports.findAsyncSequential = exports.mapAsyncSequencial = exports.getPluginI18nPath = exports.getElementsAround = exports.removePrefix = exports.removeSuffix = exports.removeTrailingSlash = exports.addTrailingSlash = exports.addTrailingPathSeparator = exports.addLeadingSlash = exports.resolvePathname = exports.isValidPathname = exports.getEditUrl = exports.aliasedSitePath = exports.normalizeUrl = exports.getSubFolder = exports.idx = exports.genChunkName = exports.toMessageRelativeFilePath = exports.genComponentName = exports.upperFirst = exports.encodePath = exports.fileToPath = exports.objectWithKeySorted = exports.generate = exports.simpleHash = exports.posixPath = void 0;
9
+ exports.parseMarkdownHeadingId = exports.updateTranslationFileMessages = exports.getSwizzledComponent = exports.mergeTranslations = exports.reportMessage = exports.getFolderContainingFile = exports.findFolderContainingFile = exports.findAsyncSequential = exports.mapAsyncSequencial = exports.getPluginI18nPath = exports.getElementsAround = exports.removePrefix = exports.removeSuffix = exports.removeTrailingSlash = exports.addTrailingSlash = exports.addTrailingPathSeparator = exports.addLeadingSlash = exports.resolvePathname = exports.isValidPathname = exports.getEditUrl = exports.aliasedSitePath = exports.getSubFolder = exports.idx = exports.genChunkName = exports.toMessageRelativeFilePath = exports.genComponentName = exports.upperFirst = exports.encodePath = exports.fileToPath = exports.objectWithKeySorted = exports.generate = exports.createAbsoluteFilePathMatcher = exports.createMatcher = exports.GlobExcludeDefault = exports.Globby = exports.docuHash = exports.simpleHash = exports.md5Hash = exports.posixPath = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
- const path_1 = tslib_1.__importDefault(require("path"));
11
+ const chalk_1 = (0, tslib_1.__importDefault)(require("chalk"));
12
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
13
13
  const crypto_1 = require("crypto");
14
14
  const lodash_1 = require("lodash");
15
- const escape_string_regexp_1 = tslib_1.__importDefault(require("escape-string-regexp"));
16
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
15
+ const escape_string_regexp_1 = (0, tslib_1.__importDefault)(require("escape-string-regexp"));
16
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
17
17
  const url_1 = require("url");
18
- // @ts-expect-error: no typedefs :s
19
- const resolve_pathname_1 = tslib_1.__importDefault(require("resolve-pathname"));
18
+ const resolve_pathname_1 = (0, tslib_1.__importDefault)(require("resolve-pathname"));
20
19
  const posixPath_1 = require("./posixPath");
21
- const pathUtils_1 = require("./pathUtils");
22
- const docuHash_1 = require("./docuHash");
20
+ const hashUtils_1 = require("./hashUtils");
21
+ const normalizeUrl_1 = require("./normalizeUrl");
22
+ const constants_1 = require("./constants");
23
+ (0, tslib_1.__exportStar)(require("./constants"), exports);
24
+ (0, tslib_1.__exportStar)(require("./mdxUtils"), exports);
25
+ (0, tslib_1.__exportStar)(require("./normalizeUrl"), exports);
26
+ (0, tslib_1.__exportStar)(require("./tags"), exports);
23
27
  exports.posixPath = posixPath_1.posixPath;
24
- tslib_1.__exportStar(require("./getFilePathForRoutePath"), exports);
25
- tslib_1.__exportStar(require("./codeTranslationsUtils"), exports);
26
- tslib_1.__exportStar(require("./markdownParser"), exports);
27
- tslib_1.__exportStar(require("./markdownLinks"), exports);
28
- tslib_1.__exportStar(require("./escapePath"), exports);
29
- tslib_1.__exportStar(require("./docuHash"), exports);
30
- var pathUtils_2 = require("./pathUtils");
31
- Object.defineProperty(exports, "simpleHash", { enumerable: true, get: function () { return pathUtils_2.simpleHash; } });
28
+ (0, tslib_1.__exportStar)(require("./markdownParser"), exports);
29
+ (0, tslib_1.__exportStar)(require("./markdownLinks"), exports);
30
+ (0, tslib_1.__exportStar)(require("./escapePath"), exports);
31
+ (0, tslib_1.__exportStar)(require("./slugger"), exports);
32
+ var hashUtils_2 = require("./hashUtils");
33
+ Object.defineProperty(exports, "md5Hash", { enumerable: true, get: function () { return hashUtils_2.md5Hash; } });
34
+ Object.defineProperty(exports, "simpleHash", { enumerable: true, get: function () { return hashUtils_2.simpleHash; } });
35
+ Object.defineProperty(exports, "docuHash", { enumerable: true, get: function () { return hashUtils_2.docuHash; } });
36
+ var globUtils_1 = require("./globUtils");
37
+ Object.defineProperty(exports, "Globby", { enumerable: true, get: function () { return globUtils_1.Globby; } });
38
+ Object.defineProperty(exports, "GlobExcludeDefault", { enumerable: true, get: function () { return globUtils_1.GlobExcludeDefault; } });
39
+ Object.defineProperty(exports, "createMatcher", { enumerable: true, get: function () { return globUtils_1.createMatcher; } });
40
+ Object.defineProperty(exports, "createAbsoluteFilePathMatcher", { enumerable: true, get: function () { return globUtils_1.createAbsoluteFilePathMatcher; } });
41
+ (0, tslib_1.__exportStar)(require("./webpackUtils"), exports);
32
42
  const fileHash = new Map();
33
43
  async function generate(generatedFilesDir, file, content, skipCache = process.env.NODE_ENV === 'production') {
34
44
  const filepath = path_1.default.join(generatedFilesDir, file);
@@ -43,10 +53,10 @@ async function generate(generatedFilesDir, file, content, skipCache = process.en
43
53
  // This is to avoid unnecessary overwriting and we can reuse old file.
44
54
  if (!lastHash && fs_extra_1.default.existsSync(filepath)) {
45
55
  const lastContent = await fs_extra_1.default.readFile(filepath, 'utf8');
46
- lastHash = crypto_1.createHash('md5').update(lastContent).digest('hex');
56
+ lastHash = (0, crypto_1.createHash)('md5').update(lastContent).digest('hex');
47
57
  fileHash.set(filepath, lastHash);
48
58
  }
49
- const currentHash = crypto_1.createHash('md5').update(content).digest('hex');
59
+ const currentHash = (0, crypto_1.createHash)('md5').update(content).digest('hex');
50
60
  if (lastHash !== currentHash) {
51
61
  await fs_extra_1.default.ensureDir(path_1.default.dirname(filepath));
52
62
  await fs_extra_1.default.writeFile(filepath, content);
@@ -100,8 +110,8 @@ function genComponentName(pagePath) {
100
110
  if (pagePath === '/') {
101
111
  return 'index';
102
112
  }
103
- const pageHash = docuHash_1.docuHash(pagePath);
104
- return upperFirst(lodash_1.camelCase(pageHash));
113
+ const pageHash = (0, hashUtils_1.docuHash)(pagePath);
114
+ return upperFirst((0, lodash_1.camelCase)(pageHash));
105
115
  }
106
116
  exports.genComponentName = genComponentName;
107
117
  // When you want to display a path in a message/warning/error,
@@ -112,7 +122,7 @@ exports.genComponentName = genComponentName;
112
122
  // on both Unix/Windows
113
123
  // For Windows users this is not perfect (as they see / instead of \) but it's probably good enough
114
124
  function toMessageRelativeFilePath(filePath) {
115
- return exports.posixPath(path_1.default.relative(process.cwd(), filePath));
125
+ return (0, exports.posixPath)(path_1.default.relative(process.cwd(), filePath));
116
126
  }
117
127
  exports.toMessageRelativeFilePath = toMessageRelativeFilePath;
118
128
  const chunkNameCache = new Map();
@@ -123,15 +133,15 @@ function genChunkName(modulePath, prefix, preferredName, shortId = process.env.N
123
133
  let chunkName = chunkNameCache.get(modulePath);
124
134
  if (!chunkName) {
125
135
  if (shortId) {
126
- chunkName = pathUtils_1.simpleHash(modulePath, 8);
136
+ chunkName = (0, hashUtils_1.simpleHash)(modulePath, 8);
127
137
  }
128
138
  else {
129
139
  let str = modulePath;
130
140
  if (preferredName) {
131
- const shortHash = pathUtils_1.simpleHash(modulePath, 3);
141
+ const shortHash = (0, hashUtils_1.simpleHash)(modulePath, 3);
132
142
  str = `${preferredName}${shortHash}`;
133
143
  }
134
- const name = str === '/' ? 'index' : docuHash_1.docuHash(str);
144
+ const name = str === '/' ? 'index' : (0, hashUtils_1.docuHash)(str);
135
145
  chunkName = prefix ? `${prefix}---${name}` : name;
136
146
  }
137
147
  chunkNameCache.set(modulePath, chunkName);
@@ -153,77 +163,20 @@ exports.idx = idx;
153
163
  * Given a filepath and dirpath, get the first directory.
154
164
  */
155
165
  function getSubFolder(file, refDir) {
156
- const separator = escape_string_regexp_1.default(path_1.default.sep);
157
- const baseDir = escape_string_regexp_1.default(path_1.default.basename(refDir));
166
+ const separator = (0, escape_string_regexp_1.default)(path_1.default.sep);
167
+ const baseDir = (0, escape_string_regexp_1.default)(path_1.default.basename(refDir));
158
168
  const regexSubFolder = new RegExp(`${baseDir}${separator}(.*?)${separator}.*`);
159
169
  const match = regexSubFolder.exec(file);
160
170
  return match && match[1];
161
171
  }
162
172
  exports.getSubFolder = getSubFolder;
163
- function normalizeUrl(rawUrls) {
164
- const urls = [...rawUrls];
165
- const resultArray = [];
166
- let hasStartingSlash = false;
167
- let hasEndingSlash = false;
168
- // If the first part is a plain protocol, we combine it with the next part.
169
- if (urls[0].match(/^[^/:]+:\/*$/) && urls.length > 1) {
170
- const first = urls.shift();
171
- urls[0] = first + urls[0];
172
- }
173
- // There must be two or three slashes in the file protocol,
174
- // two slashes in anything else.
175
- const replacement = urls[0].match(/^file:\/\/\//) ? '$1:///' : '$1://';
176
- urls[0] = urls[0].replace(/^([^/:]+):\/*/, replacement);
177
- // eslint-disable-next-line
178
- for (let i = 0; i < urls.length; i++) {
179
- let component = urls[i];
180
- if (typeof component !== 'string') {
181
- throw new TypeError(`Url must be a string. Received ${typeof component}`);
182
- }
183
- if (component === '') {
184
- if (i === urls.length - 1 && hasEndingSlash) {
185
- resultArray.push('/');
186
- }
187
- // eslint-disable-next-line
188
- continue;
189
- }
190
- if (component !== '/') {
191
- if (i > 0) {
192
- // Removing the starting slashes for each component but the first.
193
- component = component.replace(/^[/]+/,
194
- // Special case where the first element of rawUrls is empty ["", "/hello"] => /hello
195
- component[0] === '/' && !hasStartingSlash ? '/' : '');
196
- }
197
- hasEndingSlash = component[component.length - 1] === '/';
198
- // Removing the ending slashes for each component but the last.
199
- // For the last component we will combine multiple slashes to a single one.
200
- component = component.replace(/[/]+$/, i < urls.length - 1 ? '' : '/');
201
- }
202
- hasStartingSlash = true;
203
- resultArray.push(component);
204
- }
205
- let str = resultArray.join('/');
206
- // Each input component is now separated by a single slash
207
- // except the possible first plain protocol part.
208
- // Remove trailing slash before parameters or hash.
209
- str = str.replace(/\/(\?|&|#[^!])/g, '$1');
210
- // Replace ? in parameters with &.
211
- const parts = str.split('?');
212
- str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
213
- // Dedupe forward slashes in the entire path, avoiding protocol slashes.
214
- str = str.replace(/([^:]\/)\/+/g, '$1');
215
- // Dedupe forward slashes at the beginning of the path.
216
- str = str.replace(/^\/+/g, '/');
217
- return str;
218
- }
219
- exports.normalizeUrl = normalizeUrl;
220
173
  /**
221
174
  * Alias filepath relative to site directory, very useful so that we
222
175
  * don't expose user's site structure.
223
176
  * Example: some/path/to/website/docs/foo.md -> @site/docs/foo.md
224
177
  */
225
178
  function aliasedSitePath(filePath, siteDir) {
226
- const relativePath = exports.posixPath(path_1.default.relative(siteDir, filePath));
179
+ const relativePath = (0, exports.posixPath)(path_1.default.relative(siteDir, filePath));
227
180
  // Cannot use path.join() as it resolves '../' and removes
228
181
  // the '@site'. Let webpack loader resolve it.
229
182
  return `@site/${relativePath}`;
@@ -231,7 +184,7 @@ function aliasedSitePath(filePath, siteDir) {
231
184
  exports.aliasedSitePath = aliasedSitePath;
232
185
  function getEditUrl(fileRelativePath, editUrl) {
233
186
  return editUrl
234
- ? normalizeUrl([editUrl, exports.posixPath(fileRelativePath)])
187
+ ? (0, normalizeUrl_1.normalizeUrl)([editUrl, (0, exports.posixPath)(fileRelativePath)])
235
188
  : undefined;
236
189
  }
237
190
  exports.getEditUrl = getEditUrl;
@@ -251,7 +204,7 @@ function isValidPathname(str) {
251
204
  exports.isValidPathname = isValidPathname;
252
205
  // resolve pathname and fail fast if resolution fails
253
206
  function resolvePathname(to, from) {
254
- return resolve_pathname_1.default(to, from);
207
+ return (0, resolve_pathname_1.default)(to, from);
255
208
  }
256
209
  exports.resolvePathname = resolvePathname;
257
210
  function addLeadingSlash(str) {
@@ -293,23 +246,19 @@ function getElementsAround(array, aroundIndex) {
293
246
  return { previous, next };
294
247
  }
295
248
  exports.getElementsAround = getElementsAround;
296
- function getPluginI18nPath({ siteDir, locale, pluginName, pluginId = 'default', // TODO duplicated constant
297
- subPaths = [], }) {
249
+ function getPluginI18nPath({ siteDir, locale, pluginName, pluginId = constants_1.DEFAULT_PLUGIN_ID, subPaths = [], }) {
298
250
  return path_1.default.join(siteDir, 'i18n',
299
251
  // namespace first by locale: convenient to work in a single folder for a translator
300
252
  locale,
301
253
  // Make it convenient to use for single-instance
302
254
  // ie: return "docs", not "docs-default" nor "docs/default"
303
- `${pluginName}${
304
- // TODO duplicate constant :(
305
- pluginId === 'default' ? '' : `-${pluginId}`}`, ...subPaths);
255
+ `${pluginName}${pluginId === constants_1.DEFAULT_PLUGIN_ID ? '' : `-${pluginId}`}`, ...subPaths);
306
256
  }
307
257
  exports.getPluginI18nPath = getPluginI18nPath;
308
258
  async function mapAsyncSequencial(array, action) {
309
259
  const results = [];
310
260
  // eslint-disable-next-line no-restricted-syntax
311
261
  for (const t of array) {
312
- // eslint-disable-next-line no-await-in-loop
313
262
  const result = await action(t);
314
263
  results.push(result);
315
264
  }
@@ -319,7 +268,6 @@ exports.mapAsyncSequencial = mapAsyncSequencial;
319
268
  async function findAsyncSequential(array, predicate) {
320
269
  // eslint-disable-next-line no-restricted-syntax
321
270
  for (const t of array) {
322
- // eslint-disable-next-line no-await-in-loop
323
271
  if (await predicate(t)) {
324
272
  return t;
325
273
  }
@@ -362,9 +310,7 @@ function reportMessage(message, reportingSeverity) {
362
310
  }
363
311
  exports.reportMessage = reportMessage;
364
312
  function mergeTranslations(contents) {
365
- return contents.reduce((acc, content) => {
366
- return { ...acc, ...content };
367
- }, {});
313
+ return contents.reduce((acc, content) => ({ ...acc, ...content }), {});
368
314
  }
369
315
  exports.mergeTranslations = mergeTranslations;
370
316
  function getSwizzledComponent(componentPath) {
@@ -379,7 +325,7 @@ exports.getSwizzledComponent = getSwizzledComponent;
379
325
  function updateTranslationFileMessages(translationFile, updateMessage) {
380
326
  return {
381
327
  ...translationFile,
382
- content: lodash_1.mapValues(translationFile.content, (translation) => ({
328
+ content: (0, lodash_1.mapValues)(translationFile.content, (translation) => ({
383
329
  ...translation,
384
330
  message: updateMessage(translation.message),
385
331
  })),
@@ -7,7 +7,8 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.replaceMarkdownLinks = void 0;
10
- const url_1 = require("url");
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
11
12
  const index_1 = require("./index");
12
13
  function replaceMarkdownLinks({ siteDir, fileString, filePath, contentPaths, sourceToPermalink, }) {
13
14
  const { contentPath, contentPathLocalized } = contentPaths;
@@ -30,12 +31,24 @@ function replaceMarkdownLinks({ siteDir, fileString, filePath, contentPaths, sou
30
31
  while (mdMatch !== null) {
31
32
  // Replace it to correct html link.
32
33
  const mdLink = mdMatch[1];
33
- const aliasedSource = (source) => index_1.aliasedSitePath(source, siteDir);
34
- const permalink = sourceToPermalink[aliasedSource(url_1.resolve(filePath, mdLink))] ||
35
- sourceToPermalink[aliasedSource(`${contentPathLocalized}/${mdLink}`)] ||
36
- sourceToPermalink[aliasedSource(`${contentPath}/${mdLink}`)];
34
+ const sourcesToTry = [
35
+ path_1.default.resolve(path_1.default.dirname(filePath), decodeURIComponent(mdLink)),
36
+ `${contentPathLocalized}/${decodeURIComponent(mdLink)}`,
37
+ `${contentPath}/${decodeURIComponent(mdLink)}`,
38
+ ];
39
+ const aliasedSourceMatch = sourcesToTry
40
+ .map((source) => (0, index_1.aliasedSitePath)(source, siteDir))
41
+ .find((source) => sourceToPermalink[source]);
42
+ const permalink = aliasedSourceMatch
43
+ ? sourceToPermalink[aliasedSourceMatch]
44
+ : undefined;
37
45
  if (permalink) {
38
- modifiedLine = modifiedLine.replace(mdLink, permalink);
46
+ // MDX won't be happy if the permalink contains a space, we need to convert it to %20
47
+ const encodedPermalink = permalink
48
+ .split('/')
49
+ .map((part) => part.replace(/\s/g, '%20'))
50
+ .join('/');
51
+ modifiedLine = modifiedLine.replace(mdLink, encodedPermalink);
39
52
  }
40
53
  else {
41
54
  const brokenMarkdownLink = {
@@ -8,9 +8,9 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.parseMarkdownFile = exports.parseMarkdownString = exports.parseMarkdownContentTitle = exports.parseFrontMatter = exports.createExcerpt = void 0;
10
10
  const tslib_1 = require("tslib");
11
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
- const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
13
- const gray_matter_1 = tslib_1.__importDefault(require("gray-matter"));
11
+ const chalk_1 = (0, tslib_1.__importDefault)(require("chalk"));
12
+ const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
13
+ const gray_matter_1 = (0, tslib_1.__importDefault)(require("gray-matter"));
14
14
  // Hacky way of stripping out import statements from the excerpt
15
15
  // TODO: Find a better way to do so, possibly by compiling the Markdown content,
16
16
  // stripping out HTML tags and obtaining the first line.
@@ -20,6 +20,7 @@ function createExcerpt(fileString) {
20
20
  // Remove Markdown alternate title
21
21
  .replace(/^[^\n]*\n[=]+/g, '')
22
22
  .split('\n');
23
+ let inCode = false;
23
24
  /* eslint-disable no-continue */
24
25
  // eslint-disable-next-line no-restricted-syntax
25
26
  for (const fileLine of fileLines) {
@@ -31,21 +32,29 @@ function createExcerpt(fileString) {
31
32
  if (/^\s*?import\s.*(from.*)?;?|export\s.*{.*};?/.test(fileLine)) {
32
33
  continue;
33
34
  }
35
+ // Skip code block line.
36
+ if (fileLine.trim().startsWith('```')) {
37
+ inCode = !inCode;
38
+ continue;
39
+ }
40
+ else if (inCode) {
41
+ continue;
42
+ }
34
43
  const cleanedLine = fileLine
35
44
  // Remove HTML tags.
36
45
  .replace(/<[^>]*>/g, '')
37
46
  // Remove Title headers
38
- .replace(/^\#\s*([^#]*)\s*\#?/gm, '')
47
+ .replace(/^#\s*([^#]*)\s*#?/gm, '')
39
48
  // Remove Markdown + ATX-style headers
40
- .replace(/^\#{1,6}\s*([^#]*)\s*(\#{1,6})?/gm, '$1')
49
+ .replace(/^#{1,6}\s*([^#]*)\s*(#{1,6})?/gm, '$1')
41
50
  // Remove emphasis and strikethroughs.
42
- .replace(/([\*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2')
51
+ .replace(/([*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2')
43
52
  // Remove images.
44
- .replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, '$1')
53
+ .replace(/!\[(.*?)\][[(].*?[\])]/g, '$1')
45
54
  // Remove footnotes.
46
- .replace(/\[\^.+?\](\: .*?$)?/g, '')
55
+ .replace(/\[\^.+?\](: .*?$)?/g, '')
47
56
  // Remove inline links.
48
- .replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1')
57
+ .replace(/\[(.*?)\][[(].*?[\])]/g, '$1')
49
58
  // Remove inline code.
50
59
  .replace(/`(.+?)`/g, '$1')
51
60
  // Remove blockquotes.
@@ -66,7 +75,7 @@ function createExcerpt(fileString) {
66
75
  exports.createExcerpt = createExcerpt;
67
76
  function parseFrontMatter(markdownFileContent) {
68
77
  var _a;
69
- const { data, content } = gray_matter_1.default(markdownFileContent);
78
+ const { data, content } = (0, gray_matter_1.default)(markdownFileContent);
70
79
  return {
71
80
  frontMatter: data !== null && data !== void 0 ? data : {},
72
81
  content: (_a = content === null || content === void 0 ? void 0 : content.trim()) !== null && _a !== void 0 ? _a : '',
@@ -86,8 +95,7 @@ function parseMarkdownContentTitle(contentUntrimmed, options) {
86
95
  var _a, _b;
87
96
  const removeContentTitleOption = (_a = options === null || options === void 0 ? void 0 : options.removeContentTitle) !== null && _a !== void 0 ? _a : false;
88
97
  const content = contentUntrimmed.trim();
89
- const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/
90
- .source;
98
+ const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/.source;
91
99
  const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/
92
100
  .source;
93
101
  const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ /**
8
+ * Transform mdx text to plain html text
9
+ * Initially created to convert MDX blog posts to HTML for the RSS feed
10
+ * without import/export nodes
11
+ *
12
+ * TODO not ideal implementation, won't work well with MDX elements!
13
+ * TODO theme+global site config should be able to declare MDX comps in scope for rendering the RSS feeds
14
+ * see also https://github.com/facebook/docusaurus/issues/4625
15
+ */
16
+ export declare function mdxToHtml(mdxStr: string): string;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.mdxToHtml = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const react_1 = (0, tslib_1.__importDefault)(require("react"));
12
+ const server_1 = (0, tslib_1.__importDefault)(require("react-dom/server"));
13
+ const runtime_1 = (0, tslib_1.__importDefault)(require("@mdx-js/runtime"));
14
+ const remark_mdx_remove_imports_1 = (0, tslib_1.__importDefault)(require("remark-mdx-remove-imports"));
15
+ const remark_mdx_remove_exports_1 = (0, tslib_1.__importDefault)(require("remark-mdx-remove-exports"));
16
+ /**
17
+ * Transform mdx text to plain html text
18
+ * Initially created to convert MDX blog posts to HTML for the RSS feed
19
+ * without import/export nodes
20
+ *
21
+ * TODO not ideal implementation, won't work well with MDX elements!
22
+ * TODO theme+global site config should be able to declare MDX comps in scope for rendering the RSS feeds
23
+ * see also https://github.com/facebook/docusaurus/issues/4625
24
+ */
25
+ function mdxToHtml(mdxStr) {
26
+ return server_1.default.renderToString(react_1.default.createElement(runtime_1.default, { remarkPlugins: [remark_mdx_remove_imports_1.default, remark_mdx_remove_exports_1.default] }, [
27
+ mdxStr,
28
+ ]));
29
+ }
30
+ exports.mdxToHtml = mdxToHtml;
@@ -4,4 +4,4 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- export declare function getFilePathForRoutePath(routePath: string, trailingSlash: boolean | undefined): string;
7
+ export declare function normalizeUrl(rawUrls: string[]): string;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.normalizeUrl = void 0;
10
+ function normalizeUrl(rawUrls) {
11
+ const urls = [...rawUrls];
12
+ const resultArray = [];
13
+ let hasStartingSlash = false;
14
+ let hasEndingSlash = false;
15
+ // If the first part is a plain protocol, we combine it with the next part.
16
+ if (urls[0].match(/^[^/:]+:\/*$/) && urls.length > 1) {
17
+ const first = urls.shift();
18
+ urls[0] = first + urls[0];
19
+ }
20
+ // There must be two or three slashes in the file protocol,
21
+ // two slashes in anything else.
22
+ const replacement = urls[0].match(/^file:\/\/\//) ? '$1:///' : '$1://';
23
+ urls[0] = urls[0].replace(/^([^/:]+):\/*/, replacement);
24
+ // eslint-disable-next-line
25
+ for (let i = 0; i < urls.length; i++) {
26
+ let component = urls[i];
27
+ if (typeof component !== 'string') {
28
+ throw new TypeError(`Url must be a string. Received ${typeof component}`);
29
+ }
30
+ if (component === '') {
31
+ if (i === urls.length - 1 && hasEndingSlash) {
32
+ resultArray.push('/');
33
+ }
34
+ // eslint-disable-next-line
35
+ continue;
36
+ }
37
+ if (component !== '/') {
38
+ if (i > 0) {
39
+ // Removing the starting slashes for each component but the first.
40
+ component = component.replace(/^[/]+/,
41
+ // Special case where the first element of rawUrls is empty ["", "/hello"] => /hello
42
+ component[0] === '/' && !hasStartingSlash ? '/' : '');
43
+ }
44
+ hasEndingSlash = component[component.length - 1] === '/';
45
+ // Removing the ending slashes for each component but the last.
46
+ // For the last component we will combine multiple slashes to a single one.
47
+ component = component.replace(/[/]+$/, i < urls.length - 1 ? '' : '/');
48
+ }
49
+ hasStartingSlash = true;
50
+ resultArray.push(component);
51
+ }
52
+ let str = resultArray.join('/');
53
+ // Each input component is now separated by a single slash
54
+ // except the possible first plain protocol part.
55
+ // Remove trailing slash before parameters or hash.
56
+ str = str.replace(/\/(\?|&|#[^!])/g, '$1');
57
+ // Replace ? in parameters with &.
58
+ const parts = str.split('?');
59
+ str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
60
+ // Dedupe forward slashes in the entire path, avoiding protocol slashes.
61
+ str = str.replace(/([^:]\/)\/+/g, '$1');
62
+ // Dedupe forward slashes at the beginning of the path.
63
+ str = str.replace(/^\/+/g, '/');
64
+ return str;
65
+ }
66
+ exports.normalizeUrl = normalizeUrl;
@@ -6,4 +6,3 @@
6
6
  */
7
7
  export declare const isNameTooLong: (str: string) => boolean;
8
8
  export declare const shortName: (str: string) => string;
9
- export declare function simpleHash(str: string, length: number): string;
package/lib/pathUtils.js CHANGED
@@ -6,9 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.simpleHash = exports.shortName = exports.isNameTooLong = void 0;
9
+ exports.shortName = exports.isNameTooLong = void 0;
10
10
  // Based on https://github.com/gatsbyjs/gatsby/pull/21518/files
11
- const crypto_1 = require("crypto");
12
11
  // MacOS (APFS) and Windows (NTFS) filename length limit = 255 chars, Others = 255 bytes
13
12
  const MAX_PATH_SEGMENT_CHARS = 255;
14
13
  const MAX_PATH_SEGMENT_BYTES = 255;
@@ -16,11 +15,9 @@ const MAX_PATH_SEGMENT_BYTES = 255;
16
15
  const SPACE_FOR_APPENDING = 10;
17
16
  const isMacOs = process.platform === `darwin`;
18
17
  const isWindows = process.platform === `win32`;
19
- const isNameTooLong = (str) => {
20
- return isMacOs || isWindows
21
- ? str.length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_CHARS // MacOS (APFS) and Windows (NTFS) filename length limit (255 chars)
22
- : Buffer.from(str).length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_BYTES; // Other (255 bytes)
23
- };
18
+ const isNameTooLong = (str) => isMacOs || isWindows
19
+ ? str.length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_CHARS // MacOS (APFS) and Windows (NTFS) filename length limit (255 chars)
20
+ : Buffer.from(str).length + SPACE_FOR_APPENDING > MAX_PATH_SEGMENT_BYTES; // Other (255 bytes)
24
21
  exports.isNameTooLong = isNameTooLong;
25
22
  const shortName = (str) => {
26
23
  if (isMacOs || isWindows) {
@@ -34,7 +31,3 @@ const shortName = (str) => {
34
31
  .toString();
35
32
  };
36
33
  exports.shortName = shortName;
37
- function simpleHash(str, length) {
38
- return crypto_1.createHash('md5').update(str).digest('hex').substr(0, length);
39
- }
40
- exports.simpleHash = simpleHash;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ export declare type SluggerOptions = {
8
+ maintainCase?: boolean;
9
+ };
10
+ export declare type Slugger = {
11
+ slug: (value: string, options?: SluggerOptions) => string;
12
+ };
13
+ export declare function createSlugger(): Slugger;
package/lib/slugger.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.createSlugger = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const github_slugger_1 = (0, tslib_1.__importDefault)(require("github-slugger"));
12
+ function createSlugger() {
13
+ const githubSlugger = new github_slugger_1.default();
14
+ return {
15
+ slug: (value, options) => githubSlugger.slug(value, options === null || options === void 0 ? void 0 : options.maintainCase),
16
+ };
17
+ }
18
+ exports.createSlugger = createSlugger;
package/lib/tags.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ export declare type Tag = {
8
+ label: string;
9
+ permalink: string;
10
+ };
11
+ export declare type FrontMatterTag = string | Tag;
12
+ export declare function normalizeFrontMatterTag(tagsPath: string, frontMatterTag: FrontMatterTag): Tag;
13
+ export declare function normalizeFrontMatterTags(tagsPath: string, frontMatterTags: FrontMatterTag[] | undefined): Tag[];
14
+ export declare type TaggedItemGroup<Item> = {
15
+ tag: Tag;
16
+ items: Item[];
17
+ };
18
+ export declare function groupTaggedItems<Item>(items: Item[], getItemTags: (item: Item) => Tag[]): Record<string, TaggedItemGroup<Item>>;