-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
508 lines (429 loc) · 17.2 KB
/
index.js
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import { snakeCaseKeys } from '@jungvonmatt/contentful-ssg/lib/object';
import { getContentId, getContentTypeId } from '@jungvonmatt/contentful-ssg/lib/contentful';
import mm from 'micromatch';
import { existsSync } from 'fs';
import { outputFile } from 'fs-extra';
import { readFile } from 'fs/promises';
import path from 'path';
export const TYPE_CONTENT = 'content';
export const TYPE_DATA = 'data';
export const STRATEGY_DIRECTORY = 'directory';
export const STRATEGY_FILENAME = 'filename';
const defaultOptions = {
typeIdSettings: 'd-settings',
translationStrategy: STRATEGY_DIRECTORY,
typeIdI18n: 'd-i18n',
languageConfig: true,
menuDepth: 2,
autoSubMenu: false,
typeIdMenu: 'c-menu',
fieldIdHome: 'home',
fieldIdSlug: 'slug',
fieldIdParent: 'parent_page',
fieldIdMenu: 'submenu',
fieldIdMenuEntries: 'entries',
fieldIdMenuHide: 'hide_in_menu',
fieldIdMenuPos: 'menu_pos',
fieldIdMenuId: 'name',
menuRootTypes: ['page', 'folder', 'x-folder'],
typeConfig: {
[TYPE_CONTENT]: ['page'],
},
};
// Currently Hugo language internals lowercase language codes,
// which can cause conflicts with settings like defaultContentLanguage
// which are not lowercased
// See https://github.com/gohugoio/hugo/issues/7344
// https://gohugo.io/content-management/multilingual/#configure-languages
const hugoLocaleCode = (locale) => locale.code.toLowerCase();
export default (args) => {
const options = { ...defaultOptions, ...(args || {}) };
const getSettingsHelper = (runtimeContext) => {
let settings = {};
if (options.typeIdSettings) {
settings = Object.fromEntries(
Array.from((runtimeContext?.localized ?? new Map()).entries()).map(
([locale, contentfulData]) => {
const entryMap = contentfulData?.entryMap ?? new Map();
const settingsEntries = Array.from(entryMap.values()).filter(
(entry) => (entry?.sys?.contentType?.sys?.id ?? 'unknown') === options.typeIdSettings,
);
const settingsFields = settingsEntries
.map((entry) => entry?.fields ?? {})
.reduce((result, fields) => ({ ...result, ...fields }), {});
return [locale, settingsFields];
},
),
);
}
return (key, locale, defaultValue) => settings?.[locale]?.[key] ?? defaultValue;
};
const getEntryType = (transformContext) => {
const { contentTypeId } = transformContext;
const [type = TYPE_DATA] =
Object.entries(options?.typeConfig ?? {}).find(([, pattern]) =>
mm.isMatch(contentTypeId, pattern),
) || [];
return type;
};
const getPageRef = (transformContext, runtimeContext, node) => {
const { utils, locale } = transformContext;
const { localized, defaultLocale } = runtimeContext;
const id = node?.sys?.id;
const localeData =
options.translationStrategy === STRATEGY_FILENAME
? localized.get(defaultLocale)
: localized.get(locale.code);
const { entryMap } = localeData;
const entry = entryMap.get(id);
const contentType = getContentTypeId(entry);
if (!options.typeConfig[TYPE_CONTENT].includes(contentType)) {
if (entry?.fields?.link_to_entry?.sys?.id) {
return getPageRef(transformContext, runtimeContext, entry.fields.link_to_entry);
}
if (entry?.fields?.link_to_url) {
const url = new URL(entry.fields.link_to_url);
return url.pathname.slice(1);
}
}
const slugs = utils.collectValues(`fields.${options.fieldIdSlug}`, {
linkField: `fields.${options.fieldIdParent}`,
entry,
entryMap,
});
return (slugs || [entry?.fields?.[options.fieldIdSlug]]).filter((v) => v).join('/');
};
const buildMenu = async (transformContext, runtimeContext, depth = 0) => {
const { entry, entryMap } = transformContext;
const getFromEntryMap = (node) => entryMap?.get(getContentId(node));
const entries = entry.fields?.[options.fieldIdMenuEntries] ?? [];
const nodes = entries
.map((node) => getFromEntryMap(node))
.filter((node) => Boolean(node))
.map((node, index) => ({
identifier: getContentId(node),
pageRef: getPageRef(transformContext, runtimeContext, node),
weight: (index + 1) * 10,
params: {
id: getContentId(node),
// eslint-disable-next-line camelcase
content_type: getContentTypeId(node),
},
}));
// Resolve page entry
const resolvePageEntry = async (entry) => {
const id = entry?.sys?.id ?? 0;
const node = entryMap.get(id);
const contentType = node?.sys?.contentType?.sys?.id ?? '';
const pageId = node?.fields?.link_to_entry?.sys?.id;
if (options.menuRootTypes.includes(contentType)) {
return node;
}
if (pageId) {
return entryMap.get(pageId);
}
if (typeof options.resolvePage === 'function') {
return options.resolvePage(entry, entryMap);
}
};
const getChildnodesManual = async (entry, depth, ids = []) => {
const id = entry?.sys?.id ?? 0;
const page = await resolvePageEntry(entry);
const contentType = page?.sys?.contentType?.sys?.id ?? '';
const menuId = page?.fields?.[options.fieldIdMenu]?.sys?.id;
if (
!id ||
!contentType ||
!menuId ||
!entryMap.has(menuId) ||
ids.includes(id) ||
depth <= 0
) {
return [];
}
const menu = entryMap.get(menuId);
const subentries = menu?.fields?.[options.fieldIdMenuEntries] ?? [];
const collected = await Promise.all(
subentries.flatMap((node) => getChildnodesManual(node, depth - 1, [...ids, id])),
);
return [
...subentries
.map((node) => getFromEntryMap(node))
.filter((node) => Boolean(node))
.map((node, index) => ({
identifier: getContentId(node),
pageRef: getPageRef(transformContext, runtimeContext, node),
parent: id,
weight: (index + 1) * 10,
params: {
id: getContentId(node),
// eslint-disable-next-line camelcase
content_type: getContentTypeId(node),
},
})),
...collected,
];
};
const getChildnodesRecursive = async (entry, depth) => {
const id = entry?.sys?.id ?? 0;
const page = await resolvePageEntry(id);
const contentType = page?.sys?.contentType?.sys?.id ?? '';
if (!id || !contentType || depth <= 0) {
return [];
}
const childnodes = [...entryMap.values()].filter(
(entry) => (entry?.fields?.[options.fieldIdParent]?.sys?.id ?? '') === id,
);
// Filter childnodes based on hide_in_menu field
const filtered = childnodes.filter(
(entry) => !(entry?.fields?.[options.fieldIdMenuHide] ?? false),
);
// Sort based on menuPos field
const sorted = [...filtered].sort(
(a, b) =>
(a?.fields?.[options.fieldIdMenuPos] ?? Number.MAX_SAFE_INTEGER) -
(b?.fields?.[options.fieldIdMenuPos] ?? Number.MAX_SAFE_INTEGER),
);
return Array.from(
await Promise.allSettled([
...sorted
.map((node) => getFromEntryMap(node))
.filter((node) => Boolean(node))
.map((node, index) => ({
identifier: getContentId(node),
pageRef: getPageRef(transformContext, runtimeContext, node),
parent: id,
weight: (index + 1) * 10,
params: {
id: getContentId(node),
// eslint-disable-next-line camelcase
content_type: getContentTypeId(node),
},
})),
...sorted.flatMap((node) => getChildnodesRecursive(node, depth - 1)),
]),
)
.map((a) => a.value)
.filter((v) => v);
};
// When autoSubMenu parameter is set, we collect child pages automatically
// Otherwise we look for dedicated menu entries in page nodes
const childentries = options.autoSubMenu
? await Promise.all(entries.flatMap((node) => getChildnodesRecursive(node, depth)))
: await Promise.all(entries.flatMap((node) => getChildnodesManual(node, depth)));
return [...nodes, ...childentries].flat(Infinity).filter((v) => v);
};
return {
config(prev) {
const { managedDirectories } = prev || {};
return { ...prev, managedDirectories: [...(managedDirectories || []), 'data'] };
},
// Before hook
async before(runtimeContext) {
const { helper, converter, data, localized } = runtimeContext;
const locales = data?.locales ?? [];
// Initialize getSettings
const getSettings = getSettingsHelper(runtimeContext);
helper.getSettings = getSettings;
// Write config yaml according to locale settings in contentful
if (options.languageConfig) {
const rootDir = runtimeContext?.config?.rootDir ?? process.cwd();
const mainConfigFile = path.join(rootDir, 'config/_default/config.yaml');
const mainConfig = converter.yaml.parse(await readFile(mainConfigFile));
const defaultLocale = locales.find((locale) => locale.default);
if (defaultLocale && mainConfig.languageCode) {
mainConfig.languageCode = hugoLocaleCode(defaultLocale);
}
if (defaultLocale && mainConfig.defaultContentLanguage) {
mainConfig.defaultContentLanguage = hugoLocaleCode(defaultLocale);
}
await outputFile(mainConfigFile, converter.yaml.stringify(mainConfig));
const dst = path.join(rootDir, 'config/_default/languages.yaml');
const languageConfig = Object.fromEntries(
locales.map((locale) => {
const { code, name: languageName } = locale;
const languageCode = code;
const localeConfig = {
languageCode,
languageName,
weight: locale.default ? 1 : 2,
};
return [
hugoLocaleCode(locale),
options.translationStrategy === 'directory'
? { contentDir: `content/${hugoLocaleCode(locale)}`, ...localeConfig }
: localeConfig,
];
}),
);
await outputFile(dst, converter.yaml.stringify(languageConfig));
}
// Find section pages and add them to the runtimeconfig
const enhancedLocalized = new Map(
Array.from(localized.entries()).map(([localeCode, contentfulData]) => {
const { entries } = contentfulData;
const sectionIds = entries.reduce((nodes, entry) => {
const id = entry?.fields?.[options.fieldIdParent]?.sys?.id;
if (id) {
nodes.add(id);
}
return nodes;
}, new Set());
return [localeCode, { ...contentfulData, sectionIds }];
}),
);
return { ...runtimeContext, helper, localized: enhancedLocalized };
},
/**
* Add path markdown files for entry links
* @param transformContext
* @param runtimeContext
* @returns
*/
async mapEntryLink(transformContext, runtimeContext, prev) {
const directory = await runtimeContext.hooks.mapDirectory(transformContext);
const filename = await runtimeContext.hooks.mapFilename(transformContext);
return { ...prev, path: path.join(directory, filename) };
},
/**
* Map directories
* @param transformContext
* @returns
*/
async mapDirectory(transformContext) {
const { contentTypeId, locale } = transformContext;
const type = getEntryType(transformContext);
if (type === TYPE_CONTENT) {
return options.translationStrategy === STRATEGY_FILENAME ? '' : hugoLocaleCode(locale);
}
return options.translationStrategy === STRATEGY_FILENAME
? path.join('../data', contentTypeId)
: path.join('../data', hugoLocaleCode(locale), contentTypeId);
},
/**
* Map filenames data files to data, headless bundles to headless folder and pages in a
* directory structure which matches the sitemap
* @param transformContext
* @param {RuntimeContext} runtimeContext
* @returns
*/
async mapFilename(transformContext, runtimeContext) {
const { id, locale, entry, contentTypeId, utils } = transformContext;
const { helper, localized, defaultLocale } = runtimeContext;
const sectionIds = localized?.get(locale.code)?.sectionIds ?? new Set();
const localeData =
options.translationStrategy === STRATEGY_FILENAME
? localized.get(defaultLocale)
: localized.get(locale.code);
const collectEntryMap = localeData.entryMap;
const collectEntry = collectEntryMap.get(entry.sys.id);
const type = getEntryType(transformContext);
const home = helper.getSettings(options.fieldIdHome, locale.code);
const homeId = home?.sys?.id;
if (homeId && entry?.sys?.id === homeId) {
return options.translationStrategy === STRATEGY_FILENAME
? `/_index.${hugoLocaleCode(locale)}.md`
: `/_index.md`;
}
if (contentTypeId === options.typeIdSettings) {
return options.translationStrategy === STRATEGY_FILENAME
? `../settings.${hugoLocaleCode(locale)}.yaml`
: '../settings.yaml';
}
if (type === TYPE_CONTENT && sectionIds.has(id)) {
const slugs = utils.collectValues(`fields.${options.fieldIdSlug}`, {
linkField: `fields.${options.fieldIdParent}`,
entry: collectEntry,
entryMap: collectEntryMap,
});
return options.translationStrategy === STRATEGY_FILENAME
? path.join(...(slugs || []).filter((v) => v), `_index.${hugoLocaleCode(locale)}.md`)
: path.join(...(slugs || []).filter((v) => v), `_index.md`);
}
if (type === TYPE_CONTENT) {
const slugs = utils.collectParentValues(`fields.${options.fieldIdSlug}`, {
linkField: `fields.${options.fieldIdParent}`,
entry: collectEntry,
entryMap: collectEntryMap,
});
return options.translationStrategy === STRATEGY_FILENAME
? path.join(
...(slugs || []).filter((v) => v),
`${collectEntry?.fields?.[options.fieldIdSlug] ?? 'unknown'}.${hugoLocaleCode(
locale,
)}.md`,
)
: path.join(
...(slugs || []).filter((v) => v),
`${collectEntry?.fields?.[options.fieldIdSlug] ?? 'unknown'}.md`,
);
}
return options.translationStrategy === STRATEGY_FILENAME
? `${id}.${hugoLocaleCode(locale)}.yaml`
: `${id}.yaml`;
},
async transform(transformContext, runtimeContext) {
const { content, id, contentTypeId, locale, entry } = transformContext;
const type = getEntryType(transformContext);
// Automatically store dictionary entries in i18n/[locale].json
// See https://gohugo.io/content-management/multilingual/#query-basic-translation
if (options.typeIdI18n && contentTypeId === options.typeIdI18n) {
const { key, other, one } = content;
const translations = one ? { one, other } : { other };
if (!runtimeContext.i18n) {
runtimeContext.i18n = {};
}
if (!runtimeContext.i18n[hugoLocaleCode(locale)]) {
runtimeContext.i18n[hugoLocaleCode(locale)] = {};
}
runtimeContext.i18n[hugoLocaleCode(locale)][key] = translations;
// Dont't write i-18n objects to the content folder
return undefined;
}
// Automatically build hugo menus
// See https://gohugo.io/content-management/menus/
if (options.typeIdMenu && contentTypeId === options.typeIdMenu) {
const menuId = entry.fields[options.fieldIdMenuId];
const menu = await buildMenu(transformContext, runtimeContext, options.menuDepth);
if (!runtimeContext.menus) {
runtimeContext.menus = {};
}
if (!runtimeContext.menus[hugoLocaleCode(locale)]) {
runtimeContext.menus[hugoLocaleCode(locale)] = {};
}
runtimeContext.menus[hugoLocaleCode(locale)][menuId] = menu;
}
if (type === TYPE_CONTENT) {
return {
...snakeCaseKeys({
...content,
}),
translationKey: id,
};
}
return snakeCaseKeys(content);
},
async after(runtimeContext) {
const contentDir = runtimeContext.config.directory;
const { yaml } = runtimeContext.converter;
const i18n = runtimeContext?.i18n ?? {};
await Promise.all(
Object.entries(i18n).map(async ([localeCode, translations]) => {
const dictionaryPath = path.join(contentDir, `../i18n/${localeCode}.yaml`);
const oldContent = existsSync(dictionaryPath)
? yaml.parse(await readFile(dictionaryPath, 'utf8'))
: {};
return outputFile(dictionaryPath, yaml.stringify({ ...oldContent, ...translations }));
}),
);
const menus = runtimeContext?.menus ?? {};
await Promise.all(
Object.entries(menus).map(([localeCode, menuData]) => {
const file = `config/_default/menus.${localeCode}.yaml`;
const data = yaml.stringify(menuData);
return outputFile(file, data);
}),
);
},
};
};