@nera-static/plugin-utils 1.3.1 → 1.5.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.
Files changed (3) hide show
  1. package/README.md +56 -1
  2. package/index.js +158 -4
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -35,6 +35,40 @@ const config = getConfig(path.resolve(process.cwd(), 'config/my-plugin.yaml'))
35
35
  const title = config.title || 'Default title'
36
36
  ```
37
37
 
38
+ ### Slugs
39
+
40
+ #### `slugify(text: string): string`
41
+
42
+ Turns a user-authored string into a URL-safe slug, for anything that becomes a path segment, an HTML `id`, or a URL fragment.
43
+
44
+ ```js
45
+ import { slugify } from '@nera-static/plugin-utils'
46
+
47
+ slugify('Web Development') // 'web-development'
48
+ slugify('Über uns') // 'uber-uns'
49
+ slugify('Straße') // 'strasse'
50
+ slugify('Café') // 'cafe'
51
+ slugify('About Us!') // 'about-us'
52
+ slugify('日本語') // ''
53
+ ```
54
+
55
+ **Use this rather than writing your own.** The obvious one-liner is ASCII-only and produces broken output:
56
+
57
+ ```js
58
+ text.toLowerCase().replace(/[^\w]+/g, '-') // ❌ don't
59
+ ```
60
+
61
+ `\w` is `[A-Za-z0-9_]`, so `Über uns` becomes `-ber-uns` and `Straße` becomes `stra-e`. A leading hyphen is legal in an HTML `id` but is **not a valid CSS identifier** — `#-ber-uns` matches nothing in a stylesheet and `document.querySelector('#-ber-uns')` throws. That defect shipped in `plugin-one-page` until v3.0.0.
62
+
63
+ The rule: `ß` → `ss` (it has no NFKD decomposition, so it would otherwise become a hyphen mid-word), then NFKD with combining marks dropped, then lowercase, then every run of non-alphanumerics collapsed to a single `-`, then leading and trailing hyphens trimmed. It is idempotent.
64
+
65
+ A string with no Latin letters or digits returns `''`. **Decide what that means at the call site** — omitting the element is usually better than emitting `id=""`:
66
+
67
+ ```js
68
+ const id = slugify(heading)
69
+ return id ? `<a id="${id}"></a>` : ''
70
+ ```
71
+
38
72
  ### Template Publishing
39
73
 
40
74
  #### `validateNeraProject(expectedPackageName?: string): boolean`
@@ -55,7 +89,7 @@ if (validateNeraProject()) {
55
89
 
56
90
  Publishes specific template files from a plugin to a Nera project.
57
91
 
58
- If `views/vendor/<pluginName>/` already exists, publishing is **skipped** and the function returns `true` — this protects the customizations you have made to previously published templates. Pass `force: true` to overwrite them.
92
+ The destination is **theme-aware**, resolved exactly as the generator resolves its views folder (see `resolveViewsDir` below): `theme/views/vendor/<pluginName>/` on a themed site, the deprecated root `views/vendor/<pluginName>/` otherwise. If it already exists, publishing is **skipped** and the function returns `true` — this protects the customizations you have made to previously published templates. Pass `force: true` to overwrite them.
59
93
 
60
94
  ```js
61
95
  import { publishTemplates } from '@nera-static/plugin-utils'
@@ -88,6 +122,27 @@ const result = publishAllTemplates({
88
122
 
89
123
  Returns `true` and logs a warning if `sourceDir` contains no `.pug` files; an unreadable `sourceDir` returns `false`. A publish script following the `process.exit(result ? 0 : 1)` pattern below therefore exits `0` having copied nothing — check your `sourceDir` if a plugin's templates never appear.
90
124
 
125
+ #### `publishAsset(options): boolean`
126
+
127
+ Publishes a **single support file** — a plugin's client script, say — into the project's assets folder, theme-aware (`theme/assets/` on a themed site, deprecated root `assets/` otherwise) and with the same skip-if-exists rule as `publishTemplates`. Use it for plugins that ship a runtime asset alongside their templates, so the asset lands where a themed build actually serves it rather than a root `assets/` copy the build ignores.
128
+
129
+ ```js
130
+ import { publishAsset } from '@nera-static/plugin-utils'
131
+
132
+ const result = publishAsset({
133
+ sourceFile: path.resolve(__dirname, '../views/my-plugin.js'),
134
+ targetPath: 'js/my-plugin.js', // relative to the resolved assets root
135
+ expectedPackageName: 'dummy', // optional, for testing
136
+ force: false, // optional, overwrite an existing file
137
+ })
138
+ ```
139
+
140
+ Returns `false` outside a Nera project or when `sourceFile` is missing; a deliberate skip of an existing file returns `true`.
141
+
142
+ #### `resolveViewsDir(cwd?): string` / `resolveAssetsDir(cwd?): string`
143
+
144
+ 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.
145
+
91
146
  > 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.
92
147
 
93
148
  ### Template Publishing CLI Integration
package/index.js CHANGED
@@ -10,6 +10,43 @@ export function getConfig(filePath) {
10
10
  return {}
11
11
  }
12
12
 
13
+ /**
14
+ * Turns a user-authored string into a URL-safe slug, for anything that becomes
15
+ * a path segment, an HTML `id`, or a URL fragment.
16
+ *
17
+ * Lives here because plugins kept reinventing it and getting it wrong. The
18
+ * naive rule — `text.toLowerCase().replace(/[^\w]+/g, '-')` — is ASCII-only:
19
+ * `\w` is `[A-Za-z0-9_]`, so `Über uns` becomes `-ber-uns` and `Straße`
20
+ * becomes `stra-e`. A leading hyphen is legal in an HTML `id` but is **not** a
21
+ * valid CSS identifier, so `#-ber-uns` matches nothing in a stylesheet and
22
+ * `document.querySelector('#-ber-uns')` throws. That shipped in
23
+ * `plugin-one-page` until v3.0.0.
24
+ *
25
+ * The rule:
26
+ * 1. `ß` → `ss` first, because it has no NFKD decomposition and would
27
+ * otherwise become a hyphen mid-word. The expansion is the same in every
28
+ * language that uses it.
29
+ * 2. NFKD, then drop combining marks, so `é` → `e` rather than a hyphen.
30
+ * 3. Lowercase, collapse every remaining run of non-alphanumerics to a
31
+ * single `-`, and trim leading and trailing hyphens.
32
+ *
33
+ * A string with no Latin letters or digits (`日本語`, `!!!`) yields `''`.
34
+ * Callers must decide what that means — omitting the element is usually better
35
+ * than emitting an empty `id`.
36
+ *
37
+ * @param {string} text - The string to slugify
38
+ * @returns {string} - URL-safe slug, or `''` if nothing usable remains
39
+ */
40
+ export function slugify(text) {
41
+ return String(text)
42
+ .replace(/ß/g, 'ss')
43
+ .normalize('NFKD')
44
+ .replace(/[\u0300-\u036f]/g, '')
45
+ .toLowerCase()
46
+ .replace(/[^a-z0-9]+/g, '-')
47
+ .replace(/^-+|-+$/g, '')
48
+ }
49
+
13
50
  /**
14
51
  * Validates if the current working directory is a valid Nera project
15
52
  *
@@ -46,6 +83,63 @@ export function validateNeraProject(expectedPackageName = 'dummy') {
46
83
  }
47
84
  }
48
85
 
86
+ /**
87
+ * Resolves the project's presentation directory for `views` or `assets`, the
88
+ * same way the generator does (core.js), so a plugin publishes where the build
89
+ * will actually look:
90
+ *
91
+ * 1. An explicit `folders.<key>` in config/app.yaml always wins.
92
+ * 2. Otherwise, if a local `theme/` folder exists, it is `theme/<key>` — the
93
+ * generator renders themed sites from `theme/views` and serves from
94
+ * `theme/assets`, and a plugin's files are the site's own override layer,
95
+ * so they belong there.
96
+ * 3. Otherwise the deprecated root `<key>/`, byte-identical to before the
97
+ * theme system existed.
98
+ *
99
+ * @param {string} cwd - Project root
100
+ * @param {'views'|'assets'} key - Which presentation folder to resolve
101
+ * @returns {string} - Absolute path to the resolved directory
102
+ */
103
+ function resolvePresentationDir(cwd, key) {
104
+ const appConfig = getConfig(path.resolve(cwd, 'config/app.yaml'))
105
+ const explicit = appConfig?.folders?.[key]
106
+
107
+ if (typeof explicit === 'string' && explicit.trim()) {
108
+ return path.resolve(cwd, explicit)
109
+ }
110
+
111
+ if (fs.existsSync(path.resolve(cwd, 'theme'))) {
112
+ return path.resolve(cwd, 'theme', key)
113
+ }
114
+
115
+ return path.resolve(cwd, key)
116
+ }
117
+
118
+ /**
119
+ * The project's views directory — `theme/views` on a themed site, the
120
+ * deprecated root `views` otherwise (or whatever `folders.views` in
121
+ * config/app.yaml points to). Published templates land under its `vendor/`.
122
+ *
123
+ * @param {string} [cwd] - Project root (defaults to process.cwd())
124
+ * @returns {string} - Absolute path to the views directory
125
+ */
126
+ export function resolveViewsDir(cwd = process.cwd()) {
127
+ return resolvePresentationDir(cwd, 'views')
128
+ }
129
+
130
+ /**
131
+ * The project's assets directory — `theme/assets` on a themed site, the
132
+ * deprecated root `assets` otherwise (or whatever `folders.assets` in
133
+ * config/app.yaml points to). Published support files (e.g. a client script)
134
+ * land under it.
135
+ *
136
+ * @param {string} [cwd] - Project root (defaults to process.cwd())
137
+ * @returns {string} - Absolute path to the assets directory
138
+ */
139
+ export function resolveAssetsDir(cwd = process.cwd()) {
140
+ return resolvePresentationDir(cwd, 'assets')
141
+ }
142
+
49
143
  /**
50
144
  * Publishes template files from a plugin to a Nera project
51
145
  * @param {Object} options - Configuration options
@@ -71,10 +165,11 @@ export function publishTemplates({
71
165
  return false
72
166
  }
73
167
 
74
- const destinationDir = path.resolve(
75
- process.cwd(),
76
- `views/vendor/${pluginName}/`
77
- )
168
+ // Resolve the views dir the same way the build does: `theme/views/vendor`
169
+ // on a themed site, root `views/vendor` otherwise. Publishing to root on a
170
+ // themed site put files where the layered resolver never looks, so the
171
+ // includes silently found nothing.
172
+ const destinationDir = path.join(resolveViewsDir(), 'vendor', pluginName)
78
173
 
79
174
  // Check if destination already exists. Overwriting by default would
80
175
  // discard the customizations that publishing exists to enable, so the
@@ -192,3 +287,62 @@ export function publishAllTemplates({
192
287
  return false
193
288
  }
194
289
  }
290
+
291
+ /**
292
+ * Publishes a single support file — a plugin's client script, say — into the
293
+ * project's assets folder, theme-aware and with the same skip-if-exists rule as
294
+ * publishTemplates. Plugins that ship a runtime asset alongside their templates
295
+ * (e.g. plugin-search, plugin-contact-form) should copy it through here so it
296
+ * lands next to the templates (`theme/assets` on a themed site) instead of a
297
+ * hand-rolled root `assets/` copy that a themed build never serves.
298
+ *
299
+ * @param {Object} options - Configuration options
300
+ * @param {string} options.sourceFile - Absolute path to the file to copy
301
+ * @param {string} options.targetPath - Destination relative to the assets root,
302
+ * e.g. `js/contact-form.js`
303
+ * @param {string} [options.expectedPackageName] - Override for testing purposes
304
+ * @param {boolean} [options.force] - Overwrite an existing file, discarding edits
305
+ * @returns {boolean} - True on success, including a deliberate skip
306
+ */
307
+ export function publishAsset({
308
+ sourceFile,
309
+ targetPath,
310
+ expectedPackageName,
311
+ force = false
312
+ }) {
313
+ if (!validateNeraProject(expectedPackageName)) {
314
+ console.error(
315
+ '❌ Please run this command from the root of your Nera project (where the plugin is installed).'
316
+ )
317
+ return false
318
+ }
319
+
320
+ if (!fs.existsSync(sourceFile)) {
321
+ console.error(`❌ Source asset not found: ${sourceFile}`)
322
+ return false
323
+ }
324
+
325
+ const destPath = path.join(resolveAssetsDir(), targetPath)
326
+ // Shown relative to the project root so the message reads the same whether
327
+ // the file went to `theme/assets/…` or the deprecated root `assets/…`.
328
+ const shownPath = path.relative(process.cwd(), destPath)
329
+
330
+ // Same rule as publishTemplates: never clobber a user's edited copy.
331
+ if (fs.existsSync(destPath) && !force) {
332
+ console.log(
333
+ `⚠️ ${shownPath} already exists — skipping.\n` +
334
+ ' Re-run with --force to overwrite (this will discard your edits).'
335
+ )
336
+ return true
337
+ }
338
+
339
+ try {
340
+ fs.mkdirSync(path.dirname(destPath), { recursive: true })
341
+ fs.copyFileSync(sourceFile, destPath)
342
+ console.log(`✅ Copied ${path.basename(sourceFile)} to ${shownPath}`)
343
+ return true
344
+ } catch (error) {
345
+ console.error(`❌ Failed to copy asset: ${error.message}`)
346
+ return false
347
+ }
348
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.3.1",
3
+ "version": "1.5.0",
4
4
  "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
5
5
  "main": "index.js",
6
6
  "type": "module",