-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·369 lines (306 loc) · 9.42 KB
/
app.js
File metadata and controls
executable file
·369 lines (306 loc) · 9.42 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
// Core dependencies
const { join, parse } = require('node:path')
// External dependencies
const browserSync = require('browser-sync')
const compression = require('compression')
const express = require('express')
const helmet = require('helmet')
const { nunjucks } = require('nhsuk-frontend/lib')
// Local dependencies
const config = require('./app/config')
const locals = require('./app/locals')
const fileHelper = require('./lib/file-helper')
const filters = require('./lib/filters')
const macroOptions = require('./lib/macro-options')
const PageIndex = require('./lib/page-index')
const authentication = require('./middleware/authentication')
const routing = require('./middleware/routing')
const pageIndex = new PageIndex(config)
// Initialise applications
const app = express()
// Authentication middleware
app.use(authentication)
// Use local variables
app.use(locals(config))
// Use gzip compression to decrease the size of
// the response body and increase the speed of web app
app.use(compression())
// Use helmet to help secure the application
// by setting http headers
app.use(
helmet({
contentSecurityPolicy: false,
crossOriginResourcePolicy: {
policy: 'cross-origin'
}
})
)
/**
* Send different cache-control headers depending on the file path
*
* Asset filenames with fingerprint hashes (stylesheets, javascripts) are
* given an 'infinite' max-age since the content never changes.
*
* Historically, an 'infinite' max-age is the 32-bit maximum 2,147,483,648.
* https://datatracker.ietf.org/doc/html/rfc9111#section-1.2.2
*/
app.use(
'/assets',
express.static(join(config.publicPath, 'assets'), {
setHeaders(res) {
res.set('Cache-Control', 'public,max-age=0,must-revalidate')
}
})
)
/**
* Middleware to serve javascripts
* (Redirects to latest hashed file on 404)
*/
app.use('/javascripts', [
express.static(join(config.publicPath, 'javascripts'), {
setHeaders(res) {
res.set('Cache-Control', 'public,max-age=2147483648,immutable')
}
}),
(req, res, next) => {
const { name, ext } = parse(req.path)
const [basename] = name.split('.')
// Redirect to latest javascript
if (['main.js'].includes(`${basename}${ext}`)) {
res.redirect(fileHelper.getAssetPath(`${basename}.js`))
return
}
// 404 page
next()
}
])
/**
* Middleware to serve javascripts
* (Redirects to latest hashed file on 404)
*/
app.use('/stylesheets', [
express.static(join(config.publicPath, 'stylesheets'), {
setHeaders(res) {
res.set('Cache-Control', 'public,max-age=2147483648,immutable')
}
}),
(req, res, next) => {
const { name, ext } = parse(req.path)
const [basename] = name.split('.')
// Redirect to latest stylesheet
if (['main.css', 'preview.css'].includes(`${basename}${ext}`)) {
res.redirect(fileHelper.getAssetPath(`stylesheets/${basename}.scss`))
return
}
// 404 page
next()
}
])
// View engine (nunjucks)
app.set('view engine', 'njk')
// Nunjucks configuration
const env = nunjucks.configure(config.nunjucksPaths, {
express: app,
lstripBlocks: true, // Remove leading spaces from a block/tag
trimBlocks: true, // Remove trailing newlines from a block/tag
watch: true
})
/*
* Add some global nunjucks helpers
*/
env.addGlobal('getHTMLCode', fileHelper.getHTMLCode)
env.addGlobal('getNunjucksCode', fileHelper.getNunjucksCode)
env.addGlobal('getAssetPath', fileHelper.getAssetPath)
env.addGlobal('getMacroOptions', macroOptions.getMacroOptions)
env.addGlobal('getMacroPageName', macroOptions.getMacroPageName)
env.addFilter('highlight', filters.highlight)
env.addFilter('kebabCase', filters.kebabCase)
env.addFilter('slugify', filters.slugify)
env.addFilter('unindent', filters.unindent)
// Render standalone design examples
app.get('/design-example/:group/:item/:type', (req, res, next) => {
const { group, item, type } = req.params
// Continue to 404 page
if (!fileHelper.hasNunjucksPath({ group, item, type })) {
return next()
}
// Get the given example as HTML.
const exampleHtml = fileHelper.getHTMLCode({
group,
item,
type,
env
})
const { data } = fileHelper.getFrontmatter({
group,
item,
type
})
// Wrap the example HTML in a basic html base template.
const { previewLayout = 'design-example-wrapper' } = data
res.render(`layouts/${previewLayout}`, {
...data,
exampleHtml,
item
})
})
app.get('/search', (req, res) => {
const query = req.query.q
const resultsPerPage = 10
let currentPage = parseInt(req.query.page, 10)
const results = pageIndex.search(query)
const maxPage = Math.ceil(results.length / resultsPerPage)
if (!Number.isInteger(currentPage)) {
currentPage = 1
} else if (currentPage > maxPage || currentPage < 1) {
currentPage = 1
}
const startingIndex = resultsPerPage * (currentPage - 1)
const endingIndex = startingIndex + resultsPerPage
res.render('layouts/search', {
currentPage,
maxPage,
query,
results: results.slice(startingIndex, endingIndex),
resultsLen: results.length
})
})
app.get('/suggestions', (req, res) => {
const results = pageIndex.search(req.query.search)
const slicedResults = results.slice(0, 10)
res.set({ 'Content-Type': 'application/json' })
res.status(200).send(JSON.stringify(slicedResults))
})
app.get('/assets/NHS_design_principles.pdf', (req, res) => {
res.redirect('/assets/nhs-design-principles.pdf')
})
app.get('/slack', (req, res) => {
res.redirect(
'https://join.slack.com/t/nhs-service-manual/shared_invite/enQtNTIyOTEyNjU3NDkyLTk4NDQ3YzkwYzk1Njk5YjAxYTI5YTVkZmUxMGQ0ZjA3NjMyM2ZkNjBlMWMxODVjZjYzNzg1ZmU4MWY1NmE2YzE'
)
})
// Add the code redirects for community-and-contribution pages
app.get('/community/contribution-survey', (req, res) => {
res.redirect(
'https://nhsdigital.eu.qualtrics.com/jfe/form/SV_5szVfoxZIW7Kr1b'
)
})
app.get('/community/backlog-of-components-and-patterns', (req, res) => {
res.redirect('/community-and-contribution/backlog-of-components-and-patterns')
})
app.get('/community/contribution-criteria', (req, res) => {
res.redirect('/community-and-contribution/contribution-criteria')
})
app.get('/community/develop-component-pattern', (req, res) => {
res.redirect('/community-and-contribution/develop-component-pattern')
})
app.get('/community', (req, res) => {
res.redirect('/community-and-contribution')
})
app.get('/community/propose-component-pattern', (req, res) => {
res.redirect('/community-and-contribution/propose-component-pattern')
})
app.get(
'/community-and-contribution/feedback-or-share-insights',
(req, res) => {
res.redirect('/community-and-contribution/feed-back-or-share-insights')
}
)
// Redirects for new service standards URLs
app.get('/service-standard', (req, res) => {
res.redirect(301, '/standards-and-technology/service-standard')
})
app.get('/service-standard/about', (req, res) => {
res.redirect(301, '/standards-and-technology/about-the-service-standard')
})
app.get('/service-standard/:page', (req, res) => {
res.redirect(
301,
`/standards-and-technology/service-standard-points/${req.params.page}`
)
})
// Redirects for accessibility URLs
app.get(
'/accessibility/new-accessibility-requirements-wcag-2-2',
(req, res) => {
res.redirect('/accessibility/new-criteria-in-wcag-2-2')
}
)
// Redirects for design system examples
app.get('/design-example/components/checkboxes/hint', (req, res) => {
res.redirect('/design-example/components/checkboxes/hint-text')
})
// Redirects for design system components
app.get('/design-system/components/care-cards', (req, res) => {
res.redirect(
'/design-system/patterns/help-users-decide-when-and-where-to-get-care'
)
})
// Redirects for design system patterns
app.get(
'/design-system/patterns/ask-users-for-their-nhs-number',
(req, res) => {
res.redirect('/design-system/patterns/ask-for-nhs-numbers')
}
)
app.get(
'/design-system/patterns/reassure-users-that-a-page-is-up-to-date',
(req, res) => {
res.redirect('/design-system/patterns/know-that-a-page-is-up-to-date')
}
)
app.get(
'/content/health-literacy/use-a-readability-tool-to-prioritise-content',
(req, res) => {
res.redirect(302, '/page-not-found')
}
)
app.get('/content/numbers-measurement-dates-time', (req, res) => {
res.redirect('/content/numbers-measurements-dates-time')
})
// PDF page redirect
// https://github.com/nhsuk/nhsuk-service-manual/pull/965
app.get('/content/pdfs', (req, res) => {
res.redirect('/content/pdfs-and-other-non-html-documents')
})
// REDIRECT STOPS HERE
// Render sitemap.xml in XML format
app.get('/sitemap.xml', (_, res) => {
res.set({ 'Content-Type': 'application/xml' })
res.render('sitemap.xml')
})
// Render robots.txt in text format
app.get('/robots.txt', (_, res) => {
res.set('text/plain')
res.render('robots.txt')
})
// Automatically route pages
app.use(routing.matchRoutes)
// Render 404 page
app.all('/*subPaths', (_, res) => {
res.statusCode = 404
res.locals.basePath = '/page-not-found'
res.render('page-not-found')
})
// Run application on configured port
if (config.env === 'development') {
app.listen(config.port - 50, () => {
browserSync({
files: [
join(config.sourcePath, 'views/**'),
join(config.publicPath, '**')
],
notify: true,
open: false,
port: config.port,
proxy: `localhost:${config.port - 50}`,
ui: false
})
})
} else {
app.listen(config.port)
}
setTimeout(() => {
pageIndex.init()
}, 2000)
module.exports = app