@jpmorganchase/mosaic-plugins 0.1.0-beta.3 → 0.1.0-beta.31

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 (69) hide show
  1. package/dist/$AliasPlugin.d.ts +10 -0
  2. package/dist/$AliasPlugin.js +55 -0
  3. package/dist/$AliasPlugin.js.map +1 -0
  4. package/dist/$CodeModPlugin.d.ts +7 -0
  5. package/dist/$CodeModPlugin.js +24 -0
  6. package/dist/$CodeModPlugin.js.map +1 -0
  7. package/dist/$RefPlugin.d.ts +31 -0
  8. package/dist/$RefPlugin.js +119 -0
  9. package/dist/$RefPlugin.js.map +1 -0
  10. package/dist/$TagPlugin.d.ts +28 -0
  11. package/dist/$TagPlugin.js +65 -0
  12. package/dist/$TagPlugin.js.map +1 -0
  13. package/dist/BreadcrumbsPlugin.d.ts +18 -0
  14. package/dist/BreadcrumbsPlugin.js +38 -0
  15. package/dist/BreadcrumbsPlugin.js.map +1 -0
  16. package/dist/BrokenLinksPlugin.d.ts +10 -0
  17. package/dist/BrokenLinksPlugin.js +80 -0
  18. package/dist/BrokenLinksPlugin.js.map +1 -0
  19. package/dist/LazyPagePlugin.d.ts +14 -0
  20. package/dist/LazyPagePlugin.js +63 -0
  21. package/dist/LazyPagePlugin.js.map +1 -0
  22. package/dist/LocalFolderSavePlugin.d.ts +6 -0
  23. package/dist/LocalFolderSavePlugin.js +21 -0
  24. package/dist/LocalFolderSavePlugin.js.map +1 -0
  25. package/dist/PagesWithoutFileExtPlugin.d.ts +9 -0
  26. package/dist/PagesWithoutFileExtPlugin.js +29 -0
  27. package/dist/PagesWithoutFileExtPlugin.js.map +1 -0
  28. package/dist/PublicAssetsPlugin.d.ts +18 -0
  29. package/dist/PublicAssetsPlugin.js +28 -0
  30. package/dist/PublicAssetsPlugin.js.map +1 -0
  31. package/dist/ReadingTimePlugin.d.ts +10 -0
  32. package/dist/ReadingTimePlugin.js +23 -0
  33. package/dist/ReadingTimePlugin.js.map +1 -0
  34. package/dist/SearchIndexPlugin.d.ts +56 -0
  35. package/dist/SearchIndexPlugin.js +152 -0
  36. package/dist/SearchIndexPlugin.js.map +1 -0
  37. package/dist/SharedConfigPlugin.d.ts +13 -0
  38. package/dist/SharedConfigPlugin.js +34 -0
  39. package/dist/SharedConfigPlugin.js.map +1 -0
  40. package/dist/SidebarPlugin.d.ts +38 -0
  41. package/dist/SidebarPlugin.js +207 -0
  42. package/dist/SidebarPlugin.js.map +1 -0
  43. package/dist/SiteMapPlugin.d.ts +9 -0
  44. package/dist/SiteMapPlugin.js +28 -0
  45. package/dist/SiteMapPlugin.js.map +1 -0
  46. package/dist/TableOfContentsPlugin.d.ts +20 -0
  47. package/dist/TableOfContentsPlugin.js +43 -0
  48. package/dist/TableOfContentsPlugin.js.map +1 -0
  49. package/dist/utils/normaliseRefs.d.ts +1 -0
  50. package/dist/utils/normaliseRefs.js +66 -0
  51. package/dist/utils/normaliseRefs.js.map +1 -0
  52. package/package.json +41 -15
  53. package/.turbo/turbo-build.log +0 -14
  54. package/CHANGELOG.md +0 -34
  55. package/src/$AliasPlugin.ts +0 -62
  56. package/src/$CodeModPlugin.ts +0 -34
  57. package/src/$RefPlugin.ts +0 -200
  58. package/src/$TagPlugin.ts +0 -99
  59. package/src/BreadcrumbsPlugin.ts +0 -43
  60. package/src/LazyPagePlugin.ts +0 -101
  61. package/src/NextPrevPagePlugin.ts +0 -80
  62. package/src/PagesWithoutFileExtPlugin.ts +0 -38
  63. package/src/ReadingTimePlugin.mjs.ts +0 -32
  64. package/src/SharedConfigPlugin.ts +0 -49
  65. package/src/SidebarPlugin.ts +0 -154
  66. package/src/SiteMapPlugin.ts +0 -44
  67. package/src/TableOfContentsPlugin.mjs.ts +0 -52
  68. package/src/utils/normaliseRefs.ts +0 -85
  69. package/tsconfig.json +0 -21
package/src/$RefPlugin.ts DELETED
@@ -1,200 +0,0 @@
1
- import path from 'path';
2
-
3
- import reduce from 'lodash/reduce';
4
- import omit from 'lodash/omit';
5
-
6
- import escapeRegExp from 'lodash/escapeRegExp';
7
- import $RefParser from '@apidevtools/json-schema-ref-parser';
8
-
9
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
10
- import type Page from '@jpmorganchase/mosaic-types/dist/Page';
11
-
12
- import normaliseRefs from './utils/normaliseRefs';
13
-
14
- /**
15
- * Plugin that scrapes `$ref` properties from page metadata and also applies all refs stored in `config.data.refs`.
16
- * Other plugins can use `setRef` to apply new refs, as long as they call it before this plugin has reaches `$beforeSend`
17
- */
18
- const $RefPlugin: PluginType<{
19
- refs: { [key: string]: { $$path: string[]; $$value: string }[] };
20
- globalRefs: { [key: string]: { $$path: string[]; $$value: string }[] };
21
- subscribedTags: string[];
22
- }> = {
23
- async afterUpdate(
24
- mutableFilesystem,
25
- { ignorePages, globalFilesystem, serialiser, pageExtensions, globalConfig }
26
- ) {
27
- mutableFilesystem.__internal_do_not_use_addReadFileHook(async (pagePath: string, fileData) => {
28
- if (globalConfig.data.globalRefs[pagePath]) {
29
- const normalisedRef = {
30
- ...(await serialiser.deserialise(pagePath, fileData)),
31
- ...(await normaliseRefs(
32
- String(pagePath),
33
- globalConfig.data.globalRefs[pagePath],
34
- globalFilesystem,
35
- pageExtensions,
36
- ignorePages
37
- ))
38
- } as any;
39
- const resolve = createRefResolver({
40
- [pagePath]: normalisedRef
41
- }, serialiser, globalFilesystem);
42
- const refParser = new $RefParser();
43
-
44
- try {
45
- const resolved: $RefParser.JSONSchema = await refParser.dereference(
46
- String(pagePath),
47
- normalisedRef,
48
- {
49
- resolve,
50
- dereference: { circular: false }
51
- }
52
- );
53
- return serialiser.serialise(pagePath, { ...normalisedRef, ...resolved });
54
- } catch (e) {
55
- console.warn(
56
- `Error resolving ref(s) for page '${pagePath}'. ${e.message.replace(/\.$/, '')} in '${
57
- e.source
58
- }'`
59
- );
60
- throw e;
61
- }
62
- }
63
-
64
- return fileData;
65
- });
66
- },
67
- async $beforeSend(
68
- mutableFilesystem,
69
- { config, serialiser, pageExtensions, ignorePages },
70
- options
71
- ) {
72
- // Prevent any more refs being set after this lifecycle has been called - as they won't take effect
73
- config.setRef = () => {
74
- throw new Error(
75
- 'Cannot set refs after `RefPlugin` has reached `$beforeSend` lifecycle phase.'
76
- );
77
- };
78
- const normalisedRefs = {};
79
-
80
- if (config.data.refs) {
81
- // First pass of refs, normalises any $ref entries to expand wildcards
82
- for (const fullPath in config.data.refs) {
83
- const page: Page = await serialiser.deserialise(
84
- fullPath,
85
- await mutableFilesystem.promises.readFile(fullPath)
86
- );
87
-
88
- normalisedRefs[fullPath] = {
89
- ...page,
90
- ...(await normaliseRefs(
91
- String(fullPath),
92
- config.data.refs[fullPath],
93
- mutableFilesystem,
94
- pageExtensions,
95
- ignorePages
96
- ))
97
- };
98
- }
99
-
100
- const resolve = createRefResolver(normalisedRefs, serialiser, mutableFilesystem);
101
- const refParser = new $RefParser();
102
-
103
- // Second pass of refs, resolves the refs
104
- for (const fullPath in normalisedRefs) {
105
- const page = normalisedRefs[fullPath];
106
- try {
107
- const resolved: $RefParser.JSONSchema = await refParser.dereference(
108
- String(fullPath),
109
- page,
110
- {
111
- resolve,
112
- dereference: { circular: false }
113
- }
114
- );
115
- normalisedRefs[fullPath] = { ...page, ...resolved };
116
- } catch (e) {
117
- console.warn(
118
- `Error resolving ref(s) for page '${fullPath}'. ${e.message.replace(/\.$/, '')} in '${
119
- e.source
120
- }'`
121
- );
122
- throw e;
123
- }
124
- }
125
- // Third pass, write out the files
126
- for (const fullPath in normalisedRefs) {
127
- await mutableFilesystem.promises.writeFile(
128
- fullPath,
129
- await serialiser.serialise(fullPath, normalisedRefs[fullPath])
130
- );
131
- }
132
- }
133
- },
134
- async $afterSource(pages: Page[], { config, ignorePages, pageExtensions }) {
135
- const isNonHiddenPage = createPageTest(ignorePages, pageExtensions);
136
-
137
- for (const page of pages) {
138
- if (!isNonHiddenPage(page.fullPath)) {
139
- continue;
140
- }
141
- const refs = findKeys(page, '$ref');
142
-
143
- if (refs.length) {
144
- for (const ref of refs) {
145
- config.setRef(page.fullPath, ...ref);
146
- }
147
- }
148
- }
149
- return pages;
150
- }
151
- };
152
-
153
- export default $RefPlugin;
154
-
155
- function createRefResolver(normalisedRefs, serialiser, mutableFilesystem) {
156
- return {
157
- file: {
158
- canRead: true,
159
- order: 1,
160
- async read(file, callback) {
161
- try {
162
- const refedPage =
163
- normalisedRefs[file.url] ||
164
- (await serialiser.deserialise(
165
- file.url,
166
- await mutableFilesystem.promises.readFile(file.url)
167
- ));
168
- return callback(null, omit(refedPage, 'content'));
169
- } catch (e) {
170
- return callback(e, null);
171
- }
172
- }
173
- }
174
- };
175
- }
176
-
177
- const findKeys = (obj, targetProp, pathParts: string[] = []): [string[], string][] => {
178
- return reduce<string, [string[], string][]>(
179
- obj,
180
- (found, value, key) => {
181
- if (key === targetProp) {
182
- return found.concat([[pathParts.concat(String(key)), value]]);
183
- }
184
- if (typeof value === 'object') {
185
- const foundParents = findKeys(value, targetProp, pathParts.concat(String(key)));
186
- return found.concat(foundParents);
187
- }
188
- return found;
189
- },
190
- []
191
- );
192
- };
193
-
194
- function createPageTest(ignorePages, pageExtensions) {
195
- const extTest = new RegExp(`${pageExtensions.map(escapeRegExp).join('|')}$`);
196
- const ignoreTest = new RegExp(`${ignorePages.map(escapeRegExp).join('|')}$`);
197
- return file => {
198
- return !ignoreTest.test(file) && extTest.test(file) && !path.basename(file).startsWith('.');
199
- };
200
- }
package/src/$TagPlugin.ts DELETED
@@ -1,99 +0,0 @@
1
- import path from 'path';
2
-
3
- import reduce from 'lodash/reduce';
4
- import escapeRegExp from 'lodash/escapeRegExp';
5
-
6
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
7
- import type Page from '@jpmorganchase/mosaic-types/dist/Page';
8
- import type Meta from '@jpmorganchase/mosaic-types/dist/Meta';
9
-
10
- /**
11
- * Plugin that scrapes `$tag` from page metadata and also applies all aliases stored in `config.data.tags`.
12
- * Tags ultimately resolve down into refs, but are different from normal refs, in that they are applied to the
13
- * union filesystem (all merged filesystems), not to the individual source filesystem that they were defined on.
14
- * Other plugins can use `setData()` and modify the `tags` property, to apply new global refs, as long as
15
- * they do so before this plugin has reaches `$beforeSend`
16
- */
17
- const $TagPlugin: PluginType<{
18
- tagRefs: { [key: string]: { $$path: string[]; $$value: string[] }[] };
19
- globalRefs: { [key: string]: { $$path: string[]; $$value: string[] }[] };
20
- subscribedTags: string[];
21
- }> = {
22
- // Check if the updated source has any /.tag aliases that we care about - if it does, we should re-run `afterUpdate` to
23
- // make sure we pull in the latest pages
24
- async shouldClearCache(updatedSourceFilesystem, { config }) {
25
- if (
26
- !config.data?.subscribedTags ||
27
- !(await updatedSourceFilesystem.promises.exists('/.tags'))
28
- ) {
29
- return false;
30
- }
31
- // Does the updated source have tags we are interested in?
32
- return ((await updatedSourceFilesystem.promises.readdir('/.tags')) as string[]).some(tag =>
33
- config.data.subscribedTags.includes(tag)
34
- );
35
- },
36
- // Every source with tags will create symlinks with the tagged pages, inside /.tags
37
- async $afterSource(pages: Page<{ tags?: string[] }>[], { config, ignorePages, pageExtensions }) {
38
- const isNonHiddenPage = createPageTest(ignorePages, pageExtensions);
39
-
40
- for (const page of pages) {
41
- if (!isNonHiddenPage(page.fullPath)) {
42
- continue;
43
- }
44
- const meta = page as Meta<{ tags?: string[] }>;
45
- // Symlink every `tag` item to '/.tags' folder
46
- if (meta.tags?.length) {
47
- config.setTags(page.fullPath, meta.tags);
48
- delete meta.tags;
49
- }
50
-
51
- // Find any references to $tag
52
- const foundTags = findKeys(page, '$tag');
53
- if (foundTags.length) {
54
- const tags = new Set<string>();
55
-
56
- foundTags.forEach(ref => {
57
- const [tag, fragment = ''] = ref.$$value.split('#');
58
-
59
- tags.add(tag);
60
-
61
- config.setGlobalRef(
62
- page.fullPath,
63
- ref.$$path,
64
- `${path.join('/.tags', tag, '**')}#${fragment}`
65
- );
66
- });
67
- config.setData({ subscribedTags: Array.from(tags) });
68
- }
69
- }
70
- return pages;
71
- }
72
- };
73
-
74
- export default $TagPlugin;
75
-
76
- const findKeys = (obj, targetProp, pathParts: string[] = []) => {
77
- return reduce<string, { $$path: string[]; $$value: string }[]>(
78
- obj,
79
- (found, value, key) => {
80
- if (key === targetProp) {
81
- return found.concat({ $$path: pathParts.concat(String(key)), $$value: value });
82
- }
83
- if (typeof value === 'object') {
84
- const foundParents = findKeys(value, targetProp, pathParts.concat(String(key)));
85
- return found.concat(...foundParents);
86
- }
87
- return found;
88
- },
89
- []
90
- );
91
- };
92
-
93
- function createPageTest(ignorePages, pageExtensions) {
94
- const extTest = new RegExp(`${pageExtensions.map(escapeRegExp).join('|')}$`);
95
- const ignoreTest = new RegExp(`${ignorePages.map(escapeRegExp).join('|')}$`);
96
- return file => {
97
- return !ignoreTest.test(file) && extTest.test(file) && !path.basename(file).startsWith('.');
98
- };
99
- }
@@ -1,43 +0,0 @@
1
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
2
- import type Page from '@jpmorganchase/mosaic-types/dist/Page';
3
- import path from 'path';
4
-
5
- export type Breadcrumb = { label: string; path: string; id: string };
6
-
7
- /**
8
- * Calculates breadcrumbs for pages then embeds a `breadcrumbs` property to the metadata
9
- */
10
- const BreadcrumbsPlugin: PluginType<{}, { indexPageName: string }> = {
11
- async $afterSource(pages: Page[], {}, options) {
12
- for (const page of pages) {
13
- const breadcrumbs: Array<Breadcrumb> = [];
14
- let currentPage = page;
15
- let parentDir = path.posix.dirname(currentPage.fullPath);
16
-
17
- while (currentPage !== undefined) {
18
- if (breadcrumbs.findIndex(breadcrumb => breadcrumb.id === currentPage.fullPath) === -1) {
19
- breadcrumbs.unshift({
20
- label: currentPage.title,
21
- path: currentPage.route,
22
- id: currentPage.fullPath
23
- });
24
- }
25
-
26
- currentPage = pages.find(
27
- page => page.fullPath === path.posix.join(parentDir, options.indexPageName)
28
- );
29
- if (currentPage) {
30
- parentDir = path.posix.dirname(path.posix.join(String(currentPage.fullPath), '..'));
31
- }
32
- }
33
-
34
- if (!page.breadcrumbs) {
35
- page.breadcrumbs = breadcrumbs;
36
- }
37
- }
38
-
39
- return pages;
40
- }
41
- };
42
-
43
- export default BreadcrumbsPlugin;
@@ -1,101 +0,0 @@
1
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
2
- import fs from 'fs';
3
- import fsExtra from 'fs-extra';
4
- import merge from 'lodash/merge';
5
- import escapeRegExp from 'lodash/escapeRegExp';
6
- import path from 'path';
7
- import { TDataOut } from 'memfs/lib/encoding';
8
-
9
- const LazyPagePlugin: PluginType<
10
- { aliases: { [key: string]: Set<string> }; hddPaths: { [key: string]: string } },
11
- { cacheDir: string }
12
- > = {
13
- async afterUpdate(mutableFilesystem, { ignorePages, config, pageExtensions, serialiser }) {
14
- const isNonHiddenPage = createPageTest(ignorePages, pageExtensions);
15
-
16
- // This adds a hook that triggers everytime a non-cached page is read from the filesystem.
17
- mutableFilesystem.__internal_do_not_use_addReadFileHook(
18
- async (pagePath: string, fileData: TDataOut) => {
19
- // If this is a 'page' - read the original file from disk and try to inject anything that's missing.
20
- if (isNonHiddenPage(pagePath)) {
21
- const currentPage = await serialiser.deserialise(pagePath, fileData);
22
- if (config.data.hddPaths[pagePath]) {
23
- const page = await serialiser.deserialise(
24
- pagePath,
25
- await fs.promises.readFile(config.data.hddPaths[pagePath])
26
- );
27
- const completePage = await serialiser.serialise(
28
- pagePath,
29
- merge(page, currentPage, { content: page.content })
30
- );
31
- return completePage;
32
- }
33
- }
34
- return fileData;
35
- }
36
- );
37
- },
38
- async $beforeSend(
39
- mutableFilesystem,
40
- { config, serialiser, ignorePages, pageExtensions },
41
- options
42
- ) {
43
- const hddPaths = {};
44
- let originalDiskSize = 0;
45
- let newDiskSize = 0;
46
- const allPages = await mutableFilesystem.promises.glob(createFileGlob('**', pageExtensions), {
47
- ignore: ignorePages.map(ignore => `**/${ignore}`),
48
- cwd: '/',
49
- onlyFiles: true
50
- });
51
- const baseDir = path.join(
52
- process.cwd(),
53
- options.cacheDir || '.mosaic-lazy-page-plugin-cache'
54
- );
55
- await fsExtra.ensureDir(baseDir);
56
- for (const filePath of allPages) {
57
- const rawPage = await mutableFilesystem.promises.readFile(String(filePath));
58
- const page = await serialiser.deserialise(String(filePath), rawPage);
59
- originalDiskSize += rawPage.length;
60
- await fs.promises.mkdir(path.dirname(path.join(baseDir, String(filePath))), {
61
- recursive: true
62
- });
63
- await fs.promises.writeFile(
64
- path.join(baseDir, String(filePath)),
65
- await serialiser.serialise(String(filePath), page)
66
- );
67
- const { content, ...pageRest } = page;
68
- hddPaths[String(filePath)] = path.join(baseDir, String(filePath));
69
- const redactedPage = await serialiser.serialise(String(filePath), pageRest);
70
- newDiskSize += redactedPage.length;
71
- }
72
-
73
- config.setData({hddPaths});
74
-
75
- const reduction = originalDiskSize - newDiskSize;
76
- console.info(
77
- `[PullDocs] LazyPagePlugin moved ${((reduction / originalDiskSize) * 100).toFixed(
78
- 2
79
- )}% of virtual filesystem content to the hard disk. This reduced the virtual filesystem size from ${(
80
- originalDiskSize / 1000000
81
- ).toFixed(2)}mb to ${(newDiskSize / 1000000).toFixed(2)}mb (yay!)`
82
- );
83
- }
84
- };
85
-
86
- function createFileGlob(url, pageExtensions) {
87
- if (pageExtensions.length === 1) {
88
- return `${url}${pageExtensions[0]}`;
89
- }
90
- return `${url}{${pageExtensions.join(',')}}`;
91
- }
92
-
93
- export default LazyPagePlugin;
94
-
95
- function createPageTest(ignorePages, pageExtensions) {
96
- const extTest = new RegExp(`${pageExtensions.map(escapeRegExp).join('|')}$`);
97
- const ignoreTest = new RegExp(`${ignorePages.map(escapeRegExp).join('|')}$`);
98
- return file => {
99
- return !ignoreTest.test(file) && extTest.test(file) && !path.basename(file).startsWith('.');
100
- };
101
- }
@@ -1,80 +0,0 @@
1
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
2
- import { escapeRegExp } from 'lodash';
3
-
4
- /**
5
- * Sorts the pages in a folder alphabetically and then embeds a `navigation` property to the metadata with ordered
6
- * next/prev pages
7
- */
8
- const NextPrevPlugin: PluginType<
9
- {
10
- nextPrev: { [key: string]: string[] };
11
- refs: { [key: string]: { $$path: (number | string)[]; $$value: string }[] };
12
- },
13
- { indexFirst?: boolean; sortBy?: 'a-z' }
14
- > = {
15
- async $beforeSend(
16
- mutableFilesystem,
17
- { config, pageExtensions, ignorePages },
18
- { indexFirst, sortBy }
19
- ) {
20
- const pageDirs = (await mutableFilesystem.promises.glob('**', {
21
- onlyDirectories: true,
22
- ignore: ignorePages.map(ignore => `**/${ignore}`),
23
- cwd: '/'
24
- })) as string[];
25
- for (const dirName of pageDirs) {
26
- const pages = (
27
- await mutableFilesystem.promises.glob(createFileGlob('*', pageExtensions), { onlyFiles: true, cwd: dirName, ignore: ignorePages })
28
- ).sort(createSortFn(pageExtensions, { indexFirst, sortBy })) as string[];
29
- for (let i = 0; i < pages.length; i++) {
30
- if (i > 0) {
31
- config.setRef(
32
- pages[i],
33
- ['navigation', 'prev', 'title', '$ref'],
34
- `${pages[i - 1]}#/title`
35
- );
36
- config.setRef(
37
- pages[i],
38
- ['navigation', 'prev', 'fullPath', '$ref'],
39
- `${pages[i - 1]}#/route`
40
- );
41
- }
42
- if (i < pages.length - 1) {
43
- config.setRef(
44
- pages[i],
45
- ['navigation', 'next', 'title', '$ref'],
46
- `${pages[i + 1]}#/title`
47
- );
48
- config.setRef(
49
- pages[i],
50
- ['navigation', 'next', 'fullPath', '$ref'],
51
- `${pages[i + 1]}#/route`
52
- );
53
- }
54
- }
55
- }
56
- }
57
- };
58
-
59
- export default NextPrevPlugin;
60
-
61
- function createFileGlob(url, pageExtensions) {
62
- if (pageExtensions.length === 1) {
63
- return `${url}${pageExtensions[0]}`;
64
- }
65
- return `${url}{${pageExtensions.join(',')}}`;
66
- }
67
-
68
- function createSortFn(pageExtensions, { sortBy: _sortBy, indexFirst }) {
69
- const indexRegExp =
70
- indexFirst && new RegExp(`index${pageExtensions.map(escapeRegExp).join('|')}$`);
71
-
72
- // TODO: Switch out the algorithm here, based on `sortBy`
73
- return function sortFn(fullPathA, fullPathB) {
74
- // Always pin /index to the front
75
- if (indexFirst && indexRegExp.test(fullPathA)) {
76
- return -1;
77
- }
78
- return fullPathA.localeCompare(fullPathB);
79
- };
80
- }
@@ -1,38 +0,0 @@
1
- import type Page from '@jpmorganchase/mosaic-types/dist/Page';
2
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
3
- import { escapeRegExp } from 'lodash';
4
- import path from 'path';
5
-
6
- /**
7
- * Plugin that creates aliases without the file extension for every page emitted by the source.
8
- * This allows pages to be retrieved from the filesystem without specifying `.mdx` (or whatever file extension is specified in `options.stripExt`).
9
- * The plugin also modifies the `route` to point to the shorter alias. Friendly fullPaths are the shortest possible paths that
10
- * will point to the page (see `Page` docs)
11
- */
12
- const PagesWithoutFileExtPlugin: PluginType<
13
- {}
14
- > = {
15
- async $afterSource(pages: Page[], { config, ignorePages, pageExtensions }) {
16
- const isNonHiddenPage = createPageTest(ignorePages, pageExtensions);
17
- const pageTest = new RegExp(`${pageExtensions.map(escapeRegExp).join('|')}$`);
18
-
19
- for (const page of pages) {
20
- if (!isNonHiddenPage(page.fullPath)) {
21
- continue;
22
- }
23
- page.route = page.route.replace(pageTest, '');
24
- config.setAliases(page.fullPath, [page.route]);
25
- }
26
- return pages;
27
- }
28
- };
29
-
30
- export default PagesWithoutFileExtPlugin;
31
-
32
- function createPageTest(ignorePages, pageExtensions) {
33
- const extTest = new RegExp(`${pageExtensions.map(escapeRegExp).join('|')}$`);
34
- const ignoreTest = new RegExp(`${ignorePages.map(escapeRegExp).join('|')}$`);
35
- return file => {
36
- return !ignoreTest.test(file) && extTest.test(file) && !path.basename(file).startsWith('.');
37
- };
38
- }
@@ -1,32 +0,0 @@
1
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
2
- import type Page from '@jpmorganchase/mosaic-types/dist/Page';
3
- import getReadingTime from 'reading-time';
4
- import { unified } from 'unified';
5
- import { visit } from 'unist-util-visit';
6
- import markdown from 'remark-parse';
7
-
8
- /**
9
- * Calculates reading time for pages and adds to frontmatter
10
- */
11
- const ReadingTimePlugin: PluginType<{}> = {
12
- async $afterSource(pages: Page[]) {
13
- const processor = unified().use(markdown);
14
- for (const page of pages) {
15
- const tree = await processor.parse(page.content);
16
- let textContent = '';
17
-
18
- visit(
19
- tree,
20
- node => node.type === 'text' || node.type === 'code',
21
- node => {
22
- textContent += node.value;
23
- }
24
- );
25
- page.readingTime = getReadingTime(textContent);
26
- }
27
-
28
- return pages;
29
- }
30
- };
31
-
32
- export default ReadingTimePlugin;
@@ -1,49 +0,0 @@
1
- import type PluginType from '@jpmorganchase/mosaic-types/dist/Plugin';
2
- import flatten from 'lodash/flatten';
3
- import path from 'path';
4
-
5
- /**
6
- * Plugin that crawls the page hierarchy to find the closest `sharedConfig` from any parent index's page metadata.
7
- * It then exports a JSON file (name: `options.filename`) into each directory with the merged config for that level
8
- */
9
- const SharedConfigPlugin: PluginType<{}, { filename: string }> = {
10
- async $beforeSend(
11
- mutableFilesystem,
12
- { config, serialiser, ignorePages, pageExtensions },
13
- options
14
- ) {
15
- const pagePaths = await mutableFilesystem.promises.glob(
16
- createFileGlob('**/index,/index', pageExtensions),
17
- {
18
- ignore: [options.filename, ...flatten(ignorePages.map(ignore => [ignore, `**/${ignore}`]))],
19
- cwd: '/'
20
- }
21
- );
22
-
23
- for (const pagePath of pagePaths) {
24
- const sharedConfigFile = path.join(path.dirname(String(pagePath)), options.filename);
25
-
26
- const page = await serialiser.deserialise(
27
- String(pagePath),
28
- await mutableFilesystem.promises.readFile(String(pagePath))
29
- );
30
- if (page.sharedConfig) {
31
- config.setRef(sharedConfigFile, ['config', '$ref'], `${String(pagePath)}#/sharedConfig`);
32
- await mutableFilesystem.promises.writeFile(sharedConfigFile, '{}');
33
- } else {
34
- const baseDir = path.resolve(path.dirname(String(pagePath)), '../');
35
-
36
- config.setAliases(path.join(baseDir, options.filename), [sharedConfigFile]);
37
- }
38
- }
39
- }
40
- };
41
-
42
- export default SharedConfigPlugin;
43
-
44
- function createFileGlob(url, pageExtensions) {
45
- if (pageExtensions.length === 1) {
46
- return `${url}${pageExtensions[0]}`;
47
- }
48
- return `${url}{${pageExtensions.join(',')}}`;
49
- }