@nera-static/plugin-utils 1.0.5 → 1.2.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 +113 -11
  2. package/index.js +189 -5
  3. package/package.json +10 -4
package/README.md CHANGED
@@ -14,35 +14,137 @@ npm install @nera-static/plugin-utils
14
14
 
15
15
  ## 📚 Features
16
16
 
17
- Currently includes:
17
+ ### Configuration Loading
18
18
 
19
- ### `getConfig(filePath: string): object`
19
+ #### `getConfig(filePath: string): object`
20
20
 
21
21
  Reads and parses a YAML config file, returning its contents as a JavaScript object.
22
22
 
23
- #### Example usage:
24
-
25
23
  ```js
26
- import { getConfig } from '@nera/plugin-utils'
24
+ import { getConfig } from '@nera-static/plugin-utils'
27
25
 
28
26
  const config = getConfig('./path/to/config.yaml')
29
27
  console.log(config.title)
30
28
  ```
31
29
 
32
- Returns `{}` if the file does not exist or is empty.
30
+ ### Template Publishing
31
+
32
+ #### `validateNeraProject(expectedPackageName?: string): boolean`
33
+
34
+ Validates if the current working directory is a valid Nera project.
35
+
36
+ A directory qualifies if it *looks* like a Nera project — it contains both `config/app.yaml` and `pages/` — or if its `package.json` name matches `expectedPackageName` or starts with `nera`. The shape check means a project can be named anything.
37
+
38
+ ```js
39
+ import { validateNeraProject } from '@nera-static/plugin-utils'
40
+
41
+ if (validateNeraProject()) {
42
+ console.log('Valid Nera project!')
43
+ }
44
+ ```
45
+
46
+ #### `publishTemplates(options): boolean`
47
+
48
+ Publishes specific template files from a plugin to a Nera project.
49
+
50
+ 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.
51
+
52
+ ```js
53
+ import { publishTemplates } from '@nera-static/plugin-utils'
54
+
55
+ const result = publishTemplates({
56
+ pluginName: 'plugin-my-awesome-plugin',
57
+ sourceDir: path.resolve(__dirname, '../views/'),
58
+ templateFiles: ['template.pug', 'another-template.pug'], // or single file as string
59
+ expectedPackageName: 'dummy', // optional, for testing
60
+ force: false, // optional, re-publish over an existing destination
61
+ })
62
+ ```
63
+
64
+ Returns `false` if any listed template is missing from `sourceDir`. Sources are all verified before anything is copied, so a failure never leaves a partially published destination.
65
+
66
+ #### `publishAllTemplates(options): boolean`
67
+
68
+ Publishes all `.pug` template files from a plugin's views directory to a Nera project, **including those in subdirectories**, preserving their structure. A template that does `include partials/nav` therefore ships together with the partial it depends on.
69
+
70
+ ```js
71
+ import { publishAllTemplates } from '@nera-static/plugin-utils'
72
+
73
+ const result = publishAllTemplates({
74
+ pluginName: 'plugin-my-awesome-plugin',
75
+ sourceDir: path.resolve(__dirname, '../views/'),
76
+ expectedPackageName: 'dummy', // optional, for testing
77
+ force: false, // optional, re-publish over an existing destination
78
+ })
79
+ ```
80
+
81
+ ### Template Publishing CLI Integration
82
+
83
+ These functions are designed to be used in `bin/publish-template.js` scripts that can be executed via npm scripts:
84
+
85
+ ```js
86
+ #!/usr/bin/env node
87
+
88
+ import path from 'path'
89
+ import { fileURLToPath } from 'url'
90
+ import { publishAllTemplates } from '@nera-static/plugin-utils'
91
+
92
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
93
+ const pluginName = 'plugin-my-awesome-plugin'
94
+ const sourceDir = path.resolve(__dirname, '../views/')
95
+
96
+ const result = publishAllTemplates({
97
+ pluginName,
98
+ sourceDir,
99
+ expectedPackageName: 'dummy', // for test-only override
100
+ })
101
+
102
+ process.exit(result ? 0 : 1)
103
+ ```
33
104
 
34
105
  ---
35
106
 
36
- ## 🧱 Use Case
107
+ ## 🧱 Use Cases
108
+
109
+ This package is intended for use inside Nera plugins to:
37
110
 
38
- This package is intended for use inside Nera plugins to simplify configuration loading from YAML files.
111
+ 1. **Load Configuration**: Simplify loading YAML configuration files
112
+ 2. **Publish Templates**: Standardize template publishing across plugins
113
+ 3. **Validate Projects**: Ensure commands run in valid Nera projects
39
114
 
40
- Example in a plugin:
115
+ ### Example Plugin Structure
41
116
 
42
117
  ```js
43
- import { getConfig } from '@nera/plugin-utils'
118
+ // index.js - Main plugin file
119
+ import { getConfig } from '@nera-static/plugin-utils'
120
+
121
+ export function getAppData(app) {
122
+ const config = getConfig(`${__dirname}/config/my-plugin.yaml`)
123
+
124
+ return {
125
+ myPlugin: {
126
+ // ... plugin logic using config
127
+ },
128
+ }
129
+ }
130
+ ```
131
+
132
+ ```js
133
+ // bin/publish-template.js - Template publishing script
134
+ #!/usr/bin/env node
135
+
136
+ import path from 'path'
137
+ import { fileURLToPath } from 'url'
138
+ import { publishAllTemplates } from '@nera-static/plugin-utils'
139
+
140
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
141
+
142
+ const result = publishAllTemplates({
143
+ pluginName: 'plugin-my-awesome-plugin',
144
+ sourceDir: path.resolve(__dirname, '../views/')
145
+ })
44
146
 
45
- const config = getConfig(`${__dirname}/config/navigation.yaml`)
147
+ process.exit(result ? 0 : 1)
46
148
  ```
47
149
 
48
150
  ---
package/index.js CHANGED
@@ -1,10 +1,194 @@
1
1
  import fs from 'fs'
2
+ import path from 'path'
2
3
  import yaml from 'js-yaml'
3
4
 
4
5
  export function getConfig(filePath) {
5
- if (fs.existsSync(filePath)) {
6
- const content = fs.readFileSync(filePath, 'utf-8')
7
- return yaml.load(content) || {}
8
- }
9
- return {}
6
+ if (fs.existsSync(filePath)) {
7
+ const content = fs.readFileSync(filePath, 'utf-8')
8
+ return yaml.load(content) || {}
9
+ }
10
+ return {}
11
+ }
12
+
13
+ /**
14
+ * Validates if the current working directory is a valid Nera project
15
+ *
16
+ * A directory qualifies if it *looks* like a Nera project — it contains both
17
+ * `config/app.yaml` and `pages/` — or if its package name matches. The shape
18
+ * check is the primary signal; the name check is retained so that projects
19
+ * scaffolded before this release, and the `expectedPackageName` test
20
+ * override, keep working.
21
+ *
22
+ * @param {string} [expectedPackageName] - Override for testing purposes (defaults to 'dummy')
23
+ * @returns {boolean} - True if valid Nera project
24
+ */
25
+ export function validateNeraProject(expectedPackageName = 'dummy') {
26
+ const packageJsonPath = path.resolve(process.cwd(), 'package.json')
27
+
28
+ if (!fs.existsSync(packageJsonPath)) {
29
+ return false
30
+ }
31
+
32
+ const looksLikeNeraProject =
33
+ fs.existsSync(path.resolve(process.cwd(), 'config/app.yaml')) &&
34
+ fs.existsSync(path.resolve(process.cwd(), 'pages'))
35
+
36
+ try {
37
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
38
+ return (
39
+ looksLikeNeraProject ||
40
+ pkg.name === expectedPackageName ||
41
+ pkg.name.startsWith('nera')
42
+ )
43
+ } catch (e) {
44
+ console.error(`❌ Error reading package.json: ${e.message}`)
45
+ return false
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Publishes template files from a plugin to a Nera project
51
+ * @param {Object} options - Configuration options
52
+ * @param {string} options.pluginName - Name of the plugin (e.g., 'plugin-popular-content')
53
+ * @param {string} options.sourceDir - Absolute path to the plugin's views directory
54
+ * @param {string|string[]} options.templateFiles - Single file or array of template files to copy
55
+ * @param {string} [options.expectedPackageName] - Override for testing purposes
56
+ * @param {boolean} [options.force] - Re-publish over an existing destination, discarding local edits
57
+ * @returns {boolean} - True if templates were published successfully
58
+ */
59
+ export function publishTemplates({
60
+ pluginName,
61
+ sourceDir,
62
+ templateFiles,
63
+ expectedPackageName,
64
+ force = false
65
+ }) {
66
+ // Validate Nera project
67
+ if (!validateNeraProject(expectedPackageName)) {
68
+ console.error(
69
+ '❌ Please run this command from the root of your Nera project (where the plugin is installed).'
70
+ )
71
+ return false
72
+ }
73
+
74
+ const destinationDir = path.resolve(
75
+ process.cwd(),
76
+ `views/vendor/${pluginName}/`
77
+ )
78
+
79
+ // Check if destination already exists. Overwriting by default would
80
+ // discard the customizations that publishing exists to enable, so the
81
+ // skip stays and `force` is opt-in.
82
+ if (fs.existsSync(destinationDir) && !force) {
83
+ console.log(
84
+ `⚠️ Templates already exist at ${destinationDir}. Skipping.\n` +
85
+ ' Re-run with --force to overwrite (this will discard your edits).'
86
+ )
87
+ return true
88
+ }
89
+
90
+ // Ensure templateFiles is an array
91
+ const filesToCopy = Array.isArray(templateFiles)
92
+ ? templateFiles
93
+ : [templateFiles]
94
+
95
+ // Verify every source exists before creating anything. Failing mid-copy
96
+ // would leave a partial destination directory, which the skip above would
97
+ // then treat as already published on the next run.
98
+ const missing = filesToCopy.filter(
99
+ (templateFile) => !fs.existsSync(path.resolve(sourceDir, templateFile))
100
+ )
101
+
102
+ if (missing.length > 0) {
103
+ for (const templateFile of missing) {
104
+ console.error(
105
+ `❌ Source template not found: ${path.resolve(sourceDir, templateFile)}`
106
+ )
107
+ }
108
+ return false
109
+ }
110
+
111
+ try {
112
+ // Create destination directory
113
+ fs.mkdirSync(destinationDir, { recursive: true })
114
+
115
+ // Copy each template file
116
+ for (const templateFile of filesToCopy) {
117
+ const sourcePath = path.resolve(sourceDir, templateFile)
118
+ const destPath = path.resolve(destinationDir, templateFile)
119
+
120
+ // Create subdirectories if needed
121
+ fs.mkdirSync(path.dirname(destPath), { recursive: true })
122
+
123
+ fs.copyFileSync(sourcePath, destPath)
124
+ console.log(`✅ Copied ${templateFile} to ${destPath}`)
125
+ }
126
+
127
+ console.log(`✅ Templates copied to: ${destinationDir}`)
128
+ return true
129
+ } catch (error) {
130
+ console.error(`❌ Failed to copy templates: ${error.message}`)
131
+ return false
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Recursively collects .pug files under a directory, as paths relative to it.
137
+ * @param {string} dir - Directory to walk
138
+ * @param {string} [relativeTo] - Root the returned paths are relative to
139
+ * @returns {string[]} - Relative paths of every .pug file found
140
+ */
141
+ function collectPugFiles(dir, relativeTo = dir) {
142
+ return fs
143
+ .readdirSync(dir, { withFileTypes: true })
144
+ .flatMap((entry) => {
145
+ const entryPath = path.resolve(dir, entry.name)
146
+
147
+ if (entry.isDirectory()) {
148
+ return collectPugFiles(entryPath, relativeTo)
149
+ }
150
+
151
+ return entry.name.endsWith('.pug')
152
+ ? [path.relative(relativeTo, entryPath)]
153
+ : []
154
+ })
155
+ }
156
+
157
+ /**
158
+ * Publishes all .pug template files from a plugin's views directory,
159
+ * including those in subdirectories, preserving their structure.
160
+ * @param {Object} options - Configuration options
161
+ * @param {string} options.pluginName - Name of the plugin (e.g., 'plugin-popular-content')
162
+ * @param {string} options.sourceDir - Absolute path to the plugin's views directory
163
+ * @param {string} [options.expectedPackageName] - Override for testing purposes
164
+ * @param {boolean} [options.force] - Re-publish over an existing destination, discarding local edits
165
+ * @returns {boolean} - True if templates were published successfully
166
+ */
167
+ export function publishAllTemplates({
168
+ pluginName,
169
+ sourceDir,
170
+ expectedPackageName,
171
+ force = false
172
+ }) {
173
+ try {
174
+ // Walk the whole tree: templates that `include partials/...` are
175
+ // useless without the nested files they depend on.
176
+ const pugFiles = collectPugFiles(sourceDir)
177
+
178
+ if (pugFiles.length === 0) {
179
+ console.log('⚠️ No .pug template files found to publish.')
180
+ return true
181
+ }
182
+
183
+ return publishTemplates({
184
+ pluginName,
185
+ sourceDir,
186
+ templateFiles: pugFiles,
187
+ expectedPackageName,
188
+ force
189
+ })
190
+ } catch (error) {
191
+ console.error(`❌ Error reading source directory: ${error.message}`)
192
+ return false
193
+ }
10
194
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.0.5",
4
- "description": "Shared utility functions for Nera plugins (like config loading)",
3
+ "version": "1.2.0",
4
+ "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "repository": {
@@ -17,7 +17,8 @@
17
17
  "static-site-generator",
18
18
  "plugin",
19
19
  "utils",
20
- "yaml"
20
+ "yaml",
21
+ "templates"
21
22
  ],
22
23
  "author": "Michael Becker",
23
24
  "license": "MIT",
@@ -28,10 +29,15 @@
28
29
  "js-yaml": "^4.1.0"
29
30
  },
30
31
  "devDependencies": {
32
+ "eslint": "^9.17.0",
33
+ "husky": "^9.1.7",
31
34
  "vitest": "^3.2.4"
32
35
  },
33
36
  "scripts": {
34
- "test": "vitest"
37
+ "test": "vitest",
38
+ "lint": "eslint .",
39
+ "lint:fix": "eslint . --fix",
40
+ "prepare": "git config core.hooksPath .husky || true"
35
41
  },
36
42
  "exports": {
37
43
  ".": "./index.js"