@nera-static/plugin-utils 1.6.1 → 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/README.md CHANGED
@@ -25,12 +25,12 @@ npm install @nera-static/plugin-utils
25
25
 
26
26
  Reads and parses a YAML config file, returning its contents as a JavaScript object.
27
27
 
28
- Returns `{}` if the file does not exist or is empty — it never throws. **Supply a JS fallback for every key you read.**
28
+ Returns `{}` if the file does not exist, is empty or holds nothing but comments. Malformed YAML throws. **Supply a JS fallback for every key you read.** The same function is exported from `@nera-static/plugin-utils/config`, next to `loadPluginConfig` and `createConfigReader` (see [Shared helpers](#-shared-helpers-subpath-exports)), which find the file and check it for you.
29
29
 
30
30
  Plugins read config from the *user's* site, not from the package. The `config/<name>.yaml` shipped inside a plugin is documentation only; it is never merged with the user's copy. Resolve against `process.cwd()`:
31
31
 
32
32
  ```js
33
- import path from 'path'
33
+ import path from 'node:path'
34
34
  import { getConfig } from '@nera-static/plugin-utils'
35
35
 
36
36
  const config = getConfig(path.resolve(process.cwd(), 'config/my-plugin.yaml'))
@@ -143,7 +143,7 @@ Returns `false` outside a Nera project or when `sourceFile` is missing; a delibe
143
143
 
144
144
  #### `resolveViewsDir(cwd?): string` / `resolveAssetsDir(cwd?): string`
145
145
 
146
- Return the project's `views` / `assets` directory as an absolute path, resolved the same way the generator does: an explicit `folders.<key>` in `config/app.yaml` wins; otherwise `theme/views` / `theme/assets` when a local `theme/` folder exists; otherwise the deprecated root folder. `publishTemplates` and `publishAsset` use these internally, but they are exported for plugins that need to report or reason about where their files went.
146
+ Return the project's `views` / `assets` directory as an absolute path, resolved the same way the generator does: an explicit `folders.<key>` string in `config/app.yaml` wins, resolved against the project root (a blank `''` is the root itself, as in core); otherwise `theme/views` / `theme/assets` when a local `theme/` folder exists, or when `app.yaml` sets `theme:` and the site has no root `views/` folder (a thin themed site with no presentation of its own); otherwise the deprecated root folder. `publishTemplates` and `publishAsset` use these internally, but they are exported for plugins that need to report or reason about where their files went.
147
147
 
148
148
  > The `__dirname` used in these option examples is not defined in ESM. See the CLI Integration example below for the two lines that define it.
149
149
 
@@ -154,8 +154,8 @@ These functions are designed to be used in `bin/publish-template.js` scripts tha
154
154
  ```js
155
155
  #!/usr/bin/env node
156
156
 
157
- import path from 'path'
158
- import { fileURLToPath } from 'url'
157
+ import path from 'node:path'
158
+ import { fileURLToPath } from 'node:url'
159
159
  import { publishAllTemplates } from '@nera-static/plugin-utils'
160
160
 
161
161
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -173,6 +173,536 @@ process.exit(result ? 0 : 1)
173
173
 
174
174
  ---
175
175
 
176
+ ## 🧩 Shared helpers (subpath exports)
177
+
178
+ Since 1.7.0 the helpers that Nera plugins, core and the tools used to copy from each other live here, one subpath per family (1.8.0 added `/html` to `/pages`). Import them from the subpath, never write a local copy. The `.` export above is unchanged. None of them prints unless that is its job (the logger, `pageDate`'s warning), reads globals beyond a `cwd` default of `process.cwd()`, or calls `process.exit`.
179
+
180
+ | Subpath | Exports |
181
+ |---|---|
182
+ | `@nera-static/plugin-utils/values` | `isPlainObject`, `isText`, `textOr` |
183
+ | `@nera-static/plugin-utils/log` | `createLogger` |
184
+ | `@nera-static/plugin-utils/config` | `getConfig`, `loadPluginConfig`, `createConfigReader` |
185
+ | `@nera-static/plugin-utils/packages` | `requireFromSite`, `ownVersion`, `isPluginPackage`, `pluginShortName`, `pluginPackage`, `themePackage` |
186
+ | `@nera-static/plugin-utils/guard` | `satisfiesFloor`, `coreVersion`, `assertCoreVersion`, `GET_ASSETS_CORE` |
187
+ | `@nera-static/plugin-utils/html` | `escapeHtml`, `escapeXml`, `escapeRegExp` |
188
+ | `@nera-static/plugin-utils/lang` | `siteLang`, `pageLang`, `siteLanguages`, `isLanguageMap`, `localize` |
189
+ | `@nera-static/plugin-utils/dates` | `toDate`, `formatW3C`, `PUBLISHED_KEYS`, `UPDATED_KEYS`, `pageDate`, `byDate` |
190
+ | `@nera-static/plugin-utils/sort` | `byString`, `byHref` |
191
+ | `@nera-static/plugin-utils/urls` | `resolveOrigin`, `encodePath`, `joinUrl`, `siteUrl`, `normalizeBasePath`, `withBasePath`, `stripBasePath`, `hasScheme`, `isInside`, `srcsetUrls`, `mapSrcset` |
192
+ | `@nera-static/plugin-utils/frontmatter` | `FRONTMATTER_OPTIONS`, `splitFrontmatter` |
193
+ | `@nera-static/plugin-utils/glob` | `matchesPattern`, `matchesAny`, `IGNORE_FILE`, `readIgnoreList`, `isIgnoredAsset` |
194
+ | `@nera-static/plugin-utils/pages` | `isRenderedPage`, `isNoindex` |
195
+
196
+ ### `/values` — checks for parsed YAML and frontmatter
197
+
198
+ #### `isPlainObject(value: unknown): boolean`
199
+
200
+ `true` for a mapping as YAML or JSON produce it, or `Object.create(null)`: the prototype is `Object.prototype` (of any realm) or `null`. Arrays, `null`, `Date`, `Map` and class instances are `false`, so a frontmatter value like `images: 2026-10-01` (a `Date`) is never taken for a mapping.
201
+
202
+ #### `isText(value: unknown): boolean`
203
+
204
+ `true` for a string with at least one non-whitespace character.
205
+
206
+ #### `textOr(value: unknown, fallback?): string | fallback`
207
+
208
+ The **trimmed** string when `value` is text (see `isText`), otherwise `fallback` (default `undefined`).
209
+
210
+ ```js
211
+ import { isPlainObject, isText, textOr } from '@nera-static/plugin-utils/values'
212
+
213
+ isPlainObject({ title: 'Blog' }) // true
214
+ isPlainObject(Object.create(null)) // true
215
+ isPlainObject([]) // false
216
+ isPlainObject(new Date()) // false
217
+
218
+ isText(' Blog ') // true
219
+ isText(' ') // false
220
+
221
+ textOr(' Blog ') // 'Blog'
222
+ textOr('', 'Untitled') // 'Untitled'
223
+ textOr(42, 'Untitled') // 'Untitled'
224
+ ```
225
+
226
+ ### `/log` — one prefix for every message
227
+
228
+ #### `createLogger(name: string, { sink = console } = {}): { warn, info, page }`
229
+
230
+ Every line starts with `name`, taken verbatim, so a site owner can tell in a build log where a warning came from:
231
+
232
+ - `warn(msg)` prints `⚠️ <name>: <msg>` through `sink.warn`;
233
+ - `info(msg)` prints `ℹ️ <name>: <msg>` through `sink.info`;
234
+ - `page(page, what, todo)` warns about one page: `⚠️ <name>: <page>: <what> — <todo>`.
235
+
236
+ A test passes its own `sink` (an object with `warn` and `info`) instead of spying on `console`.
237
+
238
+ ```js
239
+ import { createLogger } from '@nera-static/plugin-utils/log'
240
+
241
+ const log = createLogger('plugin-sitemap')
242
+
243
+ log.warn('no origin set')
244
+ // ⚠️ plugin-sitemap: no origin set
245
+ log.info('wrote sitemap.xml')
246
+ // ℹ️ plugin-sitemap: wrote sitemap.xml
247
+ log.page('/blog/first.html', 'no date', 'add `date:` to its frontmatter')
248
+ // ⚠️ plugin-sitemap: /blog/first.html: no date — add `date:` to its frontmatter
249
+ ```
250
+
251
+ ### `/config` — finding and checking a plugin's config file
252
+
253
+ #### `getConfig(filePath: string): object`
254
+
255
+ The same function as in `.` (see [Configuration Loading](#configuration-loading)).
256
+
257
+ #### `loadPluginConfig(name: string, { cwd = process.cwd(), app } = {}): unknown`
258
+
259
+ The site's `<cwd>/<folder>/<name>.yaml`, parsed by `getConfig` and **not** checked (`{}` when it is missing). `<folder>` is `app.folders.config` when it is set, else `config`. Pass the `app` your hook receives, so a site that moved its config folder still works.
260
+
261
+ #### `createConfigReader({ file, defaults, readers, warn = console.warn }): reader`
262
+
263
+ The defaults-and-readers skeleton every plugin config shares, with one set of warnings for the whole fleet:
264
+
265
+ - `file` is the file as the site owner knows it (`'config/sitemap.yaml'`); every message starts with `<file>: `.
266
+ - `defaults` is the full default config, a plain object. Each call of `defaults()` or `normalize()` gets its own deep copy (`structuredClone`).
267
+ - `readers` holds one function per known top-level key: `(value, current, reader) => newValue`. `current` is the value so far (the default), `reader` is the object returned here, for its `bad`, `ignore` and `warn`. Returning `undefined` keeps `current`.
268
+ - `warn` is where messages go, usually a `createLogger(...).warn`.
269
+
270
+ `createConfigReader` throws a `TypeError` when `defaults` or `readers` is not a plain object. The returned `reader` has:
271
+
272
+ | Member | Does |
273
+ |---|---|
274
+ | `normalize(raw)` | a fresh copy of `defaults`, with each key of `raw` replaced by what its reader returns. `null`/`undefined` → the defaults, silently. Not a mapping → `expected a mapping at the top level, using defaults`. A key without its own reader (checked with `Object.hasOwn`, so `constructor:` or `toString:` is unknown too) → `ignoring unknown key <key>`. A key whose value is `null` (empty in YAML) keeps its default. |
275
+ | `defaults()` | a fresh deep copy of `defaults` |
276
+ | `bad(key, value, fallback)` | warns `invalid <key> <value>, using <fallback>` (or `, ignoring it` when `fallback` is `null` or `undefined`) and returns `fallback` |
277
+ | `ignore(where, what)` | warns `ignoring <where>, expected <what>` and returns `undefined` |
278
+ | `unknown(where, key)` | warns `ignoring unknown key <where><key>`, for nested mappings (`where` like `'labels.'`) |
279
+ | `show(value)` | a value as the messages show it: `a date` for a `Date`, else its JSON, else `String(value)` |
280
+ | `warn(msg)` | `warn` with the `<file>: ` prefix |
281
+
282
+ ```js
283
+ import { createConfigReader, loadPluginConfig } from '@nera-static/plugin-utils/config'
284
+ import { createLogger } from '@nera-static/plugin-utils/log'
285
+ import { isText } from '@nera-static/plugin-utils/values'
286
+
287
+ const log = createLogger('plugin-sitemap')
288
+
289
+ const reader = createConfigReader({
290
+ file: 'config/sitemap.yaml',
291
+ defaults: { changefreq: 'weekly', exclude: [] },
292
+ readers: {
293
+ changefreq: (value, current, r) =>
294
+ isText(value) ? value.trim() : r.bad('changefreq', value, current),
295
+ exclude: (value, current, r) =>
296
+ Array.isArray(value) ? value : r.ignore('exclude', 'a list of paths'),
297
+ },
298
+ warn: log.warn,
299
+ })
300
+
301
+ export function getAppData({ app }) {
302
+ const config = reader.normalize(loadPluginConfig('sitemap', { app }))
303
+ return { ...app, sitemap: config }
304
+ }
305
+ ```
306
+
307
+ With `changefreq: 3` and `excludes: []` in the site's `config/sitemap.yaml`, the build prints:
308
+
309
+ ```text
310
+ ⚠️ plugin-sitemap: config/sitemap.yaml: invalid changefreq 3, using "weekly"
311
+ ⚠️ plugin-sitemap: config/sitemap.yaml: ignoring unknown key "excludes"
312
+ ```
313
+
314
+ ### `/packages` — packages as the site sees them
315
+
316
+ #### `requireFromSite(cwd = process.cwd()): NodeJS.Require`
317
+
318
+ A `require` that resolves from the site root, as if the site's own `package.json` asked. Use it for packages the **site** installs (core, a theme, an optional highlighter): resolved from your plugin, they would come from the plugin's own dependencies, or not be found at all. The `package.json` need not exist; only its folder counts.
319
+
320
+ #### `ownVersion(url: string | URL): string | null`
321
+
322
+ The `version` of the package the module at `url` belongs to: the nearest `package.json` with a `version`, from the module's folder upwards (a `{ "type": "module" }` manifest in between is skipped). `null` when there is none or it cannot be parsed. Pass `import.meta.url`; a plain path works too.
323
+
324
+ ```js
325
+ import { ownVersion, requireFromSite } from '@nera-static/plugin-utils/packages'
326
+
327
+ const siteRequire = requireFromSite()
328
+ const themeDir = siteRequire.resolve('@nera-static/theme-blog/package.json')
329
+
330
+ const version = ownVersion(import.meta.url) // your package's version, e.g. '1.2.0'
331
+ ```
332
+
333
+ #### `isPluginPackage(name: unknown): boolean`
334
+
335
+ Whether core loads the dependency `name` as a plugin: an `@nera-static/plugin-*` package other than the library `@nera-static/plugin-utils`, core's own rule. The scope's other members (`core`, `nera`, `validate`, `theme-*`, `starter-*`) are no plugins; a non-string is `false`.
336
+
337
+ #### `pluginShortName(name: string): string`
338
+
339
+ The name core shows a plugin package under, in its log and in `config/plugin-order.yaml`: the package name without `@nera-static/`. Any other name is returned unchanged.
340
+
341
+ #### `pluginPackage(spec: unknown): { name: string, pkg: string }`
342
+
343
+ The official plugin a spec names, in the forms `nera plugin add` takes: `<name>`, `plugin-<name>` or `@nera-static/plugin-<name>`. `name` is the bare name (`'sitemap'`), `pkg` the package. Throws a `TypeError` for anything else (another scope, a version or tag such as `sitemap@1`, a path, an uppercase name, `utils`), with a message that names the accepted forms and the catalog at https://nera.js.org/plugins/.
344
+
345
+ #### `themePackage(spec: unknown): string | null`
346
+
347
+ The npm package a `theme:` spec (`app.theme`) names, by core's rule: a scoped name or one with a `/` is used verbatim (a third-party theme), a bare name becomes `@nera-static/theme-<name>`. `null` for a local theme (a spec starting with `.`) and for a missing or blank spec: no package.
348
+
349
+ ```js
350
+ import { isPluginPackage, pluginPackage, pluginShortName, themePackage } from '@nera-static/plugin-utils/packages'
351
+
352
+ isPluginPackage('@nera-static/plugin-tags') // true
353
+ isPluginPackage('@nera-static/plugin-utils') // false
354
+ isPluginPackage('@nera-static/theme-blog') // false
355
+
356
+ pluginShortName('@nera-static/plugin-tags') // 'plugin-tags'
357
+
358
+ pluginPackage('sitemap') // { name: 'sitemap', pkg: '@nera-static/plugin-sitemap' }
359
+ pluginPackage('plugin-sitemap') // the same
360
+ pluginPackage('utils') // throws TypeError: "utils" is not a Nera plugin. …
361
+
362
+ themePackage('blog') // '@nera-static/theme-blog'
363
+ themePackage('@acme/theme-x') // '@acme/theme-x'
364
+ themePackage('./theme') // null
365
+ ```
366
+
367
+ ### `/guard` — failing loudly on a too-old core
368
+
369
+ A plugin that relies on a hook of a newer `@nera-static/core` (`getAssets` since 4.13.0) is silently never called on an older one, and the build still exits 0. Check core's version from `getAppData` and fail loudly instead; `peerDependencies` reports the same at install time, the guard catches an install that ignored it.
370
+
371
+ #### `assertCoreVersion({ plugin, need = GET_ASSETS_CORE, why = 'the getAssets hook', cwd, from, version, hint })`
372
+
373
+ Throws when core is known to be older than `need`:
374
+
375
+ ```text
376
+ plugin-sitemap: @nera-static/core 4.12.0 is too old; it needs >= 4.13.0 (the getAssets hook). Update with `npm update @nera-static/nera` (or `@nera-static/core`).
377
+ ```
378
+
379
+ `plugin` is the name as you want it shown. `version` defaults to `coreVersion({ cwd, from })`. `hint`, when it is a non-blank string, is appended (trimmed) after the update advice, for a way out that only your plugin knows — e.g. ``hint: 'Or set `assets: false` in config/code-blocks.yaml.'``. An **unknown** version passes: some core is calling the plugin, and refusing on a guess would block a working setup.
380
+
381
+ #### `coreVersion({ cwd = process.cwd(), from } = {}): string | null`
382
+
383
+ The version of `@nera-static/core` the build most likely runs on: resolved from the site root `cwd` first, then, when `from` is given, from there. Pass your plugin's `import.meta.url` as `from`, so a symlinked plugin (`npm link`) that resolves from its real path still finds a core. `null` when none is found.
384
+
385
+ #### `satisfiesFloor(version: unknown, floor: string): boolean`
386
+
387
+ Whether `version` is `floor` or later by semver precedence: major, minor and patch compared as numbers, a prerelease (`4.13.0-beta.1`) **below** its release, build metadata ignored, surrounding whitespace allowed. Anything that is no version is `false`. Throws a `TypeError` when `floor` is not a plain `x.y.z`.
388
+
389
+ #### `GET_ASSETS_CORE`
390
+
391
+ `'4.13.0'`, the core release that introduced the `getAssets` hook, and the default `need`.
392
+
393
+ ```js
394
+ import { assertCoreVersion, satisfiesFloor } from '@nera-static/plugin-utils/guard'
395
+
396
+ export function getAppData({ app }) {
397
+ assertCoreVersion({ plugin: 'plugin-sitemap', from: import.meta.url })
398
+ return { ...app }
399
+ }
400
+
401
+ satisfiesFloor('4.13.0', '4.13.0') // true
402
+ satisfiesFloor(' 4.14.2 ', '4.13.0') // true
403
+ satisfiesFloor('4.13.0-beta.1', '4.13.0') // false
404
+ satisfiesFloor('latest', '4.13.0') // false
405
+ ```
406
+
407
+ ### `/html` — escaping
408
+
409
+ Each escaper takes any value: `null` and `undefined` give `''`, everything else is converted with `String()` first. Each escapes once (`&amp;` becomes `&amp;amp;`).
410
+
411
+ #### `escapeHtml(value: unknown): string`
412
+
413
+ `& < > " '` as entities (`'` as `&#39;`), safe in a text node and in a double- or single-quoted attribute.
414
+
415
+ #### `escapeXml(value: unknown): string`
416
+
417
+ `& < > " '` as entities (`'` as `&apos;`), and the characters XML 1.0 forbids even escaped (C0 controls other than tab, LF and CR; lone surrogates; U+FFFE and U+FFFF) **dropped**, so any page text gives a well-formed feed or sitemap.
418
+
419
+ #### `escapeRegExp(value: unknown): string`
420
+
421
+ Every regular-expression special character (`. * + ? ^ $ { } ( ) | [ ] \`) escaped, for a `RegExp` that matches the text literally.
422
+
423
+ ```js
424
+ import { escapeHtml, escapeRegExp, escapeXml } from '@nera-static/plugin-utils/html'
425
+
426
+ escapeHtml('<a href="x">Tom & Jerry\'s</a>')
427
+ // '&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;'
428
+ escapeHtml(null) // ''
429
+ escapeHtml(42) // '42'
430
+ escapeXml('Tom & Jerry\'s\u0007') // 'Tom &amp; Jerry&apos;s' (the BEL is dropped)
431
+ escapeRegExp('a.b*(c)') // 'a\\.b\\*\\(c\\)'
432
+ ```
433
+
434
+ ### `/lang` — languages and translated values
435
+
436
+ A language is text, **trimmed**: `lang: 'de '` is `de`, and a blank `lang` counts as absent.
437
+
438
+ #### `siteLang(app, fallback = 'en'): string`
439
+
440
+ `app.lang` trimmed, else `fallback`.
441
+
442
+ #### `pageLang(meta, app, fallback = 'en'): string`
443
+
444
+ `meta.lang` trimmed, else `siteLang(app, fallback)`.
445
+
446
+ #### `siteLanguages(app): Set<string>`
447
+
448
+ `app.lang` plus the keys of `app.translations`, each trimmed, blank ones left out. Empty when the site sets neither.
449
+
450
+ #### `isLanguageMap(value: unknown, languages?: Iterable<string>): boolean`
451
+
452
+ Whether `value` is a non-empty plain object and, when `languages` is given, every key is one of them. A map lacking a language still counts (`localize` falls back).
453
+
454
+ #### `localize(value: unknown, lang: string, { fallbacks = [], any = false } = {}): string | null`
455
+
456
+ One value in one language. A string is returned as it is. A language map gives its entry for `lang`, else for the first of `fallbacks` it has, else, with `any`, its first entry; only text entries count, so `de: ''` falls back. Anything else, and a map without a usable entry, gives **`null`** (not `undefined`).
457
+
458
+ ```js
459
+ import { isLanguageMap, localize, pageLang, siteLang, siteLanguages } from '@nera-static/plugin-utils/lang'
460
+
461
+ siteLang({ lang: ' de ' }) // 'de'
462
+ siteLang({}) // 'en'
463
+ pageLang({ lang: 'de ' }, { lang: 'en' }) // 'de'
464
+ pageLang({ lang: ' ' }, { lang: 'fr' }) // 'fr'
465
+ siteLanguages({ lang: 'en', translations: { de: {}, ' es ': {} } }) // Set { 'en', 'de', 'es' }
466
+ isLanguageMap({ en: 'a', xx: 'b' }, ['en', 'de']) // false
467
+
468
+ localize({ en: 'Hi', de: 'Hallo' }, 'de') // 'Hallo'
469
+ localize({ en: 'Hi' }, 'de') // null
470
+ localize({ en: 'Hi' }, 'de', { fallbacks: ['en'] }) // 'Hi'
471
+ localize({ fr: 'Salut' }, 'de', { any: true }) // 'Salut'
472
+ localize('Hi', 'de') // 'Hi'
473
+ ```
474
+
475
+ ### `/dates` — frontmatter dates
476
+
477
+ Nothing here reads the build machine's time zone: a time without an offset is read as **UTC**, as YAML reads an unquoted timestamp, so a site gives the same dates and the same order on every machine.
478
+
479
+ #### `toDate(value: unknown): Date | null`
480
+
481
+ A valid `Date` (core parses an unquoted frontmatter date into one), or a string `YYYY-MM-DD`, optionally followed by `T` or a space and `hh:mm[:ss[.fraction]]` with an optional `Z` or `±hh:mm` offset (surrounding whitespace ignored). A day or time that does not exist (`2026-02-30`, `24:00`) is `null`, as is every other form (`1.10.2026`, a number, an offset like `+0200`).
482
+
483
+ #### `formatW3C(value: unknown): string | null`
484
+
485
+ The date in W3C Datetime form, in UTC: `YYYY-MM-DD` for UTC midnight, else `YYYY-MM-DDThh:mm:ssZ` without milliseconds. Takes whatever `toDate` takes; `null` when that is no date.
486
+
487
+ #### `PUBLISHED_KEYS`
488
+
489
+ `['date', 'datePublished', 'published']`, frozen: the keys `pageDate(meta, 'published')` tries, in order.
490
+
491
+ #### `UPDATED_KEYS`
492
+
493
+ `['updated', 'updatedAt', 'lastmod', 'dateModified']`, frozen: the keys `pageDate(meta, 'updated')` tries, in order.
494
+
495
+ **`createdAt` is in neither list**: core fills it from the file's birth time when the frontmatter has no date, and CI stamps every file alike. A caller that wants it as a fallback for sorting passes it to `byDate` itself.
496
+
497
+ #### `pageDate(meta, kind: 'published' | 'updated', { warn = console.warn } = {}): Date | null`
498
+
499
+ The first key of the list for `kind` whose value is a usable date; `null` when none is. A present value that is no date warns once (`<href>: ignoring <key> <value>, expected a date like …`) and the next key is tried; an absent, `null` or blank value is skipped silently. Pass your logger's `warn`. Any other `kind` throws a `TypeError`.
500
+
501
+ #### `byDate(get, { descending = false } = {}): (a, b) => number`
502
+
503
+ A comparator for `Array.prototype.sort`: `get(item)` returns the item's date in any form `toDate` takes. Oldest first, newest first with `descending`; items without a usable date go **last in both directions**. Equal dates give `0`, so chain a tie-break (`byDate(get)(a, b) || byHref(a, b)`). Throws a `TypeError` when `get` is not a function.
504
+
505
+ ```js
506
+ import { byDate, formatW3C, pageDate, toDate } from '@nera-static/plugin-utils/dates'
507
+ import { createLogger } from '@nera-static/plugin-utils/log'
508
+
509
+ toDate('2026-10-01') // 2026-10-01T00:00:00.000Z
510
+ toDate('2026-10-01 09:30') // 2026-10-01T09:30:00.000Z (UTC)
511
+ toDate('2026-10-01T09:30:00+02:00') // 2026-10-01T07:30:00.000Z
512
+ toDate('2026-02-30') // null
513
+
514
+ formatW3C('2026-10-01') // '2026-10-01'
515
+ formatW3C('2026-10-01T09:30:15.250+02:00') // '2026-10-01T07:30:15Z'
516
+
517
+ const log = createLogger('plugin-feed')
518
+ pageDate({ href: '/a.html', date: '2026-02-30', published: '2026-10-01' }, 'published', { warn: log.warn })
519
+ // 2026-10-01T00:00:00.000Z, after
520
+ // ⚠️ plugin-feed: /a.html: ignoring date "2026-02-30", expected a date like 2026-10-01 or 2026-10-01T09:30:00Z
521
+
522
+ pagesData.sort(byDate((page) => page.meta.date, { descending: true }))
523
+ // newest first, pages without a date at the end
524
+ ```
525
+
526
+ ### `/sort` — locale-free comparators
527
+
528
+ They compare UTF-16 code units, like `<` on strings, never with `localeCompare`: the order is the same on every machine (uppercase before lowercase, ASCII before other letters).
529
+
530
+ #### `byString(a: unknown, b: unknown): -1 | 0 | 1`
531
+
532
+ Two strings by code unit; a non-string compares as `''` and sorts first.
533
+
534
+ #### `byHref(a, b): -1 | 0 | 1`
535
+
536
+ Two pages (`{ meta }`) or two metas by `href` (`x.meta?.href ?? x.href`), as `byString`.
537
+
538
+ ```js
539
+ import { byHref, byString } from '@nera-static/plugin-utils/sort'
540
+
541
+ ['b', 'B', 'a', 'ä'].sort(byString) // ['B', 'a', 'b', 'ä']
542
+ pagesData.sort(byHref) // by meta.href
543
+ ```
544
+
545
+ ### `/urls` — origin, absolute URLs, `base_path`, containment, `srcset`
546
+
547
+ Absolute URLs are percent-encoded, so a canonical link, a sitemap `<loc>` and a feed `<link>` of the same page are the same string. The `base_path` helpers give exactly core's output.
548
+
549
+ #### `resolveOrigin({ cwd = process.cwd(), app } = {}): string`
550
+
551
+ `app.origin`, else `app_origin` from the site's `config/canonical-links.yaml` (`app.folders.config` honoured), without surrounding whitespace and trailing slashes; `''` when neither is set. The file is only read when `app.origin` is blank or missing.
552
+
553
+ #### `encodePath(value: unknown): string`
554
+
555
+ `value` with everything a URL may not contain percent-encoded (space, non-ASCII, a `%` that starts no valid escape), while valid `%XX` escapes and URL delimiters stay, so an encoded path is not encoded twice. A lone surrogate becomes `%EF%BF%BD`; `null`/`undefined` give `''`.
556
+
557
+ #### `joinUrl(origin: string, basePath: string, href: string): string`
558
+
559
+ The absolute URL of a page: `origin` + `basePath` + `href` (`meta.href`), the path encoded by `encodePath`, otherwise verbatim (`/index.html` stays).
560
+
561
+ #### `siteUrl(origin: string, basePath?: string): string`
562
+
563
+ The site's own URL, `origin` + `basePath` without trailing slashes, encoded like `joinUrl`. A non-string `basePath` gives `origin`.
564
+
565
+ #### `normalizeBasePath(raw: unknown): string`
566
+
567
+ `base_path` from `config/app.yaml` as core normalises it into `app.basePath`: a non-string, blank text or `/` gives `''`; otherwise trimmed, trailing slashes dropped, one leading slash guaranteed.
568
+
569
+ #### `withBasePath(url: unknown, basePath: string): unknown`
570
+
571
+ `url` under `basePath`, as core prefixes every root-absolute URL of a built page. Only a string starting with a single `/` is prefixed; `//cdn/…`, a URL with a scheme, a relative URL, a non-string and a value already under `basePath` come back unchanged, so applying it twice is harmless.
572
+
573
+ #### `stripBasePath(url: unknown, basePath: string): unknown`
574
+
575
+ The inverse: `basePath` itself gives `'/'`, `basePath/…` loses the prefix, anything else (`/subway` for `/sub`) comes back unchanged.
576
+
577
+ #### `hasScheme(url: unknown): boolean`
578
+
579
+ Whether `url` starts with a scheme (`https:`, `mailto:`, `data:`, any case). `//host/…` has none.
580
+
581
+ #### `isInside(root: string, target: string, { self = true } = {}): boolean`
582
+
583
+ Whether the path `target` is `root` or lies below it, compared after `path.resolve` (symlinks not followed). A child folder named `..foo` is inside; `/site/publication` is not inside `/site/public`. With `self: false`, `root` itself does not count.
584
+
585
+ #### `srcsetUrls(value: unknown): string[]`
586
+
587
+ The URLs of a `srcset`, by the HTML standard's candidate rule: a URL ends at whitespace, so a comma inside it (`?w=1,2`, a data URI) does not split it. A non-string gives `[]`.
588
+
589
+ #### `mapSrcset(value: unknown, fn: (url, index) => unknown): unknown`
590
+
591
+ `value` with each candidate URL replaced by `fn(url, index)`; descriptors, commas and whitespace are kept byte for byte. A non-string comes back unchanged.
592
+
593
+ ```js
594
+ import {
595
+ encodePath, hasScheme, isInside, joinUrl, mapSrcset, normalizeBasePath,
596
+ resolveOrigin, siteUrl, srcsetUrls, stripBasePath, withBasePath,
597
+ } from '@nera-static/plugin-utils/urls'
598
+
599
+ resolveOrigin({ app: { origin: ' https://ex.com/ ' } }) // 'https://ex.com'
600
+
601
+ encodePath('/über uns.html') // '/%C3%BCber%20uns.html'
602
+ encodePath('/%C3%BCber.html') // '/%C3%BCber.html'
603
+ joinUrl('https://ex.com', '/sub', '/über uns.html') // 'https://ex.com/sub/%C3%BCber%20uns.html'
604
+ siteUrl('https://ex.com', '/sub/') // 'https://ex.com/sub'
605
+
606
+ normalizeBasePath('nera-website/') // '/nera-website'
607
+ normalizeBasePath('/') // ''
608
+ withBasePath('/css/main.css', '/sub') // '/sub/css/main.css'
609
+ withBasePath('/sub/a.html', '/sub') // '/sub/a.html'
610
+ withBasePath('//cdn.example.com/x.js', '/sub') // '//cdn.example.com/x.js'
611
+ stripBasePath('/sub/a.html', '/sub') // '/a.html'
612
+ stripBasePath('/subway', '/sub') // '/subway'
613
+ hasScheme('mailto:x@y.z') // true
614
+
615
+ isInside('/site/public', '/site/public/a.html') // true
616
+ isInside('/site/public', '/site/public', { self: false }) // false
617
+ isInside('/site/public', '/site/publication') // false
618
+
619
+ srcsetUrls('/a.jpg?w=1,2 1x, /b.jpg 2x') // ['/a.jpg?w=1,2', '/b.jpg']
620
+ mapSrcset('/a.jpg 1x, /b.jpg 2x', (url) => withBasePath(url, '/sub'))
621
+ // '/sub/a.jpg 1x, /sub/b.jpg 2x'
622
+ ```
623
+
624
+ ### `/frontmatter` — how core reads a page's frontmatter
625
+
626
+ Both mirror `@nera-static/core`, so a page the validator or an editor accepts parses the same way in the build.
627
+
628
+ #### `FRONTMATTER_OPTIONS`
629
+
630
+ The frozen `yaml` parse options core uses: `{ schema: 'core', customTags: ['timestamp'], merge: true, uniqueKeys: false }` — unquoted dates become `Date` objects, `<<` merge keys work, a repeated key takes the last value. Pass them to `yaml.parse` from your own `yaml` dependency; this package does not depend on `yaml`.
631
+
632
+ #### `splitFrontmatter(raw: string): { yamlText: string, body: string } | null`
633
+
634
+ A page file split by core's rule: CRLF and a lone CR read as LF, the first line must be exactly `---`, the next line that is exactly `---` closes the block (`----` or `--- ` do not). Without a closing line the rest is YAML and the body is empty; an empty block gives `yamlText: ''`. **`null`** when the file has no frontmatter (first line not `---`, a leading BOM or indentation, or `raw` not a string).
635
+
636
+ ```js
637
+ import { parse } from 'yaml'
638
+ import { FRONTMATTER_OPTIONS, splitFrontmatter } from '@nera-static/plugin-utils/frontmatter'
639
+
640
+ splitFrontmatter('---\r\ntitle: Hi\r\n---\r\n# Body\r\n') // { yamlText: 'title: Hi', body: '# Body\n' }
641
+ splitFrontmatter('# no frontmatter') // null
642
+ splitFrontmatter('---\n---\nx') // { yamlText: '', body: 'x' }
643
+
644
+ const parts = splitFrontmatter(raw)
645
+ const meta = parts ? parse(parts.yamlText, FRONTMATTER_OPTIONS) ?? {} : {}
646
+ ```
647
+
648
+ ### `/glob` — exclude patterns and `.neraignore`
649
+
650
+ Two rule sets, kept apart on purpose: the `*` glob of the sitemap and feed `exclude` lists, and core's `.neraignore` rule, which knows no wildcards.
651
+
652
+ #### `matchesPattern(href: unknown, pattern: unknown): boolean`
653
+
654
+ `*` matches any run of characters (`/` included, none at all), everything else is literal, anchored at both ends. A non-string never matches.
655
+
656
+ #### `matchesAny(href: unknown, patterns: unknown[] = []): boolean`
657
+
658
+ Whether `href` matches any of `patterns`; a non-array matches nothing.
659
+
660
+ #### `IGNORE_FILE`
661
+
662
+ `'.neraignore'`, the file name `readIgnoreList` reads from the site root.
663
+
664
+ #### `readIgnoreList(cwd = process.cwd()): string[]`
665
+
666
+ The patterns in the site's `.neraignore`, one per line, trimmed, blank lines dropped; `[]` when the file does not exist. Read from the site root, as core reads it.
667
+
668
+ #### `isIgnoredAsset(ignoreList: string[], file: string, root: string): boolean`
669
+
670
+ Whether core's asset copy skips `file`: its path relative to `root` (the assets folder), with `/` separators, equals a pattern or starts with a pattern plus `/`. So `images` skips `images/a.png`, `images/` skips nothing, and `robots` does not skip `robots.txt`.
671
+
672
+ ```js
673
+ import { isIgnoredAsset, matchesAny, matchesPattern, readIgnoreList } from '@nera-static/plugin-utils/glob'
674
+
675
+ matchesPattern('/drafts/a.html', '/drafts/*') // true
676
+ matchesPattern('/drafts/a.html', '/drafts') // false
677
+ matchesAny('/404.html', ['/404.html', '/drafts/*']) // true
678
+
679
+ const ignored = readIgnoreList() // e.g. ['images', 'robots']
680
+ isIgnoredAsset(['images'], '/site/assets/images/a.png', '/site/assets') // true
681
+ isIgnoredAsset(['robots'], '/site/assets/robots.txt', '/site/assets') // false
682
+ ```
683
+
684
+ ### `/pages` — which pages a plugin acts on
685
+
686
+ #### `isRenderedPage(meta): boolean`
687
+
688
+ Whether core renders the page: a non-blank `layout` and `href`. Core skips a page without `layout` silently, so a sitemap, feed or search index listing it points at nothing.
689
+
690
+ #### `isNoindex(meta, app): boolean`
691
+
692
+ Whether the page asks search engines not to index it: `meta.robots`, or `app.robots` when the page sets none, contains `noindex` in any case.
693
+
694
+ ```js
695
+ import { isNoindex, isRenderedPage } from '@nera-static/plugin-utils/pages'
696
+
697
+ isRenderedPage({ layout: 'pages/default.pug', href: '/a.html' }) // true
698
+ isRenderedPage({ href: '/a.html' }) // false
699
+ isNoindex({ robots: 'NoIndex, follow' }, {}) // true
700
+ isNoindex({}, { robots: 'noindex' }) // true
701
+ isNoindex({ robots: 'index' }, { robots: 'noindex' }) // false
702
+ ```
703
+
704
+ ---
705
+
176
706
  ## 🧱 Use Cases
177
707
 
178
708
  This package is intended for use inside Nera plugins to:
@@ -185,7 +715,7 @@ This package is intended for use inside Nera plugins to:
185
715
 
186
716
  ```js
187
717
  // index.js - Main plugin file
188
- import path from 'path'
718
+ import path from 'node:path'
189
719
  import { getConfig } from '@nera-static/plugin-utils'
190
720
 
191
721
  export function getAppData(data) {
@@ -212,8 +742,8 @@ See the [Nera contributing guide](https://github.com/seebaermichi/nera/blob/main
212
742
  #!/usr/bin/env node
213
743
  // bin/publish-template.js - Template publishing script
214
744
 
215
- import path from 'path'
216
- import { fileURLToPath } from 'url'
745
+ import path from 'node:path'
746
+ import { fileURLToPath } from 'node:url'
217
747
  import { publishAllTemplates } from '@nera-static/plugin-utils'
218
748
 
219
749
  const __dirname = path.dirname(fileURLToPath(import.meta.url))