@nera-static/core 4.9.1
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/LICENSE +21 -0
- package/README.md +231 -0
- package/index.js +3 -0
- package/package.json +83 -0
- package/src/core.js +227 -0
- package/src/index.js +101 -0
- package/src/render.js +299 -0
- package/src/resolve.js +59 -0
- package/src/setup-plugins.js +237 -0
- package/src/site-model.js +64 -0
- package/src/theme.js +268 -0
- package/src/watch-assets.js +29 -0
package/src/render.js
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import fs from 'fs/promises'
|
|
2
|
+
import fssync from 'fs'
|
|
3
|
+
import path from 'path'
|
|
4
|
+
import cpy from 'cpy'
|
|
5
|
+
import pug from 'pug'
|
|
6
|
+
import pretty from 'pretty'
|
|
7
|
+
import { rimraf } from 'rimraf'
|
|
8
|
+
import dotenv from 'dotenv'
|
|
9
|
+
import { makeLayeredResolver, resolveEntry } from './resolve.js'
|
|
10
|
+
|
|
11
|
+
dotenv.config()
|
|
12
|
+
|
|
13
|
+
const SUCCESS_COLOR = '\x1b[32m%s\x1b[0m'
|
|
14
|
+
|
|
15
|
+
// --- Base-path URL rewriting (config `base_path` → `app.basePath`) ------------
|
|
16
|
+
//
|
|
17
|
+
// A site served from a subdirectory (e.g. GitHub *project* Pages under
|
|
18
|
+
// `/<repo>/`) needs every root-absolute URL — links and assets alike — prefixed
|
|
19
|
+
// with that path, or they resolve against the domain root and 404. The physical
|
|
20
|
+
// output layout is unchanged (files still land at the artifact root); only the
|
|
21
|
+
// URLs *inside* the output are prefixed. All of this is a no-op when `basePath`
|
|
22
|
+
// is '' (a root-served site), so a site without `base_path` is byte-identical.
|
|
23
|
+
//
|
|
24
|
+
// Every prefixer is idempotent: a value already under `basePath` is left alone,
|
|
25
|
+
// so build-time rewriting composes safely with basePath-aware `meta.href` and
|
|
26
|
+
// the `url()` template helper (double-prefixing can't happen).
|
|
27
|
+
|
|
28
|
+
// Should this root-absolute value be prefixed? Skip protocol-relative (`//cdn`),
|
|
29
|
+
// non-absolute, and already-prefixed values.
|
|
30
|
+
const shouldPrefix = (val, basePath) =>
|
|
31
|
+
typeof val === 'string' &&
|
|
32
|
+
val.startsWith('/') &&
|
|
33
|
+
!val.startsWith('//') &&
|
|
34
|
+
val !== basePath &&
|
|
35
|
+
!val.startsWith(`${basePath}/`)
|
|
36
|
+
|
|
37
|
+
const prefixUrl = (val, basePath) =>
|
|
38
|
+
shouldPrefix(val, basePath) ? `${basePath}${val}` : val
|
|
39
|
+
|
|
40
|
+
// Rewrite the URL-bearing attributes in a rendered HTML string. Covers the
|
|
41
|
+
// attributes Nera and its plugins actually emit; `srcset` is handled specially
|
|
42
|
+
// because it holds a comma-separated list of `url descriptor` pairs.
|
|
43
|
+
export const rewriteHtmlUrls = (html, basePath) => {
|
|
44
|
+
if (!basePath) return html
|
|
45
|
+
|
|
46
|
+
return html
|
|
47
|
+
.replace(
|
|
48
|
+
/\b(href|src|poster|data-search-index)=("|')(\/[^"']*)\2/gi,
|
|
49
|
+
(m, attr, quote, val) =>
|
|
50
|
+
`${attr}=${quote}${prefixUrl(val, basePath)}${quote}`
|
|
51
|
+
)
|
|
52
|
+
.replace(/\bsrcset=("|')([^"']*)\1/gi, (m, quote, list) => {
|
|
53
|
+
const rewritten = list
|
|
54
|
+
.split(',')
|
|
55
|
+
.map((part) => {
|
|
56
|
+
const seg = part.trim()
|
|
57
|
+
if (!seg) return part
|
|
58
|
+
const [url, ...descriptor] = seg.split(/\s+/)
|
|
59
|
+
return [prefixUrl(url, basePath), ...descriptor].join(' ')
|
|
60
|
+
})
|
|
61
|
+
.join(', ')
|
|
62
|
+
return `srcset=${quote}${rewritten}${quote}`
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Rewrite `url(/…)` references inside a CSS string (fonts, background images).
|
|
67
|
+
const rewriteCssUrls = (css, basePath) =>
|
|
68
|
+
css.replace(
|
|
69
|
+
/url\(\s*(['"]?)(\/[^)'"]*)\1\s*\)/gi,
|
|
70
|
+
(m, quote, val) =>
|
|
71
|
+
`url(${quote}${prefixUrl(val, basePath)}${quote})`
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
// Rewrite root-absolute URLs held under `href`/`url` keys in a JSON asset —
|
|
75
|
+
// chiefly the search index the search plugin builds from `meta.href`, whose
|
|
76
|
+
// per-result links must resolve under the subpath. Done as a format-preserving
|
|
77
|
+
// regex on the key/value pair (not a parse+reserialize) so it stays agnostic to
|
|
78
|
+
// the emitting plugin's schema and never rewrites unrelated strings (a `content`
|
|
79
|
+
// field mentioning a path, say) — only values of an `href`/`url` key.
|
|
80
|
+
const rewriteJsonUrls = (json, basePath) =>
|
|
81
|
+
json.replace(
|
|
82
|
+
/("(?:href|url)"\s*:\s*")(\/[^"]*)(")/gi,
|
|
83
|
+
(m, pre, val, post) => `${pre}${prefixUrl(val, basePath)}${post}`
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
// Rewrite a web app manifest's root-absolute URL fields. Parsed as JSON so we
|
|
87
|
+
// only touch known URL keys — never arbitrary strings that happen to start
|
|
88
|
+
// with `/`. Returns null (caller keeps the original) if it does not parse.
|
|
89
|
+
const rewriteManifestUrls = (json, basePath) => {
|
|
90
|
+
let data
|
|
91
|
+
try {
|
|
92
|
+
data = JSON.parse(json)
|
|
93
|
+
} catch {
|
|
94
|
+
return null
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const pfx = (v) => prefixUrl(v, basePath)
|
|
98
|
+
for (const key of ['start_url', 'scope', 'id']) {
|
|
99
|
+
if (typeof data[key] === 'string') data[key] = pfx(data[key])
|
|
100
|
+
}
|
|
101
|
+
for (const key of ['icons', 'screenshots']) {
|
|
102
|
+
if (Array.isArray(data[key])) {
|
|
103
|
+
data[key].forEach((item) => {
|
|
104
|
+
if (item && typeof item.src === 'string') item.src = pfx(item.src)
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (Array.isArray(data.shortcuts)) {
|
|
109
|
+
data.shortcuts.forEach((s) => {
|
|
110
|
+
if (s && typeof s.url === 'string') s.url = pfx(s.url)
|
|
111
|
+
if (Array.isArray(s.icons)) {
|
|
112
|
+
s.icons.forEach((it) => {
|
|
113
|
+
if (it && typeof it.src === 'string') it.src = pfx(it.src)
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
return JSON.stringify(data, null, 4)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Second pass over the built `public/` tree: rewrite root-absolute URLs inside
|
|
122
|
+
// copied assets that the HTML rewrite can't reach — CSS `url(/…)` and the web
|
|
123
|
+
// app manifest. Runs after both asset copies, so it also covers theme assets.
|
|
124
|
+
// No-op without a basePath.
|
|
125
|
+
export const rewriteAssetUrls = async (publicFolder, basePath) => {
|
|
126
|
+
if (!basePath || !fssync.existsSync(publicFolder)) return
|
|
127
|
+
|
|
128
|
+
const walk = async (dir) => {
|
|
129
|
+
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
|
|
130
|
+
const full = path.join(dir, entry.name)
|
|
131
|
+
if (entry.isDirectory()) {
|
|
132
|
+
await walk(full)
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
const lower = entry.name.toLowerCase()
|
|
136
|
+
if (lower.endsWith('.css')) {
|
|
137
|
+
const css = await fs.readFile(full, 'utf-8')
|
|
138
|
+
const out = rewriteCssUrls(css, basePath)
|
|
139
|
+
if (out !== css) await fs.writeFile(full, out, 'utf-8')
|
|
140
|
+
} else if (lower.endsWith('.webmanifest')) {
|
|
141
|
+
const json = await fs.readFile(full, 'utf-8')
|
|
142
|
+
const out = rewriteManifestUrls(json, basePath)
|
|
143
|
+
if (out !== null && out !== json) {
|
|
144
|
+
await fs.writeFile(full, out, 'utf-8')
|
|
145
|
+
}
|
|
146
|
+
} else if (lower.endsWith('.json')) {
|
|
147
|
+
const json = await fs.readFile(full, 'utf-8')
|
|
148
|
+
const out = rewriteJsonUrls(json, basePath)
|
|
149
|
+
if (out !== json) await fs.writeFile(full, out, 'utf-8')
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
await walk(publicFolder)
|
|
154
|
+
}
|
|
155
|
+
// -----------------------------------------------------------------------------
|
|
156
|
+
|
|
157
|
+
const getIgnoredFiles = (basePath) => {
|
|
158
|
+
const ignorePath = path.join(basePath, '.neraignore')
|
|
159
|
+
|
|
160
|
+
if (fssync.existsSync(ignorePath)) {
|
|
161
|
+
return fssync
|
|
162
|
+
.readFileSync(ignorePath, 'utf8')
|
|
163
|
+
.split('\n')
|
|
164
|
+
.map((line) => line.trim())
|
|
165
|
+
.filter((line) => line !== '')
|
|
166
|
+
}
|
|
167
|
+
return []
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function ignoreFiles(ignoreList, filePath, sourceRoot) {
|
|
171
|
+
const relativePath = path.relative(sourceRoot, filePath).replace(/\\/g, '/')
|
|
172
|
+
|
|
173
|
+
return !ignoreList.some(
|
|
174
|
+
(pattern) =>
|
|
175
|
+
relativePath === pattern || relativePath.startsWith(`${pattern}/`)
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// `ignoreBase` is the directory to read `.neraignore` from:
|
|
180
|
+
// - omitted → the source's parent (back-compat with the pre-theme layout,
|
|
181
|
+
// where `assets/` sat at the site root so its parent *was* the root)
|
|
182
|
+
// - a path → read `.neraignore` there (pass the site root so a site's ignore
|
|
183
|
+
// list keeps filtering its assets after they move under `theme/`, §2d)
|
|
184
|
+
// - null → skip ignore entirely, as the theme pass does: a theme package's
|
|
185
|
+
// payload is author-controlled (`files:`), so nobody's `.neraignore` filters it
|
|
186
|
+
export const copyFolder = async (sourceFolder, targetFolder, ignoreBase) => {
|
|
187
|
+
if (fssync.existsSync(sourceFolder)) {
|
|
188
|
+
const base =
|
|
189
|
+
ignoreBase === undefined ? path.dirname(sourceFolder) : ignoreBase
|
|
190
|
+
const ignore = base === null ? [] : getIgnoredFiles(base)
|
|
191
|
+
|
|
192
|
+
try {
|
|
193
|
+
await cpy([`${sourceFolder}/**/*`], targetFolder, {
|
|
194
|
+
parents: true,
|
|
195
|
+
filter: (file) => ignoreFiles(ignore, file.path, sourceFolder),
|
|
196
|
+
})
|
|
197
|
+
console.log(SUCCESS_COLOR, 'Assets copied')
|
|
198
|
+
} catch (err) {
|
|
199
|
+
console.error('Copy failed:', err)
|
|
200
|
+
}
|
|
201
|
+
} else {
|
|
202
|
+
console.log(SUCCESS_COLOR, 'No Assets found')
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// The layered view resolver (`makeLayeredResolver`/`resolveEntry`) now lives in
|
|
207
|
+
// `./resolve.js` so `@nera-static/validate` can reuse the exact same logic; it
|
|
208
|
+
// is imported at the top of this file.
|
|
209
|
+
|
|
210
|
+
export const createHtmlFiles = async (
|
|
211
|
+
data,
|
|
212
|
+
viewsFolder,
|
|
213
|
+
publicFolder,
|
|
214
|
+
theme = null
|
|
215
|
+
) => {
|
|
216
|
+
if (fssync.existsSync(viewsFolder)) {
|
|
217
|
+
// No theme → single root, no resolve hook: byte-identical to before.
|
|
218
|
+
const roots = theme ? [viewsFolder, theme.viewsRoot] : [viewsFolder]
|
|
219
|
+
const resolver = theme ? makeLayeredResolver(roots) : null
|
|
220
|
+
|
|
221
|
+
// Compile options are constant across the page loop — hoist them out.
|
|
222
|
+
const compileOptions = resolver
|
|
223
|
+
? { basedir: viewsFolder, plugins: [{ resolve: resolver }] }
|
|
224
|
+
: { basedir: viewsFolder }
|
|
225
|
+
|
|
226
|
+
// Compile each distinct layout once per build, then reuse the template
|
|
227
|
+
// function for every page that uses it (ROADMAP-themes.md §6). This loop
|
|
228
|
+
// previously re-ran pug.compileFile per page, recompiling the same tree
|
|
229
|
+
// dozens of times — the dominant build cost (measured ~70× on 69 pages,
|
|
230
|
+
// ~500× on 500, since a site's pages share a handful of layouts). Keyed
|
|
231
|
+
// on the resolved entry path, so different layouts stay separate and,
|
|
232
|
+
// under a theme, a layout resolved from the theme caches independently of
|
|
233
|
+
// one resolved from the site. Scoped to this call — a fresh Map per
|
|
234
|
+
// build, no process-global pug.cache to leak between run()s or tests.
|
|
235
|
+
const compiled = new Map()
|
|
236
|
+
|
|
237
|
+
// The site's URL prefix for subdirectory deploys ('' when root-served).
|
|
238
|
+
// Exposed to templates as `url()` so authors can prefix a hardcoded path
|
|
239
|
+
// explicitly (`link(href=url('/css/main.css'))`); the post-render rewrite
|
|
240
|
+
// below also catches paths that weren't wrapped, so `url()` is optional.
|
|
241
|
+
const basePath = data.app?.basePath || ''
|
|
242
|
+
data.url = (p) => prefixUrl(p, basePath)
|
|
243
|
+
|
|
244
|
+
for (const pageData of data.pagesData) {
|
|
245
|
+
if (pageData.meta.layout) {
|
|
246
|
+
data.t = (key) =>
|
|
247
|
+
data.app.translations
|
|
248
|
+
? data.app.translations[
|
|
249
|
+
pageData.meta.lang || data.app.lang
|
|
250
|
+
]?.[key] || key
|
|
251
|
+
: key
|
|
252
|
+
|
|
253
|
+
let html = pageData.content
|
|
254
|
+
|
|
255
|
+
const entry = resolver
|
|
256
|
+
? resolveEntry(pageData.meta.layout, roots)
|
|
257
|
+
: `${viewsFolder}/${pageData.meta.layout}`
|
|
258
|
+
|
|
259
|
+
let fn = compiled.get(entry)
|
|
260
|
+
if (!fn) {
|
|
261
|
+
fn = pug.compileFile(entry, compileOptions)
|
|
262
|
+
compiled.set(entry, fn)
|
|
263
|
+
}
|
|
264
|
+
html = fn({ ...data, ...pageData })
|
|
265
|
+
|
|
266
|
+
// Prefix root-absolute URLs in the rendered page for a
|
|
267
|
+
// subdirectory deploy (no-op when basePath is '').
|
|
268
|
+
html = rewriteHtmlUrls(html, basePath)
|
|
269
|
+
|
|
270
|
+
const htmlPath = path.join(
|
|
271
|
+
publicFolder,
|
|
272
|
+
pageData.meta.dirname.replace(/^\/+/, ''),
|
|
273
|
+
`${pageData.meta.filename}`
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
await fs.mkdir(path.dirname(htmlPath), { recursive: true })
|
|
277
|
+
await fs.writeFile(htmlPath, pretty(html), 'utf-8')
|
|
278
|
+
|
|
279
|
+
console.log(
|
|
280
|
+
SUCCESS_COLOR,
|
|
281
|
+
`HTML created: ${pageData.meta.dirname}`
|
|
282
|
+
)
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
console.error('Views folder not found')
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export const deleteFolder = async (folder) => {
|
|
291
|
+
if (fssync.existsSync(folder)) {
|
|
292
|
+
try {
|
|
293
|
+
await rimraf(folder)
|
|
294
|
+
console.log(SUCCESS_COLOR, 'Public folder removed')
|
|
295
|
+
} catch (error) {
|
|
296
|
+
console.error(error)
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
package/src/resolve.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fssync from 'fs'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
|
|
4
|
+
// Layered view resolution — the single source of truth for how Nera locates a
|
|
5
|
+
// layout and its `include`/`extends` targets across a site's own presentation
|
|
6
|
+
// and an optional theme package (ROADMAP-themes.md §1b).
|
|
7
|
+
//
|
|
8
|
+
// Extracted from render.js so the exact same logic can be reused outside the
|
|
9
|
+
// render loop — chiefly `@nera-static/validate`, which must decide "does this
|
|
10
|
+
// include resolve?" identically to how the build will. Do not fork this: a
|
|
11
|
+
// second copy of the algorithm is the drift `@nera-static/validate` exists to
|
|
12
|
+
// avoid.
|
|
13
|
+
|
|
14
|
+
// Pug's own path resolution, replicated so the layered hook below can fall
|
|
15
|
+
// through to it when nothing in the chain matches. Absolute includes
|
|
16
|
+
// (`/vendor/x/y.pug`) resolve against basedir; relative ones against the
|
|
17
|
+
// including file's directory — matching pug's built-in behaviour exactly.
|
|
18
|
+
export const defaultResolvePath = (filename, source, options) => {
|
|
19
|
+
const name = filename.trim()
|
|
20
|
+
const base = name[0] === '/' ? options.basedir : path.dirname(source.trim())
|
|
21
|
+
return path.join(base, name)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// First-match-wins resolution across an ordered chain of view roots — the
|
|
25
|
+
// site's own presentation first (`<site>/theme/views`, or the deprecated root
|
|
26
|
+
// `<site>/views`), the resolved theme package second — so a site file overrides
|
|
27
|
+
// the theme's copy of the same path while everything else falls through to the
|
|
28
|
+
// theme (ROADMAP-themes.md §1b).
|
|
29
|
+
//
|
|
30
|
+
// The trick that makes it root-agnostic: resolve as pug normally would, then
|
|
31
|
+
// re-root that path relative to whichever chain root it fell under, and retry
|
|
32
|
+
// the same relative path against each root in order. This works whether the
|
|
33
|
+
// including file lives in the site or the theme.
|
|
34
|
+
export const makeLayeredResolver = (roots) => (filename, source, options) => {
|
|
35
|
+
const fallback = defaultResolvePath(filename, source, options)
|
|
36
|
+
|
|
37
|
+
for (const root of roots) {
|
|
38
|
+
const rel = path.relative(root, fallback)
|
|
39
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) continue
|
|
40
|
+
for (const candidate of roots) {
|
|
41
|
+
const p = path.join(candidate, rel)
|
|
42
|
+
if (fssync.existsSync(p)) return p
|
|
43
|
+
}
|
|
44
|
+
break
|
|
45
|
+
}
|
|
46
|
+
return fallback
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The layout file itself may live in the theme, so resolve it through the same
|
|
50
|
+
// chain rather than assuming the site's views folder.
|
|
51
|
+
export const resolveEntry = (layout, roots) => {
|
|
52
|
+
for (const root of roots) {
|
|
53
|
+
const p = path.join(root, layout)
|
|
54
|
+
if (fssync.existsSync(p)) return p
|
|
55
|
+
}
|
|
56
|
+
// Fall back to the site root; the missing-file error then surfaces from
|
|
57
|
+
// compileFile with a path the user recognises.
|
|
58
|
+
return path.join(roots[0], layout)
|
|
59
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import fs from 'fs/promises'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
import { pathToFileURL } from 'url'
|
|
4
|
+
import YAML from 'yaml'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Normalize an npm-scoped plugin name to its short name.
|
|
8
|
+
* @example "@nera-static/plugin-search" -> "plugin-search"
|
|
9
|
+
*/
|
|
10
|
+
function shortPluginName(fullName) {
|
|
11
|
+
return fullName.startsWith('@nera-static/')
|
|
12
|
+
? fullName.replace('@nera-static/', '')
|
|
13
|
+
: fullName
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Try to load plugin-order config.
|
|
18
|
+
*
|
|
19
|
+
* Expected YAML shape:
|
|
20
|
+
*
|
|
21
|
+
* plugin-order:
|
|
22
|
+
* - start:
|
|
23
|
+
* - plugin-one
|
|
24
|
+
* - plugin-two
|
|
25
|
+
* - end:
|
|
26
|
+
* - plugin-before-last
|
|
27
|
+
* - plugin-last
|
|
28
|
+
*
|
|
29
|
+
* All keys optional. Unknown plugin names are ignored.
|
|
30
|
+
*/
|
|
31
|
+
async function loadPluginOrderConfig() {
|
|
32
|
+
const orderPath = path.resolve(process.cwd(), 'config/plugin-order.yaml')
|
|
33
|
+
try {
|
|
34
|
+
const raw = await fs.readFile(orderPath, 'utf-8')
|
|
35
|
+
const parsed = YAML.parse(raw)
|
|
36
|
+
const order = parsed?.['plugin-order'] || []
|
|
37
|
+
|
|
38
|
+
let start = []
|
|
39
|
+
let end = []
|
|
40
|
+
|
|
41
|
+
for (const entry of order) {
|
|
42
|
+
if (entry.start) start = entry.start.slice()
|
|
43
|
+
if (entry.end) end = entry.end.slice()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return { start, end, hasConfig: true }
|
|
47
|
+
} catch {
|
|
48
|
+
return { start: [], end: [], hasConfig: false }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Sort loaded plugins based on plugin-order config.
|
|
54
|
+
* Unlisted plugins go in the middle, sorted alphabetically by short name.
|
|
55
|
+
*/
|
|
56
|
+
function orderPlugins(loadedPlugins, startOrder, endOrder) {
|
|
57
|
+
const pluginMap = new Map(loadedPlugins.map((p) => [p.name, p]))
|
|
58
|
+
|
|
59
|
+
const middle = loadedPlugins
|
|
60
|
+
.filter(
|
|
61
|
+
(p) => !startOrder.includes(p.name) && !endOrder.includes(p.name)
|
|
62
|
+
)
|
|
63
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
64
|
+
|
|
65
|
+
return [
|
|
66
|
+
...startOrder.map((name) => pluginMap.get(name)).filter(Boolean),
|
|
67
|
+
...middle,
|
|
68
|
+
...endOrder.map((name) => pluginMap.get(name)).filter(Boolean),
|
|
69
|
+
]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Loads and applies local and installed plugins that can modify app and page data.
|
|
74
|
+
*
|
|
75
|
+
* @param {object} initialData - Contains `app` and `pagesData` keys.
|
|
76
|
+
* @param {string} localPluginsDir - Path to local plugin directory.
|
|
77
|
+
* @returns {Promise<{app: object, pagesData: object[], plugins: object[]}>}
|
|
78
|
+
*/
|
|
79
|
+
export async function getPluginsData(
|
|
80
|
+
initialData,
|
|
81
|
+
localPluginsDir = 'src/plugins'
|
|
82
|
+
) {
|
|
83
|
+
const startTime = performance.now()
|
|
84
|
+
const loadingPromises = []
|
|
85
|
+
|
|
86
|
+
//
|
|
87
|
+
// 1. Load local plugins in parallel
|
|
88
|
+
//
|
|
89
|
+
console.log('🔌 Loading local plugins...')
|
|
90
|
+
try {
|
|
91
|
+
const localPluginDirs = await fs.readdir(localPluginsDir).catch(() => [])
|
|
92
|
+
|
|
93
|
+
for (const dir of localPluginDirs) {
|
|
94
|
+
const pluginPath = path.join(localPluginsDir, dir, 'index.js')
|
|
95
|
+
|
|
96
|
+
const loadPromise = fs
|
|
97
|
+
.access(pluginPath)
|
|
98
|
+
.then(() => import(pathToFileURL(pluginPath)))
|
|
99
|
+
.then((mod) => {
|
|
100
|
+
console.log(` ✅ Loaded local plugin: ${dir}`)
|
|
101
|
+
return { type: 'local', name: dir, module: mod }
|
|
102
|
+
})
|
|
103
|
+
.catch((err) => {
|
|
104
|
+
console.warn(
|
|
105
|
+
` ⚠️ Failed to load local plugin ${dir}:`,
|
|
106
|
+
err.message
|
|
107
|
+
)
|
|
108
|
+
return null
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
loadingPromises.push(loadPromise)
|
|
112
|
+
}
|
|
113
|
+
} catch (err) {
|
|
114
|
+
console.warn('⚠️ Could not read local plugins directory:', err.message)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
//
|
|
118
|
+
// 2. Load installed @nera-static/* plugins in parallel
|
|
119
|
+
//
|
|
120
|
+
console.log('📦 Loading npm plugins...')
|
|
121
|
+
try {
|
|
122
|
+
// Resolved from the project root (cwd), like every other lookup here:
|
|
123
|
+
// config/plugin-order.yaml below, and core.js's ./config, ./pages, etc.
|
|
124
|
+
// Resolving relative to this file instead made plugin discovery ignore
|
|
125
|
+
// the working directory, so a test that pointed cwd at a fixture
|
|
126
|
+
// project still loaded the real site's dependencies.
|
|
127
|
+
const pkgJsonPath = path.resolve(process.cwd(), 'package.json')
|
|
128
|
+
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, 'utf-8'))
|
|
129
|
+
// A plugin is, by convention, exactly an `@nera-static/plugin-*` package
|
|
130
|
+
// (CLAUDE.md). Match on that prefix rather than the whole `@nera-static/`
|
|
131
|
+
// scope, so the scope's non-plugin members are never import()ed as
|
|
132
|
+
// plugins: the engine (`@nera-static/core`) and the CLI
|
|
133
|
+
// (`@nera-static/nera`) — which a thin site now depends on directly and
|
|
134
|
+
// which would otherwise log "❌ Failed to load npm plugin nera" on every
|
|
135
|
+
// build — plus `installer`, `validate`, and theme packages
|
|
136
|
+
// (`@nera-static/theme-*`, no JS entry point). The one library sharing
|
|
137
|
+
// the `plugin-` prefix, `@nera-static/plugin-utils`, is excluded by name.
|
|
138
|
+
const NON_PLUGIN = new Set(['@nera-static/plugin-utils'])
|
|
139
|
+
const deps = Object.keys(pkgJson.dependencies || {}).filter(
|
|
140
|
+
(name) =>
|
|
141
|
+
name.startsWith('@nera-static/plugin-') && !NON_PLUGIN.has(name)
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
for (const fullName of deps) {
|
|
145
|
+
const shortName = shortPluginName(fullName)
|
|
146
|
+
|
|
147
|
+
const loadPromise = import(fullName)
|
|
148
|
+
.then((mod) => {
|
|
149
|
+
console.log(` ✅ Loaded npm plugin: ${shortName}`)
|
|
150
|
+
return { type: 'npm', name: shortName, module: mod }
|
|
151
|
+
})
|
|
152
|
+
.catch((err) => {
|
|
153
|
+
console.warn(
|
|
154
|
+
` ❌ Failed to load npm plugin ${shortName}:`,
|
|
155
|
+
err.message
|
|
156
|
+
)
|
|
157
|
+
return null
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
loadingPromises.push(loadPromise)
|
|
161
|
+
}
|
|
162
|
+
} catch (err) {
|
|
163
|
+
console.warn(
|
|
164
|
+
'⚠️ Could not load package.json for npm plugins:',
|
|
165
|
+
err.message
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
//
|
|
170
|
+
// 3. Wait for all plugins to load
|
|
171
|
+
//
|
|
172
|
+
const results = await Promise.allSettled(loadingPromises)
|
|
173
|
+
const loadedPlugins = []
|
|
174
|
+
let successCount = 0
|
|
175
|
+
let errorCount = 0
|
|
176
|
+
|
|
177
|
+
for (const result of results) {
|
|
178
|
+
if (result.status === 'fulfilled' && result.value) {
|
|
179
|
+
loadedPlugins.push(result.value)
|
|
180
|
+
successCount++
|
|
181
|
+
} else {
|
|
182
|
+
errorCount++
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const loadTime = Math.round(performance.now() - startTime)
|
|
187
|
+
console.log(
|
|
188
|
+
`🎯 Plugin loading complete: ${successCount} loaded, ${errorCount} failed (${loadTime}ms)`
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
//
|
|
192
|
+
// 4. Determine order (start / middle / end)
|
|
193
|
+
//
|
|
194
|
+
const { start: startOrder, end: endOrder } = await loadPluginOrderConfig()
|
|
195
|
+
const ordered = orderPlugins(loadedPlugins, startOrder, endOrder)
|
|
196
|
+
|
|
197
|
+
//
|
|
198
|
+
// 5. Apply plugin methods
|
|
199
|
+
//
|
|
200
|
+
let appData = { ...initialData.app }
|
|
201
|
+
let pagesData = [...initialData.pagesData]
|
|
202
|
+
|
|
203
|
+
for (const plugin of ordered) {
|
|
204
|
+
const mod = plugin.module
|
|
205
|
+
|
|
206
|
+
if (typeof mod.getAppData === 'function') {
|
|
207
|
+
const result = await mod.getAppData({ app: appData, pagesData })
|
|
208
|
+
if (result && typeof result === 'object' && !Array.isArray(result)) {
|
|
209
|
+
appData = result
|
|
210
|
+
} else {
|
|
211
|
+
console.warn(
|
|
212
|
+
`⚠️ Plugin "${plugin.name}" getAppData returned invalid format, skipping replace.`
|
|
213
|
+
)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (typeof mod.getMetaData === 'function') {
|
|
218
|
+
const result = await mod.getMetaData({ app: appData, pagesData })
|
|
219
|
+
if (Array.isArray(result)) {
|
|
220
|
+
pagesData = result
|
|
221
|
+
} else {
|
|
222
|
+
console.warn(
|
|
223
|
+
`⚠️ Plugin "${plugin.name}" getMetaData returned invalid format, skipping append.`
|
|
224
|
+
)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
//
|
|
230
|
+
// 6. Return final
|
|
231
|
+
//
|
|
232
|
+
return {
|
|
233
|
+
app: appData,
|
|
234
|
+
pagesData,
|
|
235
|
+
plugins: ordered.map((p) => p.module),
|
|
236
|
+
}
|
|
237
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
import yaml from 'yaml'
|
|
4
|
+
import { defaultSettings, computeFolders } from './core.js'
|
|
5
|
+
import { resolveTheme } from './theme.js'
|
|
6
|
+
|
|
7
|
+
// Resolve a site's view-resolution model for a given directory WITHOUT building
|
|
8
|
+
// it: the folders the build will use, the theme (if any), and the ordered
|
|
9
|
+
// `roots` chain the layered resolver walks (`[siteViews]`, or
|
|
10
|
+
// `[siteViews, themeViews]` under a theme). This is the bridge that lets
|
|
11
|
+
// `@nera-static/validate` — and, later, the platform's Node service — validate a
|
|
12
|
+
// site against the exact resolution the generator performs, importing this
|
|
13
|
+
// instead of forking a copy.
|
|
14
|
+
//
|
|
15
|
+
// Unlike loadAppData it is fully cwd-parameterised and read-only: it never lists
|
|
16
|
+
// pages, never warns, and never throws on a missing or broken theme. A theme
|
|
17
|
+
// that cannot be resolved (unset package, missing `views/`) is returned as
|
|
18
|
+
// `themeError` and a malformed app.yaml as `appConfigError`, for the caller to
|
|
19
|
+
// surface as a validation finding rather than aborting.
|
|
20
|
+
export function resolveSiteModel({
|
|
21
|
+
cwd = process.cwd(),
|
|
22
|
+
settings = defaultSettings,
|
|
23
|
+
} = {}) {
|
|
24
|
+
const configFolder =
|
|
25
|
+
settings?.folders?.config || defaultSettings.folders.config
|
|
26
|
+
const appConfigPath = path.resolve(cwd, configFolder, 'app.yaml')
|
|
27
|
+
|
|
28
|
+
let appConfig = {}
|
|
29
|
+
let appConfigError = null
|
|
30
|
+
if (fs.existsSync(appConfigPath)) {
|
|
31
|
+
try {
|
|
32
|
+
appConfig = yaml.parse(fs.readFileSync(appConfigPath, 'utf-8')) || {}
|
|
33
|
+
} catch (err) {
|
|
34
|
+
appConfigError = err.message
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const folders = computeFolders(appConfig, { settings, cwd })
|
|
39
|
+
const viewsRoot = path.resolve(cwd, folders.views)
|
|
40
|
+
|
|
41
|
+
// resolveTheme throws on a `theme:` that cannot be resolved (the build's
|
|
42
|
+
// fail-loudly behaviour). Here that must not abort — capture it so validate
|
|
43
|
+
// can report "theme set but not found" as a finding.
|
|
44
|
+
let theme = null
|
|
45
|
+
let themeError = null
|
|
46
|
+
try {
|
|
47
|
+
theme = resolveTheme({ app: appConfig, cwd })
|
|
48
|
+
} catch (err) {
|
|
49
|
+
themeError = err.message
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const roots = theme ? [viewsRoot, theme.viewsRoot] : [viewsRoot]
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
cwd,
|
|
56
|
+
appConfig,
|
|
57
|
+
appConfigError,
|
|
58
|
+
folders,
|
|
59
|
+
viewsRoot,
|
|
60
|
+
theme,
|
|
61
|
+
themeError,
|
|
62
|
+
roots,
|
|
63
|
+
}
|
|
64
|
+
}
|