@nera-static/mcp 1.4.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/pages.js CHANGED
@@ -1,10 +1,11 @@
1
- // The page and path rules both modes share (plan D4): how a page file splits
2
- // into frontmatter and body, how new frontmatter is edited into an existing
1
+ // The page and path rules both modes share: how a page file splits into
2
+ // frontmatter and body, how new frontmatter is edited into an existing
3
3
  // block, that a page names its `layout`, and which paths no tool reads or
4
4
  // writes. Pure functions only — the local file tools (src/tools/files.js) and
5
5
  // the hosted repo tools apply them to a file on disk and a file on GitHub alike.
6
6
  import path from 'node:path'
7
7
  import { isDeepStrictEqual } from 'node:util'
8
+ import { FRONTMATTER_OPTIONS, splitFrontmatter } from '@nera-static/plugin-utils/frontmatter'
8
9
  import yaml from 'yaml'
9
10
  import { ToolError } from './results.js'
10
11
 
@@ -17,23 +18,25 @@ export const SECRET_FILE = /^(\.env(\..*)?|\.npmrc)$/
17
18
  export const NO_WRITE_SEGMENTS = new Set(['node_modules'])
18
19
 
19
20
  /**
20
- * Splits a page into its frontmatter YAML and its Markdown body, the way the
21
- * build reads it: a `---` first line opens the block, the next `---` line
22
- * closes it (no closing line: the rest is frontmatter).
21
+ * The YAML options page frontmatter is read with: core's
22
+ * (`FRONTMATTER_OPTIONS`, so merge keys and repeated keys behave as in the
23
+ * build) without the `timestamp` tag, so an unquoted `date: 2026-11-28` stays
24
+ * the text the author wrote instead of becoming a date-time. The hosted
25
+ * checkout (src/hosted/checkout.js) reads layouts with them too, as the
26
+ * validator does.
27
+ */
28
+ export const PAGE_YAML_OPTIONS = Object.freeze({ ...FRONTMATTER_OPTIONS, customTags: Object.freeze([]) })
29
+
30
+ /**
31
+ * Splits a page into its frontmatter YAML and its Markdown body by the
32
+ * build's rule (`splitFrontmatter`); a page without a `---` first line is
33
+ * body only.
23
34
  *
24
35
  * @param {string} raw the file's text
25
36
  * @returns {{ yamlText: string|null, body: string }} `yamlText` null when the page has no frontmatter
26
37
  */
27
- export function splitPage(raw) {
28
- // markdown-it, which the build parses pages with, reads CRLF as LF.
29
- const lines = raw.replace(/\r\n/g, '\n').split('\n')
30
- if (lines[0] !== FENCE) return { yamlText: null, body: raw }
31
- const close = lines.indexOf(FENCE, 1)
32
- if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
33
- return {
34
- yamlText: lines.slice(1, close).join('\n'),
35
- body: lines.slice(close + 1).join('\n'),
36
- }
38
+ function pageParts(raw) {
39
+ return splitFrontmatter(raw) ?? { yamlText: null, body: raw }
37
40
  }
38
41
 
39
42
  /**
@@ -43,7 +46,7 @@ export function splitPage(raw) {
43
46
  * @returns {{ doc: import('yaml').Document|null, error: string|null }}
44
47
  */
45
48
  export function parseFrontmatter(yamlText) {
46
- const doc = yaml.parseDocument(yamlText ?? '', { merge: true, uniqueKeys: false })
49
+ const doc = yaml.parseDocument(yamlText ?? '', PAGE_YAML_OPTIONS)
47
50
  if (doc.errors.length) {
48
51
  return { doc: null, error: doc.errors[0].message }
49
52
  }
@@ -62,7 +65,7 @@ export function parseFrontmatter(yamlText) {
62
65
  * @returns {{ frontmatter: object|null, body: string, error: string|null }}
63
66
  */
64
67
  export function parsePage(raw) {
65
- const { yamlText, body } = splitPage(raw)
68
+ const { yamlText, body } = pageParts(raw)
66
69
  const { doc, error } = parseFrontmatter(yamlText)
67
70
  return { frontmatter: doc ? (doc.toJS() ?? {}) : null, body: body.replace(/^\n+/, ''), error }
68
71
  }
@@ -129,7 +132,7 @@ export function requireLayout(frontmatter) {
129
132
  * @returns {string}
130
133
  */
131
134
  export function composePage(raw, frontmatter, body) {
132
- const existing = raw === null ? null : splitPage(raw)
135
+ const existing = raw === null ? null : pageParts(raw)
133
136
  const head = `${FENCE}\n${frontmatterText(existing?.yamlText ?? null, frontmatter)}${FENCE}\n`
134
137
  return body === undefined
135
138
  ? head + (existing?.body ?? '')
package/src/paths.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
+ import { isInside } from '@nera-static/plugin-utils/urls'
3
4
 
4
5
  /**
5
6
  * A path a tool was given that points outside the folder it may touch, or that
@@ -29,11 +30,13 @@ export async function realRoot(root) {
29
30
  try {
30
31
  real = await fs.realpath(path.resolve(root))
31
32
  } catch {
32
- throw new PathError(`Root folder "${root}" does not exist. Create it, or start the server with --root pointing at an existing folder.`)
33
+ throw new PathError(`Root folder "${root}" does not exist. Create it, or start the server with --root ` +
34
+ 'pointing at an existing folder.')
33
35
  }
34
36
  const stat = await fs.stat(real)
35
37
  if (!stat.isDirectory()) {
36
- throw new PathError(`Root "${root}" is a file, not a folder. Start the server with --root pointing at a folder.`)
38
+ throw new PathError(`Root "${root}" is a file, not a folder. Start the server with ` +
39
+ '--root pointing at a folder.')
37
40
  }
38
41
  return real
39
42
  }
@@ -62,7 +65,8 @@ export async function resolveInRoot(base, input, { label = 'path' } = {}) {
62
65
 
63
66
  const real = await realpathOfNearest(path.resolve(base, input), input, label)
64
67
  if (!isInside(base, real)) {
65
- throw new PathError(`The ${label} "${input}" leads outside ${base}. Only files and folders inside it can be used.`)
68
+ throw new PathError(`The ${label} "${input}" leads outside ${base}. Only files and ` +
69
+ 'folders inside it can be used.')
66
70
  }
67
71
  return real
68
72
  }
@@ -79,12 +83,14 @@ async function realpathOfNearest(target, input, label) {
79
83
  return path.join(await fs.realpath(current), ...rest)
80
84
  } catch (error) {
81
85
  if (error.code === 'ELOOP') {
82
- throw new PathError(`The ${label} "${input}" goes through a loop of symbolic links, so it cannot be checked. Remove the loop or use another path.`)
86
+ throw new PathError(`The ${label} "${input}" goes through a loop of symbolic links, so it cannot be ` +
87
+ 'checked. Remove the loop or use another path.')
83
88
  }
84
89
  if (!MISSING.has(error.code)) throw error
85
90
  }
86
91
  if (await isDanglingLink(current)) {
87
- throw new PathError(`The ${label} "${input}" goes through a broken symbolic link, so it cannot be checked. Remove the link or use another path.`)
92
+ throw new PathError(`The ${label} "${input}" goes through a broken symbolic link, so it cannot be ` +
93
+ 'checked. Remove the link or use another path.')
88
94
  }
89
95
  const parent = path.dirname(current)
90
96
  if (parent === current) return target
@@ -100,16 +106,3 @@ async function isDanglingLink(candidate) {
100
106
  return false
101
107
  }
102
108
  }
103
-
104
- /**
105
- * Whether `target` is `base` itself or lies below it. Both must be real,
106
- * absolute paths (from `realRoot` / `resolveInRoot`).
107
- *
108
- * @param {string} base
109
- * @param {string} target
110
- * @returns {boolean}
111
- */
112
- export function isInside(base, target) {
113
- const relative = path.relative(base, target)
114
- return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
115
- }
package/src/prompts.js CHANGED
@@ -35,11 +35,15 @@ export function registerPrompts(server) {
35
35
  ${ABOUT_NERA}
36
36
 
37
37
  Steps:
38
- 1. Call list_sites. If a site for this business already exists, ask me whether to work on it instead of creating a new one.
38
+ 1. Call list_sites. If a site for this business already exists, ask me whether to work on it \
39
+ instead of creating a new one.
39
40
  2. Call list_starters and pick the \`business\` starter (or \`portfolio\` if the business shows its work in pictures).
40
41
  3. Call create_site with that starter, a short lowercase folder name${folder ? ` (\`${folder}\`)` : ''}, the business name as \`title\` and the site language as \`lang\`.
41
- 4. Call get_site, then read_page on each sample page and rewrite it with write_page for my business, keeping each page's \`layout\` in its frontmatter. Ask me for facts you do not know (address, opening hours, services, prices) instead of inventing them; leave a clear placeholder where I must fill something in.
42
- 5. Fill in the imprint and privacy pages' placeholders only with what I told you, and tell me which legal details are still missing.
42
+ 4. Call get_site, then read_page on each sample page and rewrite it with write_page for my business, keeping each \
43
+ page's \`layout\` in its frontmatter. Ask me for facts you do not know (address, opening hours, services, prices) \
44
+ instead of inventing them; leave a clear placeholder where I must fill something in.
45
+ 5. Fill in the imprint and privacy pages' placeholders only with what I told you, and tell me which legal details are \
46
+ still missing.
43
47
  6. ${VALIDATE_AND_PREVIEW}
44
48
  7. Tell me which pages exist and that put_site_online publishes the site when I am happy with it.`))
45
49
 
@@ -59,7 +63,8 @@ Steps:
59
63
  2. Call list_starters and pick the \`blog\` starter.
60
64
  3. Call create_site with it, a short lowercase folder name${folder ? ` (\`${folder}\`)` : ''}, the blog's name as \`title\` and its language as \`lang\`.
61
65
  4. Call get_site and read_page on one sample post to see the frontmatter a post uses (title, date, tags, layout).
62
- 5. Replace the sample posts with write_page: one first post on my topic, written with me, using the same frontmatter fields and \`layout\`; delete the other samples with delete_page once I agree. Update the home and about pages.
66
+ 5. Replace the sample posts with write_page: one first post on my topic, written with me, using the same frontmatter \
67
+ fields and \`layout\`; delete the other samples with delete_page once I agree. Update the home and about pages.
63
68
  6. ${VALIDATE_AND_PREVIEW}
64
69
  7. Tell me how to add the next post (the add_page prompt does it) and that put_site_online publishes the blog.`))
65
70
 
@@ -76,9 +81,12 @@ ${ABOUT_NERA}
76
81
 
77
82
  Steps:
78
83
  1. ${site ? `Call get_site with site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one. Then call get_site.'} Read the site's AGENTS.md resource (\`nera://site/<site>/AGENTS.md\`) if it has one.
79
- 2. Call read_page on an existing page of the same kind (a post for a post, a normal page otherwise) and copy its frontmatter fields and \`layout\`.
80
- 3. Choose a file name that fits the site's other pages (lowercase, hyphens, \`.md\`, in the same folder as its siblings) and write the page with write_page. Ask me for content you do not know.
81
- 4. If the site has a navigation config (e.g. config/navigation.yaml, see get_site's plugins and read_file), add the page there when it belongs in the menu, with write_file.
84
+ 2. Call read_page on an existing page of the same kind (a post for a post, a normal page otherwise) and copy its \
85
+ frontmatter fields and \`layout\`.
86
+ 3. Choose a file name that fits the site's other pages (lowercase, hyphens, \`.md\`, in the same folder as its \
87
+ siblings) and write the page with write_page. Ask me for content you do not know.
88
+ 4. If the site has a navigation config (e.g. config/navigation.yaml, see get_site's plugins and read_file), add the \
89
+ page there when it belongs in the menu, with write_file.
82
90
  5. ${VALIDATE_AND_PREVIEW}`))
83
91
 
84
92
  server.registerPrompt('put_site_online', {
@@ -91,9 +99,13 @@ ${ABOUT_NERA}
91
99
 
92
100
  Steps:
93
101
  1. ${site ? `Use site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one.'}
94
- 2. Call validate and fix every error; then call build with \`check: true\` and tell me about accessibility, privacy and legal findings (an imprint and a privacy page are required for many sites, e.g. in Germany). Fix what you can with my consent.
95
- 3. Call publish for the site. It returns a short code and a GitHub web address: give me both and ask me to open the address, sign in to GitHub (or create a free account) and enter the code. Never ask me for a password or token.
96
- 4. After I confirm, call publish again for the same site until it reports the result, and give me the address where the site is now online. Tell me that later changes go online by calling publish again.`))
102
+ 2. Call validate and fix every error; then call build with \`check: true\` and tell me about accessibility, privacy \
103
+ and legal findings (an imprint and a privacy page are required for many sites, e.g. in Germany). Fix what you can with \
104
+ my consent.
105
+ 3. Call publish for the site. It returns a short code and a GitHub web address: give me both and ask me to open the \
106
+ address, sign in to GitHub (or create a free account) and enter the code. Never ask me for a password or token.
107
+ 4. After I confirm, call publish again for the same site until it reports the result, and give me the address where \
108
+ the site is now online. Tell me that later changes go online by calling publish again.`))
97
109
  }
98
110
 
99
111
  /** What the hosted prompts add: the site is a GitHub repository and changes wait on a draft. */
@@ -126,9 +138,12 @@ ${ABOUT_HOSTED}
126
138
 
127
139
  Steps:
128
140
  1. ${site ? `Call get_site with site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one. Then call get_site.'} Read the site's AGENTS.md with read_file if it has one.
129
- 2. Call read_page on an existing page of the same kind (a post for a post, a normal page otherwise) and copy its frontmatter fields and \`layout\`.
130
- 3. Choose a file name that fits the site's other pages (lowercase, hyphens, \`.md\`, in the same folder as its siblings) and write the page with write_page, with a short commit message. Ask me for content you do not know.
131
- 4. If the site has a navigation config (e.g. config/navigation.yaml, see get_site's plugins and read_file), add the page there when it belongs in the menu, with write_file.
141
+ 2. Call read_page on an existing page of the same kind (a post for a post, a normal page otherwise) and copy its \
142
+ frontmatter fields and \`layout\`.
143
+ 3. Choose a file name that fits the site's other pages (lowercase, hyphens, \`.md\`, in the same folder as its \
144
+ siblings) and write the page with write_page, with a short commit message. Ask me for content you do not know.
145
+ 4. If the site has a navigation config (e.g. config/navigation.yaml, see get_site's plugins and read_file), add the \
146
+ page there when it belongs in the menu, with write_file.
132
147
  5. ${VALIDATE_AND_PUBLISH}`))
133
148
 
134
149
  server.registerPrompt('put_site_online', {
@@ -144,6 +159,9 @@ ${ABOUT_HOSTED}
144
159
  Steps:
145
160
  1. ${site ? `Use site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one.'} Call preview to see the live address, the last deploy and how many changes wait unpublished.
146
161
  2. Call validate and fix every error with write_page or write_file; tell me what you changed.
147
- 3. Call publish for the site. It merges the draft into main in one push and returns the deploy run and the address. If it reports that the repository has no deploy workflow, tell me to run \`nera publish\` once in the site on my computer, which sets it up.
148
- 4. Call preview after a minute or two and tell me whether the deploy succeeded and where the site is live. Tell me that later changes go live by calling publish again.`))
162
+ 3. Call publish for the site. It merges the draft into main in one push and returns the deploy run and the address. If \
163
+ it reports that the repository has no deploy workflow, tell me to run \`nera publish\` once in the site on my \
164
+ computer, which sets it up.
165
+ 4. Call preview after a minute or two and tell me whether the deploy succeeded and where the site is live. Tell me \
166
+ that later changes go live by calling publish again.`))
149
167
  }
package/src/resources.js CHANGED
@@ -48,7 +48,8 @@ function decodeSite(site) {
48
48
  try {
49
49
  return decodeURIComponent(String(site))
50
50
  } catch {
51
- throw new PathError(`The site "${site}" in the resource URI is not validly percent-encoded. Use the URI list_sites or the resource list gives.`)
51
+ throw new PathError(`The site "${site}" in the resource URI is not validly percent-encoded. Use the URI ` +
52
+ 'list_sites or the resource list gives.')
52
53
  }
53
54
  }
54
55
 
@@ -79,7 +80,8 @@ export function registerDocsResources(server, ctx) {
79
80
  for (const kindName of Object.keys(KINDS)) {
80
81
  server.registerResource(`nera_${kindName}`, `nera://catalog/${kindName}`, {
81
82
  title: `Nera ${KINDS[kindName].title}`,
82
- description: `The Nera ${KINDS[kindName].title} on npm as JSON, official ones first (the same list as the list_${kindName} tool).`,
83
+ description: `The Nera ${KINDS[kindName].title} on npm as JSON, official ones first (the same list as ` +
84
+ `the list_${kindName} tool).`,
83
85
  mimeType: 'application/json',
84
86
  }, resource(async (uri) => {
85
87
  const items = await readCatalog(ctx, kindName)
@@ -104,7 +106,9 @@ export function registerResources(server, ctx) {
104
106
  return text(uri, 'text/markdown', await fs.readFile(file, 'utf8'))
105
107
  } catch (error) {
106
108
  if (error.code !== 'ENOENT') throw error
107
- throw new ToolError(`The site "${resolved.site}" has no ${AGENTS_FILE} (sites created before @nera-static/nera 1.6.0 lack it; running \`nera update\` in the site writes one). Call get_site instead.`)
109
+ throw new ToolError(`The site "${resolved.site}" has no ${AGENTS_FILE} (sites created before ` +
110
+ '@nera-static/nera 1.6.0 lack it; running `nera update` in the site writes one). ' +
111
+ 'Call get_site instead.')
108
112
  }
109
113
  })
110
114
  const listAgents = async () => {
package/src/runner.js CHANGED
@@ -72,16 +72,16 @@ export function npmCommand(execPath = process.execPath, own = ownNpm()) {
72
72
  */
73
73
  export function commandFor(command, cwd) {
74
74
  switch (command) {
75
- case 'nera':
76
- return { file: process.execPath, prefix: [neraBin(cwd)] }
77
- case 'npm':
78
- return npmCommand()
79
- case 'node':
80
- return { file: process.execPath, prefix: [] }
81
- case 'tar':
82
- return { file: 'tar', prefix: [] }
83
- default:
84
- throw new Error(`Unknown command "${command}": the runner starts nera, npm, node or tar only.`)
75
+ case 'nera':
76
+ return { file: process.execPath, prefix: [neraBin(cwd)] }
77
+ case 'npm':
78
+ return npmCommand()
79
+ case 'node':
80
+ return { file: process.execPath, prefix: [] }
81
+ case 'tar':
82
+ return { file: 'tar', prefix: [] }
83
+ default:
84
+ throw new Error(`Unknown command "${command}": the runner starts nera, npm, node or tar only.`)
85
85
  }
86
86
  }
87
87
 
@@ -255,7 +255,9 @@ export function stopChild(child, { grace = KILL_GRACE_MS, platform = process.pla
255
255
  * @returns {(command: 'nera'|'npm'|'node'|'tar', args: string[], options: { cwd: string, signal?: AbortSignal, env?: Record<string, string> }) => Promise<{ code: number|null, stdout: string, stderr: string, timedOut: boolean, cancelled: boolean }>}
256
256
  * `code` is null when the process was stopped or could not start; `stderr` then says why
257
257
  */
258
- export function createRunner({ spawn = nodeSpawn, timeout = DEFAULT_TIMEOUT_MS, grace = KILL_GRACE_MS, platform = process.platform } = {}) {
258
+ export function createRunner({
259
+ spawn = nodeSpawn, timeout = DEFAULT_TIMEOUT_MS, grace = KILL_GRACE_MS, platform = process.platform,
260
+ } = {}) {
259
261
  return (command, args, { cwd, signal, env }) => new Promise((resolve) => {
260
262
  const { file, prefix } = commandFor(command, cwd)
261
263
  if (signal?.aborted) {
@@ -0,0 +1,11 @@
1
+ import { ownVersion } from '@nera-static/plugin-utils/packages'
2
+
3
+ /**
4
+ * The name and version both modes report in the MCP handshake and in their
5
+ * start-up log line. The version is read from this package's own
6
+ * `package.json`, wherever it is installed or bundled.
7
+ */
8
+ export const SERVER_INFO = Object.freeze({
9
+ name: '@nera-static/mcp',
10
+ version: ownVersion(import.meta.url),
11
+ })
package/src/server.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
2
2
  import { addPlugin as neraAddPlugin, createSite as neraCreateSite } from '@nera-static/nera'
3
- import pkg from '../package.json' with { type: 'json' }
4
3
  import { registerCatalogTools } from './catalog.js'
5
4
  import { realRoot } from './paths.js'
6
5
  import { createProcesses } from './processes.js'
7
6
  import { registerPrompts } from './prompts.js'
8
7
  import { registerResources } from './resources.js'
9
8
  import { createRunner } from './runner.js'
9
+ import { SERVER_INFO } from './server-info.js'
10
10
  import { registerCliTools } from './tools/cli.js'
11
11
  import { registerFileTools } from './tools/files.js'
12
12
  import { registerLongRunningTools } from './tools/long-running.js'
@@ -29,10 +29,19 @@ import { registerSiteTools } from './tools/sites.js'
29
29
  * @returns {Promise<McpServer>}
30
30
  * @throws {import('./paths.js').PathError} when `root` does not exist or is not a folder
31
31
  */
32
- export async function createServer({ root, runner = createRunner(), createSite = neraCreateSite, addPlugin = neraAddPlugin, fetch = globalThis.fetch, docsFile, processes = createProcesses(), timing }) {
32
+ export async function createServer({
33
+ root,
34
+ runner = createRunner(),
35
+ createSite = neraCreateSite,
36
+ addPlugin = neraAddPlugin,
37
+ fetch = globalThis.fetch,
38
+ docsFile,
39
+ processes = createProcesses(),
40
+ timing,
41
+ }) {
33
42
  const ctx = { root: await realRoot(root), runner, createSite, addPlugin, fetch, docsFile, processes, timing }
34
43
  const server = new McpServer(
35
- { name: pkg.name, version: pkg.version },
44
+ { ...SERVER_INFO },
36
45
  {
37
46
  instructions: `Tools for Nera, a static site generator: a site is Markdown pages (pages/) rendered through Pug layouts into plain HTML. You work in ${ctx.root}. Start with list_sites; read get_site before editing a site. The prompts walk through whole tasks, the nera://docs/llms-full.txt resource holds the full documentation.`,
38
47
  },
@@ -48,7 +57,8 @@ export async function createServer({ root, runner = createRunner(), createSite =
48
57
  // call, which stops the short commands through their signal; the
49
58
  // long-running children are stopped here.
50
59
  server.server.onclose = () => {
51
- processes.stopAll().catch((error) => console.error(`Stopping the preview and publish processes failed: ${error.message}`))
60
+ processes.stopAll().catch((error) => console.error('Stopping the preview and publish processes ' +
61
+ `failed: ${error.message}`))
52
62
  }
53
63
  return server
54
64
  }
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`). */
@@ -60,21 +58,30 @@ async function starterArg(ctx, starter) {
60
58
  const real = await resolveInRoot(ctx.root, starter, { label: 'starter folder' })
61
59
  return `./${relativeTo(ctx.root, real)}`
62
60
  }
63
- 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`).')
64
64
  }
65
65
 
66
66
  /**
67
- * The npm package of an `add_plugin` spec, in the same forms the CLI's
68
- * addPlugin takes: `@nera-static/plugin-<name>`, `plugin-<name>` or just
69
- * `<name>`; anything else (another scope, a version, a path, a URL) is
70
- * 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}
71
75
  */
72
- function pluginPackage(spec) {
73
- const name = spec.replace(new RegExp(`^(${PLUGIN_SCOPE}plugin-|plugin-)`), '')
74
- if (!PLUGIN_NAME.test(name) || NOT_PLUGINS.has(name)) {
75
- 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.')
76
84
  }
77
- return { name, pkg: `${PLUGIN_SCOPE}plugin-${name}` }
78
85
  }
79
86
 
80
87
  /**
@@ -97,14 +104,17 @@ export function registerCliTools(server, ctx) {
97
104
  }, tool(async ({ name, starter, theme, title, lang }, { signal }) => {
98
105
  const inRoot = name === '.' || name === './'
99
106
  if (!inRoot && !SITE_FOLDER.test(name)) {
100
- 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.')
101
109
  }
102
110
  const target = await resolveInRoot(ctx.root, inRoot ? '.' : name, { label: 'site folder' })
103
111
  if (!inRoot && await exists(target)) {
104
- 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.')
105
114
  }
106
115
  if (theme !== undefined && !PACKAGE_SPEC.test(theme)) {
107
- 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`).')
108
118
  }
109
119
 
110
120
  const spec = starter === undefined ? undefined : await starterArg(ctx, starter)
@@ -127,7 +137,10 @@ export function registerCliTools(server, ctx) {
127
137
  // rerun there); after anything else, an abort included,
128
138
  // createSite has removed a new folder again.
129
139
  if (!signal.aborted && typeof error.code === 'number' && await exists(path.join(target, 'package.json'))) {
130
- 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.')
131
144
  }
132
145
  throw new ToolError(`Creating the site failed: ${error.message}`)
133
146
  }
@@ -135,8 +148,10 @@ export function registerCliTools(server, ctx) {
135
148
  return ok(
136
149
  { site, log: tail(lines.join('\n')), firstSteps },
137
150
  firstSteps
138
- ? `Created the Nera site "${site}". Its starter suggests first steps (in firstSteps); follow them, starting with get_site with site "${site}".`
139
- : `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.',
140
155
  )
141
156
  }))
142
157
 
@@ -191,7 +206,7 @@ export function registerCliTools(server, ctx) {
191
206
  plugin: z.string().describe('The plugin, as `@nera-static/plugin-<name>`, `plugin-<name>` or just `<name>` (e.g. `sitemap`, `tags`).'),
192
207
  },
193
208
  }, tool(async ({ site, plugin }, { signal }) => {
194
- const { name, pkg } = pluginPackage(plugin)
209
+ const { name, pkg } = addPluginPackage(plugin)
195
210
  const resolved = await resolveSite(ctx, site)
196
211
  // addPlugin writes `<folders.config>/<name>.yaml` without checking
197
212
  // where it leads, so a config folder or file that is a symbolic link
@@ -206,12 +221,15 @@ export function registerCliTools(server, ctx) {
206
221
  const lines = []
207
222
  let added
208
223
  try {
209
- 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 })
210
226
  } catch (error) {
211
227
  // A command that ran and failed (npm install, the template
212
228
  // script) carries its exit code; its own output is not captured.
213
229
  const childFailed = !signal.aborted && typeof error.cause?.code === 'number'
214
- 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)
215
233
  }
216
234
 
217
235
  const { config, templates } = added
@@ -1,8 +1,9 @@
1
1
  import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
+ import { isInside } from '@nera-static/plugin-utils/urls'
3
4
  import { z } from 'zod'
4
5
  import { NO_WRITE_SEGMENTS, composePage, parsePage, refuseSecrets, refuseSegments, requireLayout } from '../pages.js'
5
- import { isInside, resolveInRoot } from '../paths.js'
6
+ import { resolveInRoot } from '../paths.js'
6
7
  import { ok, tool, ToolError } from '../results.js'
7
8
  import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
8
9
 
@@ -45,7 +46,8 @@ async function resolvePage(ctx, site, page) {
45
46
  const file = await resolveInRoot(resolved.dir, page, { label: 'page path' })
46
47
  const pagesFolder = relativeTo(resolved.dir, pagesDir)
47
48
  if (file === pagesDir || !isInside(pagesDir, file)) {
48
- 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.`)
49
51
  }
50
52
  if (path.extname(file) !== '.md') {
51
53
  throw new ToolError(`"${page}" does not end in .md. Pages are Markdown files, e.g. ${pagesFolder}/about.md.`)
@@ -85,13 +87,15 @@ export function registerFileTools(server, ctx) {
85
87
  const target = await resolvePage(ctx, site, page)
86
88
  const raw = await readText(target.file, target.path)
87
89
  if (raw === null) {
88
- 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.')
89
92
  }
90
93
  const { frontmatter, body, error } = parsePage(raw)
91
94
  const structured = { site: target.site, path: target.path, frontmatter, body }
92
95
  if (error) structured.frontmatterError = error
93
96
  const text = error
94
- ? `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.'
95
99
  : `Read ${target.path} (layout: ${frontmatter.layout ?? 'none — the build skips this page'}).`
96
100
  return ok(structured, text)
97
101
  }))
@@ -146,13 +150,15 @@ export function registerFileTools(server, ctx) {
146
150
  const target = await resolveFile(ctx, site, input)
147
151
  const stat = await statOrNull(target.file)
148
152
  if (stat === null) {
149
- 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.')
150
155
  }
151
156
  if (stat.isDirectory()) {
152
157
  throw new ToolError(`"${target.path}" is a folder, not a file.`)
153
158
  }
154
159
  if (stat.size > MAX_READ_BYTES) {
155
- 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.')
156
162
  }
157
163
  const buffer = await fs.readFile(target.file)
158
164
  if (buffer.includes(0)) {
@@ -175,7 +181,8 @@ export function registerFileTools(server, ctx) {
175
181
  refuseSegments(input, target.path, NO_WRITE_SEGMENTS, 'npm manages; add plugins with add_plugin')
176
182
  const { pagesDir, distDir } = await siteFolders(target.dir)
177
183
  if (isInside(distDir, target.file)) {
178
- 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.')
179
186
  }
180
187
  if (isInside(pagesDir, target.file) && path.extname(target.file) === '.md') {
181
188
  throw new ToolError(`"${target.path}" is a page. Use write_page, which checks the frontmatter.`)