-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathnuxt.config.ts
More file actions
500 lines (463 loc) · 24.1 KB
/
Copy pathnuxt.config.ts
File metadata and controls
500 lines (463 loc) · 24.1 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
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
import { readdirSync, statSync, readFileSync } from 'node:fs'
import { join, basename } from 'node:path'
import { parse as parseYaml } from 'yaml'
import remarkHandbookLinks from './utils/remark-handbook-links'
import remarkDocsLinks from './utils/remark-docs-links'
import { BLOG_TAGS } from './composables/useBlogList'
import { redirects } from './redirects'
import site from '../src/_data/site.json'
// Collect all handbook routes from content files for SSG prerendering
function collectHandbookRoutes(dir: string, basePath: string): string[] {
const routes: string[] = []
for (const file of readdirSync(dir)) {
const fullPath = join(dir, file)
if (statSync(fullPath).isDirectory()) {
routes.push(...collectHandbookRoutes(fullPath, `${basePath}/${file}`))
} else if (file.endsWith('.md')) {
const slug = basename(file, '.md')
routes.push(slug === 'index' ? `${basePath}/` : `${basePath}/${slug}/`)
}
}
return routes
}
// Same idea for changelog entries, plus the paginated listing (19 entries/page, newest first)
function collectChangelogRoutes(dir: string, basePath: string): { routes: string[], entryCount: number } {
const routes: string[] = []
let entryCount = 0
for (const file of readdirSync(dir)) {
const fullPath = join(dir, file)
if (statSync(fullPath).isDirectory()) {
const nested = collectChangelogRoutes(fullPath, `${basePath}/${file}`)
routes.push(...nested.routes)
entryCount += nested.entryCount
} else if (file.endsWith('.md')) {
entryCount += 1
routes.push(`${basePath}/${basename(file, '.md')}/`)
}
}
return { routes, entryCount }
}
// The Application Guide pages are markdown (`applicationGuideDoc`, a `page` collection).
// Their routes are largely discoverable by @nuxt/content, but we keep an explicit prerender
// list for the section index + each page. File names are <slug>.md and match the `slug` field.
function collectApplicationGuideRoutes(dir: string): string[] {
const routes = ['/application-guide/']
for (const guide of readdirSync(dir)) {
const guideDir = join(dir, guide)
if (!statSync(guideDir).isDirectory()) continue
for (const file of readdirSync(guideDir)) {
if (!file.endsWith('.md')) continue
routes.push(`/application-guide/${guide}/${basename(file, '.md').replace(/^\d+-/, '')}/`)
}
}
return routes
}
// The product tier pages (/product/[tier]/) are a `data` collection (see content.config.ts),
// so their routes aren't discoverable from @nuxt/content page paths either. Derive them from
// each file's `tierId` field rather than the filename, since that's the field the page route
// actually queries on.
function collectProductRoutes (dir: string): string[] {
const routes: string[] = []
for (const file of readdirSync(dir)) {
if (!file.endsWith('.yml')) continue
const { tierId } = parseYaml(readFileSync(join(dir, file), 'utf8'))
routes.push(`/product/${tierId}/`)
}
return routes
}
// Same idea as collectApplicationGuideRoutes above, for customer stories (flat
// src/customer-stories/ dir, see content.config.ts).
function collectStoryRoutes(dir: string): string[] {
const routes = ['/customer-stories/']
for (const file of readdirSync(dir)) {
if (!file.endsWith('.md')) continue
routes.push(`/customer-stories/${basename(file, '.md')}/`)
}
return routes
}
// Same idea for blog posts. Each entry also carries its `tags` so the 13 tag-listing
// pages (and their own pagination, 19 entries/page) can be sized correctly, and its
// `authors` so the /blog/author/{slug}/ pages can be enumerated.
function collectBlogFiles(dir: string, basePath: string): Array<{ route: string, tags: string[], authors: string[] }> {
const results: Array<{ route: string, tags: string[], authors: string[] }> = []
for (const file of readdirSync(dir)) {
const fullPath = join(dir, file)
if (statSync(fullPath).isDirectory()) {
results.push(...collectBlogFiles(fullPath, `${basePath}/${file}`))
} else if (file.endsWith('.md')) {
const raw = readFileSync(fullPath, 'utf-8')
const match = raw.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---/)
const frontmatter = match ? (parseYaml(match[1]) || {}) : {}
const date = frontmatter.date ? new Date(frontmatter.date) : new Date(0)
if (date.getTime() > Date.now() && process.env.CONTEXT === 'production') continue
results.push({ route: `${basePath}/${basename(file, '.md')}/`, tags: frontmatter.tags || [], authors: frontmatter.authors || [] })
}
}
return results
}
// `authors` values that mean "no individual author" - they have no data file by design.
const ORG_AUTHOR_SLUGS = new Set(['-', 'FlowFuse', 'flowfuse', 'flowfuseteam'])
// Author pages are rendered by pages/blog/author/[slug].vue from src/_data/{team,guests}
// rather than from an @nuxt/content collection, so neither prerendering nor the sitemap
// can discover them - enumerate the authors who both have a data file and a published post.
function collectAuthorRoutes(blogFiles: Array<{ authors: string[] }>, dataDirs: string[]): string[] {
const known = new Set(dataDirs.flatMap(dir => readdirSync(dir).filter(f => f.endsWith('.json')).map(f => basename(f, '.json'))))
const withPosts = new Set(blogFiles.flatMap(f => f.authors))
// Anything left is either a former team member or a typo - surface it in the build log.
const missing = [...withPosts].filter(slug => !known.has(slug) && !ORG_AUTHOR_SLUGS.has(slug)).sort()
if (missing.length) {
console.warn(`[blog] ${missing.length} author slug(s) in blog frontmatter have no data file in src/_data/{team,guests}; these posts fall back to the "FlowFuse" byline and get no author page: ${missing.join(', ')}`)
}
return [...withPosts].filter(slug => known.has(slug)).sort().map(slug => `/blog/author/${slug}/`)
}
function paginatedListingRoutes(basePath: string, entryCount: number): string[] {
const pageCount = Math.max(1, Math.ceil(entryCount / 19))
return [`${basePath}/`, ...Array.from({ length: pageCount - 1 }, (_, i) => `${basePath}/${i + 2}/`)]
}
const blogFiles = collectBlogFiles(join(__dirname, '../src/blog'), '/blog')
const blogAuthorRoutes = collectAuthorRoutes(blogFiles, [join(__dirname, '../src/_data/team'), join(__dirname, '../src/_data/guests')])
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
devtools: { enabled: true },
modules: ['@nuxt/ui', '@nuxt/content', '@nuxtjs/seo', 'nuxt-studio', '@nuxt/image', './modules/docs-source', 'nuxt-llms'],
// Captured at build time (Netlify sets CONTEXT during the build, not necessarily
// in the deployed Function's runtime), then baked into the server bundle via
// runtimeConfig so analytics.ts doesn't depend on a process.env read at request time.
runtimeConfig: {
isProductionContext: process.env.CONTEXT === 'production'
},
css: ['~/assets/css/theme.css'],
// Heebo is already loaded via the Google Fonts <link> in app.head.
// @nuxt/fonts is a transitive dep of @nuxt/ui; disable all provider downloads
// so it never fetches font files at build time (which exhausts Netlify's memory).
fonts: { providers: { google: false, bunny: false, fontshare: false, adobe: false } },
site: {
url: site.baseURL,
name: 'FlowFuse',
description: site.messaging.subtitle,
defaultLocale: 'en',
trailingSlash: true,
},
// Only covers content already served by Nuxt. The handbook is deliberately excluded
// (internal company content, not product documentation) - see README.md. Everything
// still on the legacy Eleventy site (customer-stories, use-cases, platform, etc.) isn't
// visible to @nuxt/content, so it's absent here too until those pages are migrated.
llms: {
domain: site.baseURL,
title: 'FlowFuse',
description: `${site.messaging.tagLine} - ${site.messaging.subtitle}`,
full: {
title: 'FlowFuse - Full Documentation',
description: 'Complete FlowFuse documentation, blog, changelog, and resources in a single markdown document.',
},
notes: [
'This file only covers pages served by the Nuxt frontend. Some sections of flowfuse.com are still served by a legacy Eleventy site not represented here.',
],
// /raw/<path>.md, the per-page markdown endpoint the links below point at, is served
// by @nuxt/content's own llms feature rather than by nuxt-llms, and it searches every
// page-type collection by default. That included the handbook, so the exclusion above
// only held for llms.txt while /raw/handbook/company.md answered with the same content
// in markdown. Same reasoning applies to both surfaces.
contentRawMarkdown: {
excludeCollections: ['handbook'],
},
sections: [
{
title: 'Documentation',
description: 'FlowFuse and Node-RED product documentation.',
contentCollection: 'docs',
contentFilters: [
{ field: 'redirect', operator: 'IS NULL' },
],
},
{
title: 'Blog',
description: 'Tutorials, product updates, and industrial application guides.',
contentCollection: 'blog',
},
{
title: 'Changelog',
description: 'Release notes for the FlowFuse platform.',
contentCollection: 'changelog',
},
{
title: 'Ebooks',
description: 'Long-form guides on Node-RED and industrial applications.',
contentCollection: 'ebooks',
},
{
title: 'Whitepapers',
description: 'Long-form guides on Node-RED and industrial applications.',
contentCollection: 'whitepapers',
},
{
title: 'Product & Company',
links: [
{ title: 'Home', href: `${site.baseURL}/`, description: 'FlowFuse platform overview' },
{ title: 'Pricing', href: `${site.baseURL}/pricing/`, description: 'Plans and pricing information' },
{ title: 'Integrations', href: `${site.baseURL}/integrations/`, description: 'Supported integrations and connectors' },
{ title: 'Application Guide', href: `${site.baseURL}/application-guide/`, description: 'Patterns for building FlowFuse applications' },
{ title: 'Create an account', href: `${site.appURL}/account/create`, description: 'Start a free trial' },
{ title: 'Terms of Service', href: `${site.baseURL}/terms/` },
{ title: 'Privacy Policy', href: `${site.baseURL}/privacy-policy/` },
],
},
],
},
ogImage: {
zeroRuntime: true,
// resvg's default (loadSystemFonts: true) scans and parses every installed system
// font on every single render — measured at ~1.1-1.3s per image, over 2/3 of total
// render time. Satori already embeds all glyphs as vector paths (embedFont: true,
// the module default) before resvg ever sees the SVG, so resvg needs zero font
// resolution of its own at rasterization time.
resvgOptions: { font: { loadSystemFonts: false } },
// Content-addressed (hash of component + props + module version), so a build cache
// hit skips font-load/render-satori/render-resvg entirely and just returns the
// cached bytes — only pages whose title/section actually changed pay to re-render.
// A sibling of the font cache dir, not nested inside it: nuxt-og-image's own
// build-cache pruning does a flat readdirSync+readFileSync over this directory,
// which throws EISDIR if it also contains the font cache's fonts-ttf/ subdirectory.
// netlify.toml/test.yml cache both directories under one cache step.
buildCache: { base: 'node_modules/.cache/nuxt/.nuxt/cache/og-image-render' },
},
sitemap: {
sources: [
// Nuxt-native dynamic routes (integrations) that
// @nuxtjs/seo's static-route auto-discovery can't see
'/api/__sitemap__/dynamic-urls',
// docs/handbook/changelog/blog/ebooks/whitepapers with lastmod/images -
// see content-urls.get.ts for why this isn't done via a `sitemap` schema
// field on the collections instead.
'/api/__sitemap__/content-urls',
],
urls: blogAuthorRoutes.map(loc => ({ loc, priority: 0.6 })),
exclude: ['/_studio/**', '/api/**'],
},
robots: {
groups: [
{ userAgent: ['*'], allow: ['/'] },
{ userAgent: ['Algolia Crawler'], allow: ['/'] },
],
// sitemap.xml covers Nuxt-native pages; sitemap-legacy.xml (generated by 11ty,
// served as a static file from nuxt/public/) covers everything still on 11ty.
sitemap: [`${site.baseURL}/sitemap.xml`, `${site.baseURL}/sitemap-legacy.xml`],
},
linkChecker: {
failOnError: true,
// trailing-slash: 11ty pages use trailing slashes intentionally
// no-error-response: links to 11ty pages return 404 in the Nuxt-only static output
skipInspections: ['trailing-slash', 'no-error-response'],
},
// @nuxt/content generates import statements for remark plugin keys.
// These aliases make them resolvable in the Vite bundle context.
alias: {
'handbook-links': join(__dirname, 'utils/remark-handbook-links'),
'docs-links': join(__dirname, 'utils/remark-docs-links'),
},
app: {
head: {
// nuxt-seo-utils' default title template is `%s %separator %siteName`; the
// separator defaults to '|' if unset. This makes every page's <title>/og:title
// "{page title} • FlowFuse" without each page having to append the brand itself.
templateParams: { separator: '•' },
link: [
{ rel: 'stylesheet', href: '/css/style.css' },
{ rel: 'preconnect', href: 'https://fonts.googleapis.com' },
{ rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&display=swap' },
{ rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css', integrity: 'sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+', crossorigin: 'anonymous' },
{ rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' },
{ rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' },
{ rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png' },
{ rel: 'mask-icon', href: '/safari-pinned-tab.svg', color: '#aa4444' },
],
meta: [
{ name: 'msapplication-TileColor', content: '#00aba9' },
{ name: 'theme-color', content: '#ffffff' },
],
script: [
// Explicit nav-click tracking. Source is src/js/nav-tracking.js;
// prod:eleventy-nuxt copies the 11ty output into nuxt/public/.
{ src: '/js/nav-tracking.js', defer: true },
]
}
},
image: {
// The Netlify image provider proxies through a Netlify Image CDN function that only
// exists on deployed/Netlify-run infra, so it 404s under plain `nuxt dev`. Fall back to
// the passthrough provider outside production builds, or when SKIP_IMAGES is set.
provider: (process.env.NODE_ENV !== 'production' || process.env.SKIP_IMAGES === 'true') ? 'none' : 'netlify',
domains: ['flowfuse.com', 'www.flowfuse.com'],
quality: 80,
},
routeRules: {
'/terms': { robots: false },
'/privacy-policy': { robots: false },
'/thank-you/**': { robots: false },
...redirects,
},
nitro: {
preset: 'netlify',
// Nitro emits a .mjs.map next to every server chunk, so the Netlify functions bundle
// ships one map file per chunk. Skipping them keeps the bundle smaller and the
// server build a little shorter. The cost is that a server-side stack trace in the
// function logs no longer resolves back to the original source.
sourceMap: false,
serverAssets: [
{
baseName: 'analytics',
// Nitro resolves this dir against nitro.srcDir (Nuxt's serverDir, i.e. nuxt/server),
// not against the nuxt/ root — so this needs one more level up than it looks like.
dir: '../../src/_includes/analytics'
},
{
baseName: 'team',
dir: '../src/_data/team'
},
{
baseName: 'guests',
dir: '../src/_data/guests'
}
],
prerender: {
routes: (() => {
// The changelog listing is a single page now (grouped by release, revealed
// as you scroll), so there are no /changelog/<n>/ pages to enumerate.
const changelog = collectChangelogRoutes(join(__dirname, '../src/changelog'), '/changelog')
const blogListingRoutes = paginatedListingRoutes('/blog', blogFiles.length)
const blogTagRoutes = BLOG_TAGS.flatMap(tag =>
paginatedListingRoutes(`/blog/${tag}`, blogFiles.filter(f => f.tags.includes(tag)).length)
)
return [
'/terms',
'/privacy-policy',
'/integrations',
'/pricing',
'/product',
// /ai is only linked from 11ty-generated HTML (nav, homepage), which the
// Nuxt prerender crawler never parses, so it has to be listed explicitly
// or the route is missing from nuxt/dist and every link to it breaks.
'/ai',
...collectProductRoutes(join(__dirname, 'content/products')),
// Without this, @nuxtjs/sitemap only bakes /sitemap.xml statically when
// isNuxtGenerate() is true, which checks for nitro.static/preset "static" -
// the netlify preset here is hybrid (prerendered pages + a fallback
// function), so it doesn't qualify and /sitemap.xml gets served live by
// that function instead. There, /var/task has no `git` binary, so every
// git-derived lastmod (handbook/changelog/blog/ebooks/whitepapers, see
// content-urls.get.ts) silently resolves to undefined. Explicitly listing
// it here bakes it at build time instead, inside the git checkout.
'/sitemap.xml',
'/contact-us',
'/book-demo',
'/support',
'/professional-services',
'/ebooks/beginner-guide-to-a-professional-nodered/',
'/ebooks/ultimate-guide-to-building-applications-with-flowfuse-dashboard-for-node-red/',
'/whitepaper/uns-decoupling-data-producers-and-consumers/',
'/whitepaper/open-source-software-for-manufacturing/',
'/whitepaper/accelerating-innovation-in-manufacturing-with-flowfuse/',
'/whitepaper/accelerating-industrial-innovation-with-low-code-platforms/',
'/resources/publications/',
...collectApplicationGuideRoutes(join(__dirname, 'content/application-guide')),
'/changelog/index.xml',
'/changelog/',
...changelog.routes,
'/blog/index.xml',
...blogListingRoutes,
...blogTagRoutes,
...blogFiles.map(f => f.route),
...blogAuthorRoutes,
...collectHandbookRoutes(join(__dirname, 'content/handbook'), '/handbook'),
...collectStoryRoutes(join(__dirname, '../src/customer-stories')),
]
})(),
crawlLinks: false,
// Nitro renders one route at a time by default, which serialises much the
// longest phase of the build. A sizeable share of that phase is fixed per-route
// overhead rather than render work, and that part overlaps away as soon as
// several routes render at once. Matched to the vCPU count on GitHub's standard
// runner. Raising it further trades peak memory for wall time.
concurrency: 4
}
},
hooks: {
'content:file:beforeParse' ({ file, collection }) {
if (collection.name !== 'blog') return
file.body = file.body.replace(
/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*/,
(block) => block.replace(/^meta:[ \t]*\r?$/m, 'structuredData:')
)
},
// Enumerate /integrations/{id}/ routes at config-time so SSG prerenders them.
// Can't use Nuxt's $fetch here — it only exists at nitro runtime.
async 'nitro:config' (nitroConfig: import('nitropack').NitroConfig) {
if (nitroConfig.dev) return
const { buildEnrichedIntegrations } = await import('./server/utils/integrations-enrich')
const integrations = await buildEnrichedIntegrations()
if (integrations.length === 0) {
throw new Error('[nuxt] integrations enumeration returned 0 nodes — refusing to build a site with no detail pages')
}
const routes = integrations.map(node => `/integrations/${node._id}/`)
nitroConfig.prerender = nitroConfig.prerender || {}
nitroConfig.prerender.routes = [...new Set([...(nitroConfig.prerender.routes || []), ...routes])]
console.log(`[nuxt] enumerated ${routes.length} /integrations/{id}/ routes for prerender`)
}
},
studio: {
route: '/_studio',
repository: {
provider: 'github',
owner: 'FlowFuse',
repo: 'website',
branch: 'main',
branchStrategy: 'feature-branch',
}
},
content: {
build: {
markdown: {
toc: {
depth: 4,
searchDepth: 4,
},
remarkPlugins: {
'handbook-links': { instance: remarkHandbookLinks },
'docs-links': { instance: remarkDocsLinks },
'remark-math': {},
},
rehypePlugins: {
'rehype-katex': {},
},
},
},
},
vue: {
compilerOptions: {
// lite-youtube-embed is a web component loaded client-side by LiteYoutube.vue,
// not a Vue component - stop Vue from warning about an unresolved <lite-youtube>.
isCustomElement: (tag) => tag === 'lite-youtube',
},
},
vite: {
optimizeDeps: {
include: [
'@vue/devtools-core',
'@vue/devtools-kit',
],
},
},
ui: {
// Dark mode isn't implemented across the site yet. Disabling the color-mode
// module here (rather than just setting a light `colorMode` preference) is
// what actually stops Nuxt UI from switching to dark for visitors whose OS
// prefers it — see https://ui.nuxt.com/docs/getting-started/integrations/color-mode/nuxt#configuration
colorMode: false,
theme: {
colors: ['primary', 'secondary', 'success', 'info', 'warning', 'error', 'highlight']
}
},
// Dev proxying to 11ty is handled by server/middleware/legacy.ts
// to allow per-route exclusions as pages are migrated.
})