-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathgenerate-tutorials.mjs
More file actions
235 lines (199 loc) Β· 7.62 KB
/
generate-tutorials.mjs
File metadata and controls
235 lines (199 loc) Β· 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/* eslint-disable @silverhand/fp/no-mutating-methods, no-await-in-loop */
import { existsSync, promises as fs } from 'node:fs';
import path from 'node:path';
import { load } from 'js-yaml';
const locales = ['en', 'es', 'fr', 'ja', 'th'];
const getDocRelativePath = (fullPath) => fullPath.split('/').slice(0, -1).join('/');
const getSlugByPath = (fullPath, locale) =>
'/' +
fullPath
.split('/')
.slice(locale === 'en' ? 1 : 3, -1)
.join('/');
const hasTutorialFragment = (fullPath) => {
const isSdk = fullPath.includes('/quick-starts/framework/');
const isConnector = fullPath.includes('/integrations/');
return (
(isSdk && existsSync(path.join(getDocRelativePath(fullPath), '_for-tutorial.mdx'))) ||
(isConnector && existsSync(path.join(getDocRelativePath(fullPath), '_integration.mdx')))
);
};
const getInputDocsDir = (locale) =>
locale === 'en' ? 'docs' : `i18n/${locale}/docusaurus-plugin-content-docs/current`;
const getOutputDir = (locale) =>
locale === 'en'
? 'tutorial/build-with-logto'
: `i18n/${locale}/docusaurus-plugin-content-blog-tutorial/build-with-logto`;
const getSdkDisplayName = (sdk) =>
String(sdk.frontMatter.tutorial_name ?? sdk.frontMatter.sidebar_label ?? '');
const getConnectorDisplayName = (connector) =>
String(connector.frontMatter.tutorial_name ?? connector.frontMatter.sidebar_label ?? '');
const getSdkPath = (metadata) => {
const sdkName = String(metadata.frontMatter.tutorial_name ?? '');
return sdkName
? sdkName.replaceAll(' ', '-').replaceAll(/[()]/g, '').replaceAll('.', 'dot').toLowerCase()
: metadata.slug.split('/').slice(2).join('-');
};
const getConnectorPath = (metadata) => {
const connectorName = String(
metadata.frontMatter.tutorial_name ?? metadata.frontMatter.sidebar_label ?? ''
);
return connectorName
.toLowerCase()
.split(/[^\da-z-]/gi) // Remove non-alphanumeric characters
.filter(Boolean)
.join('-');
};
/**
* Extract frontmatter from MDX file content
* @param {string} content - MDX file content
* @returns {Object|null} Parsed frontmatter object or null if not found
*/
function extractFrontmatter(content) {
const frontmatterRegex = /^---\s*\n([\S\s]*?)\n---/;
const match = content.match(frontmatterRegex);
if (!match) {
return null;
}
try {
return load(match[1]) || {};
} catch (error) {
console.error('Error parsing YAML frontmatter:', error.message);
return null;
}
}
/**
* Process all MDX files in a directory recursively
* @param {string} dir - Directory to search for MDX files
* @returns {Array} Array of objects with file path and frontmatter
*/
async function processMdxFiles(dir, locale) {
const results = [];
async function walkDir(currentPath) {
const files = await fs.readdir(currentPath, { withFileTypes: true });
for (const file of files) {
const fullPath = path.join(currentPath, file.name);
if (file.isDirectory()) {
await walkDir(fullPath);
} else if (file.name.endsWith('.mdx')) {
try {
const content = await fs.readFile(fullPath, 'utf8');
const title = content.match(/# (.+)/)?.[1];
const frontMatter = extractFrontmatter(content);
if (frontMatter && hasTutorialFragment(fullPath)) {
results.push({
file: fullPath,
title: frontMatter.title ?? title,
slug: frontMatter.slug ?? getSlugByPath(fullPath, locale),
frontMatter,
});
}
} catch (error) {
console.error(`Error reading file ${fullPath}:`, error.message);
}
}
}
}
await walkDir(dir);
return results;
}
const generate = async (
sdks,
connectors,
template,
outputDir,
/**
* The type of the passwordless connector. Value is either "Email" or "SMS".
* Social connectors should leave this empty.
*/
type
) => {
await Promise.all(
sdks.flatMap((sdk) =>
connectors.flatMap(async (connector) => {
const connectorPath = getConnectorPath(connector);
const sdkPath = getSdkPath(sdk);
/* eslint-disable no-template-curly-in-string */
const post = template
.replaceAll('${connector}', getConnectorDisplayName(connector))
.replaceAll('${connectorPath}', connectorPath)
// How the connector service provider call it. E.g. GitHub calls it "GitHub OAuth app"
.replaceAll(
'${connectorConfigName}',
String(connector.frontMatter.tutorial_config_name ?? '')
)
.replaceAll('${connectorType}', type ?? '')
.replaceAll('${connectorTypeLowerCase}', (type ?? '').toLowerCase())
.replaceAll(
'${passwordlessSignUpIdentifier}',
String(connector.frontMatter.tutorial_sign_up_identifier ?? '')
)
.replaceAll('${connectorDocDir}', getDocRelativePath(connector.file))
.replaceAll('${sdkDocDir}', getDocRelativePath(sdk.file))
.replaceAll('${sdk}', getSdkDisplayName(sdk))
.replaceAll('${sdkPath}', sdkPath)
.replaceAll('${sdkOfficialLink}', String(sdk.frontMatter.official_link))
.replaceAll('${language}', String(sdk.frontMatter.language))
.replaceAll('${appType}', String(sdk.frontMatter.app_type))
.replaceAll('${framework}', String(sdk.frontMatter.framework));
/* eslint-enable no-template-curly-in-string */
const filename = `generated-${sdkPath}-${connectorPath}.mdx`;
const outputFilename = path.join(outputDir, filename);
await fs.writeFile(outputFilename, post, 'utf8');
console.log('Generated', outputFilename);
})
)
);
};
async function run(locale) {
const inputDocsDir = getInputDocsDir(locale);
const outputDir = getOutputDir(locale);
const socialTemplatePath = path.join(outputDir, '_template-social.mdx');
const passwordlessTemplatePath = path.join(outputDir, '_template-passwordless.mdx');
const ssoTemplatePath = path.join(outputDir, '_template-sso.mdx');
const [socialTemplate, passwordlessTemplate, ssoTemplate] = await Promise.all([
fs.readFile(socialTemplatePath, 'utf8'),
fs.readFile(passwordlessTemplatePath, 'utf8'),
fs.readFile(ssoTemplatePath, 'utf8'),
]);
const [sdks, socialConnectors, emailConnectors, smsConnectors, ssoConnectors] = await Promise.all(
[
processMdxFiles(path.join(inputDocsDir, 'quick-starts/framework'), locale),
processMdxFiles(path.join(inputDocsDir, 'integrations/social'), locale),
processMdxFiles(path.join(inputDocsDir, 'integrations/email'), locale),
processMdxFiles(path.join(inputDocsDir, 'integrations/sms'), locale),
processMdxFiles(path.join(inputDocsDir, 'integrations/sso'), locale),
]
);
if (locale === 'en') {
// Write tutorial metadata of default locale to output folder as json
await fs.writeFile(
path.join(outputDir, 'metadata.json'),
JSON.stringify(
{
sdks,
socialConnectors,
emailConnectors,
smsConnectors,
ssoConnectors,
},
null,
2
)
);
}
await Promise.all([
generate(sdks, socialConnectors, socialTemplate, outputDir),
generate(sdks, emailConnectors, passwordlessTemplate, outputDir, 'Email'),
generate(sdks, smsConnectors, passwordlessTemplate, outputDir, 'SMS'),
generate(sdks, ssoConnectors, ssoTemplate, outputDir),
]);
}
try {
await Promise.all(locales.map((locale) => run(locale)));
} catch (error) {
console.error('Error generating tutorials:', error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}
/* eslint-enable @silverhand/fp/no-mutating-methods, no-await-in-loop */