@nera-static/mcp 1.3.0 → 1.4.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/src/tools/cli.js CHANGED
@@ -1,15 +1,13 @@
1
1
  import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
  import { hasErrors, validate } from '@nera-static/nera'
4
+ import { pluginPackage } from '@nera-static/plugin-utils/packages'
4
5
  import { z } from 'zod'
5
6
  import { resolveInRoot } from '../paths.js'
6
7
  import { ok, tool, ToolError } from '../results.js'
7
8
  import { childEnv } from '../runner.js'
8
9
  import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
9
10
 
10
- const PLUGIN_SCOPE = '@nera-static/'
11
- const PLUGIN_NAME = /^[a-z0-9][a-z0-9-]*$/
12
- const NOT_PLUGINS = new Set(['utils'])
13
11
  /** A folder name `nera new` accepts, or `.` for the root itself. */
14
12
  const SITE_FOLDER = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
15
13
  /** A theme or starter package: a bare name (`blog`) or an npm package (`@scope/name`, `nera-starter-x`). */
@@ -36,7 +34,13 @@ export function failureText(run) {
36
34
  return tail(run.stderr) || tail(run.stdout) || `exit code ${run.code}`
37
35
  }
38
36
 
39
- function countBySeverity(results) {
37
+ /**
38
+ * How many of the validator's records are errors and how many warnings.
39
+ *
40
+ * @param {Array<{severity: string}>} results
41
+ * @returns {{ errors: number, warnings: number }}
42
+ */
43
+ export function countBySeverity(results) {
40
44
  const errors = results.filter((r) => r.severity === 'error').length
41
45
  return { errors, warnings: results.length - errors }
42
46
  }
@@ -54,21 +58,30 @@ async function starterArg(ctx, starter) {
54
58
  const real = await resolveInRoot(ctx.root, starter, { label: 'starter folder' })
55
59
  return `./${relativeTo(ctx.root, real)}`
56
60
  }
57
- throw new ToolError(`Invalid starter "${starter}". Use a starter name from list_starters (e.g. \`blog\`), a package name (\`@nera-static/starter-blog\`), a GitHub repository (\`github:owner/repo\`) or a starter folder inside the root (\`./my-starter\`).`)
61
+ throw new ToolError(`Invalid starter "${starter}". Use a starter name from list_starters (e.g. \`blog\`), a ` +
62
+ 'package name (`@nera-static/starter-blog`), a GitHub repository (`github:owner/repo`) or a starter ' +
63
+ 'folder inside the root (`./my-starter`).')
58
64
  }
59
65
 
60
66
  /**
61
- * The npm package of an `add_plugin` spec, in the same forms the CLI's
62
- * addPlugin takes: `@nera-static/plugin-<name>`, `plugin-<name>` or just
63
- * `<name>`; anything else (another scope, a version, a path, a URL) is
64
- * refused.
67
+ * The npm package of an `add_plugin` spec, by the rule the CLI's addPlugin
68
+ * uses (`pluginPackage`): `@nera-static/plugin-<name>`, `plugin-<name>` or
69
+ * just `<name>`; anything else (another scope, a version, a path, a URL) is
70
+ * refused with a pointer to list_plugins.
71
+ *
72
+ * @param {string} spec
73
+ * @returns {{ name: string, pkg: string }}
74
+ * @throws {ToolError}
65
75
  */
66
- function pluginPackage(spec) {
67
- const name = spec.replace(new RegExp(`^(${PLUGIN_SCOPE}plugin-|plugin-)`), '')
68
- if (!PLUGIN_NAME.test(name) || NOT_PLUGINS.has(name)) {
69
- throw new ToolError(`"${spec}" is not a Nera plugin. Pass an official plugin as \`@nera-static/plugin-<name>\`, \`plugin-<name>\` or just \`<name>\` (e.g. \`sitemap\`); call list_plugins for the catalog.`)
76
+ function addPluginPackage(spec) {
77
+ try {
78
+ return pluginPackage(spec)
79
+ } catch (error) {
80
+ if (!(error instanceof TypeError)) throw error
81
+ throw new ToolError(`"${spec}" is not a Nera plugin. Pass an official plugin as ` +
82
+ '`@nera-static/plugin-<name>`, `plugin-<name>` or just `<name>` (e.g. `sitemap`); call ' +
83
+ 'list_plugins for the catalog.')
70
84
  }
71
- return { name, pkg: `${PLUGIN_SCOPE}plugin-${name}` }
72
85
  }
73
86
 
74
87
  /**
@@ -91,14 +104,17 @@ export function registerCliTools(server, ctx) {
91
104
  }, tool(async ({ name, starter, theme, title, lang }, { signal }) => {
92
105
  const inRoot = name === '.' || name === './'
93
106
  if (!inRoot && !SITE_FOLDER.test(name)) {
94
- throw new ToolError(`Invalid site folder "${name}". Use one folder name made of letters, digits, \`.\`, \`-\` and \`_\`, starting with a letter or digit (e.g. \`my-site\`), or \`.\` for the root itself.`)
107
+ throw new ToolError(`Invalid site folder "${name}". Use one folder name made of letters, digits, \`.\`, ` +
108
+ '`-` and `_`, starting with a letter or digit (e.g. `my-site`), or `.` for the root itself.')
95
109
  }
96
110
  const target = await resolveInRoot(ctx.root, inRoot ? '.' : name, { label: 'site folder' })
97
111
  if (!inRoot && await exists(target)) {
98
- throw new ToolError(`"${name}" already exists in ${ctx.root}. Choose another name, or call list_sites to work on an existing site.`)
112
+ throw new ToolError(`"${name}" already exists in ${ctx.root}. Choose another name, or call list_sites to ` +
113
+ 'work on an existing site.')
99
114
  }
100
115
  if (theme !== undefined && !PACKAGE_SPEC.test(theme)) {
101
- throw new ToolError(`Invalid theme "${theme}". Use a theme name from list_themes (e.g. \`blog\`) or a package name (\`@nera-static/theme-blog\`).`)
116
+ throw new ToolError(`Invalid theme "${theme}". Use a theme name from list_themes (e.g. \`blog\`) or a ` +
117
+ 'package name (`@nera-static/theme-blog`).')
102
118
  }
103
119
 
104
120
  const spec = starter === undefined ? undefined : await starterArg(ctx, starter)
@@ -121,7 +137,10 @@ export function registerCliTools(server, ctx) {
121
137
  // rerun there); after anything else, an abort included,
122
138
  // createSite has removed a new folder again.
123
139
  if (!signal.aborted && typeof error.code === 'number' && await exists(path.join(target, 'package.json'))) {
124
- throw new ToolError(`The files of the site "${site}" are written, but installing its packages failed: ${error.message}\nnpm's own output is in the server's log. Fix what npm reports (often the network connection), then run \`npm install\` in that folder, or call create_site again with another name.`)
140
+ throw new ToolError(`The files of the site "${site}" are written, but installing its packages ` +
141
+ `failed: ${error.message}\nnpm's own output is in the server's log. Fix what npm reports (often ` +
142
+ 'the network connection), then run `npm install` in that folder, or call create_site again ' +
143
+ 'with another name.')
125
144
  }
126
145
  throw new ToolError(`Creating the site failed: ${error.message}`)
127
146
  }
@@ -129,8 +148,10 @@ export function registerCliTools(server, ctx) {
129
148
  return ok(
130
149
  { site, log: tail(lines.join('\n')), firstSteps },
131
150
  firstSteps
132
- ? `Created the Nera site "${site}". Its starter suggests first steps (in firstSteps); follow them, starting with get_site with site "${site}".`
133
- : `Created the Nera site "${site}". Call get_site with site "${site}" to see its pages, then edit them with write_page.`,
151
+ ? `Created the Nera site "${site}". Its starter suggests first steps (in firstSteps); follow them, ` +
152
+ `starting with get_site with site "${site}".`
153
+ : `Created the Nera site "${site}". Call get_site with site "${site}" to see its pages, then ` +
154
+ 'edit them with write_page.',
134
155
  )
135
156
  }))
136
157
 
@@ -185,7 +206,7 @@ export function registerCliTools(server, ctx) {
185
206
  plugin: z.string().describe('The plugin, as `@nera-static/plugin-<name>`, `plugin-<name>` or just `<name>` (e.g. `sitemap`, `tags`).'),
186
207
  },
187
208
  }, tool(async ({ site, plugin }, { signal }) => {
188
- const { name, pkg } = pluginPackage(plugin)
209
+ const { name, pkg } = addPluginPackage(plugin)
189
210
  const resolved = await resolveSite(ctx, site)
190
211
  // addPlugin writes `<folders.config>/<name>.yaml` without checking
191
212
  // where it leads, so a config folder or file that is a symbolic link
@@ -200,12 +221,15 @@ export function registerCliTools(server, ctx) {
200
221
  const lines = []
201
222
  let added
202
223
  try {
203
- added = await ctx.addPlugin(pkg, { cwd: resolved.dir, signal, env: childEnv(), log: (line) => lines.push(line) })
224
+ const log = (line) => lines.push(line)
225
+ added = await ctx.addPlugin(pkg, { cwd: resolved.dir, signal, env: childEnv(), log })
204
226
  } catch (error) {
205
227
  // A command that ran and failed (npm install, the template
206
228
  // script) carries its exit code; its own output is not captured.
207
229
  const childFailed = !signal.aborted && typeof error.cause?.code === 'number'
208
- throw new ToolError(childFailed ? `${error.message}\nThe command's own output is in the server's log. Fix what it reports (for npm often the network connection), then call add_plugin again.` : error.message)
230
+ throw new ToolError(childFailed ? `${error.message}\nThe command's own output is in the server's log. ` +
231
+ 'Fix what it reports (for npm often the network connection), ' +
232
+ 'then call add_plugin again.' : error.message)
209
233
  }
210
234
 
211
235
  const { config, templates } = added
@@ -1,21 +1,14 @@
1
1
  import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
- import { isDeepStrictEqual } from 'node:util'
4
- import yaml from 'yaml'
3
+ import { isInside } from '@nera-static/plugin-utils/urls'
5
4
  import { z } from 'zod'
6
- import { isInside, resolveInRoot } from '../paths.js'
5
+ import { NO_WRITE_SEGMENTS, composePage, parsePage, refuseSecrets, refuseSegments, requireLayout } from '../pages.js'
6
+ import { resolveInRoot } from '../paths.js'
7
7
  import { ok, tool, ToolError } from '../results.js'
8
8
  import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
9
9
 
10
10
  /** Larger files are refused by read_file: a model cannot use them whole. */
11
11
  const MAX_READ_BYTES = 1024 * 1024
12
- const FENCE = '---'
13
- /** Path segments no file tool reads or writes: git internals may hold credentials. */
14
- const FORBIDDEN_SEGMENTS = new Set(['.git'])
15
- /** File names no file tool reads or writes: `.env` files and `.npmrc` (npm `_authToken`) hold tokens. */
16
- const SECRET_FILE = /^(\.env(\..*)?|\.npmrc)$/
17
- /** Path segments write_file refuses: installed packages belong to npm. */
18
- const NO_WRITE_SEGMENTS = new Set(['node_modules'])
19
12
 
20
13
  const pageInput = z
21
14
  .string()
@@ -24,71 +17,6 @@ const fileInput = z
24
17
  .string()
25
18
  .describe('The file, relative to the site folder — e.g. `config/app.yaml`, `theme/views/layouts/default.pug`, `assets/css/main.css`.')
26
19
 
27
- /**
28
- * Splits a page into its frontmatter YAML and its Markdown body, the way the
29
- * build reads it: a `---` first line opens the block, the next `---` line
30
- * closes it (no closing line: the rest is frontmatter).
31
- *
32
- * @param {string} raw the file's text
33
- * @returns {{ yamlText: string|null, body: string }} `yamlText` null when the page has no frontmatter
34
- */
35
- function splitPage(raw) {
36
- // markdown-it, which the build parses pages with, reads CRLF as LF.
37
- const lines = raw.replace(/\r\n/g, '\n').split('\n')
38
- if (lines[0] !== FENCE) return { yamlText: null, body: raw }
39
- const close = lines.indexOf(FENCE, 1)
40
- if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
41
- return {
42
- yamlText: lines.slice(1, close).join('\n'),
43
- body: lines.slice(close + 1).join('\n'),
44
- }
45
- }
46
-
47
- /** Parses frontmatter YAML into a document that keeps comments and quoting. */
48
- function parseFrontmatter(yamlText) {
49
- const doc = yaml.parseDocument(yamlText ?? '', { merge: true, uniqueKeys: false })
50
- if (doc.errors.length) {
51
- return { doc: null, error: doc.errors[0].message }
52
- }
53
- if (doc.contents !== null && !yaml.isMap(doc.contents)) {
54
- return { doc: null, error: 'The frontmatter is not a list of `key: value` lines.' }
55
- }
56
- return { doc, error: null }
57
- }
58
-
59
- /**
60
- * The frontmatter YAML for `frontmatter`, edited into the page's existing
61
- * frontmatter when it has one that parses: unchanged keys keep their comments,
62
- * quoting and order, a changed value keeps its quoting style, keys left out are
63
- * removed, new keys are appended. Nothing changed: the block stays byte for byte.
64
- */
65
- function frontmatterText(existingYaml, frontmatter) {
66
- const { doc } = existingYaml === null ? { doc: null } : parseFrontmatter(existingYaml)
67
- if (!doc || doc.contents === null) {
68
- return new yaml.Document(frontmatter).toString({ flowCollectionPadding: false })
69
- }
70
- const current = doc.toJS() ?? {}
71
- let changed = false
72
- for (const key of Object.keys(current)) {
73
- if (!Object.hasOwn(frontmatter, key)) {
74
- doc.delete(key)
75
- changed = true
76
- }
77
- }
78
- for (const [key, value] of Object.entries(frontmatter)) {
79
- if (!isDeepStrictEqual(current[key], value)) {
80
- doc.set(key, value)
81
- changed = true
82
- }
83
- }
84
- if (!changed) return withTrailingNewline(existingYaml)
85
- return doc.toString({ flowCollectionPadding: false })
86
- }
87
-
88
- function withTrailingNewline(text) {
89
- return text.endsWith('\n') ? text : `${text}\n`
90
- }
91
-
92
20
  async function statOrNull(file) {
93
21
  try {
94
22
  return await fs.stat(file)
@@ -108,24 +36,6 @@ async function readText(file, shown) {
108
36
  }
109
37
  }
110
38
 
111
- /**
112
- * Refuses `input` when it, or the site-relative real path it resolved to (a
113
- * symbolic link may point into `.git/`), has a segment from `segments`.
114
- */
115
- function refuseSegments(input, resolved, segments, why) {
116
- const hit = [input, resolved]
117
- .flatMap((candidate) => candidate.split(/[\\/]/))
118
- .find((segment) => segments.has(segment))
119
- if (hit) throw new ToolError(`"${input}" is inside ${hit}/, which ${why}.`)
120
- }
121
-
122
- function refuseSecrets(input, resolved) {
123
- refuseSegments(input, resolved, FORBIDDEN_SEGMENTS, 'these tools never read or change')
124
- if ([input, resolved].some((candidate) => SECRET_FILE.test(path.basename(candidate)))) {
125
- throw new ToolError(`"${input}" can hold secrets (tokens, passwords); these tools never read or change it.`)
126
- }
127
- }
128
-
129
39
  /**
130
40
  * Resolves a page argument: inside the site, inside its pages folder, a `.md`
131
41
  * file.
@@ -136,7 +46,8 @@ async function resolvePage(ctx, site, page) {
136
46
  const file = await resolveInRoot(resolved.dir, page, { label: 'page path' })
137
47
  const pagesFolder = relativeTo(resolved.dir, pagesDir)
138
48
  if (file === pagesDir || !isInside(pagesDir, file)) {
139
- throw new ToolError(`"${page}" is not inside the site's pages folder (${pagesFolder}/). Give a path like ${pagesFolder}/about.md; for other files use read_file / write_file.`)
49
+ throw new ToolError(`"${page}" is not inside the site's pages folder (${pagesFolder}/). Give a path ` +
50
+ `like ${pagesFolder}/about.md; for other files use read_file / write_file.`)
140
51
  }
141
52
  if (path.extname(file) !== '.md') {
142
53
  throw new ToolError(`"${page}" does not end in .md. Pages are Markdown files, e.g. ${pagesFolder}/about.md.`)
@@ -176,15 +87,15 @@ export function registerFileTools(server, ctx) {
176
87
  const target = await resolvePage(ctx, site, page)
177
88
  const raw = await readText(target.file, target.path)
178
89
  if (raw === null) {
179
- throw new ToolError(`The page "${target.path}" does not exist. Call get_site for the list of pages, or write_page to create it.`)
90
+ throw new ToolError(`The page "${target.path}" does not exist. Call get_site for the list of pages, or ` +
91
+ 'write_page to create it.')
180
92
  }
181
- const { yamlText, body } = splitPage(raw)
182
- const { doc, error } = parseFrontmatter(yamlText)
183
- const frontmatter = doc ? (doc.toJS() ?? {}) : null
184
- const structured = { site: target.site, path: target.path, frontmatter, body: body.replace(/^\n+/, '') }
93
+ const { frontmatter, body, error } = parsePage(raw)
94
+ const structured = { site: target.site, path: target.path, frontmatter, body }
185
95
  if (error) structured.frontmatterError = error
186
96
  const text = error
187
- ? `Read ${target.path}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, passing the whole frontmatter.`
97
+ ? `Read ${target.path}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, ` +
98
+ 'passing the whole frontmatter.'
188
99
  : `Read ${target.path} (layout: ${frontmatter.layout ?? 'none — the build skips this page'}).`
189
100
  return ok(structured, text)
190
101
  }))
@@ -199,16 +110,10 @@ export function registerFileTools(server, ctx) {
199
110
  body: z.string().optional().describe('The page\'s Markdown content, without the frontmatter. Leave out to keep the existing body.'),
200
111
  },
201
112
  }, tool(async ({ site, path: page, frontmatter, body }) => {
202
- if (typeof frontmatter.layout !== 'string' || frontmatter.layout.trim() === '') {
203
- throw new ToolError('The frontmatter has no `layout`. Nera only renders pages that name their layout — add e.g. `layout: pages/default.pug` (read an existing page with read_page to see which layout the site uses).')
204
- }
113
+ requireLayout(frontmatter)
205
114
  const target = await resolvePage(ctx, site, page)
206
115
  const raw = await readText(target.file, target.path)
207
- const existing = raw === null ? null : splitPage(raw)
208
- const head = `${FENCE}\n${frontmatterText(existing?.yamlText ?? null, frontmatter)}${FENCE}\n`
209
- const content = body === undefined
210
- ? head + (existing?.body ?? '')
211
- : `${head}\n${withTrailingNewline(body.replace(/^\n+/, ''))}`
116
+ const content = composePage(raw, frontmatter, body)
212
117
  await fs.mkdir(path.dirname(target.file), { recursive: true })
213
118
  await fs.writeFile(target.file, content)
214
119
  const created = raw === null
@@ -245,13 +150,15 @@ export function registerFileTools(server, ctx) {
245
150
  const target = await resolveFile(ctx, site, input)
246
151
  const stat = await statOrNull(target.file)
247
152
  if (stat === null) {
248
- throw new ToolError(`The file "${target.path}" does not exist in site "${target.site}". Call get_site to see the site's folders.`)
153
+ throw new ToolError(`The file "${target.path}" does not exist in site "${target.site}". Call get_site to ` +
154
+ 'see the site\'s folders.')
249
155
  }
250
156
  if (stat.isDirectory()) {
251
157
  throw new ToolError(`"${target.path}" is a folder, not a file.`)
252
158
  }
253
159
  if (stat.size > MAX_READ_BYTES) {
254
- throw new ToolError(`"${target.path}" is ${stat.size} bytes, more than the ${MAX_READ_BYTES} bytes read_file returns.`)
160
+ throw new ToolError(`"${target.path}" is ${stat.size} bytes, more than the ${MAX_READ_BYTES} ` +
161
+ 'bytes read_file returns.')
255
162
  }
256
163
  const buffer = await fs.readFile(target.file)
257
164
  if (buffer.includes(0)) {
@@ -274,7 +181,8 @@ export function registerFileTools(server, ctx) {
274
181
  refuseSegments(input, target.path, NO_WRITE_SEGMENTS, 'npm manages; add plugins with add_plugin')
275
182
  const { pagesDir, distDir } = await siteFolders(target.dir)
276
183
  if (isInside(distDir, target.file)) {
277
- throw new ToolError(`"${target.path}" is in the output folder (${relativeTo(target.dir, distDir)}/), which every build deletes and recreates. Change the page, template or asset it is built from instead.`)
184
+ throw new ToolError(`"${target.path}" is in the output folder (${relativeTo(target.dir, distDir)}/), ` +
185
+ 'which every build deletes and recreates. Change the page, template or asset it is built from instead.')
278
186
  }
279
187
  if (isInside(pagesDir, target.file) && path.extname(target.file) === '.md') {
280
188
  throw new ToolError(`"${target.path}" is a page. Use write_page, which checks the frontmatter.`)
@@ -1,3 +1,4 @@
1
+ import { satisfiesFloor } from '@nera-static/plugin-utils/guard'
1
2
  import { z } from 'zod'
2
3
  import { freePort } from '../processes.js'
3
4
  import { ok, tool, ToolError } from '../results.js'
@@ -37,8 +38,10 @@ const ACTIONS = {
37
38
  }
38
39
 
39
40
  const INSTRUCTIONS = {
40
- github_sign_in: ({ code, url }) => `Ask the user to open ${url} and enter the code ${code}, then call publish again.`,
41
- github_app_install: ({ url }) => `Ask the user to open ${url} and install the Nera Static app on their GitHub account, then call publish again.`,
41
+ github_sign_in: ({ code, url }) => `Ask the user to open ${url} and enter the code ${code}, ` +
42
+ 'then call publish again.',
43
+ github_app_install: ({ url }) => `Ask the user to open ${url} and install the Nera Static app on their GitHub ` +
44
+ 'account, then call publish again.',
42
45
  netlify_sign_in: ({ url }) => `Ask the user to open ${url} and choose "Authorize", then call publish again.`,
43
46
  }
44
47
 
@@ -110,31 +113,6 @@ function lastProgress(stderr) {
110
113
  return last.length > PROGRESS_MAX ? `${last.slice(0, PROGRESS_MAX)}…` : last
111
114
  }
112
115
 
113
- /** `x.y.z` with an optional `-prerelease` (and `+build`, ignored), or null. */
114
- function parseVersion(version) {
115
- const match = typeof version === 'string' && version.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/)
116
- return match ? { numbers: match.slice(1, 4).map(Number), prerelease: match[4] !== undefined } : null
117
- }
118
-
119
- /**
120
- * Whether `version` is `floor` or later, by semver precedence: major, minor
121
- * and patch compared as numbers, and a prerelease of a version (`1.27.0-beta.1`)
122
- * below that version. Anything that is no `x.y.z` version is not.
123
- *
124
- * @param {string|null} version
125
- * @param {string} floor an `x.y.z` version without a prerelease
126
- * @returns {boolean}
127
- */
128
- export function meetsFloor(version, floor) {
129
- const have = parseVersion(version)
130
- if (!have) return false
131
- const need = parseVersion(floor).numbers
132
- for (let i = 0; i < 3; i++) {
133
- if (have.numbers[i] !== need[i]) return have.numbers[i] > need[i]
134
- }
135
- return !have.prerelease
136
- }
137
-
138
116
  /**
139
117
  * The local address `nera dev` serves on, once Vite has printed it.
140
118
  *
@@ -204,7 +182,7 @@ export function registerLongRunningTools(server, ctx) {
204
182
 
205
183
  server.registerTool('preview', {
206
184
  title: 'Preview a Nera site',
207
- description: 'Builds a Nera site and serves it on this computer (`nera dev`), rebuilding whenever a page, template or setting changes, and returns the local address (e.g. http://localhost:3000/) for the user to open in a browser. Calling it again for the same site returns the running server\'s address; edits show up there by themselves. Pass `stop: true` to stop it. The server stops when this MCP server closes. If it fails, call validate to find the cause.',
185
+ description: 'Builds a Nera site and serves it on this computer (`nera dev`), rebuilding whenever a page, template or setting changes, and returns the local address (e.g. http://localhost:3000/) for the user to open in a browser. Calling it again for the same site returns the running server\'s address. After a change the user may need to reload the page in the browser to see it. Pass `stop: true` to stop it. The server stops when this MCP server closes. If it fails, call validate to find the cause.',
208
186
  inputSchema: {
209
187
  site: siteInput,
210
188
  stop: z.boolean().optional().describe('Stop the site\'s running preview instead of starting one. Default false.'),
@@ -216,7 +194,8 @@ export function registerLongRunningTools(server, ctx) {
216
194
  const stopped = await ctx.processes.stop(key)
217
195
  return ok(
218
196
  { site: resolved.site, stopped },
219
- stopped ? `Stopped the preview of "${resolved.site}".` : `No preview of "${resolved.site}" was running.`,
197
+ stopped ? `Stopped the preview of "${resolved.site}".` : `No preview of "${resolved.site}" ` +
198
+ 'was running.',
220
199
  )
221
200
  }
222
201
 
@@ -236,7 +215,8 @@ export function registerLongRunningTools(server, ctx) {
236
215
  const url = previewUrl(run.stdout)
237
216
  if (run.exited) {
238
217
  ctx.processes.forget(key)
239
- throw new ToolError(`The preview of "${resolved.site}" stopped: ${failureText(run)}\nCall validate to find the cause, fix it, then call preview again.`)
218
+ throw new ToolError(`The preview of "${resolved.site}" stopped: ${failureText(run)}\nCall validate to ` +
219
+ 'find the cause, fix it, then call preview again.')
240
220
  }
241
221
  if (!url) {
242
222
  await ctx.processes.stop(key)
@@ -244,7 +224,7 @@ export function registerLongRunningTools(server, ctx) {
244
224
  }
245
225
  return ok(
246
226
  { site: resolved.site, url, reused },
247
- `${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address; it updates by itself when files change.`,
227
+ `${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address. The site rebuilds after every change; the user may need to reload the page to see it.`,
248
228
  )
249
229
  }))
250
230
 
@@ -265,9 +245,10 @@ export function registerLongRunningTools(server, ctx) {
265
245
  if (!run) {
266
246
  // an older CLI announces no browser step as an event, so the user would never see the sign-in code
267
247
  const version = neraVersion(resolved.dir)
268
- if (!meetsFloor(version, PUBLISH_CLI_FLOOR)) {
248
+ if (!satisfiesFloor(version, PUBLISH_CLI_FLOOR)) {
269
249
  const runs = version ? `@nera-static/nera ${version}` : 'a @nera-static/nera whose version cannot be read'
270
- throw new ToolError(`Publishing "${resolved.site}" runs ${runs}; publish needs ${PUBLISH_CLI_FLOOR} or later. Run \`npm update\` in the site, then call publish again.`)
250
+ throw new ToolError(`Publishing "${resolved.site}" runs ${runs}; publish needs ${PUBLISH_CLI_FLOOR} ` +
251
+ 'or later. Run `npm update` in the site, then call publish again.')
271
252
  }
272
253
  run = ctx.processes.start(key, 'nera', publishArgs(options), { cwd: resolved.dir })
273
254
  }
@@ -1,13 +1,14 @@
1
1
  import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
  import { resolveSiteModel } from '@nera-static/core'
4
+ import { isPluginPackage } from '@nera-static/plugin-utils/packages'
5
+ import { byString } from '@nera-static/plugin-utils/sort'
6
+ import { isInside } from '@nera-static/plugin-utils/urls'
4
7
  import { z } from 'zod'
5
- import { isInside, resolveInRoot } from '../paths.js'
8
+ import { resolveInRoot } from '../paths.js'
6
9
  import { ok, tool, ToolError } from '../results.js'
7
10
 
8
11
  const CLI_PACKAGE = '@nera-static/nera'
9
- const PLUGIN_PREFIX = '@nera-static/plugin-'
10
- const NOT_PLUGINS = new Set(['@nera-static/plugin-utils'])
11
12
  /** How deep `list_sites` looks below the root (the root itself is depth 0). */
12
13
  const MAX_SITE_DEPTH = 3
13
14
  const SKIPPED_FOLDERS = new Set(['node_modules', 'public'])
@@ -30,12 +31,38 @@ async function readPackage(dir) {
30
31
  }
31
32
  }
32
33
 
34
+ /**
35
+ * @param {object|null} pkg a parsed package.json
36
+ * @returns {Record<string, string>} its dependencies and devDependencies
37
+ */
33
38
  function allDependencies(pkg) {
34
39
  return { ...pkg?.devDependencies, ...pkg?.dependencies }
35
40
  }
36
41
 
37
- function isNeraSite(pkg) {
38
- return Boolean(allDependencies(pkg)[CLI_PACKAGE])
42
+ /**
43
+ * @param {object|null} pkg a parsed package.json
44
+ * @returns {boolean} whether it is a Nera site's: it depends on `@nera-static/nera`
45
+ */
46
+ export function isNeraSite(pkg) {
47
+ return Boolean(neraRange(pkg))
48
+ }
49
+
50
+ /**
51
+ * @param {object|null} pkg a parsed package.json
52
+ * @returns {string|undefined} the `@nera-static/nera` range it depends on
53
+ */
54
+ export function neraRange(pkg) {
55
+ return allDependencies(pkg)[CLI_PACKAGE]
56
+ }
57
+
58
+ /**
59
+ * @param {object|null} pkg a parsed package.json
60
+ * @returns {string[]} the Nera plugins it depends on, sorted
61
+ */
62
+ export function sitePlugins(pkg) {
63
+ return Object.keys(allDependencies(pkg))
64
+ .filter(isPluginPackage)
65
+ .sort(byString)
39
66
  }
40
67
 
41
68
  /**
@@ -59,7 +86,8 @@ export async function resolveSite(ctx, site) {
59
86
  const dir = await resolveInRoot(ctx.root, site, { label: 'site' })
60
87
  const pkg = await readPackage(dir)
61
88
  if (!isNeraSite(pkg)) {
62
- throw new ToolError(`"${site}" is not a Nera site: it has no package.json that depends on ${CLI_PACKAGE}. Call list_sites to see the sites under the root, or create_site to make one.`)
89
+ throw new ToolError(`"${site}" is not a Nera site: it has no package.json that depends on ${CLI_PACKAGE}. ` +
90
+ 'Call list_sites to see the sites under the root, or create_site to make one.')
63
91
  }
64
92
  return { dir, site: relativeTo(ctx.root, dir), pkg }
65
93
  }
@@ -94,7 +122,7 @@ async function listPages(dir, pagesDir) {
94
122
  .map((entry) => path.join(entry.parentPath, entry.name))
95
123
  .filter((file) => isInside(pagesDir, file))
96
124
  .map((file) => relativeTo(dir, file))
97
- .sort()
125
+ .sort(byString)
98
126
  }
99
127
 
100
128
  /**
@@ -110,7 +138,7 @@ export async function findSites(root) {
110
138
  found.push({
111
139
  site: relativeTo(root, dir),
112
140
  name: pkg.name ?? null,
113
- nera: allDependencies(pkg)[CLI_PACKAGE],
141
+ nera: neraRange(pkg),
114
142
  })
115
143
  return
116
144
  }
@@ -127,7 +155,7 @@ export async function findSites(root) {
127
155
  }
128
156
  }
129
157
  await visit(root, 0)
130
- return found.sort((a, b) => a.site.localeCompare(b.site))
158
+ return found.sort((a, b) => byString(a.site, b.site))
131
159
  }
132
160
 
133
161
  /**
@@ -158,14 +186,12 @@ export function registerSiteTools(server, ctx) {
158
186
  }, tool(async ({ site }) => {
159
187
  const resolved = await resolveSite(ctx, site)
160
188
  const { model, pagesDir } = await siteFolders(resolved.dir)
161
- const plugins = Object.keys(allDependencies(resolved.pkg))
162
- .filter((name) => name.startsWith(PLUGIN_PREFIX) && !NOT_PLUGINS.has(name))
163
- .sort()
189
+ const plugins = sitePlugins(resolved.pkg)
164
190
  const pages = await listPages(resolved.dir, pagesDir)
165
191
  const structured = {
166
192
  site: resolved.site,
167
193
  name: resolved.pkg.name ?? null,
168
- nera: allDependencies(resolved.pkg)[CLI_PACKAGE],
194
+ nera: neraRange(resolved.pkg),
169
195
  app: model.appConfig,
170
196
  appConfigError: model.appConfigError,
171
197
  folders: model.folders,