@nera-static/plugin-utils 1.7.0 → 1.9.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/CHANGELOG.md CHANGED
@@ -5,6 +5,85 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.9.0] - 2026-11-28
9
+
10
+ ### Added
11
+
12
+ - **`@nera-static/plugin-utils/files`**: `walkFiles(dir, { dotfiles, ext,
13
+ relative })`, the one recursive file listing for core's pages folder
14
+ (dotfiles skipped, names relative to the folder, as `fs-readdir-recursive`
15
+ gave them) and its asset copy (`dotfiles: true`, absolute paths). It is
16
+ synchronous and lists depth first, each folder's entries in byte order;
17
+ it follows symbolic links, skips dangling ones, does not loop on a link
18
+ back to an ancestor, and gives `[]` for a missing folder. No runtime
19
+ dependency was added
20
+
21
+ ## [1.8.0] - 2026-11-27
22
+
23
+ The second half of the helpers Nera plugins, core and the tools copy from
24
+ each other: languages, dates, URLs and `base_path`, escaping, frontmatter,
25
+ glob matching, package names and page selection. Each subpath is written
26
+ once from the best sibling variant and documented in the README under
27
+ "Shared helpers". Nothing in `.` or in the 1.7.0 subpaths changed, and no
28
+ runtime dependency was added (still `js-yaml` only).
29
+
30
+ If you replace a local copy with one of these, check the shapes below: several
31
+ differ from what some siblings return today.
32
+
33
+ ### Added
34
+
35
+ - **`@nera-static/plugin-utils/html`**: `escapeHtml` (`& < > " '`, `'` as
36
+ `&#39;`), `escapeXml` (`'` as `&apos;`, and the characters XML 1.0 forbids
37
+ even escaped are dropped) and `escapeRegExp`. Every escaper takes any
38
+ value: `null` and `undefined` give `''`, so `escapeHtml(null)` is `''`, not
39
+ `'null'`
40
+ - **`@nera-static/plugin-utils/lang`**: `siteLang(app, fallback = 'en')`,
41
+ `pageLang(meta, app, fallback = 'en')`, `siteLanguages(app)`,
42
+ `isLanguageMap(value, languages)` and `localize(value, lang, { fallbacks,
43
+ any })`. Languages are trimmed and a blank one counts as absent, so
44
+ `lang: 'de '` is `de`. `localize` returns `null` (not `undefined`) when no
45
+ entry fits
46
+ - **`@nera-static/plugin-utils/dates`**: `toDate(value)`, `formatW3C(value)`,
47
+ `pageDate(meta, 'published' | 'updated', { warn })`, `byDate(get, {
48
+ descending })` and the frozen key lists `PUBLISHED_KEYS` (`date`,
49
+ `datePublished`, `published`) and `UPDATED_KEYS` (`updated`, `updatedAt`,
50
+ `lastmod`, `dateModified`). **`createdAt` is never read**: core fills it
51
+ from the file's birth time, which CI stamps alike for every file. A time
52
+ without an offset is read as UTC, an impossible day such as `2026-02-30` is
53
+ no date, and only `Z` and `±hh:mm` offsets are accepted (`+0200` is not).
54
+ `pageDate` takes the first valid key and warns once per invalid value;
55
+ `byDate` puts items without a date last in both directions
56
+ - **`@nera-static/plugin-utils/sort`**: `byString` and `byHref`, comparing
57
+ code units instead of `localeCompare`, so the order is the same on every
58
+ machine
59
+ - **`@nera-static/plugin-utils/urls`**: `resolveOrigin({ cwd, app })`
60
+ (`app.origin`, else canonical-links' `app_origin`, trimmed),
61
+ `encodePath`, `joinUrl` and `siteUrl` (percent-encoded, so a canonical
62
+ link and a sitemap URL of a page are the same string),
63
+ `normalizeBasePath`, `withBasePath` and `stripBasePath` (core's exact
64
+ `base_path` rules), `hasScheme`, `isInside(root, target, { self })` (a
65
+ child folder named `..foo` is inside), and `srcsetUrls`/`mapSrcset`. The
66
+ `srcset` helpers follow the HTML candidate rule, where a URL ends at
67
+ whitespace: `/a.jpg?w=1,2` and data URIs stay whole, unlike splitting on
68
+ commas
69
+ - **`@nera-static/plugin-utils/frontmatter`**: `FRONTMATTER_OPTIONS`, core's
70
+ frozen `yaml` options (`timestamp`, `<<` merge, last duplicate key wins),
71
+ and `splitFrontmatter(raw)` → `{ yamlText, body }` by core's fence rule
72
+ (`----` and `--- ` are no fences, an unclosed block is YAML to the end).
73
+ It returns `null` when the file has no frontmatter
74
+ - **`@nera-static/plugin-utils/glob`**: `matchesPattern` and `matchesAny`
75
+ (the `*` glob of the sitemap and feed `exclude` lists), and, mirroring
76
+ core's `.neraignore` handling, `IGNORE_FILE`, `readIgnoreList(cwd)` and
77
+ `isIgnoredAsset(list, file, root)` (`true` means skipped)
78
+ - **`@nera-static/plugin-utils/packages`** gains the package-name rules:
79
+ `isPluginPackage(name)` (core's plugin discovery), `pluginShortName(name)`,
80
+ `pluginPackage(spec)`, which returns `{ name, pkg }` and throws a
81
+ `TypeError` for an invalid spec, and `themePackage(spec)` (core's rule,
82
+ `null` for a local or blank spec)
83
+ - **`@nera-static/plugin-utils/pages`**: `isRenderedPage(meta)` (non-blank
84
+ `layout` and `href`) and `isNoindex(meta, app)` (`noindex` in the page's
85
+ `robots`, else the site's)
86
+
8
87
  ## [1.7.0] - 2026-11-27
9
88
 
10
89
  The helpers that Nera plugins, core and the tools copy from each other now
package/README.md CHANGED
@@ -175,15 +175,24 @@ process.exit(result ? 0 : 1)
175
175
 
176
176
  ## 🧩 Shared helpers (subpath exports)
177
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. 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), reads globals beyond a `cwd` default of `process.cwd()`, or calls `process.exit`.
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`, 1.9.0 `/files`). 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
179
 
180
180
  | Subpath | Exports |
181
181
  |---|---|
182
182
  | `@nera-static/plugin-utils/values` | `isPlainObject`, `isText`, `textOr` |
183
183
  | `@nera-static/plugin-utils/log` | `createLogger` |
184
184
  | `@nera-static/plugin-utils/config` | `getConfig`, `loadPluginConfig`, `createConfigReader` |
185
- | `@nera-static/plugin-utils/packages` | `requireFromSite`, `ownVersion` |
185
+ | `@nera-static/plugin-utils/packages` | `requireFromSite`, `ownVersion`, `isPluginPackage`, `pluginShortName`, `pluginPackage`, `themePackage` |
186
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
+ | `@nera-static/plugin-utils/files` | `walkFiles` |
187
196
 
188
197
  ### `/values` — checks for parsed YAML and frontmatter
189
198
 
@@ -322,6 +331,40 @@ const themeDir = siteRequire.resolve('@nera-static/theme-blog/package.json')
322
331
  const version = ownVersion(import.meta.url) // your package's version, e.g. '1.2.0'
323
332
  ```
324
333
 
334
+ #### `isPluginPackage(name: unknown): boolean`
335
+
336
+ 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`.
337
+
338
+ #### `pluginShortName(name: string): string`
339
+
340
+ 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.
341
+
342
+ #### `pluginPackage(spec: unknown): { name: string, pkg: string }`
343
+
344
+ 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/.
345
+
346
+ #### `themePackage(spec: unknown): string | null`
347
+
348
+ 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.
349
+
350
+ ```js
351
+ import { isPluginPackage, pluginPackage, pluginShortName, themePackage } from '@nera-static/plugin-utils/packages'
352
+
353
+ isPluginPackage('@nera-static/plugin-tags') // true
354
+ isPluginPackage('@nera-static/plugin-utils') // false
355
+ isPluginPackage('@nera-static/theme-blog') // false
356
+
357
+ pluginShortName('@nera-static/plugin-tags') // 'plugin-tags'
358
+
359
+ pluginPackage('sitemap') // { name: 'sitemap', pkg: '@nera-static/plugin-sitemap' }
360
+ pluginPackage('plugin-sitemap') // the same
361
+ pluginPackage('utils') // throws TypeError: "utils" is not a Nera plugin. …
362
+
363
+ themePackage('blog') // '@nera-static/theme-blog'
364
+ themePackage('@acme/theme-x') // '@acme/theme-x'
365
+ themePackage('./theme') // null
366
+ ```
367
+
325
368
  ### `/guard` — failing loudly on a too-old core
326
369
 
327
370
  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.
@@ -362,6 +405,323 @@ satisfiesFloor('4.13.0-beta.1', '4.13.0') // false
362
405
  satisfiesFloor('latest', '4.13.0') // false
363
406
  ```
364
407
 
408
+ ### `/html` — escaping
409
+
410
+ Each escaper takes any value: `null` and `undefined` give `''`, everything else is converted with `String()` first. Each escapes once (`&amp;` becomes `&amp;amp;`).
411
+
412
+ #### `escapeHtml(value: unknown): string`
413
+
414
+ `& < > " '` as entities (`'` as `&#39;`), safe in a text node and in a double- or single-quoted attribute.
415
+
416
+ #### `escapeXml(value: unknown): string`
417
+
418
+ `& < > " '` 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.
419
+
420
+ #### `escapeRegExp(value: unknown): string`
421
+
422
+ Every regular-expression special character (`. * + ? ^ $ { } ( ) | [ ] \`) escaped, for a `RegExp` that matches the text literally.
423
+
424
+ ```js
425
+ import { escapeHtml, escapeRegExp, escapeXml } from '@nera-static/plugin-utils/html'
426
+
427
+ escapeHtml('<a href="x">Tom & Jerry\'s</a>')
428
+ // '&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;'
429
+ escapeHtml(null) // ''
430
+ escapeHtml(42) // '42'
431
+ escapeXml('Tom & Jerry\'s\u0007') // 'Tom &amp; Jerry&apos;s' (the BEL is dropped)
432
+ escapeRegExp('a.b*(c)') // 'a\\.b\\*\\(c\\)'
433
+ ```
434
+
435
+ ### `/lang` — languages and translated values
436
+
437
+ A language is text, **trimmed**: `lang: 'de '` is `de`, and a blank `lang` counts as absent.
438
+
439
+ #### `siteLang(app, fallback = 'en'): string`
440
+
441
+ `app.lang` trimmed, else `fallback`.
442
+
443
+ #### `pageLang(meta, app, fallback = 'en'): string`
444
+
445
+ `meta.lang` trimmed, else `siteLang(app, fallback)`.
446
+
447
+ #### `siteLanguages(app): Set<string>`
448
+
449
+ `app.lang` plus the keys of `app.translations`, each trimmed, blank ones left out. Empty when the site sets neither.
450
+
451
+ #### `isLanguageMap(value: unknown, languages?: Iterable<string>): boolean`
452
+
453
+ 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).
454
+
455
+ #### `localize(value: unknown, lang: string, { fallbacks = [], any = false } = {}): string | null`
456
+
457
+ 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`).
458
+
459
+ ```js
460
+ import { isLanguageMap, localize, pageLang, siteLang, siteLanguages } from '@nera-static/plugin-utils/lang'
461
+
462
+ siteLang({ lang: ' de ' }) // 'de'
463
+ siteLang({}) // 'en'
464
+ pageLang({ lang: 'de ' }, { lang: 'en' }) // 'de'
465
+ pageLang({ lang: ' ' }, { lang: 'fr' }) // 'fr'
466
+ siteLanguages({ lang: 'en', translations: { de: {}, ' es ': {} } }) // Set { 'en', 'de', 'es' }
467
+ isLanguageMap({ en: 'a', xx: 'b' }, ['en', 'de']) // false
468
+
469
+ localize({ en: 'Hi', de: 'Hallo' }, 'de') // 'Hallo'
470
+ localize({ en: 'Hi' }, 'de') // null
471
+ localize({ en: 'Hi' }, 'de', { fallbacks: ['en'] }) // 'Hi'
472
+ localize({ fr: 'Salut' }, 'de', { any: true }) // 'Salut'
473
+ localize('Hi', 'de') // 'Hi'
474
+ ```
475
+
476
+ ### `/dates` — frontmatter dates
477
+
478
+ 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.
479
+
480
+ #### `toDate(value: unknown): Date | null`
481
+
482
+ 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`).
483
+
484
+ #### `formatW3C(value: unknown): string | null`
485
+
486
+ 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.
487
+
488
+ #### `PUBLISHED_KEYS`
489
+
490
+ `['date', 'datePublished', 'published']`, frozen: the keys `pageDate(meta, 'published')` tries, in order.
491
+
492
+ #### `UPDATED_KEYS`
493
+
494
+ `['updated', 'updatedAt', 'lastmod', 'dateModified']`, frozen: the keys `pageDate(meta, 'updated')` tries, in order.
495
+
496
+ **`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.
497
+
498
+ #### `pageDate(meta, kind: 'published' | 'updated', { warn = console.warn } = {}): Date | null`
499
+
500
+ 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`.
501
+
502
+ #### `byDate(get, { descending = false } = {}): (a, b) => number`
503
+
504
+ 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.
505
+
506
+ ```js
507
+ import { byDate, formatW3C, pageDate, toDate } from '@nera-static/plugin-utils/dates'
508
+ import { createLogger } from '@nera-static/plugin-utils/log'
509
+
510
+ toDate('2026-10-01') // 2026-10-01T00:00:00.000Z
511
+ toDate('2026-10-01 09:30') // 2026-10-01T09:30:00.000Z (UTC)
512
+ toDate('2026-10-01T09:30:00+02:00') // 2026-10-01T07:30:00.000Z
513
+ toDate('2026-02-30') // null
514
+
515
+ formatW3C('2026-10-01') // '2026-10-01'
516
+ formatW3C('2026-10-01T09:30:15.250+02:00') // '2026-10-01T07:30:15Z'
517
+
518
+ const log = createLogger('plugin-feed')
519
+ pageDate({ href: '/a.html', date: '2026-02-30', published: '2026-10-01' }, 'published', { warn: log.warn })
520
+ // 2026-10-01T00:00:00.000Z, after
521
+ // ⚠️ plugin-feed: /a.html: ignoring date "2026-02-30", expected a date like 2026-10-01 or 2026-10-01T09:30:00Z
522
+
523
+ pagesData.sort(byDate((page) => page.meta.date, { descending: true }))
524
+ // newest first, pages without a date at the end
525
+ ```
526
+
527
+ ### `/sort` — locale-free comparators
528
+
529
+ 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).
530
+
531
+ #### `byString(a: unknown, b: unknown): -1 | 0 | 1`
532
+
533
+ Two strings by code unit; a non-string compares as `''` and sorts first.
534
+
535
+ #### `byHref(a, b): -1 | 0 | 1`
536
+
537
+ Two pages (`{ meta }`) or two metas by `href` (`x.meta?.href ?? x.href`), as `byString`.
538
+
539
+ ```js
540
+ import { byHref, byString } from '@nera-static/plugin-utils/sort'
541
+
542
+ ['b', 'B', 'a', 'ä'].sort(byString) // ['B', 'a', 'b', 'ä']
543
+ pagesData.sort(byHref) // by meta.href
544
+ ```
545
+
546
+ ### `/urls` — origin, absolute URLs, `base_path`, containment, `srcset`
547
+
548
+ 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.
549
+
550
+ #### `resolveOrigin({ cwd = process.cwd(), app } = {}): string`
551
+
552
+ `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.
553
+
554
+ #### `encodePath(value: unknown): string`
555
+
556
+ `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 `''`.
557
+
558
+ #### `joinUrl(origin: string, basePath: string, href: string): string`
559
+
560
+ The absolute URL of a page: `origin` + `basePath` + `href` (`meta.href`), the path encoded by `encodePath`, otherwise verbatim (`/index.html` stays).
561
+
562
+ #### `siteUrl(origin: string, basePath?: string): string`
563
+
564
+ The site's own URL, `origin` + `basePath` without trailing slashes, encoded like `joinUrl`. A non-string `basePath` gives `origin`.
565
+
566
+ #### `normalizeBasePath(raw: unknown): string`
567
+
568
+ `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.
569
+
570
+ #### `withBasePath(url: unknown, basePath: string): unknown`
571
+
572
+ `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.
573
+
574
+ #### `stripBasePath(url: unknown, basePath: string): unknown`
575
+
576
+ The inverse: `basePath` itself gives `'/'`, `basePath/…` loses the prefix, anything else (`/subway` for `/sub`) comes back unchanged.
577
+
578
+ #### `hasScheme(url: unknown): boolean`
579
+
580
+ Whether `url` starts with a scheme (`https:`, `mailto:`, `data:`, any case). `//host/…` has none.
581
+
582
+ #### `isInside(root: string, target: string, { self = true } = {}): boolean`
583
+
584
+ 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.
585
+
586
+ #### `srcsetUrls(value: unknown): string[]`
587
+
588
+ 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 `[]`.
589
+
590
+ #### `mapSrcset(value: unknown, fn: (url, index) => unknown): unknown`
591
+
592
+ `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.
593
+
594
+ ```js
595
+ import {
596
+ encodePath, hasScheme, isInside, joinUrl, mapSrcset, normalizeBasePath,
597
+ resolveOrigin, siteUrl, srcsetUrls, stripBasePath, withBasePath,
598
+ } from '@nera-static/plugin-utils/urls'
599
+
600
+ resolveOrigin({ app: { origin: ' https://ex.com/ ' } }) // 'https://ex.com'
601
+
602
+ encodePath('/über uns.html') // '/%C3%BCber%20uns.html'
603
+ encodePath('/%C3%BCber.html') // '/%C3%BCber.html'
604
+ joinUrl('https://ex.com', '/sub', '/über uns.html') // 'https://ex.com/sub/%C3%BCber%20uns.html'
605
+ siteUrl('https://ex.com', '/sub/') // 'https://ex.com/sub'
606
+
607
+ normalizeBasePath('nera-website/') // '/nera-website'
608
+ normalizeBasePath('/') // ''
609
+ withBasePath('/css/main.css', '/sub') // '/sub/css/main.css'
610
+ withBasePath('/sub/a.html', '/sub') // '/sub/a.html'
611
+ withBasePath('//cdn.example.com/x.js', '/sub') // '//cdn.example.com/x.js'
612
+ stripBasePath('/sub/a.html', '/sub') // '/a.html'
613
+ stripBasePath('/subway', '/sub') // '/subway'
614
+ hasScheme('mailto:x@y.z') // true
615
+
616
+ isInside('/site/public', '/site/public/a.html') // true
617
+ isInside('/site/public', '/site/public', { self: false }) // false
618
+ isInside('/site/public', '/site/publication') // false
619
+
620
+ srcsetUrls('/a.jpg?w=1,2 1x, /b.jpg 2x') // ['/a.jpg?w=1,2', '/b.jpg']
621
+ mapSrcset('/a.jpg 1x, /b.jpg 2x', (url) => withBasePath(url, '/sub'))
622
+ // '/sub/a.jpg 1x, /sub/b.jpg 2x'
623
+ ```
624
+
625
+ ### `/frontmatter` — how core reads a page's frontmatter
626
+
627
+ Both mirror `@nera-static/core`, so a page the validator or an editor accepts parses the same way in the build.
628
+
629
+ #### `FRONTMATTER_OPTIONS`
630
+
631
+ 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`.
632
+
633
+ #### `splitFrontmatter(raw: string): { yamlText: string, body: string } | null`
634
+
635
+ 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).
636
+
637
+ ```js
638
+ import { parse } from 'yaml'
639
+ import { FRONTMATTER_OPTIONS, splitFrontmatter } from '@nera-static/plugin-utils/frontmatter'
640
+
641
+ splitFrontmatter('---\r\ntitle: Hi\r\n---\r\n# Body\r\n') // { yamlText: 'title: Hi', body: '# Body\n' }
642
+ splitFrontmatter('# no frontmatter') // null
643
+ splitFrontmatter('---\n---\nx') // { yamlText: '', body: 'x' }
644
+
645
+ const parts = splitFrontmatter(raw)
646
+ const meta = parts ? parse(parts.yamlText, FRONTMATTER_OPTIONS) ?? {} : {}
647
+ ```
648
+
649
+ ### `/glob` — exclude patterns and `.neraignore`
650
+
651
+ 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.
652
+
653
+ #### `matchesPattern(href: unknown, pattern: unknown): boolean`
654
+
655
+ `*` matches any run of characters (`/` included, none at all), everything else is literal, anchored at both ends. A non-string never matches.
656
+
657
+ #### `matchesAny(href: unknown, patterns: unknown[] = []): boolean`
658
+
659
+ Whether `href` matches any of `patterns`; a non-array matches nothing.
660
+
661
+ #### `IGNORE_FILE`
662
+
663
+ `'.neraignore'`, the file name `readIgnoreList` reads from the site root.
664
+
665
+ #### `readIgnoreList(cwd = process.cwd()): string[]`
666
+
667
+ 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.
668
+
669
+ #### `isIgnoredAsset(ignoreList: string[], file: string, root: string): boolean`
670
+
671
+ 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`.
672
+
673
+ ```js
674
+ import { isIgnoredAsset, matchesAny, matchesPattern, readIgnoreList } from '@nera-static/plugin-utils/glob'
675
+
676
+ matchesPattern('/drafts/a.html', '/drafts/*') // true
677
+ matchesPattern('/drafts/a.html', '/drafts') // false
678
+ matchesAny('/404.html', ['/404.html', '/drafts/*']) // true
679
+
680
+ const ignored = readIgnoreList() // e.g. ['images', 'robots']
681
+ isIgnoredAsset(['images'], '/site/assets/images/a.png', '/site/assets') // true
682
+ isIgnoredAsset(['robots'], '/site/assets/robots.txt', '/site/assets') // false
683
+ ```
684
+
685
+ ### `/pages` — which pages a plugin acts on
686
+
687
+ #### `isRenderedPage(meta): boolean`
688
+
689
+ 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.
690
+
691
+ #### `isNoindex(meta, app): boolean`
692
+
693
+ 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.
694
+
695
+ ```js
696
+ import { isNoindex, isRenderedPage } from '@nera-static/plugin-utils/pages'
697
+
698
+ isRenderedPage({ layout: 'pages/default.pug', href: '/a.html' }) // true
699
+ isRenderedPage({ href: '/a.html' }) // false
700
+ isNoindex({ robots: 'NoIndex, follow' }, {}) // true
701
+ isNoindex({}, { robots: 'noindex' }) // true
702
+ isNoindex({ robots: 'index' }, { robots: 'noindex' }) // false
703
+ ```
704
+
705
+ ### `/files` — listing the files under a folder
706
+
707
+ #### `walkFiles(dir: string, { dotfiles = false, ext, relative = false } = {}): string[]`
708
+
709
+ Every regular file under `dir`, synchronously, depth first, the entries of each folder in byte order (so `a/z.md` comes before `a.md`, and `B.md` before `a.md`), the same on every machine. Symbolic links are followed: a linked file is listed under the link's name, a linked folder is walked (under each name it is linked by), a dangling link is skipped, and a link back to a folder already being walked is not entered again. A `dir` that does not exist or is no folder gives `[]`.
710
+
711
+ - `dotfiles`: list names starting with `.`; when `false` (the default) a dot folder is not entered either.
712
+ - `ext`: keep only files with this extension, or one of a list, compared exactly with `path.extname` (`'.md'`, not `'md'`).
713
+ - `relative`: paths relative to `dir`, with the platform separator, instead of absolute ones.
714
+
715
+ With the defaults and `relative: true` it lists a pages folder as core does; with `dotfiles: true` it lists an assets folder as core copies it (core then drops OS junk such as `.DS_Store` by name).
716
+
717
+ ```js
718
+ import { walkFiles } from '@nera-static/plugin-utils/files'
719
+
720
+ walkFiles('pages', { relative: true }) // ['blog/post.md', 'index.md']
721
+ walkFiles('pages', { relative: true, ext: '.md' }) // only Markdown files
722
+ walkFiles('/site/assets', { dotfiles: true }) // ['/site/assets/.well-known/security.txt', '/site/assets/css/main.css']
723
+ ```
724
+
365
725
  ---
366
726
 
367
727
  ## 🧱 Use Cases
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.7.0",
4
- "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
3
+ "version": "1.9.0",
4
+ "description": "Shared helpers for Nera plugins and tools: config loading, template publishing, and subpath exports for values, logging, languages, dates, URLs and base_path, escaping, frontmatter, globs, package names, pages and file listing",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "repository": {
@@ -31,7 +31,8 @@
31
31
  "devDependencies": {
32
32
  "eslint": "^10.8.0",
33
33
  "husky": "^9.1.7",
34
- "vitest": "^5.0.0"
34
+ "vitest": "^5.0.0",
35
+ "yaml": "^2.4.1"
35
36
  },
36
37
  "scripts": {
37
38
  "test": "vitest",
@@ -45,7 +46,16 @@
45
46
  "./log": "./src/log.js",
46
47
  "./config": "./src/config.js",
47
48
  "./packages": "./src/packages.js",
48
- "./guard": "./src/guard.js"
49
+ "./guard": "./src/guard.js",
50
+ "./html": "./src/html.js",
51
+ "./lang": "./src/lang.js",
52
+ "./dates": "./src/dates.js",
53
+ "./sort": "./src/sort.js",
54
+ "./urls": "./src/urls.js",
55
+ "./frontmatter": "./src/frontmatter.js",
56
+ "./glob": "./src/glob.js",
57
+ "./pages": "./src/pages.js",
58
+ "./files": "./src/files.js"
49
59
  },
50
60
  "files": [
51
61
  "index.js",