UNPKG

2.78 kBJavaScriptView Raw
1import { getPeopleHTML } from './util.js'
2import spdxParse from 'spdx-expression-parse'
3import spdxList from 'spdx-license-list/full'
4function renderSpdxObject(spdxObject, output, depth = 0) {
5 if (spdxObject.license) {
6 const code = spdxObject.license
7 const details = spdxList[code]
8 if (!details) {
9 throw new Error(`Could not find the details for the license ${code}`)
10 }
11 const name = details.name
12 const body = details.licenseText
13 const url = `http://spdx.org/licenses/${code}.html`
14 return output === 'description'
15 ? depth === 0
16 ? `<ul><li><a href="${url}">${name}</a></li></ul>`
17 : `<a href="${url}">${name}</a>`
18 : body
19 // Remove useless copyright headers - (spdx-license-list@5.x)
20 .replace('\nCopyright (c) <year> <copyright holders>\n', '')
21 // Remove useless copyright headers - (spdx-license-list@6.x)
22 .replace(/\s?Copyright.+holders>/gi, '')
23 // Remove license introductions
24 .replace(/^[\s\S]+<<endOptional>>\s*/m, '')
25 // Convert the license into HTML
26 .replace(
27 /^(.+?)\n\s*([\s\S]+)\s*$/,
28 '<h2>$1</h2>\n\n<pre>\n$2\n</pre>'
29 )
30 } else if (spdxObject.conjunction) {
31 const left = renderSpdxObject(spdxObject.left, output, depth + 1)
32 const middle = spdxObject.conjunction
33 const right = renderSpdxObject(spdxObject.right, output, depth + 1)
34 return output === 'description'
35 ? `<ul><li>${left}</li>\n<li>${middle}</li>\n<li>${right}</li></ul>`
36 : `${left}\n\n${right}\n\n`.trim()
37 } else {
38 throw new Error(
39 `Unknown spdx object value: ${JSON.stringify(spdxObject, null, ' ')}`
40 )
41 }
42}
43function getLicensesHTML(spdxString, output) {
44 const sdpxObject = spdxParse(spdxString)
45 return renderSpdxObject(sdpxObject, output)
46}
47function getLicenseIntroduction(data) {
48 // Check
49 if (!data.license) {
50 throw new Error('License file was requested, but no license was specified')
51 }
52 // Prepare
53 const result = [
54 'Unless stated otherwise all works are:',
55 '',
56 getPeopleHTML(data.authors, { displayCopyright: true, displayYears: true }),
57 '',
58 'and licensed under:',
59 '',
60 getLicensesHTML(data.license, 'description'),
61 ].join('\n')
62 // Return
63 return result
64}
65export function getLicenseFile(data) {
66 // Check
67 if (!data.license) {
68 throw new Error('License file was requested, but no license was specified')
69 }
70 // Prepare
71 const result = [
72 '<h1>License</h1>',
73 '',
74 getLicenseIntroduction(data),
75 '',
76 getLicensesHTML(data.license, 'body'),
77 ].join('\n')
78 // Return
79 return result
80}
81export function getLicenseSection(data) {
82 // Check
83 if (!data.license) {
84 throw new Error('License file was requested, but no license was specified')
85 }
86 // Prepare
87 const result = ['<h2>License</h2>', '', getLicenseIntroduction(data)].join(
88 '\n'
89 )
90 // Return
91 return result
92}