@nera-static/plugin-utils 1.4.0 → 1.6.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 +24 -1
  2. package/index.js +140 -6
  3. package/package.json +4 -4
package/README.md CHANGED
@@ -5,6 +5,8 @@
5
5
 
6
6
  🛠 Utility helpers for developing plugins for the [Nera](https://github.com/seebaermichi/nera) static site generator.
7
7
 
8
+ 📖 **Documentation:** [nera.js.org](https://nera.js.org)
9
+
8
10
  ---
9
11
 
10
12
  ## 📦 Installation
@@ -89,7 +91,7 @@ if (validateNeraProject()) {
89
91
 
90
92
  Publishes specific template files from a plugin to a Nera project.
91
93
 
92
- 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.
94
+ 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.
93
95
 
94
96
  ```js
95
97
  import { publishTemplates } from '@nera-static/plugin-utils'
@@ -122,6 +124,27 @@ const result = publishAllTemplates({
122
124
 
123
125
  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.
124
126
 
127
+ #### `publishAsset(options): boolean`
128
+
129
+ 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.
130
+
131
+ ```js
132
+ import { publishAsset } from '@nera-static/plugin-utils'
133
+
134
+ const result = publishAsset({
135
+ sourceFile: path.resolve(__dirname, '../views/my-plugin.js'),
136
+ targetPath: 'js/my-plugin.js', // relative to the resolved assets root
137
+ expectedPackageName: 'dummy', // optional, for testing
138
+ force: false, // optional, overwrite an existing file
139
+ })
140
+ ```
141
+
142
+ Returns `false` outside a Nera project or when `sourceFile` is missing; a deliberate skip of an existing file returns `true`.
143
+
144
+ #### `resolveViewsDir(cwd?): string` / `resolveAssetsDir(cwd?): string`
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.
147
+
125
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.
126
149
 
127
150
  ### Template Publishing CLI Integration
package/index.js CHANGED
@@ -1,11 +1,28 @@
1
1
  import fs from 'fs'
2
2
  import path from 'path'
3
- import yaml from 'js-yaml'
3
+ // js-yaml 5 dropped the default export; `load` is a named export now.
4
+ import { load } from 'js-yaml'
5
+
6
+ // js-yaml 5 throws on a document with no content, where 4 returned undefined.
7
+ // A packaged config whose every key is commented out is the normal case here —
8
+ // that is how plugins ship their defaults — so it has to keep behaving like an
9
+ // absent config instead of crashing the build. Real syntax errors still throw.
10
+ function hasNoDocument(content) {
11
+ return content
12
+ .split('\n')
13
+ .every((line) => {
14
+ const trimmed = line.trim()
15
+ return trimmed === '' || trimmed.startsWith('#')
16
+ })
17
+ }
4
18
 
5
19
  export function getConfig(filePath) {
6
20
  if (fs.existsSync(filePath)) {
7
21
  const content = fs.readFileSync(filePath, 'utf-8')
8
- return yaml.load(content) || {}
22
+ if (hasNoDocument(content)) {
23
+ return {}
24
+ }
25
+ return load(content) || {}
9
26
  }
10
27
  return {}
11
28
  }
@@ -83,6 +100,63 @@ export function validateNeraProject(expectedPackageName = 'dummy') {
83
100
  }
84
101
  }
85
102
 
103
+ /**
104
+ * Resolves the project's presentation directory for `views` or `assets`, the
105
+ * same way the generator does (core.js), so a plugin publishes where the build
106
+ * will actually look:
107
+ *
108
+ * 1. An explicit `folders.<key>` in config/app.yaml always wins.
109
+ * 2. Otherwise, if a local `theme/` folder exists, it is `theme/<key>` — the
110
+ * generator renders themed sites from `theme/views` and serves from
111
+ * `theme/assets`, and a plugin's files are the site's own override layer,
112
+ * so they belong there.
113
+ * 3. Otherwise the deprecated root `<key>/`, byte-identical to before the
114
+ * theme system existed.
115
+ *
116
+ * @param {string} cwd - Project root
117
+ * @param {'views'|'assets'} key - Which presentation folder to resolve
118
+ * @returns {string} - Absolute path to the resolved directory
119
+ */
120
+ function resolvePresentationDir(cwd, key) {
121
+ const appConfig = getConfig(path.resolve(cwd, 'config/app.yaml'))
122
+ const explicit = appConfig?.folders?.[key]
123
+
124
+ if (typeof explicit === 'string' && explicit.trim()) {
125
+ return path.resolve(cwd, explicit)
126
+ }
127
+
128
+ if (fs.existsSync(path.resolve(cwd, 'theme'))) {
129
+ return path.resolve(cwd, 'theme', key)
130
+ }
131
+
132
+ return path.resolve(cwd, key)
133
+ }
134
+
135
+ /**
136
+ * The project's views directory — `theme/views` on a themed site, the
137
+ * deprecated root `views` otherwise (or whatever `folders.views` in
138
+ * config/app.yaml points to). Published templates land under its `vendor/`.
139
+ *
140
+ * @param {string} [cwd] - Project root (defaults to process.cwd())
141
+ * @returns {string} - Absolute path to the views directory
142
+ */
143
+ export function resolveViewsDir(cwd = process.cwd()) {
144
+ return resolvePresentationDir(cwd, 'views')
145
+ }
146
+
147
+ /**
148
+ * The project's assets directory — `theme/assets` on a themed site, the
149
+ * deprecated root `assets` otherwise (or whatever `folders.assets` in
150
+ * config/app.yaml points to). Published support files (e.g. a client script)
151
+ * land under it.
152
+ *
153
+ * @param {string} [cwd] - Project root (defaults to process.cwd())
154
+ * @returns {string} - Absolute path to the assets directory
155
+ */
156
+ export function resolveAssetsDir(cwd = process.cwd()) {
157
+ return resolvePresentationDir(cwd, 'assets')
158
+ }
159
+
86
160
  /**
87
161
  * Publishes template files from a plugin to a Nera project
88
162
  * @param {Object} options - Configuration options
@@ -108,10 +182,11 @@ export function publishTemplates({
108
182
  return false
109
183
  }
110
184
 
111
- const destinationDir = path.resolve(
112
- process.cwd(),
113
- `views/vendor/${pluginName}/`
114
- )
185
+ // Resolve the views dir the same way the build does: `theme/views/vendor`
186
+ // on a themed site, root `views/vendor` otherwise. Publishing to root on a
187
+ // themed site put files where the layered resolver never looks, so the
188
+ // includes silently found nothing.
189
+ const destinationDir = path.join(resolveViewsDir(), 'vendor', pluginName)
115
190
 
116
191
  // Check if destination already exists. Overwriting by default would
117
192
  // discard the customizations that publishing exists to enable, so the
@@ -229,3 +304,62 @@ export function publishAllTemplates({
229
304
  return false
230
305
  }
231
306
  }
307
+
308
+ /**
309
+ * Publishes a single support file — a plugin's client script, say — into the
310
+ * project's assets folder, theme-aware and with the same skip-if-exists rule as
311
+ * publishTemplates. Plugins that ship a runtime asset alongside their templates
312
+ * (e.g. plugin-search, plugin-contact-form) should copy it through here so it
313
+ * lands next to the templates (`theme/assets` on a themed site) instead of a
314
+ * hand-rolled root `assets/` copy that a themed build never serves.
315
+ *
316
+ * @param {Object} options - Configuration options
317
+ * @param {string} options.sourceFile - Absolute path to the file to copy
318
+ * @param {string} options.targetPath - Destination relative to the assets root,
319
+ * e.g. `js/contact-form.js`
320
+ * @param {string} [options.expectedPackageName] - Override for testing purposes
321
+ * @param {boolean} [options.force] - Overwrite an existing file, discarding edits
322
+ * @returns {boolean} - True on success, including a deliberate skip
323
+ */
324
+ export function publishAsset({
325
+ sourceFile,
326
+ targetPath,
327
+ expectedPackageName,
328
+ force = false
329
+ }) {
330
+ if (!validateNeraProject(expectedPackageName)) {
331
+ console.error(
332
+ '❌ Please run this command from the root of your Nera project (where the plugin is installed).'
333
+ )
334
+ return false
335
+ }
336
+
337
+ if (!fs.existsSync(sourceFile)) {
338
+ console.error(`❌ Source asset not found: ${sourceFile}`)
339
+ return false
340
+ }
341
+
342
+ const destPath = path.join(resolveAssetsDir(), targetPath)
343
+ // Shown relative to the project root so the message reads the same whether
344
+ // the file went to `theme/assets/…` or the deprecated root `assets/…`.
345
+ const shownPath = path.relative(process.cwd(), destPath)
346
+
347
+ // Same rule as publishTemplates: never clobber a user's edited copy.
348
+ if (fs.existsSync(destPath) && !force) {
349
+ console.log(
350
+ `⚠️ ${shownPath} already exists — skipping.\n` +
351
+ ' Re-run with --force to overwrite (this will discard your edits).'
352
+ )
353
+ return true
354
+ }
355
+
356
+ try {
357
+ fs.mkdirSync(path.dirname(destPath), { recursive: true })
358
+ fs.copyFileSync(sourceFile, destPath)
359
+ console.log(`✅ Copied ${path.basename(sourceFile)} to ${shownPath}`)
360
+ return true
361
+ } catch (error) {
362
+ console.error(`❌ Failed to copy asset: ${error.message}`)
363
+ return false
364
+ }
365
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -26,12 +26,12 @@
26
26
  "access": "public"
27
27
  },
28
28
  "dependencies": {
29
- "js-yaml": "^4.1.0"
29
+ "js-yaml": "^5.2.2"
30
30
  },
31
31
  "devDependencies": {
32
- "eslint": "^9.17.0",
32
+ "eslint": "^10.8.0",
33
33
  "husky": "^9.1.7",
34
- "vitest": "^3.2.4"
34
+ "vitest": "^4.1.10"
35
35
  },
36
36
  "scripts": {
37
37
  "test": "vitest",