@nera-static/plugin-utils 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/urls.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Site URLs, `base_path`, path containment and `srcset`, shared by every
3
+ * Nera plugin and tool (`@nera-static/plugin-utils/urls`).
4
+ *
5
+ * Absolute URLs are percent-encoded (`joinUrl`, `siteUrl`), so a canonical
6
+ * link, a sitemap `<loc>` and a feed `<link>` of the same page are the same
7
+ * string. The `base_path` helpers give exactly `@nera-static/core`'s output.
8
+ */
9
+
10
+ import path from 'node:path'
11
+ import { loadPluginConfig } from './config.js'
12
+ import { isPlainObject } from './values.js'
13
+
14
+ // A percent-escape that is already valid: `%` and two hex digits. The
15
+ // capture group keeps it in `split`'s output, at the odd indexes.
16
+ const PERCENT_ESCAPE = /(%[0-9A-Fa-f]{2})/
17
+
18
+ // A URL scheme (`https:`, `mailto:`, `data:`, …), per RFC 3986.
19
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i
20
+
21
+ // ASCII whitespace as the HTML standard defines it for `srcset`.
22
+ const WHITESPACE = /[\t\n\f\r ]/
23
+
24
+ // The origin without whitespace and trailing slashes, '' for a non-string.
25
+ const trimOrigin = (origin) => (typeof origin === 'string' ? origin.trim().replace(/\/+$/, '') : '')
26
+
27
+ /**
28
+ * The site origin without surrounding whitespace and trailing slashes:
29
+ * `app.origin`, else `app_origin` from the site's
30
+ * `config/canonical-links.yaml` (`app.folders.config` honoured), the order
31
+ * canonical-links, sitemap, feed and validate use. `''` when neither is a
32
+ * non-blank string. The file is only read when `app.origin` is blank or
33
+ * missing; a missing file reads as no origin.
34
+ *
35
+ * @param {{ cwd?: string, app?: object }} [options]
36
+ * @returns {string} e.g. `'https://example.com'`, or `''`
37
+ */
38
+ export function resolveOrigin({ cwd = process.cwd(), app } = {}) {
39
+ const own = trimOrigin(app?.origin)
40
+ if (own) return own
41
+ const canonical = loadPluginConfig('canonical-links', { cwd, app })
42
+ return trimOrigin(isPlainObject(canonical) ? canonical.app_origin : undefined)
43
+ }
44
+
45
+ /**
46
+ * `value` with everything a URL may not contain percent-encoded (space,
47
+ * non-ASCII, a `%` that starts no valid escape, …), while valid `%XX`
48
+ * escapes and URL delimiters (`/ ? # & =` …) stay as they are, so an
49
+ * already-encoded path is not encoded twice. Lone surrogates become
50
+ * `%EF%BF%BD` (U+FFFD) instead of throwing. `null` and `undefined` give
51
+ * `''`, other non-strings are converted with `String()`.
52
+ *
53
+ * @param {unknown} value a path such as `meta.href`
54
+ * @returns {string}
55
+ */
56
+ export function encodePath(value) {
57
+ const text = value === null || value === undefined ? '' : String(value)
58
+ return text
59
+ .toWellFormed()
60
+ .split(PERCENT_ESCAPE)
61
+ .map((part, index) => (index % 2 ? part : encodeURI(part)))
62
+ .join('')
63
+ }
64
+
65
+ /**
66
+ * The absolute URL of a page: `origin` + `basePath` + the logical `href`
67
+ * (`meta.href`), with the path percent-encoded by `encodePath` but
68
+ * otherwise verbatim (`/index.html` stays). `origin` is used as given
69
+ * (from `resolveOrigin`), `basePath` is core's normalised `app.basePath`
70
+ * (`''` or `'/sub'`).
71
+ *
72
+ * @param {string} origin
73
+ * @param {string} [basePath]
74
+ * @param {string} href
75
+ * @returns {string} e.g. `'https://ex.com/sub/%C3%BCber%20uns.html'`
76
+ */
77
+ export function joinUrl(origin, basePath, href) {
78
+ return `${origin}${encodePath(`${basePath || ''}${href}`)}`
79
+ }
80
+
81
+ /**
82
+ * The site's own URL: `origin` + `basePath` without trailing slashes,
83
+ * percent-encoded like `joinUrl`. Ids such as `<siteUrl>/#website` and
84
+ * absolute links hang off it. A non-string `basePath` gives `origin`.
85
+ *
86
+ * @param {string} origin
87
+ * @param {string} [basePath]
88
+ * @returns {string} e.g. `'https://ex.com/sub'`
89
+ */
90
+ export function siteUrl(origin, basePath) {
91
+ if (typeof basePath !== 'string') return origin
92
+ return `${origin}${encodePath(basePath.replace(/\/+$/, ''))}`
93
+ }
94
+
95
+ /**
96
+ * A site's `base_path` (config/app.yaml) as a URL prefix, exactly as core
97
+ * normalises it into `app.basePath`: a non-string, blank text or `/` gives
98
+ * `''` (a root-served site); otherwise trimmed, trailing slashes dropped and
99
+ * one leading slash guaranteed (`'nera-website'` → `'/nera-website'`,
100
+ * `'/foo/bar/'` → `'/foo/bar'`).
101
+ *
102
+ * @param {unknown} raw
103
+ * @returns {string}
104
+ */
105
+ export function normalizeBasePath(raw) {
106
+ if (typeof raw !== 'string') return ''
107
+ const trimmed = raw.trim()
108
+ if (trimmed === '' || trimmed === '/') return ''
109
+ const noTrailing = trimmed.replace(/\/+$/, '')
110
+ return noTrailing.startsWith('/') ? noTrailing : `/${noTrailing}`
111
+ }
112
+
113
+ /**
114
+ * `url` under `basePath`, as core prefixes every root-absolute URL of a
115
+ * built page: only a string starting with one `/` is prefixed. A
116
+ * protocol-relative `//cdn/…`, a relative or absolute URL with a scheme, a
117
+ * non-string, and a value already under `basePath` (`basePath` itself or
118
+ * `basePath/…`) are returned unchanged, so applying it twice is harmless.
119
+ * An empty `basePath` changes nothing.
120
+ *
121
+ * @param {unknown} url
122
+ * @param {string} basePath normalised, `''` or `'/sub'`
123
+ * @returns {unknown} the prefixed string, or `url` itself
124
+ */
125
+ export function withBasePath(url, basePath) {
126
+ if (!basePath || typeof url !== 'string') return url
127
+ if (!url.startsWith('/') || url.startsWith('//')) return url
128
+ if (url === basePath || url.startsWith(`${basePath}/`)) return url
129
+ return `${basePath}${url}`
130
+ }
131
+
132
+ /**
133
+ * The logical path of a root-absolute `url` under `basePath`, the inverse
134
+ * of `withBasePath`: `basePath` itself gives `'/'`, `basePath/…` loses the
135
+ * prefix, anything else (another path, `/subway` for `/sub`, a non-string)
136
+ * is returned unchanged. An empty `basePath` changes nothing.
137
+ *
138
+ * @param {unknown} url
139
+ * @param {string} basePath normalised, `''` or `'/sub'`
140
+ * @returns {unknown} the stripped string, or `url` itself
141
+ */
142
+ export function stripBasePath(url, basePath) {
143
+ if (!basePath || typeof url !== 'string') return url
144
+ if (url === basePath) return '/'
145
+ return url.startsWith(`${basePath}/`) ? url.slice(basePath.length) : url
146
+ }
147
+
148
+ /**
149
+ * Whether `url` starts with a URL scheme (`https:`, `mailto:`, `tel:`,
150
+ * `data:`, case-insensitive). `//host/…` has none; a non-string is `false`.
151
+ *
152
+ * @param {unknown} url
153
+ * @returns {boolean}
154
+ */
155
+ export function hasScheme(url) {
156
+ return typeof url === 'string' && SCHEME.test(url)
157
+ }
158
+
159
+ /**
160
+ * Whether the path `target` is `root` itself or lies below it, compared
161
+ * lexically after `path.resolve` (symlinks are not followed). A child
162
+ * folder literally named `..foo` is inside. With `self: false`, `root`
163
+ * itself does not count ("strictly below").
164
+ *
165
+ * @param {string} root
166
+ * @param {string} target
167
+ * @param {{ self?: boolean }} [options]
168
+ * @returns {boolean}
169
+ */
170
+ export function isInside(root, target, { self = true } = {}) {
171
+ const relative = path.relative(root, target)
172
+ if (relative === '') return self
173
+ return !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)
174
+ }
175
+
176
+ // The image candidates of a `srcset` value, with each URL's position, by
177
+ // the HTML standard's rule: candidates are separated by commas, a URL runs
178
+ // to the next whitespace (so `?a=1,2` and `data:…;base64,…` stay whole), a
179
+ // URL's trailing commas end the candidate, and the descriptors run to the
180
+ // next comma outside parentheses.
181
+ function srcsetCandidates(value) {
182
+ const candidates = []
183
+ let pos = 0
184
+ while (pos < value.length) {
185
+ while (pos < value.length && (value[pos] === ',' || WHITESPACE.test(value[pos]))) pos++
186
+ if (pos >= value.length) break
187
+
188
+ const start = pos
189
+ while (pos < value.length && !WHITESPACE.test(value[pos])) pos++
190
+ let end = pos
191
+ if (value[end - 1] === ',') {
192
+ while (value[end - 1] === ',') end--
193
+ candidates.push({ start, end })
194
+ continue
195
+ }
196
+ candidates.push({ start, end })
197
+
198
+ // The standard's tokenizer does not nest parentheses: the first `)`
199
+ // leaves them, whatever `(` came before it.
200
+ let inParens = false
201
+ while (pos < value.length && (value[pos] !== ',' || inParens)) {
202
+ if (value[pos] === '(') inParens = true
203
+ else if (value[pos] === ')') inParens = false
204
+ pos++
205
+ }
206
+ }
207
+ return candidates
208
+ }
209
+
210
+ /**
211
+ * The URLs of a `srcset` value, in order, parsed by the HTML standard's
212
+ * candidate rule: a URL ends at whitespace, so a comma inside it
213
+ * (`/a.jpg?a=1,2`, a data URI) does not split it. A non-string gives `[]`.
214
+ *
215
+ * @param {unknown} value e.g. `'/a.jpg 1x, /b.jpg 2x'`
216
+ * @returns {string[]}
217
+ */
218
+ export function srcsetUrls(value) {
219
+ if (typeof value !== 'string') return []
220
+ return srcsetCandidates(value).map(({ start, end }) => value.slice(start, end))
221
+ }
222
+
223
+ /**
224
+ * `value` with every candidate URL of the `srcset` replaced by
225
+ * `fn(url, index)` (converted with `String()`), found as `srcsetUrls`
226
+ * finds them. Everything else, descriptors, commas and whitespace, is kept
227
+ * byte for byte, so an `fn` that returns its argument gives `value` back.
228
+ * A non-string is returned unchanged.
229
+ *
230
+ * @param {unknown} value
231
+ * @param {(url: string, index: number) => unknown} fn
232
+ * @returns {unknown}
233
+ */
234
+ export function mapSrcset(value, fn) {
235
+ if (typeof value !== 'string') return value
236
+ let result = ''
237
+ let last = 0
238
+ srcsetCandidates(value).forEach(({ start, end }, index) => {
239
+ result += value.slice(last, start) + String(fn(value.slice(start, end), index))
240
+ last = end
241
+ })
242
+ return result + value.slice(last)
243
+ }